Skip to content

A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.

feat(cocos): the importer binds SkinnedMeshRenderer to the model skin and plays SkeletalAnimation clips on the skeleton they are put on, cut to the span and wrap mode Cocos names

yhh34bc39aa3b64
diff --git a/pipeline/src/import/cocos/components.ts b/pipeline/src/import/cocos/components.ts
index 1e6d45680..1d666b7fe 100644
--- a/pipeline/src/import/cocos/components.ts
+++ b/pipeline/src/import/cocos/components.ts
@@ -16,6 +16,7 @@ import { particleSystem } from './particle';
import type { CocosAssetEntry, CocosAssetIndex } from './assets';
import { type CocosComponent, type CocosNode } from './document';
import type { ImportReport } from './report';
+import { NODE_REF } from './document';
export interface ComponentData {
type: string;
@@ -47,6 +48,15 @@ export interface ComponentContext {
* the part was picked because the model draws only one.
*/
modelMesh?(uuid: string): { components: Record<string, unknown>[]; exact: boolean } | null;
+ /** The joints, by name, a skinned part of a model is bound to, in the order its vertices index them. */
+ modelSkin?(meshUuid: string): string[] | null;
+ /**
+ * A clip of a model, ready to play on the hierarchy @p paths describes (node name to its path under the node the clip plays from): the
+ * project-relative timeline, or null when the clip or its nodes are not there.
+ */
+ clipOn?(clipUuid: string, paths: Map<string, string>, where: string): string | null;
+ /** The Cocos node an id names in the document being converted. */
+ nodeById?: Map<string, CocosNode>;
/** The script class a compressed class id names, when the project has that script. */
scriptClass?(classId: string): { name: string } | undefined;
/** The project-relative ref of a prefab, queuing it for conversion; null when the project does not have it. */
@@ -424,6 +434,67 @@ function directionalLight(c: CocosComponent, ctx: ComponentContext, where: strin
};
}
+/** Where each node under @p node stands, by name, as a path from it: what a clip addresses a node by. The first node of a name wins. */
+function namePaths(node: CocosNode): Map<string, string> {
+ const paths = new Map<string, string>();
+ const walk = (n: CocosNode, prefix: string): void => {
+ for (const child of n.children) {
+ const here = prefix ? `${prefix}/${child.name}` : child.name;
+ if (!paths.has(child.name)) paths.set(child.name, here);
+ walk(child, here);
+ }
+ };
+ walk(node, '');
+ return paths;
+}
+
+/** The first node of a name in the subtree under @p root, the root itself included. */
+function findByName(root: CocosNode, name: string): CocosNode | null {
+ if (root.name === name) return root;
+ for (const child of root.children) {
+ const hit = findByName(child, name);
+ if (hit) return hit;
+ }
+ return null;
+}
+
+/**
+ * `cc.SkinnedMeshRenderer`: a part of a model bound to bones that are nodes of this document. The mesh is the model's own; the joints are the
+ * nodes under the skinning root that carry the names the model's skin binds, in the order the model's vertices index them.
+ */
+function skinnedMeshRenderer(c: CocosComponent, ctx: ComponentContext, where: string): { component: ComponentData; extra: ComponentData[] } | null {
+ const mesh = meshRenderer(c, ctx, where);
+ if (!mesh) return null;
+ const meshUuid = uuidOf(c.data._mesh);
+ const names = ctx.modelSkin?.(meshUuid);
+ const rootRef = isObj(c.data._skinningRoot) ? c.data._skinningRoot[NODE_REF] : undefined;
+ const root = typeof rootRef === 'string' ? ctx.nodeById?.get(rootRef) : undefined;
+ if (!names || names.length === 0 || !root) {
+ ctx.report.component('cc.SkinnedMeshRenderer', 'partial');
+ ctx.report.note('skin-not-bound', where);
+ return { component: mesh.component, extra: [] };
+ }
+ const joints = names.map((name) => {
+ const node = findByName(root, name);
+ return node ? { [NODE_REF]: node.id } : { [NODE_REF]: null };
+ });
+ const missing = names.filter((name) => !findByName(root, name)).length;
+ ctx.report.component('cc.SkinnedMeshRenderer', missing > 0 || mesh.partial ? 'partial' : 'mapped');
+ if (missing > 0) ctx.report.note('skin-joint-missing', `${where}: ${missing} of ${names.length}`);
+ return { component: mesh.component, extra: [{ type: 'MeshSkin', data: { joints } }] };
+}
+
+/** `cc.SkeletalAnimation`: the clip it plays by default, copied onto this node's own bones, played from the start if the node asks. */
+function skeletalAnimation(c: CocosComponent, node: CocosNode, ctx: ComponentContext, where: string): ComponentData | null {
+ const clips = (Array.isArray(c.data._clips) ? c.data._clips : []).map(uuidOf).filter(Boolean);
+ const wanted = uuidOf(c.data._defaultClip) || clips[0] || '';
+ const ref = wanted ? ctx.clipOn?.(wanted, namePaths(node), where) : null;
+ if (!ref) return null;
+ if (clips.length > 1) ctx.report.note('animation-several-clips', where);
+ ctx.report.component('cc.SkeletalAnimation', clips.length > 1 ? 'partial' : 'mapped');
+ return { type: 'TimelinePlayer', data: { timeline: ref, playing: c.data.playOnLoad === true, speed: 1, wrapMode: '' } };
+}
+
/**
* The shapes Cocos Creator builds in (`db://internal/primitives.fbx`), identified by the bounds of what the editor imported them to: the
* engine's own builtin meshes, and the size of the Cocos one in world units. The engine's are 100 across, the Cocos ones about 1 (a plane 10),
@@ -440,7 +511,7 @@ const PRIMITIVE_MESHES: Record<string, { ref: string; size: number }> = {
const ENGINE_PRIMITIVE_SIZE = 100;
/** `cc.MeshRenderer`: the mesh is the model's own part, drawn with the model's own material until the Cocos material is carried across. */
-function meshRenderer(c: CocosComponent, ctx: ComponentContext, where: string): { component: ComponentData; scale?: number } | null {
+function meshRenderer(c: CocosComponent, ctx: ComponentContext, where: string): { component: ComponentData; scale?: number; partial: boolean } | null {
const meshUuid = uuidOf(c.data._mesh);
const hasMaterial = Array.isArray(c.data._materials) && c.data._materials.some((m) => uuidOf(m) !== '');
if (meshUuid.startsWith(COCOS_PRIMITIVES)) {
@@ -449,11 +520,11 @@ function meshRenderer(c: CocosComponent, ctx: ComponentContext, where: string):
ctx.report.note('mesh-builtin-shape-unknown', `${where}: ${meshUuid.split('@')[1] ?? ''}`);
return null;
}
- ctx.report.component('cc.MeshRenderer', hasMaterial ? 'partial' : 'mapped');
if (hasMaterial) ctx.report.note('mesh-material-not-carried', where);
return {
component: { type: 'MeshRenderer', data: { mesh: primitive.ref, enabled: c.enabled } },
scale: primitive.size / ENGINE_PRIMITIVE_SIZE,
+ partial: hasMaterial,
};
}
const found = meshUuid ? ctx.modelMesh?.(meshUuid) : null;
@@ -471,8 +542,7 @@ function meshRenderer(c: CocosComponent, ctx: ComponentContext, where: string):
partial = true;
ctx.report.note('mesh-material-from-model', where);
}
- ctx.report.component('cc.MeshRenderer', partial ? 'partial' : 'mapped');
- return { component: { type: 'MeshRenderer', data: { ...found.components[0]!, enabled: c.enabled } } };
+ return { component: { type: 'MeshRenderer', data: { ...found.components[0]!, enabled: c.enabled } }, partial };
}
/** `cc.UIOpacity`: the alpha of the node and everything under it, which the engine's GroupOpacity is. */
@@ -521,6 +591,8 @@ export function convertNode(node: CocosNode, ctx: ComponentContext, where: strin
const unmapped: Raw[] = [];
// a mesh whose unit is not the engine's resizes the node it hangs on
let unitScale = 1;
+ // components a mapped one brings with it, added after the loop
+ const extra: ComponentData[] = [];
for (const c of node.components) {
let out: ComponentData | null = null;
@@ -577,9 +649,19 @@ export function convertNode(node: CocosNode, ctx: ComponentContext, where: strin
case 'cc.MeshRenderer': {
const mesh = meshRenderer(c, ctx, where);
out = mesh?.component ?? null;
+ if (mesh) ctx.report.component('cc.MeshRenderer', mesh.partial ? 'partial' : 'mapped');
if (mesh?.scale !== undefined) unitScale = mesh.scale;
break;
}
+ case 'cc.SkinnedMeshRenderer': {
+ const skinned = skinnedMeshRenderer(c, ctx, where);
+ out = skinned?.component ?? null;
+ if (skinned) extra.push(...skinned.extra);
+ break;
+ }
+ case 'cc.SkeletalAnimation':
+ out = skeletalAnimation(c, node, ctx, where);
+ break;
case 'cc.UIOpacity':
out = uiOpacity(c, ctx);
break;
@@ -614,6 +696,7 @@ export function convertNode(node: CocosNode, ctx: ComponentContext, where: strin
unmapped.push({ type: c.type, enabled: c.enabled, data: c.data });
}
+ components.push(...extra);
if (unitScale !== 1) {
const scale = components[0]!.data.scale as { x: number; y: number; z: number };
components[0]!.data.scale = { x: scale.x * unitScale, y: scale.y * unitScale, z: scale.z * unitScale };
diff --git a/pipeline/src/import/cocos/convert.ts b/pipeline/src/import/cocos/convert.ts
index deb23502a..808de1ffb 100644
--- a/pipeline/src/import/cocos/convert.ts
+++ b/pipeline/src/import/cocos/convert.ts
@@ -79,7 +79,7 @@ export interface ConvertContext extends ComponentContext {
/** The project-relative path the converted prefab of a uuid is written to. */
prefabRef(uuid: string): string | null;
/** The engine prefab of a model a uuid names (the whole model, or its scene), or null when the uuid is not a model that was brought in. */
- modelInstance?(uuid: string): { prefab: string; rootId: string; name: string } | null;
+ modelInstance?(uuid: string): { prefab: string; rootId: string; name: string; paths: Map<string, string> } | null;
/** Where the document being converted lives, for notes. */
where: string;
}
@@ -283,13 +283,29 @@ function diff(pristine: Map<string, Flat>, patched: Map<string, Flat>, ctx: Conv
* instance's root can be addressed: its name, whether it is active and where it stands. The rest (a material put on a mesh, a clip set on its
* animation) is counted, not lost silently.
*/
-function modelInstanceOverrides(node: CocosNode, model: { rootId: string; name: string }, ctx: ConvertContext): PrefabOverride[] {
+function modelInstanceOverrides(node: CocosNode, model: { rootId: string; name: string; paths: Map<string, string> }, ctx: ConvertContext): PrefabOverride[] {
const inst = node.instance!;
- const roots = inst.overrides.filter((o) => o.target.length === 1);
- const inner = inst.overrides.length - roots.length;
+ // A property of the instance's root: its name, whether it is on, where it stands. The overrides on a component of the model are told apart
+ // by what they set: a skeletal animation's clip is carried, anything else is counted.
+ const animation = animationOverrides(inst.overrides);
+ const shape = (o: CocosOverride): boolean => ['_name', '_active', '_lpos', '_lrot', '_lscale', '_euler'].includes(o.path[0] ?? '');
+ const roots = inst.overrides.filter((o) => o.target.length === 1 && shape(o));
+ const inner = inst.overrides.length - roots.length - animation.used;
if (inner > 0) ctx.report.note('model-instance-overrides', `${ctx.where}: ${node.name} (${inner} on the model's own parts)`);
+ const out: PrefabOverride[] = [];
+ if (animation.clip) {
+ const timeline = ctx.clipOn?.(animation.clip, model.paths, `${ctx.where}: ${node.name}`);
+ if (timeline) {
+ out.push({
+ prefabEntityId: model.rootId, type: 'component_added', componentType: 'TimelinePlayer',
+ componentData: { type: 'TimelinePlayer', data: { timeline, playing: animation.playOnLoad, speed: 1, wrapMode: '' } },
+ });
+ } else {
+ ctx.report.note('model-instance-clip-not-found', `${ctx.where}: ${node.name}`);
+ }
+ }
const addr = roots[0]?.target[0];
- if (addr === undefined) return [];
+ if (addr === undefined) return out;
const base: CocosNode = {
id: addr, name: model.name, active: true, pos: { x: 0, y: 0, z: 0 }, rot: { x: 0, y: 0, z: 0, w: 1 }, scale: { x: 1, y: 1, z: 1 },
layer: 33554432, components: [], children: [],
@@ -298,7 +314,24 @@ function modelInstanceOverrides(node: CocosNode, model: { rootId: string; name:
const patched = structuredClone(pristine);
applyOverrides(patched, roots, ctx);
const quiet: ConvertContext = { ...ctx, report: new ImportReport() };
- return diff(flatten(pristine, quiet), flatten(patched, quiet), ctx).map((o) => ({ ...o, prefabEntityId: model.rootId }));
+ return [...out, ...diff(flatten(pristine, quiet), flatten(patched, quiet), ctx).map((o) => ({ ...o, prefabEntityId: model.rootId }))];
+}
+
+/** The clip an instance sets on its model's skeletal animation, if it sets one, and whether it plays on load. `used` counts the overrides read. */
+function animationOverrides(overrides: CocosOverride[]): { clip: string | null; playOnLoad: boolean; used: number } {
+ let defaultClip = '';
+ let firstClip = '';
+ let playOnLoad = false;
+ let used = 0;
+ for (const o of overrides) {
+ const prop = o.path[0];
+ const value = o.value as { __uuid__?: unknown } | boolean | null;
+ if (prop === '_defaultClip' && typeof value === 'object' && value && typeof value.__uuid__ === 'string') { defaultClip = value.__uuid__; used++; }
+ else if (prop === '_clips' && o.path[1] === '0' && typeof value === 'object' && value && typeof value.__uuid__ === 'string') { firstClip = value.__uuid__; used++; }
+ else if (prop === '_clips' && o.path[1] === 'length') used++;
+ else if (prop === 'playOnLoad') { playOnLoad = value === true; used++; }
+ }
+ return { clip: defaultClip || firstClip || null, playOnLoad, used };
}
/** The overrides an instance node applies over the prefab it names, or null when that prefab is missing. */
@@ -348,7 +381,19 @@ function resolveRefs(components: ComponentData[], to: (id: string) => unknown, m
// Documents.
// ---------------------------------------------------------------------------
+/** Every node of a document by id, the nodes under an instance left out (they are the prefab's own, in its own space). */
+function indexNodes(roots: CocosNode[]): Map<string, CocosNode> {
+ const nodes = new Map<string, CocosNode>();
+ const walk = (n: CocosNode): void => {
+ nodes.set(n.id, n);
+ if (!n.instance) n.children.forEach(walk);
+ };
+ roots.forEach(walk);
+ return nodes;
+}
+
export function convertPrefab(doc: CocosDocument, ctx: ConvertContext): PrefabFile {
+ ctx.nodeById = indexNodes(doc.roots);
const root = doc.roots[0];
if (!root) throw new Error('prefab has no root node');
const entities: PrefabEntity[] = [];
@@ -387,6 +432,7 @@ export function convertPrefab(doc: CocosDocument, ctx: ConvertContext): PrefabFi
}
export function convertScene(doc: CocosDocument, ctx: ConvertContext): SceneFile {
+ ctx.nodeById = indexNodes(doc.roots);
const entities: (SceneEntity | SceneInstanceEntry)[] = [];
ctx.report.documents.converted++;
// From 1: 0 is the engine's "no entity", and a reference to an entity numbered 0 would read as none.
diff --git a/pipeline/src/import/cocos/importProject.ts b/pipeline/src/import/cocos/importProject.ts
index 600393333..f8fb92db7 100644
--- a/pipeline/src/import/cocos/importProject.ts
+++ b/pipeline/src/import/cocos/importProject.ts
@@ -18,7 +18,7 @@ import type { AssetHints, SliceBorder } from './components';
import { convertPrefab, convertScene, type ConvertContext } from './convert';
import { parseCocosDocument, type CocosDocument } from './document';
import { ImportReport, type ImportReportData } from './report';
-import { CocosModels } from './models';
+import { CocosModels, clipOf, clipPlayOf, retargetClip } from './models';
export interface CocosImportOptions {
/** The Cocos project folder (the one holding `assets/` and `settings/`). */
@@ -162,7 +162,31 @@ export async function importCocosProject(opts: CocosImportOptions): Promise<Impo
},
modelInstance(uuid) {
const m = models.use(uuid);
- return m && m.use.prefab ? { prefab: m.use.prefab, rootId: m.use.rootId, name: path.basename(m.entry.rel).replace(/\.[^.]+$/, '') } : null;
+ return m && m.use.prefab ? { prefab: m.use.prefab, rootId: m.use.rootId, name: path.basename(m.entry.rel).replace(/\.[^.]+$/, ''), paths: m.use.paths } : null;
+ },
+ modelSkin(meshUuid) {
+ const m = models.use(meshUuid);
+ if (!m) return null;
+ const name = models.meshName(m.entry, meshUuid);
+ const own = name ? m.use.skin.get(name) : undefined;
+ if (own) return own;
+ return m.use.skin.size === 1 ? [...m.use.skin.values()][0]! : null;
+ },
+ clipOn(clipUuid, paths, where) {
+ const clip = models.use(clipUuid);
+ if (!clip) return null;
+ const sub = clip.entry.subs.get(clipUuid);
+ const ref = clipOf(clip.use, sub?.name);
+ if (!ref) return null;
+ if (opts.dryRun) return ref;
+ const key = createHash('sha1').update(JSON.stringify([...paths].sort())).digest('hex').slice(0, 8);
+ const copy = retargetClip(out, ref, paths, key, clipPlayOf(sub?.userData));
+ if (!copy) {
+ report.note('animation-no-matching-bones', where);
+ return null;
+ }
+ if (copy.dropped > 0) report.note('animation-tracks-dropped', `${where}: ${copy.dropped}`);
+ return copy.ref;
},
modelMesh(uuid) {
const m = models.use(uuid);
diff --git a/pipeline/src/import/cocos/models.ts b/pipeline/src/import/cocos/models.ts
index a45ced2db..6115150f6 100644
--- a/pipeline/src/import/cocos/models.ts
+++ b/pipeline/src/import/cocos/models.ts
@@ -8,10 +8,11 @@
* import for each model a converted document uses, and answers the two questions the converter has: which prefab is this model, and which mesh
* component does this Cocos mesh correspond to.
*/
-import { existsSync, readdirSync, readFileSync } from 'node:fs';
+import { existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from 'node:fs';
import path from 'node:path';
import { importModelFile } from '../../assets/importModelFile';
import { modelStem } from '../../assets/readModelSource';
+import { metaTypeFor, mintMeta } from '../../assets/assetMeta';
import type { CocosAssetEntry, CocosAssetIndex } from './assets';
type Raw = Record<string, unknown>;
@@ -26,6 +27,10 @@ export interface ModelUse {
byEntity: Map<string, Raw[]>;
/** Project-relative path of each animation clip, by the animation's own name. */
clips: Map<string, string>;
+ /** Where each node of the model stands under the prefab's root, as the path a clip addresses it by, keyed by the node's name. */
+ paths: Map<string, string>;
+ /** The names of the joints a skinned part is bound to, in the order its vertices index them, keyed by the part's name. */
+ skin: Map<string, string[]>;
}
const MODEL_EXT = /\.(fbx|gltf|glb)$/i;
@@ -105,6 +110,21 @@ export class CocosModels {
}
}
+/** A clip's name as a file name carries it: what the model import made of it, so a Cocos name and a product name compare. */
+const clipKey = (name: string): string => name.replace(/\.(animation|anim)$/i, '').replace(/[^A-Za-z0-9]+/g, '_').replace(/^_+|_+$/g, '').toLowerCase();
+
+/**
+ * A clip of this model by the name Cocos gave it, or its only clip when the names do not meet (a model with one animation has nothing
+ * else a node could mean).
+ */
+export function clipOf(use: ModelUse, cocosName: string | undefined): string | null {
+ if (cocosName) {
+ const wanted = clipKey(cocosName);
+ for (const [name, ref] of use.clips) if (clipKey(name) === wanted) return ref;
+ }
+ return use.clips.size === 1 ? [...use.clips.values()][0]! : null;
+}
+
function readUse(prefabAbs: string, prefab: string, absDir: string, stem: string, destDir: string): ModelUse {
// A file with animation and no mesh produces no prefab, only clips.
const hasPrefab = existsSync(prefabAbs);
@@ -122,5 +142,93 @@ function readUse(prefabAbs: string, prefab: string, absDir: string, stem: string
} catch {
// no clips beside the model
}
- return { prefab: hasPrefab ? prefab : '', rootId: (doc as { rootEntityId?: string }).rootEntityId ?? 'n1', byEntity, clips };
+ // where each node stands, by name: a clip addresses a node by its path under the root, the root itself left out
+ const entities = (doc as { entities?: Raw[] }).entities ?? [];
+ const byId = new Map(entities.map((e) => [String(e.prefabEntityId), e]));
+ const paths = new Map<string, string>();
+ const pathOf = (e: Raw): string => {
+ const parent = typeof e.parent === 'string' ? byId.get(e.parent) : undefined;
+ return parent && parent.parent !== null && parent.parent !== undefined ? `${pathOf(parent)}/${String(e.name)}` : String(e.name);
+ };
+ for (const e of entities) if (e.parent !== null && e.parent !== undefined && !paths.has(String(e.name))) paths.set(String(e.name), pathOf(e));
+ const skin = new Map<string, string[]>();
+ for (const e of entities) {
+ for (const c of Array.isArray(e.components) ? (e.components as Raw[]) : []) {
+ if (c.type !== 'MeshSkin' || !isObj(c.data) || !Array.isArray(c.data.joints)) continue;
+ skin.set(String(e.name), c.data.joints.map((id) => String(byId.get(String(id))?.name ?? '')));
+ }
+ }
+ return { prefab: hasPrefab ? prefab : '', rootId: (doc as { rootEntityId?: string }).rootEntityId ?? 'n1', byEntity, clips, paths, skin };
+}
+
+/** How a Cocos clip plays, from the sub-asset the scene names: the part of the animation it is, and what it does at its end. */
+export interface ClipPlay {
+ span?: { from: number; to: number };
+ wrapMode?: 'once' | 'loop' | 'pingPong';
+}
+
+/** Cocos's `AnimationClip.WrapMode` in the timeline's names: Loop (2) and PingPong (36) are themselves; the rest play once. */
+export function wrapModeOf(cocos: unknown): ClipPlay['wrapMode'] {
+ return cocos === 2 || cocos === 22 ? 'loop' : cocos === 36 ? 'pingPong' : 'once';
+}
+
+/** What a clip sub-asset says about how it plays: the span of the take it covers and its wrap mode. */
+export function clipPlayOf(userData: Record<string, unknown> | undefined): ClipPlay {
+ const span = userData?.span;
+ const play: ClipPlay = { wrapMode: wrapModeOf(userData?.wrapMode) };
+ if (isObj(span) && typeof span.from === 'number' && typeof span.to === 'number' && span.to > span.from) play.span = { from: span.from, to: span.to };
+ return play;
+}
+
+interface Key { time: number; [k: string]: unknown }
+
+/**
+ * A clip written for one hierarchy, addressed to another: each track follows the node of its last name to where that node stands in @p paths.
+ * Cocos plays an animation file's clip on any skeleton whose bones carry the names it animates, and the engine addresses by path, so the clip is
+ * copied once for each skeleton it is played on. A track whose node the target does not have is dropped, and counted. Cocos also cuts one take
+ * into named clips by time range; the copy keeps the keys inside @p play.span, moved to start at zero.
+ *
+ * @returns the project-relative path of the copy, or null when no track found its node.
+ */
+export function retargetClip(out: string, clipRef: string, paths: Map<string, string>, key: string, play: ClipPlay = {}): { ref: string; dropped: number } | null {
+ const abs = path.join(out, clipRef);
+ const doc = JSON.parse(readFileSync(abs, 'utf8')) as { tracks?: Raw[]; duration?: number; wrapMode?: string };
+ const span = play.span;
+ const tracks: Raw[] = [];
+ let dropped = 0;
+ // A clip of a single object animates the object itself, which the file calls by its own name and a scene calls whatever it likes: when exactly
+ // every track is on one top-level name and it finds no node, it is the node the clip plays on.
+ const loose = new Set<string>();
+ for (const track of doc.tracks ?? []) {
+ const cp = typeof track.childPath === 'string' ? track.childPath : '';
+ if (cp !== '' && !cp.includes('/') && !paths.has(cp)) loose.add(cp);
+ }
+ const host = loose.size === 1 && (doc.tracks ?? []).every((t) => t.childPath === [...loose][0]) ? [...loose][0]! : null;
+ for (const track of doc.tracks ?? []) {
+ const childPath = typeof track.childPath === 'string' ? track.childPath : '';
+ const name = childPath.split('/').pop() ?? '';
+ const target = childPath === '' || (host !== null && childPath === host) ? '' : paths.get(name);
+ if (target === undefined) {
+ dropped++;
+ continue;
+ }
+ const channels = (Array.isArray(track.channels) ? (track.channels as Raw[]) : []).map((channel) => {
+ const keys = (Array.isArray(channel.keyframes) ? (channel.keyframes as Key[]) : []);
+ if (!span) return channel;
+ const inside = keys.filter((k) => k.time >= span.from - 1e-6 && k.time <= span.to + 1e-6).map((k) => ({ ...k, time: Math.max(0, k.time - span.from) }));
+ return { ...channel, keyframes: inside };
+ }).filter((channel) => (channel.keyframes as unknown[]).length > 0);
+ if (channels.length === 0) continue;
+ tracks.push({ ...track, childPath: target, name: target.split('/').pop() || track.name, channels });
+ }
+ if (tracks.length === 0) return null;
+ const tag = [key, span ? `${span.from}-${span.to}` : '', play.wrapMode ?? ''].filter(Boolean).join('_').replace(/[^A-Za-z0-9]+/g, '_');
+ const ref = clipRef.replace(/\.estimeline$/, `__${tag}.estimeline`);
+ const file = path.join(out, ref);
+ mkdirSync(path.dirname(file), { recursive: true });
+ const copy = { ...doc, tracks, duration: span ? span.to - span.from : doc.duration, ...(play.wrapMode ? { wrapMode: play.wrapMode } : {}) };
+ writeFileSync(file, `${JSON.stringify(copy, null, 2)}\n`);
+ const type = metaTypeFor(file);
+ if (type && !existsSync(`${file}.meta`)) writeFileSync(`${file}.meta`, `${JSON.stringify(mintMeta(type), null, 2)}\n`);
+ return { ref, dropped };
}
diff --git a/pipeline/tests/cocos-import-models.test.ts b/pipeline/tests/cocos-import-models.test.ts
index 9c28ca39a..3e534857f 100644
--- a/pipeline/tests/cocos-import-models.test.ts
+++ b/pipeline/tests/cocos-import-models.test.ts
@@ -146,3 +146,61 @@ describe('a Cocos built-in shape', () => {
expect(transform.data.scale.x).toBeCloseTo(0.02, 6);
});
});
+
+describe('a clip played on another skeleton', () => {
+ let dir: string;
+ const clip = (tracks: Array<{ childPath: string; keys: number[] }>) => ({
+ version: '1.3', type: 'timeline', duration: 4, wrapMode: 'once',
+ tracks: tracks.map((t) => ({
+ type: 'property', name: t.childPath.split('/').pop(), childPath: t.childPath, component: 'Transform',
+ channels: [{ property: 'position.x', keyframes: t.keys.map((time) => ({ time, value: time * 10, inTangent: 0, outTangent: 0, interpolation: 'linear' })) }],
+ })),
+ });
+ const write = (name: string, doc: unknown): string => {
+ mkdirSync(path.join(dir, 'clips'), { recursive: true });
+ writeFileSync(path.join(dir, 'clips', name), JSON.stringify(doc));
+ return `clips/${name}`;
+ };
+ const read = (ref: string): any => JSON.parse(readFileSync(path.join(dir, ref), 'utf8'));
+
+ beforeAll(() => { dir = mkdtempSync(path.join(tmpdir(), 'cocos-clip-')); });
+ afterAll(() => rmSync(dir, { recursive: true, force: true, maxRetries: 10, retryDelay: 50 }));
+
+ it('addresses each track by where its bone stands in the skeleton it is played on', async () => {
+ const { retargetClip } = await import('../src/import/cocos/models');
+ const ref = write('walk.estimeline', clip([{ childPath: 'Bone001', keys: [0, 1] }, { childPath: 'Bone001/Hand', keys: [0, 1] }]));
+ const copy = retargetClip(dir, ref, new Map([['Bone001', 'Root/Bone001'], ['Hand', 'Root/Bone001/Hand']]), 'rigA');
+ expect(copy?.dropped).toBe(0);
+ expect(read(copy!.ref).tracks.map((t: any) => t.childPath)).toEqual(['Root/Bone001', 'Root/Bone001/Hand']);
+ expect(existsSync(path.join(dir, `${copy!.ref}.meta`))).toBe(true);
+ });
+
+ it('drops a track whose bone the skeleton does not have, and says how many', async () => {
+ const { retargetClip } = await import('../src/import/cocos/models');
+ const ref = write('run.estimeline', clip([{ childPath: 'Bone001', keys: [0, 1] }, { childPath: 'Bone001/Tail', keys: [0, 1] }]));
+ const copy = retargetClip(dir, ref, new Map([['Bone001', 'Bone001']]), 'rigB');
+ expect(copy?.dropped).toBe(1);
+ expect(read(copy!.ref).tracks).toHaveLength(1);
+ expect(retargetClip(dir, ref, new Map(), 'rigC')).toBeNull();
+ });
+
+ it('plays a clip that animates a single object on the node it is put on, whatever that node is called', async () => {
+ const { retargetClip } = await import('../src/import/cocos/models');
+ const ref = write('spin.estimeline', clip([{ childPath: 'fx_moon', keys: [0, 2] }]));
+ const copy = retargetClip(dir, ref, new Map(), 'host');
+ expect(read(copy!.ref).tracks.map((t: any) => t.childPath)).toEqual(['']);
+ });
+
+ it('keeps the part of the take a Cocos clip covers, starting at zero, and the wrap mode it asks for', async () => {
+ const { retargetClip, clipPlayOf } = await import('../src/import/cocos/models');
+ const ref = write('take.estimeline', clip([{ childPath: 'Bone001', keys: [0, 1, 2, 3, 4] }]));
+ const play = clipPlayOf({ span: { from: 1, to: 3 }, wrapMode: 2 });
+ const copy = retargetClip(dir, ref, new Map([['Bone001', 'Bone001']]), 'cut', play);
+ const doc = read(copy!.ref);
+ expect(doc.duration).toBe(2);
+ expect(doc.wrapMode).toBe('loop');
+ expect(doc.tracks[0].channels[0].keyframes.map((k: any) => k.time)).toEqual([0, 1, 2]);
+ expect(clipPlayOf({ wrapMode: 36 }).wrapMode).toBe('pingPong');
+ expect(clipPlayOf({ wrapMode: 1 }).wrapMode).toBe('once');
+ });
+});
diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjs
index 3dea80af8..5b58ce784 100644
--- a/tools/releaseNotes.mjs
+++ b/tools/releaseNotes.mjs
@@ -28,6 +28,8 @@ export const NOTES_FLOOR = 'v0.65.0';
* the reader recognises anyway.
*/
export const NOTED = {
+ 'feat(cocos): the importer binds SkinnedMeshRenderer to the model skin and plays SkeletalAnimation clips on the skeleton they are put on, cut to the span and wrap mode Cocos names':
+ {"internal":"The Cocos Creator compatibility layer and importer have not shipped; nothing a creator reaches without opting in."},
'feat(cocos): the importer brings in the models a project draws with the engine model import, maps MeshRenderer and the built-in shapes onto it, and the editor and the importer share one model import':
{"internal":"The Cocos Creator compatibility layer and importer have not shipped; the shared model import is a refactor with no change a creator sees."},
'feat(particle): an emitter can carry an added velocity per particle and limit particle speed with a dampening, and the Cocos velocity, force and limit modules map onto them':