Skip to content

armgit / 67.js

Public Imported from GitHub
0

3D engine that AI agents drive

Rank flush and near-flush triangles so they stop flickering by default (#751)

Nguyen Xuan An17599eed0ab0
diff --git a/changes/751-flush-rank.size.md b/changes/751-flush-rank.size.md
new file mode 100644
index 00000000..7c19dea4
--- /dev/null
+++ b/changes/751-flush-rank.size.md
@@ -0,0 +1,17 @@
+- entry:core: the depth rank (a view-space bias in the vertex shader, ranked index ranges in the draw loop) lives in the core, +494 bytes gzip (85185 to 85679); it is what makes decals and flush faces separate the same way on every depth format
+- entry:coplanar-overlap: the triangle-level flush search and the rank resolver, +3848 bytes gzip (4032 to 7880); an addon chunk, loaded by agent scenes and by renderers that pass resolveCoplanar
+- scene:lit-box: same core growth (+483 bytes gzip); accepted for flicker-free rendering, optimisation later
+- scene:gltf-box: same core growth (+509 bytes gzip); accepted for flicker-free rendering, optimisation later
+- scene:gltf-box+lazy: same core growth (+509 bytes gzip); accepted for flicker-free rendering, optimisation later
+- scene:agent-scene: same core growth plus the leftover report wiring (+749 bytes gzip); accepted for flicker-free rendering, optimisation later
+- scene:agent-scene+lazy: the core growth plus the larger flush search chunk; it is the fix, so it has to load
+- goal:lit-box: the growth is the depth rank code in the core; accepted for flicker-free rendering, optimisation later
+- goal:gltf-box: the growth is the depth rank code in the core; accepted for flicker-free rendering, optimisation later
+- goal:agent-scene: the growth is the depth rank code in the core; accepted for flicker-free rendering, optimisation later
+
+Measured on the Melbourne drape map (282,399 triangles, 9 parts; RTX 3060 through Chrome, 1920x1080, 4 samples):
+search and ranking once per parts change 0.9 to 1.4 s in Node (16,751 pairs on the drape file, 108,955 on the flat file); the search holds about 21 MB of typed arrays per 282k triangles while it runs (144 MB at the 2 M triangle budget);
+one ranked index copy per affected batch, 3.2 MB on the CPU and +2.76 MiB of GPU index buffers (geometry 13.52 to 16.29 MiB);
+draw calls 9 to 40 (walls 12 ranges, glass 15, roofs 6, canopy 2);
+frame time 1.11 to 1.24 ms without ranks and 1.15 to 1.22 ms with ranks (median of 5 rounds of 60 frames ended by a readPixels, two runs, two views): no difference outside the noise.
+Tool cost: no schema or result grew (`npm run tool-cost`); the detail sits in the depthBias topic of scene_capabilities.
diff --git a/changes/751.md b/changes/751.md
index 2f5cb47b..81f59aee 100644
--- a/changes/751.md
+++ b/changes/751.md
@@ -1 +1,2 @@
- Depth precision by default (#751, phase 1 of 2): the colour pass draws with reversed-Z and a 32-bit float depth buffer wherever `EXT_clip_control` exists, at any far / near ratio, from the first frame; the 16-bit depth buffer is gone; without the extension the depth buffer is 24-bit and the near plane fits the visible bounds when the camera left near unset; `reversedDepth: false` opts out; `installDepthPrecision`, `hasFarOverlap` and `requestReversedDepth` are removed (use `installCoplanarDiagnostics` for the warning); `bench/flicker/index.html` is a viewer with a flicker probe
+- Flush faces stop flickering by default (#751, phase 2, step 1 of 2): faces that lie on one plane or a few millimetres apart, inside one mesh or across parts, are ranked per triangle and drawn with a small view-space depth bias, so the face in front wins at every distance and on every depth format; agent scenes do it unless `environment.resolveCoplanar` is `false`, a renderer does it with `resolveCoplanar: resolveFlushParts`; `decal` and `depthLayer` use the same bias; what cannot be ranked (more than 15 faces stacked on one plane, double-sided faces a gap apart) comes back as a `coplanar-overlap` warning with a `reason`; `coplanarLayers`, `resolveCoplanarParts` and `EXACT_FLUSH_DISTANCE` are removed; `bench/flicker` has trap scenes (`?trap=`, `probe.mjs --traps`)
diff --git a/docs/agent-look.md b/docs/agent-look.md
index 0dda961f..2e273eed 100644
--- a/docs/agent-look.md
+++ b/docs/agent-look.md
@@ -121,7 +121,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 |
| `hdri` | absent | A shipped HDRI (`sky-clouds`, `studio-softbox`) or the 64-character ID of a `.hdr` file in `scene_asset_catalog`. It lights, reflects and (with `world: true`) forms the background instead of the setup sky; `environmentIntensity` is its strength and `environmentRotation` turns it about the vertical axis. The setup still gives the key light, so set `keyIntensity: 0` when the HDRI has its own sun. `null` clears. See [Catalog HDRIs and looks](#catalog-hdris-and-looks) |
| `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 |
+| `resolveCoplanar` | `'offset'` | Flush and near-flush faces, inside one mesh or across parts, are ranked per triangle and drawn with a small depth-only bias, so the face in front wins at every distance and nothing flickers. Geometry never moves. `false` opts out, and `scene_inspect` then lists each pair as a `coplanar-overlap` warning. Parts that set `decal` or `depthLayer` keep their own layer. What cannot be ranked comes back as a `coplanar-overlap` warning with a `reason`: `rank-overflow` (more than 15 faces stacked on one plane), `double-sided-gap`, `unchecked` or `collapsed-node` |
| `objectReflections` | on | Absent unless set. Each smooth metal part (`metallic` 0.5 or more, `roughness` 0.6 or less; at most 8 such parts, in a scene with at most 256 other 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` |
| `sky` | absent | Absent unless set. `{ type: 'physical', sunElevation, sunRotation, turbidity, groundAlbedo, aerialPerspective, ozone, sunDisc }`: one time-of-day control. `sunElevation` -90 to 90 degrees (default 45), `sunRotation` degrees clockwise from -Z seen from above (0), `turbidity` 1 to 10 haze (3), `groundAlbedo` 0 to 1 (0.3), `aerialPerspective` 0 to 4 scales the distance haze (1; 0 for none), `ozone` 0 to 10 Chappuis-band absorption (1), `sunDisc` boolean (true). The sky sets `lightDirection`, `keyColor` (the sun reddens and dims with air mass and sets below the horizon), `skyTop`, `skyBottom`, `fogColor` and `fogDensity`, and replaces the setup's environment map with the sky, so those fields no longer take your values while a sky is set. `environment` motion tracks can animate `sunElevation`, `sunRotation`, `turbidity`, `groundAlbedo`, `aerialPerspective` and `ozone` for time-of-day arcs. A `set-environment` patch changes the fields it names and keeps the rest; `sky: null` in a patch keeps the last derived values as plain fields. It is an analytic single-scattering approximation (Rayleigh, aerosol and ozone, Kasten-Young air mass), not Blender's Nishita integration: no clouds. Raster first: the path tracer backends read the same environment map and key light, but are not yet checked against it. |
| `floorSkyTrace` | on | Absent unless set. A closed room a sun lights gets the sky each floor texel sees traced into its floor (`applyFloorSkyVisibility`, strength 0.2), so shadowed floors under a roof or between walls get less world and sky light; it makes the dark end of halls closer to Cycles. Open scenes and rooms lit by lamps alone are left as they are. `false` turns it off; a value that is not a boolean is refused. It loads lazily with a recipe that names its sun (`keyColor` or `keyIntensity`), costs about 1 s of trace when the scene is built and adds triangles to the floor (0.1 to 0.4 ms per frame in the reference halls). |
diff --git a/docs/learn/contact-detection.md b/docs/learn/contact-detection.md
index 21f9132a..b0c02909 100644
--- a/docs/learn/contact-detection.md
+++ b/docs/learn/contact-detection.md
@@ -186,7 +186,7 @@ Both parts draw the plane `y = 0.1`, so the patch flickers against the slab. The
Use a real offset along the normal when the gap should be visible in exports or the path tracer.
-The coplanar code is not in the core bundle. Call `installCoplanarDiagnostics(renderer)` from `67js/addons/coplanar-overlap` to add the warning to `renderer.diagnostics` (checked once per layout). `scene_inspect` shows it once `loadAllAgentSceneModules()` (or a recipe with `resolveCoplanar`) has loaded the code.
+The coplanar code is not in the core bundle. Call `installCoplanarDiagnostics(renderer)` from `67js/addons/coplanar-overlap` to add the warning to `renderer.diagnostics` (checked once per layout). To fix the flicker instead of naming it, pass `resolveCoplanar: resolveFlushParts` (same addon) to `new Renderer67`: it ranks flush and near-flush triangles, inside one part and across parts, and draws each rank with a small depth-only bias, so the face in front wins at every distance; ranked pairs leave the warning. Agent scenes do this by default wherever the code is loaded (the MCP preview always has it; elsewhere call `loadAllAgentSceneModules()`), and `environment.resolveCoplanar: false` opts out.
### Depth precision far from the camera
diff --git a/skills/build-67js-scene/references/errors-and-recovery.md b/skills/build-67js-scene/references/errors-and-recovery.md
index f3fa1c15..85c89848 100644
--- a/skills/build-67js-scene/references/errors-and-recovery.md
+++ b/skills/build-67js-scene/references/errors-and-recovery.md
@@ -23,7 +23,7 @@ Every tool error names what failed and what to do next, so read the message befo
`diagnostics` appears only when something needs a decision. The ones that change the picture:
- `closed-room-without-bake`: add a bake (`light.md`).
-- `coplanar-overlap`: flush faces will flicker; `environment.resolveCoplanar: "offset"` or a node `decal` (`light.md`).
+- `coplanar-overlap`: flush faces are ranked automatically; this is what is left. Follow its `fix` (`light.md`).
- `motionIk` `warnings` (`wrong-bend`, `hyperextended`) and `limited`: fix `bendToward` and `limits`.
- `rig` problems: unweighted vertices, bones with no vertices.
- Mesh lint (`mesh_inspect`): `intersecting-parts`, `thin-wall`, `floating-part`; each comes with a fix.
diff --git a/skills/build-67js-scene/references/light.md b/skills/build-67js-scene/references/light.md
index f4f12723..19642e3d 100644
--- a/skills/build-67js-scene/references/light.md
+++ b/skills/build-67js-scene/references/light.md
@@ -85,19 +85,19 @@ A motion track that moves a light, the sun or a part leaves the baked light behi
## Flush faces flicker (z-fighting)
-`scene_inspect` lists a `coplanar-overlap` diagnostic for two faces on one plane. Depth precision itself needs no
-setting: the renderer switches to reversed depth by itself when the camera's `far` over `near` passes 10000 (a large
-world with a small `near`), and also when a flush pair sits far from the eye. If you still see flicker, raise `near`
-(`set-camera`) first, then pick one fix per pair:
+The fix is automatic. Depth precision needs no setting, and faces that lie flush or a few millimetres apart, inside
+one mesh or across parts, are ranked per triangle at draw time so the face in front always wins; geometry never moves.
+`scene_inspect` returns `flush.ranked`, the number of parts that got ranks. You only act on what is left:
-- `environment.resolveCoplanar: "offset"` moves the smaller part of every flagged pair onto the next depth layer;
- geometry never moves.
-- A single node gets `decal: true` (a sticker on a surface) or `depthLayer` (1 to 4).
+- A `coplanar-overlap` diagnostic with `reason: "rank-overflow"` means more than 15 faces are stacked on one plane:
+ remove the duplicate faces. The other reasons (`double-sided-gap`, `unchecked`, `collapsed-node`) carry their own `fix`.
+- To choose which of two flush nodes wins, set `decal: true` on the one on top (a sticker on a surface) or `depthLayer`
+ (1 to 4) to stack several.
+- `environment.resolveCoplanar: false` opts out; `scene_inspect` then lists each flush pair as `coplanar-overlap`.
```json
{ "expectedRevision": 5, "operations": [
- { "type": "set-environment", "environment": { "resolveCoplanar": "offset" } },
- { "type": "set-camera", "near": 0.5, "far": 2000 }
+ { "type": "set-environment", "environment": { "resolveCoplanar": false } }
] }
```
diff --git a/skills/build-67js-scene/references/scene-contract.md b/skills/build-67js-scene/references/scene-contract.md
index 0ab7dc5b..9f76140d 100644
--- a/skills/build-67js-scene/references/scene-contract.md
+++ b/skills/build-67js-scene/references/scene-contract.md
@@ -131,7 +131,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. 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.
+Closed-solid containment requires two `solid: true` indices. Surface contact does not prove volume penetration. Flush faces are ranked at draw time automatically, so they do not flicker (`environment.resolveCoplanar: false` opts out); `scene_inspect` warns `coplanar-overlap` only for what is left. To choose the winner yourself set `decal: true` on the node on top (a sign, a road marking) or `depthLayer` 0 to 4 for stacked decals. 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-scene-modules.js b/src/agent-scene-modules.js
index 3d64dba7..b2c55d4f 100644
--- a/src/agent-scene-modules.js
+++ b/src/agent-scene-modules.js
@@ -78,9 +78,9 @@ const MODULE_MARKERS = {
crowd: ['"crowd":{'],
lineArt: ['"lines":{', '"toon":'],
viewTransform: ['"viewTransform":"agx"', '"viewTransform":"neutral"', '"look":"'],
- // Flush faces are ranked by default (issue #751), so every recipe loads this unless it opts out. A recipe that opted out still
- // gets the coplanar-overlap warning in scene_inspect once loadAllAgentSceneModules has loaded it.
- coplanar: [/^(?!.*"resolveCoplanar":false)/s],
+ // Flush faces are ranked whenever this is loaded (issue #751): the MCP preview registers it, loadAllAgentSceneModules loads it,
+ // and so does a recipe that names resolveCoplanar. A plain recipe in a host without it still needs no on-demand module.
+ coplanar: ['"resolveCoplanar"'],
// A closed room a sun lights gets the floor sky trace by default. The recipe text can not say whether a room is closed, so a recipe that names its sun loads it and the module skips an open scene.
floorSky: ['"keyColor"', '"keyIntensity"'],
physicalSky: ['"type":"physical"'],
diff --git a/src/agent-scene.js b/src/agent-scene.js
index df753b83..5204afa9 100644
--- a/src/agent-scene.js
+++ b/src/agent-scene.js
@@ -1475,9 +1475,12 @@ export function createAgentScene(input, inputLimits = {}, options = {}) {
return parts;
}
if (flushCache?.parts !== parts) {
- flushCache = { parts, ...coplanar.resolveFlushParts(parts) };
+ const resolved = coplanar.resolveFlushParts(parts);
+ // Ranked parts batch apart, so the list they are staged in is a new one: the renderer then regroups, also when the
+ // ranking is switched on or off for parts that did not change.
+ flushCache = { parts, staged: resolved.ranked ? Object.freeze([...parts]) : parts, ...resolved };
}
- return parts;
+ return flushCache.staged;
}
// scene_inspect names what the ranking could not settle. A scene that opted out gets the pairs of parts that fight instead:
diff --git a/tests/coplanar-overlap.test.js b/tests/coplanar-overlap.test.js
index 2d20dab9..8b3f9c6f 100644
--- a/tests/coplanar-overlap.test.js
+++ b/tests/coplanar-overlap.test.js
@@ -8,7 +8,7 @@ import { frameDiagnostics } from '../src/frame-diagnostics.js';
import { groupParts } from '../src/renderer.js';
import { resolveEffects } from '../src/effects.js';
-await loadAgentSceneModules({});
+await loadAgentSceneModules({ environment: { resolveCoplanar: 'offset' } });
function node(id, translation, scale, extra = {}) {
return { id, geometry: 'box', material: 'paint', translation, scale, ...extra };
diff --git a/tests/mcp-environment-schema.test.js b/tests/mcp-environment-schema.test.js
index 2e322819..1bcb4445 100644
--- a/tests/mcp-environment-schema.test.js
+++ b/tests/mcp-environment-schema.test.js
@@ -142,8 +142,8 @@ test('set-environment accepts ground, viewTransform and resolveCoplanar', () =>
assert.equal(scene.environment.resolveCoplanar, 'offset');
});
-test('a coplanar depth layer regroups parts, and the preview sees every texture map so it rebuilds the renderer', () => {
- const scene = createAgentScene(coplanarRecipe());
+test('switching the flush ranks on regroups parts, and the preview sees every texture map so it rebuilds the renderer', () => {
+ const scene = createAgentScene({ ...coplanarRecipe(), environment: { resolveCoplanar: false } });
const before = scene.topologyRevision;
scene.apply([{ type: 'set-environment', environment: { resolveCoplanar: 'offset' } }], { expectedRevision: scene.revision });
assert.ok(scene.topologyRevision > before, 'the edit changes topology, which replaceParts refuses for textured parts');
diff --git a/tests/renderer.test.js b/tests/renderer.test.js
index 519615d9..a1c27721 100644
--- a/tests/renderer.test.js
+++ b/tests/renderer.test.js
@@ -564,7 +564,7 @@ test('the shadow depth pass draws both faces of a single-sided batch, so the sun
CULL_FACE: 2884,
enable(capability) { culling.push(['enable', capability]); },
disable(capability) { culling.push(['disable', capability]); },
- uniform1f() {}, activeTexture() {}, bindTexture() {},
+ uniform1f() {}, uniform3f() {}, activeTexture() {}, bindTexture() {},
};
const singleSided = { doubleSided: false, alphaMode: 'opaque', alphaCutoff: 0, opacity: 1, mapState: [null], textures: [] };
renderer.applyAlphaState(singleSided, false);