@edv4h/usketch-plugin-elevation 0.5.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -6,10 +6,13 @@ import { jsx as _jsx } from "react/jsx-runtime";
6
6
  // meanwhile the flat ground layer is hidden. Without WebGL2 nothing is drawn here and
7
7
  // the flat layer stays (its shading tilted with the board, as before).
8
8
  //
9
- // The canvas is one layer: DOM layers above it (shapes, characters) are always drawn
10
- // in front of the hills, even behind one.
11
- import { view3dOverscanPx, viewMatrix, } from "@edv4h/usketch-shared";
12
- import { useEffect, useRef, useState } from "react";
9
+ // The canvas is one layer: DOM layers above it (shapes, characters) are drawn in front
10
+ // of the hills, even behind one. So that a hill hides the shapes behind it, a second,
11
+ // "cover" canvas over the shapes gets the hills again — only where the ground is nearer
12
+ // the eye than every shape drawn there (the shapes' faces, from the canvas's 3D pick,
13
+ // are drawn into the depth and stencil buffers first). Everywhere else it is clear.
14
+ import { cameraEye, view3dOverscanPx, viewMatrix, } from "@edv4h/usketch-shared";
15
+ import { useCallback, useEffect, useRef, useState } from "react";
13
16
  import { DECAL_MARGIN, decalLookupArea, decalTexMapping, decalTileArea, nextDecalTilePx, paintDecalTile, projectedTilePx, tileWorldRect, } from "./elevation-decals.js";
14
17
  import { chunkKey } from "./elevation-field.js";
15
18
  import { tileRevision } from "./elevation-layer.js";
@@ -17,6 +20,111 @@ import { buildTileMesh, RAMP_WIDTH, rampPixels, rampRange, tileIndices, VERTEX_F
17
20
  import { boardElevation, elevationSampler } from "./elevation-model.js";
18
21
  import { planTiles, visibleWorldRect } from "./elevation-tiles.js";
19
22
  export const MESH_LAYER_ID = "usketch-elevation:mesh";
23
+ /** The layer with the cover canvas: the hills drawn again over the shapes they hide. */
24
+ export const COVER_LAYER_ID = "usketch-elevation:cover";
25
+ /**
26
+ * How much nearer the eye (px of depth) the ground must be than a shape to cover it: a
27
+ * shape lying on the ground isn't swallowed by the ground just around it.
28
+ */
29
+ export const COVER_DEPTH_BIAS = 6;
30
+ /** Most ground samples along a side of a lying face, to find how high the ground rises under it. */
31
+ const MAX_LIFT_SAMPLES = 17;
32
+ /**
33
+ * How far the ground rises above a face lying flat (both its sides level), world units:
34
+ * the highest of a grid of samples over it, above the face. `0` for a face that isn't
35
+ * level. A lying shape is judged as if that much higher, so the slope it lies on doesn't
36
+ * swallow it — only a hill between it and the eye covers it. Pure.
37
+ */
38
+ export function coverLift(q, groundAt,
39
+ /** World units between samples (the terrain's spacing); more past {@link MAX_LIFT_SAMPLES}. */
40
+ step = 32) {
41
+ if (Math.abs(q.u[2]) > 1e-6 || Math.abs(q.v[2]) > 1e-6)
42
+ return 0;
43
+ const count = (len) => Math.min(MAX_LIFT_SAMPLES, Math.max(2, Math.ceil(len / Math.max(1, step)) + 1));
44
+ const nu = count(Math.hypot(q.u[0], q.u[1]));
45
+ const nv = count(Math.hypot(q.v[0], q.v[1]));
46
+ let top = Number.NEGATIVE_INFINITY;
47
+ for (let i = 0; i < nu; i++) {
48
+ for (let j = 0; j < nv; j++) {
49
+ const a = i / (nu - 1);
50
+ const b = j / (nv - 1);
51
+ const h = groundAt(q.at[0] + q.u[0] * a + q.v[0] * b, q.at[1] + q.u[1] * a + q.v[1] * b);
52
+ if (Number.isFinite(h) && h > top)
53
+ top = h;
54
+ }
55
+ }
56
+ return Number.isFinite(top) ? Math.max(0, top - q.at[2]) : 0;
57
+ }
58
+ /** Floats per cover vertex: where it is drawn (x, y, height), then where its depth is taken. */
59
+ export const COVER_VERTEX_FLOATS = 6;
60
+ /** Largest cell a face is cut into (world units), and most cells along a side. */
61
+ const COVER_CELL = 32;
62
+ const MAX_COVER_CELLS = 16;
63
+ /**
64
+ * The triangles of the shapes' faces, 6 vertices per cell of a quad, each {@link COVER_VERTEX_FLOATS}
65
+ * floats: where it is drawn — x, y relative to `origin`, height — then the point its
66
+ * depth is taken at: the same, or for a lying face with {@link coverLift} above 0 the
67
+ * point toward `eye` on its line of sight that is that much higher (drawn on the same
68
+ * pixel, so the ground just around the face isn't nearer than it). Pure.
69
+ */
70
+ export function coverVertices(faces, origin, ground,
71
+ /**
72
+ * Largest cell, world units: a face is cut into cells so its depth (linear in depth,
73
+ * as the mesh's) is right across it, not only at its corners.
74
+ */
75
+ cell = COVER_CELL) {
76
+ const cells = (q) => {
77
+ const n = (v) => Math.min(MAX_COVER_CELLS, Math.max(1, Math.ceil(Math.hypot(v[0], v[1], v[2]) / cell)));
78
+ return { nu: n(q.u), nv: n(q.v) };
79
+ };
80
+ let n = 0;
81
+ for (const f of faces) {
82
+ for (const q of f.quads) {
83
+ const { nu, nv } = cells(q);
84
+ n += nu * nv;
85
+ }
86
+ }
87
+ const out = new Float32Array(n * 6 * COVER_VERTEX_FLOATS);
88
+ let i = 0;
89
+ for (const f of faces) {
90
+ for (const q of f.quads) {
91
+ const lift = ground ? ground.liftOf(q) : 0;
92
+ const corner = (a, b) => {
93
+ const x = q.at[0] + q.u[0] * a + q.v[0] * b;
94
+ const y = q.at[1] + q.u[1] * a + q.v[1] * b;
95
+ const z = q.at[2] + q.u[2] * a + q.v[2] * b;
96
+ out[i++] = x - origin.x;
97
+ out[i++] = y - origin.y;
98
+ out[i++] = z;
99
+ let t = 0;
100
+ if (ground && lift > 0) {
101
+ const rise = ground.eye.height - z;
102
+ t = rise > 0 ? Math.min(0.99, lift / rise) : 0;
103
+ }
104
+ const e = ground?.eye;
105
+ out[i++] = (e ? x + (e.x - x) * t : x) - origin.x;
106
+ out[i++] = (e ? y + (e.y - y) * t : y) - origin.y;
107
+ out[i++] = e ? z + (e.height - z) * t : z;
108
+ };
109
+ const { nu, nv } = cells(q);
110
+ for (let a = 0; a < nu; a++) {
111
+ for (let b = 0; b < nv; b++) {
112
+ const a0 = a / nu;
113
+ const a1 = (a + 1) / nu;
114
+ const b0 = b / nv;
115
+ const b1 = (b + 1) / nv;
116
+ corner(a0, b0);
117
+ corner(a1, b0);
118
+ corner(a1, b1);
119
+ corner(a0, b0);
120
+ corner(a1, b1);
121
+ corner(a0, b1);
122
+ }
123
+ }
124
+ }
125
+ }
126
+ return out;
127
+ }
20
128
  /** Depth range in px: depth values are scaled by 1 / this into the depth buffer. */
21
129
  const DEPTH_RANGE = 200_000;
22
130
  const VERTEX = `#version 300 es
@@ -76,6 +184,22 @@ void main() {
76
184
  }
77
185
  outColor = vec4(rgb, a);
78
186
  }`;
187
+ const COVER_VERTEX = `#version 300 es
188
+ in vec3 aPos; // x, y relative to the view's origin, height
189
+ in vec3 aDepthPos; // the point its depth is taken at (see coverVertices)
190
+ uniform mat4 uView;
191
+ uniform float uBias;
192
+ void main() {
193
+ vec4 p = uView * vec4(aPos, 1.0);
194
+ float depth = -(uView * vec4(aDepthPos, 1.0)).z - uBias;
195
+ gl_Position = vec4(p.x, p.y, clamp(depth / ${DEPTH_RANGE.toFixed(1)}, -1.0, 1.0) * p.w, p.w);
196
+ }`;
197
+ const COVER_FRAGMENT = `#version 300 es
198
+ precision mediump float;
199
+ out vec4 outColor;
200
+ void main() {
201
+ outColor = vec4(0.0);
202
+ }`;
79
203
  /**
80
204
  * Decal bitmap texels (re)painted per frame at most — about one 1024² tile, or many
81
205
  * small far ones; the rest wait for the next frames. The first paint of a frame always
@@ -102,6 +226,32 @@ function meanHeight(vertices, water) {
102
226
  }
103
227
  return n > 0 ? sum / n : 0;
104
228
  }
229
+ /** A linked program of two shader sources, its attributes at 0, 1, … Throws on failure. */
230
+ function linkProgram(gl, vertex, fragment, attributes) {
231
+ const shader = (type, src) => {
232
+ const s = gl.createShader(type);
233
+ if (!s)
234
+ throw new Error("shader");
235
+ gl.shaderSource(s, src);
236
+ gl.compileShader(s);
237
+ if (!gl.getShaderParameter(s, gl.COMPILE_STATUS))
238
+ throw new Error(gl.getShaderInfoLog(s) ?? "");
239
+ return s;
240
+ };
241
+ const program = gl.createProgram();
242
+ if (!program)
243
+ throw new Error("program");
244
+ gl.attachShader(program, shader(gl.VERTEX_SHADER, vertex));
245
+ gl.attachShader(program, shader(gl.FRAGMENT_SHADER, fragment));
246
+ attributes.forEach((name, i) => {
247
+ gl.bindAttribLocation(program, i, name);
248
+ });
249
+ gl.linkProgram(program);
250
+ if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {
251
+ throw new Error(gl.getProgramInfoLog(program) ?? "");
252
+ }
253
+ return program;
254
+ }
105
255
  /** Owns the GL objects of one canvas. */
106
256
  class MeshRenderer {
107
257
  gl;
@@ -116,8 +266,19 @@ class MeshRenderer {
116
266
  scratch = null;
117
267
  frame = 0;
118
268
  u = {};
269
+ /** The faces' program and buffer (built on first cover). */
270
+ cover = null;
271
+ /** The cover canvas holds a picture (cleared once nothing is covered). */
272
+ covered = false;
273
+ /** Lying faces' lifts, for the terrain they were found on (shapes seldom move). */
274
+ lifts = null;
119
275
  static create(canvas) {
120
- const gl = canvas.getContext("webgl2", { antialias: true, premultipliedAlpha: true });
276
+ const gl = canvas.getContext("webgl2", {
277
+ antialias: true,
278
+ premultipliedAlpha: true,
279
+ // The shapes' faces mark where the cover may draw.
280
+ stencil: true,
281
+ });
121
282
  if (!gl)
122
283
  return null;
123
284
  return MeshRenderer.fromGl(gl);
@@ -133,27 +294,7 @@ class MeshRenderer {
133
294
  }
134
295
  constructor(gl) {
135
296
  this.gl = gl;
136
- const shader = (type, src) => {
137
- const s = gl.createShader(type);
138
- if (!s)
139
- throw new Error("shader");
140
- gl.shaderSource(s, src);
141
- gl.compileShader(s);
142
- if (!gl.getShaderParameter(s, gl.COMPILE_STATUS))
143
- throw new Error(gl.getShaderInfoLog(s) ?? "");
144
- return s;
145
- };
146
- const program = gl.createProgram();
147
- if (!program)
148
- throw new Error("program");
149
- gl.attachShader(program, shader(gl.VERTEX_SHADER, VERTEX));
150
- gl.attachShader(program, shader(gl.FRAGMENT_SHADER, FRAGMENT));
151
- gl.bindAttribLocation(program, 0, "aVertex");
152
- gl.linkProgram(program);
153
- if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {
154
- throw new Error(gl.getProgramInfoLog(program) ?? "");
155
- }
156
- this.program = program;
297
+ this.program = linkProgram(gl, VERTEX, FRAGMENT, ["aVertex"]);
157
298
  for (const name of [
158
299
  "uView",
159
300
  "uWater",
@@ -167,7 +308,7 @@ class MeshRenderer {
167
308
  "uDecalOn",
168
309
  "uDecalMap",
169
310
  ]) {
170
- this.u[name] = gl.getUniformLocation(program, name);
311
+ this.u[name] = gl.getUniformLocation(this.program, name);
171
312
  }
172
313
  const vao = gl.createVertexArray();
173
314
  const ib = gl.createBuffer();
@@ -203,8 +344,11 @@ class MeshRenderer {
203
344
  }
204
345
  const rect = visibleWorldRect(opts.store, opts.overscanPx);
205
346
  const plan = rect ? planTiles(field, rect, vp.zoom) : null;
206
- if (!plan)
347
+ if (!plan) {
348
+ if (opts.cover)
349
+ this.clearCover(opts.cover.canvas);
207
350
  return false;
351
+ }
208
352
  this.frame++;
209
353
  // biome-ignore lint/correctness/useHookAtTopLevel: WebGL's useProgram, not a React hook
210
354
  gl.useProgram(this.program);
@@ -245,60 +389,93 @@ class MeshRenderer {
245
389
  const sampler = elevationSampler(model);
246
390
  const fk = `${field.id}|${field.spacing}|${n}|${field.seed}|${field.waterLevel}|${field.gen.relief}|${field.gen.scale}|${field.gen.roughness}|${field.gen.ridges}|${field.gen.octaves}`;
247
391
  const count = n * n * 6;
248
- for (let ty = plan.ty0; ty <= plan.ty1; ty++) {
249
- for (let tx = plan.tx0; tx <= plan.tx1; tx++) {
250
- const key = `${plan.level}:${chunkKey(tx, ty)}`;
251
- const revision = `${fk}#${tileRevision(model, plan.level, tx, ty)}`;
252
- let tile = this.tiles.get(key);
253
- if (!tile || tile.revision !== revision) {
254
- const buffer = tile?.buffer ?? gl.createBuffer();
255
- if (!buffer)
256
- continue;
257
- gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
258
- const vertices = buildTileMesh(sampler, plan.level, tx, ty);
259
- gl.bufferData(gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW);
260
- tile = {
261
- revision,
262
- buffer,
263
- used: this.frame,
264
- meanHeight: meanHeight(vertices, field.waterLevel),
265
- };
266
- this.tiles.set(key, tile);
267
- }
268
- tile.used = this.frame;
269
- gl.bindBuffer(gl.ARRAY_BUFFER, tile.buffer);
270
- gl.enableVertexAttribArray(0);
271
- gl.vertexAttribPointer(0, VERTEX_FLOATS, gl.FLOAT, false, VERTEX_FLOATS * 4, 0);
272
- gl.uniformMatrix4fv(u.uView, false, viewMatrix(view, { x: tx * plan.worldSize, y: ty * plan.worldSize }));
273
- const decal = decals
274
- ? this.decalFor(decals, key, tx, ty, plan.worldSize, {
275
- vp,
276
- camera,
277
- width,
278
- height,
279
- dpr: opts.dpr,
280
- z: tile.meanHeight,
281
- canPaint,
282
- painted: (cost) => {
283
- texels += cost;
284
- },
285
- })
286
- : null;
287
- if (decal?.pending)
288
- pending = true;
289
- if (decal?.texture) {
290
- const map = decalTexMapping(plan.worldSize, decal.texture.px);
291
- gl.activeTexture(gl.TEXTURE1);
292
- gl.bindTexture(gl.TEXTURE_2D, decal.texture.texture);
293
- gl.uniform1f(u.uDecalOn, 1);
294
- gl.uniform2f(u.uDecalMap, map.scale, map.offset);
295
- }
296
- else {
297
- gl.uniform1f(u.uDecalOn, 0);
392
+ const drawTiles = () => {
393
+ for (let ty = plan.ty0; ty <= plan.ty1; ty++) {
394
+ for (let tx = plan.tx0; tx <= plan.tx1; tx++) {
395
+ const key = `${plan.level}:${chunkKey(tx, ty)}`;
396
+ const revision = `${fk}#${tileRevision(model, plan.level, tx, ty)}`;
397
+ let tile = this.tiles.get(key);
398
+ if (!tile || tile.revision !== revision) {
399
+ const buffer = tile?.buffer ?? gl.createBuffer();
400
+ if (!buffer)
401
+ continue;
402
+ gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
403
+ const vertices = buildTileMesh(sampler, plan.level, tx, ty);
404
+ gl.bufferData(gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW);
405
+ tile = {
406
+ revision,
407
+ buffer,
408
+ used: this.frame,
409
+ meanHeight: meanHeight(vertices, field.waterLevel),
410
+ };
411
+ this.tiles.set(key, tile);
412
+ }
413
+ tile.used = this.frame;
414
+ gl.bindBuffer(gl.ARRAY_BUFFER, tile.buffer);
415
+ gl.enableVertexAttribArray(0);
416
+ gl.vertexAttribPointer(0, VERTEX_FLOATS, gl.FLOAT, false, VERTEX_FLOATS * 4, 0);
417
+ gl.uniformMatrix4fv(u.uView, false, viewMatrix(view, { x: tx * plan.worldSize, y: ty * plan.worldSize }));
418
+ const decal = decals
419
+ ? this.decalFor(decals, key, tx, ty, plan.worldSize, {
420
+ vp,
421
+ camera,
422
+ width,
423
+ height,
424
+ dpr: opts.dpr,
425
+ z: tile.meanHeight,
426
+ canPaint,
427
+ painted: (cost) => {
428
+ texels += cost;
429
+ },
430
+ })
431
+ : null;
432
+ if (decal?.pending)
433
+ pending = true;
434
+ if (decal?.texture) {
435
+ const map = decalTexMapping(plan.worldSize, decal.texture.px);
436
+ gl.activeTexture(gl.TEXTURE1);
437
+ gl.bindTexture(gl.TEXTURE_2D, decal.texture.texture);
438
+ gl.uniform1f(u.uDecalOn, 1);
439
+ gl.uniform2f(u.uDecalMap, map.scale, map.offset);
440
+ }
441
+ else {
442
+ gl.uniform1f(u.uDecalOn, 0);
443
+ }
444
+ gl.drawElements(gl.TRIANGLES, count, gl.UNSIGNED_SHORT, 0);
298
445
  }
299
- gl.drawElements(gl.TRIANGLES, count, gl.UNSIGNED_SHORT, 0);
446
+ }
447
+ };
448
+ if (opts.cover && !opts.external) {
449
+ const { canvas: target, faces } = opts.cover;
450
+ // The ground as drawn: water at its level.
451
+ const water = field.waterLevel;
452
+ const groundAt = (x, y) => {
453
+ const h = sampler.heightAt(x, y);
454
+ return water !== null && h < water ? water : h;
455
+ };
456
+ if (faces.length > 0 &&
457
+ this.drawCoverMask(faces, view, this.liftFor(sampler, groundAt, field.spacing))) {
458
+ // The hills, only where the faces were and only nearer than them.
459
+ // biome-ignore lint/correctness/useHookAtTopLevel: WebGL's useProgram, not a React hook
460
+ gl.useProgram(this.program);
461
+ gl.bindVertexArray(this.vao);
462
+ gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this.indexBuffer);
463
+ gl.enable(gl.STENCIL_TEST);
464
+ gl.stencilFunc(gl.EQUAL, 1, 0xff);
465
+ gl.stencilOp(gl.KEEP, gl.KEEP, gl.KEEP);
466
+ gl.depthFunc(gl.LESS);
467
+ gl.enable(gl.BLEND);
468
+ drawTiles();
469
+ gl.disable(gl.STENCIL_TEST);
470
+ gl.depthFunc(gl.LEQUAL);
471
+ this.copyCover(target);
472
+ gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT | gl.STENCIL_BUFFER_BIT);
473
+ }
474
+ else {
475
+ this.clearCover(target);
300
476
  }
301
477
  }
478
+ drawTiles();
302
479
  // Drop the meshes of tiles no longer drawn (a few frames' grace for panning back).
303
480
  for (const [key, tile] of this.tiles) {
304
481
  if (this.frame - tile.used > 120) {
@@ -310,6 +487,102 @@ class MeshRenderer {
310
487
  gl.activeTexture(gl.TEXTURE0);
311
488
  return pending;
312
489
  }
490
+ /**
491
+ * The shapes' faces into the depth and stencil buffers (no colour): clears the frame,
492
+ * then marks each pixel a face covers with its nearest depth (nudged toward the eye by
493
+ * {@link COVER_DEPTH_BIAS}). `false` when the faces program can't be built.
494
+ */
495
+ drawCoverMask(faces, view, liftOf) {
496
+ const { gl } = this;
497
+ if (!this.cover) {
498
+ try {
499
+ const program = linkProgram(gl, COVER_VERTEX, COVER_FRAGMENT, ["aPos", "aDepthPos"]);
500
+ const vao = gl.createVertexArray();
501
+ const buffer = gl.createBuffer();
502
+ if (!vao || !buffer)
503
+ return false;
504
+ this.cover = {
505
+ program,
506
+ vao,
507
+ buffer,
508
+ uView: gl.getUniformLocation(program, "uView"),
509
+ uBias: gl.getUniformLocation(program, "uBias"),
510
+ };
511
+ }
512
+ catch {
513
+ return false;
514
+ }
515
+ }
516
+ const c = this.cover;
517
+ const first = faces.find((f) => f.quads.length > 0)?.quads[0];
518
+ if (!first)
519
+ return false;
520
+ const origin = { x: first.at[0], y: first.at[1] };
521
+ const vertices = coverVertices(faces, origin, { liftOf, eye: cameraEye(view) });
522
+ gl.clearStencil(0);
523
+ gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT | gl.STENCIL_BUFFER_BIT);
524
+ // biome-ignore lint/correctness/useHookAtTopLevel: WebGL's useProgram, not a React hook
525
+ gl.useProgram(c.program);
526
+ gl.bindVertexArray(c.vao);
527
+ gl.bindBuffer(gl.ARRAY_BUFFER, c.buffer);
528
+ gl.bufferData(gl.ARRAY_BUFFER, vertices, gl.DYNAMIC_DRAW);
529
+ const stride = COVER_VERTEX_FLOATS * 4;
530
+ gl.enableVertexAttribArray(0);
531
+ gl.vertexAttribPointer(0, 3, gl.FLOAT, false, stride, 0);
532
+ gl.enableVertexAttribArray(1);
533
+ gl.vertexAttribPointer(1, 3, gl.FLOAT, false, stride, 12);
534
+ gl.uniformMatrix4fv(c.uView, false, viewMatrix(view, origin));
535
+ gl.uniform1f(c.uBias, COVER_DEPTH_BIAS);
536
+ gl.disable(gl.BLEND);
537
+ gl.colorMask(false, false, false, false);
538
+ gl.enable(gl.STENCIL_TEST);
539
+ gl.stencilFunc(gl.ALWAYS, 1, 0xff);
540
+ gl.stencilOp(gl.KEEP, gl.KEEP, gl.REPLACE);
541
+ gl.depthFunc(gl.LESS);
542
+ gl.drawArrays(gl.TRIANGLES, 0, vertices.length / COVER_VERTEX_FLOATS);
543
+ gl.colorMask(true, true, true, true);
544
+ gl.disable(gl.STENCIL_TEST);
545
+ gl.depthFunc(gl.LEQUAL);
546
+ gl.enable(gl.BLEND);
547
+ return true;
548
+ }
549
+ /** A face's {@link coverLift}, remembered while the terrain stays the same. */
550
+ liftFor(sampler, groundAt, step) {
551
+ if (!this.lifts || this.lifts.sampler !== sampler || this.lifts.values.size > 4096) {
552
+ this.lifts = { sampler, values: new Map() };
553
+ }
554
+ const values = this.lifts.values;
555
+ return (q) => {
556
+ const key = `${q.at.join(",")}|${q.u.join(",")}|${q.v.join(",")}`;
557
+ let lift = values.get(key);
558
+ if (lift === undefined) {
559
+ lift = coverLift(q, groundAt, step);
560
+ values.set(key, lift);
561
+ }
562
+ return lift;
563
+ };
564
+ }
565
+ /** The frame drawn so far onto the cover canvas (sized like ours). */
566
+ copyCover(target) {
567
+ const source = this.gl.canvas;
568
+ if (target.width !== source.width)
569
+ target.width = source.width;
570
+ if (target.height !== source.height)
571
+ target.height = source.height;
572
+ const ctx = target.getContext("2d");
573
+ if (!ctx)
574
+ return;
575
+ ctx.clearRect(0, 0, target.width, target.height);
576
+ ctx.drawImage(source, 0, 0);
577
+ this.covered = true;
578
+ }
579
+ /** Nothing covered: a clear cover canvas. */
580
+ clearCover(target) {
581
+ if (!this.covered)
582
+ return;
583
+ this.covered = false;
584
+ target.getContext("2d")?.clearRect(0, 0, target.width, target.height);
585
+ }
313
586
  /**
314
587
  * The decal texture for a tile, (re)painted when the decals there changed or the
315
588
  * tile now shows at another resolution — within the frame's paint budget (`pending`
@@ -418,12 +691,18 @@ class MeshRenderer {
418
691
  gl.deleteTexture(tex.texture);
419
692
  this.decalTextures.clear();
420
693
  gl.deleteBuffer(this.indexBuffer);
694
+ if (this.cover) {
695
+ gl.deleteBuffer(this.cover.buffer);
696
+ gl.deleteVertexArray(this.cover.vao);
697
+ gl.deleteProgram(this.cover.program);
698
+ this.cover = null;
699
+ }
421
700
  gl.deleteTexture(this.ramp);
422
701
  gl.deleteVertexArray(this.vao);
423
702
  gl.deleteProgram(this.program);
424
703
  }
425
704
  }
426
- export function ElevationMeshLayer({ store, display, overscan, view3d, state, decals, gpu, }) {
705
+ export function ElevationMeshLayer({ store, display, overscan, view3d, state, decals, gpu, cover, }) {
427
706
  const isOn = () => (view3d()?.amount() ?? 0) > 0 && boardElevation(store) !== null && !gpu?.isDrawing();
428
707
  const [on, setOn] = useState(isOn);
429
708
  // biome-ignore lint/correctness/useExhaustiveDependencies: isOn reads only these
@@ -443,9 +722,9 @@ export function ElevationMeshLayer({ store, display, overscan, view3d, state, de
443
722
  }, [on, state]);
444
723
  if (!on)
445
724
  return null;
446
- return (_jsx(MeshCanvas, { store: store, display: display, overscan: overscan, view3d: view3d, state: state, decals: decals }));
725
+ return (_jsx(MeshCanvas, { store: store, display: display, overscan: overscan, view3d: view3d, state: state, decals: decals, cover: cover }));
447
726
  }
448
- function MeshCanvas({ store, display, overscan, view3d, state, decals, }) {
727
+ function MeshCanvas({ store, display, overscan, view3d, state, decals, cover, }) {
449
728
  const ref = useRef(null);
450
729
  useEffect(() => {
451
730
  const canvas = ref.current;
@@ -457,12 +736,20 @@ function MeshCanvas({ store, display, overscan, view3d, state, decals, }) {
457
736
  return;
458
737
  }
459
738
  let raf = 0;
739
+ let queued = false;
740
+ let disposed = false;
460
741
  const draw = () => {
742
+ if (disposed)
743
+ return;
744
+ queued = false;
745
+ if (raf)
746
+ cancelAnimationFrame(raf);
461
747
  raf = 0;
462
748
  const model = boardElevation(store);
463
749
  const v = view3d();
464
750
  if (!model || !v)
465
751
  return;
752
+ const coverCanvas = cover?.target.get().canvas ?? null;
466
753
  const pending = renderer.draw({
467
754
  model,
468
755
  viewport: store.getViewport(),
@@ -474,14 +761,21 @@ function MeshCanvas({ store, display, overscan, view3d, state, decals, }) {
474
761
  display: display.get(),
475
762
  store,
476
763
  decals,
764
+ cover: cover && coverCanvas ? { canvas: coverCanvas, faces: cover.faces() } : undefined,
477
765
  });
478
766
  // Decal tiles left for the next frames (the paint budget ran out).
479
- if (pending)
480
- schedule();
767
+ if (pending && !raf)
768
+ raf = requestAnimationFrame(draw);
481
769
  };
770
+ // Redraw at the end of the task that changed something, so in the same frame: a
771
+ // follow camera moves the viewport in its own animation frame, and a redraw one frame
772
+ // later would put the hills (and the cover over the shapes) a frame behind the DOM
773
+ // shapes on some frames and not others — they would judder against each other.
482
774
  const schedule = () => {
483
- if (!raf)
484
- raf = requestAnimationFrame(draw);
775
+ if (queued)
776
+ return;
777
+ queued = true;
778
+ queueMicrotask(draw);
485
779
  };
486
780
  const offs = [
487
781
  store.subscribe(schedule),
@@ -489,6 +783,7 @@ function MeshCanvas({ store, display, overscan, view3d, state, decals, }) {
489
783
  overscan.subscribe(schedule),
490
784
  view3d()?.subscribe(schedule),
491
785
  decals?.subscribe(schedule),
786
+ cover?.target.subscribe(schedule),
492
787
  ];
493
788
  const onResize = () => schedule();
494
789
  window.addEventListener("resize", onResize);
@@ -498,12 +793,13 @@ function MeshCanvas({ store, display, overscan, view3d, state, decals, }) {
498
793
  for (const off of offs)
499
794
  off?.();
500
795
  window.removeEventListener("resize", onResize);
796
+ disposed = true;
501
797
  if (raf)
502
798
  cancelAnimationFrame(raf);
503
799
  renderer.dispose();
504
800
  state.set({ drawing: false });
505
801
  };
506
- }, [store, display, overscan, view3d, state, decals]);
802
+ }, [store, display, overscan, view3d, state, decals, cover]);
507
803
  return (_jsx("canvas", { ref: ref, "data-usketch-elevation-mesh": "", style: {
508
804
  position: "absolute",
509
805
  inset: 0,
@@ -512,6 +808,32 @@ function MeshCanvas({ store, display, overscan, view3d, state, decals, }) {
512
808
  pointerEvents: "none",
513
809
  } }));
514
810
  }
811
+ /**
812
+ * The cover canvas (see the file comment), over the shapes, while the mesh draws the
813
+ * ground on its own canvas. The mesh paints it; this only mounts it.
814
+ */
815
+ export function ElevationCoverLayer({ target, state, }) {
816
+ const [drawing, setDrawing] = useState(() => state.get().drawing);
817
+ useEffect(() => {
818
+ const check = () => setDrawing(state.get().drawing);
819
+ check();
820
+ return state.subscribe(check);
821
+ }, [state]);
822
+ const ref = useCallback((el) => {
823
+ // `set` skips `undefined` but not `null`: unmounting clears it.
824
+ if (target.get().canvas !== el)
825
+ target.set({ canvas: el });
826
+ }, [target]);
827
+ if (!drawing)
828
+ return null;
829
+ return (_jsx("canvas", { ref: ref, "data-usketch-elevation-cover": "", style: {
830
+ position: "absolute",
831
+ inset: 0,
832
+ width: "100%",
833
+ height: "100%",
834
+ pointerEvents: "none",
835
+ } }));
836
+ }
515
837
  /**
516
838
  * The mesh as a drawable of a GPU 3D renderer (`view3dGl` in shared): drawn into its
517
839
  * canvas and depth buffer, so what stands on the hills sorts against them. Asks for a