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.

fix(import): Cocos enums as the engine's numbers, bitmapfont meta so the page ships, and the engine's own component validation in the test

yhhb0558b169858
diff --git a/pipeline/src/import/cocos/components.ts b/pipeline/src/import/cocos/components.ts
index eaa7e3ce7..c33686221 100644
--- a/pipeline/src/import/cocos/components.ts
+++ b/pipeline/src/import/cocos/components.ts
@@ -39,6 +39,8 @@ const color = (v: unknown, fallback = 1): Raw => {
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 clamp012 = (v: unknown): number => Math.min(2, Math.max(0, Math.trunc(num(v, 0))));
+
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. */
@@ -102,12 +104,12 @@ function sprite(c: CocosComponent, box: UiBox | null, ctx: ComponentContext, whe
};
const hasBorder = border.left + border.right + border.top + border.bottom > 0;
if (kind === 1 && hasBorder) {
- data.drawMode = 'NineSlice';
+ data.drawMode = 3; // NineSlice
data.texture = ctx.assetRef(entry, border);
} else {
data.texture = ctx.assetRef(entry);
if (kind === 2) {
- data.drawMode = 'Tiled';
+ data.drawMode = 2; // Tiled
} else if (kind === 3) {
status = 'partial';
ctx.report.note('sprite-filled-as-simple', where);
@@ -148,10 +150,11 @@ function label(c: CocosComponent, siblings: CocosComponent[], ctx: ComponentCont
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',
+ // Left/Center/Right and Top/Middle/Bottom number the same in both engines (0, 1, 2).
+ align: clamp012(d._horizontalAlign),
+ verticalAlign: clamp012(d._verticalAlign),
wordWrap: d._enableWrapText !== false,
- overflow: overflow === 1 ? 'Clip' : 'Visible',
+ overflow: overflow === 1 ? 1 : 0, // Clip : Visible
lineHeight: fontSize > 0 ? Math.round((lineHeight / fontSize) * 1000) / 1000 : 1.2,
bold: d._isBold === true,
italic: d._isItalic === true,
@@ -213,7 +216,7 @@ function richText(c: CocosComponent, ctx: ComponentContext): ComponentData {
color: color(d._fontColor),
richText: true,
wordWrap: num(d._maxWidth, 0) > 0,
- align: (['Left', 'Center', 'Right'] as const)[num(d._horizontalAlign, 0)] ?? 'Left',
+ align: clamp012(d._horizontalAlign),
enabled: c.enabled,
},
};
@@ -225,7 +228,7 @@ function camera(c: CocosComponent, ctx: ComponentContext): ComponentData {
return {
type: 'Camera',
data: {
- projectionType: num(d._projection, 0) === 0 ? 'Orthographic' : 'Perspective',
+ projectionType: num(d._projection, 0) === 0 ? 1 : 0, // Orthographic : Perspective
fov: num(d._fov, 45),
orthoSize: num(d._orthoHeight, 10),
nearPlane: num(d._near, 1),
diff --git a/pipeline/src/import/cocos/importProject.ts b/pipeline/src/import/cocos/importProject.ts
index 4a6b4c3b9..ed275ba04 100644
--- a/pipeline/src/import/cocos/importProject.ts
+++ b/pipeline/src/import/cocos/importProject.ts
@@ -173,7 +173,12 @@ export function importCocosProject(opts: CocosImportOptions): ImportReportData {
}
mkdirSync(path.dirname(dest), { recursive: true });
copyFileSync(entry.file, dest);
- if (entry.file.endsWith('.fnt')) copyFontPages(entry.file, dest);
+ if (entry.file.endsWith('.fnt')) {
+ copyFontPages(entry.file, dest);
+ // The asset database ships a font's page image only for a `bitmapfont`, since nothing else names it.
+ writeOut(`${dest}.meta`, `${JSON.stringify({ uuid: entry.uuid, version: '2.0', type: 'bitmapfont', importer: {} }, null, 2)}
+`);
+ }
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`);
diff --git a/pipeline/tests/cocos-import.test.ts b/pipeline/tests/cocos-import.test.ts
index 1caff28d6..ab49904e8 100644
--- a/pipeline/tests/cocos-import.test.ts
+++ b/pipeline/tests/cocos-import.test.ts
@@ -115,6 +115,11 @@ function* files(dir: string): Generator<string> {
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;
+const SDK = path.resolve(__dirname, '../../sdk/src');
+
+type Validate = (name: string, defaults: unknown, data: unknown, assetFields?: unknown) => { field: string; expected: string; value: unknown }[];
+let validate: Validate;
+let registry: Record<string, any>;
let root: string;
let src: string;
@@ -124,6 +129,9 @@ let before: Record<string, string>;
beforeAll(async () => {
flattenPrefab = (await import(/* @vite-ignore */ FLATTEN)).flattenPrefab as Flatten;
+ validate = (await import(/* @vite-ignore */ path.join(SDK, 'util/validation.ts'))).validateComponentData as Validate;
+ registry = await import(/* @vite-ignore */ path.join(SDK, 'ecs/component.ts'));
+ registry.Text = (await import(/* @vite-ignore */ path.join(SDK, 'ui/core/text.ts'))).Text;
root = mkdtempSync(path.join(tmpdir(), 'cocos-import-'));
src = path.join(root, 'creator');
out = path.join(root, 'estella');
@@ -175,7 +183,7 @@ describe('importing a Cocos project', () => {
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',
+ content: 'hello', fontSize: 20, align: 1, verticalAlign: 1, overflow: 0, 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');
@@ -226,4 +234,25 @@ describe('importing a Cocos project', () => {
expect(report.notes['scene-globals-dropped']?.count).toBe(1);
expect(report.prefabInstances).toBe(3);
});
+
+ it('writes component data the engine accepts: every field has the type its component declares', () => {
+ // A string where the engine wants an enum number loads, warns, and falls back to the default — a UI that is
+ // wrong everywhere and says so only in a console. The engine's own validator is the judge.
+ const docs = ['assets/cocos/ui/item.esprefab', 'assets/cocos/ui/panel.esprefab', 'assets/cocos/main.esscene'].map(readJson);
+ const problems: string[] = [];
+ let checked = 0;
+ for (const doc of docs) {
+ for (const e of doc.entities) {
+ const all = [...(e.components ?? []), ...(e.nestedPrefab?.overrides ?? e.overrides ?? []).flatMap((o: any) => (o.type === 'property' ? [{ type: o.componentType, data: { [o.propertyName]: o.value } }] : o.componentData ? [o.componentData] : []))];
+ for (const c of all) {
+ const def = registry[c.type];
+ if (!def) continue;
+ checked++;
+ for (const err of validate(c.type, def._default, c.data, def.assetFields)) problems.push(`${c.type}.${err.field}: expected ${err.expected}, got ${JSON.stringify(err.value)}`);
+ }
+ }
+ }
+ expect(checked).toBeGreaterThan(5);
+ expect(problems).toEqual([]);
+ });
});