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 converted effect's ambient parameters start at what most of the project's game scenes set, so a fake-lit material is not brighter than the game draws it

yhha8edd9855e6f
diff --git a/pipeline/src/import/cocos/effectConvert.ts b/pipeline/src/import/cocos/effectConvert.ts
index 45da97c41..bf683856c 100644
--- a/pipeline/src/import/cocos/effectConvert.ts
+++ b/pipeline/src/import/cocos/effectConvert.ts
@@ -203,6 +203,8 @@ const ARITY: Record<string, number> = { float: 1, int: 1, vec2: 2, vec3: 3, vec4
export interface EffectOptions {
/** The text of a chunk by its include name (`common/data/unpack`, a project's `tower_defense_death_dissolve`), or null when there is none. */
chunk?(name: string): string | null;
+ /** The values a scene gives a fragment (`cc_ambientSky`…), where the project has them: the parameters of the material start there. */
+ scene?: Record<string, number[]>;
}
/** Chunks of Cocos that the prelude gives (a fragment's built-ins, the scene's uniform blocks): they are left out rather than read. */
@@ -570,6 +572,7 @@ export function convertPass(
const sceneValues: Record<string, number[]> = {
cc_ambientSky: [1, 1, 1, 1], cc_ambientGround: [1, 1, 1, 1], cc_cameraPos: [0, 0, 0, 1], cc_nearFar: [0.1, 1000, 0, 0],
cc_screenSize: [1, 1, 1, 1], cc_exposure: [1, 1, 0, 0], cc_mainLitColor: [1, 1, 1, 1], cc_mainLitDir: [0, 0, -1, 0],
+ ...options.scene,
};
const everything = `${vertexText}\n${body}`;
for (const [name, value] of Object.entries(sceneValues)) {
diff --git a/pipeline/src/import/cocos/importProject.ts b/pipeline/src/import/cocos/importProject.ts
index d6b246038..8b0d39318 100644
--- a/pipeline/src/import/cocos/importProject.ts
+++ b/pipeline/src/import/cocos/importProject.ts
@@ -26,13 +26,14 @@ import { convertAnimationGraph } from './animationGraph';
import type { MaterialInfo } from './components';
import { parseEffect, type CocosEffect, type EffectPass } from './effects';
import { convertPass, isOutlinePass, type PassConversion } from './effectConvert';
+import { dominantAmbient } from './sceneAmbient';
/**
* The revision of what an import writes. It is recorded in the state file; a converted project whose record is older was written by an
* importer that made less (or differently), and is brought up to date when it is opened. Raise it when the converted output changes in a
* way an existing project needs to pick up: a new generated file, a field a document or a manifest now carries.
*/
-export const COCOS_IMPORT_REVISION = 24;
+export const COCOS_IMPORT_REVISION = 25;
/** Whether the project at @p projectRoot was written by an importer of this revision. A project that was not converted has nothing to bring up. */
export function cocosImportIsCurrent(projectRoot: string): boolean {
@@ -722,6 +723,9 @@ export async function importCocosProject(opts: CocosImportOptions): Promise<Impo
// material of it, and the renderers that wore the Cocos material wear that one. Null when the pass cannot be given the engine's vertex stage.
// The chunks an effect includes: the project's own (by their path under the assets folder, or just their name), then the Creator install's.
const projectChunks = [...index.byUuid.values()].filter((e) => e.rel.endsWith('.chunk') && !e.rel.startsWith(`${INTERNAL_FOLDER}/`));
+ // What the project's scenes set for the ambient, which the converted effects read as parameters of their material.
+ const ambient = dominantAmbient(index);
+ const sceneValues = ambient ? { cc_ambientSky: ambient.sky, cc_ambientGround: ambient.ground } : null;
const chunkText = (name: string): string | null => {
const own = projectChunks.find((e) => { const rel = e.rel.replace(/\.chunk$/, ''); return rel === name || rel.endsWith(`/${name}`); });
if (own) return readFileSync(own.file, 'utf8');
@@ -759,7 +763,7 @@ export async function importCocosProject(opts: CocosImportOptions): Promise<Impo
const stem = entry.rel.replace(/^assets\//, '').replace(/\.effect$/, '');
const variant = Object.keys(defines).length === 0 ? '' : `.${createHash('sha1').update(JSON.stringify(Object.entries(defines).sort())).digest('hex').slice(0, 8)}`;
const rel = outRef(`effects/${stem}.${technique.name}.${passIndex}${variant}.esshader`);
- const converted = convertPass(parsed.effect, technique.passes[passIndex]!, `${stem}.${technique.name}.${passIndex}${variant}`, { chunk: chunkText }, defines);
+ const converted = convertPass(parsed.effect, technique.passes[passIndex]!, `${stem}.${technique.name}.${passIndex}${variant}`, { chunk: chunkText, ...(sceneValues ? { scene: sceneValues } : {}) }, defines);
const error = refused.get(rel);
const result = error ? { shader: null, unsupported: `the converted shader does not compile: ${error}`, state: converted.state, rel } : { ...converted, rel };
shaders.set(key, result);
diff --git a/pipeline/src/import/cocos/sceneAmbient.ts b/pipeline/src/import/cocos/sceneAmbient.ts
new file mode 100644
index 000000000..7d7ee8e51
--- /dev/null
+++ b/pipeline/src/import/cocos/sceneAmbient.ts
@@ -0,0 +1,65 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file The ambient light most of a project's scenes share, as the values Cocos hands a fragment (`cc_ambientSky`, `cc_ambientGround`).
+ *
+ * A converted effect reads these as parameters of its material, which start at a value that changes nothing. A scene that lights its models by the
+ * ambient (a fake light that adds the ground colour times the sky's illumination) comes out as bright as that value is wrong, so the parameters
+ * start at what the project's scenes set: one value for every material, the one most of them agree on.
+ */
+import { readFileSync } from 'node:fs';
+import type { CocosAssetIndex } from './assets';
+
+type Raw = Record<string, unknown>;
+const isObj = (v: unknown): v is Raw => typeof v === 'object' && v !== null && !Array.isArray(v);
+
+/** Scenes that are tools and tests of the editor: what they set is not what the game draws with. */
+const NOT_THE_GAME = /(?:^|\/)(?:editor|test|tools?)(?:\/|$)|(?:^|\/)(?:MapEditor|scene-test)/i;
+
+export interface SceneAmbient {
+ /** `cc_ambientSky`: the sky colour and, in w, the illumination it is lit by. */
+ sky: [number, number, number, number];
+ /** `cc_ambientGround`: the ground albedo, and 1. */
+ ground: [number, number, number, number];
+}
+
+const three = (v: unknown): [number, number, number] | null =>
+ isObj(v) && typeof v.x === 'number' && typeof v.y === 'number' && typeof v.z === 'number' ? [v.x, v.y, v.z] : null;
+
+/** The ambient of one scene file, or null when it sets none. */
+export function ambientOfScene(file: string): SceneAmbient | null {
+ try {
+ const objs = JSON.parse(readFileSync(file, 'utf8')) as unknown[];
+ const head = objs[0];
+ const scene = isObj(head) && isObj(head.scene) && typeof head.scene.__id__ === 'number' ? objs[head.scene.__id__] : null;
+ const globals = isObj(scene) && isObj(scene._globals) && typeof scene._globals.__id__ === 'number' ? objs[scene._globals.__id__] : null;
+ const info = isObj(globals) && isObj(globals.ambient) && typeof globals.ambient.__id__ === 'number' ? objs[globals.ambient.__id__] : null;
+ if (!isObj(info)) return null;
+ const sky = three(info._skyColorLDR);
+ const ground = three(info._groundAlbedoLDR);
+ if (!sky || !ground) return null;
+ const illum = typeof info._skyIllumLDR === 'number' ? info._skyIllumLDR : 1;
+ return { sky: [sky[0], sky[1], sky[2], illum], ground: [ground[0], ground[1], ground[2], 1] };
+ } catch {
+ return null;
+ }
+}
+
+/** The ambient most of the project's game scenes set, or null when none does. */
+export function dominantAmbient(index: CocosAssetIndex): SceneAmbient | null {
+ const tally = new Map<string, { count: number; ambient: SceneAmbient }>();
+ const seen = new Set<string>();
+ for (const entry of index.byUuid.values()) {
+ if (seen.has(entry.file) || !entry.rel.endsWith('.scene') || NOT_THE_GAME.test(entry.rel)) continue;
+ seen.add(entry.file);
+ const ambient = ambientOfScene(entry.file);
+ if (!ambient) continue;
+ const key = [...ambient.sky, ...ambient.ground].map((x) => x.toFixed(4)).join(',');
+ const held = tally.get(key);
+ if (held) held.count++;
+ else tally.set(key, { count: 1, ambient });
+ }
+ let best: { count: number; ambient: SceneAmbient } | null = null;
+ for (const t of tally.values()) if (!best || t.count > best.count) best = t;
+ return best?.ambient ?? null;
+}
diff --git a/pipeline/tests/cocos-scene-ambient.test.ts b/pipeline/tests/cocos-scene-ambient.test.ts
new file mode 100644
index 000000000..7a7c4bdf5
--- /dev/null
+++ b/pipeline/tests/cocos-scene-ambient.test.ts
@@ -0,0 +1,48 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file The ambient most of a project's game scenes set is what a converted effect's scene parameters start at.
+ */
+import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import path from 'node:path';
+import { afterAll, describe, expect, it } from 'vitest';
+import { ambientOfScene, dominantAmbient } from '../src/import/cocos/sceneAmbient';
+import type { CocosAssetEntry, CocosAssetIndex } from '../src/import/cocos/assets';
+
+const v4 = (x: number, y: number, z: number) => ({ __type__: 'cc.Vec4', x, y, z, w: 0 });
+const scene = (sky: [number, number, number], illum: number, ground: [number, number, number]) => [
+ { __type__: 'cc.SceneAsset', scene: { __id__: 1 } },
+ { __type__: 'cc.Scene', _globals: { __id__: 2 } },
+ { __type__: 'cc.SceneGlobals', ambient: { __id__: 3 } },
+ { __type__: 'cc.AmbientInfo', _skyColorLDR: v4(...sky), _skyIllumLDR: illum, _groundAlbedoLDR: v4(...ground) },
+];
+
+describe('the ambient of a project', () => {
+ const dir = mkdtempSync(path.join(tmpdir(), 'cocos-ambient-scenes-'));
+ afterAll(() => rmSync(dir, { recursive: true, force: true, maxRetries: 10, retryDelay: 50 }));
+
+ const entries: CocosAssetEntry[] = [];
+ const put = (rel: string, content: unknown): void => {
+ const file = path.join(dir, rel.replace(/\//g, '_'));
+ writeFileSync(file, JSON.stringify(content));
+ entries.push({ uuid: String(entries.length), file, rel, importer: 'scene', userData: {}, subs: new Map() });
+ };
+ const index = (): CocosAssetIndex => ({ root: dir, byUuid: new Map(entries.map((e) => [e.uuid, e])), bundles: [] });
+
+ it('reads the sky colour with its illumination, and the ground', () => {
+ put('a/one.scene', scene([0.5, 0.6, 1], 0.8, [1, 1, 1]));
+ expect(ambientOfScene(entries[0]!.file)).toEqual({ sky: [0.5, 0.6, 1, 0.8], ground: [1, 1, 1, 1] });
+ });
+
+ it('is the one most game scenes set, and not what the editor tools set', () => {
+ put('a/two.scene', scene([0.5, 0.6, 1], 0.8, [1, 1, 1]));
+ put('a/three.scene', scene([1, 1, 1], 1, [0.6, 0.6, 0.5]));
+ for (const n of ['x', 'y', 'z', 'w']) put(`editor/${n}.scene`, scene([0.2, 0.2, 0.2], 0.5, [0.1, 0.1, 0.1]));
+ expect(dominantAmbient(index())).toEqual({ sky: [0.5, 0.6, 1, 0.8], ground: [1, 1, 1, 1] });
+ });
+
+ it('is null for a project whose scenes set none', () => {
+ expect(dominantAmbient({ root: dir, byUuid: new Map(), bundles: [] })).toBeNull();
+ });
+});