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

/cocosair-gltf

@ed38648
by oahc09oahc09/cocosairjs3 stars
2
Run it yourself

Load glTF/GLB models, extensions, decoder injection and instances. Use for Draco/meshopt/KTX2 deployment, GLTF_DECODER_MISSING, uncoded load errors or animation loops.

  • 10 files
  • 110.6 KB
  • MIT
  • Updated last month
  • GitHub
Use this Skill: https://skilld.dev/gh/oahc09/cocosairjs/cocosair-gltf

Nothing lands on disk. Nothing to clean up.

Fork this Skill

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

referencesloader-api.md

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

Derived from src/air/assets/gltf/loader.ts, src/air/assets/gltf/asset.ts, src/air/assets/gltf/index.ts, src/air/assets/gltf/parser-context.ts, src/air/assets/gltf/extension-registry.ts, src/air/assets/gltf/progress.ts, build/cocosair.module.js, build/cocosair.module.d.ts, docs/evidence/examples-verified.json, examples/gltf-viewer/main.js, examples/gltf-skin/src/main.ts, examples/gltf-skin/example.json, examples/gltf-animation-contract/src/main.ts, examples/animated-character-showcase/src/main.ts, examples/gltf-asset-readonly/src/main.ts (as of 2026-10-09).

Two entry points

loadAsync(url) (src/air/assets/gltf/loader.ts:108-113) is the asset-manager path: it calls registerGLTFLoader() first (:109), then assetManager.loadRemote<GLTFAsset>(absoluteURL(url), { ext: gltfExtension(url) || '.glb', gltf: {...} }, cb) (:111-112). gltfExtension applies /\.(gltf|glb)$/i to the query/hash-stripped path and lowercases the match (:36-38), so an extensionless URL falls back to ext: '.glb'; absoluteURL resolves against document.baseURI when document exists (:39-41). Caching and in-flight deduplication belong to the native asset manager (:110). parseAsync(data, baseUrl?) (:115-184) is the in-memory path: it accepts string | ArrayBuffer, honors an abort signal, and touches no cache. Importing src/air/assets/gltf/index.ts auto-registers the loader at import time (src/air/assets/gltf/index.ts:25-26); calling registerGLTFLoader() manually is only needed when importing the loader module directly.

registerGLTFLoader() (src/air/assets/gltf/loader.ts:187-209) is idempotent through a module-level flag (:187-189) and registers, for both .gltf and .glb (:190): a downloader that fetches with options.header and credentials: 'include' | 'same-origin' from options.withCredentials, checks response.ok, and returns arrayBuffer() (:191-196); a parser that runs decodeContainer(data) purely as validation and passes the original data through (:197-199); and a factory that runs new GLTFLoader(loaderOptions).parseAsync(data, base) where base is undefined for data:/blob: URLs and otherwise new URL('.', absoluteURL(url)).href (:200-202). On factory failure it evicts files/parsed entries keyed ${url}@native (:205) so the native caches cannot turn a transient failure into a permanent one.

Configuring a loader

The constructor copies its argument (this.options = { ...options }, src/air/assets/gltf/loader.ts:78-80), so later mutation of the caller's object does not affect the loader. The option contract (src/air/assets/gltf/progress.ts:11-17):

Option Role
signal?: AbortSignal checked at parseAsync entry (src/air/assets/gltf/loader.ts:117) and at every throwIfAborted checkpoint (src/air/assets/gltf/parser-context.ts:84-86)
dracoDecoder? / meshoptDecoder? / ktx2Transcoder? decoder contracts; normally set through the setters, see skills/cocosair-gltf/references/decoders.md
onProgress? receives GLTFLoadProgress { phase, loaded, total, url? } (src/air/assets/gltf/progress.ts:4-9)

Progress phases are 'container' | 'dependencies' | 'decode' | 'textures' | 'objects' (src/air/assets/gltf/progress.ts:5). The loader's report closure emits container/decode/textures/objects and includes url only when the input was a string (src/air/assets/gltf/loader.ts:120-121, :132, :139, :152, :179); dependencies comes from loadBuffers per buffer through context.report, which never sets url (src/air/assets/gltf/parser-context.ts:87-89, :159, :168), and resolvePrimitives emits additional decode progress per primitive (src/air/assets/gltf/parser-context.ts:210).

setDRACODecoder / setMeshoptDecoder / setKTX2Transcoder (src/air/assets/gltf/loader.ts:82-90) each spread-merge into this.options, map null to undefined, and return this. register / unregister (:91-92) both return this, and unregister discards the registry's boolean (src/air/assets/gltf/extension-registry.ts:72-76), so the loader cannot tell you whether the factory was present. configureGLTFLoaderDefaults(options) (src/air/assets/gltf/loader.ts:43-47) is merge-only and process-wide; every resolution site spreads { ...globalDefaults, ...this.options }, so instance options win (:96, :112, :116). Through loadAsync the resolved options travel under the asset-manager gltf key (:112) and are read back by the native factory (:201). getExtensionSupport() and the 21 registrations are documented in skills/cocosair-gltf/references/extensions-matrix.md.

What parseAsync does, in order

All line numbers are src/air/assets/gltf/loader.ts unless noted.

  1. A pre-aborted signal throws DOMException('glTF load aborted', 'AbortError') - not a GLTFError (:117).
  2. decodeContainer(data) splits JSON + binary (:118; GLB 2.0 chunk checks and glTF-2.0-only enforcement in src/air/assets/gltf/parser-context.ts:12-42).
  3. new GLTFParserContext(json, baseUrl === undefined ? undefined : absoluteURL(baseUrl), resolved) (:119); the report closure passes url only when data is a string (:120-121).
  4. prepareNodes(context) (:122), then new GLTFAsset(context, layout) (:123) - the asset exists before parsing succeeds and is destroyed in the catch.
  5. Inside try: throwIfAborted (:125), registry.createHandlers assigned to context.handlers (:127-128), validateRequired (:129), per-handler validate?.() (:130), abort check (:131), report('container', 1, 1) (:132).
  6. await context.loadBuffers(bin) (:134), which also warns per optional extension with no handler (src/air/assets/gltf/parser-context.ts:140-144).
  7. Every accessor is validated up front via (json.accessors || []).forEach((_, i) => context.accessor(i)) (:136) before any image decode or GPU allocation; accessor() enforces a 16M decoded-component limit (src/air/assets/gltf/parser-context.ts:229, :237).
  8. Per-handler resolveData?.() (:138) is the binary snapshot point: releaseDecodedData() later drops buffers, accessor caches and decoded views (src/air/assets/gltf/parser-context.ts:118-121). Then report('decode', ...) (:139) and an abort check (:140).
  9. Material features: createMaterialFeatures(i, source) plus per-handler await extendMaterial?.() per material (:143-148), assigned to context.materialFeatures (:149).
  10. await loadGLTFTextures(...) (:151), report('textures', ...) (:152), createSkeletons(...) (:153).
  11. await context.resolvePrimitives() (:156) - compressed (Draco) primitives decode before mesh construction (src/air/assets/gltf/parser-context.ts:196-213); plain bufferViews already replaced their payload during loadBuffers(), which calls resolveBufferViews() at src/air/assets/gltf/parser-context.ts:170 and implements it at :178-194.
  12. Mesh/material build loop (:158-170). The dedup key is `${primitive.material ?? -1}:${primitive.attributes.COLOR_0 !== undefined}` (:161), so the same material index yields two distinct materials when one primitive has COLOR_0 and the other does not; primitive.material === undefined builds default features via createMaterialFeatures(-1, {}) (:164-165).
  13. Node cross-checks: every node mesh index resolves and every skin node also references a mesh (:172-177).
  14. createGLTFAnimations(context, layout.paths) (:178), report('objects', 1, 1) (:179), abort check (:180), context.releaseDecodedData() (:181), return (:182).
  15. The catch runs context.dispose(); asset.destroy(); throw error; (:183) - a failed parse leaves no half-built asset alive; dispose() also drains cleanup handlers and calls handler dispose?.() (src/air/assets/gltf/parser-context.ts:111-116). context.warn records into warnings and console.warn('[glTF] ...') (src/air/assets/gltf/parser-context.ts:90).

GLTFAsset surface

class GLTFAsset extends Asset (src/air/assets/gltf/asset.ts:50). There are five public read-only collections, backed by the @internal mutable builder owned (:52-53):

Member Returns Line
meshes / materials / textures / skeletons / animations readonly views of owned.* src/air/assets/gltf/asset.ts:54-58
sceneNames scene names, or ['scene_0'] when the document has no scenes array :59, :73
document context.json - original glTF metadata including camera/light descriptions and original node names :60-61
warnings context.warnings :62
images, meshMaterials @internal; per-mesh material slot lists :63-64

The uuid is `air-gltf-parsed-${++parsedAssetId}` from a module counter (:72, :23). destroy() (:198-204) returns false if already invalid or already requested, sets destroyRequested, removes itself from the assets registry when assets.get(this._uuid) === this (:201), and calls releaseResources() immediately only when instances === 0 (:202); otherwise release is deferred to the last instance's destroy hook. releaseResources() (:205-212) is idempotent through resourcesReleased and destroys the Set union of materials, meshes, skeletons, animations, textures, images and every cached per-scene clip (:207-209), then super.destroy() (:211).

destroy() and dispose() on instances are independent: destroy() on the asset never tears down live instances, and once destroyRequested is set, instantiate() rejects with asset is destroyed (:77) while existing instances keep running until disposed. The instance destroy hook passes decRef(!this.destroyRequested) (:172), so engine auto-release only fires when the asset is not already slated for destruction.

instantiate(sceneIndex)

instantiate(sceneIndex = this.context.json.scene ?? 0) (src/air/assets/gltf/asset.ts:76-196) guards on destroyed/invalid asset and scene index (:77-78). Roots come from json.scenes[sceneIndex].nodes or, when there are no scenes, every parentless layout node (:80). A visible set is built by recursive child walk (:81-83); an included set additionally pulls in every ancestor of every skin joint (:84-89), so skeleton chains survive even when joints sit outside the scene subgraph. Animation clips are rebuilt per scene index - keeping only tracks whose track.path.parseHierarchyAt(0) is in the included path set - cached in sceneClips and reused across instances (:90-101).

The root Node is named sceneNames[sceneIndex] (:102). Handlers see a GLTFInstantiationContext (:104-109; interface at src/air/assets/gltf/extension-registry.ts:42-53). makeNodes runs a buildNode hook that may replace a node with one or more derived nodes (:111-120); rendererTargets(i) prefers instCtx.renderTargets, then mounts, then the original node (:122-125). GLTFWinding is added to the root (:126). The renderer loop (:127-152) rejects a skin node without a mesh (:129), range-checks JOINTS_0 values against skin.joints.length per primitive (:135-138), gives skin nodes a SkinnedMeshRenderer with setUseBakedAnimation(false), skinningRoot = root, skeleton = skin (:139-141) and others a plain MeshRenderer (:143), assigns shared materials per slot (:146), and validates node morph weights against the target count before applying them per primitive (:147-151). Per-node handler.instantiate?.() runs next (:154-158). Finally the root gets Animation plus the private GLTFAnimationPolicy component, winding.lateUpdate() is called once, and animation.clips = clips.slice() with playOnLoad = false (:159-163). GLTFAnimationPolicy (:25-38) is @executionOrder(100) because native Animation is 99 (:27); its onLoad reapplies recorded loops as WrapMode.Loop/Normal because native Animation.onLoad rebuilds the state table and would drop per-instance wrap overrides (:32-36).

Refcounting: ++this.instances; this.addRef() (:164); a root.once(Node.EventType.NODE_DESTROYED, ...) hook (:168-175) decrements and decRefs in a microtask - NODE_DESTROYED precedes child/component teardown - and calls releaseResources() only when destroyRequested && instances === 0. Any failure inside the body destroys the root and rethrows (:195).

GLTFInstance

interface GLTFInstance (src/air/assets/gltf/asset.ts:40-47): readonly root: Node, readonly animations: readonly AnimationClip[], setAnimationLoop(loop, clipName?), dispose(). setAnimationLoop (:176-190) throws a TypeError carrying code: 'AIR_E_GLTF_ANIMATION_OPTIONS' and a clipName property (:177-179) - this is not a GLTFError and that code is not in GLTFErrorCode (see skills/cocosair-gltf/references/diagnostics.md). Four rejection cases: disposed instance or invalid root (:180); non-boolean loop or non-string clipName (:181-183); unknown clip name, with the message listing available clip names (:184-185); a selected native state that has been removed (:187-188). clipName === undefined selects all instance clips (:184). On success it records animationPolicy.loops per selected clip and sets each state.wrapMode (:189-190); calling animation.getState(name) first is what initializes the native evaluator before the override is applied (:186-187). dispose() (:191-194) is idempotent through a disposed flag and runs animation.stop(); root.active = false; root.destroy(); GPU resources follow Cocos deferred destruction (:45).

Both methods are closure properties on the object literal returned by instantiate() (:176-194), so no instrumentation mechanism - prototype, static, export-wrapper, data-property or namespace-member - can attach to them; they are structurally unbindable for apiProof evidence.

Public face versus internals

The single export { ... } block of build/cocosair.module.js (build/cocosair.module.js:161574) includes GLTFLoader, GLTFAsset, GLTFError, GLTFExtensionRegistry, registerGLTFLoader, configureGLTFLoaderDefaults, createDracoDecoder, createMeshoptDecoder, createKTX2Transcoder, isMeshoptAvailable, isKTX2Available, detectImageMime, SUPPORTED_IMAGE_MIMES, KTX2_RAW_MIME, meshQuantizationFactory, meshoptCompressionFactory, dracoCompressionFactory, KHR_MESH_QUANTIZATION, KHR_MESHOPT_COMPRESSION, EXT_MESHOPT_COMPRESSION and KHR_DRACO_MESH_COMPRESSION; it does not include MAX_KTX2_DIMENSION, GLTFParserContext or gltfPhysicalEffect. GLTFInstance and GLTFLoaderOptions are types only (src/air/assets/gltf/index.ts:2, :4). In build/cocosair.module.d.ts: GLTFAsset class :56850, GLTFInstance :56876, getExtensionSupport(): readonly GLTFExtensionSupport[] :56892, handler hooks :56917-56931, GLTFExtensionFactory :56942, GLTFInstantiationContext :56944, registry createHandlers/validateRequired :56965/:56970, GLTFExtensionStatus :56973, GLTFExtensionSupport :56974; gltfPhysicalEffect has zero hits. GLTFParserContext has 15 hits but every one is the name-mangled __private._air_assets_gltf_parser_context__GLTFParserContext, with export class _air_assets_gltf_parser_context__GLTFParserContext at build/cocosair.module.d.ts:72760 inside the __private namespace. A TypeScript consumer writing a custom GLTFExtensionFactory therefore cannot name the context parameter type and must use Parameters<GLTFExtensionFactory>[0] or any.

The loader module also re-exports three type groups for convenience: GLTFExtensionHandler/GLTFExtensionFactory, GLTFLoaderOptions/GLTFLoadProgress, and GLTFExtensionSupport/GLTFExtensionStatus (src/air/assets/gltf/loader.ts:211-213).

Evidence position

From docs/evidence/examples-verified.json (file-level measuredAt 2026-10-04T05:52:32.537Z :2, top-level candidateFingerprint 2f089f6ce25eaccd :7; each results[] entry carries its own fingerprint and no measuredAt). Seventeen of the eighteen gltf-touching ids listed in skills/cocosair-gltf/references/extensions-matrix.md carry GLTF* apiProof bindings - gltf-catalog carries none - and all are result: PASS. Strong bindings (tallied across entry lines docs/evidence/examples-verified.json:1940-19726, :28831-28865, :59997-60048, :63402-63589, :76587-76672, :78899-78950): GLTFLoader -> scene-ready x10 + asset-loaded x2 (12 entries, :16058-:78933); GLTFLoader.parseAsync -> asset-loaded x10 + visible-frame x3 (13 entries, :1957-:78950); GLTFAsset.instantiate -> asset-loaded x5 + visible-frame x2 + node-exists x2 + scene-ready x2 + resource-released x1; GLTFAsset.destroy -> resource-released x10; GLTFLoader.loadAsync -> asset-loaded x1 (:16075); GLTFLoader.getExtensionSupport -> capability-status x1 (:16884); GLTFLoader.setMeshoptDecoder -> scene-ready x1 (:17959), while setDRACODecoder/setKTX2Transcoder stay at no-runtime-error (:17398, :17415). The five collections plus sceneNames/images/owned each carry asset-loaded bindings (meshes x2, :15499, :63487, :76638). Weak (no-runtime-error only): GLTFLoader.constructor/register/unregister, GLTFAsset.constructor/document/warnings/meshMaterials, and all 13 GLTFAsset members exercised by examples/gltf-asset-readonly/src/main.ts (entry id at docs/evidence/examples-verified.json:15289, bindings :15379-15584).

Bound to nothing at all: GLTFInstance itself, GLTFInstance.setAnimationLoop, GLTFInstance.dispose, configureGLTFLoaderDefaults, registerGLTFLoader - zero apiProof entries exist for any of them. For setAnimationLoop/dispose this is structural (closure properties, see above); their proof is indirect: setAnimationLoop is called in examples/gltf-viewer/main.js:189, examples/gltf-skin/src/main.ts:67, examples/gltf-animation-contract/src/main.ts:67 and examples/animated-character-showcase/src/main.ts:92, and examples/gltf-skin/example.json:14 declares it in apiClaims; those examples' validators pass while the call is in their source. animation-playing bindings on gltf ids come from engine symbols (Animation.play, AnimationClip) or from GLTFAsset.animations (docs/evidence/examples-verified.json:76587), never from GLTFInstance. Raw collector runs land under output/, which is gitignored (.gitignore:16) and outside the npm files list, so a loader-API claim is durable only when it points at docs/evidence/examples-verified.json or at the source.

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
[
  "load a glTF or GLB from URL or bytes",
  "compressed model will not load",
  "which glTF extensions are supported",
  "instance animation will not loop",
  "destroying a model leaves GPU resources"
]
owns
[
  "gltf",
  "glb",
  "decoder-injection",
  "extension-support",
  "model-instancing",
  "gltf-errors"
]
not_for
[
  "generic asset caching -> cocosair-assets",
  "edit imported shared materials -> cocosair-materials-effects",
  "skeleton bind poses or morph weights -> cocosair-skinning-morph"
]
metadata
{
  "author": "oahc09@gmail.com",
  "version": "1.0.0",
  "last-updated": "2026-10-13",
  "description_zh": "加载 glTF 和 GLB,配置解码器、扩展、进度、实例和错误处理。用于模型加载、压缩资源部署和加载器能力诊断。"
}

README badge

README badge for oahc09/cocosairjs/cocosair-gltf