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(render): the opaque scene can be drawn twice, depth alone first, so a pixel is shaded for the surface in front of it
yhh07021c9cd55f
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 34e5b9de7..c6a9501c9 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -16,6 +16,7 @@ published separately; it ships inside the editor.### Added+- **A depth prepass for the opaque scene.** A quality level can draw the opaque meshes twice, depth alone first, so a pixel is shaded for the surface that is in front of it and not for every one drawn there on the way: `QualityProfile.depthPrepass` (on for `high` and `medium`, off for `low` and with the quality system off), and `renderer_setDepthPrepass` for a host without one. Cut-out leaves take part, with the coverage their own shader writes. The surfaces with a vertex hook (the terrain) do not. On the Terrain & Water example, on an RTX 3060, a frame is 4 to 36 ms shorter, most where trees stand thick.- **A third mesh for a plant.** A part of a world's plants can name `lod2Mesh` and its kind `lod2Distance`: past that distance the third mesh stands in for the cheaper one, until the kind stops being drawn as itself. The Terrain & Water example's trees have one (a tenth of the triangles, made by `tools/plant-lod2.mjs`) from 80 m, which takes 9 to 15 ms off a frame on an RTX 3060 where trees stand between 60 and 170 m. `tools/terrain-water-cost.mjs` measures what each part of that example costs a frame headless, and `docs/TERRAIN_WATER_GPU_COST.md` has the numbers.- **A generated world on worker threads.** A planet provider can give the engine its generator as `workerSource` (the text of a self-contained module), and the world's placements and the planet's pages (heights, normals, and the paint by the biomes) are then worked out by a pool of workers (`runtime/jobs.ts`), byte for byte what the main thread works out, while the main thread only puts each answer in the world as it arrives. Laying out a planet's world no longer costs the frame: 2 to 8 frames a second while it was laid out became 60.- **A flat world's generation on worker threads too.** Laying out a `WorldGen` over a `Terrain` (a field or noise ground, with its baked water) is worked out by the same pool of workers, from the ground and the water handed over as data, byte for byte what the main thread works out. Stopping the terrain-water example no longer leaves the editor at 2 frames a second: it is back at 60.diff --git a/docs/TERRAIN_WATER_GPU_COST.md b/docs/TERRAIN_WATER_GPU_COST.mdindex 392fed832..cc25974f3 100644--- a/docs/TERRAIN_WATER_GPU_COST.md+++ b/docs/TERRAIN_WATER_GPU_COST.md@@ -116,3 +116,34 @@(`ms` 是同一轮里交替量的均值。1 + 2 是精确的重排,每个机位约省 7%;3 + 4 再省约 1 ms,是取舍:窄半影变得稍粗,螺旋逐点旋转,留下的是颗粒而不是条带。)三维阴影的 20 个像素验收(`mesh-shadow*`、`sun-shadow*`、`soft-shadow*`、`spot-shadow`、`point-shadow*`)在 WebGL2 与 WebGPU 上都通过。同一个包两次运行之间云和水就有 2% 到 3% 的像素不同,所以没有做逐像素差的结论。**没有动的:**阴影的 12 到 38 ms 是拿掉阴影后的差,接收端占了其中大部分;这里在默认机位省下约 3.5 ms,花海约 10 ms,约为这个函数成本的三成。剩下的主要是“每个被着色的像素都付 16 个采样”,而植物叶片多层叠,一个像素被着色多次(前向渲染,没有深度预通道)。要再省下去,是深度预通道让被遮住的像素不再着色,而不是继续改这个函数。++## 深度预通道(2026-10-25 第四轮)++前向渲染没有深度预通道:不透明的网格按状态排序、各画各的,一个像素被树叶、草、地面依次着色,最后只有一个留下。树叶是 alpha-to-coverage 的镂空卡片,层叠最多,也是植物里最贵的部分。++**先量:**场景 opaque 网格里,默认机位 1507 个中 1013 个是镂空(`alphaIsCoverage`),只有 494 个是实心的,32 个是顶点被材质弯曲(地形)。只让实心的做预通道,默认机位省 0.6 ms,花海省约 10 ms;让镂空的也做,才是大头。++**做了什么:**+- 渲染管线 `PipelineDesc` 加 `colorWrite`(不写颜色)与 `depthEqual`(深度等于也通过);GL 与 WebGPU 两个后端都实现。+- 一个网格 draw 有 `depth_shader_id`:只写深度的程序,顶点阶段就是它自己的(`mesh.esshader` 的 `SHADOW_DEPTH` 变体,与着色用的是同一份顶点源;`gl_Position` / WGSL 的位置都标了 `invariant`,两个程序算出同一个深度)。+- 镂空材质用新的 `PREPASS_COVERAGE` 变体:写出与着色片元相同的覆盖率(同一个表达式、同一个输入、同一个顺序),所以在 alpha-to-coverage 下两遍画出同样的采样点。只对引擎自己的 `Model` 着色器这样做,别的(头发、自带顶点阶段)留在预通道之外。+- `DrawList::execute` 多了 `DrawPass`:先 `DepthPrepass`,再 `ColorAfterPrepass`(参与的 draw 用 `depthEqual`、不再写深度)。+- 质量档位加 `depthPrepass`:high、medium 开,low 关,质量系统关掉时也关。分块 GPU(手机)上这一遍是几何画两次,所以默认不开。++**没做的:**顶点被材质弯曲的 draw(地形、风吹的植被)不参加。试过让地形的深度程序走 `shadowProgram`,中远景地形块的深度与着色那遍对不上,整块不画出来;原因没有查清,所以关掉了(默认机位去掉它没有损失,地形自己没有过度绘制)。++**同一个包里的开关前后**(`no-prepass` 是 `depthPrepass: false`,RTX 3060,1080p,每个值 5 组 12 帧):++| 机位 | 没有预通道 ms | 有预通道 ms | 差 |+|---|---|---|---|+| 默认 | 34.4 | 30.6 | −3.9 |+| 花海 | 81.1 | 45.0 | −36.1 |+| 湖边 | 69.4 | 48.0 | −21.4 |+| 湖与河口 | 63.8 | 45.8 | −18.0 |+| 沿河 | 50.8 | 40.4 | −10.4 |++三角形数不变;绘制数不变(预通道 607 个 draw,是同一批)。预通道在 `render.prepass.draws`,没有参加的原因在 `render.prepass.cutout`/`bent`/`noProgram`。++**检查:**帧对比没有看到空洞或光晕;与上一个构建的像素差,树和花的带状区域有 0.12% 的像素差大于 24,在同一个包两次运行 0.01% 的参照之上,看截图是远处镂空卡片边缘的取样不同,和重叠的共面卡片在 `LEQUAL` 下谁盖谁。像素验收:原来的 128 个网格/阴影/深度/天空相关的场景在 WebGL2 通过、WebGPU 通过(`device-loss-*` 的四个在 WebGPU 上先前就失败);新增 11 个 `*-prepass` 孪生场景(同一画面、预通道开着,并要求至少有一个 draw 参加),WebGL2 与 WebGPU 都通过。WebGPU 上没有量帧耗时。++**限制:**只在一块 NVIDIA 显卡的 D3D11 上量过;预通道要求两个程序的位置逐位相同,靠 `invariant` 保证,在别的驱动上没有试过(出问题时的表现是着色那遍的像素被深度测试挡掉,画面上有洞)。diff --git a/fixtures/scenes/mesh-lit-opaque.esscene b/fixtures/scenes/mesh-lit-opaque.esscenenew file mode 100644index 000000000..ec0b0607b--- /dev/null+++ b/fixtures/scenes/mesh-lit-opaque.esscene@@ -0,0 +1,106 @@+{+ "version": 4,+ "name": "MeshLitOpaque",+ "entities": [+ {+ "id": 0,+ "name": "Camera",+ "parent": null,+ "children": [],+ "components": [+ {+ "type": "Transform",+ "data": {+ "position": {+ "x": 0,+ "y": 0,+ "z": 10+ }+ }+ },+ {+ "type": "Camera",+ "data": {+ "projectionType": 1,+ "orthoSize": 300,+ "isActive": true,+ "priority": 0+ }+ }+ ],+ "visible": true+ },+ {+ "id": 1,+ "name": "Sun",+ "parent": null,+ "children": [],+ "components": [+ {+ "type": "Transform",+ "data": {+ "position": {+ "x": 0,+ "y": 0,+ "z": 0+ }+ }+ },+ {+ "type": "Light",+ "data": {+ "type": 1,+ "color": {+ "r": 1,+ "g": 1,+ "b": 1,+ "a": 1+ },+ "intensity": 1,+ "direction": {+ "x": 0,+ "y": 0+ },+ "enabled": true+ }+ }+ ],+ "visible": true+ },+ {+ "id": 2,+ "name": "LitTriangles",+ "parent": null,+ "children": [],+ "components": [+ {+ "type": "Transform",+ "data": {+ "position": {+ "x": 0,+ "y": 0,+ "z": 0+ }+ }+ },+ {+ "type": "MeshRenderer",+ "data": {+ "color": {+ "r": 1,+ "g": 1,+ "b": 1,+ "a": 1+ },+ "layer": 0,+ "enabled": true,+ "lit": true,+ "mesh": "/scenes/lit-triangles.esmesh",+ "opaque": true+ }+ }+ ],+ "visible": true+ }+ ]+}diff --git a/fixtures/scenes/mesh-morph-opaque.esscene b/fixtures/scenes/mesh-morph-opaque.esscenenew file mode 100644index 000000000..b20548273--- /dev/null+++ b/fixtures/scenes/mesh-morph-opaque.esscene@@ -0,0 +1,75 @@+{+ "version": 4,+ "name": "MeshMorphOnOpaque",+ "entities": [+ {+ "id": 0,+ "name": "Camera",+ "parent": null,+ "children": [],+ "visible": true,+ "components": [+ {+ "type": "Transform",+ "data": {+ "position": {+ "x": 0,+ "y": 0,+ "z": 10+ }+ }+ },+ {+ "type": "Camera",+ "data": {+ "projectionType": 1,+ "orthoSize": 100,+ "isActive": true,+ "priority": 0+ }+ }+ ]+ },+ {+ "id": 1,+ "name": "Quad",+ "parent": null,+ "children": [],+ "visible": true,+ "components": [+ {+ "type": "Transform",+ "data": {+ "position": {+ "x": 0,+ "y": 0,+ "z": 0+ }+ }+ },+ {+ "type": "MeshRenderer",+ "data": {+ "mesh": "scenes/morph-quad.esmesh",+ "color": {+ "r": 0,+ "g": 1,+ "b": 0,+ "a": 1+ },+ "enabled": true,+ "opaque": true+ }+ },+ {+ "type": "MeshMorph",+ "data": {+ "weights": [+ 1+ ]+ }+ }+ ]+ }+ ]+}diff --git a/fixtures/scenes/mesh-renderer-opaque.esscene b/fixtures/scenes/mesh-renderer-opaque.esscenenew file mode 100644index 000000000..95d9b34dc--- /dev/null+++ b/fixtures/scenes/mesh-renderer-opaque.esscene@@ -0,0 +1,117 @@+{+ "version": 4,+ "name": "MeshRendererOpaque",+ "entities": [+ {+ "id": 0,+ "name": "Camera",+ "parent": null,+ "children": [],+ "components": [+ {+ "type": "Transform",+ "data": {+ "position": {+ "x": 0,+ "y": 0,+ "z": 10+ }+ }+ },+ {+ "type": "Camera",+ "data": {+ "projectionType": 1,+ "orthoSize": 300,+ "isActive": true,+ "priority": 0+ }+ }+ ],+ "visible": true+ },+ {+ "id": 1,+ "name": "TwoTriangles",+ "parent": null,+ "children": [],+ "components": [+ {+ "type": "Transform",+ "data": {+ "position": {+ "x": 0,+ "y": 0,+ "z": 0+ }+ }+ },+ {+ "type": "MeshRenderer",+ "data": {+ "color": {+ "r": 1,+ "g": 1,+ "b": 1,+ "a": 1+ },+ "layer": 0,+ "enabled": true,+ "geometry": {+ "positions": [+ -200,+ -100,+ -40,+ -100,+ -120,+ 100,+ 40,+ -100,+ 200,+ -100,+ 120,+ 100+ ],+ "colors": [+ 1,+ 0,+ 0,+ 1,+ 1,+ 0,+ 0,+ 1,+ 1,+ 0,+ 0,+ 1,+ 0,+ 1,+ 0,+ 1,+ 0,+ 1,+ 0,+ 1,+ 0,+ 1,+ 0,+ 1+ ],+ "indices": [+ 0,+ 1,+ 2,+ 3,+ 4,+ 5+ ]+ },+ "opaque": true+ }+ }+ ],+ "visible": true+ }+ ]+}diff --git a/fixtures/scenes/mesh-skin-opaque.esscene b/fixtures/scenes/mesh-skin-opaque.esscenenew file mode 100644index 000000000..8527b0854--- /dev/null+++ b/fixtures/scenes/mesh-skin-opaque.esscene@@ -0,0 +1,114 @@+{+ "version": 4,+ "name": "MeshSkinOpaque",+ "entities": [+ {+ "id": 0,+ "name": "Camera",+ "parent": null,+ "children": [],+ "components": [+ {+ "type": "Transform",+ "data": {+ "position": {+ "x": 60,+ "y": 20,+ "z": 10+ }+ }+ },+ {+ "type": "Camera",+ "data": {+ "projectionType": 1,+ "orthoSize": 100,+ "isActive": true,+ "priority": 0+ }+ }+ ],+ "visible": true+ },+ {+ "id": 1,+ "name": "Bone0",+ "parent": null,+ "children": [],+ "components": [+ {+ "type": "Transform",+ "data": {+ "position": {+ "x": 0,+ "y": 0,+ "z": 0+ }+ }+ }+ ],+ "visible": true+ },+ {+ "id": 2,+ "name": "Bone1",+ "parent": null,+ "children": [],+ "components": [+ {+ "type": "Transform",+ "data": {+ "position": {+ "x": 60,+ "y": 60,+ "z": 0+ }+ }+ }+ ],+ "visible": true+ },+ {+ "id": 3,+ "name": "Body",+ "parent": null,+ "children": [],+ "components": [+ {+ "type": "Transform",+ "data": {+ "position": {+ "x": 0,+ "y": 0,+ "z": 0+ }+ }+ },+ {+ "type": "MeshRenderer",+ "data": {+ "mesh": "scenes/skinned-arm.esmesh",+ "color": {+ "r": 0,+ "g": 1,+ "b": 0,+ "a": 1+ },+ "enabled": true,+ "opaque": true+ }+ },+ {+ "type": "MeshSkin",+ "data": {+ "joints": [+ 1,+ 2+ ]+ }+ }+ ],+ "visible": true+ }+ ]+}diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.mdindex ebb5ea1d4..62f0b3b88 100644--- a/sdk/etc/index.api.md+++ b/sdk/etc/index.api.md@@ -7655,6 +7655,7 @@ static prototype: QualityController## QualityProfile — interface @experimental```+depthPrepass: booleandetailScale: numberminRenderScale: numbermsaaSamples: 2 | 1 | 4 | 8diff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.mdindex aec219714..47abe5194 100644--- a/sdk/etc/index.native.api.md+++ b/sdk/etc/index.native.api.md@@ -7858,6 +7858,7 @@ static prototype: QualityController## QualityProfile — interface @experimental```+depthPrepass: booleandetailScale: numberminRenderScale: numbermsaaSamples: 2 | 1 | 4 | 8diff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.mdindex 63fa5c0a0..ce5df1f9c 100644--- a/sdk/etc/index.node.api.md+++ b/sdk/etc/index.node.api.md@@ -7650,6 +7650,7 @@ static prototype: QualityController## QualityProfile — interface @experimental```+depthPrepass: booleandetailScale: numberminRenderScale: numbermsaaSamples: 2 | 1 | 4 | 8diff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.mdindex 492f8e049..d03f679c7 100644--- a/sdk/etc/minigame.api.md+++ b/sdk/etc/minigame.api.md@@ -7943,6 +7943,7 @@ static prototype: QualityController## QualityProfile — interface @experimental```+depthPrepass: booleandetailScale: numberminRenderScale: numbermsaaSamples: 2 | 1 | 4 | 8diff --git a/sdk/etc/wasm.api.md b/sdk/etc/wasm.api.mdindex d46783ff7..fadc9edae 100644--- a/sdk/etc/wasm.api.md+++ b/sdk/etc/wasm.api.md@@ -514,6 +514,7 @@ renderer_setClearColor: (r: number, g: number, b: number, a: number) => voidrenderer_setColorSpace: ((linear: number) => void) | undefinedrenderer_setCullingMask: ((mask: number) => void) | undefinedrenderer_setDepthLayers: ((mask: number) => void) | undefined+renderer_setDepthPrepass: ((on: boolean) => void) | undefinedrenderer_setEntityDrawOrder: ((registry: CppRegistry, entitiesPtr: number, count: number) => void) | undefinedrenderer_setLodPreview: ((view: number, entity: number, level: number) => void) | undefinedrenderer_setMeshEdgeBuffers: ((enabled: boolean) => void) | undefineddiff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.mdindex 8adf4f722..0ddc29cfc 100644--- a/sdk/etc/wechat.api.md+++ b/sdk/etc/wechat.api.md@@ -7657,6 +7657,7 @@ static prototype: QualityController## QualityProfile — interface @experimental```+depthPrepass: booleandetailScale: numberminRenderScale: numbermsaaSamples: 2 | 1 | 4 | 8diff --git a/sdk/src/ecs/bridge/nativeEngineApi.generated.ts b/sdk/src/ecs/bridge/nativeEngineApi.generated.tsindex f3cbd5ba6..93289bc64 100644--- a/sdk/src/ecs/bridge/nativeEngineApi.generated.ts+++ b/sdk/src/ecs/bridge/nativeEngineApi.generated.ts@@ -210,6 +210,7 @@ export interface NativeEngineApi {renderer_setColorSpace?(linear: number): void;renderer_setCullingMask?(mask: number): void;renderer_setDepthLayers?(mask: number): void;+ renderer_setDepthPrepass?(on: boolean): void;renderer_setEntityDrawOrder?(registry: unknown, entitiesPtr: number, count: number): void;renderer_setLodPreview?(view: number, entity: number, level: number): void;renderer_setMeshEdgeBuffers?(enabled: boolean): void;@@ -536,6 +537,7 @@ export function createNativeEngineApi(bind('renderer_setColorSpace', 'es_renderer_setColorSpace', false);bind('renderer_setCullingMask', 'es_renderer_setCullingMask', false);bind('renderer_setDepthLayers', 'es_renderer_setDepthLayers', false);+ bind('renderer_setDepthPrepass', 'es_renderer_setDepthPrepass', false);bind('renderer_setEntityDrawOrder', 'es_renderer_setEntityDrawOrder', true);bind('renderer_setLodPreview', 'es_renderer_setLodPreview', false);bind('renderer_setMeshEdgeBuffers', 'es_renderer_setMeshEdgeBuffers', false);diff --git a/sdk/src/render/quality.ts b/sdk/src/render/quality.tsindex 77002cb18..859de5fc4 100644--- a/sdk/src/render/quality.ts+++ b/sdk/src/render/quality.ts@@ -29,6 +29,12 @@ export interface QualityProfile {planarReflectionMaxSize: number;/** Zero means every frame; this never caps the main scene. */planarReflectionUpdatesPerSecond: number;+ /**+ * Whether the opaque scene is drawn twice, depth alone first, so each pixel is shaded for the surface in front of it and not for every one drawn+ * there on the way. It pays where surfaces overlap (a wood, a crowd of foliage) on a GPU that shades what it rasterises; on one that defers+ * shading to the end of a tile it is geometry paid for twice, so the weakest level leaves it off.+ */+ depthPrepass: boolean;postProcess: boolean;ssao: boolean;/** How many of a body of water's four waves are summed: in the geometry, the shading and what the surface answers for code. 1 to 4. */@@ -73,7 +79,7 @@ const PROFILES: Record<QualityLevel, QualityProfile> = {low: {renderScale: 0.75, minRenderScale: 0.5, msaaSamples: 1,shadowAtlasSize: 1024, shadowCellSize: 256, shadowCascades: 2,- planarReflectionScale: 0.25, planarReflectionMaxSize: 512, planarReflectionUpdatesPerSecond: 0,+ planarReflectionScale: 0.25, planarReflectionMaxSize: 512, planarReflectionUpdatesPerSecond: 0, depthPrepass: false,shadowDistance: 0, detailScale: 0.5, particleLimit: 1000, postProcess: true, ssao: false,waterWaves: 2, waterRippleCells: 32, waterDisplacement: false, waterMirror: false, waterCaustics: false,skipEffects: ['ssr', 'taa', 'depthOfField', 'lightShafts', 'motionBlur', 'lensFlare', 'gtao', 'subsurface', 'voxelGI'],@@ -81,7 +87,7 @@ const PROFILES: Record<QualityLevel, QualityProfile> = {medium: {renderScale: 1, minRenderScale: 0.65, msaaSamples: 2,shadowAtlasSize: 2048, shadowCellSize: 512, shadowCascades: 3,- planarReflectionScale: 0.5, planarReflectionMaxSize: 1024, planarReflectionUpdatesPerSecond: 0,+ planarReflectionScale: 0.5, planarReflectionMaxSize: 1024, planarReflectionUpdatesPerSecond: 0, depthPrepass: true,shadowDistance: 0, detailScale: 0.8, particleLimit: 5000, postProcess: true, ssao: true,waterWaves: 3, waterRippleCells: 64, waterDisplacement: true, waterMirror: true, waterCaustics: true,skipEffects: ['ssr', 'depthOfField'],@@ -91,7 +97,7 @@ const PROFILES: Record<QualityLevel, QualityProfile> = {// A face is millimetres of relief: at 512 texels a cascade, a skin-hugging card (a brow, a hairline) falls inside one texel of the skin and the// shadow speckles it with dirt. 1024 is the cell that clears it for a character at arm's length.shadowAtlasSize: 4096, shadowCellSize: 1024, shadowCascades: 4,- planarReflectionScale: 1, planarReflectionMaxSize: 2048, planarReflectionUpdatesPerSecond: 0,+ planarReflectionScale: 1, planarReflectionMaxSize: 2048, planarReflectionUpdatesPerSecond: 0, depthPrepass: true,shadowDistance: 0, detailScale: 1, particleLimit: 20000, postProcess: true, ssao: true,waterWaves: 4, waterRippleCells: 128, waterDisplacement: true, waterMirror: true, waterCaustics: true,skipEffects: [],@@ -166,6 +172,7 @@ function resolveProfile(level: QualityLevel, value: unknown): QualityProfile {planarReflectionScale: finite(r.planarReflectionScale, base.planarReflectionScale, 0.125, 1),planarReflectionMaxSize: Math.round(finite(r.planarReflectionMaxSize, base.planarReflectionMaxSize, 64, 4096)),planarReflectionUpdatesPerSecond: finite(r.planarReflectionUpdatesPerSecond, base.planarReflectionUpdatesPerSecond, 0, 120),+ depthPrepass: typeof r.depthPrepass === 'boolean' ? r.depthPrepass : base.depthPrepass,postProcess: typeof r.postProcess === 'boolean' ? r.postProcess : base.postProcess,ssao: typeof r.ssao === 'boolean' ? r.ssao : base.ssao,waterWaves: Math.round(finite(r.waterWaves, base.waterWaves, 1, 4)),diff --git a/sdk/src/render/qualityRuntime.ts b/sdk/src/render/qualityRuntime.tsindex c8eaef697..63169910a 100644--- a/sdk/src/render/qualityRuntime.ts+++ b/sdk/src/render/qualityRuntime.ts@@ -39,6 +39,7 @@ export function installQuality(app: App, config: QualityConfig, authoredMsaa: nuquality.setLimitation('shadow-distance-unavailable',enabled && applied.shadowDistance > 0 && !api?.renderer_setShadowDistance);api?.renderer_setShadowDistance?.(enabled ? applied.shadowDistance : 0);+ api?.renderer_setDepthPrepass?.(enabled && applied.depthPrepass);api?.renderer_setPlanarReflectionQuality?.(enabled ? applied.planarReflectionScale : 0.5,enabled ? applied.planarReflectionMaxSize : 1024,enabled ? applied.planarReflectionUpdatesPerSecond : 0);diff --git a/sdk/src/wasm.ts b/sdk/src/wasm.tsindex 2e8995c72..1bef65497 100644--- a/sdk/src/wasm.ts+++ b/sdk/src/wasm.ts@@ -698,6 +698,8 @@ export interface ESEngineModule {renderer_setQualityBudgets?(atlasSize: number, cellSize: number,cascades: number, particleLimit: number): void;renderer_setShadowDistance?(distance: number): void;+ /** Draw the opaque scene twice, depth alone first, so a pixel is shaded for the surface in front of it. */+ renderer_setDepthPrepass?(on: boolean): void;renderer_setPlanarReflectionQuality?(scale: number, maxSize: number, updatesPerSecond: number): void;renderer_getPlanarReflectionStatus?(view: number, entity: number): string;renderer_setViewLighting?(mode: number, rotationDegrees: number, keyIntensity: number, fillIntensity: number, skyIntensity: number, showSky: boolean): void;diff --git a/sdk/tests/quality-runtime.test.ts b/sdk/tests/quality-runtime.test.tsindex f17132e1d..bf4978502 100644--- a/sdk/tests/quality-runtime.test.ts+++ b/sdk/tests/quality-runtime.test.ts@@ -12,10 +12,10 @@ vi.mock('../src/platform', () => ({platformOnAppHide: () => () => {}, platformOnAppShow: () => () => {},}));vi.mock('../src/ecs/bridge/engineApi', () => ({- engineApi: () => ({ renderer_setQualityBudgets: vi.fn(), renderer_setShadowDistance: distanceBudget, renderer_setPlanarReflectionQuality: reflectionBudget }),+ engineApi: () => ({ renderer_setQualityBudgets: vi.fn(), renderer_setShadowDistance: distanceBudget, renderer_setPlanarReflectionQuality: reflectionBudget, renderer_setDepthPrepass: prepass }),}));-const { distanceBudget, reflectionBudget } = vi.hoisted(() => ({ distanceBudget: vi.fn(), reflectionBudget: vi.fn() }));+const { distanceBudget, reflectionBudget, prepass } = vi.hoisted(() => ({ distanceBudget: vi.fn(), reflectionBudget: vi.fn(), prepass: vi.fn() }));describe('quality runtime device selection', () => {it('applies the tier shadow range and restores camera coverage when disabled', () => {@@ -32,6 +32,22 @@ describe('quality runtime device selection', () => {expect(distanceBudget).toHaveBeenLastCalledWith(0);expect(reflectionBudget).toHaveBeenLastCalledWith(0.5,1024,0);});+ it('turns the depth prepass on for a level that asks for it and off with the quality system, or for a level that does not', () => {+ let apply: (() => void) | undefined;+ let controller: import('../src/render/quality').QualityController;+ const app = { wasmModule: null, insertResource: (_: unknown, value: typeof controller) => { controller = value; },+ pipeline: { setQuality: (_: unknown, callback: () => void) => { apply = callback; } },+ addPlugin: vi.fn(), onFrameEnd: () => () => {},+ } as unknown as App;+ installQuality(app, { mode: 'high' }, 4);+ expect(prepass).toHaveBeenLastCalledWith(true);+ controller!.setMode('low'); apply!();+ expect(prepass).toHaveBeenLastCalledWith(false);+ controller!.setMode('medium'); apply!();+ expect(prepass).toHaveBeenLastCalledWith(true);+ controller!.setMode('off'); apply!();+ expect(prepass).toHaveBeenLastCalledWith(false);+ });it('uses this app’s actual renderer identity when a GPU rule matches', () => {const insertResource = vi.fn();const wasmModule = { deviceIdentity: () => 'WebGL2|NVIDIA|RTX 3060|driver' } as ESEngineModule;diff --git a/src/esengine/bindings/RendererBindings.cpp b/src/esengine/bindings/RendererBindings.cppindex ac8af1c84..60fd368e7 100644--- a/src/esengine/bindings/RendererBindings.cpp+++ b/src/esengine/bindings/RendererBindings.cpp@@ -1162,6 +1162,10 @@ void renderer_setShadowDistance(f32 distance) {if (g_renderFrame) g_renderFrame->setShadowDistance(distance);}+void renderer_setDepthPrepass(bool on) {+ if (g_renderFrame) g_renderFrame->setDepthPrepass(on);+}+// Which layers the NEXT collect draws. Set per camera, before renderer_submitAll.void renderer_setCullingMask(u32 mask) {if (auto* frame = g_renderFrame) frame->setCullingMask(mask);diff --git a/src/esengine/bindings/RendererBindings.hpp b/src/esengine/bindings/RendererBindings.hppindex 2b14baa75..5c86918ec 100644--- a/src/esengine/bindings/RendererBindings.hpp+++ b/src/esengine/bindings/RendererBindings.hpp@@ -26,6 +26,7 @@ void renderer_init(u32 width, u32 height);void renderer_resize(u32 width, u32 height);void renderer_setQualityBudgets(u32 atlasSize, u32 cellSize, u32 cascades, u32 particleLimit);void renderer_setShadowDistance(f32 distance);+void renderer_setDepthPrepass(bool on);void renderer_setPlanarReflectionQuality(f32 scale, u32 maxSize, f32 updatesPerSecond);std::string renderer_getPlanarReflectionStatus(u32 view, u32 entity);/**diff --git a/src/esengine/bindings/WebSDKEntry.cpp b/src/esengine/bindings/WebSDKEntry.cppindex 358434ecc..95da58451 100644--- a/src/esengine/bindings/WebSDKEntry.cpp+++ b/src/esengine/bindings/WebSDKEntry.cpp@@ -788,6 +788,7 @@ EMSCRIPTEN_BINDINGS(esengine_renderer) {emscripten::function("renderer_setDepthLayers", &esengine::renderer_setDepthLayers);emscripten::function("renderer_setQualityBudgets", &esengine::renderer_setQualityBudgets);emscripten::function("renderer_setShadowDistance", &esengine::renderer_setShadowDistance);+ emscripten::function("renderer_setDepthPrepass", &esengine::renderer_setDepthPrepass);emscripten::function("renderer_setPlanarReflectionQuality", &esengine::renderer_setPlanarReflectionQuality);emscripten::function("renderer_getPlanarReflectionStatus", &esengine::renderer_getPlanarReflectionStatus);emscripten::function("renderer_setViewLighting", &esengine::renderer_setViewLighting);diff --git a/src/esengine/data/shaders/mesh.esshader b/src/esengine/data/shaders/mesh.esshaderindex ece7f6388..24eb61375 100644--- a/src/esengine/data/shaders/mesh.esshader+++ b/src/esengine/data/shaders/mesh.esshader@@ -47,6 +47,10 @@// the rectangle it is drawn on.#pragma feature SHADOW_ALPHA+// The scene's depth prepass of a cut-out: the depth program writes the coverage the colour pass's fragment writes, by the same expression on the same+// inputs, so under alpha-to-coverage both draw the same samples and the colour pass lands on the depth this one left. With SHADOW_DEPTH.+#pragma feature PREPASS_COVERAGE+// A skinned surface coloured by how much ONE joint moves each vertex: the weight a rig is// painted with, read off the surface instead of a table. The joint is the record's tint x// (a diagnostic draw has no tint to carry), the colour goes out through the same varying the@@ -121,6 +125,10 @@ void applyMorph(inout vec3 position, inout vec3 normal) {}}+// The same position from every program of this vertex stage: the depth prepass draws a surface with one and the colour pass lands on that depth+// with another, and a compiler may order the arithmetic of two programs differently unless it is told it may not.+invariant gl_Position;+out vec2 v_texCoord;out vec4 v_color;#ifdef MESH_LIGHTMAP@@ -324,6 +332,14 @@ void main() {highp vec2 was = v_velPrev.xy / max(v_velPrev.w, 1e-6);fragColor = vec4((was - now) * 0.5, gl_FragCoord.z, v_velPrev.w > 1e-6 ? 1.0 : 0.0);#elif defined(SHADOW_DEPTH)+#ifdef PREPASS_COVERAGE+ // The colour pass's own: base alpha is the texture's times the draw's colour times the material's tint, in that order, and the cut is sharpened to+ // about a pixel. The derivative is taken before the discard, where every fragment of the quad still runs. Nothing is written but the coverage.+ highp float baseAlpha = texture(u_texture, v_texCoord).a * v_color.a * u_tint.a;+ highp float coverage = (baseAlpha - u_alphaCutoff) / max(fwidth(baseAlpha), 1e-4) + 0.5;+ if (coverage <= 0.0) discard;+ fragColor = vec4(0.0, 0.0, 0.0, min(coverage, 1.0));+#else#ifdef SHADOW_ALPHA// A cut-out's shadow is cut where the cut-out is, at the cutoff (glTF's MASK), through the mip chain: seen small from the light, the// cut-out keeps its share of the light because its mips keep their coverage at the cutoff (preserveAlphaCoverage).@@ -334,6 +350,7 @@ void main() {// sides mean it alike.fragColor = vec4(packDepth(clamp(v_shadowClip.z / v_shadowClip.w * 0.5 + 0.5,0.0, 1.0)), 1.0);+#endif#elsevec4 base = texture(u_texture, v_texCoord) * v_color;#ifdef LIT@@ -409,7 +426,7 @@ struct VSIn {@builtin(vertex_index) vertexIndex : u32,};struct VSOut {- @builtin(position) pos : vec4f,+ @builtin(position) @invariant pos : vec4f,@location(0) v_texCoord : vec2f,@location(1) v_color : vec4f,#ifdef LIT@@ -654,6 +671,16 @@ fn packNormal(n : vec3f) -> vec2f {let was = v.v_velPrev.xy / max(v.v_velPrev.w, 1e-6);return vec4f((was - now) * 0.5, v.pos.z, select(0.0, 1.0, v.v_velPrev.w > 1e-6));#elif defined(SHADOW_DEPTH)+#ifdef PREPASS_COVERAGE+ // See the GLSL twin: the colour pass's coverage, by its expression on its inputs.+ let duvx = dpdx(v.v_texCoord);+ let duvy = dpdy(v.v_texCoord);+ let baseAlpha = textureSampleGrad(t0, s0, v.v_texCoord, duvx, duvy).a * v.v_color.a * mc.u_tint.a;+ let edge = max(fwidth(baseAlpha), 1e-4);+ let coverage = (baseAlpha - mc.u_alphaCutoff) / max(edge, 1e-4) + 0.5;+ if (coverage <= 0.0) { discard; }+ return vec4f(0.0, 0.0, 0.0, min(coverage, 1.0));+#else#ifdef SHADOW_ALPHA// See the GLSL twin: through the mip chain (level 0 alone left a card's shadow a different shape from WebGL2's), cut at the cutoff.let duvx = dpdx(v.v_texCoord);@@ -665,6 +692,7 @@ fn packNormal(n : vec3f) -> vec2f {// sides mean it alike.return vec4f(packDepth(clamp(v.v_shadowClip.z / v.v_shadowClip.w * 0.5 + 0.5,0.0, 1.0)), 1.0);+#endif#else// Through the mip chain, as the GLSL twin's texture() is: level 0 alone shimmers on anything seen smaller than its texture, and// the gradients are taken here, before any branch, where every fragment of the quad still runs.diff --git a/src/esengine/renderer/draw/BatchBuilder.cpp b/src/esengine/renderer/draw/BatchBuilder.cppindex e811f3759..175330ed2 100644--- a/src/esengine/renderer/draw/BatchBuilder.cpp+++ b/src/esengine/renderer/draw/BatchBuilder.cpp@@ -122,6 +122,7 @@ void pushBatchDraw(DrawList& drawList, const ClipState& clips,cmd.probe_index = key.probeIndex;cmd.planar_index = key.planarIndex;cmd.shader_id = key.shaderId;+ cmd.depth_shader_id = key.depthShaderId;cmd.blend_mode = key.blend;cmd.layout_id = key.layoutId;cmd.material_id = key.materialId;diff --git a/src/esengine/renderer/draw/BatchBuilder.hpp b/src/esengine/renderer/draw/BatchBuilder.hppindex 42a7b1404..0b5230a19 100644--- a/src/esengine/renderer/draw/BatchBuilder.hpp+++ b/src/esengine/renderer/draw/BatchBuilder.hpp@@ -85,6 +85,8 @@ struct BatchDrawKey {// -128..127; 0 says nothing, leaving a renderable without such a field as it was.i32 order = 0;u32 shaderId = 0;+ // The program of the scene's depth prepass for this draw; 0 keeps it out of one. @see DrawCommand::depth_shader_id.+ u32 depthShaderId = 0;BlendMode blend = BlendMode::Normal;u32 textureId = 0;// A second sampler this draw needs for itself (a mesh's normal map), bound todiff --git a/src/esengine/renderer/draw/DrawCommand.hpp b/src/esengine/renderer/draw/DrawCommand.hppindex 24ec3417a..aa68e70fa 100644--- a/src/esengine/renderer/draw/DrawCommand.hpp+++ b/src/esengine/renderer/draw/DrawCommand.hpp@@ -104,6 +104,9 @@ struct DrawCommand {u32 vertex_byte_offset = 0;u32 shader_id = 0;+ /// The program that writes only this draw's depth, for the scene's depth prepass (0 = the draw takes no part in one). Its vertex stage is+ /// the draw's own, so the depth it writes is the depth the draw's colour pass lands on.+ u32 depth_shader_id = 0;BlendMode blend_mode = BlendMode::Normal;LayoutId layout_id = LayoutId::Batch;@@ -395,7 +398,7 @@ struct DrawCommand {return BatchBreak::Instanced;}if (!sameInstancedGeometry(next)) return BatchBreak::Instanced;- if (shader_id != next.shader_id) return BatchBreak::Shader;+ if (shader_id != next.shader_id || depth_shader_id != next.depth_shader_id) return BatchBreak::Shader;if (material_id != next.material_id) return BatchBreak::Material;if (cull != next.cull) return BatchBreak::Cull;if (depth_bias != next.depth_bias) return BatchBreak::Cull;@@ -409,7 +412,7 @@ struct DrawCommand {}return BatchBreak::None;}- if (shader_id != next.shader_id) return BatchBreak::Shader;+ if (shader_id != next.shader_id || depth_shader_id != next.depth_shader_id) return BatchBreak::Shader;if (blend_mode != next.blend_mode) return BatchBreak::Blend;if (layout_id != next.layout_id || vertex_buffer != next.vertex_buffer|| index_buffer != next.index_buffer || vertex_layout != next.vertex_layout) return BatchBreak::Layout;diff --git a/src/esengine/renderer/draw/DrawList.cpp b/src/esengine/renderer/draw/DrawList.cppindex 99ad114e0..24be95080 100644--- a/src/esengine/renderer/draw/DrawList.cpp+++ b/src/esengine/renderer/draw/DrawList.cpp@@ -378,6 +378,19 @@ bool DrawList::anyBlendedWithoutSceneColor(const MaterialStore& materials) constreturn false;}+/// A draw the prepass takes in: opaque and depth-writing, with a program of its own for it, and nothing that changes where it lands (a stencil).+static bool takesPartInPrepass(const DrawCommand& cmd) {+ return cmd.depth_shader_id != 0 && cmd.depth_test && cmd.depth_write && stencilModeOf(cmd.state_flags) == GfxStencilMode::Off;+}++u32 DrawList::depthPrepassDraws() const {+ u32 n = 0;+ for (u32 i = 0; i < merged_draw_calls_; ++i) {+ if (takesPartInPrepass(commands_[i])) ++n;+ }+ return n;+}+bool DrawList::anyUsesSceneDepth(const MaterialStore& materials) const {for (u32 i = 0; i < merged_draw_calls_; ++i) {if (commands_[i].material_id != 0 && materials.usesSceneDepth(commands_[i].material_id)) return true;@@ -387,7 +400,9 @@ bool DrawList::anyUsesSceneDepth(const MaterialStore& materials) const {void DrawList::execute(GfxDevice& device, TransientBufferPool& buffers,MaterialStore& materials, u32 white_texture_id,- FrameCapture* capture, const PerDrawBlockSet& blocks, Phase phase) {+ FrameCapture* capture, const PerDrawBlockSet& blocks, Phase phase, DrawPass pass) {+ const bool prepass = pass == DrawPass::DepthPrepass;+ const bool afterPrepass = pass == DrawPass::ColorAfterPrepass;PipelineDesc lastDesc{};PipelineHandle lastHandle = PipelineHandle::Invalid;// The draws of this phase read the scene's colour and compose it under themselves.@@ -399,11 +414,13 @@ void DrawList::execute(GfxDevice& device, TransientBufferPool& buffers,device.bindTexture(MESH_INSTANCE_TEXTURE_UNIT, buffers.instanceTexture());}- stageBlocks(blocks);+ // The colour pass after a prepass is the same list the prepass staged the per-draw blocks for.+ if (!afterPrepass) stageBlocks(blocks);for (u32 i = 0; i < merged_draw_calls_; ++i) {const auto& cmd = commands_[i];const StagedBlocks& staged = staged_[i];+ if (prepass && !takesPartInPrepass(cmd)) continue;if (phase != Phase::All) {const bool refracts = cmd.material_id != 0 && materials.usesSceneColor(cmd.material_id);const bool blended = isBlendedStage(cmd.stage);@@ -449,6 +466,18 @@ void DrawList::execute(GfxDevice& device, TransientBufferPool& buffers,// record, written unblended where the device can say so per target.desc.gbuffer = gbuffer_pass_ && materials.programWritesGBuffer(cmd.shader_id)&& (!desc.blendEnabled || (composes && device.supportsUnblendedSurfaceTarget()));+ if (prepass) {+ // Depth alone: the draw's depth program, unblended, no colour to either attachment. A cut-out keeps the alpha-to-coverage the colour pass draws with.+ desc.program = ShaderHandle{cmd.depth_shader_id};+ desc.blend = BlendMode::None;+ desc.blendEnabled = false;+ desc.gbuffer = false;+ desc.colorWrite = false;+ } else if (afterPrepass && takesPartInPrepass(cmd)) {+ // Its depth is already in the buffer: it lands where it is level with it, and writes nothing there again.+ desc.depthEqual = true;+ desc.depthWrite = false;+ }if (lastHandle == PipelineHandle::Invalid || !(desc == lastDesc)) {lastHandle = device.createPipeline(desc);@@ -484,9 +513,8 @@ void DrawList::execute(GfxDevice& device, TransientBufferPool& buffers,if (stencil != GfxStencilMode::Off) {device.setStencilReference(cmd.stencil_ref);}- // A draw that samples binds every unit its shader declares, not only the- // ones it reads: an untouched unit holds what the last draw put there, in- // any pass. The fill is a STABLE white, so unused units cost no rebind.+ // A draw that samples binds every unit its shader declares, not only the ones it reads: an untouched unit holds what the last draw+ // put there, in any pass, the prepass too (a vertex hook reads textures). The fill is a STABLE white, so unused units cost no rebind.if (cmd.texture_count > 0) {for (u8 slot = 0; slot < MAX_CMD_TEXTURE_SLOTS; ++slot) {// The top units are the frame's screen-space light masks wherever one@@ -528,7 +556,7 @@ void DrawList::execute(GfxDevice& device, TransientBufferPool& buffers,static_cast<u32>(static_cast<uintptr_t>(cmd.index_offset) * sizeof(u32)));}- if (capture) {+ if (capture && !prepass) {if (capture->isReplaying()) {if (capture->stepReplay()) break;} else if (capture->isCapturing()) {diff --git a/src/esengine/renderer/draw/DrawList.hpp b/src/esengine/renderer/draw/DrawList.hppindex b0efc1c83..a51a75083 100644--- a/src/esengine/renderer/draw/DrawList.hpp+++ b/src/esengine/renderer/draw/DrawList.hpp@@ -58,10 +58,17 @@ public:/// Which of the list's draws an execute makes. A draw whose material reads the picture behind it (`u_sceneColor`) has to be/// made after a copy of that picture is taken, so the frame executes the list twice: the rest, then those.enum class Phase : u8 { All, WithoutSceneColor, SceneColorOnly, OpaqueOnly, BlendedOnly };+ /// What a run of the list is for. A depth prepass draws the opaque surfaces that have a depth program, into the depth buffer alone; the colour+ /// pass that follows (`ColorAfterPrepass`) draws those same surfaces where their depth is equal to what is there, so a pixel is shaded once, for+ /// the surface that is in front of it.+ enum class DrawPass : u8 { Color, DepthPrepass, ColorAfterPrepass };void execute(GfxDevice& device, TransientBufferPool& buffers,MaterialStore& materials, u32 white_texture_id = 0,FrameCapture* capture = nullptr,- const PerDrawBlockSet& blocks = {}, Phase phase = Phase::All);+ const PerDrawBlockSet& blocks = {}, Phase phase = Phase::All, DrawPass pass = DrawPass::Color);++ /// How many of the merged draws take part in a depth prepass; 0 means a prepass has nothing to draw.+ u32 depthPrepassDraws() const;/// Whether any merged draw reads the picture behind it.bool anyUsesSceneColor(const MaterialStore& materials) const;diff --git a/src/esengine/renderer/frame/RenderFrame.cpp b/src/esengine/renderer/frame/RenderFrame.cppindex feb0040c7..88f0bb96b 100644--- a/src/esengine/renderer/frame/RenderFrame.cpp+++ b/src/esengine/renderer/frame/RenderFrame.cpp@@ -290,8 +290,20 @@ void RenderFrame::drawScene(DrawList::Phase phase) {#ifdef ES_ENABLE_POSTPROCESSdraw_list_.setGBufferPass(post_process_ && post_process_->sceneHasGBuffer());#endif+ // The opaque surfaces first, depth alone, so the colour pass shades each pixel for the surface that is in front of it and not for every+ // one that was drawn there on the way. Only a phase that draws the opaque scene, and only when something in the list has a depth program.+ const bool opaque = phase == DrawList::Phase::All || phase == DrawList::Phase::WithoutSceneColor || phase == DrawList::Phase::OpaqueOnly;+ const u32 prepassDraws = depth_prepass_ && opaque ? draw_list_.depthPrepassDraws() : 0u;+ const bool prepass = prepassDraws > 0;+ if (opaque) ES_PROFILE_COUNTER("render.prepass.draws", prepassDraws);+ if (prepass) {+ ES_PROFILE_SCOPE("render.submit.prepass");+ draw_list_.execute(device_, pool_, context_.materials(), context_.getWhiteTextureId(),+ nullptr, context_.perDrawBlocks(), phase, DrawList::DrawPass::DepthPrepass);+ }draw_list_.execute(device_, pool_, context_.materials(), context_.getWhiteTextureId(),- &frame_capture_, context_.perDrawBlocks(), phase);+ &frame_capture_, context_.perDrawBlocks(), phase,+ prepass ? DrawList::DrawPass::ColorAfterPrepass : DrawList::DrawPass::Color);draw_list_.setGBufferPass(false);}diff --git a/src/esengine/renderer/frame/RenderFrame.hpp b/src/esengine/renderer/frame/RenderFrame.hppindex cc9c72ec3..800b9a029 100644--- a/src/esengine/renderer/frame/RenderFrame.hpp+++ b/src/esengine/renderer/frame/RenderFrame.hpp@@ -111,6 +111,9 @@ public:void resize(u32 width, u32 height);void setShadowBudget(u32 atlasSize, u32 cellSize, u32 cascades);void setShadowDistance(f32 distance);+ /// Draws the opaque scene twice, depth alone first (see DrawList::DrawPass). Off unless asked: where a GPU already shades each pixel once+ /// (a tiled one), the second pass is geometry paid for twice.+ void setDepthPrepass(bool on) { depth_prepass_ = on; }void setPlanarQuality(f32 scale, u32 maxSize, f32 updatesPerSecond);u32 planarTextureFor(Entity entity) const {return entity == planar_receiver_ ? planar_texture_ : 0;@@ -994,6 +997,8 @@ private:glm::mat4 cover_view_projection_{1.0f};/// The shift the scene was drawn with, so a pass that borrows the frame's constants can hand them back as they were.glm::vec2 scene_jitter_{0.0f};+ /// Whether the opaque scene is drawn twice, depth alone first. See DrawList::DrawPass.+ bool depth_prepass_ = false;/// One per view, kept across frames for the capacity. The whole pass is collected/// before any of it is drawn, so a view's commands have to outlive its collect.std::vector<DrawList> shadow_view_lists_;diff --git a/src/esengine/renderer/plugins/MeshPlugin.cpp b/src/esengine/renderer/plugins/MeshPlugin.cppindex f18f83f0d..c949687ee 100644--- a/src/esengine/renderer/plugins/MeshPlugin.cpp+++ b/src/esengine/renderer/plugins/MeshPlugin.cpp@@ -661,6 +661,8 @@ void MeshPlugin::collect(RenderCollectContext& collect_ctx) {f64 phase[5] = {0, 0, 0, 0, 0};f64 mark = timing ? es_profile_now_ms() : 0.0;u32 walked = 0, coldDecompose = 0, lodGathers = 0, programAsks = 0, instanceRecords = 0;+ // Where the scene's opaque meshes went in the choice of a depth prepass: taken, left out for a cut-out or a bent vertex, or no program to be had.+ u32 prepassTaken = 0, prepassCutout = 0, prepassBent = 0, prepassNoProgram = 0;const auto tick = [&](int slot) {if (!timing) return;const f64 now = es_profile_now_ms();@@ -1049,6 +1051,30 @@ void MeshPlugin::collect(RenderCollectContext& collect_ctx) {key.materialId = mesh.material;}}+ // The scene's depth prepass: an opaque, unblended, depth-writing surface has its depth drawn first by a program on its own vertex stage,+ // and is shaded only where that depth is the nearest. Not what reads the picture behind it, and not the views that change what a+ // surface is drawn as.+ if (!depthPass && !motion && ctx.purpose == RenderPurpose::Scene && mesh.opaque && key.stage == RenderStage::Opaque+ && key.blend == BlendMode::None && key.depthTest && key.depthWrite && shading == ShadingMode::Shaded && !heated) {+ const bool refracts = key.materialId != 0 && ctx.materials && ctx.materials->usesSceneColor(key.materialId);+ const bool cutout = key.materialId != 0 && ctx.materials && ctx.materials->alphaIsCoverage(key.materialId);+ if (refracts) {+ } else if (cutout) {+ // Its alpha is coverage: a program that writes the same coverage, under the alpha-to-coverage the colour pass draws with.+ key.depthShaderId = ctx.materials->prepassCoverageProgram(key.materialId, ctx.resources, resident->hasNormals, skinned,+ resident->hasTangents);+ if (key.depthShaderId != 0) ++prepassTaken; else ++prepassCutout;+ } else {+ if (key.materialId != 0 && ctx.materials && ctx.materials->hasVertexHook(key.materialId)) {+ // A material that bends its vertices: left out until its depth is shown to be the colour pass's own.+ ++prepassBent;+ } else {+ const u32 depthVariant = meshDrawFor(ctx, registry, entity, mesh, resident, true, warned_bones_).variant;+ key.depthShaderId = meshProgram(ctx, depthVariant);+ if (key.depthShaderId != 0) ++prepassTaken; else ++prepassNoProgram;+ }+ }+ }key.layoutId = LayoutId::MeshInstance;key.instanceCount = 1;key.instanceStride = MESH_INSTANCE_STRIDE;@@ -1162,6 +1188,13 @@ void MeshPlugin::collect(RenderCollectContext& collect_ctx) {ES_PROFILE_COUNTER("render.mesh.coldDecompose", coldDecompose);ES_PROFILE_COUNTER("render.mesh.lodGathers", lodGathers);ES_PROFILE_COUNTER("render.mesh.programAsks", programAsks);+ // The scene's own collect says it; a shadow map's, which comes after, would overwrite it with zeroes.+ if (ctx.purpose == RenderPurpose::Scene) {+ ES_PROFILE_COUNTER("render.prepass.taken", prepassTaken);+ ES_PROFILE_COUNTER("render.prepass.cutout", prepassCutout);+ ES_PROFILE_COUNTER("render.prepass.bent", prepassBent);+ ES_PROFILE_COUNTER("render.prepass.noProgram", prepassNoProgram);+ }ES_PROFILE_COUNTER("render.mesh.programCompiles", compiled_this_frame_);// Material-owned programs built so far, CUMULATIVE. Read-only: an observer// that had to ask for readiness to see it would be the one paying, and thediff --git a/src/esengine/renderer/rhi/GLDevice.cpp b/src/esengine/renderer/rhi/GLDevice.cppindex be877fa28..b27340b2d 100644--- a/src/esengine/renderer/rhi/GLDevice.cpp+++ b/src/esengine/renderer/rhi/GLDevice.cpp@@ -416,6 +416,7 @@ void GLDevice::resetStateCache() {scissor_test_ = -1;current_depth_bias_ = 0;alpha_to_coverage_ = -1;+ depth_equal_ = -1;surface_blend_off_ = false;current_framebuffer_ = 0;timer_query_state_ = 0;@@ -1014,6 +1015,12 @@ void GLDevice::backendSetPipeline(u32 id, const PipelineDesc& desc) {if (desc.cullEnabled) setCullFace(desc.cullFront);setDepthBias(desc.depthBias);applyStencilMode(desc.stencil);+ // After the stencil mode, which states the colour mask for its own sake: a depth-only draw takes it away whatever the stencil said.+ if (!desc.colorWrite) setColorMask(false, false, false, false);+ if (static_cast<i8>(desc.depthEqual) != depth_equal_) {+ glDepthFunc(desc.depthEqual ? GL_LEQUAL : GL_LESS);+ depth_equal_ = static_cast<i8>(desc.depthEqual);+ }if (static_cast<i8>(desc.alphaToCoverage) != alpha_to_coverage_) {if (desc.alphaToCoverage) glEnable(GL_SAMPLE_ALPHA_TO_COVERAGE);else glDisable(GL_SAMPLE_ALPHA_TO_COVERAGE);diff --git a/src/esengine/renderer/rhi/GLDevice.hpp b/src/esengine/renderer/rhi/GLDevice.hppindex aef3e3308..6d0b562d1 100644--- a/src/esengine/renderer/rhi/GLDevice.hpp+++ b/src/esengine/renderer/rhi/GLDevice.hpp@@ -234,6 +234,7 @@ private:u32 active_texture_unit_ = 0;u32 bound_texture_[kTextureSlots] = {};i16 current_depth_bias_ = 0;+ i8 depth_equal_ = -1; ///< -1: unknown. 1 when the depth test passes on equal depth too.i8 alpha_to_coverage_ = -1; ///< -1: unknown, so the next pipeline sets it./// The framebuffer being drawn into carries a second colour attachment, and which of the two draw/// buffer sets is live: 0 = colour only, 1 = both, -1 = not yet said for this pass.diff --git a/src/esengine/renderer/rhi/PipelineState.hpp b/src/esengine/renderer/rhi/PipelineState.hppindex 7825fc427..6de07b1f9 100644--- a/src/esengine/renderer/rhi/PipelineState.hpp+++ b/src/esengine/renderer/rhi/PipelineState.hpp@@ -80,6 +80,11 @@ struct PipelineDesc {/// to receive it. A pipeline without it draws into a target that has one and leaves it alone:/// WebGPU wants that said in the pipeline, and GL wants the draw buffers set to match.bool gbuffer = false;+ /// False writes no colour, to either attachment: a depth-only pass, whose surfaces are then drawn again with colour.+ bool colorWrite = true;+ /// Passes where the depth is EQUAL to what the buffer holds, not only where it is less: a surface drawn a second time, after a pass that+ /// wrote its depth, must land on itself.+ bool depthEqual = false;bool operator==(const PipelineDesc&) const = default;};diff --git a/src/esengine/renderer/store/MaterialStore.cpp b/src/esengine/renderer/store/MaterialStore.cppindex 6401a6cf3..411a49f81 100644--- a/src/esengine/renderer/store/MaterialStore.cpp+++ b/src/esengine/renderer/store/MaterialStore.cpp@@ -168,6 +168,58 @@ u32 MaterialStore::shadowProgram(u32 materialId, resource::ResourceManager& resoreturn program;}+u32 MaterialStore::prepassCoverageProgram(u32 materialId, resource::ResourceManager& resources,+ bool withNormals, bool skinned, bool tangents) const {+ const MaterialRecord* rec = find(materialId);+ if (!rec || !rec->shaderRef.isValid()) return 0;+ const u64 shape = (1ull << 41) | (withNormals ? (1ull << 32) : 0ull) | (skinned ? (1ull << 33) : 0ull)+ | (tangents && withNormals ? (1ull << 39) : 0ull);+ auto& variants = mesh_programs_[rec->shaderRef.id()];+ auto cached = variants.find(shape);+ if (cached != variants.end()) {+ const Shader* shader = resources.getShader(cached->second);+ return shader ? shader->getProgramId() : 0;+ }+ auto src = sources_.find(rec->shaderRef.id());+ if (src == sources_.end()) {+ variants[shape] = {};+ return 0;+ }+ const resource::ParsedShader material = resource::ShaderParser::parse(src->second.source);+ resource::ParsedShader depth = resource::ShaderParser::parse(ShaderEmbeds::MESH);+ // The Model shader's coverage is what the depth fragment reproduces, and a hook would move vertices the colour pass moves its own way.+ if (!material.valid || !depth.valid || material.name != "Model" || material.coverageParam != "u_alphaCutoff" || !material.vertexHook.empty()) {+ variants[shape] = {};+ return 0;+ }+ depth.properties = material.properties;+ depth.materialBlockSize = material.materialBlockSize;++ std::vector<std::string> features;+ if (withNormals) features.emplace_back("MESH_NORMALS");+ if (skinned) features.emplace_back("SKINNED");+ features.emplace_back("SHADOW_DEPTH");+ features.emplace_back("PREPASS_COVERAGE");+ const auto target = resources.preferredShaderTarget();+ const std::string vert = resource::ShaderParser::assembleStage(depth, resource::ShaderStage::Vertex, "", features, target);+ const std::string frag = resource::ShaderParser::assembleStage(depth, resource::ShaderStage::Fragment, "", features, target);+ if (vert.empty() || frag.empty()) {+ ES_LOG_WARN("MaterialStore: no prepass program for material {} (stage assembly failed)", materialId);+ variants[shape] = {};+ return 0;+ }+ resource::ShaderHandle handle = resources.createShaderWithBindings(vert, frag, {}, resources.preferredShaderLanguage());+ Shader* shader = resources.getShader(handle);+ if (!shader || !shader->isValid()) {+ resources.releaseShader(handle);+ variants[shape] = {};+ return 0;+ }+ const u32 program = shader->getProgramId();+ variants[shape] = handle;+ return program;+}+u32 MaterialStore::particleProgram(u32 materialId, resource::ResourceManager& resources) const {return variantProgram(materialId, resources, 1ull << 35, { "PARTICLE" }, "particles");}diff --git a/src/esengine/renderer/store/MaterialStore.hpp b/src/esengine/renderer/store/MaterialStore.hppindex c45b10271..616a51b47 100644--- a/src/esengine/renderer/store/MaterialStore.hpp+++ b/src/esengine/renderer/store/MaterialStore.hpp@@ -246,6 +246,12 @@ public:u32 shadowProgram(u32 materialId, resource::ResourceManager& resources,bool withNormals, bool skinned, bool tangents = false) const;+ /// The program that draws @p materialId's depth for the scene's prepass when its alpha is coverage: the engine's depth shader writing the coverage+ /// the material's own fragment writes, so under alpha-to-coverage the two pass draw the same samples. Only for the engine's Model shader, whose+ /// coverage it reproduces; 0 for anything else, for a bent vertex, and when the variant fails — the draw then takes no part in a prepass.+ u32 prepassCoverageProgram(u32 materialId, resource::ResourceManager& resources,+ bool withNormals, bool skinned, bool tangents = false) const;+/// The program that draws @p materialId on PARTICLE geometry — the instanced/// quad an emitter streams. Same source, same author's fragment, a different/// engine vertex stage; 0 on the same terms as {@link meshProgram}.diff --git a/src/esengine/renderer/webgpu/WebGPUDevice.cpp b/src/esengine/renderer/webgpu/WebGPUDevice.cppindex 699323304..f1a20db12 100644--- a/src/esengine/renderer/webgpu/WebGPUDevice.cpp+++ b/src/esengine/renderer/webgpu/WebGPUDevice.cpp@@ -1337,14 +1337,14 @@ WGPURenderPipeline WebGPUDevice::ensurePipeline(u32 id) {WGPUColorTargetState targets[2]{};targets[0].format = pass_color_format_;targets[0].blend = desc.blendEnabled ? &blendState : nullptr;- targets[0].writeMask = writesStencil(desc.stencil) ? WGPUColorWriteMask_None- : WGPUColorWriteMask_All;+ targets[0].writeMask = (writesStencil(desc.stencil) || !desc.colorWrite) ? WGPUColorWriteMask_None+ : WGPUColorWriteMask_All;// The second attachment, when the pass has one: written by a shader that has the output, and// declared with an empty write mask by every other — WebGPU asks the pipeline to account for// every attachment of the pass, and a shader with one output may not be given a mask that// would write the second. Never blended: a normal averaged with what was there is neither's.targets[1].format = WGPUTextureFormat_RGBA8Unorm;- targets[1].writeMask = (desc.gbuffer && !writesStencil(desc.stencil)) ? WGPUColorWriteMask_All+ targets[1].writeMask = (desc.gbuffer && desc.colorWrite && !writesStencil(desc.stencil)) ? WGPUColorWriteMask_All: WGPUColorWriteMask_None;WGPUFragmentState fragment{};diff --git a/src/esengine/renderer/webgpu/WebGPUMappings.hpp b/src/esengine/renderer/webgpu/WebGPUMappings.hppindex 841b76f41..afae91006 100644--- a/src/esengine/renderer/webgpu/WebGPUMappings.hpp+++ b/src/esengine/renderer/webgpu/WebGPUMappings.hpp@@ -325,7 +325,7 @@ inline WGPUDepthStencilState toWGPUDepthStencil(const PipelineDesc& desc, WGPUTeds.format = format;ds.depthWriteEnabled = (desc.depthTest && desc.depthWrite) ? WGPUOptionalBool_True: WGPUOptionalBool_False;- ds.depthCompare = desc.depthTest ? WGPUCompareFunction_Less : WGPUCompareFunction_Always;+ ds.depthCompare = desc.depthTest ? (desc.depthEqual ? WGPUCompareFunction_LessEqual : WGPUCompareFunction_Less) : WGPUCompareFunction_Always;ds.stencilFront = toWGPUStencilFace(desc.stencil);ds.stencilBack = toWGPUStencilFace(desc.stencil);ds.stencilReadMask = 0xFFu;diff --git a/src/esengine/resource/ShaderParser.cpp b/src/esengine/resource/ShaderParser.cppindex 608f6ef2b..eb04de0e1 100644--- a/src/esengine/resource/ShaderParser.cpp+++ b/src/esengine/resource/ShaderParser.cpp@@ -1323,7 +1323,9 @@ fn diskTapSpun(i : i32, n : i32, radius : f32, spin : f32) -> vec2f {fn shadowSpin(worldPos : vec3f) -> f32 {return 6.2831853 * fract(sin(dot(worldPos, vec3f(12.9898, 78.233, 37.719))) * 43758.5453);}-// The spiral taps for 16 and 32 points, as numbers (see the GLSL twin): each is turned by the pixel's own spin where it is used.+)"+// Split again for the same cap; the WGSL is unchanged.+R"(// The spiral taps for 8, 16 and 32 points, as numbers (see the GLSL twin): each is turned by the pixel's own spin where it is used.const kSpiral8 = array<vec2f, 8>(vec2f(0.2500000, 0.0000000),vec2f(-0.3192901, 0.2924959),diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjsindex 22f2a2a4c..b7db28710 100644--- a/tools/releaseNotes.mjs+++ b/tools/releaseNotes.mjs@@ -2980,4 +2980,6 @@ export const NOTED = {{"note":"A third mesh for a plant."},"perf(render): a lit surface takes its shadow in fewer operations":{"note":"A lit surface takes its shadow in fewer operations."},+ "feat(render): the opaque scene can be drawn twice, depth alone first, so a pixel is shaded for the surface in front of it":+ {"note":"A depth prepass for the opaque scene."},};diff --git a/tools/render-host/host.ts b/tools/render-host/host.tsindex dbf708f12..2295e9006 100644--- a/tools/render-host/host.ts+++ b/tools/render-host/host.ts@@ -42,6 +42,8 @@ const backend = params.get('backend') === 'webgpu' ? 'webgpu' : 'webgl2';const colorSpace = params.get('colorSpace') === 'linear' ? 'linear' : undefined;const outputTransform = params.get('outputTransform') === 'aces' ? 'aces' : undefined;const msaaSamples = Number(params.get('msaa')) || undefined;+/** The opaque scene drawn twice, depth alone first: the quality levels turn it on, and this host has none. */+const depthPrepass = params.get('prepass') === '1';const seedParam = params.get('seed');const randomSeed = seedParam !== null && Number.isFinite(Number(seedParam)) ? Number(seedParam) : undefined;const depthLayers = Number(params.get('depthLayers')) || undefined;@@ -151,6 +153,7 @@ async function boot(): Promise<void> {app.enableStats();// The editor's engine asks for edge buffers before its assets load; so does this host.module.renderer_setMeshEdgeBuffers?.(true);+ if (depthPrepass) module.renderer_setDepthPrepass?.(true);if (runtimeTextures) {app.getResource(Assets).getTextureLoader().setPixelDecoder(async (path) => {const res = await fetch(path);diff --git a/tools/render-host/run.mjs b/tools/render-host/run.mjsindex 9e6450147..cbaf3b886 100644--- a/tools/render-host/run.mjs+++ b/tools/render-host/run.mjs@@ -44,6 +44,7 @@* ESTELLA_VERIFY_SCALE copy the scene's content onto a grid (JSON), for a cost gate* ESTELLA_VERIFY_OUTPUT_TRANSFORM the frame's output curve ("aces")* ESTELLA_VERIFY_MSAA multisample count the scene asks for (the app's default otherwise)+ * ESTELLA_VERIFY_PREPASS 1: draw the opaque scene twice, depth alone first (what a quality level does)* ESTELLA_VERIFY_TEXTURES "runtime": images upload through the engine, as a shipped game's do* ESTELLA_VERIFY_PROFILE record N further frames and report the TS/C++ cost split* ESTELLA_VERIFY_TIMEOUT_MS how long this run may take before it reports one@@ -102,6 +103,7 @@ const COLORSPACE = process.env.ESTELLA_VERIFY_COLORSPACE === 'linear' ? 'linear'// is a curve on the way out and engages the capture on its own.const OUTPUT_TRANSFORM = process.env.ESTELLA_VERIFY_OUTPUT_TRANSFORM === 'aces' ? 'aces' : '';const MSAA = process.env.ESTELLA_VERIFY_MSAA ?? '';+const PREPASS = process.env.ESTELLA_VERIFY_PREPASS === '1';const TEXTURES = process.env.ESTELLA_VERIFY_TEXTURES === 'runtime' ? 'runtime' : '';// A scene whose emitters roll dice has no constant to assert until the run is// seeded; the engine seeds itself from the clock when nobody says otherwise.@@ -255,7 +257,7 @@ app.whenReady().then(async () => {let server;try {server = await serveHost(DIST);- const url = `http://127.0.0.1:${server.address().port}/${PAGE}?w=${W}&h=${H}&backend=${BACKEND}${COLORSPACE ? `&colorSpace=${COLORSPACE}` : ''}${OUTPUT_TRANSFORM ? `&outputTransform=${OUTPUT_TRANSFORM}` : ''}${MSAA ? `&msaa=${MSAA}` : ''}${TEXTURES ? `&textures=${TEXTURES}` : ''}${DEPTH_LAYERS ? `&depthLayers=${DEPTH_LAYERS}` : ''}${RENDER_RESOLUTION ? `&renderResolution=${RENDER_RESOLUTION}` : ''}${SEED ? `&seed=${SEED}` : ''}`;+ const url = `http://127.0.0.1:${server.address().port}/${PAGE}?w=${W}&h=${H}&backend=${BACKEND}${COLORSPACE ? `&colorSpace=${COLORSPACE}` : ''}${OUTPUT_TRANSFORM ? `&outputTransform=${OUTPUT_TRANSFORM}` : ''}${MSAA ? `&msaa=${MSAA}` : ''}${PREPASS ? '&prepass=1' : ''}${TEXTURES ? `&textures=${TEXTURES}` : ''}${DEPTH_LAYERS ? `&depthLayers=${DEPTH_LAYERS}` : ''}${RENDER_RESOLUTION ? `&renderResolution=${RENDER_RESOLUTION}` : ''}${SEED ? `&seed=${SEED}` : ''}`;// useContentSize: the capture rectangle must be the page area, not the// outer frame (the same trap the parity runner documents).@@ -295,7 +297,7 @@ app.whenReady().then(async () => {}// The engine's per-frame counters are only recorded while profiling is on, and// it goes on BEFORE the steps: what is read afterwards is the last frame's.- if (process.env.ESTELLA_VERIFY_COUNTERS || process.env.ESTELLA_VERIFY_COUNTERS_MAX || process.env.ESTELLA_VERIFY_FRAME_DEBUG) {+ if (process.env.ESTELLA_VERIFY_COUNTERS || process.env.ESTELLA_VERIFY_COUNTERS_MAX || process.env.ESTELLA_VERIFY_FRAME_DEBUG || PREPASS) {await exec('window.__estellaHeadless.api.setCpuProfiling(true)');}// Project render config stand-in: ESTELLA_VERIFY_YSORT = layer bitmask@@ -713,7 +715,7 @@ app.whenReady().then(async () => {// exact pins a scene small enough to enumerate, a ceiling asks whether cost stayed// bounded where nobody can. Both fail on a counter the frame never set.let counters = null;- if (process.env.ESTELLA_VERIFY_COUNTERS || process.env.ESTELLA_VERIFY_COUNTERS_MAX) {+ if (process.env.ESTELLA_VERIFY_COUNTERS || process.env.ESTELLA_VERIFY_COUNTERS_MAX || PREPASS) {const want = JSON.parse(process.env.ESTELLA_VERIFY_COUNTERS ?? '{}');const ceiling = JSON.parse(process.env.ESTELLA_VERIFY_COUNTERS_MAX ?? '{}');const got = await exec('window.__estellaHeadless.api.getCounters()');@@ -725,6 +727,9 @@ app.whenReady().then(async () => {name, max: value, got: got?.[name] ?? null,ok: typeof got?.[name] === 'number' && got[name] <= value,})),+ // A prepass twin of a scene that never had a prepass proves nothing about it: the draw it took part in is counted.+ ...(PREPASS ? [{ name: 'render.prepass.draws', min: 1, got: got?.['render.prepass.draws'] ?? null,+ ok: (got?.['render.prepass.draws'] ?? 0) >= 1 }] : []),];counters = { points, ok: points.every((p) => p.ok) };}diff --git a/tools/renderScenes.mjs b/tools/renderScenes.mjsindex dd652e37f..55a1a4250 100644--- a/tools/renderScenes.mjs+++ b/tools/renderScenes.mjs@@ -901,6 +901,28 @@ export const SCENES = [{ id: "device-roundtrip-post", tier: "pr", webgpu: true, env: { ESTELLA_VERIFY_DEVICE_LOSS: "roundtrip", ESTELLA_VERIFY_LOSS_ROUNDS: "2", ESTELLA_VERIFY_PLAY: "1", ESTELLA_VERIFY_SCENE: "/scenes/ui-screen-post.esscene", ESTELLA_VERIFY_MANIFEST: "/scenes/ui-screen-post.textures.json", ESTELLA_VERIFY_W: "640", ESTELLA_VERIFY_H: "360", ESTELLA_VERIFY_STEPS: "4" } },];+/**+ * The same pixels with the opaque scene drawn twice, depth alone first. A quality level turns the prepass on, and this host has none, so a scene+ * that must look the same either way runs again with `ESTELLA_VERIFY_PREPASS`; the run also fails if no draw took part in the prepass, which a+ * twin of a scene with nothing opaque to draw first would otherwise pass without having tried.+ */+const PREPASS_TWINS = [+ // Scenes that draw opaque meshes already.+ 'mesh-opaque', 'mesh-instanced', 'corpus-cutout-edge', 'mesh-normalmap', 'mesh-shadow-cutout', 'mesh-shadow', 'sun-shadow',+ // The same scenes with their meshes made opaque (fixtures/scenes/*-opaque.esscene), for what a mesh can be besides a rigid one that is lit:+ // skinned, morphing.+ { id: 'mesh-skin', scene: 'mesh-skin-opaque.esscene' }, { id: 'mesh-morph-shaped', scene: 'mesh-morph-opaque.esscene' },+ { id: 'mesh-lit', scene: 'mesh-lit-opaque.esscene' }, { id: 'mesh-resident', scene: 'mesh-renderer-opaque.esscene', as: 'mesh-renderer' },+];+for (const entry of PREPASS_TWINS) {+ const { id, scene, as } = typeof entry === 'string' ? { id: entry } : entry;+ const base = SCENES.find((s) => s.id === id);+ if (!base) throw new Error(`renderScenes: no scene "${id}" to run a prepass twin of`);+ const env = { ...base.env, ESTELLA_VERIFY_PREPASS: '1' };+ if (scene) env.ESTELLA_VERIFY_SCENE = `/scenes/${scene}`;+ SCENES.push({ ...base, id: `${as ?? (scene ? scene.replace('.esscene', '') : id)}-prepass`, env });+}+const rank = (tier) => TIERS.indexOf(tier);/** Scenes that run at `tier`, cheaper tiers included. */diff --git a/tools/terrain-water-cost.mjs b/tools/terrain-water-cost.mjsindex dab9090eb..41ddb3daa 100644--- a/tools/terrain-water-cost.mjs+++ b/tools/terrain-water-cost.mjs@@ -102,6 +102,7 @@ const VARIANTS = [{ id: 'trees-noshadow', label: 'trees cast no shadow', world: trees((p) => { for (const part of [...p.parts, ...(p.far ?? [])]) part.castShadows = false; }) },{ id: 'trees-nofar', label: 'no far cards (trees fade out at their draw distance)', world: (w) => { for (const p of Object.values(w.plants)) p.farDistance = 0; } },// Quality knobs, one at a time from high+ { id: 'no-prepass', label: 'no depth prepass (what the example drew before it)', config: quality('high', { depthPrepass: false }) },{ id: 'msaa-1', label: 'no multisampling', config: quality('high', { msaaSamples: 1 }) },{ id: 'msaa-2', label: 'msaa 2x', config: quality('high', { msaaSamples: 2 }) },{ id: 'cascades-2', label: 'two shadow cascades', config: quality('high', { shadowCascades: 2 }) },@@ -215,7 +216,7 @@ try {}if (!r) { table[v.id] = { label: v.label, failed: true }; continue; }table[v.id] = { label: v.label, ...r };- console.log(`${v.id.padEnd(17)} ${r.ms.toFixed(2).padStart(7)} ms [${r.min.toFixed(2)}..${r.max.toFixed(2)}] cpu ${r.cpu.toFixed(2)} draws ${r.counters['batch.draws'] ?? '?'} shadow ${r.counters['render.shadow.draws'] ?? '?'} tris ${((r.counters['render.triangles'] ?? 0) / 1e6).toFixed(2)}M placed ${r.counters['render.placements.seen'] ?? '?'}/coarse ${r.counters['render.placements.coarse'] ?? '?'}/far ${r.counters['render.placements.tooFar'] ?? '?'} ${r.errors.length ? 'ERRORS ' + r.errors[0] : ''}`);+ console.log(`${v.id.padEnd(17)} ${r.ms.toFixed(2).padStart(7)} ms [${r.min.toFixed(2)}..${r.max.toFixed(2)}] cpu ${r.cpu.toFixed(2)} draws ${r.counters['batch.draws'] ?? '?'} shadow ${r.counters['render.shadow.draws'] ?? '?'} tris ${((r.counters['render.triangles'] ?? 0) / 1e6).toFixed(2)}M prepass ${r.counters['render.prepass.draws'] ?? '?'} (meshes taken ${r.counters['render.prepass.taken'] ?? '?'}, cut-out ${r.counters['render.prepass.cutout'] ?? '?'}, bent ${r.counters['render.prepass.bent'] ?? '?'}, none ${r.counters['render.prepass.noProgram'] ?? '?'}) ${r.errors.length ? 'ERRORS ' + r.errors[0] : ''}`);}} finally {await writeFile(path.join(DIR, 'assets/scenes/main.esscene'), original.scene);