Index of every page on this site: llms.txt
All skills
oahc09 avatar

/cocosair-primitives-mesh

@ed38648
by oahc09oahc09/cocosairjs3 stars
2
Run it yourself

Build primitive geometry, Mesh buffers and MeshRenderer bindings. Use for vertex attributes, indices, wireframes or AIR_E_PRIMITIVE_DESCRIPTOR validation.

  • 9 files
  • 64.8 KB
  • MIT
  • Updated last month
  • GitHub
Use this Skill: https://skilld.dev/gh/oahc09/cocosairjs/cocosair-primitives-mesh

Nothing lands on disk. Nothing to clean up.

Fork this Skill

Edit a local copy. It keeps the author and licence.

referencescommon-mistakes.md

≈2.7k tokens on demand. Your agent reads this file only when SKILL.md points to it.

Derived from the cocosair-primitives-mesh skill and its canonical docs/source pointers; reorganized on 2026-10-11. Source annotations below identify repository inputs, not files guaranteed to ship to npm consumers.

Common Mistakes

Current dynamic-mesh contract (2026-10-24 automatic synchronization)

Use mesh.updateSubMesh(0, geometry) with no manual renderer notification. After a successful update commits buffers, counts and bounds, all bound renderers synchronously refresh their model bounds and input-assembler draw info. Shared meshes work with each node's world transform. Rebinding or destroying a renderer releases its old subscription; invalid updates do not notify. The public renderer.onGeometryChanged() remains compatible but is unnecessary for this path. Direct struct/buffer mutations are outside this automatic contract.

The regression checks both the stale-frustum case and actual indexed draw counts (6→3→0→6). See test/smoke/dynamic-mesh-renderer-sync.test.ts and tools/verify/effect-runtime-contracts.cjs. Historical E02/E04 attribution is still unconfirmed without the original arm inputs.

<details> <summary>Historical pre-fix workaround and reproduction; superseded by the automatic contract above</summary>

[HIGH] Updating an attached dynamic mesh without notifying its renderer

createDynamicMesh requires a device (await createAirApp() first), typed geometry channels and sufficient maxSubMeshVertices/maxSubMeshIndices. Use indices16/indices32, not the static indices key. Current Mesh.updateSubMesh() derives bounds from updated positions when explicit minPos/maxPos are absent; supplying struct bounds alone is not a renderer notification.

After changing geometry already attached to a renderer, call:

mesh.updateSubMesh(0, geometry);
renderer.onGeometryChanged();

The second call updates the model bounds and submodel geometry state. Notify every renderer that shares the mesh. Do not claim that all missing draws share this cause: also check the actual draw counts, camera/layers, material topology, shader attributes and frustum. The E02/E04 historical root cause remains unconfirmed without their original source; an engine-local reproduction is a separate, bounded observation. See src/cocos/3d/assets/mesh.ts and src/cocos/3d/framework/mesh-renderer.ts.

The 2026-10-24 engine-local Chromium control observed 20736 green pixels on initial creation without a notification; after moving the model outside the frustum, returning positions with explicit mesh bounds but no notification produced 0 pixels and left model centre X at 100. A notification reset model centre X to 0 and restored 20736 pixels. This confirms the attached-model stale-bounds case, not a general initial-creation failure. Reproduce with tools/verify/effect-runtime-contracts.cjs against a freshly built candidate; supply a fresh --out directory.

</details>

[HIGH] Assigning the createPrimitiveGeometry result straight to MeshRenderer.mesh

Wrong:

const geometry = createPrimitiveGeometry({ type: 'cylinder', radiusTop: 0.2, radiusBottom: 0.2, height: 2 });
renderer.mesh = geometry;   // geometry.initialize is not a function -> TypeError

Correct:

const geometry = createPrimitiveGeometry({ type: 'cylinder', radiusTop: 0.2, radiusBottom: 0.2, height: 2 });
renderer.mesh = utils.MeshUtils.createMesh(geometry);   // IGeometry -> Mesh asset

The setter assigns const mesh = this._mesh = val; first (src/cocos/3d/framework/mesh-renderer.ts:489) and only then calls mesh?.initialize() on it (:490), ahead of every other side effect; a plain IGeometry is truthy but has no initialize, so optional chaining clears the null guard and then throws a TypeError. An agent writes it because the call already looks like a geometry constructor, and three.js mesh.geometry = bufferGeometry is directly assignable.

[HIGH] Passing a shape outside the four-type whitelist to createPrimitiveGeometry

Wrong:

const g = createPrimitiveGeometry({ type: 'capsule', radius: 0.4, height: 1 });   // RangeError AIR_E_PRIMITIVE_DESCRIPTOR

Correct:

const g = createPrimitiveGeometry({ type: 'cylinder', radiusTop: 0.2, radiusBottom: 0.4, height: 1 });
const cap = primitives.capsule(0.4, 0.4, 0.8);   // capsule/torus/plane/quad/circle are only on primitives.*

The primitives namespace exposes nine generators, so an agent expects the descriptor to take all nine; createPrimitiveGeometry checks type against a four-key map and throws for anything else, and the thrown object is a RangeError (src/air/primitive-geometry.ts:43-44).

[HIGH] Calling primitives.cone with an options object

Wrong:

const g = primitives.cone({ radius: 0.5, height: 1, radialSegments: 16 });   // radius becomes the object
renderer.mesh = utils.MeshUtils.createMesh(g);   // mesh builds, positions are NaN, nothing renders

Correct:

const g = primitives.cone(0.5, 1, { radialSegments: 16 });   // cone(radius, height, opts) is positional
renderer.mesh = utils.MeshUtils.createMesh(g);

box and plane take an options object, so an agent assumes every generator does; cone is cone(radius = 0.5, height = 1, opts) delegating to cylinder(0, radius, height, opts) (src/cocos/primitive/cone.ts:40-45), and cylinder's torso math multiplies radiusBottom numerically (src/cocos/primitive/cylinder.ts:127,136,146-148), so the object yields NaN positions. The shipped examples/mesh-prim-compare/src/main.ts:75 makes this exact call, and no error is thrown at assign time.

[MEDIUM] Expecting includeNormal to strip a channel from a descriptor shape

Wrong:

const g = createPrimitiveGeometry({ type: 'box', width: 1, height: 1, length: 1, includeNormal: false });
// g.normals is still a full array; a lighting assumption built on "no normals" is wrong

Correct:

const g = createPrimitiveGeometry({ type: 'box', width: 1, height: 1, length: 1 });
delete g.normals;   // to actually drop a channel, delete it before createMesh or hand-build the Attribute list

The flags are validated as booleans and forwarded, but box/sphere/cylinder/cone never read them (src/air/primitive-geometry.ts:48-53); among the non-descriptor generators only plane and quad consume them (src/cocos/primitive/plane.ts:120,145,156, src/cocos/primitive/quad.ts:55,63), while circle hands them to applyDefaultGeometryOptions (src/cocos/primitive/circle.ts:45, src/cocos/primitive/define.ts:57-67) and never reads either one (src/cocos/primitive/circle.ts:85-92), so includeNormal: false is accepted and silently ignored on every shape reachable here.

[MEDIUM] Reading an attribute with a gfx.ATTRIB_POSITION constant

Wrong:

const pos = mesh.readAttribute(0, gfx.ATTRIB_POSITION);   // no such constant -> undefined name -> null
const n = pos.length;                                      // TypeError reading length of null

Correct:

const pos = mesh.readAttribute(0, gfx.AttributeName.ATTR_POSITION);   // 'a_position'

readAttribute matches attributes.findIndex(a => a.name === attributeName) (src/cocos/3d/assets/mesh.ts:1309), so an undefined name finds nothing and returns null rather than throwing. Attribute names are the string enum values gfx.AttributeName.ATTR_* (src/cocos/gfx/base/define.ts:2074-2095); examples/mesh-attributes-indices/src/main.ts:80 reaches for the non-existent gfx.ATTRIB_POSITION, so its probe lands on the null branch.

Dynamic mesh creation and update checklist

中文检索:动态网格不渲染、updateSubMesh 后看不见、onGeometryChanged。

  1. Initialize the app/device first. Call utils.MeshUtils.createDynamicMesh, not a nonexistent utils.createDynamicMesh; mesh.updateSubMesh is the update method, not updateSubMesh on MeshUtils.
  2. Create finite Float32Array positions in XYZ triples, matching initial channel vertex counts, and Uint16Array / Uint32Array indices through indices16 / indices32. Do not pass the static geometry key indices. Reserve enough capacity; when supplying options, provide all three fields maxSubMeshes, maxSubMeshVertices, maxSubMeshIndices.
  3. Creation fixes the channel layout and indexed/non-indexed route. Update existing streams and use the same index width; new attributes require a compatible mesh recreation. Keep index values below the committed vertex count. An intentional zero draw count renders no pixels.
  4. Attach the mesh and a compatible material to an active MeshRenderer under the intended camera. Match mesh and pass topology, required shader attributes, camera layer mask, clip range and bounds. Data upload success alone does not establish visibility.
  5. Use mesh.updateSubMesh(0, geometry) for changes. On current AIR, successful updates commit buffers, counts and bounds and automatically notify all bound renderers. Positions derive bounds when explicit minPos/maxPos are absent; if supplying bounds, provide both finite ordered endpoints. Direct writes to buffers or mesh.struct bypass this update/synchronization contract.
  6. If a deployed older SDK requires the historical manual notification above, call renderer.onGeometryChanged() after a successful update for every sharing renderer. Verify that version first. Do not prescribe it as a required extra call for current AIR or assume its omission proves the E02/E04 failure cause.

Minimal current sequence, after app initialization and with node attached to the intended scene:

const geometry = {
    positions: new Float32Array([-0.5, -0.5, 0, 0.5, -0.5, 0, 0, 0.5, 0]),
    indices16: new Uint16Array([0, 1, 2]),
};
const mesh = utils.MeshUtils.createDynamicMesh(0, geometry, undefined, {
    maxSubMeshes: 1,
    maxSubMeshVertices: 3,
    maxSubMeshIndices: 3,
});
const renderer = node.addComponent(MeshRenderer);
renderer.mesh = mesh;
renderer.setSharedMaterial(material, 0); // An initialized compatible material.
geometry.positions[0] = -0.25;
mesh.updateSubMesh(0, geometry); // Current AIR synchronizes the attached renderer here.

When pixels are still missing, compare actual vertex/index draw counts and world bounds before editing the shader. Out-of-capacity, wrong-key and malformed-channel input on current AIR raises AIR_E_MESH_* before mutation; stale SDKs can behave differently. Detach consumers before releasing owned mesh/material resources. See the buffer layout reference and the current synchronization contract at the top of this file.

Source: SKILL.md on GitHub

skilld matched fixed text patterns in SKILL.md and file names. Patterns miss obfuscated code.

skilld run checks every file with the same patterns. It asks for approval before it loads a Skill with a behavior marked Needs approval.

No third-party reports yet.

Signed by skilld at ed38648. This ties the file your Agent reads to that commit on GitHub. It does not review the instructions.

Last checked against GitHub yesterday.

Activeupdated last month
layer
subsystem
All 1 allowed tools
Read Edit Write Bash
Other metadata
compatibility
Cocos AIR source checkout or installed cocosair.js package. Browser rendering requires WebGL 2; source tooling requires Node.js >=18. Use the host-provided tools and user-authorized workspace.
when_to_use
[
  "generate a box, sphere, cylinder or cone",
  "attach procedural geometry to a renderer",
  "author custom vertex buffers and indices",
  "read or copy mesh attributes",
  "a primitive descriptor fails validation"
]
owns
[
  "primitive-geometry",
  "mesh-buffers",
  "vertex-attributes",
  "mesh-indices",
  "mesh-renderer",
  "wireframe"
]
not_for
[
  "draw-call batching and instancing -> cocosair-performance",
  "skeletal binding or morph weights -> cocosair-skinning-morph",
  "material uniforms and effects -> cocosair-materials-effects"
]
metadata
{
  "author": "oahc09@gmail.com",
  "version": "1.0.0",
  "last-updated": "2026-10-13",
  "description_zh": "构建基本几何和原生 Mesh,检查顶点属性、索引、边界与渲染器写入契约。用于代码生成几何或自定义网格。"
}

README badge

README badge for oahc09/cocosairjs/cocosair-primitives-mesh