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): a root pinned to the screen is stored where the engine places it in the design box, so the document and the viewport agree

yhh968a445f9e26
diff --git a/pipeline/src/import/cocos/convert.ts b/pipeline/src/import/cocos/convert.ts
index 30bad8a62..c93cc8d38 100644
--- a/pipeline/src/import/cocos/convert.ts
+++ b/pipeline/src/import/cocos/convert.ts
@@ -16,6 +16,14 @@
import { convertNode, sameData, type ComponentContext, type ComponentData } from './components';
import { NODE_REF, type CocosDocument, type CocosNode, type CocosOverride } from './document';
import { ImportReport } from './report';
+import { anchoredRect, type RectAnchorsData } from '../../../../sdk/src/ui/layout/rect-anchors';
+
+/** What a field a document does not carry means (the component's own defaults). */
+const DEFAULT_ANCHORS: RectAnchorsData = {
+ alignFlags: 0, left: 0, right: 0, top: 0, bottom: 0, horizontalCenter: 0, verticalCenter: 0,
+ isAbsLeft: true, isAbsRight: true, isAbsTop: true, isAbsBottom: true, isAbsHorizontalCenter: true, isAbsVerticalCenter: true,
+ alignMode: 1, enabled: true,
+};
const SEP = '/';
@@ -80,6 +88,8 @@ export interface ConvertContext extends ComponentContext {
prefabRef(uuid: string): string | null;
/** Where the document being converted lives, for notes. */
where: string;
+ /** The project's design resolution: the box a root pinned to the screen is placed in, so the document holds where it will be. */
+ design?: { width: number; height: number };
}
// ---------------------------------------------------------------------------
@@ -429,6 +439,28 @@ export function convertPrefab(doc: CocosDocument, ctx: ConvertContext): PrefabFi
return { version: '2', name: doc.name, rootEntityId: root.id, entities };
}
+/**
+ * A root pinned to the screen is stored where the engine will put it: Cocos keeps such a root at its own corner-based position, and the
+ * engine's screen is centred on the origin, so the document would otherwise say one place and show another until the first frame. The
+ * same function the engine aligns with places it, in the project's design box.
+ */
+function placeInDesign(components: ComponentData[], design: { width: number; height: number }): void {
+ const anchors = components.find((c) => c.type === 'RectAnchors');
+ const transform = components.find((c) => c.type === 'Transform');
+ if (!anchors || !transform) return;
+ const a = { ...DEFAULT_ANCHORS, ...(anchors.data as Partial<RectAnchorsData>) };
+ if (!a.alignFlags || a.enabled === false) return;
+ const rect = components.find((c) => c.type === 'ContentRect')?.data as { size?: { x: number; y: number }; pivot?: { x: number; y: number } } | undefined;
+ const t = transform.data as { position: { x: number; y: number; z: number }; scale?: { x: number; y: number } };
+ const out = anchoredRect(
+ a, { left: -design.width / 2, right: design.width / 2, bottom: -design.height / 2, top: design.height / 2 },
+ { width: rect?.size?.x ?? 0, height: rect?.size?.y ?? 0, pivotX: rect?.pivot?.x ?? 0.5, pivotY: rect?.pivot?.y ?? 0.5 },
+ { x: t.scale?.x ?? 1, y: t.scale?.y ?? 1 }, { x: t.position.x, y: t.position.y },
+ );
+ t.position = { ...t.position, x: out.x, y: out.y };
+ if (rect?.size) rect.size = { x: out.width, y: out.height };
+}
+
export function convertScene(doc: CocosDocument, ctx: ConvertContext): SceneFile {
ctx.nodeById = indexNodes(doc.roots);
const entities: (SceneEntity | SceneInstanceEntry)[] = [];
@@ -478,5 +510,6 @@ export function convertScene(doc: CocosDocument, ctx: ConvertContext): SceneFile
for (const r of doc.roots) walk(r, null);
// 0 is the engine's "no entity"; the loader maps the rest.
for (const e of entities) if ('components' in e) resolveRefs(e.components, (id) => ids.get(id) ?? 0, 0);
+ if (ctx.design) for (const e of entities) if ('components' in e && e.parent === null) placeInDesign(e.components, ctx.design);
return { version: 4, name: doc.name, entities };
}
diff --git a/pipeline/src/import/cocos/importProject.ts b/pipeline/src/import/cocos/importProject.ts
index 7e2bd6831..88db524e3 100644
--- a/pipeline/src/import/cocos/importProject.ts
+++ b/pipeline/src/import/cocos/importProject.ts
@@ -152,6 +152,15 @@ function startSceneOf(scenes: readonly string[]): string | undefined {
return find(/(^|\/)launch\/main\.scene$/) ?? find(/(^|\/)launch\/[^/]+\.scene$/) ?? find(/^main\.scene$/);
}
+/** The design resolution a Cocos project declares, which is the box its screen-pinned roots are placed in. */
+function designSizeOf(source: string): { width: number; height: number } | undefined {
+ try {
+ const settings = JSON.parse(readFileSync(path.join(source, 'settings', 'v2', 'packages', 'project.json'), 'utf8')) as { general?: { designResolution?: { width?: number; height?: number } } };
+ const size = settings.general?.designResolution;
+ return size?.width && size.height ? { width: size.width, height: size.height } : undefined;
+ } catch { return undefined; }
+}
+
/**
* Make the converted project start where the Cocos game does: the starter project opens its own empty scene and an 800x600 design size, so
* playing it shows nothing of the game. Only a manifest still carrying the starter's values is changed; one the creator edited is theirs.
@@ -342,6 +351,7 @@ export async function importCocosProject(opts: CocosImportOptions): Promise<Impo
const scriptNames = new Set<string>();
const ctx: ConvertContext = {
assets: index,
+ design: designSizeOf(source),
scriptClass: (classId) => {
const found = scripts.get(classId);
if (found) { usedScripts.add(found.rel); scriptNames.add(`Cocos.${found.name}`); }
diff --git a/pipeline/tests/cocos-import-layer.test.ts b/pipeline/tests/cocos-import-layer.test.ts
index 376b5801c..02701e82c 100644
--- a/pipeline/tests/cocos-import-layer.test.ts
+++ b/pipeline/tests/cocos-import-layer.test.ts
@@ -104,7 +104,9 @@ describe('importing for the compatibility layer', () => {
const comp = (name: string, type: string) => entity(name).components.find((c) => c.type === type)!;
it('keeps a node\'s rectangle as a component of its own, as well as the size its renderers got', () => {
- expect(comp('Canvas', 'ContentRect').data).toEqual({ size: { x: 960, y: 640 }, pivot: { x: 0.5, y: 0.5 } });
+ // a root pinned to the screen is stored as the engine will place it in the project's design box (1080x1920, centred on the origin)
+ expect(comp('Canvas', 'ContentRect').data).toEqual({ size: { x: 1060, y: 1910 }, pivot: { x: 0.5, y: 0.5 } });
+ expect(comp('Canvas', 'Transform').data.position).toMatchObject({ x: 0, y: 0 });
});
it('carries a widget\'s and a layout\'s settings under the names the layer uses', () => {