Skip to content

armgit / 67.js

Public Imported from GitHub
0

3D engine that AI agents drive

Warn about and fix z-fighting on flush surfaces (part of #310)

Nguyen Xuan Anbfbc7bdcd9c0
diff --git a/bench/size/budgets.json b/bench/size/budgets.json
index 459b421b..8f4fd6de 100644
--- a/bench/size/budgets.json
+++ b/bench/size/budgets.json
@@ -6,7 +6,7 @@
"agent-scene": 100000
},
"budgets": {
- "entry:core": 88890,
+ "entry:core": 91470,
"entry:model": 14400,
"entry:nature": 13200,
"entry:motion": 15260,
@@ -34,10 +34,10 @@
"entry:ground-bounce": 9460,
"entry:path-tracer": 15960,
"entry:texture-set": 900,
- "entry:agent-scene": 80770,
- "entry:agent-scene+lazy": 263350,
- "entry:agent-asset": 112170,
- "entry:agent-asset+lazy": 274720,
+ "entry:agent-scene": 83620,
+ "entry:agent-scene+lazy": 266200,
+ "entry:agent-asset": 115100,
+ "entry:agent-asset+lazy": 277650,
"entry:hdri": 3300,
"entry:camera-effects": 8600,
"entry:water-reflection": 26580,
@@ -46,10 +46,10 @@
"entry:material-layer-shaders": 21400,
"entry:light-linking": 19720,
"entry:cascaded-shadows": 28530,
- "scene:lit-box": 65870,
- "scene:gltf-box": 90150,
- "scene:gltf-box+lazy": 93480,
- "scene:agent-scene": 109670,
- "scene:agent-scene+lazy": 292250
+ "scene:lit-box": 68540,
+ "scene:gltf-box": 92810,
+ "scene:gltf-box+lazy": 96140,
+ "scene:agent-scene": 112860,
+ "scene:agent-scene+lazy": 295440
}
}
diff --git a/bench/tool-cost-budgets.json b/bench/tool-cost-budgets.json
index 0ff57b3c..a65acbe2 100644
--- a/bench/tool-cost-budgets.json
+++ b/bench/tool-cost-budgets.json
@@ -1,5 +1,5 @@
{
- "measured": "2026-10-31, from scripts/measure-tool-cost.mjs; raised by 800 total and 150 for scene_apply for branch and labels fields (no new tool); raised by 650 total and 80 for scene_apply for clip layers, bone masks and retargeting through MCP; raised by 20 for scene_create and 20 for the scene_capabilities result after merging the expression language with the material graph; was 373388 schema bytes before shared IDs and recipe references; trimmed after the render-passes merge: material graph, depth of field, motion blur and passes details moved to scene_capabilities, budgets set to the measured value plus 0.5% (total 188267, scene_capabilities result 5167); raised by 95 for scene_apply and 690 for the scene_capabilities result for node relations; curve and text geometry entries shortened to a pointer at scene_capabilities curveText, budgets set to the measured value plus 0.5% (total 189468, scene_capabilities result 6399); then six modifier ops (weld, triangulate, edge_split, smooth, simple_deform, cast) added as one compact schema entry with details in scene_capabilities meshModifiers, entry and mesh_stack description shortened: total 190382 (budget unchanged at 190420), mesh_edit 34216 (budget 34220), scene_capabilities result 7042 (budget 7050); mesh_stack 11682 (budget 11690); after merging imported mesh topology with the modifier ops: raised the total to 190480 (measured 190471), mesh_edit to 34300 (measured 34293) and the scene_capabilities result to 7520 (measured 7512) for imported mesh edits; then cloth (recipe cloth, set-cloth, grid geometry) added with the total unchanged at 190480 (measured 189159): physics descriptions shortened and set-physics now takes the same record reference as set-motion, scene_create raised to 62150 and scene_apply lowered to 44130, scene_capabilities result raised to 8190 (measured 8176) for the cloth details; then particles and hair (recipe `particles`, set-particles) added with the total unchanged at 190480 (measured 189642, scene_create raised to 62350 and scene_apply to 44370 for the recipe particles reference and set-particles): the section is one record reference described in scene_capabilities, so the scene_capabilities result rose to 9570 (measured 9523) for the particle and hair fields; after merging the film timeline (recipe timeline, set-timeline) with particles: total 190719 (budget 190730), scene_create 62464, scene_apply 44620, scene_capabilities result 9902; then the path tracer renderer setting (drop z.int bounds, integers still checked by the job validator): total raised to 190830 (measured 190818); after merging the render limits and light bake with the path tracer: measured total 190013, scene_create raised to 62680 (measured 62667), scene_apply to 44860 (measured 44852) and the scene_capabilities result to 10620 (measured 10613) for the bake section and job size limits; then material layers anisotropy and iridescence (issue #51): the 16 layer fields take one short line each in the schema and their ranges and notes moved to scene_capabilities scene.materialLayers, so the scene_capabilities result rose to 12230 (measured 12168); then the worker bake limit added workerMaxSeconds to the bake limits (result 13361, budget raised to 13370); then the sculpt and shrinkwrap mesh edits (issue #47) with the total unchanged at 190830 (measured 190612): the face rule and tag prefix descriptions shortened (the face rule text repeats in every select field), so mesh_edit rose to 33980 (measured 33960) and mesh_stack fell to 11030 (measured 11014), and the scene_capabilities result rose to 13350 (measured 13338) for the meshSculpt notes; then recipe light links and shadow cascades (issue #52): environment fields added to the shared environment schema with the total unchanged at 190830 (measured 190507) by shortening its descriptions, and the scene_capabilities result raised to 13870 (measured 13865) for lightLinking and shadowCascades; then the nine remaining modifiers (issue #42: screw, skin, wireframe, lattice, curve, hook, wave, weighted_normal, smooth_by_angle) added their notes to meshModifiers and a free modifier record replaced the modifier schema entry, so the schemas shrank and the scene_capabilities result rose to 15900 (measured 15814); path query of scene_inspect (issue #64): one record field of 205 bytes in the scene_inspect schema (total 190732, within its budget) and the navigation notes in scene_capabilities, so the result rose to 14500 (measured 14494); reflection probes (issue #55): the bake.probes line, and the scene_capabilities result raised to 16600 (measured 16541) after merging with main; volumeFog shadowAmbient (issue #165): scene_create raised to 62945 (measured 62940) and scene_apply to 45040 (measured 45037); keyframe easing (issue #286): one easing string field in each of the motion track schemas, scene_create raised to 63450 (measured 63444) and the total to 191000 (measured 190994); glTF import line gltfImport (issue #280): the scene_capabilities result raised to 16701 (measured 16681)",
+ "measured": "2026-10-31, from scripts/measure-tool-cost.mjs; raised by 800 total and 150 for scene_apply for branch and labels fields (no new tool); raised by 650 total and 80 for scene_apply for clip layers, bone masks and retargeting through MCP; raised by 20 for scene_create and 20 for the scene_capabilities result after merging the expression language with the material graph; was 373388 schema bytes before shared IDs and recipe references; trimmed after the render-passes merge: material graph, depth of field, motion blur and passes details moved to scene_capabilities, budgets set to the measured value plus 0.5% (total 188267, scene_capabilities result 5167); raised by 95 for scene_apply and 690 for the scene_capabilities result for node relations; curve and text geometry entries shortened to a pointer at scene_capabilities curveText, budgets set to the measured value plus 0.5% (total 189468, scene_capabilities result 6399); then six modifier ops (weld, triangulate, edge_split, smooth, simple_deform, cast) added as one compact schema entry with details in scene_capabilities meshModifiers, entry and mesh_stack description shortened: total 190382 (budget unchanged at 190420), mesh_edit 34216 (budget 34220), scene_capabilities result 7042 (budget 7050); mesh_stack 11682 (budget 11690); after merging imported mesh topology with the modifier ops: raised the total to 190480 (measured 190471), mesh_edit to 34300 (measured 34293) and the scene_capabilities result to 7520 (measured 7512) for imported mesh edits; then cloth (recipe cloth, set-cloth, grid geometry) added with the total unchanged at 190480 (measured 189159): physics descriptions shortened and set-physics now takes the same record reference as set-motion, scene_create raised to 62150 and scene_apply lowered to 44130, scene_capabilities result raised to 8190 (measured 8176) for the cloth details; then particles and hair (recipe `particles`, set-particles) added with the total unchanged at 190480 (measured 189642, scene_create raised to 62350 and scene_apply to 44370 for the recipe particles reference and set-particles): the section is one record reference described in scene_capabilities, so the scene_capabilities result rose to 9570 (measured 9523) for the particle and hair fields; after merging the film timeline (recipe timeline, set-timeline) with particles: total 190719 (budget 190730), scene_create 62464, scene_apply 44620, scene_capabilities result 9902; then the path tracer renderer setting (drop z.int bounds, integers still checked by the job validator): total raised to 190830 (measured 190818); after merging the render limits and light bake with the path tracer: measured total 190013, scene_create raised to 62680 (measured 62667), scene_apply to 44860 (measured 44852) and the scene_capabilities result to 10620 (measured 10613) for the bake section and job size limits; then material layers anisotropy and iridescence (issue #51): the 16 layer fields take one short line each in the schema and their ranges and notes moved to scene_capabilities scene.materialLayers, so the scene_capabilities result rose to 12230 (measured 12168); then the worker bake limit added workerMaxSeconds to the bake limits (result 13361, budget raised to 13370); then the sculpt and shrinkwrap mesh edits (issue #47) with the total unchanged at 190830 (measured 190612): the face rule and tag prefix descriptions shortened (the face rule text repeats in every select field), so mesh_edit rose to 33980 (measured 33960) and mesh_stack fell to 11030 (measured 11014), and the scene_capabilities result rose to 13350 (measured 13338) for the meshSculpt notes; then recipe light links and shadow cascades (issue #52): environment fields added to the shared environment schema with the total unchanged at 190830 (measured 190507) by shortening its descriptions, and the scene_capabilities result raised to 13870 (measured 13865) for lightLinking and shadowCascades; then the nine remaining modifiers (issue #42: screw, skin, wireframe, lattice, curve, hook, wave, weighted_normal, smooth_by_angle) added their notes to meshModifiers and a free modifier record replaced the modifier schema entry, so the schemas shrank and the scene_capabilities result rose to 15900 (measured 15814); path query of scene_inspect (issue #64): one record field of 205 bytes in the scene_inspect schema (total 190732, within its budget) and the navigation notes in scene_capabilities, so the result rose to 14500 (measured 14494); reflection probes (issue #55): the bake.probes line, and the scene_capabilities result raised to 16600 (measured 16541) after merging with main; volumeFog shadowAmbient (issue #165): scene_create raised to 62945 (measured 62940) and scene_apply to 45040 (measured 45037); keyframe easing (issue #286): one easing string field in each of the motion track schemas, scene_create raised to 63450 (measured 63444) and the total to 191000 (measured 190994); glTF import line gltfImport (issue #280): the scene_capabilities result raised to 16701 (measured 16681); depth bias line depthBias (issue #310): the scene_capabilities result raised to 17000 (measured 16979)",
"schemaTotalBytes": 191040,
"schemaToolBytes": {
"scene_create": 63450,
@@ -10,7 +10,7 @@
},
"schemaOtherToolBytes": 4000,
"resultBytes": {
- "scene_capabilities": 16701,
+ "scene_capabilities": 17000,
"scene_create": 1400,
"scene_inspect": 1400,
"mesh_inspect": 1200,
diff --git a/changes/310.md b/changes/310.md
new file mode 100644
index 00000000..82fc21c7
--- /dev/null
+++ b/changes/310.md
@@ -0,0 +1 @@
+- Stop z-fighting on flush surfaces (part of #310): `renderer.diagnostics` and `scene_inspect` warn `coplanar-overlap` with both part names, the shared area and a fix, and a node's `decal: true` or `depthLayer` (0 to 4), or `environment.resolveCoplanar: 'offset'`, draws the smaller part with a scoped polygon offset in the colour pass and render passes without moving geometry. Reversed-Z depth stays open.
diff --git a/docs/agent-look.md b/docs/agent-look.md
index 80167f3d..487f909f 100644
--- a/docs/agent-look.md
+++ b/docs/agent-look.md
@@ -107,6 +107,7 @@ Sky colors use display RGB, matching the renderer's existing environment contrac
| --- | --- | --- |
| `world` | `false` | Boolean world presentation flag. With `true` the setup environment is also the background |
| `ground` | on | Absent unless set. `false` removes the preview's automatic floor and contact shadow |
+| `resolveCoplanar` | off | `'offset'` puts the smaller part of each coplanar pair (see the `coplanar-overlap` warning) on the next depth layer, drawn with a polygon offset; `false` or absent leaves parts as authored. Geometry never moves. Parts that set `decal` or `depthLayer` keep their own |
| `objectReflections` | on | Absent unless set. Each smooth metal part (`metallic` 0.5 or more, `roughness` 0.6 or less; at most 8 such parts) gets a reflection probe of the scene around it, so a chrome sphere shows the floor and its neighbours. `false` turns it off. Probes are traced at rest, so a part that moves reflects the scene as it started. `scene_inspect` names them in `reflections` |
| `setup` | `daylight` | `daylight`, `overcast`, `sunset` or `studio`. See Lighting setups |
| `environmentIntensity` | `1` | `0` to `100`. Scales the setup's environment light and reflections |
diff --git a/docs/guide.md b/docs/guide.md
index 3a774589..257cd63d 100644
--- a/docs/guide.md
+++ b/docs/guide.md
@@ -196,7 +196,7 @@ The `surfaces` mode finds triangle contact. The `closed-solids` mode also tests
An index also supports `raycast(matrix, ray)` for a triangle number, hit point and barycentric coordinates.
The [mesh query contract](https://github.com/codepawl/67.js/blob/main/docs/mesh-query.md) describes results, solid validation, numerical limits and budget errors.
Rebuild indices after geometry edits. Queries reject skin and morph channels.
-Contact results do not measure penetration depth, resolve collisions or diagnose z-fighting.
+Contact results do not measure penetration depth or resolve collisions. Z-fighting has its own check: `renderer.diagnostics` and `scene_inspect` report `coplanar-overlap` for two parts that draw the same plane (within 1 mm, same facing, at least 1 cm2 shared). Fix it with `decal: true` on the smaller part (layer 1; `depthLayer` 0 to 4 orders stacked decals), or `environment.resolveCoplanar: 'offset'` to bias the smaller part of every flagged pair. Both draw with a scoped polygon offset in the colour pass and render passes, and never move geometry. Use a real offset along the normal when the gap should be visible in exports or the path tracer. Reversed-Z depth is not implemented yet (#310).
## Shrinkwrap and surface patches
diff --git a/skills/build-67js-scene/references/scene-contract.md b/skills/build-67js-scene/references/scene-contract.md
index bc8f6552..0f247409 100644
--- a/skills/build-67js-scene/references/scene-contract.md
+++ b/skills/build-67js-scene/references/scene-contract.md
@@ -129,7 +129,7 @@ It rejects skin, morph, assembly and procedural targets. It does not detect arbi
Static `createMeshQueryIndex` copies geometry into an owned disposable BVH. Read `docs/mesh-query.md` for numerical and work limits.
Pass current affine matrices to `createMeshPairQuery(...).evaluate()`. Rebuild indices after editing geometry.
-Closed-solid containment requires two `solid: true` indices. Surface contact does not prove volume penetration or z-fighting.
+Closed-solid containment requires two `solid: true` indices. Surface contact does not prove volume penetration. Flush faces flicker: `scene_inspect` warns `coplanar-overlap` naming both parts; set `decal: true` on the smaller node (a sign, a road marking), `depthLayer` 0 to 4 for stacked decals, or `environment.resolveCoplanar: 'offset'` to bias every flagged pair at draw time. Or move one part 2 mm along its normal. Never use these to hide overlapping solids.
Use `docs/primitives.md` for exact seam closure and preallocation bounds. Preserve indeterminate and budget errors rather than reporting a miss.
diff --git a/src/agent-look.js b/src/agent-look.js
index e5c693df..85a2229b 100644
--- a/src/agent-look.js
+++ b/src/agent-look.js
@@ -11,7 +11,7 @@ const MAX_LOOK_ARRAY_ENTRIES = Math.max(MAX_POINT_LIGHTS, MAX_SPOT_LIGHTS, MAX_A
const ENVIRONMENT_FIELDS = [
'world', 'ground', 'setup', 'environmentIntensity', 'environmentRotation', 'lightDirection', 'keyColor', 'keyIntensity', 'fillIntensity', 'ambientIntensity',
- 'daylight', 'pointLights', 'spotLights', 'areaLights', 'skyTop', 'skyBottom', 'fogColor', 'fogDensity', 'volumeFog', 'liquid', 'shadowCascades', 'keyAffects', 'objectReflections',
+ 'daylight', 'pointLights', 'spotLights', 'areaLights', 'skyTop', 'skyBottom', 'fogColor', 'fogDensity', 'volumeFog', 'liquid', 'shadowCascades', 'keyAffects', 'objectReflections', 'resolveCoplanar',
];
const LIQUID_FIELDS = ['thickness', 'ior', 'refraction', 'scattering', 'foamOpacity', 'foamSoftness'];
const EFFECT_FIELDS = ['exposure', 'saturation', 'contrast', 'temperature', 'vignette', 'grain', 'ambientOcclusion', 'ambientOcclusionRadius', 'bloom', 'depthOfField', 'motionBlur'];
@@ -271,6 +271,12 @@ function environmentFrom(input = {}) {
}
environment.objectReflections = input.objectReflections;
}
+ if (input.resolveCoplanar !== undefined) {
+ if (input.resolveCoplanar !== 'offset' && input.resolveCoplanar !== false) {
+ throw new TypeError("environment.resolveCoplanar must be 'offset' or false.");
+ }
+ environment.resolveCoplanar = input.resolveCoplanar;
+ }
if (input.spotLights !== undefined) {
environment.spotLights = lightListFrom(input.spotLights, MAX_SPOT_LIGHTS, 'spotLights').map(spotLightFrom);
}
diff --git a/src/agent-scene-capabilities.js b/src/agent-scene-capabilities.js
index 5b5bcb88..059cb38b 100644
--- a/src/agent-scene-capabilities.js
+++ b/src/agent-scene-capabilities.js
@@ -208,6 +208,8 @@ export const AGENT_SCENE_CAPABILITIES = Object.freeze({
localShadows: Object.freeze({ lights: Object.freeze(['pointLights', 'spotLights']), atlasTiles: 24, pointLightTiles: 6, spotLightTiles: 1, tileSize: 512 }),
lightLinking: Object.freeze({ fields: Object.freeze(['environment.keyAffects', 'pointLights[].affects', 'spotLights[].affects', 'areaLights[].affects']), unlisted: 'a light without affects lights every node', unknownNode: 'rejected', bake: 'honoured', pathTracer: 'ignored, named in report.ignored' }),
shadowCascades: Object.freeze({ field: 'environment.shadowCascades', counts: Object.freeze([0, 1, 2, 3, 4]), zero: 'one shadow map', automatic: 'three cascades when shadow.extent is above 40 and the field is unset', maximumDistance: 150, note: 'volume fog and water read the single map' }),
+ // Flush surfaces flicker (z-fighting). scene_inspect and renderer.diagnostics warn with coplanar-overlap; these fix it at draw time.
+ depthBias: Object.freeze({ nodeFields: Object.freeze(['decal', 'depthLayer']), maxDepthLayer: 4, environment: 'environment.resolveCoplanar', modes: Object.freeze(['offset']), warning: 'coplanar-overlap', note: 'decal wins over the surface below; depthLayer stacks decals; resolveCoplanar offset biases the smaller part of a flagged pair.' }),
proceduralMotion: true,
motionIk: Object.freeze(['two-bone', 'aim']),
// Authored rigs: armatures expand into bone nodes, and a node `skin` binds a mesh with automatic weights (four influences).
diff --git a/src/agent-scene.js b/src/agent-scene.js
index 3bc1912b..556d5ced 100644
--- a/src/agent-scene.js
+++ b/src/agent-scene.js
@@ -8,6 +8,7 @@ import { MESH_SMOOTH_ANGLE_DEFAULT, CURVE_TEXT_LIMITS, AGENT_SCENE_CAPABILITIES,
import { ALL_LIGHTS_MASK, MATERIAL_LAYER_FIELDS, validateMaterialLayers } from './material-layers.js';
import { recipeDiagnostics, closedRoomDiagnostic } from './agent-diagnostics.js';
import { closedRoomShare, CLOSED_ROOM_SHARE } from './closed-room.js';
+import { coplanarOverlapDiagnostics, depthLayerOf, findCoplanarOverlaps, MAXIMUM_DEPTH_LAYER, resolveCoplanarParts } from './coplanar-overlap.js';
import { armatureNodes, bakeRigExport, bindSkins, createSkinStages, normalizeArmatures, publishSkinPoses, restWorldMatrix, rigReport, stageSkinPoses, transformedBounds, withoutArmatureNodes } from './rig.js';
export { AGENT_SCENE_CAPABILITIES, AGENT_SCENE_DEFAULT_LIMITS };
export { normalizeAgentLook, resolveAgentShadow } from './agent-look.js';
@@ -22,7 +23,7 @@ const MAX_MESH_REPORTS = 16;
// Terrain meshes carry one more float for each vertex (sky visibility) than the 56 bytes the budget estimates.
const TERRAIN_SKY_VISIBILITY_BYTES = 4;
const CAMERA_DEFAULTS = Object.freeze({ eye: [4, 3, 5], target: [0, 0, 0], up: [0, 1, 0], fov: 45, near: 0.1, far: 1000 });
-const NODE_FIELDS = ['translation', 'rotation', 'scale', 'parent', 'label', 'geometry', 'material', 'skin', 'relations'];
+const NODE_FIELDS = ['translation', 'rotation', 'scale', 'parent', 'label', 'geometry', 'material', 'skin', 'relations', 'decal', 'depthLayer'];
const MATERIAL_FIELDS = ['color', 'metallic', 'roughness', 'emission', 'emissiveColor', 'opacity', 'alphaMode', 'doubleSided', 'pattern', ...MATERIAL_LAYER_FIELDS];
const PATTERN_TEXTURE_FIELDS = ['map', 'normalMap', 'metallicRoughnessMap', 'emissiveMap', 'boxMapScale', 'boxMapAxis'];
const CAMERA_FIELDS = Object.keys(CAMERA_DEFAULTS);
@@ -283,6 +284,12 @@ function nodeFrom(value) {
identifier(value.geometry);
identifier(value.material);
}
+ if (value.decal !== undefined && typeof value.decal !== 'boolean') {
+ throw new TypeError('decal must be boolean.');
+ }
+ if (value.depthLayer !== undefined) {
+ integer(value.depthLayer, 0, MAXIMUM_DEPTH_LAYER, 'depthLayer');
+ }
if (value.skin !== undefined) {
if (value.geometry === undefined) {
throw new TypeError('Only mesh nodes can have a skin.');
@@ -1050,9 +1057,10 @@ export function createAgentScene(input, inputLimits = {}) {
const material = materialHandles.get(node.material).output;
const activePart = removedNodes.has(node.id) ? null : activeParts.get(node.id);
const existing = [activePart, preferredParts.get(node.id)]
- .find(part => part?.geometry === geometry && part.material === material && part.skin === binding?.skin);
+ .find(part => part?.geometry === geometry && part.material === material && part.skin === binding?.skin && depthLayerOf(part) === depthLayerOf(node));
return existing ?? Object.freeze({
name: node.id, geometry, material,
+ ...(depthLayerOf(node) ? { depthLayer: depthLayerOf(node) } : {}),
matrix: new Float32Array(graph.getNode(node.id).worldMatrix),
...(binding ? { skin: binding.skin } : {}),
});
@@ -1063,7 +1071,7 @@ export function createAgentScene(input, inputLimits = {}) {
const sourceRestParts = sameParts ? state.sourceRestParts : Object.freeze(nextParts);
const lightBakeResult = stageLightBake(recipe, sourceRestParts, graph);
const reflected = stageObjectReflections(recipe, sourceRestParts, lightBakeResult ? lightBakeResult.parts : sourceRestParts, graph);
- const restParts = stageLightLinks(recipe, reflected ? reflected.parts : lightBakeResult ? lightBakeResult.parts : sourceRestParts);
+ const restParts = stageCoplanarOffsets(recipe, stageLightLinks(recipe, reflected ? reflected.parts : lightBakeResult ? lightBakeResult.parts : sourceRestParts));
const stagedState = {
recipe, geometryRecords, geometries, graph, materialHandles,
// Part identity decides what the next stage reuses, so it compares the parts as built, before any bake.
@@ -1159,6 +1167,30 @@ export function createAgentScene(input, inputLimits = {}) {
return share !== null && share >= CLOSED_ROOM_SHARE ? [closedRoomDiagnostic(share)] : [];
}
+ // environment.resolveCoplanar 'offset' puts the smaller part of each coplanar pair on the next depth layer, so the
+ // renderer draws it with a polygon offset. Geometry never moves. The result is kept while the parts are the same objects.
+ let coplanarCache = null;
+ function stageCoplanarOffsets(recipe, parts) {
+ if (recipe.environment.resolveCoplanar !== 'offset') {
+ return parts;
+ }
+ if (coplanarCache?.parts === parts) {
+ return coplanarCache.resolved;
+ }
+ const resolved = Object.freeze(resolveCoplanarParts(parts));
+ coplanarCache = { parts, resolved };
+ return resolved;
+ }
+
+ // scene_inspect names coplanar pairs: the check is bounded, runs on inspect only and is kept until the scene changes.
+ let coplanarReportCache = null;
+ function coplanarProblems() {
+ if (coplanarReportCache?.revision !== revision) {
+ coplanarReportCache = { revision, problems: coplanarOverlapDiagnostics(findCoplanarOverlaps(state.parts)) };
+ }
+ return coplanarReportCache.problems;
+ }
+
// A bake costs a solver run, so an unchanged section on unchanged geometry reuses the last one.
function stagePhysics(recipe, geometryRecords) {
if (!recipe.physics) {
@@ -1347,7 +1379,7 @@ export function createAgentScene(input, inputLimits = {}) {
knownKeys(operation, ['type', lookField], 'operation');
const patch = operation[lookField];
// Spot and area lights, cascades and sun links are absent from a recipe until it sets them.
- const optionalFields = lookField === 'environment' ? ['spotLights', 'areaLights', 'shadowCascades', 'keyAffects', 'objectReflections'] : [];
+ const optionalFields = lookField === 'environment' ? ['spotLights', 'areaLights', 'shadowCascades', 'keyAffects', 'objectReflections', 'resolveCoplanar'] : [];
knownKeys(patch, [...Object.keys(candidate[lookField]), ...optionalFields], lookField);
const nestedField = lookField === 'environment' ? 'volumeFog' : lookField === 'effects' ? 'bloom' : null;
const merged = { ...candidate[lookField], ...(lookField === 'environment' ? environmentPatchWithSetup(patch) : patch) };
@@ -1496,7 +1528,7 @@ export function createAgentScene(input, inputLimits = {}) {
return result;
});
const resident = geometryStats(ownedGeometryRecords());
- const diagnostics = [...recipeDiagnostics(state.recipe), ...closedRoomProblems()];
+ const diagnostics = [...recipeDiagnostics(state.recipe), ...closedRoomProblems(), ...coplanarProblems()];
return {
revision, topologyRevision,
...(state.recipe.motion?.ik?.length ? { motionIk: agentSceneModule('motion').compileAgentMotion(state.recipe.motion, state.recipe).sweepIk() } : {}),
diff --git a/src/coplanar-overlap.js b/src/coplanar-overlap.js
new file mode 100644
index 00000000..4572c964
--- /dev/null
+++ b/src/coplanar-overlap.js
@@ -0,0 +1,340 @@
+// Finds pairs of parts that draw the same plane in the same place, which z-fight: a sign flush with a wall, a road marking
+// on asphalt, two boxes whose visible faces coincide. The work is bounded: a sweep over part bounds, then triangles only
+// inside the shared box of a pair, with a fixed budget for the whole scene (`truncated` says it ran out).
+// Only faces that look the same way count, since a face against a floor looks away from it and is culled. A part with a
+// double-sided material shows both sides, so there an opposite-facing pair counts too.
+
+/** Planes closer than this (metres) and facing the same way are treated as one plane. */
+export const COPLANAR_TOLERANCE = 0.001;
+/** Overlaps smaller than this (square metres) are edge contact, not a fight. */
+export const COPLANAR_MINIMUM_AREA = 1e-4;
+/** Highest layer `resolveCoplanar` hands out; the draw-time offset grows with the layer. */
+export const MAXIMUM_DEPTH_LAYER = 4;
+/** The distance suggested in the fix text, in metres. */
+export const SUGGESTED_OFFSET = 0.002;
+const DEFAULT_WORK_BUDGET = 1_000_000;
+const MAXIMUM_TRIANGLES_PER_PART_IN_PAIR = 512;
+const SAME_FACING = Math.cos(Math.PI / 180);
+const REPORTED_PAIRS = 8;
+
+const localBoundsByGeometry = new WeakMap();
+
+function localBounds(geometry) {
+ let bounds = localBoundsByGeometry.get(geometry);
+ if (bounds) return bounds;
+ bounds = [Infinity, Infinity, Infinity, -Infinity, -Infinity, -Infinity];
+ const { positions } = geometry;
+ for (let offset = 0; offset < positions.length; offset += 3) {
+ for (let axis = 0; axis < 3; axis++) {
+ bounds[axis] = Math.min(bounds[axis], positions[offset + axis]);
+ bounds[3 + axis] = Math.max(bounds[3 + axis], positions[offset + axis]);
+ }
+ }
+ localBoundsByGeometry.set(geometry, bounds);
+ return bounds;
+}
+
+function worldBounds(part) {
+ const local = localBounds(part.geometry);
+ const matrix = part.matrix;
+ const bounds = [Infinity, Infinity, Infinity, -Infinity, -Infinity, -Infinity];
+ for (let corner = 0; corner < 8; corner++) {
+ const x = corner & 1 ? local[3] : local[0];
+ const y = corner & 2 ? local[4] : local[1];
+ const z = corner & 4 ? local[5] : local[2];
+ for (let axis = 0; axis < 3; axis++) {
+ const value = matrix[axis] * x + matrix[4 + axis] * y + matrix[8 + axis] * z + matrix[12 + axis];
+ bounds[axis] = Math.min(bounds[axis], value);
+ bounds[3 + axis] = Math.max(bounds[3 + axis], value);
+ }
+ }
+ return bounds;
+}
+
+function determinantSign(matrix) {
+ const determinant = matrix[0] * (matrix[5] * matrix[10] - matrix[6] * matrix[9])
+ - matrix[4] * (matrix[1] * matrix[10] - matrix[2] * matrix[9])
+ + matrix[8] * (matrix[1] * matrix[6] - matrix[2] * matrix[5]);
+ return determinant < 0 ? -1 : 1;
+}
+
+// World-space triangles of one part that touch `region`, each as corners (9 numbers) plus a unit normal (3).
+function trianglesInRegion(part, region, tolerance) {
+ const { positions, indices } = part.geometry;
+ const matrix = part.matrix;
+ const flip = determinantSign(matrix);
+ const triangles = [];
+ const corners = new Float64Array(9);
+ for (let triangle = 0; triangle < indices.length / 3; triangle++) {
+ let outside = false;
+ for (let corner = 0; corner < 3; corner++) {
+ const vertex = indices[triangle * 3 + corner] * 3;
+ for (let axis = 0; axis < 3; axis++) {
+ corners[corner * 3 + axis] = matrix[axis] * positions[vertex] + matrix[4 + axis] * positions[vertex + 1] + matrix[8 + axis] * positions[vertex + 2] + matrix[12 + axis];
+ }
+ }
+ for (let axis = 0; axis < 3 && !outside; axis++) {
+ const low = Math.min(corners[axis], corners[3 + axis], corners[6 + axis]);
+ const high = Math.max(corners[axis], corners[3 + axis], corners[6 + axis]);
+ outside = high < region[axis] - tolerance || low > region[3 + axis] + tolerance;
+ }
+ if (outside) continue;
+ const edgeOne = [corners[3] - corners[0], corners[4] - corners[1], corners[5] - corners[2]];
+ const edgeTwo = [corners[6] - corners[0], corners[7] - corners[1], corners[8] - corners[2]];
+ const normal = [
+ edgeOne[1] * edgeTwo[2] - edgeOne[2] * edgeTwo[1],
+ edgeOne[2] * edgeTwo[0] - edgeOne[0] * edgeTwo[2],
+ edgeOne[0] * edgeTwo[1] - edgeOne[1] * edgeTwo[0],
+ ];
+ const length = Math.hypot(...normal);
+ if (!(length > 1e-12)) continue;
+ triangles.push({ corners: Float64Array.from(corners), normal: normal.map(component => component * flip / length) });
+ if (triangles.length >= MAXIMUM_TRIANGLES_PER_PART_IN_PAIR) break;
+ }
+ return triangles;
+}
+
+function planeDistance(first, second, corner) {
+ const normal = first.normal;
+ return (second.corners[corner * 3] - first.corners[0]) * normal[0]
+ + (second.corners[corner * 3 + 1] - first.corners[1]) * normal[1]
+ + (second.corners[corner * 3 + 2] - first.corners[2]) * normal[2];
+}
+
+// Projects a triangle to the plane's two largest axes, clips it against the other (Sutherland-Hodgman) and returns the
+// shared area in square metres.
+function sharedArea(first, second) {
+ const normal = first.normal.map(Math.abs);
+ const dropped = normal.indexOf(Math.max(...normal));
+ const axes = [0, 1, 2].filter(axis => axis !== dropped);
+ const project = (triangle, corner) => [triangle.corners[corner * 3 + axes[0]], triangle.corners[corner * 3 + axes[1]]];
+ let polygon = [0, 1, 2].map(corner => project(second, corner));
+ const clipper = [0, 1, 2].map(corner => project(first, corner));
+ const clipperTurn = signedArea(clipper) >= 0 ? 1 : -1;
+ for (let edge = 0; edge < 3 && polygon.length > 0; edge++) {
+ const start = clipper[edge];
+ const end = clipper[(edge + 1) % 3];
+ const side = point => clipperTurn * ((end[0] - start[0]) * (point[1] - start[1]) - (end[1] - start[1]) * (point[0] - start[0]));
+ const next = [];
+ for (let index = 0; index < polygon.length; index++) {
+ const current = polygon[index];
+ const previous = polygon[(index + polygon.length - 1) % polygon.length];
+ const currentSide = side(current);
+ const previousSide = side(previous);
+ if ((currentSide >= 0) !== (previousSide >= 0)) {
+ const along = previousSide / (previousSide - currentSide);
+ next.push([previous[0] + (current[0] - previous[0]) * along, previous[1] + (current[1] - previous[1]) * along]);
+ }
+ if (currentSide >= 0) next.push(current);
+ }
+ polygon = next;
+ }
+ return polygon.length < 3 ? 0 : Math.abs(signedArea(polygon)) / Math.max(normal[dropped], 1e-12);
+}
+
+function signedArea(polygon) {
+ let total = 0;
+ for (let index = 0; index < polygon.length; index++) {
+ const next = polygon[(index + 1) % polygon.length];
+ total += polygon[index][0] * next[1] - next[0] * polygon[index][1];
+ }
+ return total / 2;
+}
+
+function boundsOverlapRegion(first, second, tolerance) {
+ const region = [0, 0, 0, 0, 0, 0];
+ for (let axis = 0; axis < 3; axis++) {
+ region[axis] = Math.max(first[axis], second[axis]);
+ region[3 + axis] = Math.min(first[3 + axis], second[3 + axis]);
+ if (region[axis] > region[3 + axis] + tolerance) return null;
+ }
+ return region;
+}
+
+function diagonal(bounds) {
+ return Math.hypot(bounds[3] - bounds[0], bounds[4] - bounds[1], bounds[5] - bounds[2]);
+}
+
+function resolvedByLayer(first, second) {
+ return depthLayerOf(first) !== depthLayerOf(second);
+}
+
+/** The layer a part draws on: `depthLayer` if set, else 1 for `decal: true`, else 0. */
+export function depthLayerOf(part) {
+ return part.depthLayer ?? (part.decal ? 1 : 0);
+}
+
+function pairOverlap(first, second, region, tolerance, budget) {
+ const bothSides = first.part.material?.doubleSided === true || second.part.material?.doubleSided === true;
+ const firstTriangles = trianglesInRegion(first.part, region, tolerance);
+ const secondTriangles = trianglesInRegion(second.part, region, tolerance);
+ let area = 0;
+ let distance = 0;
+ let normal = null;
+ let largestPiece = 0;
+ for (const firstTriangle of firstTriangles) {
+ if (budget.work > budget.limit) break;
+ for (const secondTriangle of secondTriangles) {
+ budget.work++;
+ const facing = firstTriangle.normal[0] * secondTriangle.normal[0] + firstTriangle.normal[1] * secondTriangle.normal[1] + firstTriangle.normal[2] * secondTriangle.normal[2];
+ const visibleTogether = facing >= SAME_FACING || (bothSides && facing <= -SAME_FACING);
+ if (!visibleTogether) continue;
+ let largest = 0;
+ for (let corner = 0; corner < 3; corner++) largest = Math.max(largest, Math.abs(planeDistance(firstTriangle, secondTriangle, corner)));
+ if (largest > tolerance) continue;
+ const shared = sharedArea(firstTriangle, secondTriangle);
+ if (shared <= 0) continue;
+ area += shared;
+ distance = Math.max(distance, largest);
+ if (shared > largestPiece) {
+ largestPiece = shared;
+ normal = firstTriangle.normal;
+ }
+ }
+ }
+ return area >= COPLANAR_MINIMUM_AREA ? { area, distance, normal } : null;
+}
+
+// Broad phase: a uniform grid sized to the typical part. A pair is tested once, in the lowest cell both parts cover. Parts
+// spanning more than LARGE_CELLS cells (floors, long walls) are tested against everything instead of entering the grid.
+const LARGE_CELLS = 8;
+const CELL_LIMIT = 65535;
+
+function cellCoordinate(value, cellSize) {
+ return Math.max(-CELL_LIMIT, Math.min(CELL_LIMIT, Math.floor(value / cellSize)));
+}
+
+function cellKey(x, y, z) {
+ return ((x + CELL_LIMIT) * 131072 + (y + CELL_LIMIT)) * 131072 + (z + CELL_LIMIT);
+}
+
+function forEachCandidatePair(entries, tolerance, budget, test) {
+ const meanExtents = entries.map(entry => ((entry.bounds[3] - entry.bounds[0]) + (entry.bounds[4] - entry.bounds[1]) + (entry.bounds[5] - entry.bounds[2])) / 3).sort((first, second) => first - second);
+ const cellSize = Math.max(meanExtents[Math.floor(meanExtents.length / 2)], 0.01);
+ const grid = new Map();
+ const large = [];
+ for (const entry of entries) {
+ const low = [0, 1, 2].map(axis => cellCoordinate(entry.bounds[axis] - tolerance, cellSize));
+ const high = [0, 1, 2].map(axis => cellCoordinate(entry.bounds[3 + axis] + tolerance, cellSize));
+ entry.lowCell = low;
+ if (high.some((value, axis) => value - low[axis] >= LARGE_CELLS)) {
+ large.push(entry);
+ continue;
+ }
+ for (let x = low[0]; x <= high[0]; x++) {
+ for (let y = low[1]; y <= high[1]; y++) {
+ for (let z = low[2]; z <= high[2]; z++) {
+ const key = cellKey(x, y, z);
+ const members = grid.get(key);
+ if (members) members.push(entry);
+ else grid.set(key, [entry]);
+ }
+ }
+ }
+ }
+ for (const [key, members] of grid) {
+ const z = key % 131072 - CELL_LIMIT;
+ const y = Math.floor(key / 131072) % 131072 - CELL_LIMIT;
+ const x = Math.floor(key / 17179869184) - CELL_LIMIT;
+ for (let first = 0; first < members.length; first++) {
+ for (let second = first + 1; second < members.length; second++) {
+ const a = members[first].lowCell;
+ const b = members[second].lowCell;
+ if (Math.max(a[0], b[0]) !== x || Math.max(a[1], b[1]) !== y || Math.max(a[2], b[2]) !== z) continue;
+ if (budget.work > budget.limit) return;
+ test(members[first], members[second]);
+ }
+ }
+ }
+ const largeSet = new Set(large);
+ for (let index = 0; index < large.length; index++) {
+ for (const other of entries) {
+ if (other === large[index] || (largeSet.has(other) && large.indexOf(other) < index)) continue;
+ if (budget.work > budget.limit) return;
+ test(large[index], other);
+ }
+ }
+}
+
+/**
+ * Pairs of parts that draw the same plane in the same place. A part is `{ name, geometry: { positions, indices }, matrix,
+ * material?, decal?, depthLayer?, skin?, morph? }`; skinned and morphed parts are skipped. Returns
+ * `{ overlaps, truncated, work }` with each overlap as `{ smaller, larger, area, distance, normal }` (areas in square
+ * metres, the larger part by bounds diagonal). `work` counts bounds and triangle tests, capped by `workBudget`.
+ */
+export function findCoplanarOverlaps(parts, { tolerance = COPLANAR_TOLERANCE, workBudget = DEFAULT_WORK_BUDGET } = {}) {
+ const entries = [];
+ for (const part of parts) {
+ if (part.skin || part.morph || !part.geometry?.indices?.length) continue;
+ entries.push({ part, bounds: worldBounds(part) });
+ }
+ const budget = { work: 0, limit: workBudget };
+ const overlaps = [];
+ if (entries.length < 2) return { overlaps, truncated: false, work: 0 };
+ const test = (first, second) => {
+ budget.work++;
+ const region = boundsOverlapRegion(first.bounds, second.bounds, tolerance);
+ if (!region || resolvedByLayer(first.part, second.part)) return;
+ const found = pairOverlap(first, second, region, tolerance, budget);
+ if (!found) return;
+ const firstIsLarger = diagonal(first.bounds) >= diagonal(second.bounds);
+ overlaps.push({ smaller: (firstIsLarger ? second : first).part, larger: (firstIsLarger ? first : second).part, ...found });
+ };
+ forEachCandidatePair(entries, tolerance, budget, test);
+ const truncated = budget.work > workBudget;
+ overlaps.sort((first, second) => second.area - first.area || String(first.smaller.name).localeCompare(String(second.smaller.name)));
+ return { overlaps, truncated, work: budget.work };
+}
+
+function metres(value) {
+ return `${Math.round(value * 1000) / 1000}`;
+}
+
+/** Warnings in the shape of `agent-diagnostics.js`, the biggest overlaps first, plus one line for the rest. */
+export function coplanarOverlapDiagnostics({ overlaps, truncated }) {
+ const problems = overlaps.slice(0, REPORTED_PAIRS).map(({ smaller, larger, area, distance, normal }) => ({
+ kind: 'coplanar-overlap',
+ severity: 'warning',
+ target: smaller.name,
+ parts: [smaller.name, larger.name],
+ area: Math.round(area * 10000) / 10000,
+ message: `${smaller.name} and ${larger.name} draw the same plane (${metres(distance * 1000)} mm apart, ${metres(area)} m2 overlap) and will flicker (z-fighting).`,
+ fix: `Move ${smaller.name} ${metres(SUGGESTED_OFFSET * 1000)} mm along its normal [${normal.map(component => Math.round(component * 1000) / 1000).join(', ')}], or set decal: true on ${smaller.name}, or set environment.resolveCoplanar to 'offset' to bias it at draw time without moving it.`,
+ }));
+ if (overlaps.length > REPORTED_PAIRS || (truncated && overlaps.length)) {
+ problems.push({
+ kind: 'coplanar-overlap',
+ severity: 'warning',
+ target: 'scene',
+ message: truncated ? `${overlaps.length} coplanar pairs found before the check hit its work budget; more may exist.` : `${overlaps.length - REPORTED_PAIRS} more coplanar pairs.`,
+ fix: "Set environment.resolveCoplanar to 'offset' to bias every smaller part at draw time.",
+ });
+ }
+ return problems;
+}
+
+/**
+ * The layer each smaller part of a pair should draw on, as a Map from part to layer. A part that is the smaller one against
+ * a part already on layer n gets n + 1, up to MAXIMUM_DEPTH_LAYER. Parts that set their own layer are left alone.
+ */
+export function coplanarLayers(overlaps) {
+ const layers = new Map();
+ const ordered = [...overlaps].sort((first, second) => diagonalOfPart(second.larger) - diagonalOfPart(first.larger));
+ for (const { smaller, larger } of ordered) {
+ if (smaller.decal !== undefined || smaller.depthLayer !== undefined) continue;
+ const base = layers.get(larger) ?? depthLayerOf(larger);
+ layers.set(smaller, Math.min(MAXIMUM_DEPTH_LAYER, Math.max(layers.get(smaller) ?? 0, base + 1)));
+ }
+ return layers;
+}
+
+function diagonalOfPart(part) {
+ return diagonal(worldBounds(part));
+}
+
+/** `parts` with `depthLayer` set on the smaller part of each coplanar pair; other parts are returned as they are. */
+export function resolveCoplanarParts(parts) {
+ const layers = coplanarLayers(findCoplanarOverlaps(parts).overlaps);
+ if (layers.size === 0) return parts;
+ return parts.map(part => (layers.has(part) ? Object.freeze({ ...part, depthLayer: layers.get(part) }) : part));
+}
diff --git a/src/frame-diagnostics.js b/src/frame-diagnostics.js
index b584ad6b..6cd5203b 100644
--- a/src/frame-diagnostics.js
+++ b/src/frame-diagnostics.js
@@ -1,4 +1,5 @@
import { resolveShadowLight } from './shadow-light.js';
+import { coplanarOverlapDiagnostics } from './coplanar-overlap.js';
/**
* Diagnostics for a frame that renders without error but not as asked. They use the shape of `agent-diagnostics.js`
@@ -28,7 +29,7 @@ function shadowDirectionProblem(world, lightDirection, shadowBounds) {
'Drop shadowBounds.eye, or point lightDirection from shadowBounds.target to it.');
}
-export function frameDiagnostics({ world, depth, effects, lightDirection, shadowBounds }) {
+export function frameDiagnostics({ world, depth, effects, lightDirection, shadowBounds, coplanarOverlaps = null }) {
const problems = [];
if (effects.ambientOcclusion > 0 && !depth) {
problems.push(warning('ambient-occlusion-without-depth', 'effects.ambientOcclusion',
@@ -39,5 +40,6 @@ export function frameDiagnostics({ world, depth, effects, lightDirection, shadow
const problem = shadowDirectionProblem(world, lightDirection, shadowBounds);
if (problem) problems.push(problem);
}
+ if (coplanarOverlaps?.overlaps.length) problems.push(...coplanarOverlapDiagnostics(coplanarOverlaps));
return problems.length ? problems : NO_DIAGNOSTICS;
}
diff --git a/src/renderer.js b/src/renderer.js
index 8ec77ca2..8064d07a 100644
--- a/src/renderer.js
+++ b/src/renderer.js
@@ -7,6 +7,7 @@ import { planRenderSize, estimateTextureBytes, estimateFrameBytes } from './budg
import { applyProjection } from './camera.js';
import { resolveEffects } from './effects.js';
import { frameDiagnostics } from './frame-diagnostics.js';
+import { depthLayerOf, findCoplanarOverlaps, MAXIMUM_DEPTH_LAYER } from './coplanar-overlap.js';
import { createLightingState, updateLightingState } from './lighting.js';
import { SHADOW_ATLAS_WIDTH, SHADOW_ATLAS_HEIGHT, tileViewport, writeShadowTile } from './local-shadows.js';
import { resolveVolumeFog, volumeShadowAmbient } from './volumetric.js';
@@ -204,6 +205,17 @@ function materialAlphaState(material) {
return [alphaMode, alphaCutoff, opacity, material.doubleSided === true];
}
+// A decal or depth layer draws with a scoped polygon offset so it wins against the surface it lies on (z-fighting).
+// Larger layers win over smaller ones; geometry never moves.
+const DEPTH_LAYER_UNITS = 4;
+
+function validateDepthLayer(part) {
+ if (part.decal !== undefined && typeof part.decal !== 'boolean') throw new TypeError('decal must be a boolean');
+ if (part.depthLayer !== undefined && (!Number.isInteger(part.depthLayer) || part.depthLayer < 0 || part.depthLayer > MAXIMUM_DEPTH_LAYER)) {
+ throw new RangeError(`depthLayer must be an integer from 0 to ${MAXIMUM_DEPTH_LAYER}`);
+ }
+}
+
// Translucent glass is not a shadow caster unless the part asks for it.
function castsShadow(part) {
return part.castShadow ?? (part.material.alphaMode ?? 'opaque') !== 'blend';
@@ -320,6 +332,7 @@ export function groupParts(parts, batching = true) {
const morphInfos = new Map();
for (const part of parts) {
validateTransform(part);
+ validateDepthLayer(part);
if (part.castShadow !== undefined && typeof part.castShadow !== 'boolean') throw new TypeError('castShadow must be a boolean');
validateSkinGeometry(part.geometry, part.skin);
if (part.skin) validateSkinPose(part.skin, part.geometry, part.matrix);
@@ -331,7 +344,7 @@ export function groupParts(parts, batching = true) {
const key = batching ? part.geometry : part;
if (!groups.has(key)) groups.set(key, new Map());
let maps = groups.get(key);
- for (const value of [...materialMapState(part.material), ...materialLayerState(part.material), part.skin ?? null, part.morph ?? null, castsShadow(part), renderPass(part.material), part.lods ?? null, part.shadowLods ?? null, ...materialAlphaState(part.material)]) {
+ for (const value of [...materialMapState(part.material), ...materialLayerState(part.material), part.skin ?? null, part.morph ?? null, castsShadow(part), depthLayerOf(part), renderPass(part.material), part.lods ?? null, part.shadowLods ?? null, ...materialAlphaState(part.material)]) {
if (!maps.has(value)) maps.set(value, new Map());
maps = maps.get(value);
}
@@ -1023,7 +1036,7 @@ export class Renderer67 {
const [alphaMode, alphaCutoff, opacity, doubleSided] = materialAlphaState(parts[0].material);
const layerState = materialLayerState(parts[0].material);
const culling = this.createCullingState(parts);
- const batch = { ...culling, alphaMode, alphaCutoff, opacity, doubleSided, layerState, parts: [...parts], vertexArray, instanceBuffer, instanceData, textures, mapState, splat, lightMapTexture, texture: textures[0], map, skin, skinTexture, influenceTexture, morph, morphTexture, morphWeights, indexCount: geometry.indices.length, instanceCount: parts.length, floor: parts[0].material.tag === 'floor', castShadow: castsShadow(parts[0]), pass: renderPass(parts[0].material) };
+ const batch = { ...culling, alphaMode, alphaCutoff, opacity, doubleSided, layerState, parts: [...parts], vertexArray, instanceBuffer, instanceData, textures, mapState, splat, lightMapTexture, texture: textures[0], map, skin, skinTexture, influenceTexture, morph, morphTexture, morphWeights, indexCount: geometry.indices.length, instanceCount: parts.length, floor: parts[0].material.tag === 'floor', castShadow: castsShadow(parts[0]), depthLayer: depthLayerOf(parts[0]), pass: renderPass(parts[0].material) };
if (parts[0].lods) culling.levelGeometries.forEach((geometryOfLevel, level) => this.levelDraw(batch, level));
culling.shadowLevels?.levelGeometries.forEach((geometryOfLevel, level) => this.levelDraw(batch, level, batch.shadowLevels));
parts.forEach((part, index) => this.partLocations.set(part, { batch, index, geometry: part.geometry, map, mapState, layerState, skin, jointMatrices: skin?.jointMatrices, skinIndices: geometry.skinIndices, skinWeights: geometry.skinWeights, morph, morphWeights: morph?.weights, morphTargets: geometry.morphTargets, normalMatrix: mat3.create(), committedMatrix: batch.instanceData.subarray(index * INSTANCE_STRIDE, index * INSTANCE_STRIDE + 16) }));
@@ -1050,7 +1063,7 @@ export class Renderer67 {
const mapState = materialMapState(first.material);
const sameParts = batch?.parts.length === group.length && batch.parts.every((part, index) => part === group[index]);
const alphaState = materialAlphaState(first.material);
- const sameState = location?.geometry === first.geometry && batch?.castShadow === castsShadow(first) &&
+ const sameState = location?.geometry === first.geometry && batch?.castShadow === castsShadow(first) && (batch.depthLayer ?? 0) === depthLayerOf(first) &&
batch.floor === (first.material.tag === 'floor') && batchPass(batch) === renderPass(first.material) &&
[batch.alphaMode, batch.alphaCutoff, batch.opacity, batch.doubleSided].every((value, index) => value === alphaState[index]) &&
batch.mapState.every((value, index) => value === mapState[index]) &&
@@ -1141,6 +1154,7 @@ export class Renderer67 {
this.triangles = parts.reduce((total, part) => total + part.geometry.indices.length / 3, 0);
this.updateBatches.clear();
this.shadowsDirty = true;
+ if (this.coplanarState) this.coplanarState.dirty = true;
this.updateParts(renderParts);
return parts.length;
}
@@ -1203,6 +1217,8 @@ export class Renderer67 {
if (part.skin || part.morph) this.updatePartIdentities.add(part);
if (part.castShadow !== undefined && typeof part.castShadow !== 'boolean') throw new TypeError('castShadow must be a boolean');
if (castsShadow(part) !== location.batch.castShadow) throw new Error(`Shadow casting changes require a new renderer: ${part.name}`);
+ validateDepthLayer(part);
+ if (depthLayerOf(part) !== (location.batch.depthLayer ?? 0)) throw new Error(`Decal and depthLayer changes require replaceParts or a new renderer: ${part.name}`);
// A material whose fields still equal the ones that passed the full checks below needs none of them again.
const materialUnchanged = location.materialSnapshot?.matches(part.material) === true;
if (!materialUnchanged) {
@@ -1365,6 +1381,7 @@ export class Renderer67 {
this.drawBatch(batch, false, selection, levelSet);
}
context.disable(context.POLYGON_OFFSET_FILL);
+ this.activeDepthLayer = 0;
context.enable(context.CULL_FACE);
}
@@ -1913,6 +1930,7 @@ export class Renderer67 {
}
return;
}
+ this.applyDepthLayer(batch.depthLayer);
const useCoverage = masked && this.samples > 1 && !this.benchmark && !this.renderingPass;
if (useCoverage) {
context.enable(context.SAMPLE_ALPHA_TO_COVERAGE);
@@ -1927,6 +1945,32 @@ export class Renderer67 {
context.uniform1f(uniforms.doubleSided, batch.doubleSided ? 1 : 0);
}
+ /** Sets the scoped polygon offset of a depth layer for the colour pass; layer 0 is the plain depth test. */
+ applyDepthLayer(layer) {
+ if (layer === (this.activeDepthLayer ?? 0)) return;
+ const context = this.context;
+ if (layer > 0) {
+ context.enable(context.POLYGON_OFFSET_FILL);
+ context.polygonOffset(-layer, -layer * DEPTH_LAYER_UNITS);
+ } else {
+ context.disable(context.POLYGON_OFFSET_FILL);
+ }
+ this.activeDepthLayer = layer;
+ }
+
+ /**
+ * Coplanar-overlap warnings for the parts as first laid out or last replaced. The check is bounded (src/coplanar-overlap.js)
+ * and runs once per layout, not per frame, so parts that move later are not rechecked.
+ */
+ coplanarOverlapReport() {
+ const state = this.coplanarState ??= { dirty: true, result: null };
+ if (state.dirty) {
+ state.result = findCoplanarOverlaps(this.batches.flatMap(batch => batch.parts));
+ state.dirty = false;
+ }
+ return state.result;
+ }
+
/** Reorders a blend batch's instances back to front for this eye; translation columns stand in for object centers. */
uploadSortedInstances(batch, eye) {
if (batch.instanceCount < 2) return;
@@ -1975,6 +2019,7 @@ export class Renderer67 {
this.drawAlphaBatch(batch, true);
}
context.depthMask(true);
+ this.applyDepthLayer(0);
context.disable(context.BLEND);
context.disable(context.SAMPLE_ALPHA_TO_COVERAGE);
context.enable(context.CULL_FACE);
@@ -2073,7 +2118,7 @@ export class Renderer67 {
// The shadow view follows the sun, so a moved sun redraws the map.
const lightChanged = String(this.activeLightDirection) !== String(environment.lightDirection);
this.activeLightDirection = environment.lightDirection;
- this.diagnostics = frameDiagnostics({ world: this.world, depth: this.depth, effects, lightDirection: environment.lightDirection, shadowBounds: this.shadowBounds });
+ this.diagnostics = frameDiagnostics({ world: this.world, depth: this.depth, effects, lightDirection: environment.lightDirection, shadowBounds: this.shadowBounds, coplanarOverlaps: this.benchmark ? null : this.coplanarOverlapReport() });
const start = performance.now();
const context = this.context;
this.beginGpuTiming();
@@ -2164,6 +2209,7 @@ export class Renderer67 {
this.drawAlphaBatch(batch, true, passMode !== OBJECT_ID_PASS_MODE);
}
}
+ this.applyDepthLayer(0);
context.disable(context.SAMPLE_ALPHA_TO_COVERAGE);
context.enable(context.CULL_FACE);
context.bindVertexArray(null);
diff --git a/tests/coplanar-overlap.test.js b/tests/coplanar-overlap.test.js
new file mode 100644
index 00000000..c97d2bf3
--- /dev/null
+++ b/tests/coplanar-overlap.test.js
@@ -0,0 +1,113 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import { createAgentScene } from '../src/agent-scene.js';
+import { findCoplanarOverlaps, coplanarOverlapDiagnostics, resolveCoplanarParts, depthLayerOf } from '../src/coplanar-overlap.js';
+import { frameDiagnostics } from '../src/frame-diagnostics.js';
+import { groupParts, Renderer67 } from '../src/renderer.js';
+import { resolveEffects } from '../src/effects.js';
+
+function node(id, translation, scale, extra = {}) {
+ return { id, geometry: 'box', material: 'paint', translation, scale, ...extra };
+}
+
+function recipe(nodes, environment) {
+ return {
+ format: '67js.scene', schemaVersion: 1,
+ geometries: [{ id: 'box', type: 'box', bevel: 0 }],
+ materials: [{ id: 'paint', color: [0.5, 0.5, 0.5] }],
+ nodes,
+ ...(environment ? { environment } : {}),
+ };
+}
+
+function coplanarWarnings(nodes, environment) {
+ const inspection = createAgentScene(recipe(nodes, environment)).inspect();
+ return (inspection.diagnostics ?? []).filter(entry => entry.kind === 'coplanar-overlap');
+}
+
+// The wall's front face is at z = 0.1; the sign shares that face and sits inside the wall's outline.
+const wall = node('wall', [0, 0, 0], [10, 4, 0.2]);
+const sign = node('sign', [0, 0, 0], [1, 0.5, 0.2]);
+
+test('a sign flush with a wall is reported with both parts, the area and a fix', () => {
+ const warnings = coplanarWarnings([wall, sign]);
+ assert.equal(warnings.length, 1);
+ const [warning] = warnings;
+ assert.deepEqual(warning.parts, ['sign', 'wall']);
+ assert.match(warning.message, /sign and wall/);
+ assert.ok(warning.area > 0.45 && warning.area < 1.1, `shared area ${warning.area}`);
+ assert.match(warning.fix, /decal: true/);
+ assert.match(warning.fix, /resolveCoplanar/);
+ assert.match(warning.fix, /along its normal/);
+});
+
+test('two boxes that share a visible top face are reported', () => {
+ const warnings = coplanarWarnings([node('big', [0, 0, 0], [2, 1, 2]), node('small', [0.5, 0, 0], [1, 1, 1])]);
+ assert.equal(warnings.length, 1);
+ assert.deepEqual(warnings[0].parts, ['small', 'big']);
+});
+
+test('a box resting on a floor is quiet', () => {
+ assert.deepEqual(coplanarWarnings([node('floor', [0, 0, 0], [10, 0.2, 10]), node('crate', [0, 0.6, 0], [1, 1, 1])]), []);
+});
+
+test('boxes that only touch along an edge or side by side are quiet', () => {
+ assert.deepEqual(coplanarWarnings([node('left', [-0.5, 0, 0], [1, 1, 1]), node('right', [0.5, 0, 0], [1, 1, 1])]), []);
+ assert.deepEqual(coplanarWarnings([node('first', [0, 0, 0], [1, 1, 1]), node('second', [1, 1, 0], [1, 1, 1])]), []);
+});
+
+test('a gap of half a millimetre still fights, a gap of five millimetres does not', () => {
+ assert.equal(coplanarWarnings([wall, node('near', [0, 0, 0.0005], [1, 0.5, 0.2])]).length, 1);
+ assert.deepEqual(coplanarWarnings([wall, node('clear', [0, 0, 0.005], [1, 0.5, 0.2])]), []);
+});
+
+test('decal, depthLayer and resolveCoplanar all silence the pair without moving geometry', () => {
+ assert.deepEqual(coplanarWarnings([wall, { ...sign, decal: true }]), []);
+ assert.deepEqual(coplanarWarnings([wall, { ...sign, depthLayer: 2 }]), []);
+ const scene = createAgentScene(recipe([wall, sign], { resolveCoplanar: 'offset' }));
+ const [wallPart, signPart] = ['wall', 'sign'].map(name => scene.parts.find(part => part.name === name));
+ assert.equal(depthLayerOf(wallPart), 0);
+ assert.equal(depthLayerOf(signPart), 1);
+ assert.deepEqual(Array.from(signPart.matrix), Array.from(createAgentScene(recipe([wall, sign])).parts.find(part => part.name === 'sign').matrix));
+ assert.deepEqual((scene.inspect().diagnostics ?? []).filter(entry => entry.kind === 'coplanar-overlap'), []);
+});
+
+test('node decal and depthLayer are validated', () => {
+ assert.throws(() => createAgentScene(recipe([wall, { ...sign, decal: 'yes' }])), /decal must be boolean/);
+ assert.throws(() => createAgentScene(recipe([wall, { ...sign, depthLayer: 9 }])), /depthLayer must be within 0 and 4/);
+ assert.throws(() => createAgentScene(recipe([wall], { resolveCoplanar: true })), /resolveCoplanar/);
+});
+
+test('renderer diagnostics carry the same warning, and a decal batches apart from its wall', () => {
+ const scene = createAgentScene(recipe([wall, sign]));
+ const result = findCoplanarOverlaps(scene.parts);
+ const problems = frameDiagnostics({ world: false, depth: true, effects: resolveEffects({}), coplanarOverlaps: result });
+ assert.deepEqual(problems.map(problem => problem.kind), ['coplanar-overlap']);
+ const resolved = resolveCoplanarParts(scene.parts);
+ assert.equal(groupParts(scene.parts).length, 1);
+ assert.equal(groupParts(resolved).length, 2);
+});
+
+test('the polygon offset is scoped to the layer and switched off for layer 0', () => {
+ const calls = [];
+ const context = {
+ POLYGON_OFFSET_FILL: 'fill',
+ enable: capability => calls.push(['enable', capability]),
+ disable: capability => calls.push(['disable', capability]),
+ polygonOffset: (factor, units) => calls.push(['offset', factor, units]),
+ };
+ const fake = { context, activeDepthLayer: 0 };
+ Renderer67.prototype.applyDepthLayer.call(fake, 0);
+ assert.deepEqual(calls, []);
+ Renderer67.prototype.applyDepthLayer.call(fake, 2);
+ Renderer67.prototype.applyDepthLayer.call(fake, 2);
+ Renderer67.prototype.applyDepthLayer.call(fake, 0);
+ assert.deepEqual(calls, [['enable', 'fill'], ['offset', -2, -8], ['disable', 'fill']]);
+});
+
+test('the check is bounded: a work budget ends the sweep and says so', () => {
+ const scene = createAgentScene(recipe([wall, sign]));
+ const result = findCoplanarOverlaps(scene.parts, { workBudget: 0 });
+ assert.equal(result.truncated, true);
+ assert.deepEqual(coplanarOverlapDiagnostics({ overlaps: [], truncated: true }), []);
+});