Skip to content

armgit / 67.js

Public Imported from GitHub
0

3D engine that AI agents drive

Move the mirror-only level hook into the water addon and stitch the coarse chunk edges (part of #316)

Nguyen Xuan Anc03fd2060bdd
diff --git a/changes/316-mirror-terrain-lod.md b/changes/316-mirror-terrain-lod.md
index 5808cbe1..1e5efa12 100644
--- a/changes/316-mirror-terrain-lod.md
+++ b/changes/316-mirror-terrain-lod.md
@@ -1,2 +1 @@
-- `createTerrain({ mirrorLevels })` (default 0) builds up to that many extra coarser meshes for each chunk, used only by the water mirror draw. The renderer never picks a `mirrorOnly` level for the main camera, so main-camera pixels do not change; the mirror picks them by the screen error of the mirror's own camera. Terrain meshes of a chunk are not edge-matched across mirror levels, so a seam can show in the blurred reflection. Part of #316.
-- `lods` entries accept `mirrorOnly: true`: the level is skipped in a normal frame and in the shadow draw, and chosen by the water mirror draw like any other level.
+- `createTerrain({ mirrorLevels })` (default 0) builds up to that many extra coarser meshes for each chunk, used only by the water mirror draw (part of #316). Their chunk edges keep every finest-grid vertex, so they meet a neighbour's finest edge or another mirror mesh with no crack (a plain coarse mesh left gaps of up to 3 m on a hilly test terrain). `attachWaterReflection` hides these levels from every other draw and lets the mirror pick them by its own screen error, so a terrain that sets `mirrorLevels` must be used with it. No renderer code changed.
diff --git a/changes/316-mirror-terrain-lod.size.md b/changes/316-mirror-terrain-lod.size.md
index bf0ac02e..2855a7e4 100644
--- a/changes/316-mirror-terrain-lod.size.md
+++ b/changes/316-mirror-terrain-lod.size.md
@@ -1,4 +1,2 @@
-- entry:terrain: 279 bytes for the mirror meshes (coarse levels, their error and the option check); terrain is the only place that builds them (#316).
-- scene:agent-scene+lazy: 317 bytes, the terrain code above plus 37 bytes of core in the renderer, in a scene that bundles terrain.
-- goal:lit-box: asks for 37 bytes over the 50 KB goal; the core part is two lines in the renderer that let a `lods` level be skipped in a normal frame.
-- goal:agent-scene: asks for 36 bytes over the 100 KB goal, the same two lines.
+- entry:terrain: the option builds the coarse mirror meshes with finest-grid chunk edges (about 100 lines of mesh code, which only the terrain module can hold), so the terrain entry grows past its allowance.
+- scene:agent-scene+lazy: the lazy bundle of this scene contains the terrain module, so it carries the same 762 bytes of mesh code.
diff --git a/scripts/capture-mirror-seams.mjs b/scripts/capture-mirror-seams.mjs
new file mode 100644
index 00000000..84f5fa12
--- /dev/null
+++ b/scripts/capture-mirror-seams.mjs
@@ -0,0 +1,91 @@
+// Writes the water mirror picture itself (not the lit frame) for a hilly terrain seen at a grazing angle, so a crack between
+// terrain chunks that the mirror draws at different levels shows as sky through the ground:
+// node scripts/capture-mirror-seams.mjs <folder>
+// truth.png: finest terrain only. stitched.png: terrain with mirrorLevels 3 (finest-grid chunk edges and skirts).
+// unstitched.png: the same levels as plain grid meshes with no stitching and no skirt, as the first version of the option drew them.
+import { mkdir, writeFile } from 'node:fs/promises';
+import { constants, setPriority } from 'node:os';
+import { chromium } from 'playwright';
+import { createServer } from 'vite';
+
+setPriority(0, constants.priority.PRIORITY_BELOW_NORMAL);
+const folder = process.argv[2];
+if (!folder) throw new Error('Give the output folder.');
+const server = await createServer({ server: { host: '127.0.0.1', port: 0 }, logLevel: 'silent' });
+await server.listen();
+const browser = await chromium.launch({ executablePath: process.env.CHROME_PATH ?? 'C:/Program Files/Google/Chrome/Application/chrome.exe', headless: true, args: ['--enable-webgl', '--use-angle=swiftshader', '--enable-unsafe-swiftshader'] });
+try {
+ const serverUrl = `http://127.0.0.1:${server.httpServer.address().port}`;
+ const page = await browser.newPage({ viewport: { width: 960, height: 540 } });
+ await page.route('**/seams.html', route => route.fulfill({ contentType: 'text/html', body: '<canvas style="width:960px;height:540px;display:block"></canvas>' }));
+ await page.goto(`${serverUrl}/seams.html`);
+ const results = await page.evaluate(async () => {
+ const { Renderer67 } = await import('/src/renderer.js');
+ const { box } = await import('/src/geometry.js');
+ const { createTerrain } = await import('/src/terrain.js');
+ const { applyWaterReflection, attachWaterReflection } = await import('/src/water-reflection.js');
+ const canvas = document.querySelector('canvas');
+ const options = { size: 450, resolution: 64, chunks: 8, levels: 1, height: (x, z) => 16 * Math.sin(x * 0.06) * Math.cos(z * 0.05) + 7 * Math.sin(x * 0.19 + z * 0.14) + 2 * Math.sin(x * 0.51) * Math.sin(z * 0.43) - 2 };
+ const sea = { name: 'sea', geometry: box(0, 1), matrix: new Float32Array([4000, 0, 0, 0, 0, 1, 0, 0, 0, 0, 4000, 0, 0, -0.5, 0, 1]), material: { tag: 'surface', color: [0.02, 0.06, 0.1], metallic: 0, roughness: 0.04, emission: 0 } };
+ // A terrain whose chunks are all at one level: the plain grid mesh of that level, with no stitching.
+ const uniformGeometries = [0, 1, 2, 3].map(level => createTerrain({ ...options, levels: level + 1, lodDistance: 1e-6 }).parts.map(part => part.geometry));
+ const truthTerrain = createTerrain(options);
+ const stitchedTerrain = createTerrain({ ...options, mirrorLevels: 3 });
+ const unstitchedTerrain = createTerrain({ ...options, mirrorLevels: 3 });
+ unstitchedTerrain.parts.forEach((part, index) => {
+ part.lods = part.lods.map((level, step) => (step === 0 ? level : { geometry: { ...uniformGeometries[step][index], mirrorOnly: true }, error: level.error, mirrorOnly: true }));
+ });
+
+ function mirrorPicture(terrain) {
+ const marked = applyWaterReflection([...terrain.parts, sea]);
+ const renderer = new Renderer67(canvas, marked.parts, { hdr: false, depth: true, world: true, ground: false, pixelRatio: 1, samples: 1 });
+ const context = renderer.context;
+ const detach = attachWaterReflection(renderer, marked.surface);
+ renderer.render({ eye: [0, 12, 160], target: [0, 4, -100], time: 1 });
+ const unit = 7;
+ context.activeTexture(context.TEXTURE0 + unit);
+ const texture = context.getParameter(context.TEXTURE_BINDING_2D);
+ context.activeTexture(context.TEXTURE0);
+ const width = Math.ceil(canvas.width * 0.75);
+ const height = Math.ceil(canvas.height * 0.75);
+ const framebuffer = context.createFramebuffer();
+ context.bindFramebuffer(context.FRAMEBUFFER, framebuffer);
+ context.framebufferTexture2D(context.FRAMEBUFFER, context.COLOR_ATTACHMENT0, context.TEXTURE_2D, texture, 0);
+ const pixels = new Uint8Array(width * height * 4);
+ context.readPixels(0, 0, width, height, context.RGBA, context.UNSIGNED_BYTE, pixels);
+ context.bindFramebuffer(context.FRAMEBUFFER, null);
+ const picture = document.createElement('canvas');
+ picture.width = width;
+ picture.height = height;
+ const image = new ImageData(new Uint8ClampedArray(pixels), width, height);
+ picture.getContext('2d').putImageData(image, 0, 0);
+ detach();
+ renderer.dispose();
+ return picture.toDataURL('image/png');
+ }
+ // Worst case: chunks in a checkerboard draw their coarsest mesh and the others their finest, so every shared edge joins two levels.
+ function forceCheckerboard(terrain) {
+ terrain.parts.forEach((part, index) => {
+ const coarse = (index % 8 + Math.floor(index / 8)) % 2 === 0;
+ part.lods = part.lods.map((level, step) => ({ ...level, error: step === 0 ? 0 : coarse ? 1e-6 * step : 1e6 * step }));
+ });
+ return terrain;
+ }
+ const checkerboardStitched = forceCheckerboard(createTerrain({ ...options, mirrorLevels: 3 }));
+ const checkerboardUnstitched = createTerrain({ ...options, mirrorLevels: 3 });
+ checkerboardUnstitched.parts.forEach((part, index) => {
+ part.lods = part.lods.map((level, step) => (step === 0 ? level : { geometry: { ...uniformGeometries[step][index], mirrorOnly: true }, error: level.error, mirrorOnly: true }));
+ });
+ forceCheckerboard(checkerboardUnstitched);
+ return {
+ truth: mirrorPicture(truthTerrain), stitched: mirrorPicture(stitchedTerrain), unstitched: mirrorPicture(unstitchedTerrain),
+ checkerboardStitched: mirrorPicture(checkerboardStitched), checkerboardUnstitched: mirrorPicture(checkerboardUnstitched),
+ };
+ });
+ await mkdir(folder, { recursive: true });
+ for (const [name, image] of Object.entries(results)) await writeFile(`${folder}/${name}.png`, Buffer.from(image.split(',')[1], 'base64'));
+ console.log('written', Object.keys(results).join(', '));
+} finally {
+ await browser.close();
+ await server.close();
+}
diff --git a/src/renderer.js b/src/renderer.js
index 91f6e5cb..a8b9f3c8 100644
--- a/src/renderer.js
+++ b/src/renderer.js
@@ -293,7 +293,7 @@ function partGeometries(part) {
/** The state of one list of levels: errors, geometries, the draw of each level once it is first needed, and a selection. */
function createLevelSet(levels, instanceCount) {
- return { levelErrors: levels.map(level => level.mirrorOnly ? Infinity : level.error), mirrorErrors: levels.map(level => level.error), levelGeometries: levels.map(level => level.geometry), levelDraws: [], selection: new InstanceSelection(instanceCount, levels.length) };
+ return { levelErrors: levels.map(level => level.error), levelGeometries: levels.map(level => level.geometry), levelDraws: [], selection: new InstanceSelection(instanceCount, levels.length) };
}
function groundPart() {
@@ -949,7 +949,7 @@ export class Renderer67 {
if (!this.culling || !batch.cullable) return null;
return selectInstances(batch.selection, {
instanceData: batch.instanceData, instanceCount: batch.instanceCount, stride: INSTANCE_STRIDE, bounds: batch.bounds, margin: batch.swayReach * Math.abs(this.windState.strength),
- levelErrors: this.mirrorCulling ? batch.mirrorErrors : batch.levelErrors, planes: this.frustumPlanes, viewProjection: this.viewProjection,
+ levelErrors: batch.levelErrors, planes: this.frustumPlanes, viewProjection: this.viewProjection,
pixelsPerUnit: this.canvas.height / 2 * this.projection[5], pixelError: this.lodPixelError * (this.mirrorCulling?.lodScale ?? 1),
belowHeight: this.mirrorCulling?.belowHeight, minimumPixelRadius: this.mirrorCulling?.minimumPixelRadius,
});
diff --git a/src/terrain.js b/src/terrain.js
index 2bcb4156..c2b3204e 100644
--- a/src/terrain.js
+++ b/src/terrain.js
@@ -364,14 +364,77 @@ export function createTerrain({ size = 512, resolution = 32, chunks = 8, levels
return largest;
}
- // Coarser meshes for the water mirror only (the renderer never picks them for the main camera): each has its own edges, so a
- // seam can open between two chunks that the mirror draws at different levels, which the blurred reflection hides.
+ /**
+ * A coarse mesh whose four chunk edges keep every finest-grid vertex, so they meet a neighbour's finest edge or another mirror
+ * mesh exactly; the cells on the border are fans around their centre. A neighbour whose own edge is
+ * already snapped to a coarser main level can still leave a thin gap.
+ */
+ function buildMirrorGeometry(chunkColumn, chunkRow, level) {
+ const step = 2 ** level;
+ const cells = resolution / step;
+ const side = cells + 1;
+ const firstColumn = chunkColumn * resolution;
+ const firstRow = chunkRow * resolution;
+ const positions = [];
+ const normals = [];
+ const uvs = [];
+ const skyVisibility = [];
+ const indices = [];
+ const normalScratch = new Float32Array(3);
+ function addVertex(gridColumn, gridRow) {
+ const worldX = origin + gridColumn * spacing;
+ const worldZ = origin + gridRow * spacing;
+ gridNormal(gridColumn, gridRow, 1, normalScratch, 0);
+ positions.push(worldX, gridHeight(gridColumn, gridRow), worldZ);
+ normals.push(normalScratch[0], normalScratch[1], normalScratch[2]);
+ uvs.push(worldX, worldZ);
+ skyVisibility.push(skyVisibilityAt(clamp(gridColumn, 0, gridCells), clamp(gridRow, 0, gridCells)));
+ return skyVisibility.length - 1;
+ }
+ for (let row = 0; row < side; row++) {
+ for (let column = 0; column < side; column++) addVertex(firstColumn + column * step, firstRow + row * step);
+ }
+ const borderVertices = new Map();
+ // Local finest-grid position (row, column in 0..resolution) to a vertex: a coarse corner, or a border vertex made once.
+ function vertexAt(fineRow, fineColumn) {
+ if (fineRow % step === 0 && fineColumn % step === 0) return (fineRow / step) * side + fineColumn / step;
+ const key = fineRow * (resolution + 1) + fineColumn;
+ if (!borderVertices.has(key)) borderVertices.set(key, addVertex(firstColumn + fineColumn, firstRow + fineRow));
+ return borderVertices.get(key);
+ }
+ for (let row = 0; row < cells; row++) {
+ for (let column = 0; column < cells; column++) {
+ const rowStart = row * step;
+ const rowEnd = rowStart + step;
+ const columnStart = column * step;
+ const columnEnd = columnStart + step;
+ if (isHole(origin + (firstColumn + columnStart + step / 2) * spacing, origin + (firstRow + rowStart + step / 2) * spacing)) continue;
+ const onBorder = { north: row === 0, south: row === cells - 1, west: column === 0, east: column === cells - 1 };
+ if (!onBorder.north && !onBorder.south && !onBorder.west && !onBorder.east) {
+ const corner00 = row * side + column;
+ indices.push(corner00, corner00 + side + 1, corner00 + 1, corner00, corner00 + side, corner00 + side + 1);
+ continue;
+ }
+ const ring = [];
+ for (let fine = columnStart; fine < (onBorder.north ? columnEnd : columnStart + 1); fine++) ring.push(vertexAt(rowStart, fine));
+ for (let fine = rowStart; fine < (onBorder.east ? rowEnd : rowStart + 1); fine++) ring.push(vertexAt(fine, columnEnd));
+ for (let fine = columnEnd; fine > (onBorder.south ? columnStart : columnEnd - 1); fine--) ring.push(vertexAt(rowEnd, fine));
+ for (let fine = rowEnd; fine > (onBorder.west ? rowStart : rowEnd - 1); fine--) ring.push(vertexAt(fine, columnStart));
+ const center = addVertex(firstColumn + columnStart + step / 2, firstRow + rowStart + step / 2);
+ for (let index = 0; index < ring.length; index++) indices.push(center, ring[(index + 1) % ring.length], ring[index]);
+ }
+ }
+ return { positions: new Float32Array(positions), normals: new Float32Array(normals), uvs: new Float32Array(uvs), skyVisibility: new Float32Array(skyVisibility), indices: new Uint32Array(indices), mirrorOnly: true };
+ }
+
+ // Coarser meshes for the water mirror only. The water reflection addon hides them from every other draw, so a terrain that sets
+ // mirrorLevels must be used with attachWaterReflection.
function buildMirrorLods(state) {
const lods = [{ geometry: state.part.geometry, error: 0 }];
for (let extra = 1; extra <= mirrorLevels; extra++) {
const level = state.targetLevel + extra;
- const edgeLevels = { west: level, east: level, north: level, south: level };
- lods.push({ geometry: buildChunkGeometry(state.chunkColumn, state.chunkRow, level, edgeLevels), error: Math.max(lods[extra - 1].error, coarseError(state, level)), mirrorOnly: true });
+ const error = Math.max(lods[extra - 1].error, coarseError(state, level));
+ lods.push({ geometry: buildMirrorGeometry(state.chunkColumn, state.chunkRow, level), error, mirrorOnly: true });
}
return lods;
}
diff --git a/src/water-reflection.js b/src/water-reflection.js
index 2822a90f..cb8ccbfb 100644
--- a/src/water-reflection.js
+++ b/src/water-reflection.js
@@ -329,6 +329,22 @@ layerTextureSupport.bind = (renderer, mapState, layerState) => {
* values as the one it was drawn for and no part was updated (`renderer.updateParts`); `updateEvery: 2` also keeps it for one lit frame
* after each draw (the reflection then trails the camera by a frame), which suits a film.
*/
+/**
+ * Hides the geometries flagged `mirrorOnly` (the coarse terrain meshes of `createTerrain({ mirrorLevels })`) from every draw but
+ * the mirror: the batch keeps its true level errors in `mirrorErrors` and shows an infinite error for those levels, which no
+ * frame or shadow selection can pass. Done once for each batch.
+ */
+function hideMirrorOnlyLevels(batch, hiddenBatches) {
+ if (hiddenBatches.has(batch)) {
+ return;
+ }
+ hiddenBatches.add(batch);
+ if (batch.levelGeometries?.some(geometry => geometry.mirrorOnly)) {
+ batch.mirrorErrors = batch.levelErrors;
+ batch.levelErrors = batch.levelErrors.map((error, level) => (batch.levelGeometries[level].mirrorOnly ? Infinity : error));
+ }
+}
+
export function attachWaterReflection(renderer, surface, { scale = WATER_REFLECTION_SCALE, updateEvery = 1 } = {}) {
if (!surface) {
return () => {};
@@ -339,7 +355,25 @@ export function attachWaterReflection(renderer, surface, { scale = WATER_REFLECT
const dispose = renderer.dispose;
const updateParts = renderer.updateParts;
const renderFrame = frame => render.call(renderer, frame);
+ const hiddenBatches = new WeakSet();
+ const selectBatchInstances = renderer.selectBatchInstances;
+ // The mirror draw selects among all the levels of a batch; every other draw never sees the mirror-only ones.
+ renderer.selectBatchInstances = batch => {
+ hideMirrorOnlyLevels(batch, hiddenBatches);
+ if (!state.drawing || !batch.mirrorErrors) {
+ return selectBatchInstances.call(renderer, batch);
+ }
+ const hidden = batch.levelErrors;
+ batch.levelErrors = batch.mirrorErrors;
+ try {
+ return selectBatchInstances.call(renderer, batch);
+ } finally {
+ batch.levelErrors = hidden;
+ }
+ };
renderer.render = frame => {
+ // The shadow passes of a lit frame run before its first draw, so every batch is checked first.
+ renderer.batches?.forEach(batch => hideMirrorOnlyLevels(batch, hiddenBatches));
// A render pass (albedo, depth, object ID...) never shows the reflection, so it skips the mirror draw.
if (!frame.reflectionTarget && frame.pass === undefined) {
drawMirrorImage(renderer, state, frame, renderFrame);
@@ -359,6 +393,7 @@ export function attachWaterReflection(renderer, surface, { scale = WATER_REFLECT
};
return () => {
renderer.render = render;
+ renderer.selectBatchInstances = selectBatchInstances;
renderer.dispose = dispose;
if (updateParts) {
renderer.updateParts = updateParts;
diff --git a/tests/render-culling.test.js b/tests/render-culling.test.js
index dc29f970..0da56d25 100644
--- a/tests/render-culling.test.js
+++ b/tests/render-culling.test.js
@@ -232,7 +232,7 @@ test('the renderer lets the water mirror widen the level error, and a normal fra
const { projection, viewProjection, planes } = cameraMatrices();
const renderer = Object.create(Renderer67.prototype);
Object.assign(renderer, { culling: true, canvas: { height: CANVAS_HEIGHT }, projection, viewProjection, frustumPlanes: planes, lodPixelError: 1, windState: { strength: 0 } });
- const batch = { cullable: true, selection: new InstanceSelection(2, 2), instanceData: instanceData([[0, -5, 0], [0, 1, 0]]), instanceCount: 2, bounds: { center: [0, 0, 0], radius: 1 }, swayReach: 0, levelErrors: [0, 0.02], mirrorErrors: [0, 0.02] };
+ const batch = { cullable: true, selection: new InstanceSelection(2, 2), instanceData: instanceData([[0, -5, 0], [0, 1, 0]]), instanceCount: 2, bounds: { center: [0, 0, 0], radius: 1 }, swayReach: 0, levelErrors: [0, 0.02] };
const levelOfSecond = () => {
const selection = renderer.selectBatchInstances(batch);
return selection.indices[1][0] === 1 ? 1 : 0;
@@ -244,22 +244,3 @@ test('the renderer lets the water mirror widen the level error, and a normal fra
assert.equal(mirrored.visibleCount, 1);
assert.equal(levelOfSecond(), 1);
});
-
-test('a mirrorOnly level is never chosen by a normal frame and is chosen by the water mirror', () => {
- const { projection, viewProjection, planes } = cameraMatrices();
- const renderer = Object.create(Renderer67.prototype);
- Object.assign(renderer, { culling: true, canvas: { height: CANVAS_HEIGHT }, projection, viewProjection, frustumPlanes: planes, lodPixelError: 1, windState: { strength: 0 } });
- const geometry = box(0, 1);
- const lods = [{ geometry, error: 0 }, { geometry: box(0, 1), error: 0.0001, mirrorOnly: true }];
- const state = createLevelSetFor(lods);
- const batch = { cullable: true, selection: state.selection, instanceData: instanceData([[0, 1, 0]]), instanceCount: 1, bounds: { center: [0, 0, 0], radius: 1 }, swayReach: 0, levelErrors: state.levelErrors, mirrorErrors: state.mirrorErrors };
- assert.equal(renderer.selectBatchInstances(batch).counts[1], 0, 'the main camera keeps level 0 even when the error is tiny');
- renderer.mirrorCulling = { belowHeight: -10, lodScale: 3, minimumPixelRadius: 0 };
- assert.equal(renderer.selectBatchInstances(batch).counts[1], 1);
-});
-
-function createLevelSetFor(lods) {
- const renderer = Object.create(Renderer67.prototype);
- const part = { name: 'p', geometry: lods[0].geometry, lods, matrix: new Float32Array([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]), material: { tag: 'surface', color: [1, 1, 1], metallic: 0, roughness: 0.5, emission: 0 } };
- return renderer.createCullingState([part]);
-}
diff --git a/tests/terrain.test.js b/tests/terrain.test.js
index 66324d4a..bec7405d 100644
--- a/tests/terrain.test.js
+++ b/tests/terrain.test.js
@@ -47,16 +47,30 @@ test('the same seed gives the same terrain and another seed differs', () => {
test('mirrorLevels gives every chunk coarser mirrorOnly meshes with growing errors, and none without the option', () => {
const plain = createTerrain(SMALL);
assert.ok(plain.parts.every(part => part.lods === undefined));
- const terrain = createTerrain({ ...SMALL, levels: 1, resolution: 16, mirrorLevels: 3 });
+ const terrain = createTerrain({ ...SMALL, levels: 1, resolution: 64, mirrorLevels: 3 });
for (const part of terrain.parts) {
assert.equal(part.lods.length, 4);
assert.equal(part.lods[0].geometry, part.geometry);
assert.equal(part.lods[0].mirrorOnly, undefined);
- assert.ok(part.lods.slice(1).every(level => level.mirrorOnly === true));
+ assert.ok(part.lods.slice(1).every(level => level.mirrorOnly === true && level.geometry.mirrorOnly === true));
for (let index = 1; index < part.lods.length; index++) {
assert.ok(part.lods[index].error >= part.lods[index - 1].error);
- assert.ok(part.lods[index].geometry.indices.length < part.lods[index - 1].geometry.indices.length);
}
+ assert.ok(part.lods[3].geometry.indices.length < part.lods[0].geometry.indices.length / 2);
+ }
+});
+
+test('a mirror mesh keeps every finest-grid vertex on the chunk edge, so it meets its neighbours without a crack', () => {
+ const terrain = createTerrain({ ...SMALL, levels: 1, resolution: 64, mirrorLevels: 3 });
+ const part = terrain.parts[5];
+ const finest = vertexList(part.geometry);
+ const lowestZ = Math.min(...finest.map(vertex => vertex[2]));
+ const edgeAt = vertices => new Set(vertices.filter(vertex => Math.abs(vertex[2] - lowestZ) < 1e-4).map(vertex => vertex[0].toFixed(3)));
+ const finestEdge = edgeAt(finest);
+ assert.equal(finestEdge.size, 65);
+ for (const level of part.lods.slice(1)) {
+ const mirrorEdge = edgeAt(vertexList(level.geometry));
+ assert.deepEqual([...mirrorEdge].sort(), [...finestEdge].sort());
}
assert.throws(() => createTerrain({ ...SMALL, levels: 3, mirrorLevels: 3 }), RangeError);
});
diff --git a/tests/water-reflection.test.js b/tests/water-reflection.test.js
index a7609d5c..250922d2 100644
--- a/tests/water-reflection.test.js
+++ b/tests/water-reflection.test.js
@@ -105,6 +105,30 @@ test('the mirror image is drawn at three quarters of the canvas in each directio
detach();
});
+test('a mirrorOnly level is hidden from every draw but the mirror, and detaching puts the renderer back', () => {
+ const context = new Proxy({}, {
+ get: (_, name) => (name === 'checkFramebufferStatus' ? () => 1 : name === 'FRAMEBUFFER_COMPLETE' ? 1 : typeof name === 'string' && name === name.toUpperCase() ? 0 : () => ({})),
+ });
+ const coarse = { positions: new Float32Array(9), indices: new Uint32Array(3), mirrorOnly: true };
+ const batch = { levelErrors: [0, 0.01], levelGeometries: [{ positions: new Float32Array(9), indices: new Uint32Array(3) }, coarse] };
+ const seen = [];
+ const renderer = {
+ context, canvas: { width: 960, height: 540 }, hdr: false, viewProjection: new Float32Array(16), batches: [batch], dispose() {},
+ selectBatchInstances: chosen => seen.push([...chosen.levelErrors]),
+ render(frame) {
+ renderer.selectBatchInstances(batch);
+ seen.push(frame.reflectionTarget ? 'mirror' : 'lit');
+ },
+ };
+ const original = renderer.selectBatchInstances;
+ const detach = attachWaterReflection(renderer, findWaterSurface(lakeScene()));
+ renderer.render({ eye: [0, 20, 100], target: [0, 0, 0] });
+ assert.deepEqual(seen, [[0, 0.01], 'mirror', [0, Infinity], 'lit'], 'the mirror draw sees the true errors, the lit frame an infinite one');
+ assert.deepEqual(batch.levelErrors, [0, Infinity]);
+ detach();
+ assert.equal(renderer.selectBatchInstances, original);
+});
+
test('a render pass frame skips the mirror image and the next lit frame draws it again', () => {
const context = new Proxy({}, {
get: (_, name) => {