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: bake material-aware static geometry proxies
yhh78034c431ee6
diff --git a/.github/workflows/build.yml b/.github/workflows/build.ymlindex 275cb0fc2..71524ebec 100644--- a/.github/workflows/build.yml+++ b/.github/workflows/build.yml@@ -111,6 +111,17 @@ jobs:run: node tools/tests/composite-batch.e2e.mjs --webgl-only- name: Check 2D and 3D world residency teardown with genuine headless Chromiumrun: node tools/tests/world-residency.e2e.mjs --webgl-only+ - name: Check baked static proxy geometry and materials+ run: node tools/tests/static-proxy.e2e.mjs --webgl-only+ - name: Upload static proxy observations+ if: always()+ uses: actions/upload-artifact@v7+ with:+ name: static-proxy-webgl2+ path: |+ output/static-proxy/*.png+ output/static-proxy/report.json+ retention-days: 3- name: Upload world residency observationsif: always()uses: actions/upload-artifact@v7@@ -1131,6 +1142,17 @@ jobs:run: node tools/tests/composite-batch.e2e.mjs --webgpu-only- name: Check 2D and 3D world residency teardown on the second backendrun: node tools/tests/world-residency.e2e.mjs --webgpu-only+ - name: Check baked static proxy geometry and materials on the second backend+ run: node tools/tests/static-proxy.e2e.mjs --webgpu-only+ - name: Upload second-backend static proxy observations+ if: always()+ uses: actions/upload-artifact@v7+ with:+ name: static-proxy-webgpu+ path: |+ output/static-proxy/*.png+ output/static-proxy/report.json+ retention-days: 3- name: Upload second-backend world residency observationsif: always()uses: actions/upload-artifact@v7diff --git a/docs/astro/src/content/docs/performance/level-of-detail.mdx b/docs/astro/src/content/docs/performance/level-of-detail.mdxindex 4f2789460..9ad32ee63 100644--- a/docs/astro/src/content/docs/performance/level-of-detail.mdx+++ b/docs/astro/src/content/docs/performance/level-of-detail.mdx@@ -149,14 +149,50 @@ world.insert(tree, Impostor, { screenSize: 0.06, frames: 8, resolution: 1024 });goes round (more `frames` is smaller steps), a card casts no shadow and is not seen from below, and the pictures are taken inPlay and in a built game, not in the editor's own viewport.+## Baking static cluster geometry++Node authoring tools can call `bakeStaticProxy` from `@estella/pipeline` to merge and+simplify an already-partitioned cluster. Each source supplies decoded mesh data, a+world matrix, draw state and an explicit motion/blending classification. The baker+uses the same geometry merge and draw grouping as static batching.++```typescript+import { bakeStaticProxy } from '@estella/pipeline';++const proxy = await bakeStaticProxy(sources, {+ origin: [1000, 0, 2000],+ ratio: 0.25,+ maxWorldError: 0.05,+});+```++The result contains cluster-local meshes, their original draw state, source ids,+before/after triangle and byte counts, measured error and input fingerprints.+Place them at `proxy.origin`. Material, texture, tint, layer, lighting and shadow+differences remain separate draws. The caller writes the mesh assets and resolves+the collected draw identifiers to asset references; this API does not modify a scene.++`maxWorldError` is in world units, so adding a distant building does not enlarge the+allowed error. `ratio` is a target; the error limit can retain more triangles.+Vertex colours and both UV sets contribute to the simplification error. Set+`preserveGeometry: true` on emissive or other sensitive surfaces; any protected+source preserves the geometry of its compatible group while still allowing merging.+`pruneDisconnected: true` permits deletion of entire small disconnected pieces and+requires image comparison. It is off by default.++Moving, deformed, billboard, blended, lightmapped, skinned and morphing surfaces+are reported in `refused`. Keep those surfaces under their existing ownership.+This is the geometry stage of HLOD: texture/emission baking, automatic cell+proxy generation, distance selection and detail/proxy streaming handoff remain separate work.+## What this is not`LODGroup` is about **one object at different sizes**. It is not a streamingsystem: every level's mesh is resident, nothing is loaded or unloaded, and anobject that is `cullSize`-small is simply not drawn rather than removed from theworld. Combining distant objects into one merged proxy (HLOD) and loading a world-in pieces are separate concerns, and there is no general-purpose HLOD that bakes-arbitrary scene objects into a proxy. What exists is specific: the far versions+in pieces are separate concerns. The static proxy baker above does not yet connect+cell proxies to world streaming. Existing runtime choices are the far versionsof plants (`Foliage`, `PlacedFoliage` — see [Foliage](/docs/graphics/foliage/)),the terrain's own distance-based quadtree([Terrain](/docs/graphics/terrain/)), and [static batching](/docs/performance/static-batching/),diff --git a/docs/astro/src/content/docs/zh-cn/performance/level-of-detail.mdx b/docs/astro/src/content/docs/zh-cn/performance/level-of-detail.mdxindex f2bc88e06..7561bafcc 100644--- a/docs/astro/src/content/docs/zh-cn/performance/level-of-detail.mdx+++ b/docs/astro/src/content/docs/zh-cn/performance/level-of-detail.mdx@@ -35,6 +35,33 @@ world.insert(rock, LODGroup, {*编辑器里的 **LOD Group**:正在使用的级别、实体的屏幕占比和各级阈值表。*+## 烘焙静态区域的代理几何++Node 创作工具可以调用 `@estella/pipeline` 的 `bakeStaticProxy`。输入是已经分好区域的静态表面,+包含解码后的网格、世界矩阵、绘制状态,以及明确的运动和混合分类。它复用静态合批的几何合并与绘制分组规则。++```typescript+import { bakeStaticProxy } from '@estella/pipeline';++const proxy = await bakeStaticProxy(sources, {+ origin: [1000, 0, 2000],+ ratio: 0.25,+ maxWorldError: 0.05,+});+```++结果包含区域局部坐标下的网格、原绘制状态、来源 id、简化前后的三角形和字节数、实际误差及输入指纹。+将代理放在 `proxy.origin`。材质、纹理、颜色、层、照明和投影设置不同的表面会保留为不同绘制组。+调用方负责写入网格资源,并将采集的绘制标识转换为资源引用;这个接口不会直接修改场景。++`maxWorldError` 使用世界单位,不会因为区域里增加了一栋远处的建筑而放宽精度。`ratio` 是目标,+误差限制可能让结果保留更多三角形。顶点颜色和两套 UV 都参与误差计算。+发光或其他敏感表面应设置 `preserveGeometry: true`:兼容组里只要有受保护的表面,整组就保留几何,仍可合并绘制。+`pruneDisconnected: true` 允许删除小的独立构件,默认关闭,启用后需要对照画面验收。++会运动、变形、朝向相机、透明混合、带光照贴图、骨骼或形态目标的表面会列入 `refused`,由原有逻辑继续管理。+这目前是 HLOD 的几何制作环节;纹理和发光烘焙、自动生成格子代理、距离选择以及精细场景与代理之间的流送交接尚未接通。+## 这些尺寸是屏幕占比,不是距离`lod1Size` 和它的兄弟们,是物体包围体覆盖**视口高度**的比例。`1.0` 表示物体正好一屏高,diff --git a/pipeline/src/index.ts b/pipeline/src/index.tsindex 7b5361ed7..1e2a3ca4f 100644--- a/pipeline/src/index.ts+++ b/pipeline/src/index.ts@@ -24,6 +24,7 @@ export * from './assets/assetMeta';export * from './assets/assetDb';export * from './assets/cookAssets';export * from './assets/addressableManifest';+export * from './world/staticProxy';export * from './bundle/importMap';export * from './bundle/esengineResolve';export * from './bundle/bundleDiagnostics';diff --git a/pipeline/src/world/staticProxy.ts b/pipeline/src/world/staticProxy.tsnew file mode 100644index 000000000..d7b6b4144--- /dev/null+++ b/pipeline/src/world/staticProxy.ts@@ -0,0 +1,121 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file staticProxy.ts+ * @brief Bake a static cluster into material-preserving, simplified geometry proxies.+ */+import { createHash } from 'node:crypto';+import { staticBatchLayout, staticBatchLayoutRefusal, mergeMeshes, planStaticBatches, staticBatchKey, encodeMesh,+ type MeshData, type StaticBatchDrawState, type StaticBatchRefusal } from 'esengine';+import { simplifyMesh } from '../assets/meshSimplify';++/** One placed surface. The collector must classify motion and material blending before baking. */+export interface StaticProxySource {+ entity: number;+ mesh: MeshData;+ world: ArrayLike<number>;+ state: StaticBatchDrawState;+ motion: 'static' | 'dynamic' | 'deformed' | 'billboard';+ blended: boolean;+ /** Preserve high-contrast or emissive geometry until its appearance has a baked replacement. */+ preserveGeometry?: boolean;+ baked?: boolean;+ enabled?: boolean;+}++export interface StaticProxyOptions {+ /** Cluster-local origin; the returned meshes are placed here when drawn. */+ origin: readonly [number, number, number];+ /** Target triangle share, in (0, 1]. The error limit takes precedence. */+ ratio: number;+ /** Maximum simplification error in world units, independent of cluster extent. */+ maxWorldError: number;+ /** Allow entire disconnected pieces to disappear within the error bound. Requires visual review. */+ pruneDisconnected?: boolean;+ /** Vertex budget before simplification. A single larger source remains one group. */+ maxVertices?: number;+}++export interface StaticProxyGroup {+ sources: number[];+ state: StaticBatchDrawState;+ mesh: MeshData;+ trianglesBefore: number;+ trianglesAfter: number;+ bytesBefore: number;+ bytesAfter: number;+ worldError: number;+ preservedGeometry: boolean;+ fingerprint: string;+}++export interface StaticProxyResult {+ origin: [number, number, number];+ groups: StaticProxyGroup[];+ refused: Array<{ entity: number; reason: StaticBatchRefusal | 'deformed' | 'transform' }>;+}++function refusal(source: StaticProxySource): StaticProxyResult['refused'][number]['reason'] | null {+ if (source.enabled === false) return 'disabled';+ if (source.motion === 'dynamic') return 'moves';+ if (source.motion === 'deformed') return 'deformed';+ if (source.motion === 'billboard') return 'billboard';+ if (source.blended) return 'blended';+ if (source.baked) return 'baked';+ if (source.mesh.vertexCount === 0 || source.mesh.indices.length === 0) return 'no-mesh';+ const m = Array.from(source.world);+ if (m.length !== 16 || m.some(value => !Number.isFinite(value))+ || m[3] !== 0 || m[7] !== 0 || m[11] !== 0 || m[15] !== 1) return 'transform';+ const determinant = m[0]! * (m[5]! * m[10]! - m[9]! * m[6]!)+ - m[4]! * (m[1]! * m[10]! - m[9]! * m[2]!) + m[8]! * (m[1]! * m[6]! - m[5]! * m[2]!);+ if (determinant === 0) return 'transform';+ return staticBatchLayoutRefusal(source.mesh);+}++/** Bake one already-partitioned cluster. Refused surfaces remain the caller's responsibility. */+export async function bakeStaticProxy(sources: readonly StaticProxySource[], options: StaticProxyOptions): Promise<StaticProxyResult> {+ if (!Number.isFinite(options.ratio) || options.ratio <= 0 || options.ratio > 1+ || !Number.isFinite(options.maxWorldError) || options.maxWorldError < 0+ || options.origin.length !== 3 || options.origin.some(value => !Number.isFinite(value))+ || (options.maxVertices !== undefined && (!Number.isInteger(options.maxVertices) || options.maxVertices < 3))) {+ throw new Error('Static proxy requires a finite origin, ratio in (0, 1], nonnegative world error and a positive vertex budget');+ }+ const result: StaticProxyResult = { origin: [...options.origin], groups: [], refused: [] };+ const accepted = new Map<number, StaticProxySource>();+ const seen = new Set<number>();+ for (const source of [...sources].sort((a, b) => a.entity - b.entity)) {+ if (!Number.isSafeInteger(source.entity) || seen.has(source.entity)) throw new Error('Static proxy source ids must be unique integers');+ seen.add(source.entity);+ const reason = refusal(source);+ if (reason) result.refused.push({ entity: source.entity, reason });+ else accepted.set(source.entity, source);+ }+ const plan = planStaticBatches([...accepted.values()].map(source => ({+ entity: source.entity, key: staticBatchKey(source.state, staticBatchLayout(source.mesh.channels, source.mesh.vertexStride)),+ center: [0, 0, 0], vertices: source.mesh.vertexCount,+ })), { cellSize: 1, maxVertices: options.maxVertices ?? 262144 });+ const groups = [...plan.batches.map(batch => batch.entities), ...plan.alone.map(entity => [entity])]+ .sort((a, b) => a[0]! - b[0]!);+ for (const ids of groups) {+ const parts = ids.map(entity => accepted.get(entity)!);+ const merged = mergeMeshes(parts.map(source => {+ const world = Array.from(source.world);+ for (let axis = 0; axis < 3; axis++) world[12 + axis]! -= options.origin[axis]!;+ return { mesh: source.mesh, world };+ }));+ const preservedGeometry = parts.some(source => source.preserveGeometry);+ const simplified = preservedGeometry ? null : await simplifyMesh(merged, { ratio: options.ratio, maxError: options.maxWorldError,+ flags: options.pruneDisconnected ? ['ErrorAbsolute', 'Permissive', 'Prune'] : ['ErrorAbsolute', 'Permissive'] });+ const mesh = simplified?.data ?? merged;+ const state = structuredClone(parts[0]!.state);+ const fingerprint = createHash('sha256').update('static-proxy-v1\0')+ .update(JSON.stringify([options.origin, options.ratio, options.maxWorldError, !!options.pruneDisconnected, preservedGeometry,+ staticBatchKey(state, staticBatchLayout(merged.channels, merged.vertexStride)), ids]))+ .update(encodeMesh(merged)).digest('hex');+ result.groups.push({ sources: ids, state, mesh, worldError: simplified?.error ?? 0, preservedGeometry, fingerprint,+ trianglesBefore: merged.indices.length / 3, trianglesAfter: mesh.indices.length / 3,+ bytesBefore: merged.vertices.byteLength + merged.indices.byteLength,+ bytesAfter: mesh.vertices.byteLength + mesh.indices.byteLength });+ }+ return result;+}diff --git a/pipeline/tests/static-proxy.test.ts b/pipeline/tests/static-proxy.test.tsnew file mode 100644index 000000000..71a84892f--- /dev/null+++ b/pipeline/tests/static-proxy.test.ts@@ -0,0 +1,116 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file static-proxy.test.ts+ * @brief Verify static proxy placement, draw boundaries, error budgets and reproducibility.+ */+import { describe, expect, it } from 'vitest';+import { builtinMeshTemplate, composeTRS, encodeMesh, MeshChannel, type MeshData } from 'esengine';+import { bakeStaticProxy, type StaticProxySource } from '../src/world/staticProxy';++const cube = builtinMeshTemplate('builtin:cube')!.build();+const sphere = builtinMeshTemplate('builtin:sphere')!.build();+const placed = (entity: number, x = 0, scale = 1, mesh: MeshData = cube): StaticProxySource => ({+ entity, mesh, world: composeTRS({ x, y: 0, z: 0 }, { x: 0, y: 0, z: 0, w: 1 }, { x: scale, y: scale, z: scale }),+ state: { material: 1, texture: 0, normalMap: 0, color: { r: 1, g: 1, b: 1, a: 1 },+ layer: 0, cullBackfaces: true, lit: true, castShadows: true, parallax: { x: 1, y: 1 }, group: '' },+ motion: 'static', blended: false,+});+const options = { origin: [0, 0, 0] as const, ratio: 0.15, maxWorldError: 0.5 };++describe('bakeStaticProxy', () => {+ it('bakes translated and mirrored parts relative to the cluster origin without changing sources', async () => {+ const a = placed(2, 1010), b = placed(1, 1020, -2);+ const before = encodeMesh(cube).slice();+ const result = await bakeStaticProxy([a, b], { ...options, origin: [1000, 0, 0], ratio: 1 });+ expect(result.groups).toHaveLength(1);+ const group = result.groups[0]!;+ expect(group.sources).toEqual([1, 2]);+ expect(group.mesh.aabbMin).toEqual([-80, -100, -100]);+ expect(group.mesh.aabbMax).toEqual([120, 100, 100]);+ expect(group.mesh.indices.length).toBe(cube.indices.length * 2);+ expect(encodeMesh(cube)).toEqual(before);+ expect(a.world[12]).toBe(1010);+ expect(result.origin).toEqual([1000, 0, 0]);+ });++ it.each(['material', 'texture', 'normalMap', 'layer', 'castShadows', 'lit', 'cullBackfaces', 'color', 'parallax', 'group'] as const)(+ 'keeps %s differences in separate draw groups', async field => {+ const a = placed(1), b = placed(2, 100);+ const changed = { material: 2, texture: 2, normalMap: 2, layer: 2, castShadows: false,+ lit: false, cullBackfaces: false, color: { r: 1, g: 0, b: 0, a: 1 }, parallax: { x: 2, y: 1 }, group: 'other' };+ Object.assign(b.state, { [field]: changed[field] });+ const result = await bakeStaticProxy([a, b], { ...options, ratio: 1 });+ expect(result.groups).toHaveLength(2);+ },+ );++ it('uses an absolute error budget even for a cluster with widely separated parts', async () => {+ const result = await bakeStaticProxy([placed(1, 0, 1, sphere), placed(2, 50000, 2, sphere)], options);+ expect(result.groups).toHaveLength(1);+ const group = result.groups[0]!;+ expect(group.trianglesAfter).toBeLessThan(group.trianglesBefore);+ expect(group.worldError).toBeLessThanOrEqual(options.maxWorldError + 1e-5);+ const data = group.mesh, position = data.channels.find(c => c.semantic === MeshChannel.Position)!;+ const view = new DataView(data.vertices.buffer, data.vertices.byteOffset, data.vertices.byteLength);+ let left = 0, right = 0;+ for (const index of data.indices) {+ const x = view.getFloat32(index * data.vertexStride + position.offset, true);+ if (x < 1000) left++; else right++;+ }+ expect(left).toBeGreaterThan(12);+ expect(right).toBeGreaterThan(12);+ });++ it('reports surfaces that cannot be represented by fixed merged geometry', async () => {+ const sources = Array.from({ length: 8 }, (_, i) => placed(i));+ sources[0]!.motion = 'dynamic'; sources[1]!.motion = 'deformed'; sources[2]!.motion = 'billboard';+ sources[3]!.blended = true; sources[4]!.baked = true; sources[5]!.enabled = false;+ sources[6]!.mesh = { ...cube, inverseBindMatrices: new Float32Array(16) };+ sources[7]!.mesh = { ...cube, morph: { names: ['shape'], hasNormals: false, deltas: new Float32Array(0) } };+ const result = await bakeStaticProxy(sources, options);+ expect(result.groups).toEqual([]);+ expect(result.refused.map(row => row.reason)).toEqual(['moves', 'deformed', 'billboard', 'blended', 'baked', 'disabled', 'skinned', 'morph']);+ });++ it('refuses nonfinite, singular and projective transforms', async () => {+ const sources = [placed(1, NaN), placed(2, 0, 0), placed(3)];+ const projective = Array.from(sources[2]!.world); projective[3] = 1; sources[2]!.world = projective;+ const result = await bakeStaticProxy(sources, options);+ expect(result.groups).toEqual([]);+ expect(result.refused.map(row => row.reason)).toEqual(['transform', 'transform', 'transform']);+ });++ it('keeps reproducible bytes and fingerprints regardless of collection order', async () => {+ const sources = [placed(7, 160), placed(2, -160), placed(4)];+ const first = await bakeStaticProxy(sources, options);+ const second = await bakeStaticProxy([...sources].reverse(), options);+ expect(second.groups.map(group => group.fingerprint)).toEqual(first.groups.map(group => group.fingerprint));+ expect(encodeMesh(second.groups[0]!.mesh)).toEqual(encodeMesh(first.groups[0]!.mesh));+ sources[0]!.state.castShadows = false;+ const changed = await bakeStaticProxy(sources, options);+ expect(changed.groups.map(group => group.fingerprint)).not.toEqual(first.groups.map(group => group.fingerprint));+ });++ it('splits groups at the vertex budget while simplifying singleton groups too', async () => {+ const result = await bakeStaticProxy([placed(1, 0, 1, sphere), placed(2, 300, 1, sphere)],+ { ...options, maxVertices: sphere.vertexCount });+ expect(result.groups).toHaveLength(2);+ expect(result.groups.every(group => group.trianglesAfter < group.trianglesBefore)).toBe(true);+ });++ it('retains protected geometry even when disconnected pruning is requested', async () => {+ const part = placed(1, 0, 1, sphere); part.preserveGeometry = true;+ const result = await bakeStaticProxy([part, placed(2, 200, 1, sphere)], { ...options, pruneDisconnected: true });+ expect(result.groups).toHaveLength(1);+ expect(result.groups[0]!.preservedGeometry).toBe(true);+ expect(result.groups[0]!.trianglesAfter).toBe(result.groups[0]!.trianglesBefore);+ expect(result.groups[0]!.worldError).toBe(0);+ });++ it('rejects ambiguous source ownership and invalid budgets', async () => {+ await expect(bakeStaticProxy([placed(1), placed(1)], options)).rejects.toThrow('unique');+ await expect(bakeStaticProxy([placed(1)], { ...options, ratio: 0 })).rejects.toThrow('ratio');+ await expect(bakeStaticProxy([placed(1)], { ...options, maxWorldError: NaN })).rejects.toThrow('world error');+ });+});diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.mdindex df120208a..0c8857b75 100644--- a/sdk/etc/index.api.md+++ b/sdk/etc/index.api.md@@ -1,7 +1,7 @@# API surface — esengine/index<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 115 public · 164 beta · 2056 experimental · 3 deprecated+Symbols: 115 public · 164 beta · 2060 experimental · 3 deprecated## ABI_LAYOUT_HASH — const @experimental```@@ -10538,6 +10538,20 @@ group: stringstate: number```+## StaticBatchDrawState — interface @experimental+```+castShadows: boolean | undefined+color: { r: number; g: number; b: number; a: number; }+cullBackfaces: boolean+group: string+layer: number+lit: boolean+material: number+normalMap: number+parallax: { x: number; y: number; }+texture: number+```+## StaticBatchGroup — interface @experimental```bytes: number@@ -17231,6 +17245,21 @@ MotionDriver<AnimatorClipMotion>(config: DebugChannelConfig): void```+## staticBatchKey — function @experimental+```+(state: StaticBatchState, layout: string): string+```++## staticBatchLayout — function @experimental+```+(channels: readonly MeshChannelDesc[], stride: number): string+```++## staticBatchLayoutRefusal — function @experimental+```+(mesh: MeshData): StaticBatchRefusal | null+```+## staticBatchPlugin — const @experimental```Plugindiff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.mdindex 016c15cf4..482adbdb7 100644--- a/sdk/etc/index.native.api.md+++ b/sdk/etc/index.native.api.md@@ -1,7 +1,7 @@# API surface — esengine/index.native<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 115 public · 169 beta · 2075 experimental · 3 deprecated+Symbols: 115 public · 169 beta · 2079 experimental · 3 deprecated## ABI_LAYOUT_HASH — const @experimental```@@ -10754,6 +10754,20 @@ group: stringstate: number```+## StaticBatchDrawState — interface @experimental+```+castShadows: boolean | undefined+color: { r: number; g: number; b: number; a: number; }+cullBackfaces: boolean+group: string+layer: number+lit: boolean+material: number+normalMap: number+parallax: { x: number; y: number; }+texture: number+```+## StaticBatchGroup — interface @experimental```bytes: number@@ -17497,6 +17511,21 @@ MotionDriver<AnimatorClipMotion>(config: DebugChannelConfig): void```+## staticBatchKey — function @experimental+```+(state: StaticBatchState, layout: string): string+```++## staticBatchLayout — function @experimental+```+(channels: readonly MeshChannelDesc[], stride: number): string+```++## staticBatchLayoutRefusal — function @experimental+```+(mesh: MeshData): StaticBatchRefusal | null+```+## staticBatchPlugin — const @experimental```Plugindiff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.mdindex 7e170fd02..c4f408c56 100644--- a/sdk/etc/index.node.api.md+++ b/sdk/etc/index.node.api.md@@ -1,7 +1,7 @@# API surface — esengine/index.node<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 115 public · 166 beta · 2055 experimental · 3 deprecated+Symbols: 115 public · 166 beta · 2059 experimental · 3 deprecated## ANCHOR_AXES — const @experimental```@@ -10533,6 +10533,20 @@ group: stringstate: number```+## StaticBatchDrawState — interface @experimental+```+castShadows: boolean | undefined+color: { r: number; g: number; b: number; a: number; }+cullBackfaces: boolean+group: string+layer: number+lit: boolean+material: number+normalMap: number+parallax: { x: number; y: number; }+texture: number+```+## StaticBatchGroup — interface @experimental```bytes: number@@ -17236,6 +17250,21 @@ MotionDriver<AnimatorClipMotion>(config: DebugChannelConfig): void```+## staticBatchKey — function @experimental+```+(state: StaticBatchState, layout: string): string+```++## staticBatchLayout — function @experimental+```+(channels: readonly MeshChannelDesc[], stride: number): string+```++## staticBatchLayoutRefusal — function @experimental+```+(mesh: MeshData): StaticBatchRefusal | null+```+## staticBatchPlugin — const @experimental```Plugindiff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.mdindex 964b54846..5921c509e 100644--- a/sdk/etc/minigame.api.md+++ b/sdk/etc/minigame.api.md@@ -1,7 +1,7 @@# API surface — esengine/minigame<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 115 public · 164 beta · 2077 experimental · 3 deprecated+Symbols: 115 public · 164 beta · 2081 experimental · 3 deprecated## ANCHOR_AXES — const @experimental```@@ -10829,6 +10829,20 @@ group: stringstate: number```+## StaticBatchDrawState — interface @experimental+```+castShadows: boolean | undefined+color: { r: number; g: number; b: number; a: number; }+cullBackfaces: boolean+group: string+layer: number+lit: boolean+material: number+normalMap: number+parallax: { x: number; y: number; }+texture: number+```+## StaticBatchGroup — interface @experimental```bytes: number@@ -17543,6 +17557,21 @@ MotionDriver<AnimatorClipMotion>(config: DebugChannelConfig): void```+## staticBatchKey — function @experimental+```+(state: StaticBatchState, layout: string): string+```++## staticBatchLayout — function @experimental+```+(channels: readonly MeshChannelDesc[], stride: number): string+```++## staticBatchLayoutRefusal — function @experimental+```+(mesh: MeshData): StaticBatchRefusal | null+```+## staticBatchPlugin — const @experimental```Plugindiff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.mdindex 712029fad..0c63b2fd6 100644--- a/sdk/etc/wechat.api.md+++ b/sdk/etc/wechat.api.md@@ -1,7 +1,7 @@# API surface — esengine/wechat<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 115 public · 164 beta · 2068 experimental · 3 deprecated+Symbols: 115 public · 164 beta · 2072 experimental · 3 deprecated## ANCHOR_AXES — const @experimental```@@ -10540,6 +10540,20 @@ group: stringstate: number```+## StaticBatchDrawState — interface @experimental+```+castShadows: boolean | undefined+color: { r: number; g: number; b: number; a: number; }+cullBackfaces: boolean+group: string+layer: number+lit: boolean+material: number+normalMap: number+parallax: { x: number; y: number; }+texture: number+```+## StaticBatchGroup — interface @experimental```bytes: number@@ -17269,6 +17283,21 @@ MotionDriver<AnimatorClipMotion>(config: DebugChannelConfig): void```+## staticBatchKey — function @experimental+```+(state: StaticBatchState, layout: string): string+```++## staticBatchLayout — function @experimental+```+(channels: readonly MeshChannelDesc[], stride: number): string+```++## staticBatchLayoutRefusal — function @experimental+```+(mesh: MeshData): StaticBatchRefusal | null+```+## staticBatchPlugin — const @experimental```Plugindiff --git a/sdk/src/core-content.ts b/sdk/src/core-content.tsindex 23a8bc616..e37bd0639 100644--- a/sdk/src/core-content.ts+++ b/sdk/src/core-content.ts@@ -868,6 +868,8 @@ export {} from './terrain/provider';export {mergeMeshes, planStaticBatches, STATIC_BATCH_DEFAULTS,+ channelSignature as staticBatchLayout, layoutRefusal as staticBatchLayoutRefusal, staticBatchKey,+ type StaticBatchState as StaticBatchDrawState,type StaticBatchGroup, type StaticBatchLimits, type StaticBatchRefusal, type StaticBatchReport,} from './render/staticBatch';export {diff --git a/tools/fixtures/static-proxy.ts b/tools/fixtures/static-proxy.tsnew file mode 100644index 000000000..54bf6348d--- /dev/null+++ b/tools/fixtures/static-proxy.ts@@ -0,0 +1,53 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file static-proxy.ts+ * @brief Bake one procedural cluster for native material and shadow parity checks.+ */+import { builtinMeshTemplate, composeTRS, encodeMesh } from 'esengine';+import { bakeStaticProxy, type StaticProxySource } from '../../pipeline/src/world/staticProxy';++export async function staticProxyFixture() {+ const origin = [17, 1, -11] as const;+ const sources: StaticProxySource[] = [], entities: any[] = [], fullIds: number[] = [];+ const assets: Record<string, Uint8Array> = {};+ const comp = (type: string, data: unknown) => ({ type, data });+ const add = (id: number, name: string, components: unknown[]) => entities.push({ id, name, parent: null, children: [], visible: true, components });+ for (let i = 0; i < 18; i++) {+ const mesh = i % 2 ? 'builtin:cylinder' : 'builtin:cube';+ const position = { x: origin[0] + (i % 6 - 2.5) * 0.7, y: origin[1] + 0.3, z: origin[2] + (Math.floor(i / 6) - 1) * 0.7 };+ const rotation = { x: 0, y: Math.sin(i * 0.07), z: 0, w: Math.cos(i * 0.07) };+ const scale = { x: i % 5 ? 0.005 : -0.005, y: 0.006, z: 0.005 };+ const color = i % 3 ? { r: 0.2, g: 0.7, b: 0.8, a: 1 } : { r: 0.8, g: 0.3, b: 0.15, a: 1 };+ const state = { material: 0, texture: 0, normalMap: 0, color, layer: 0, cullBackfaces: false,+ castShadows: i % 4 !== 0, lit: true, parallax: { x: 1, y: 1 }, group: '' };+ const id = 100 + i;+ sources.push({ entity: id, mesh: builtinMeshTemplate(mesh)!.build(), world: composeTRS(position, rotation, scale),+ state, motion: 'static', blended: false });+ fullIds.push(id);+ // Symmetric primitives provide an independent reference for mirrored placements.+ add(id, `Source ${i}`, [comp('Transform', { position, rotation, scale: { ...scale, x: Math.abs(scale.x) } }),+ comp('MeshRenderer', { mesh, ...state, opaque: true })]);+ }+ const exact = await bakeStaticProxy(sources, { origin, ratio: 1, maxWorldError: 0 });+ const coarse = await bakeStaticProxy(sources, { origin, ratio: 0.2, maxWorldError: 0.01 });+ const emit = (result: typeof exact, start: number, label: string) => result.groups.map((group, i) => {+ const id = start + i, mesh = `/proxy/${label}-${i}.esmesh`;+ assets[mesh] = encodeMesh(group.mesh);+ add(id, `${label} ${i}`, [comp('Transform', { position: { x: origin[0], y: origin[1], z: origin[2] } }),+ comp('MeshRenderer', { ...group.state, mesh, opaque: true, enabled: false })]);+ return id;+ });+ const exactIds = emit(exact, 200, 'exact'), coarseIds = emit(coarse, 300, 'coarse');+ add(1, 'Camera', [comp('Transform', { position: { x: 17, y: 4, z: -4 },+ rotation: { x: Math.sin(-0.19), y: 0, z: 0, w: Math.cos(-0.19) } }),+ comp('Camera', { isActive: true, projectionType: 0, fov: 50, nearPlane: 0.1, farPlane: 100 })]);+ add(2, 'Sun', [comp('Transform', { rotation: { x: -0.3826834324, y: 0, z: 0, w: 0.9238795325 } }),+ comp('Light', { type: 1, intensity: 1.1, meshShadows: true, shadowExtent: 12 })]);+ add(3, 'Ground', [comp('Transform', { position: { x: 17, y: 0.95, z: -11 }, scale: { x: 0.065, y: 1, z: 0.04 } }),+ comp('MeshRenderer', { mesh: 'builtin:plane', lit: true, opaque: true, color: { r: 0.65, g: 0.6, b: 0.55, a: 1 } })]);+ return { scene: { version: 4, name: 'Static proxy validation', entities }, assets, fullIds, exactIds, coarseIds,+ statistics: { sources: sources.length, groups: exact.groups.length,+ fullTriangles: exact.groups.reduce((n, g) => n + g.trianglesBefore, 0),+ coarseTriangles: coarse.groups.reduce((n, g) => n + g.trianglesAfter, 0) } };+}diff --git a/tools/tests/static-proxy.e2e.mjs b/tools/tests/static-proxy.e2e.mjsnew file mode 100644index 000000000..de6cb7349--- /dev/null+++ b/tools/tests/static-proxy.e2e.mjs@@ -0,0 +1,90 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file static-proxy.e2e.mjs+ * @brief Render baked cluster geometry with the engine on both graphics backends.+ */+import { chromium } from 'playwright';+import { build } from 'esbuild';+import { mkdir, writeFile } from 'node:fs/promises';+import { createRequire } from 'node:module';+import { fileURLToPath, pathToFileURL } from 'node:url';+import path from 'node:path';+import assert from 'node:assert/strict';+import { serveHost } from '../lib/staticServer.mjs';+import { requireCurrentEngine } from '../lib/engineBuild.mjs';++const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../..');+const out = path.join(root, 'output/static-proxy');+const { PNG } = createRequire(new URL('../../pipeline/package.json', import.meta.url))('pngjs');+requireCurrentEngine(root, path.join(root, 'build/render-host/wasm'));+await mkdir(out, { recursive: true });+await build({ entryPoints: [path.join(root, 'tools/fixtures/static-proxy.ts')], outfile: path.join(out, 'fixture.mjs'),+ bundle: true, format: 'esm', platform: 'node', alias: { esengine: path.join(root, 'sdk/dist/index.node.js') } });+const fixture = await (await import(pathToFileURL(path.join(out, 'fixture.mjs')).href)).staticProxyFixture();+assert.ok(fixture.statistics.groups < fixture.statistics.sources);+assert.ok(fixture.statistics.coarseTriangles < fixture.statistics.fullTriangles);+const server = await serveHost(path.join(root, 'build/render-host'));+const browser = await chromium.launch({ channel: 'chromium', headless: true,+ args: ['--enable-unsafe-webgpu', '--ignore-gpu-blocklist', '--enable-unsafe-swiftshader', '--mute-audio'] });+assert.ok(!(process.argv.includes('--webgl-only') && process.argv.includes('--webgpu-only')));+const backends = process.argv.includes('--webgl-only') ? ['webgl2'] : process.argv.includes('--webgpu-only') ? ['webgpu'] : ['webgl2', 'webgpu'];+const report = { status: 'failed', statistics: fixture.statistics, cases: [] };+try {+ for (const backend of backends) {+ const page = await browser.newPage({ viewport: { width: 640, height: 400 } }), errors = [];+ page.on('pageerror', error => errors.push(String(error)));+ page.on('console', event => { if (event.type() === 'error') errors.push(event.text()); });+ await page.route('**/favicon.ico', route => route.fulfill({ status: 204 }));+ await page.route('**/proxy/**', route => {+ const name = new URL(route.request().url()).pathname;+ return route.fulfill(name.endsWith('.esscene') ? { json: fixture.scene }+ : { contentType: 'application/octet-stream', body: Buffer.from(fixture.assets[name]) });+ });+ await page.goto(`http://127.0.0.1:${server.address().port}/?w=640&h=400&backend=${backend}`);+ await page.evaluate(async () => { await window.__estellaHeadless.ready; });+ const loaded = await page.evaluate(() => window.__estellaHeadless.api.loadScene('/proxy/fixture.esscene'));+ assert.deepEqual(loaded.missing, []);+ const capture = async label => {+ const raw = await page.evaluate(async () => {+ const { api } = window.__estellaHeadless;+ await api.step(3); await api.waitForShaders(); await api.step(2);+ const pixels = await api.captureViewportPixels();+ return { width: pixels.width, height: pixels.height, rgba: Array.from(pixels.rgba) };+ });+ const image = new PNG({ width: raw.width, height: raw.height }), data = Buffer.from(raw.rgba), stride = raw.width * 4;+ for (let y = 0; y < raw.height; y++) data.copy(image.data, y * stride, (raw.height - y - 1) * stride, (raw.height - y) * stride);+ await writeFile(path.join(out, `${backend}-${label}.png`), PNG.sync.write(image));+ return image;+ };+ const reference = await capture('detail');+ let cyan = 0, red = 0;+ for (let i = 0; i < reference.data.length; i += 4) {+ const [r, g, b] = reference.data.subarray(i, i + 3);+ if (g > r * 1.5 && b > r * 1.5 && g > 40) cyan++;+ if (r > g * 2 && r > b * 2 && r > 40) red++;+ }+ assert.ok(cyan > 1000 && red > 500, `Both material groups must render: cyan=${cyan}, red=${red}`);+ for (const [label, ids] of [['exact', fixture.exactIds], ['coarse', fixture.coarseIds]]) {+ await page.evaluate(({ full, exact, coarse, active }) => {+ const api = window.__estellaHeadless.api;+ for (const id of [...full, ...exact, ...coarse]) api.setField(id, 'MeshRenderer', 'enabled', '', active.includes(id));+ }, { full: fixture.fullIds, exact: fixture.exactIds, coarse: fixture.coarseIds, active: ids });+ const proxy = await capture(label);+ let changed = 0, sum = 0, over8 = 0;+ for (let i = 0; i < reference.data.length; i += 4) {+ let max = 0;+ for (let c = 0; c < 3; c++) { const d = Math.abs(reference.data[i + c] - proxy.data[i + c]); sum += d; max = Math.max(max, d); }+ if (max) changed++; if (max > 8) over8++;+ }+ const pixels = reference.width * reference.height, meanChannel = sum / (pixels * 3);+ report.cases.push({ backend, label, changed, over8, pixels, meanChannel });+ assert.ok(meanChannel < (label === 'exact' ? 0.1 : 1), `${backend} ${label} changed average color by ${meanChannel}`);+ assert.ok(over8 < pixels * (label === 'exact' ? 0.001 : 0.02), `${backend} ${label} changed ${over8} significant pixels`);+ }+ assert.deepEqual(errors, []); await page.close();+ }+ report.status = 'checks-passed';+} catch (error) { report.error = String(error); throw error; }+finally { await writeFile(path.join(out, 'report.json'), JSON.stringify(report, null, 2)); await browser.close(); await new Promise(resolve => server.close(resolve)); }+console.log(JSON.stringify(report));