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.
TypeScript 2d-game-engine3d3d-game-engineandroidcppecsgame-editorgame-enginegamedeviostypescriptwebassemblywebglwebgpuwechat-minigame
feat(pipeline): import a Cocos Creator 3.x project as Estella prefabs and scenes, without touching the source
yhh67337f1484c1
diff --git a/pipeline/bin/estella.mjs b/pipeline/bin/estella.mjsindex 8492f9ce6..9d16ef027 100644--- a/pipeline/bin/estella.mjs+++ b/pipeline/bin/estella.mjs@@ -24,6 +24,8 @@ const USAGE = `usage: node pipeline/bin/estella.mjs create <template> <dir> [--n[--project <dir>] [--scale <n>][--specular-map color|orm] [--lightmap-uv] [--lods <0-3>]node pipeline/bin/estella.mjs import-hdr <file.hdr> [outDir] [--face-size <n>]+ node pipeline/bin/estella.mjs import-cocos <cocosProjectDir> <estellaProjectDir>+ [--only <assets/ subpath>]... [--into <folder>] [--dry-run]node pipeline/bin/estella.mjs bake-scene <scene.esscene> [--check]node pipeline/bin/estella.mjs package-openpaas <exportDir> --config <local.json> --out <game.sp>@@ -75,6 +77,16 @@ editor), unwrapping one where the source's second set is too sparse to bake intotriangles) as <mesh>_lod<n>.esmesh and a LODGroup that swaps them in (GenerateLODs in the editor); skinned and morphing meshes keep one level.+import-cocos takes a Cocos Creator 3.x project into an Estella project without touching+it: the source is only read, and an output folder inside it is refused. Prefabs and scenes+become \`.esprefab\` / \`.esscene\` under assets/<into> (default cocos), keeping the source's+folder layout; a prefab instance stays a nested prefab whose changes are overrides. Only the+textures and fonts the converted documents use are copied. Components with a counterpart+(Node, Sprite, Label, RichText, Camera) are mapped; every other component is kept verbatim+under the entity's metadata.cocos and counted. assets/<into>/import-report.json says what+was mapped, approximated and left out, and --dry-run writes nothing but still prints it.+--only restricts the documents converted to those under the given assets/ subpath(s).+import-hdr bakes an equirectangular panorama into the two things a renderer asksan environment for: nine irradiance coefficients (in the \`.esenv\`) and oneprefiltered octahedral atlas beside it, which the document names as a sibling.@@ -134,6 +146,20 @@ function parseArgs(argv) {}return { command, source: path.resolve(projectDir), config: path.resolve(rest[config + 1]), out: path.resolve(rest[out + 1]) };}+ if (command === 'import-cocos') {+ const target = rest.find((a, i) => !a.startsWith('--') && rest[i - 1] !== '--only' && rest[i - 1] !== '--into');+ if (!projectDir || !target) {+ console.error(USAGE);+ process.exit(2);+ }+ const only = [];+ for (let i = 0; i < rest.length; i++) if (rest[i] === '--only' && rest[i + 1]) only.push(rest[i + 1].replace(/^\/+/, ''));+ const into = rest.indexOf('--into');+ return {+ command, source: path.resolve(projectDir), out: path.resolve(target), only,+ into: into >= 0 ? rest[into + 1] : undefined, dryRun: rest.includes('--dry-run'),+ };+ }if (command === 'import-model' || command === 'import-gltf' || command === 'import-hdr') {if (!projectDir) {console.error(USAGE);@@ -793,6 +819,21 @@ if (opts.command === 'package-openpaas') {process.exit(process.exitCode ?? 0);}+if (opts.command === 'import-cocos') {+ const { mod, cleanup } = await loadPipeline(path.join(PIPELINE, 'src', 'import', 'cocos', 'index.ts'), 'cocosImport.mjs');+ try {+ const report = mod.importCocosProject({+ source: opts.source, out: opts.out, only: opts.only, dryRun: opts.dryRun, ...(opts.into ? { into: opts.into } : {}),+ });+ console.log(JSON.stringify(report, null, 2));+ process.exitCode = report.documents.failed.length ? 1 : 0;+ } catch (e) {+ console.error(e instanceof Error ? e.message : String(e));+ process.exitCode = 1;+ } finally { cleanup(); }+ process.exit(process.exitCode ?? 0);+}+// `import-gltf` is the name this command shipped under; it reads any of the// model sources now, and the old spelling keeps working.if (opts.command === 'import-model' || opts.command === 'import-gltf') {diff --git a/pipeline/src/import/cocos/assets.ts b/pipeline/src/import/cocos/assets.tsnew file mode 100644index 000000000..38c6e0c16--- /dev/null+++ b/pipeline/src/import/cocos/assets.ts@@ -0,0 +1,82 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file What a Cocos project's `.meta` files say about its assets.+ *+ * A scene names its assets by uuid; the `.meta` beside each file is the+ * only place that says which file a uuid is, and a sprite frame is a+ * sub-asset (`<image uuid>@f9941`) of its image. This reads every meta+ * once into a lookup. Read-only.+ */+import { readdirSync, readFileSync } from 'node:fs';+import path from 'node:path';++export interface CocosAssetEntry {+ uuid: string;+ /** Absolute path of the asset file. */+ file: string;+ /** Path relative to the project's `assets` folder, forward slashes. */+ rel: string;+ importer: string;+ userData: Record<string, unknown>;+ /** Sub-assets by their full uuid (`<uuid>@<id>`). */+ subs: Map<string, { importer: string; userData: Record<string, unknown> }>;+}++export interface CocosAssetIndex {+ /** The project's `assets` folder. */+ root: string;+ /** Every asset and every sub-asset, by uuid. A sub-asset resolves to its parent file. */+ byUuid: Map<string, CocosAssetEntry>;+}++const SKIP = new Set(['node_modules', '.git']);++function* walk(dir: string): Generator<string> {+ let entries;+ try {+ entries = readdirSync(dir, { withFileTypes: true });+ } catch {+ return;+ }+ for (const e of entries) {+ if (e.isDirectory()) {+ if (!SKIP.has(e.name)) yield* walk(path.join(dir, e.name));+ } else if (e.name.endsWith('.meta')) {+ yield path.join(dir, e.name);+ }+ }+}++const asObj = (v: unknown): Record<string, unknown> => (typeof v === 'object' && v !== null && !Array.isArray(v) ? (v as Record<string, unknown>) : {});++export function buildCocosAssetIndex(root: string): CocosAssetIndex {+ const byUuid = new Map<string, CocosAssetEntry>();+ for (const metaFile of walk(root)) {+ let meta: Record<string, unknown>;+ try {+ meta = asObj(JSON.parse(readFileSync(metaFile, 'utf8')));+ } catch {+ continue;+ }+ const uuid = meta.uuid;+ if (typeof uuid !== 'string' || meta.importer === 'directory') continue;+ const file = metaFile.slice(0, -'.meta'.length);+ const entry: CocosAssetEntry = {+ uuid,+ file,+ rel: path.relative(root, file).split(path.sep).join('/'),+ importer: typeof meta.importer === 'string' ? meta.importer : '',+ userData: asObj(meta.userData),+ subs: new Map(),+ };+ for (const sub of Object.values(asObj(meta.subMetas))) {+ const s = asObj(sub);+ if (typeof s.uuid !== 'string') continue;+ entry.subs.set(s.uuid, { importer: typeof s.importer === 'string' ? s.importer : '', userData: asObj(s.userData) });+ byUuid.set(s.uuid, entry);+ }+ byUuid.set(uuid, entry);+ }+ return { root, byUuid };+}diff --git a/pipeline/src/import/cocos/components.ts b/pipeline/src/import/cocos/components.tsnew file mode 100644index 000000000..eaa7e3ce7--- /dev/null+++ b/pipeline/src/import/cocos/components.ts@@ -0,0 +1,297 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file Cocos components to Estella components, one node at a time.+ *+ * Only what has a faithful counterpart is mapped. Everything else is kept+ * verbatim under the entity's `metadata.cocos`, so a later stage (a script+ * shim, a Widget system) can read it and nothing is silently lost — and is+ * counted in the report as unmapped.+ *+ * UI note: a Cocos UI node is "anchor + content size + local position".+ * That is a world-space `Sprite`/`Text` with a pivot, not a flex box, so+ * UI maps there and `UITransform` is folded into it.+ */+import type { CocosAssetEntry, CocosAssetIndex } from './assets';+import type { CocosComponent, CocosNode } from './document';+import type { ImportReport } from './report';++export interface ComponentData {+ type: string;+ data: Record<string, unknown>;+}++export interface SliceBorder { left: number; right: number; top: number; bottom: number }++export interface ComponentContext {+ assets: CocosAssetIndex;+ report: ImportReport;+ /** The project-relative ref of a copied asset; records that it must be copied. */+ assetRef(entry: CocosAssetEntry, slice?: SliceBorder): string;+}++type Raw = Record<string, unknown>;+const isObj = (v: unknown): v is Raw => typeof v === 'object' && v !== null && !Array.isArray(v);+const num = (v: unknown, d: number): number => (typeof v === 'number' && Number.isFinite(v) ? v : d);++const color = (v: unknown, fallback = 1): Raw => {+ const c = isObj(v) ? v : {};+ return { r: num(c.r, 255) / 255, g: num(c.g, 255) / 255, b: num(c.b, 255) / 255, a: num(c.a, fallback * 255) / 255 };+};++const uuidOf = (v: unknown): string => (isObj(v) && typeof v.__uuid__ === 'string' ? v.__uuid__ : '');++/** The same value for `a` and `b`, structurally. Overrides are the fields where it is not. */+export function sameData(a: unknown, b: unknown): boolean {+ if (a === b) return true;+ if (typeof a !== typeof b || a === null || b === null || typeof a !== 'object') return false;+ if (Array.isArray(a) !== Array.isArray(b)) return false;+ const ka = Object.keys(a as Raw);+ const kb = Object.keys(b as Raw);+ if (ka.length !== kb.length) return false;+ return ka.every((k) => sameData((a as Raw)[k], (b as Raw)[k]));+}++function transform(node: CocosNode): ComponentData {+ return {+ type: 'Transform',+ data: { position: { ...node.pos }, rotation: { ...node.rot }, scale: { ...node.scale } },+ };+}++interface UiBox { width: number; height: number; ax: number; ay: number }++function uiBox(node: CocosNode): UiBox | null {+ const t = node.components.find((c) => c.type === 'cc.UITransform');+ if (!t) return null;+ const s = isObj(t.data._contentSize) ? t.data._contentSize : {};+ const a = isObj(t.data._anchorPoint) ? t.data._anchorPoint : {};+ return { width: num(s.width, 100), height: num(s.height, 100), ax: num(a.x, 0.5), ay: num(a.y, 0.5) };+}++function sprite(c: CocosComponent, box: UiBox | null, ctx: ComponentContext, where: string): ComponentData | null {+ const frameUuid = uuidOf(c.data._spriteFrame);+ const data: Raw = { color: color(c.data._color), enabled: c.enabled };+ if (box) {+ data.size = { x: box.width, y: box.height };+ data.pivot = { x: box.ax, y: box.ay };+ }+ if (!frameUuid) {+ ctx.report.component('cc.Sprite', 'partial');+ ctx.report.note('sprite-no-frame', where);+ return { type: 'Sprite', data };+ }+ const entry = ctx.assets.byUuid.get(frameUuid);+ const sub = entry?.subs.get(frameUuid);+ if (!entry || !sub || entry.importer !== 'image' || sub.importer !== 'sprite-frame') {+ ctx.report.component('cc.Sprite', 'unmapped');+ ctx.report.note(entry ? 'sprite-frame-not-from-image' : 'sprite-frame-missing', where);+ if (!entry) ctx.report.missingAsset(frameUuid);+ return null;+ }++ const ud = sub.userData;+ const kind = num(c.data._type, 0);+ let status: 'mapped' | 'partial' = 'mapped';++ const border: SliceBorder = {+ left: num(ud.borderLeft, 0),+ right: num(ud.borderRight, 0),+ top: num(ud.borderTop, 0),+ bottom: num(ud.borderBottom, 0),+ };+ const hasBorder = border.left + border.right + border.top + border.bottom > 0;+ if (kind === 1 && hasBorder) {+ data.drawMode = 'NineSlice';+ data.texture = ctx.assetRef(entry, border);+ } else {+ data.texture = ctx.assetRef(entry);+ if (kind === 2) {+ data.drawMode = 'Tiled';+ } else if (kind === 3) {+ status = 'partial';+ ctx.report.note('sprite-filled-as-simple', where);+ }+ }++ const rawW = num(ud.rawWidth, 0);+ const rawH = num(ud.rawHeight, 0);+ const w = num(ud.width, rawW);+ const h = num(ud.height, rawH);+ const x = num(ud.trimX, 0);+ const y = num(ud.trimY, 0);+ if (rawW > 0 && rawH > 0 && (w !== rawW || h !== rawH || x !== 0 || y !== 0)) {+ data.uvOffset = { x: x / rawW, y: 1 - (y + h) / rawH };+ data.uvScale = { x: w / rawW, y: h / rawH };+ status = 'partial';+ ctx.report.note('sprite-trimmed-frame', where);+ }+ if (ud.rotated === true) {+ status = 'partial';+ ctx.report.note('sprite-rotated-frame', where);+ }+ if (c.data._useGrayscale === true) {+ status = 'partial';+ ctx.report.note('sprite-grayscale', where);+ }+ ctx.report.component('cc.Sprite', status);+ return { type: 'Sprite', data };+}++function label(c: CocosComponent, siblings: CocosComponent[], ctx: ComponentContext, where: string): ComponentData {+ const d = c.data;+ const fontSize = num(d._fontSize, 40);+ const lineHeight = num(d._lineHeight, fontSize);+ const overflow = num(d._overflow, 0);+ let status: 'mapped' | 'partial' = 'mapped';+ const data: Raw = {+ content: typeof d._string === 'string' ? d._string : '',+ fontSize,+ color: color(d._color),+ align: (['Left', 'Center', 'Right'] as const)[num(d._horizontalAlign, 0)] ?? 'Left',+ verticalAlign: (['Top', 'Middle', 'Bottom'] as const)[num(d._verticalAlign, 0)] ?? 'Top',+ wordWrap: d._enableWrapText !== false,+ overflow: overflow === 1 ? 'Clip' : 'Visible',+ lineHeight: fontSize > 0 ? Math.round((lineHeight / fontSize) * 1000) / 1000 : 1.2,+ bold: d._isBold === true,+ italic: d._isItalic === true,+ enabled: c.enabled,+ };+ if (overflow === 2 || overflow === 3) {+ status = 'partial';+ ctx.report.note(overflow === 2 ? 'label-shrink-overflow' : 'label-resize-height', where);+ }++ const fontUuid = uuidOf(d._font);+ if (d._isSystemFontUsed === false && fontUuid) {+ const font = ctx.assets.byUuid.get(fontUuid);+ if (font?.importer === 'ttf-font') {+ data.font = ctx.assetRef(font);+ } else if (font?.importer === 'bitmap-font') {+ // The engine takes a .fnt in Text.font. How its glyph scale reads `fontSize` is still to be checked on screen.+ data.font = ctx.assetRef(font);+ status = 'partial';+ ctx.report.note('label-bitmap-font', where);+ } else {+ status = 'partial';+ ctx.report.note(font ? 'label-font-unsupported' : 'label-font-missing', where);+ if (!font) ctx.report.missingAsset(fontUuid);+ }+ } else if (typeof d._fontFamily === 'string') {+ data.fontFamily = d._fontFamily;+ }+ if (d._isUnderline === true) {+ status = 'partial';+ ctx.report.note('label-underline', where);+ }++ const outline = siblings.find((s) => s.type === 'cc.LabelOutline' && s.enabled);+ if (outline) {+ data.strokeColor = color(outline.data._color);+ data.strokeWidth = num(outline.data._width, 0);+ }+ const shadow = siblings.find((s) => s.type === 'cc.LabelShadow' && s.enabled);+ if (shadow) {+ const off = isObj(shadow.data._offset) ? shadow.data._offset : {};+ data.shadowColor = color(shadow.data._color);+ data.shadowBlur = num(shadow.data._blur, 0);+ data.shadowOffsetX = num(off.x, 2);+ data.shadowOffsetY = -num(off.y, -2);+ }+ ctx.report.component('cc.Label', status);+ return { type: 'Text', data };+}++function richText(c: CocosComponent, ctx: ComponentContext): ComponentData {+ const d = c.data;+ ctx.report.component('cc.RichText', 'partial');+ return {+ type: 'Text',+ data: {+ content: typeof d._string === 'string' ? d._string : '',+ fontSize: num(d._fontSize, 40),+ color: color(d._fontColor),+ richText: true,+ wordWrap: num(d._maxWidth, 0) > 0,+ align: (['Left', 'Center', 'Right'] as const)[num(d._horizontalAlign, 0)] ?? 'Left',+ enabled: c.enabled,+ },+ };+}++function camera(c: CocosComponent, ctx: ComponentContext): ComponentData {+ const d = c.data;+ ctx.report.component('cc.Camera', 'mapped');+ return {+ type: 'Camera',+ data: {+ projectionType: num(d._projection, 0) === 0 ? 'Orthographic' : 'Perspective',+ fov: num(d._fov, 45),+ orthoSize: num(d._orthoHeight, 10),+ nearPlane: num(d._near, 1),+ farPlane: num(d._far, 1000),+ priority: num(d._priority, 0),+ cullingMask: num(d._visibility, 0xffffffff) >>> 0,+ isActive: c.enabled,+ },+ };+}++/** Components that are folded into another, or carry nothing of their own. */+const FOLDED = new Set(['cc.UITransform', 'cc.LabelOutline', 'cc.LabelShadow']);++export interface ConvertedNode {+ components: ComponentData[];+ /** Everything not mapped, verbatim, for whatever consumes it next. */+ metadata?: Raw;+}++export function convertNode(node: CocosNode, ctx: ComponentContext, where: string): ConvertedNode {+ const components: ComponentData[] = [transform(node)];+ const box = uiBox(node);+ const unmapped: Raw[] = [];++ for (const c of node.components) {+ let out: ComponentData | null = null;+ switch (c.type) {+ case 'cc.Sprite':+ out = sprite(c, box, ctx, where);+ break;+ case 'cc.Label':+ out = label(c, node.components, ctx, where);+ break;+ case 'cc.RichText':+ out = richText(c, ctx);+ break;+ case 'cc.Camera':+ out = camera(c, ctx);+ break;+ default:+ break;+ }+ if (out) {+ components.push(out);+ continue;+ }+ if (FOLDED.has(c.type)) {+ const host = c.type === 'cc.UITransform' ? true : node.components.some((s) => s.type === 'cc.Label');+ if (host) {+ ctx.report.component(c.type, 'mapped');+ continue;+ }+ }+ if (c.type === 'cc.Sprite') {+ // the sprite counted itself unmapped; keep what it said+ } else {+ ctx.report.component(c.type, 'unmapped');+ }+ unmapped.push({ type: c.type, enabled: c.enabled, data: c.data });+ }++ const cocos: Raw = {};+ if (unmapped.length) cocos.components = unmapped;+ if (box) cocos.ui = { width: box.width, height: box.height, anchorX: box.ax, anchorY: box.ay };+ if (node.layer !== 33554432 && node.layer !== 0) cocos.layer = node.layer;+ const metadata = Object.keys(cocos).length ? { cocos } : undefined;+ return metadata ? { components, metadata } : { components };+}diff --git a/pipeline/src/import/cocos/convert.ts b/pipeline/src/import/cocos/convert.tsnew file mode 100644index 000000000..09651bc32--- /dev/null+++ b/pipeline/src/import/cocos/convert.ts@@ -0,0 +1,369 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file A Cocos prefab or scene as an Estella prefab or scene.+ *+ * A nested prefab stays a nested prefab: the instance becomes a slot that+ * names the converted prefab, and what the Cocos instance changed becomes+ * overrides. Those are not translated property by property — the instance's+ * overrides are applied to the Cocos tree, both versions are converted, and+ * the difference is the override list. So the override vocabulary is+ * whatever the component mapping already knows, with no second table.+ *+ * Addresses follow the engine's own: an entity inside a nested prefab is+ * `slot/localId`, a prefab's own entities are bare ids.+ */+import { convertNode, sameData, type ComponentContext, type ComponentData } from './components';+import type { CocosDocument, CocosNode, CocosOverride } from './document';+import { ImportReport } from './report';++const SEP = '/';++type Raw = Record<string, unknown>;++export interface PrefabOverride {+ prefabEntityId: string;+ type: 'property' | 'component_added' | 'component_removed' | 'name' | 'visibility';+ componentType?: string;+ propertyName?: string;+ value?: unknown;+ componentData?: ComponentData;+}++export interface PrefabEntity {+ prefabEntityId: string;+ name: string;+ parent: string | null;+ children: string[];+ components: ComponentData[];+ visible: boolean;+ metadata?: Raw;+ nestedPrefab?: { prefabPath: string; overrides: PrefabOverride[] };+}++export interface PrefabFile {+ version: string;+ name: string;+ rootEntityId: string;+ entities: PrefabEntity[];+}++export interface SceneEntity {+ id: number;+ name: string;+ parent: number | null;+ children: number[];+ components: ComponentData[];+ visible: boolean;+ metadata?: Raw;+}++export interface SceneInstanceEntry {+ id: number;+ parent: number | null;+ prefab: string;+ overrides: PrefabOverride[];+ added: never[];+ removed: string[];+}++export interface SceneFile {+ version: number;+ name: string;+ entities: (SceneEntity | SceneInstanceEntry)[];+}++export interface ConvertContext extends ComponentContext {+ /** The parsed prefab a uuid names, or null when the project does not have it. */+ loadPrefab(uuid: string): CocosDocument | null;+ /** The project-relative path the converted prefab of a uuid is written to. */+ prefabRef(uuid: string): string | null;+ /** Where the document being converted lives, for notes. */+ where: string;+}++// ---------------------------------------------------------------------------+// The expanded Cocos tree: instances inlined, overrides applied.+// ---------------------------------------------------------------------------++interface XNode {+ /** Engine address: bare id in a prefab's own space, `slot/id` across a nesting boundary. */+ addr: string;+ /** Prefix the engine address adds to this node's components' ids. */+ prefix: string;+ node: CocosNode;+ children: XNode[];+}++const MAX_DEPTH = 24;++function build(node: CocosNode, ctx: ConvertContext, stack: string[]): XNode {+ if (node.instance) {+ const sub = expandAsset(node.instance.asset, ctx, stack);+ if (!sub) {+ ctx.report.note('prefab-missing', `${ctx.where}: ${node.name}`);+ ctx.report.missingAsset(node.instance.asset);+ return { addr: node.id, prefix: '', node: { ...node, children: [] }, children: [] };+ }+ applyOverrides(sub, node.instance.overrides, ctx);+ if (node.instance.mountedChildren) ctx.report.note('instance-mounted-children', `${ctx.where}: ${node.name}`);+ if (node.instance.mountedComponents) ctx.report.note('instance-mounted-components', `${ctx.where}: ${node.name}`);+ if (node.instance.removedComponents) ctx.report.note('instance-removed-components', `${ctx.where}: ${node.name}`);+ return lift(sub, node.id);+ }+ return { addr: node.id, prefix: '', node: { ...node, children: [] }, children: node.children.map((c) => build(c, ctx, stack)) };+}++/** Put a tree under a slot: every address gains the slot's prefix. */+function lift(tree: XNode, slot: string): XNode {+ const walk = (x: XNode): XNode => ({+ addr: `${slot}${SEP}${x.addr}`,+ prefix: x.prefix ? `${slot}${SEP}${x.prefix}` : slot,+ node: x.node,+ children: x.children.map(walk),+ });+ return walk(tree);+}++const expanded = new WeakMap<ConvertContext, Map<string, XNode | null>>();++/** A prefab with its own instances expanded, in its own address space. Cached; callers get a copy. */+function expandAsset(uuid: string, ctx: ConvertContext, stack: string[]): XNode | null {+ let cache = expanded.get(ctx);+ if (!cache) expanded.set(ctx, (cache = new Map()));+ const hit = cache.get(uuid);+ if (hit !== undefined) return hit ? structuredClone(hit) : null;+ if (stack.includes(uuid) || stack.length > MAX_DEPTH) {+ ctx.report.note('prefab-cycle', `${ctx.where}: ${uuid}`);+ return null;+ }+ const doc = ctx.loadPrefab(uuid);+ const root = doc?.roots[0];+ if (!doc || !root) {+ cache.set(uuid, null);+ return null;+ }+ const tree = build(root, ctx, [...stack, uuid]);+ cache.set(uuid, tree);+ return structuredClone(tree);+}++// ---------------------------------------------------------------------------+// Overrides, in the Cocos domain.+// ---------------------------------------------------------------------------++/** A Cocos value without its `__type__` tags, which name the class and mean nothing to the data. */+function clean(v: unknown): unknown {+ if (Array.isArray(v)) return v.map(clean);+ if (typeof v !== 'object' || v === null) return v;+ return Object.fromEntries(Object.entries(v).filter(([k]) => k !== '__type__').map(([k, x]) => [k, clean(x)]));+}++function applyOverrides(tree: XNode, overrides: CocosOverride[], ctx: ConvertContext): void {+ const nodes = new Map<string, XNode>();+ const comps = new Map<string, { c: CocosNode["components"][number] }>();+ const index = (x: XNode): void => {+ nodes.set(x.addr, x);+ for (const c of x.node.components) comps.set(x.prefix ? `${x.prefix}${SEP}${c.id}` : c.id, { c });+ x.children.forEach(index);+ };+ index(tree);++ for (const raw of overrides) {+ const o = { ...raw, value: clean(raw.value) };+ const key = o.target.join(SEP);+ const prop = o.path[0];+ const nodeHit = nodes.get(key);+ const compHit = comps.get(key);+ if (compHit && prop !== undefined) {+ // The tree came from a clone, so its nodes are this call's to change.+ const { c } = compHit;+ if (prop === '_enabled') {+ c.enabled = o.value !== false;+ continue;+ }+ setPath(c.data, o.path, o.value);+ continue;+ }+ if (nodeHit && prop !== undefined) {+ const n = nodeHit.node;+ const v = o.value as Raw;+ if (typeof v === 'object' && v !== null && '__id__' in v) {+ ctx.report.note('override-object-reference', `${ctx.where}: ${key}.${prop}`);+ continue;+ }+ switch (prop) {+ case '_name': n.name = String(o.value); break;+ case '_active': n.active = o.value !== false; break;+ case '_lpos': n.pos = { ...n.pos, ...(v as object) }; break;+ case '_lrot': n.rot = { ...n.rot, ...(v as object) }; break;+ case '_lscale': n.scale = { ...n.scale, ...(v as object) }; break;+ case '_layer': n.layer = Number(o.value); break;+ case '_euler': break; // derived from the rotation+ default: ctx.report.note('override-node-property', `${ctx.where}: ${prop}`);+ }+ continue;+ }+ ctx.report.note(o.target.length > 1 ? 'override-target-missing-nested' : 'override-target-missing', `${ctx.where}: ${key}`);+ }+}++function setPath(target: Raw, path: string[], value: unknown): void {+ let cur = target;+ for (let i = 0; i < path.length - 1; i++) {+ const k = path[i]!;+ const next = cur[k];+ cur[k] = typeof next === 'object' && next !== null ? { ...(next as Raw) } : {};+ cur = cur[k] as Raw;+ }+ cur[path[path.length - 1]!] = value;+}++// ---------------------------------------------------------------------------+// Converting an expanded tree, and the difference between two.+// ---------------------------------------------------------------------------++interface Flat {+ name: string;+ visible: boolean;+ components: ComponentData[];+}++function flatten(tree: XNode, ctx: ConvertContext): Map<string, Flat> {+ const out = new Map<string, Flat>();+ const walk = (x: XNode): void => {+ const conv = convertNode(x.node, ctx, `${ctx.where}: ${x.node.name}`);+ out.set(x.addr, { name: x.node.name, visible: x.node.active, components: conv.components });+ x.children.forEach(walk);+ };+ walk(tree);+ return out;+}++/** What turns `pristine` into `patched`, as the engine's override list. */+function diff(pristine: Map<string, Flat>, patched: Map<string, Flat>, ctx: ConvertContext): PrefabOverride[] {+ const out: PrefabOverride[] = [];+ for (const [addr, now] of patched) {+ const was = pristine.get(addr);+ if (!was) {+ ctx.report.note('instance-added-entity', `${ctx.where}: ${addr}`);+ continue;+ }+ if (was.name !== now.name) out.push({ prefabEntityId: addr, type: 'name', value: now.name });+ if (was.visible !== now.visible) out.push({ prefabEntityId: addr, type: 'visibility', value: now.visible });+ const before = new Map(was.components.map((c) => [c.type, c]));+ const after = new Map(now.components.map((c) => [c.type, c]));+ for (const [type, c] of after) {+ const b = before.get(type);+ if (!b) {+ out.push({ prefabEntityId: addr, type: 'component_added', componentType: type, componentData: c });+ continue;+ }+ for (const [field, value] of Object.entries(c.data)) {+ if (!sameData(b.data[field], value)) {+ out.push({ prefabEntityId: addr, type: 'property', componentType: type, propertyName: field, value });+ }+ }+ }+ for (const type of before.keys()) {+ if (!after.has(type)) out.push({ prefabEntityId: addr, type: 'component_removed', componentType: type });+ }+ }+ return out;+}++/** The overrides an instance node applies over the prefab it names, or null when that prefab is missing. */+function instanceOverrides(node: CocosNode, ctx: ConvertContext): PrefabOverride[] | null {+ const inst = node.instance;+ if (!inst) return null;+ const pristine = expandAsset(inst.asset, ctx, []);+ if (!pristine) return null;+ const patched = structuredClone(pristine);+ applyOverrides(patched, inst.overrides, ctx);+ if (inst.mountedChildren) ctx.report.note('instance-mounted-children', `${ctx.where}: ${node.name}`);+ if (inst.mountedComponents) ctx.report.note('instance-mounted-components', `${ctx.where}: ${node.name}`);+ if (inst.removedComponents) ctx.report.note('instance-removed-components', `${ctx.where}: ${node.name}`);+ // Converting both sides is for the difference only; the report counts a component where its own prefab is converted.+ const quiet: ConvertContext = { ...ctx, report: new ImportReport() };+ return diff(flatten(pristine, quiet), flatten(patched, quiet), ctx);+}++// ---------------------------------------------------------------------------+// Documents.+// ---------------------------------------------------------------------------++export function convertPrefab(doc: CocosDocument, ctx: ConvertContext): PrefabFile {+ const root = doc.roots[0];+ if (!root) throw new Error('prefab has no root node');+ const entities: PrefabEntity[] = [];+ ctx.report.documents.converted++;+ if (doc.duplicateIds) ctx.report.note('duplicate-fileid', `${ctx.where}: ${doc.duplicateIds}`);++ const walk = (n: CocosNode, parent: string | null): void => {+ ctx.report.nodes++;+ const here = `${ctx.where}: ${n.name}`;+ const entity: PrefabEntity = { prefabEntityId: n.id, name: n.name, parent, children: [], components: [], visible: n.active };+ entities.push(entity);+ const ref = n.instance ? ctx.prefabRef(n.instance.asset) : null;+ const overrides = n.instance && ref ? instanceOverrides(n, ctx) : null;+ if (n.instance) {+ ctx.report.prefabInstances++;+ if (ref && overrides) entity.nestedPrefab = { prefabPath: ref, overrides };+ else {+ ctx.report.note('prefab-missing', here);+ ctx.report.missingAsset(n.instance.asset);+ }+ return;+ }+ const conv = convertNode(n, ctx, here);+ entity.components = conv.components;+ if (conv.metadata) entity.metadata = conv.metadata;+ for (const c of n.children) {+ entity.children.push(c.id);+ walk(c, n.id);+ }+ };+ walk(root, null);+ return { version: '2', name: doc.name, rootEntityId: root.id, entities };+}++export function convertScene(doc: CocosDocument, ctx: ConvertContext): SceneFile {+ const entities: (SceneEntity | SceneInstanceEntry)[] = [];+ ctx.report.documents.converted++;+ let next = 0;+ if (doc.globals.length) ctx.report.note('scene-globals-dropped', `${ctx.where}: ${doc.globals.join(',')}`);++ const walk = (n: CocosNode, parent: SceneEntity | null): void => {+ ctx.report.nodes++;+ const id = next++;+ const here = `${ctx.where}: ${n.name}`;+ if (n.instance) {+ ctx.report.prefabInstances++;+ const ref = ctx.prefabRef(n.instance.asset);+ const overrides = ref ? instanceOverrides(n, ctx) : null;+ if (ref && overrides) {+ // Same shape the engine writes: the entry carries its parent, the parent lists the entry.+ entities.push({ id, parent: parent ? parent.id : null, prefab: ref, overrides, added: [], removed: [] });+ parent?.children.push(id);+ return;+ }+ ctx.report.note('prefab-missing', here);+ ctx.report.missingAsset(n.instance.asset);+ }+ const conv = n.instance ? { components: [] as ComponentData[] } : convertNode(n, ctx, here);+ const entity: SceneEntity = {+ id,+ name: n.name,+ parent: parent ? parent.id : null,+ children: [],+ components: conv.components,+ visible: n.active,+ };+ if ('metadata' in conv && conv.metadata) entity.metadata = conv.metadata;+ entities.push(entity);+ parent?.children.push(id);+ if (!n.instance) for (const c of n.children) walk(c, entity);+ };+ for (const r of doc.roots) walk(r, null);+ return { version: 4, name: doc.name, entities };+}diff --git a/pipeline/src/import/cocos/document.ts b/pipeline/src/import/cocos/document.tsnew file mode 100644index 000000000..829f6b5a5--- /dev/null+++ b/pipeline/src/import/cocos/document.ts@@ -0,0 +1,199 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file A Cocos Creator 3.x `.scene` / `.prefab` file read as a tree.+ *+ * The file is a flat array whose objects point at each other by index+ * (`{__id__: n}`) and at assets by uuid (`{__uuid__}`). Nothing downstream+ * wants that shape, so it is resolved once here into nodes with their+ * components, and a prefab instance — a node whose children live in+ * another file — is kept as a reference plus the overrides it applies.+ *+ * Read-only: nothing here touches the project it reads.+ */++export interface CocosVec3 { x: number; y: number; z: number }+export interface CocosQuat { x: number; y: number; z: number; w: number }++/** One `propertyOverrides` entry of a prefab instance. */+export interface CocosOverride {+ /** `localID` of the target: the instance nodes crossed, then the node or component. */+ target: string[];+ /** Property path on the target (`['_lpos']`, `['_color']`). */+ path: string[];+ value: unknown;+}++export interface CocosComponent {+ /** `cc.Sprite`, or a script's compressed class id. */+ type: string;+ /** Stable id inside its file (the `CompPrefabInfo` fileId). */+ id: string;+ enabled: boolean;+ /** The serialised fields, without the bookkeeping that points back at the node. */+ data: Record<string, unknown>;+}++export interface CocosInstanceRef {+ /** uuid of the prefab this node stands for. */+ asset: string;+ overrides: CocosOverride[];+ /** Things an instance can carry that this reader does not carry across yet. */+ mountedChildren: number;+ mountedComponents: number;+ removedComponents: number;+}++export interface CocosNode {+ /** Stable id inside its file: the `PrefabInstance` fileId for an instance, else the `PrefabInfo` fileId, else the node's `_id`. */+ id: string;+ name: string;+ active: boolean;+ pos: CocosVec3;+ rot: CocosQuat;+ scale: CocosVec3;+ layer: number;+ components: CocosComponent[];+ children: CocosNode[];+ instance?: CocosInstanceRef;+}++export interface CocosDocument {+ kind: 'prefab' | 'scene';+ name: string;+ roots: CocosNode[];+ /** Scene-level settings (skybox, fog, shadows...) that were present and are not carried over. */+ globals: string[];+ /** Node ids that had to be made unique because the file repeats them. */+ duplicateIds: number;+}++type Raw = Record<string, unknown>;++const BOOKKEEPING = new Set(['__type__', '_name', '_objFlags', 'node', '__prefab', '_id', '__editorExtras__']);++const isObj = (v: unknown): v is Raw => typeof v === 'object' && v !== null && !Array.isArray(v);+const num = (v: unknown, d: number): number => (typeof v === 'number' && Number.isFinite(v) ? v : d);++function vec3(v: unknown, d: CocosVec3): CocosVec3 {+ return isObj(v) ? { x: num(v.x, d.x), y: num(v.y, d.y), z: num(v.z, d.z) } : { ...d };+}++function quat(v: unknown): CocosQuat {+ return isObj(v) ? { x: num(v.x, 0), y: num(v.y, 0), z: num(v.z, 0), w: num(v.w, 1) } : { x: 0, y: 0, z: 0, w: 1 };+}++/** A fileId is base64, so it can hold `/`; the engine reads `/` as the step into a nested prefab, so it cannot stay. */+const safeId = (id: string): string => id.replaceAll('/', '|');++export function parseCocosDocument(file: unknown, fallbackName = ''): CocosDocument {+ if (!Array.isArray(file) || file.length === 0) throw new Error('not a Cocos scene/prefab: expected a non-empty array');+ const objs = file as unknown[];+ const at = (ref: unknown): Raw | null => {+ if (!isObj(ref) || typeof ref.__id__ !== 'number') return null;+ const o = objs[ref.__id__];+ return isObj(o) ? o : null;+ };+ const indexOf = (ref: unknown): number => (isObj(ref) && typeof ref.__id__ === 'number' ? ref.__id__ : -1);++ const head = isObj(objs[0]) ? objs[0] : null;+ const globals: string[] = [];+ let rootRefs: unknown[];+ let kind: CocosDocument['kind'];+ let name = fallbackName;+ if (head?.__type__ === 'cc.Prefab') {+ kind = 'prefab';+ name = typeof head._name === 'string' && head._name ? head._name : name;+ rootRefs = [head.data];+ } else if (head?.__type__ === 'cc.SceneAsset') {+ kind = 'scene';+ const scene = at(head.scene);+ if (!scene) throw new Error('scene asset has no scene');+ name = typeof scene._name === 'string' && scene._name ? scene._name : name;+ rootRefs = Array.isArray(scene._children) ? scene._children : [];+ const g = at(scene._globals);+ if (g) for (const k of ['ambient', 'shadows', 'skybox', 'fog', 'octree', 'lightProbeInfo']) if (g[k]) globals.push(k);+ } else {+ throw new Error(`not a Cocos scene/prefab: first object is ${String(head?.__type__)}`);+ }++ const seen = new Set<number>();+ const usedIds = new Map<string, number>();+ let duplicateIds = 0;+ // Copy-pasted instances can carry the same fileId; the engine needs every entity in a prefab to have its own.+ const unique = (id: string): string => {+ const n = usedIds.get(id) ?? 0;+ usedIds.set(id, n + 1);+ if (n === 0) return id;+ duplicateIds++;+ return `${id}~${n + 1}`;+ };+ const readNode = (ref: unknown): CocosNode | null => {+ const idx = indexOf(ref);+ const n = at(ref);+ if (!n || n.__type__ !== 'cc.Node' || seen.has(idx)) return null;+ seen.add(idx);+ const info = at(n._prefab);+ const instRaw = info ? at(info.instance) : null;+ // An instance node's PrefabInfo.fileId is the nested prefab's own root id, so two instances of one prefab share it;+ // the instance's identity inside this file — and the first step of any override path crossing it — is the PrefabInstance's.+ const id = unique(safeId((instRaw && typeof instRaw.fileId === 'string' && instRaw.fileId)+ || (info && typeof info.fileId === 'string' && info.fileId)+ || (typeof n._id === 'string' && n._id)+ || `#${idx}`));++ const node: CocosNode = {+ id,+ name: typeof n._name === 'string' ? n._name : '',+ active: n._active !== false,+ pos: vec3(n._lpos, { x: 0, y: 0, z: 0 }),+ rot: quat(n._lrot),+ scale: vec3(n._lscale, { x: 1, y: 1, z: 1 }),+ layer: num(n._layer, 0),+ components: [],+ children: [],+ };++ for (const cref of Array.isArray(n._components) ? n._components : []) {+ const c = at(cref);+ if (!c || typeof c.__type__ !== 'string') continue;+ const cinfo = at(c.__prefab);+ const cid = safeId((cinfo && typeof cinfo.fileId === 'string' && cinfo.fileId) || (typeof c._id === 'string' && c._id) || `#${indexOf(cref)}`);+ const data: Record<string, unknown> = {};+ for (const [k, v] of Object.entries(c)) if (!BOOKKEEPING.has(k)) data[k] = v;+ node.components.push({ type: c.__type__, id: cid, enabled: c._enabled !== false, data });+ }++ if (instRaw && info) {+ const asset = isObj(info.asset) && typeof info.asset.__uuid__ === 'string' ? info.asset.__uuid__ : '';+ const overrides: CocosOverride[] = [];+ for (const oref of Array.isArray(instRaw.propertyOverrides) ? instRaw.propertyOverrides : []) {+ const o = at(oref);+ const t = o ? at(o.targetInfo) : null;+ if (!o || !t || !Array.isArray(t.localID) || !Array.isArray(o.propertyPath)) continue;+ overrides.push({ target: t.localID.map((x) => safeId(String(x))), path: o.propertyPath.map(String), value: o.value });+ }+ const count = (v: unknown): number => (Array.isArray(v) ? v.length : 0);+ node.instance = {+ asset,+ overrides,+ mountedChildren: count(instRaw.mountedChildren),+ mountedComponents: count(instRaw.mountedComponents),+ removedComponents: count(instRaw.removedComponents),+ };+ }++ for (const cr of Array.isArray(n._children) ? n._children : []) {+ const child = readNode(cr);+ if (child) node.children.push(child);+ }+ return node;+ };++ const roots: CocosNode[] = [];+ for (const r of rootRefs) {+ const n = readNode(r);+ if (n) roots.push(n);+ }+ return { kind, name, roots, globals, duplicateIds };+}diff --git a/pipeline/src/import/cocos/importProject.ts b/pipeline/src/import/cocos/importProject.tsnew file mode 100644index 000000000..4a6b4c3b9--- /dev/null+++ b/pipeline/src/import/cocos/importProject.ts@@ -0,0 +1,185 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file Take a Cocos Creator 3.x project into an Estella project, without+ * touching it.+ *+ * The source is only ever read. Output goes under `<out>/assets/cocos/`,+ * keeping the source's folder layout so a path in one is findable in the+ * other. Only what the converted documents reference is copied.+ */+import { copyFileSync, existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from 'node:fs';+import path from 'node:path';+import { buildCocosAssetIndex, type CocosAssetEntry } from './assets';+import type { SliceBorder } from './components';+import { convertPrefab, convertScene, type ConvertContext } from './convert';+import { parseCocosDocument, type CocosDocument } from './document';+import { ImportReport, type ImportReportData } from './report';++export interface CocosImportOptions {+ /** The Cocos project folder (the one holding `assets/` and `settings/`). */+ source: string;+ /** The Estella project folder to write into. */+ out: string;+ /** Convert only documents whose path under `assets/` starts with one of these; prefabs they use follow. */+ only?: string[];+ /** Parse and convert but write nothing. */+ dryRun?: boolean;+ /** Folder under the project's `assets/` that receives everything. */+ into?: string;+}++const norm = (p: string): string => p.split(path.sep).join('/');++function* walk(dir: string): Generator<string> {+ let entries;+ try {+ entries = readdirSync(dir, { withFileTypes: true });+ } catch {+ return;+ }+ for (const e of entries) {+ if (e.isDirectory()) yield* walk(path.join(dir, e.name));+ else yield path.join(dir, e.name);+ }+}++function writeOut(file: string, text: string): void {+ mkdirSync(path.dirname(file), { recursive: true });+ writeFileSync(file, text);+}++/** A bitmap font is a .fnt that names its glyph pages; they sit beside it and must travel with it. */+function copyFontPages(fnt: string, dest: string): void {+ const text = readFileSync(fnt, 'utf8');+ for (const m of text.matchAll(/file="([^"]+)"/g)) {+ const page = path.join(path.dirname(fnt), m[1]!);+ if (existsSync(page)) copyFileSync(page, path.join(path.dirname(dest), m[1]!));+ }+}++export function importCocosProject(opts: CocosImportOptions): ImportReportData {+ const source = path.resolve(opts.source);+ const out = path.resolve(opts.out);+ const rel = path.relative(source, out);+ if (rel === '' || (!rel.startsWith('..') && !path.isAbsolute(rel))) {+ throw new Error('the output project must not be inside the Cocos project: the source is never written to');+ }+ const assetsDir = path.join(source, 'assets');+ if (!existsSync(assetsDir)) throw new Error(`no assets folder in ${source}: is this a Cocos Creator project?`);+ const into = opts.into ?? 'cocos';++ const report = new ImportReport();+ const index = buildCocosAssetIndex(assetsDir);++ const outRef = (assetRel: string): string => `assets/${into}/${assetRel}`;+ const esRel = (assetRel: string, ext: string): string => assetRel.replace(/\.[^./]+$/, ext);++ const textures = new Map<string, { entry: CocosAssetEntry; slice?: SliceBorder }>();+ const docs = new Map<string, CocosDocument | null>();+ const pending: string[] = [];+ const queued = new Set<string>();++ const prefabEntry = (uuid: string): CocosAssetEntry | null => {+ const e = index.byUuid.get(uuid);+ return e && e.rel.endsWith('.prefab') ? e : null;+ };+ const loadDoc = (e: CocosAssetEntry): CocosDocument | null => {+ if (docs.has(e.file)) return docs.get(e.file) ?? null;+ let doc: CocosDocument | null = null;+ try {+ doc = parseCocosDocument(JSON.parse(readFileSync(e.file, 'utf8')), path.basename(e.rel).replace(/\.[^.]+$/, ''));+ } catch (err) {+ report.documents.failed.push({ file: e.rel, error: (err as Error).message });+ }+ docs.set(e.file, doc);+ return doc;+ };++ const ctx: ConvertContext = {+ assets: index,+ report,+ where: '',+ assetRef(entry, slice) {+ const merged = slice ?? textures.get(entry.file)?.slice;+ textures.set(entry.file, merged ? { entry, slice: merged } : { entry });+ return outRef(entry.rel);+ },+ loadPrefab(uuid) {+ const e = prefabEntry(uuid);+ return e ? loadDoc(e) : null;+ },+ prefabRef(uuid) {+ const e = prefabEntry(uuid);+ if (!e) return null;+ if (!queued.has(e.rel)) {+ queued.add(e.rel);+ pending.push(e.rel);+ }+ return outRef(esRel(e.rel, '.esprefab'));+ },+ };++ const wanted = (relPath: string): boolean => !opts.only?.length || opts.only.some((p) => relPath.startsWith(p));+ const scenes: string[] = [];+ for (const f of walk(assetsDir)) {+ const r = norm(path.relative(assetsDir, f));+ if (!wanted(r)) continue;+ if (r.endsWith('.scene')) scenes.push(r);+ else if (r.endsWith('.prefab') && !queued.has(r)) {+ queued.add(r);+ pending.push(r);+ }+ }++ const write = (relPath: string, json: unknown): void => {+ if (!opts.dryRun) writeOut(path.join(out, relPath), `${JSON.stringify(json, null, 2)}\n`);+ };++ const byRel = new Map<string, CocosAssetEntry>();+ for (const e of index.byUuid.values()) byRel.set(e.rel, e);++ for (let i = 0; i < pending.length; i++) {+ const r = pending[i]!;+ const e = byRel.get(r);+ const doc = e ? loadDoc(e) : null;+ if (!e || !doc) continue;+ ctx.where = r;+ try {+ write(outRef(esRel(r, '.esprefab')), convertPrefab(doc, ctx));+ } catch (err) {+ report.documents.failed.push({ file: r, error: (err as Error).message });+ }+ }+ for (const r of scenes) {+ const e = byRel.get(r);+ const doc = e ? loadDoc(e) : null;+ if (!e || !doc) continue;+ ctx.where = r;+ try {+ write(outRef(esRel(r, '.esscene')), convertScene(doc, ctx));+ } catch (err) {+ report.documents.failed.push({ file: r, error: (err as Error).message });+ }+ }++ report.textures = textures.size;+ if (!opts.dryRun) {+ for (const { entry, slice } of textures.values()) {+ const dest = path.join(out, outRef(entry.rel));+ if (!existsSync(entry.file)) {+ report.missingAsset(entry.uuid);+ continue;+ }+ mkdirSync(path.dirname(dest), { recursive: true });+ copyFileSync(entry.file, dest);+ if (entry.file.endsWith('.fnt')) copyFontPages(entry.file, dest);+ if (slice) {+ // A slice border is a texture import setting here; the Cocos image keeps its uuid.+ writeOut(`${dest}.meta`, `${JSON.stringify({ uuid: entry.uuid, version: '2.0', type: 'texture', importer: { sliceBorder: slice } }, null, 2)}\n`);+ }+ }+ writeOut(path.join(out, 'assets', into, 'import-report.json'), `${JSON.stringify(report.toJSON(), null, 2)}\n`);+ }+ return report.toJSON();+}diff --git a/pipeline/src/import/cocos/index.ts b/pipeline/src/import/cocos/index.tsnew file mode 100644index 000000000..9c7920ee7--- /dev/null+++ b/pipeline/src/import/cocos/index.ts@@ -0,0 +1,7 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+export { importCocosProject, type CocosImportOptions } from './importProject';+export { parseCocosDocument, type CocosDocument, type CocosNode } from './document';+export { buildCocosAssetIndex, type CocosAssetIndex } from './assets';+export { convertPrefab, convertScene, type ConvertContext, type PrefabFile, type SceneFile } from './convert';+export { ImportReport, type ImportReportData } from './report';diff --git a/pipeline/src/import/cocos/report.ts b/pipeline/src/import/cocos/report.tsnew file mode 100644index 000000000..dc49a8508--- /dev/null+++ b/pipeline/src/import/cocos/report.ts@@ -0,0 +1,66 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file What an import did and did not carry across.+ *+ * A converter that only reports success is worse than none: a game that+ * loads with half its UI missing looks like a runtime bug. Every+ * component is counted as mapped, partial or unmapped, and every+ * approximation names itself, so the gap is a list rather than a hunt.+ */++export type MapStatus = 'mapped' | 'partial' | 'unmapped';++export interface ComponentTally { mapped: number; partial: number; unmapped: number }+export interface NoteTally { count: number; examples: string[] }++export interface ImportReportData {+ documents: { converted: number; failed: { file: string; error: string }[] };+ nodes: number;+ prefabInstances: number;+ components: Record<string, ComponentTally>;+ notes: Record<string, NoteTally>;+ assets: { textures: number; missing: string[] };+}++const EXAMPLES = 3;++export class ImportReport {+ documents = { converted: 0, failed: [] as { file: string; error: string }[] };+ nodes = 0;+ prefabInstances = 0;+ private readonly components = new Map<string, ComponentTally>();+ private readonly notes = new Map<string, NoteTally>();+ private readonly missing = new Set<string>();+ textures = 0;++ component(type: string, status: MapStatus): void {+ let t = this.components.get(type);+ if (!t) this.components.set(type, (t = { mapped: 0, partial: 0, unmapped: 0 }));+ t[status]++;+ }++ /** A thing approximated, dropped or not understood, keyed by a stable code. */+ note(code: string, where: string): void {+ let n = this.notes.get(code);+ if (!n) this.notes.set(code, (n = { count: 0, examples: [] }));+ n.count++;+ if (n.examples.length < EXAMPLES && !n.examples.includes(where)) n.examples.push(where);+ }++ missingAsset(uuid: string): void {+ this.missing.add(uuid);+ }++ toJSON(): ImportReportData {+ const byCount = <T>(m: Map<string, T>, size: (v: T) => number): [string, T][] => [...m].sort((a, b) => size(b[1]) - size(a[1]));+ return {+ documents: this.documents,+ nodes: this.nodes,+ prefabInstances: this.prefabInstances,+ components: Object.fromEntries(byCount(this.components, (v) => v.mapped + v.partial + v.unmapped)),+ notes: Object.fromEntries(byCount(this.notes, (v) => v.count)),+ assets: { textures: this.textures, missing: [...this.missing].slice(0, 50) },+ };+ }+}diff --git a/pipeline/tests/cocos-import.test.ts b/pipeline/tests/cocos-import.test.tsnew file mode 100644index 000000000..1caff28d6--- /dev/null+++ b/pipeline/tests/cocos-import.test.ts@@ -0,0 +1,229 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file What taking a Cocos project over must keep true.+ *+ * The fixture is a project written out by the test, small enough that every+ * expectation can be checked by eye. The claims that carry the importer:+ *+ * - the source is never written to;+ * - a nested prefab stays nested, and the engine's own `flattenPrefab` expands+ * the converted files to the same entities the Cocos instance has — that is+ * the test of the override diff, which has no table of its own to be checked+ * against;+ * - what is not mapped is counted, not dropped.+ */+import { afterAll, beforeAll, describe, expect, it } from 'vitest';+import { createHash } from 'node:crypto';+import { mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync, existsSync } from 'node:fs';+import { tmpdir } from 'node:os';+import path from 'node:path';+import { importCocosProject } from '../src/import/cocos';++const IMG = '11111111-1111-4111-8111-111111111111';+const ITEM = '22222222-2222-4222-8222-222222222222';+const PANEL = '33333333-3333-4333-8333-333333333333';+const FONT = '44444444-4444-4444-8444-444444444444';++const vec = (x: number, y: number, z = 0) => ({ __type__: 'cc.Vec3', x, y, z });+const ident = { __type__: 'cc.Quat', x: 0, y: 0, z: 0, w: 1 };+const one = vec(1, 1, 1);++function node(name: string, parent: number | null, children: number[], components: number[], prefab: number, pos = vec(0, 0)): object {+ return {+ __type__: 'cc.Node', _name: name, _parent: parent === null ? null : { __id__: parent },+ _children: children.map((__id__) => ({ __id__ })), _active: true,+ _components: components.map((__id__) => ({ __id__ })), _prefab: { __id__: prefab },+ _lpos: pos, _lrot: ident, _lscale: one, _layer: 33554432,+ };+}+const uiT = (n: number, c: number, w: number, h: number) =>+ [{ __type__: 'cc.UITransform', node: { __id__: n }, _enabled: true, __prefab: { __id__: c }, _contentSize: { width: w, height: h }, _anchorPoint: { x: 0.5, y: 0.5 } },+ { __type__: 'cc.CompPrefabInfo', fileId: `ut${n}` }];++/** item.prefab: root "Item" (sprite 100x40, tinted white) with a Label child. */+const itemPrefab = [+ { __type__: 'cc.Prefab', _name: 'item', data: { __id__: 1 } },+ node('Item', null, [2], [4, 6], 8, vec(5, 6)), // 1+ node('Caption', 1, [], [9, 11], 13), // 2+ { __type__: 'cc.Node', _name: 'unused' }, // 3 (keeps ids stable)+ ...uiT(1, 5, 100, 40), // 4,5+ { __type__: 'cc.Sprite', node: { __id__: 1 }, _enabled: true, __prefab: { __id__: 7 }, _color: { r: 255, g: 255, b: 255, a: 255 }, _spriteFrame: { __uuid__: `${IMG}@f9941` }, _type: 0 }, // 6+ { __type__: 'cc.CompPrefabInfo', fileId: 'spr' }, // 7+ { __type__: 'cc.PrefabInfo', root: { __id__: 1 }, asset: { __id__: 0 }, fileId: 'itemRoot', instance: null }, // 8+ { __type__: 'cc.UITransform', node: { __id__: 2 }, _enabled: true, __prefab: { __id__: 10 }, _contentSize: { width: 80, height: 20 }, _anchorPoint: { x: 0.5, y: 0.5 } }, // 9+ { __type__: 'cc.CompPrefabInfo', fileId: 'ut2' }, // 10+ { __type__: 'cc.Label', node: { __id__: 2 }, _enabled: true, __prefab: { __id__: 12 }, _string: 'hello', _fontSize: 20, _lineHeight: 24, _color: { r: 255, g: 0, b: 0, a: 255 }, _horizontalAlign: 1, _verticalAlign: 1, _isSystemFontUsed: false, _font: { __uuid__: FONT }, _overflow: 0, _enableWrapText: true }, // 11+ { __type__: 'cc.CompPrefabInfo', fileId: 'lab' }, // 12+ { __type__: 'cc.PrefabInfo', root: { __id__: 1 }, asset: { __id__: 0 }, fileId: 'capt', instance: null }, // 13+];++const instOverrides = (extra: object[]) => extra;+/** panel.prefab: root "Panel" holding two instances of item, the second repositioned, tinted and renamed. */+const panelPrefab = [+ { __type__: 'cc.Prefab', _name: 'panel', data: { __id__: 1 } },+ node('Panel', null, [2, 6], [], 10), // 1+ { __type__: 'cc.Node', _objFlags: 0, _parent: { __id__: 1 }, _prefab: { __id__: 3 } }, // 2 (instance A, untouched)+ { __type__: 'cc.PrefabInfo', root: { __id__: 2 }, asset: { __uuid__: ITEM }, fileId: 'itemRoot', instance: { __id__: 4 } }, // 3+ { __type__: 'cc.PrefabInstance', fileId: 'instA', prefabRootNode: { __id__: 1 }, mountedChildren: [], mountedComponents: [], propertyOverrides: [], removedComponents: [] }, // 4+ { __type__: 'cc.Node', _name: 'pad' }, // 5+ { __type__: 'cc.Node', _objFlags: 0, _parent: { __id__: 1 }, _prefab: { __id__: 7 } }, // 6 (instance B)+ { __type__: 'cc.PrefabInfo', root: { __id__: 6 }, asset: { __uuid__: ITEM }, fileId: 'itemRoot', instance: { __id__: 8 } }, // 7+ { __type__: 'cc.PrefabInstance', fileId: 'instB', prefabRootNode: { __id__: 1 }, mountedChildren: [], mountedComponents: [], removedComponents: [],+ propertyOverrides: [{ __id__: 11 }, { __id__: 13 }, { __id__: 15 }, { __id__: 17 }] }, // 8+ { __type__: 'cc.Node', _name: 'pad' }, // 9+ { __type__: 'cc.PrefabInfo', root: { __id__: 1 }, asset: { __id__: 0 }, fileId: 'panelRoot', instance: null }, // 10+ { __type__: 'CCPropertyOverrideInfo', targetInfo: { __id__: 12 }, propertyPath: ['_name'], value: 'second' }, // 11+ { __type__: 'cc.TargetInfo', localID: ['itemRoot'] }, // 12+ { __type__: 'CCPropertyOverrideInfo', targetInfo: { __id__: 12 }, propertyPath: ['_lpos'], value: vec(0, -50) }, // 13+ { __type__: 'cc.TargetInfo', localID: ['spr'] }, // 14+ { __type__: 'CCPropertyOverrideInfo', targetInfo: { __id__: 14 }, propertyPath: ['_color'], value: { __type__: 'cc.Color', r: 0, g: 255, b: 0, a: 255 } }, // 15+ { __type__: 'cc.TargetInfo', localID: ['lab'] }, // 16+ { __type__: 'CCPropertyOverrideInfo', targetInfo: { __id__: 16 }, propertyPath: ['_string'], value: 'changed' }, // 17+];+void instOverrides;++/** main.scene: one root node holding an instance of panel whose item B is nudged once more. */+const scene = [+ { __type__: 'cc.SceneAsset', _name: 'main', scene: { __id__: 1 } },+ { __type__: 'cc.Scene', _name: 'main', _children: [{ __id__: 2 }], _globals: { __id__: 5 } },+ { __type__: 'cc.Node', _name: 'Canvas', _parent: { __id__: 1 }, _children: [{ __id__: 3 }], _active: true, _components: [], _prefab: null, _lpos: vec(0, 0), _lrot: ident, _lscale: one, _layer: 33554432, _id: 'canvas' },+ { __type__: 'cc.Node', _objFlags: 0, _parent: { __id__: 2 }, _prefab: { __id__: 4 }, _id: '' },+ { __type__: 'cc.PrefabInfo', root: { __id__: 3 }, asset: { __uuid__: PANEL }, fileId: 'panelRoot', instance: { __id__: 6 } },+ { __type__: 'cc.SceneGlobals', skybox: { __id__: 5 } },+ { __type__: 'cc.PrefabInstance', fileId: 'inst', prefabRootNode: { __id__: 2 }, mountedChildren: [], mountedComponents: [], removedComponents: [], propertyOverrides: [{ __id__: 7 }] },+ { __type__: 'CCPropertyOverrideInfo', targetInfo: { __id__: 8 }, propertyPath: ['_lpos'], value: vec(9, 9) },+ { __type__: 'cc.TargetInfo', localID: ['instB', 'itemRoot'] },+];++const meta = (uuid: string, importer: string, extra: object = {}) => ({ ver: '1', importer, uuid, subMetas: {}, userData: {}, ...extra });+const imageMeta = meta(IMG, 'image', {+ subMetas: { f9941: { importer: 'sprite-frame', uuid: `${IMG}@f9941`, userData: { width: 64, height: 64, rawWidth: 64, rawHeight: 64, borderLeft: 8, borderRight: 8, borderTop: 8, borderBottom: 8 } } },+});++const sha = (f: string): string => createHash('sha1').update(readFileSync(f)).digest('hex');+function* files(dir: string): Generator<string> {+ for (const e of readdirSync(dir, { withFileTypes: true })) {+ const p = path.join(dir, e.name);+ if (e.isDirectory()) yield* files(p);+ else yield p;+ }+}++// The engine's own expander, loaded by path: it is the reference the overrides are judged against, and importing it+// statically would put the whole SDK under this package's compiler settings.+type Flatten = (prefab: unknown, overrides: unknown[], ctx: { allocateId: () => number; loadPrefab: (p: string) => unknown }) => { entities: any[] };+const FLATTEN = path.resolve(__dirname, '../../sdk/src/prefab/flatten.ts');+let flattenPrefab: Flatten;++let root: string;+let src: string;+let out: string;+let report: ReturnType<typeof importCocosProject>;+let before: Record<string, string>;++beforeAll(async () => {+ flattenPrefab = (await import(/* @vite-ignore */ FLATTEN)).flattenPrefab as Flatten;+ root = mkdtempSync(path.join(tmpdir(), 'cocos-import-'));+ src = path.join(root, 'creator');+ out = path.join(root, 'estella');+ const put = (rel: string, v: unknown): void => {+ const f = path.join(src, 'assets', rel);+ mkdirSync(path.dirname(f), { recursive: true });+ writeFileSync(f, typeof v === 'string' ? v : JSON.stringify(v));+ };+ put('ui/icon.png', 'not really a png');+ put('ui/icon.png.meta', imageMeta);+ put('ui/item.prefab', itemPrefab);+ put('ui/item.prefab.meta', meta(ITEM, 'prefab'));+ put('ui/panel.prefab', panelPrefab);+ put('ui/panel.prefab.meta', meta(PANEL, 'prefab'));+ put('ui/f.fnt', 'info face="f"\npage id=0 file="f_0.png"\n');+ put('ui/f_0.png', 'page');+ put('ui/f.fnt.meta', meta(FONT, 'bitmap-font'));+ put('main.scene', scene);+ put('main.scene.meta', meta('55555555-5555-4555-8555-555555555555', 'scene'));+ before = Object.fromEntries([...files(src)].map((f) => [f, sha(f)]));+ report = importCocosProject({ source: src, out });+});++afterAll(() => rmSync(root, { recursive: true, force: true }));++const readJson = (rel: string): any => JSON.parse(readFileSync(path.join(out, rel), 'utf8'));++describe('importing a Cocos project', () => {+ it('never writes to the source, and refuses an output inside it', () => {+ expect(Object.fromEntries([...files(src)].map((f) => [f, sha(f)]))).toEqual(before);+ expect(() => importCocosProject({ source: src, out: path.join(src, 'out') })).toThrow(/never written/);+ });++ it('converts every prefab and scene without failures', () => {+ expect(report.documents.failed).toEqual([]);+ expect(report.documents.converted).toBe(3);+ for (const f of ['item.esprefab', 'panel.esprefab', 'main.esscene']) expect(existsSync(path.join(out, 'assets/cocos', f.endsWith('scene') ? f : `ui/${f}`))).toBe(true);+ });++ it('maps a Sprite with its size, anchor, tint, texture and nine-slice border', () => {+ const item = readJson('assets/cocos/ui/item.esprefab');+ const root = item.entities.find((e: any) => e.prefabEntityId === 'itemRoot');+ const sprite = root.components.find((c: any) => c.type === 'Sprite').data;+ expect(sprite).toMatchObject({ size: { x: 100, y: 40 }, pivot: { x: 0.5, y: 0.5 }, texture: 'assets/cocos/ui/icon.png' });+ expect(root.components[0]).toEqual({ type: 'Transform', data: { position: { x: 5, y: 6, z: 0 }, rotation: { x: 0, y: 0, z: 0, w: 1 }, scale: { x: 1, y: 1, z: 1 } } });+ expect(existsSync(path.join(out, 'assets/cocos/ui/icon.png'))).toBe(true);+ });++ it('maps a Label to Text with a bitmap font, and carries the font pages along', () => {+ const caption = readJson('assets/cocos/ui/item.esprefab').entities.find((e: any) => e.prefabEntityId === 'capt');+ expect(caption.components.find((c: any) => c.type === 'Text').data).toMatchObject({+ content: 'hello', fontSize: 20, align: 'Center', verticalAlign: 'Middle', font: 'assets/cocos/ui/f.fnt',+ });+ const written = [...files(out)].map((f) => path.relative(out, f).split(path.sep).join('/'));+ expect(written, written.join(',')).toContain('assets/cocos/ui/f_0.png');+ });++ it('keeps a nested prefab nested, with the instance\'s changes as overrides', () => {+ const panel = readJson('assets/cocos/ui/panel.esprefab');+ const b = panel.entities.find((e: any) => e.prefabEntityId === 'instB');+ expect(b.nestedPrefab.prefabPath).toBe('assets/cocos/ui/item.esprefab');+ const kinds = b.nestedPrefab.overrides.map((o: any) => `${o.type}:${o.prefabEntityId}:${o.componentType ?? ''}.${o.propertyName ?? ''}`);+ expect(kinds).toEqual(expect.arrayContaining([+ 'name:itemRoot:.', 'property:itemRoot:Transform.position', 'property:itemRoot:Sprite.color', 'property:capt:Text.content',+ ]));+ // nothing else changed, so nothing else is said+ expect(kinds).toHaveLength(4);+ });++ it('expands, through the engine\'s own flatten, to what the Cocos instance has', () => {+ const panel = readJson('assets/cocos/ui/panel.esprefab');+ const item = readJson('assets/cocos/ui/item.esprefab');+ const load = (p: string): any => (p.endsWith('item.esprefab') ? item : null);+ let id = 0;+ const { entities } = flattenPrefab(panel, [], { allocateId: () => ++id, loadPrefab: load });+ const byName = new Map(entities.map((e: any) => [e.name, e]));+ const second = byName.get('second') as any;+ expect(second.components.find((c: any) => c.type === 'Transform').data.position).toEqual({ x: 0, y: -50, z: 0 });+ expect(second.components.find((c: any) => c.type === 'Sprite').data.color).toEqual({ r: 0, g: 1, b: 0, a: 1 });+ const texts = entities.filter((e: any) => e.components.some((c: any) => c.type === 'Text')).map((e: any) => e.components.find((c: any) => c.type === 'Text').data.content);+ expect(texts.sort()).toEqual(['changed', 'hello']);+ });++ it('turns a scene\'s prefab instance into an entry with the overrides it applied', () => {+ const scene = readJson('assets/cocos/main.esscene');+ const entry = scene.entities.find((e: any) => typeof e.prefab === 'string');+ expect(entry).toMatchObject({ prefab: 'assets/cocos/ui/panel.esprefab', parent: 0, added: [], removed: [] });+ // 'instB/itemRoot' addresses the engine's composed id for the nested root: slot / local id+ expect(entry.overrides).toEqual([+ expect.objectContaining({ prefabEntityId: 'instB/itemRoot', type: 'property', componentType: 'Transform', propertyName: 'position', value: { x: 9, y: 9, z: 0 } }),+ ]);+ expect(scene.entities[0].children).toEqual([entry.id]);+ expect(scene.version).toBe(4);+ });++ it('counts what it did not map instead of dropping it', () => {+ expect(report.components['cc.Sprite']).toEqual({ mapped: 1, partial: 0, unmapped: 0 });+ expect(report.components['cc.Label']).toEqual({ mapped: 0, partial: 1, unmapped: 0 });+ expect(report.notes['label-bitmap-font']?.count).toBe(1);+ expect(report.notes['scene-globals-dropped']?.count).toBe(1);+ expect(report.prefabInstances).toBe(3);+ });+});