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 project's own effect is converted to an Estella shader and material, so a sprite or mesh that wore it keeps its look

yhha16c35278b8b
diff --git a/pipeline/package.json b/pipeline/package.json
index 5b8af36ab..e8fe4cdd5 100644
--- a/pipeline/package.json
+++ b/pipeline/package.json
@@ -19,12 +19,14 @@
"esbuild": "^0.27.0",
"esengine": "workspace:*",
"ffmpeg-static": "^5.3.0",
+ "js-yaml": "4.3.0",
"meshoptimizer": "^1.2.0",
"pngjs": "^7.0.0",
"typescript": "^6.0.3",
"wasm-media-encoders": "^0.7.0"
},
"devDependencies": {
+ "@types/js-yaml": "^4.0.9",
"@types/node": "^25.9.3",
"@types/pngjs": "^6.0.5",
"vitest": "^2.1.9"
diff --git a/pipeline/src/import/cocos/components.ts b/pipeline/src/import/cocos/components.ts
index 09e1e5162..71919f858 100644
--- a/pipeline/src/import/cocos/components.ts
+++ b/pipeline/src/import/cocos/components.ts
@@ -61,6 +61,8 @@ export interface ComponentContext {
drawsBakedOutline?(materialUuid: string): boolean;
/** What a Cocos material draws and how; null when the project has no such material. */
material?(uuid: string): MaterialInfo | null;
+ /** The Estella material a Cocos material of the project's own effect became (its shader converted), by its project path; null when the effect could not be converted. */
+ convertedMaterial?(uuid: string): { ref: string } | null;
/**
* The engine MeshRenderer data of the part of a model a Cocos mesh sub-asset names, once that model was brought in. `exact` is false when
* the part was picked because the model draws only one.
@@ -160,6 +162,13 @@ function sprite(c: CocosComponent, box: UiBox | null, ctx: ComponentContext, whe
const ud = sub.userData;
const kind = num(c.data._type, 0);
let status: 'mapped' | 'partial' = 'mapped';
+ // The material the sprite is drawn with, when the project's own effect for it was converted.
+ const customMaterial = uuidOf(c.data._customMaterial) || uuidOf(Array.isArray(c.data._materials) ? c.data._materials[0] : undefined);
+ if (customMaterial) {
+ const converted = ctx.convertedMaterial?.(customMaterial);
+ if (converted) data.material = converted.ref;
+ else if (ctx.material?.(customMaterial)?.builtinEffect === false) { status = 'partial'; ctx.report.note('sprite-custom-effect', where); }
+ }
const border: SliceBorder = {
left: num(ud.borderLeft, 0),
@@ -607,14 +616,16 @@ function applyMaterial(data: Raw, c: CocosComponent, ctx: ComponentContext, wher
return { found: false, exact: false };
}
delete data.material;
+ const converted = ctx.convertedMaterial?.(uuids[0]!);
+ if (converted) data.material = converted.ref;
if (info.texture) data.texture = ctx.assetRef(info.texture);
if (info.normal) data.normalMap = ctx.assetRef(info.normal);
if (info.color) data.color = info.color;
data.lit = !info.unlit;
data.opaque = !info.transparent;
data.cullBackfaces = info.cullBack;
- let exact = info.builtinEffect;
- if (!info.builtinEffect) ctx.report.note('mesh-custom-effect', where);
+ let exact = info.builtinEffect || converted !== null && converted !== undefined;
+ if (!exact) ctx.report.note('mesh-custom-effect', where);
if (uuids.length > 1) {
exact = false;
ctx.report.note('mesh-several-materials', where);
diff --git a/pipeline/src/import/cocos/effectConvert.ts b/pipeline/src/import/cocos/effectConvert.ts
new file mode 100644
index 000000000..181eb0f06
--- /dev/null
+++ b/pipeline/src/import/cocos/effectConvert.ts
@@ -0,0 +1,323 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file effectConvert.ts
+ * @brief A Cocos `.effect` pass as an Estella `.esshader` and the render state of its `.esmaterial`.
+ *
+ * What carries across is what a pass says about its own fragment: the `frag()` function, the properties it reads (a `Constant` block's
+ * members and its samplers, which become `#pragma param`), the macros it branches on (`#pragma switch`) and the pass's blend, depth and cull
+ * state. The vertex stage is the engine's own: a pass whose vertex program only applies the standard transform needs nothing of its own, which
+ * is the usual case (a sprite, a UI quad, an unlit mesh). A pass whose vertex program does more (a wave, a sway, an outline expansion) cannot be
+ * given the engine's stage and is reported, not approximated: the converted material would draw something other than what it was made to.
+ *
+ * The Cocos built-ins a fragment calls (`CCFragOutput`, `CC_APPLY_FOG`, `cc_time`…) are given by a short prelude written here, not by
+ * expanding the chunks of the Creator install, which are written against Cocos's own uniform buffers and pipeline.
+ */
+import { macrosIn, type CocosEffect, type EffectPass, type EffectProperty } from './effects';
+
+export interface ConvertedShader {
+ /** The `.esshader` source. */
+ source: string;
+ /** The macros the shader branches on, which a material turns on by name (`switches`). */
+ switches: string[];
+ /** The parameters it declares, by name, with the value a material starts from. */
+ params: Array<{ name: string; type: 'float' | 'vec2' | 'vec3' | 'vec4' | 'color' | 'int' | 'texture'; value: number[] | string }>;
+ /** What the engine does not do the way the effect asked: the shader still converts, and says so. */
+ approximations: string[];
+}
+
+export interface PassConversion {
+ shader: ConvertedShader | null;
+ /** Why there is no shader: what the pass needs that the engine's stage does not give. */
+ unsupported: string | null;
+ /** `.esmaterial` render state. */
+ state: { blendMode: number; depthTest: boolean; depthWrite: boolean; cull: number };
+}
+
+// ---------------------------------------------------------------------------
+// Render state
+// ---------------------------------------------------------------------------
+
+const FACTOR = (v: unknown): string => String(v ?? '').toLowerCase();
+
+/** The engine's blend mode for a Cocos blend target, or null where the pair is none of the engine's. */
+function blendModeOf(blend: unknown): number {
+ const targets = (blend as { targets?: Array<Record<string, unknown>> } | null)?.targets;
+ const t = targets?.[0];
+ if (!t || t.blend === false || t.blend === undefined) return 9; // BlendMode.None: the source replaces
+ const src = FACTOR(t.blendSrc ?? 'one');
+ const dst = FACTOR(t.blendDst ?? 'zero');
+ if (src === 'src_alpha' && dst === 'one_minus_src_alpha') return 0;
+ if (src === 'src_alpha' && dst === 'one') return 1;
+ if ((src === 'dst_color' || src === 'zero') && (dst === 'one_minus_src_alpha' || dst === 'src_color')) return 2;
+ if (src === 'one' && dst === 'one_minus_src_color') return 3;
+ if (src === 'one' && dst === 'one_minus_src_alpha') return 4;
+ if (src === 'one' && dst === 'one') return 5;
+ return 0;
+}
+
+function cullOf(rasterizer: unknown): number {
+ const c = FACTOR((rasterizer as { cullMode?: unknown } | null)?.cullMode ?? 'back');
+ return c === 'none' ? 0 : c === 'front' ? 2 : 1;
+}
+
+function stateOf(pass: EffectPass): PassConversion['state'] {
+ const ds = (pass.depthStencil ?? {}) as { depthTest?: boolean; depthWrite?: boolean };
+ return {
+ blendMode: blendModeOf(pass.blend),
+ depthTest: ds.depthTest ?? true,
+ depthWrite: ds.depthWrite ?? true,
+ cull: cullOf(pass.rasterizer),
+ };
+}
+
+// ---------------------------------------------------------------------------
+// Programs
+// ---------------------------------------------------------------------------
+
+const stripComments = (s: string): string => s.replace(/\/\*[\s\S]*?\*\//g, '').replace(/\/\/[^\n]*/g, '');
+
+/** The names a vertex stage may use and still be the engine's standard transform. */
+const STANDARD_VERTEX_TOKENS = new Set([
+ 'cc_matWorld', 'cc_matView', 'cc_matProj', 'cc_matViewProj', 'a_position', 'a_texCoord', 'a_color', 'a_normal',
+]);
+
+/** Whether a vertex stage only places the vertex: nothing in it needs more than the engine's own. Null when it does; else why not. */
+function customVertexReason(ref: string, effect: CocosEffect): string | null {
+ const [program, entry] = ref.split(':');
+ if (!program) return 'the pass names no vertex program';
+ const found = effect.programs.get(program);
+ // A chunk of the Creator install (`legacy/main-functions/general-vs`): the standard vertex stage of an unlit or lit mesh.
+ // A program the Creator install supplies (`general-vs`, `legacy/main-functions/general-vs`): the standard vertex stage of a mesh or a quad.
+ if (!found) return /^(?:(?:general|unlit|sprite|standard)-vs|legacy\/main-functions\/(?:general|unlit|standard)-vs)$/.test(program) ? null : `vertex program ${program} is not in the effect`;
+ const code = stripComments(found.source);
+ // Its own entry only: a helper another stage shares may use more.
+ void entry;
+ if (/\b#include\s*<legacy\/main-functions\/(general|unlit)-vs>/.test(code) && !/\bvoid\s+main\b/.test(code)) return null;
+ const used = new Set<string>([...code.matchAll(/\b((?:cc|a)_[A-Za-z0-9_]+)\b/g)].map((m) => m[1]!));
+ const extra = [...used].filter((u) => !STANDARD_VERTEX_TOKENS.has(u) && !u.startsWith('a_'));
+ const attrs = [...used].filter((u) => u.startsWith('a_') && !STANDARD_VERTEX_TOKENS.has(u));
+ if (extra.length > 0) return `its vertex program reads ${extra.join(', ')}`;
+ if (attrs.length > 0) return `its vertex program reads the attributes ${attrs.join(', ')}`;
+ if (/\btexture\s*\(|\bsin\s*\(|\bcos\s*\(/.test(code)) return 'its vertex program computes per-vertex displacement';
+ return null;
+}
+
+/** Cocos names for what the engine's vertex stage hands the fragment. */
+const VARYINGS: Record<string, { name: string; glsl: string; mesh?: boolean }> = {
+ v_uv: { name: 'v_texCoord', glsl: 'in vec2 v_texCoord;' },
+ uv0: { name: 'v_texCoord', glsl: 'in vec2 v_texCoord;' },
+ v_color: { name: 'v_color', glsl: 'in vec4 v_color;' },
+ color: { name: 'v_color', glsl: 'in vec4 v_color;' },
+};
+
+/** The world position a Cocos fragment reads as `v_position`. The engine's vertex stage gives the full position to a mesh that has normals and the position in the plane otherwise. */
+const POSITION_VARYING = `#ifdef MESH_NORMALS
+in highp vec3 v_worldXYZ;
+#define cocos_position v_worldXYZ
+#else
+in highp vec2 v_worldPos;
+#define cocos_position vec3(v_worldPos, 0.0)
+#endif`;
+const NORMAL_VARYING = `#ifdef MESH_NORMALS
+in highp vec3 v_worldNormal;
+#define cocos_normal v_worldNormal
+#else
+#define cocos_normal vec3(0.0, 0.0, 1.0)
+#endif`;
+
+const PRELUDE = `// Cocos built-ins the converted fragment calls.
+#define CCFragOutput(c) (c)
+#define CC_APPLY_FOG(c, p)
+#define cc_time u_time
+#define CC_HANDLE_RT_SAMPLE_FLIP(uv)
+vec3 LinearToSRGB(vec3 c) { return mix(c * 12.92, 1.055 * pow(c, vec3(1.0 / 2.4)) - 0.055, step(vec3(0.0031308), c)); }
+vec3 SRGBToLinear(vec3 c) { return mix(c / 12.92, pow((c + 0.055) / 1.055, vec3(2.4)), step(vec3(0.04045), c)); }
+`;
+
+/**
+ * A preprocessor expression with each bare macro name asked as `defined(NAME)`: a name that is not defined is 0 in Cocos, and in GLSL ES it is an
+ * error. A name compared with a number (`LEVEL == 2`) is left as it is, which is the one thing a bare switch cannot say.
+ */
+function definedForm(expr: string): string {
+ const kept: string[] = [];
+ const guarded = expr.replace(/\bdefined\s*(?:\(\s*\w+\s*\)|\s+\w+)/g, (m) => { kept.push(m); return `\u0001${kept.length - 1}\u0001`; });
+ const wrapped = guarded.replace(/\b([A-Z][A-Z0-9_]+)\b(?!\s*(?:==|!=|<=|>=|<|>))(?<!(?:==|!=|<=|>=|<|>)\s*[A-Z][A-Z0-9_]*)/g, 'defined($1)');
+ return wrapped.replace(/\u0001(\d+)\u0001/g, (_m, i: string) => kept[Number(i)]!);
+}
+
+type ParamType = ConvertedShader['params'][number]['type'];
+
+function paramTypeOf(glsl: string, prop: EffectProperty | undefined): ParamType {
+ if (glsl === 'float') return 'float';
+ if (glsl === 'int' || glsl === 'bool') return 'int';
+ if (glsl === 'vec2') return 'vec2';
+ if (glsl === 'vec3') return prop?.editorType === 'color' ? 'color' : 'vec3';
+ return prop?.editorType === 'color' ? 'color' : 'vec4';
+}
+
+const TEXTURE_DEFAULTS: Record<string, string> = { white: 'white', grey: 'grey', gray: 'grey', black: 'black', normal: 'normal', default: 'white' };
+
+const csv = (v: number[]): string => v.map((x) => String(+x.toFixed(6))).join(',');
+
+function numbersOf(value: unknown, n: number): number[] {
+ const arr = Array.isArray(value) ? value.map(Number) : typeof value === 'number' ? [value] : [];
+ while (arr.length < n) arr.push(0);
+ return arr.slice(0, n).map((x) => (Number.isFinite(x) ? x : 0));
+}
+
+const ARITY: Record<string, number> = { float: 1, int: 1, vec2: 2, vec3: 3, vec4: 4, color: 4 };
+
+/** Convert one pass. The effect's name is the shader's. */
+export function convertPass(effect: CocosEffect, pass: EffectPass, shaderName: string): PassConversion {
+ const state = stateOf(pass);
+ const vertex = customVertexReason(pass.vert, effect);
+ if (vertex) return { shader: null, unsupported: vertex, state };
+ const [fragProgram, fragEntry = 'frag'] = pass.frag.split(':');
+ const program = effect.programs.get(fragProgram ?? '');
+ if (!program) return { shader: null, unsupported: `fragment program ${fragProgram} is not in the effect`, state };
+
+ const approximations: string[] = [];
+ const props = new Map(pass.properties.map((p) => [p.name, p]));
+ const params: ConvertedShader['params'] = [];
+ const declared = new Set<string>();
+ let body = program.source;
+
+ // The programs it includes: named by what they give, which the prelude gives.
+ const includes = [...body.matchAll(/#include\s*<([^>]+)>/g)].map((m) => m[1]!);
+ for (const inc of includes) {
+ if (/fog-fs|output|embedded-alpha|alpha-test|common-define|cc-global|cc-local|gamma/.test(inc)) continue;
+ return { shader: null, unsupported: `it includes ${inc}, which the engine has no counterpart for`, state };
+ }
+ if (includes.some((i) => /fog-fs/.test(i))) approximations.push('fog is not applied');
+
+ body = body.replace(/^\s*#include\s*<[^>]+>\s*$/gm, '').replace(/^\s*precision\s+\w+\s+float\s*;\s*$/gm, '').replace(/^\s*#pragma\s+builtin\([^)]*\)\s*$/gm, '');
+
+ // The Constant block's members become parameters; the block goes.
+ body = body.replace(/(?:layout\s*\([^)]*\)\s*)?uniform\s+(\w+)\s*\{([\s\S]*?)\}\s*;?/g, (_m, block: string, members: string) => {
+ if (block === 'AlphaTestConstants' || block === 'ALPHA_TEST_CONSTANTS') { members = 'float alphaThreshold;'; }
+ for (const decl of members.split(';')) {
+ const m = /^\s*(?:highp\s+|mediump\s+|lowp\s+)?(float|int|bool|vec2|vec3|vec4)\s+(\w+)\s*$/.exec(decl.replace(/\/\/[^\n]*/g, '').trim());
+ if (!m) continue;
+ const [, glsl, name] = m as unknown as [string, string, string];
+ if (declared.has(name)) continue;
+ declared.add(name);
+ const prop = props.get(name);
+ const type = paramTypeOf(glsl, prop);
+ params.push({ name, type, value: numbersOf(prop?.value ?? (name === 'alphaThreshold' ? 0.5 : 0), ARITY[type]!) });
+ }
+ return '';
+ });
+
+ // Samplers: `uniform sampler2D name;` is a texture parameter, bound by the engine.
+ body = body.replace(/(?:layout\s*\([^)]*\)\s*)?uniform\s+(?:highp\s+|mediump\s+|lowp\s+)?sampler(\w+)\s+(\w+)\s*;/g, (_m, dim: string, name: string) => {
+ if (dim !== '2D') { approximations.push(`${name} is a sampler${dim}, which has no counterpart; it reads as a 2D texture`); }
+ if (!declared.has(name)) {
+ declared.add(name);
+ const def = props.get(name)?.value;
+ params.push({ name, type: 'texture', value: TEXTURE_DEFAULTS[String(def)] ?? 'white' });
+ }
+ return '';
+ });
+
+ // Varyings: Cocos's names for what the engine's vertex stage supplies. One it does not supply is the pass's reason not to convert.
+ const needed = new Set<string>();
+ const renames = new Map<string, string>();
+ body = body.replace(/^\s*in\s+(?:highp\s+|mediump\s+|lowp\s+)?(\w+)\s+(\w+)\s*;\s*$/gm, (_m, _type: string, name: string) => {
+ const v = VARYINGS[name];
+ if (v) { needed.add(v.glsl); renames.set(name, v.name); return ''; }
+ if (name === 'v_position' || name === 'v_worldPos') { needed.add(POSITION_VARYING); renames.set(name, 'cocos_position'); return ''; }
+ if (name === 'v_normal') { needed.add(NORMAL_VARYING); renames.set(name, 'cocos_normal'); return ''; }
+ needed.add(`/* the vertex stage does not supply ${name} */`);
+ return '';
+ });
+ const missing = [...needed].filter((n) => n.startsWith('/*'));
+ if (missing.length > 0) return { shader: null, unsupported: `its fragment reads ${missing.map((m) => /supply (\w+)/.exec(m)![1]).join(', ')}, which the engine's vertex stage does not supply`, state };
+ for (const [from, to] of renames) if (from !== to) body = body.replace(new RegExp(`\\b${from}\\b`, 'g'), to);
+ const usesPosition = needed.has(POSITION_VARYING);
+ if (usesPosition) approximations.push('v_position is the world position of the draw: the engine gives the full position to meshes with normals, and the plane position to sprites');
+
+ // GLSL 1.00 spellings of the 3.00 functions, which Cocos's own compiler accepts.
+ body = body.replace(/\btexture2D\s*\(/g, 'texture(').replace(/\btextureCube\s*\(/g, 'texture(').replace(/\btexture2DLodEXT\s*\(/g, 'textureLod(');
+
+ // An atlas whose alpha is kept apart (ETC1) is sampled by a helper; here a texture holds its own alpha, so it is a plain sample. Spelt out, not
+ // a macro: the engine's twin tool finds a batch texture by the form `texture(u_textures[N], …)`.
+ body = body.replace(/\bCCSampleWithAlphaSeparated\s*\(/g, 'texture(');
+
+ // The sprite's own texture: the engine binds it as the first of the batch's textures.
+ let usesSpriteTexture = false;
+ if (/\bcc_spriteTexture\b/.test(body)) {
+ usesSpriteTexture = true;
+ body = body.replace(/\bcc_spriteTexture\b/g, 'u_textures[0]');
+ }
+
+ // Cocos's scene values (`cc_ambientSky`, `cc_cameraPos`): the engine has no counterpart at the fragment, so each is a parameter of the material
+ // that starts at a value that changes nothing, which the project can set where it had a scene setting.
+ 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],
+ };
+ for (const [name, value] of Object.entries(sceneValues)) {
+ if (!new RegExp(`\\b${name}\\b`).test(body) || declared.has(name)) continue;
+ declared.add(name);
+ params.push({ name, type: 'vec4', value });
+ approximations.push(`${name} is a parameter of the material, not the scene's`);
+ }
+
+ // Alpha test: a parameter and a discard, behind the switch the effect uses.
+ if (/\bALPHA_TEST\s*\(/.test(body)) {
+ if (!declared.has('alphaThreshold')) { declared.add('alphaThreshold'); params.push({ name: 'alphaThreshold', type: 'float', value: [0.5] }); }
+ body = `#define ALPHA_TEST(c) if ((c).a < alphaThreshold) discard;\n${body}`;
+ }
+
+ // The entry: `vec4 frag()` is the fragment's colour.
+ const entry = new RegExp(`\\bvec4\\s+${fragEntry}\\s*\\(\\s*\\)`);
+ if (!entry.test(body)) return { shader: null, unsupported: `the fragment entry ${fragEntry}() is not there`, state };
+ body = body.replace(entry, 'vec4 cocos_frag()');
+
+ // Cocos reads a macro that is not defined as 0 in `#if`; GLSL ES refuses an undefined name there. A switch is defined when it is on.
+ body = body.replace(/^([ \t]*#[ \t]*(?:el)?if)([ \t]+.*)$/gm, (_m, directive: string, expr: string) => `${directive}${definedForm(expr)}`);
+
+ // Macros: what the code branches on is a switch a material turns on.
+ const found = macrosIn(body);
+ const switches = found.switches.filter((s) => !/^(MESH_NORMALS|GL_ES|CC_[A-Z_]+_ENABLED)$/.test(s) && !found.compared.includes(s));
+ if (found.compared.length > 0) approximations.push(`${found.compared.join(', ')} is compared to a number; the engine's switches are on or off`);
+
+ const lines: string[] = [
+ `#pragma shader "${shaderName}"`,
+ '#pragma version 300 es',
+ usesPosition ? '#pragma domain Lit' : '#pragma domain Unlit',
+ ];
+ for (const s of switches) lines.push(`#pragma switch ${s} default(${pass.macros[s] ? 'on' : 'off'})`);
+ for (const p of params) {
+ lines.push(p.type === 'texture'
+ ? `#pragma param ${p.name} texture default(${p.value})`
+ : `#pragma param ${p.name} ${p.type} default(${csv(p.value as number[])})`);
+ }
+ lines.push('', '#pragma fragment', 'precision mediump float;', '', ...[...needed].filter((n) => !n.startsWith('/*')).map((n) => n), '',
+ ...(usesSpriteTexture ? ['uniform sampler2D u_textures[8];'] : []), 'out vec4 fragColor;', '', PRELUDE, body.trim(), '', 'void main() {', ' fragColor = cocos_frag();', '}', '#pragma end', '');
+ return { shader: { source: lines.join('\n'), switches, params, approximations }, unsupported: null, state };
+}
+
+/**
+ * Whether a pass draws an outline: a second draw of the mesh pushed out along its normals and shown from behind. It is a way of drawing the mesh, not
+ * the mesh's own surface, so the pass that is the surface is the one a material is converted from.
+ */
+export function isOutlinePass(pass: EffectPass): boolean {
+ return /outline/i.test(pass.vert) || /outline/i.test(pass.frag);
+}
+
+export interface EffectConversion {
+ /** Each technique's passes, in order. */
+ techniques: Array<{ name: string; passes: PassConversion[] }>;
+}
+
+/** Convert every pass of an effect. @p stem names the shaders. */
+export function convertEffect(effect: CocosEffect, stem: string): EffectConversion {
+ return {
+ techniques: effect.techniques.map((t) => ({
+ name: t.name,
+ passes: t.passes.map((p, i) => convertPass(effect, p, `${stem}.${t.name}.${i}`)),
+ })),
+ };
+}
diff --git a/pipeline/src/import/cocos/effects.ts b/pipeline/src/import/cocos/effects.ts
new file mode 100644
index 000000000..605e51f86
--- /dev/null
+++ b/pipeline/src/import/cocos/effects.ts
@@ -0,0 +1,180 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file effects.ts
+ * @brief Reading a Cocos `.effect` file: its technique/pass/property description and its GLSL programs.
+ *
+ * An effect is one text file of two kinds of block: `CCEffect %{ … }%`, YAML describing the techniques, their passes (which program is the
+ * vertex stage and which the fragment, the blend, depth and cull state) and each pass's properties; and `CCProgram name %{ … }%`, GLSL 3.00
+ * that the passes name as `program:entry`. The programs `#include <builtin/…>` chunks of the Creator install and declare the uniform blocks
+ * they read. This reads both into data; turning that into an Estella material is the converter's job (effectConvert.ts), and what an
+ * effect needs of the renderer, which decides whether it can be converted at all, is {@link describeEffect}.
+ */
+import yaml from 'js-yaml';
+
+export interface EffectProperty {
+ name: string;
+ /** The declared default, as written: a number, a vector, or a texture default name (`white`, `grey`, `normal`, …). */
+ value: unknown;
+ /** The editor's type for it (`color`, `vector`, …), which tells a colour from a vector. */
+ editorType: string | null;
+ /** The uniform (or sampler) the property is stored in, when it says: `target: baseColor.rgb`. */
+ target: string | null;
+}
+
+export interface EffectPass {
+ /** `program:entry` of each stage as written. */
+ vert: string;
+ frag: string;
+ /** Macro defines the pass fixes (`embeddedMacros`). */
+ macros: Record<string, unknown>;
+ blend: unknown;
+ depthStencil: unknown;
+ rasterizer: unknown;
+ /** The pass's phase (`forward-add`, a custom pipeline's name…), which says which part of the frame draws it. */
+ phase: string | null;
+ properties: EffectProperty[];
+ /** The pass is a reference to another effect's pass (`switch`, `pass: builtin-xxx`) rather than its own. */
+ inherits: string | null;
+}
+
+export interface EffectProgram {
+ name: string;
+ source: string;
+}
+
+export interface CocosEffect {
+ techniques: Array<{ name: string; passes: EffectPass[] }>;
+ programs: Map<string, EffectProgram>;
+}
+
+const BLOCK = /(CCEffect|CCProgram)\s*([A-Za-z0-9_\-.]*)\s*%\{([\s\S]*?)\}%/g;
+
+/** Read an effect file's blocks. A file with no CCEffect has no techniques. Throws on YAML it cannot read. */
+export function parseEffect(text: string): CocosEffect {
+ const effect: CocosEffect = { techniques: [], programs: new Map() };
+ for (const m of text.matchAll(BLOCK)) {
+ const [, kind, name, body] = m;
+ if (kind === 'CCProgram') { effect.programs.set(name!, { name: name!, source: body! }); continue; }
+ const doc = yaml.load(body!) as { techniques?: unknown[] } | null;
+ for (const [i, t] of (doc?.techniques ?? []).entries()) {
+ const tech = t as { name?: string; passes?: unknown[] };
+ effect.techniques.push({
+ name: tech.name ?? `technique${i}`,
+ passes: (tech.passes ?? []).map((p) => passOf(p as Record<string, unknown>)),
+ });
+ }
+ }
+ return effect;
+}
+
+function passOf(p: Record<string, unknown>): EffectPass {
+ const props = (p.properties ?? {}) as Record<string, unknown>;
+ return {
+ vert: String(p.vert ?? ''),
+ frag: String(p.frag ?? ''),
+ macros: (p.embeddedMacros ?? {}) as Record<string, unknown>,
+ blend: p.blendState ?? null,
+ depthStencil: p.depthStencilState ?? null,
+ rasterizer: p.rasterizerState ?? null,
+ phase: typeof p.phase === 'string' ? p.phase : null,
+ inherits: typeof p.switch === 'string' ? p.switch : typeof p.pass === 'string' ? p.pass : null,
+ properties: Object.entries(props).map(([name, def]) => {
+ const d = (def ?? {}) as { value?: unknown; editor?: { type?: string }; target?: string };
+ return { name, value: d.value ?? null, editorType: d.editor?.type ?? null, target: d.target ?? null };
+ }),
+ };
+}
+
+// ---------------------------------------------------------------------------
+// What an effect asks of the renderer
+// ---------------------------------------------------------------------------
+
+export interface EffectFacts {
+ passes: number;
+ techniques: number;
+ phases: string[];
+ /** `builtin/…` and `common/…` chunks the programs include. */
+ includes: string[];
+ /** The Cocos uniform blocks and built-in uniforms the shader code reads (`cc_time`, `cc_matWorld`, …). */
+ builtinUniforms: string[];
+ /** The vertex attributes the vertex program reads. */
+ attributes: string[];
+ samplers: number;
+ properties: number;
+ /** Macros the programs branch on (`#if USE_TEXTURE`). */
+ macros: string[];
+ /** Reads the frame behind it, or the depth: not a function of the object alone. */
+ readsFrame: boolean;
+ readsDepth: boolean;
+ /** Uses the scene's lights or shadows: needs what the renderer's lighting provides. */
+ usesLighting: boolean;
+ usesShadow: boolean;
+ skinned: boolean;
+ instanced: boolean;
+ /** What kind of thing it draws, by its stages: a sprite/UI quad, a mesh, a particle, a screen pass. */
+ kind: 'sprite' | 'mesh' | 'particle' | 'screen' | 'other';
+}
+
+const unique = (xs: Iterable<string>): string[] => [...new Set(xs)].sort();
+
+/**
+ * The macros a program branches on: every name in an `#if`, `#elif`, `#ifdef` or `#ifndef`, wherever it stands in the expression. A name a number
+ * is compared with (`LEVEL == 2`) is in the second list, since a switch cannot say it.
+ */
+export function macrosIn(source: string): { switches: string[]; compared: string[] } {
+ const switches = new Set<string>(), compared = new Set<string>();
+ const code = source.replace(/\/\*[\s\S]*?\*\//g, '').replace(/\/\/[^\n]*/g, '');
+ for (const m of code.matchAll(/^[ \t]*#[ \t]*(if|elif|ifdef|ifndef)\b(.*)$/gm)) {
+ const expr = m[2]!.replace(/\bdefined\b/g, ' ');
+ for (const t of expr.matchAll(/\b([A-Z][A-Z0-9_]+)\b(\s*(?:==|!=|<=|>=|<|>))?/g)) {
+ (t[2] ? compared : switches).add(t[1]!);
+ }
+ }
+ return { switches: [...switches].sort(), compared: [...compared].sort() };
+}
+
+/** The facts about one effect that decide how it can be taken across. Reads the passes' programs, not their names. */
+export function describeEffect(effect: CocosEffect, file = ''): EffectFacts {
+ const passes = effect.techniques.flatMap((t) => t.passes);
+ const stageNames = new Set<string>();
+ const vertNames = new Set<string>();
+ for (const p of passes) {
+ for (const ref of [p.vert, p.frag]) if (ref) stageNames.add(ref.split(':')[0]!);
+ if (p.vert) vertNames.add(p.vert.split(':')[0]!);
+ }
+ const source = [...stageNames].map((n) => effect.programs.get(n)?.source ?? '').join('\n');
+ const vertSource = [...vertNames].map((n) => effect.programs.get(n)?.source ?? '').join('\n');
+ const includes = [...source.matchAll(/#include\s*<([^>]+)>/g)].map((m) => m[1]!);
+ const builtinUniforms = [...source.matchAll(/\b(cc_[A-Za-z0-9_]+)\b/g)].map((m) => m[1]!);
+ const attributes = [...vertSource.matchAll(/^\s*in\s+(?:highp\s+|mediump\s+|lowp\s+)?\w+\s+(a_\w+)/gm)].map((m) => m[1]!);
+ const macros = macrosIn(source).switches;
+ const samplers = [...source.matchAll(/uniform\s+(?:highp\s+|mediump\s+|lowp\s+)?sampler\w+\s+\w+/g)].length;
+ const has = (re: RegExp): boolean => re.test(source);
+ const lower = file.toLowerCase();
+ const attrs = new Set(attributes);
+ let kind: EffectFacts['kind'] = 'other';
+ if (/particle|trail/.test(lower) || attrs.has('a_dir') || attrs.has('a_texCoord1')) kind = 'particle';
+ else if (attrs.has('a_normal') || attrs.has('a_tangent') || attrs.has('a_joints')) kind = 'mesh';
+ else if (/bloom|post|blur|screen/.test(lower) || has(/cc_screenSize|cc_spriteTexture.*RT/)) kind = 'screen';
+ else if (attrs.has('a_position') && attrs.has('a_texCoord') && attrs.has('a_color')) kind = 'sprite';
+ else if (attrs.has('a_position')) kind = 'mesh';
+ return {
+ passes: passes.length,
+ techniques: effect.techniques.length,
+ phases: unique(passes.map((p) => p.phase).filter((x): x is string => !!x)),
+ includes: unique(includes),
+ builtinUniforms: unique(builtinUniforms),
+ attributes: unique(attributes),
+ samplers,
+ properties: passes.reduce((n, p) => n + p.properties.length, 0),
+ macros: unique(macros),
+ readsFrame: has(/cc_gbuffer|cc_(?:grab|screen)Tex|SAMPLE_FROM_RT|frameBuffer|sceneColor/i),
+ readsDepth: has(/cc_depth|depthTex|cc_gbufferDepth/i),
+ usesLighting: includes.some((i) => /lighting|cc-forward-light|shading|pbr|standard-surface/i.test(i)) || has(/cc_mainLitDir|CCStandardShading|CCToon/),
+ usesShadow: includes.some((i) => /shadow/i.test(i)) || has(/cc_shadow|CC_RECEIVE_SHADOW/),
+ skinned: attrs.has('a_joints') || has(/CCSkin|USE_SKINNING/),
+ instanced: has(/USE_INSTANCING|a_matWorld0/),
+ kind,
+ };
+}
diff --git a/pipeline/src/import/cocos/importProject.ts b/pipeline/src/import/cocos/importProject.ts
index e2d6b0865..a4a0737e9 100644
--- a/pipeline/src/import/cocos/importProject.ts
+++ b/pipeline/src/import/cocos/importProject.ts
@@ -22,13 +22,15 @@ import { CocosModels, clipOf, clipPlayOf, mintSidecar, retargetClip } from './mo
import { convertAnimationClip } from './animationClip';
import { convertAnimationGraph } from './animationGraph';
import type { MaterialInfo } from './components';
+import { parseEffect } from './effects';
+import { convertEffect, isOutlinePass, type PassConversion } from './effectConvert';
/**
* 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 = 1;
+export const COCOS_IMPORT_REVISION = 2;
/** 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 {
@@ -395,6 +397,9 @@ export async function importCocosProject(opts: CocosImportOptions): Promise<Impo
material(materialUuid) {
return materialInfo(materialUuid);
},
+ convertedMaterial(materialUuid) {
+ return convertedMaterial(materialUuid);
+ },
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(/\.[^.]+$/, ''), paths: m.use.paths } : null;
@@ -618,6 +623,108 @@ export async function importCocosProject(opts: CocosImportOptions): Promise<Impo
return info;
};
+ // A material of the project's own effect, taken across: the effect's pass becomes a shader of the project, the material's settings become a
+ // 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.
+ type EffectTechnique = { name: string; passes: PassConversion[]; passCount: number; outline: boolean[] };
+ const effects = new Map<string, EffectTechnique[] | null>();
+ const convertedMaterials = new Map<string, { ref: string } | null>();
+ const effectOf = (entry: CocosAssetEntry): EffectTechnique[] | null => {
+ if (effects.has(entry.file)) return effects.get(entry.file) ?? null;
+ let result: EffectTechnique[] | null = null;
+ try {
+ const parsed = parseEffect(readFileSync(entry.file, 'utf8'));
+ const stem = entry.rel.replace(/^assets\//, '').replace(/\.effect$/, '');
+ result = convertEffect(parsed, stem).techniques.map((t, i) => ({ name: t.name, passes: t.passes, passCount: t.passes.length, outline: parsed.techniques[i]!.passes.map(isOutlinePass) }));
+ } catch (err) {
+ report.note('effect-unreadable', `${entry.rel}: ${(err as Error).message.split('\n')[0]}`);
+ }
+ effects.set(entry.file, result);
+ return result;
+ };
+ const FACTORS: Record<number, string> = { 0: 'zero', 1: 'one', 2: 'src_alpha', 3: 'dst_alpha', 4: 'one_minus_src_alpha', 5: 'one_minus_dst_alpha', 6: 'src_color', 7: 'dst_color', 8: 'one_minus_src_color', 9: 'one_minus_dst_color' };
+ const numberOf = (x: unknown, d: number): number => (typeof x === 'number' && Number.isFinite(x) ? x : d);
+ const convertedMaterial = (materialUuid: string): { ref: string } | null => {
+ if (convertedMaterials.has(materialUuid)) return convertedMaterials.get(materialUuid) ?? null;
+ let result: { ref: string } | null = null;
+ try {
+ const mat = index.byUuid.get(materialUuid);
+ if (mat && mat.rel.endsWith('.mtl')) {
+ const json = JSON.parse(readFileSync(mat.file, 'utf8')) as {
+ _effectAsset?: { __uuid__?: string }; _techIdx?: number;
+ _defines?: Array<Record<string, unknown>>; _props?: Array<Record<string, unknown>>;
+ _states?: Array<{ blendState?: { targets?: Array<{ blend?: boolean; blendSrc?: number; blendDst?: number }> }; rasterizerState?: { cullMode?: number }; depthStencilState?: { depthTest?: boolean; depthWrite?: boolean } }>;
+ };
+ // the engine's own look-alikes of Cocos's built-in effects are what a built-in effect becomes, as before
+ const effectEntry = BUILTIN_EFFECTS.has(json._effectAsset?.__uuid__ ?? '') ? undefined : index.byUuid.get(json._effectAsset?.__uuid__ ?? '');
+ const technique = effectEntry && effectEntry.rel.endsWith('.effect') ? effectOf(effectEntry)?.[json._techIdx ?? 0] : undefined;
+ // The pass that is the surface: the first that is not an outline, which is where a material's own settings are (its arrays run by pass).
+ const passIndex = technique ? Math.max(0, technique.outline.findIndex((o) => !o)) : 0;
+ const pass = technique?.passes[passIndex];
+ if (effectEntry && technique && pass) {
+ if (!pass.shader) {
+ report.note('effect-not-converted', `${effectEntry.rel}: ${pass.unsupported}`);
+ } else {
+ if (technique.passCount > 1) report.note('effect-extra-passes', `${effectEntry.rel} (${technique.name}): only pass ${passIndex} is drawn${technique.outline.some(Boolean) ? ' (its outline is not)' : ''}`);
+ for (const a of pass.shader.approximations) report.note('effect-approximated', `${effectEntry.rel}: ${a}`);
+ const shaderRel = outRef(`effects/${effectEntry.rel.replace(/^assets\//, '').replace(/\.effect$/, '')}.${technique.name}.${passIndex}.esshader`);
+ writeText(shaderRel, pass.shader.source);
+ const materialRel = outRef(`materials/${mat.rel.replace(/^assets\//, '').replace(/\.mtl$/, '')}.esmaterial`);
+ const props = (json._props?.[passIndex] ?? json._props?.[0] ?? {}) as Record<string, unknown>;
+ const properties: Record<string, unknown> = {};
+ for (const param of pass.shader.params) {
+ const v = props[param.name];
+ if (v === undefined || v === null) continue;
+ if (param.type === 'texture') {
+ const u = typeof v === 'object' ? (v as { __uuid__?: string }).__uuid__ : undefined;
+ const entry = u ? index.byUuid.get(u.split('@')[0]!) : undefined;
+ if (entry) properties[param.name] = ctx.assetRef(entry);
+ } else if (typeof v === 'number') {
+ properties[param.name] = v;
+ } else if (typeof v === 'object') {
+ const o = v as Record<string, unknown>;
+ if ('r' in o) {
+ const c = { r: numberOf(o.r, 255) / 255, g: numberOf(o.g, 255) / 255, b: numberOf(o.b, 255) / 255, a: numberOf(o.a, 255) / 255 };
+ properties[param.name] = param.type === 'color' ? c : { x: c.r, y: c.g, z: c.b, w: c.a };
+ } else if ('x' in o) {
+ properties[param.name] = param.type === 'color'
+ ? { r: numberOf(o.x, 1), g: numberOf(o.y, 1), b: numberOf(o.z, 1), a: numberOf(o.w, 1) }
+ : { x: numberOf(o.x, 0), y: numberOf(o.y, 0), z: numberOf(o.z, 0), w: numberOf(o.w, 0) };
+ }
+ }
+ }
+ const switches: Record<string, boolean> = {};
+ for (const [name, on] of Object.entries(json._defines?.[passIndex] ?? json._defines?.[0] ?? {})) if (pass.shader.switches.includes(name) && on) switches[name] = true;
+ const state = json._states?.[passIndex] ?? json._states?.[0];
+ const target = state?.blendState?.targets?.[0];
+ let blendMode = pass.state.blendMode;
+ if (target) {
+ const src = FACTORS[target.blendSrc ?? 1], dst = FACTORS[target.blendDst ?? 0];
+ blendMode = target.blend !== true ? 9 : src === 'src_alpha' && dst === 'one' ? 1 : src === 'one' && dst === 'one_minus_src_alpha' ? 4 : src === 'one' && dst === 'one' ? 5 : 0;
+ }
+ const cull = state?.rasterizerState?.cullMode;
+ write(materialRel, {
+ version: '1.0',
+ type: 'material',
+ shader: path.posix.relative(path.posix.dirname(materialRel), shaderRel),
+ blendMode,
+ depthTest: state?.depthStencilState?.depthTest ?? pass.state.depthTest,
+ depthWrite: state?.depthStencilState?.depthWrite ?? pass.state.depthWrite,
+ cull: cull === undefined ? pass.state.cull : cull === 0 ? 0 : cull === 1 ? 2 : 1,
+ ...(Object.keys(switches).length > 0 ? { switches } : {}),
+ properties,
+ });
+ report.note('effect-converted', `${effectEntry.rel} (${technique.name})`);
+ result = { ref: materialRel };
+ }
+ }
+ }
+ } catch {
+ result = null;
+ }
+ convertedMaterials.set(materialUuid, result);
+ return result;
+ };
+
// A material says how its font page is read through the effect it uses; the outline effect mixes an outline colour in by the red channel.
const bakes = new Map<string, boolean>();
const materialBakesOutline = (materialUuid: string): boolean => {
@@ -659,8 +766,8 @@ export async function importCocosProject(opts: CocosImportOptions): Promise<Impo
}
})();
const digest = (text: string): string => createHash('sha1').update(text).digest('hex');
- const write = (relPath: string, json: unknown): void => {
- const text = `${JSON.stringify(json, null, 2)}\n`;
+ const write = (relPath: string, json: unknown): void => writeText(relPath, `${JSON.stringify(json, null, 2)}\n`);
+ function writeText(relPath: string, text: string): void {
const file = path.join(out, relPath);
const next = digest(text);
const now = existsSync(file) ? digest(readFileSync(file, 'utf8')) : null;
@@ -674,7 +781,7 @@ export async function importCocosProject(opts: CocosImportOptions): Promise<Impo
}
written[relPath] = next;
if (!opts.dryRun && now !== next) writeOut(file, text);
- };
+ }
const byRel = new Map<string, CocosAssetEntry>();
for (const e of index.byUuid.values()) byRel.set(e.rel, e);
diff --git a/pipeline/tests/cocos-effect-convert.test.ts b/pipeline/tests/cocos-effect-convert.test.ts
new file mode 100644
index 000000000..69d55be4b
--- /dev/null
+++ b/pipeline/tests/cocos-effect-convert.test.ts
@@ -0,0 +1,142 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file A Cocos `.effect` pass as an Estella `.esshader`: what is read from the effect, what the converted fragment declares, and which passes are
+ * not converted because the engine's vertex stage cannot stand in for theirs.
+ */
+import { describe, expect, it } from 'vitest';
+import { parseEffect, describeEffect } from '../src/import/cocos/effects';
+import { convertEffect } from '../src/import/cocos/effectConvert';
+
+const SPRITE_ADD = `
+CCEffect %{
+ techniques:
+ - passes:
+ - vert: sprite-vs:vert
+ frag: sprite-fs:frag
+ depthStencilState: { depthTest: false, depthWrite: false }
+ blendState:
+ targets:
+ - blend: true
+ blendSrc: src_alpha
+ blendDst: one
+ rasterizerState: { cullMode: none }
+ properties:
+ addColor: { value: [0.0, 0.5, 0.25, 1], editor: { type: color } }
+ addWeight: { value: 1.0 }
+ mainTexture: { value: grey }
+}%
+CCProgram sprite-vs %{
+ precision highp float;
+ #include <builtin/uniforms/cc-global>
+ in vec3 a_position;
+ in vec2 a_texCoord;
+ in vec4 a_color;
+ out vec4 color;
+ out vec2 uv0;
+ vec4 vert () {
+ vec4 pos = cc_matViewProj * vec4(a_position, 1);
+ uv0 = a_texCoord;
+ color = a_color;
+ return pos;
+ }
+}%
+CCProgram sprite-fs %{
+ precision highp float;
+ #include <builtin/internal/alpha-test>
+ in vec4 color;
+ in vec2 uv0;
+ uniform sampler2D mainTexture;
+ uniform Constant {
+ vec4 addColor;
+ float addWeight;
+ };
+ vec4 frag () {
+ vec4 o = texture(mainTexture, uv0) * color;
+ #if USE_GLOW
+ o.rgb += addColor.rgb * addWeight;
+ #endif
+ #if !USE_GLOW && USE_TINT
+ o.rgb *= 0.5;
+ #endif
+ ALPHA_TEST(o);
+ return CCFragOutput(o);
+ }
+}%
+`;
+
+describe('reading an effect', () => {
+ it('reads its techniques, passes and properties, and its programs', () => {
+ const effect = parseEffect(SPRITE_ADD);
+ expect(effect.techniques).toHaveLength(1);
+ const pass = effect.techniques[0]!.passes[0]!;
+ expect(pass.frag).toBe('sprite-fs:frag');
+ expect(pass.properties.map((p) => [p.name, p.editorType])).toEqual([['addColor', 'color'], ['addWeight', null], ['mainTexture', null]]);
+ expect([...effect.programs.keys()]).toEqual(['sprite-vs', 'sprite-fs']);
+ });
+
+ it('says what the programs ask of the renderer', () => {
+ const facts = describeEffect(parseEffect(SPRITE_ADD), 'sprite-add.effect');
+ expect(facts.kind).toBe('sprite');
+ expect(facts.macros).toEqual(['USE_GLOW', 'USE_TINT']);
+ expect(facts.usesLighting).toBe(false);
+ expect(facts.samplers).toBe(1);
+ });
+});
+
+describe('converting a pass', () => {
+ const pass = convertEffect(parseEffect(SPRITE_ADD), 'sprite-add').techniques[0]!.passes[0]!;
+
+ it('turns the Constant block and the samplers into parameters, with the effect\'s defaults', () => {
+ expect(pass.unsupported).toBeNull();
+ const source = pass.shader!.source;
+ expect(source).toContain('#pragma param addColor color default(0,0.5,0.25,1)');
+ expect(source).toContain('#pragma param addWeight float default(1)');
+ expect(source).toContain('#pragma param mainTexture texture default(grey)');
+ expect(source).not.toMatch(/uniform\s+Constant/);
+ expect(source).not.toMatch(/uniform sampler2D mainTexture/);
+ });
+
+ it('takes the engine\'s vertex stage, and the varyings it supplies under their engine names', () => {
+ const source = pass.shader!.source;
+ expect(source).not.toContain('#pragma vertex');
+ expect(source).toContain('in vec2 v_texCoord;');
+ expect(source).toContain('in vec4 v_color;');
+ expect(source).toContain('texture(mainTexture, v_texCoord) * v_color');
+ expect(source).toContain('fragColor = cocos_frag();');
+ });
+
+ it('makes the macros it branches on switches, asked as defined() because an undefined name is an error in GLSL ES', () => {
+ expect(pass.shader!.switches).toEqual(['USE_GLOW', 'USE_TINT']);
+ const source = pass.shader!.source;
+ expect(source).toContain('#pragma switch USE_GLOW default(off)');
+ expect(source).toContain('#if defined(USE_GLOW)');
+ expect(source).toContain('#if !defined(USE_GLOW) && defined(USE_TINT)');
+ });
+
+ it('gives the alpha test its threshold as a parameter', () => {
+ expect(pass.shader!.source).toContain('#pragma param alphaThreshold float default(0.5)');
+ expect(pass.shader!.source).toContain('#define ALPHA_TEST(c) if ((c).a < alphaThreshold) discard;');
+ });
+
+ it('maps the pass\'s blend, depth and cull state', () => {
+ expect(pass.state).toEqual({ blendMode: 1, depthTest: false, depthWrite: false, cull: 0 });
+ });
+});
+
+describe('a pass the engine\'s vertex stage cannot stand in for', () => {
+ const SWAY = SPRITE_ADD.replace('vec4 pos = cc_matViewProj * vec4(a_position, 1);', 'vec4 pos = cc_matViewProj * vec4(a_position + vec3(sin(cc_time.x), 0, 0), 1);');
+
+ it('is not converted, and says what its vertex program does', () => {
+ const swayed = convertEffect(parseEffect(SWAY), 'sway').techniques[0]!.passes[0]!;
+ expect(swayed.shader).toBeNull();
+ expect(swayed.unsupported).toMatch(/cc_time|displacement/);
+ });
+
+ it('is not converted when its fragment reads something the vertex stage does not supply', () => {
+ const odd = SPRITE_ADD.replace('in vec2 uv0;\n uniform sampler2D', 'in vec2 uv0;\n in vec3 v_barycentric;\n uniform sampler2D');
+ const converted = convertEffect(parseEffect(odd), 'odd').techniques[0]!.passes[0]!;
+ expect(converted.shader).toBeNull();
+ expect(converted.unsupported).toContain('v_barycentric');
+ });
+});
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index beaf2e8de..7c6f6cbfd 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -183,6 +183,9 @@ importers:
ffmpeg-static:
specifier: ^5.3.0
version: 5.3.0
+ js-yaml:
+ specifier: 4.3.0
+ version: 4.3.0
meshoptimizer:
specifier: ^1.2.0
version: 1.2.0
@@ -196,6 +199,9 @@ importers:
specifier: ^0.7.0
version: 0.7.0
devDependencies:
+ '@types/js-yaml':
+ specifier: ^4.0.9
+ version: 4.0.9
'@types/node':
specifier: ^25.9.3
version: 25.9.3
@@ -1330,6 +1336,9 @@ packages:
resolution: {integrity: sha512-L3LgimLHXtGkWikKnsPg0/VFx9OGZaC+eN1u4r+OB1XRqH3meBIAVC2zr1WdMH+RHmnRkqliQAOHNJ/E0j/e0Q==}
+ '@types/[email protected]':
+ resolution: {integrity: sha512-k4MGaQl5TGo/iipqb2UDG2UwjXziSWkh0uysQelTlJpX1qGlpUZYm8PnO4DxG1qBomtJUdYJ6qR6xdIah10JLg==}
+
resolution: {integrity: sha512-BQ5aZNSCpj7D6K2ksrRCTmKRLEpnPvWDiLPfoGyhZ++8YtiK9d/3DBKPJgry359X/P1PfruyYwvnvwFjuEiEIg==}
@@ -4773,6 +4782,8 @@ snapshots:
'@types/[email protected]': {}
+ '@types/[email protected]': {}
+
dependencies:
'@types/node': 25.9.3