@kuncat/avoidant 0.1.4 → 0.2.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.
Files changed (52) hide show
  1. package/README.md +26 -0
  2. package/dist/components/AvoidantGame.svelte +226 -137
  3. package/dist/components/IdleBillboard.svelte +27 -0
  4. package/dist/components/IdleBillboard.svelte.d.ts +8 -0
  5. package/dist/components/board.svelte +245 -99
  6. package/dist/components/board.svelte.d.ts +3 -0
  7. package/dist/components/fragment.glsl +29 -19
  8. package/dist/components/terrain-depth-sort.d.ts +17 -0
  9. package/dist/components/terrain-depth-sort.js +63 -0
  10. package/dist/components/vertex.glsl +12 -7
  11. package/dist/generated/shared-constants.d.ts +0 -3
  12. package/dist/generated/shared-constants.js +0 -3
  13. package/dist/paraglide/messages/_index.d.ts +14 -0
  14. package/dist/paraglide/messages/_index.js +15 -1
  15. package/dist/paraglide/messages/cells_per_face.d.ts +18 -0
  16. package/dist/paraglide/messages/cells_per_face.js +29 -0
  17. package/dist/paraglide/messages/faces_count.d.ts +18 -0
  18. package/dist/paraglide/messages/faces_count.js +29 -0
  19. package/dist/paraglide/messages/field_cell_density.d.ts +16 -0
  20. package/dist/paraglide/messages/field_cell_density.js +29 -0
  21. package/dist/paraglide/messages/field_map_shape.d.ts +16 -0
  22. package/dist/paraglide/messages/field_map_shape.js +29 -0
  23. package/dist/paraglide/messages/field_radius.d.ts +16 -0
  24. package/dist/paraglide/messages/field_radius.js +29 -0
  25. package/dist/paraglide/messages/field_radius_x.d.ts +16 -0
  26. package/dist/paraglide/messages/field_radius_x.js +29 -0
  27. package/dist/paraglide/messages/field_radius_y.d.ts +16 -0
  28. package/dist/paraglide/messages/field_radius_y.js +29 -0
  29. package/dist/paraglide/messages/field_radius_z.d.ts +16 -0
  30. package/dist/paraglide/messages/field_radius_z.js +29 -0
  31. package/dist/paraglide/messages/field_spikiness.d.ts +16 -0
  32. package/dist/paraglide/messages/field_spikiness.js +29 -0
  33. package/dist/paraglide/messages/field_subdivisions.d.ts +16 -0
  34. package/dist/paraglide/messages/field_subdivisions.js +29 -0
  35. package/dist/paraglide/messages/field_surface_detail.d.ts +16 -0
  36. package/dist/paraglide/messages/field_surface_detail.js +29 -0
  37. package/dist/paraglide/messages/shape_label.d.ts +26 -0
  38. package/dist/paraglide/messages/shape_label.js +55 -0
  39. package/dist/paraglide/messages/text_density_summary.d.ts +19 -0
  40. package/dist/paraglide/messages/text_density_summary.js +29 -0
  41. package/dist/paraglide/messages/text_invite_after_opening.d.ts +16 -0
  42. package/dist/paraglide/messages/text_invite_after_opening.js +29 -0
  43. package/dist/troika-webgl2-atlas.d.ts +33 -0
  44. package/dist/troika-webgl2-atlas.js +65 -0
  45. package/dist/wasm/avoidant_wasm.d.ts +77 -35
  46. package/dist/wasm/avoidant_wasm.js +236 -223
  47. package/dist/wasm/avoidant_wasm_bg.wasm +0 -0
  48. package/dist/wasm/avoidant_wasm_bg.wasm.d.ts +27 -27
  49. package/dist/workers/mapgen-client.js +2 -0
  50. package/dist/workers/mapgen.worker.d.ts +2 -0
  51. package/dist/workers/mapgen.worker.js +3 -0
  52. package/package.json +1 -1
@@ -1,9 +1,14 @@
1
1
  <script module lang="ts">
2
2
  import _vertexShader from "./vertex.glsl?raw";
3
3
  import _fragmentShader from "./fragment.glsl?raw";
4
- import { MAP_AREA, PULSE_SWEEP_BAND } from "../generated/shared-constants";
4
+ import { PULSE_SWEEP_BAND } from "../generated/shared-constants";
5
5
  import openSans from "../assets/OpenSans-VariableFont_wdth,wght.ttf?url";
6
6
  import { getLocale } from "../paraglide/runtime";
7
+ import { installTroikaWebGL2AtlasFix } from "../troika-webgl2-atlas";
8
+
9
+ // Must run before troika-three-text (`<Text>`) creates its SDF atlas canvas so it
10
+ // gets a WebGL 2 context. Works around Brave dropping ANGLE_instanced_arrays.
11
+ installTroikaWebGL2AtlasFix();
7
12
 
8
13
  export const MAX_PULSES = 16;
9
14
  export const VOID_FALL_DURATION_MS = 900;
@@ -44,18 +49,20 @@
44
49
  </script>
45
50
 
46
51
  <script lang="ts">
47
- import { onMount } from "svelte";
52
+ import IdleBillboard from "./IdleBillboard.svelte";
53
+ import { TerrainDepthSort } from "./terrain-depth-sort";
48
54
  import { SvelteMap, SvelteSet } from "svelte/reactivity";
49
55
  import { Pulse } from "../wasm/avoidant_wasm";
50
56
  import type { GameState } from "../wasm/avoidant_wasm";
51
- import { T, useThrelte } from "@threlte/core";
52
- import { interactivity, Text, Billboard } from "@threlte/extras";
57
+ import { T, useTask, useThrelte } from "@threlte/core";
58
+ import { interactivity, Text } from "@threlte/extras";
53
59
  import {
54
60
  BufferAttribute,
55
61
  BufferGeometry,
56
62
  DataTexture,
57
63
  DoubleSide,
58
64
  Mesh,
65
+ Matrix4,
59
66
  NearestFilter,
60
67
  RGBAFormat,
61
68
  ShaderMaterial,
@@ -69,7 +76,11 @@
69
76
 
70
77
  interface Props {
71
78
  gameState: GameState;
72
- terrain?: { positions: number[]; normals: number[]; cellIndices: number[] } | undefined;
79
+ terrain?:
80
+ | { positions: number[]; normals: number[]; cellIndices: number[]; heights: number[] }
81
+ | undefined;
82
+ flat?: boolean;
83
+ surfaceArea?: number;
73
84
  interactive?: boolean;
74
85
  highlightedCellIndex?: number | undefined;
75
86
  onCellClicked?: (cellIndex: number) => void;
@@ -78,6 +89,8 @@
78
89
  let {
79
90
  gameState = $bindable(),
80
91
  terrain = undefined,
92
+ flat = false,
93
+ surfaceArea = 0,
81
94
  interactive = true,
82
95
  highlightedCellIndex = undefined,
83
96
  onCellClicked = undefined,
@@ -87,109 +100,172 @@
87
100
  let pulses = $derived(gameState?.uiState?.pulses);
88
101
  let nowMs = $state(0);
89
102
 
90
- onMount(() => {
91
- let rafId = 0;
92
- const tick = () => {
93
- const now = performance.now();
94
- const hasActivePulses = $pulses.some((p) => now - p.createdAtMs < Math.max(1, p.durationMs));
95
- const hasFallingCells = fallStart.size > 0;
96
- const hasHighlight = highlightedCellIndex !== undefined;
97
- if (hasActivePulses || hasFallingCells || hasHighlight) {
98
- nowMs = now;
99
-
100
- if (hasFallingCells) {
101
- const meta = cellMeta;
102
- for (const [cellIndex, startMs] of fallStart) {
103
- const progress = Math.min(1, (now - startMs) / VOID_FALL_DURATION_MS);
104
- meta.setFallProgress(cellIndex, progress);
105
- if (progress >= 1) {
106
- fallStart.delete(cellIndex);
107
- fellCells.add(cellIndex);
108
- }
109
- }
110
- meta.flush();
111
- }
112
-
113
- // Invalidate when remote state changes to draw a new frame.
114
- invalidate();
115
- }
116
- rafId = requestAnimationFrame(tick);
117
- };
118
- rafId = requestAnimationFrame(tick);
119
- return () => cancelAnimationFrame(rafId);
120
- });
121
-
122
103
  /**
123
104
  * Build a merged triangle mesh for all cell interiors from a Rust-side subdivided terrain payload.
124
105
  *
125
- * Each emitted vertex carries an `aCellIndex` attribute so the fragment shader can look up per-cell metadata in {@link CellMetaTexture}. The subdivision (and therefore the terrain detail) is decoupled from the Voronoi cell-corner density and is controlled by the `terrainSubdivisions` field on {@link GameOptions}.
126
- *
127
- * When `shrinkFactor < 1`, every vertex's XZ position is contracted toward its cell's XZ centroid by that factor, producing gaps between adjacent cells. A second copy of the geometry rendered un-shrunken (with `shrinkFactor = 1`) underneath shows through those gaps as the "gap lines". Y values and normals are preserved as-is. At the 3-4% shrink range the slight inconsistency between a perimeter vertex's stored Y/normal and the true noise surface at its new XZ is invisible.
106
+ * Each emitted vertex carries an `aCellIndex` attribute so the fragment shader can look up per-cell metadata in {@link CellMetaTexture}. It also carries `aCellNormal` (the cell's outward unit normal) so the vertex shader can displace falling void cells along the local outward direction — which is the face normal for polyhedra and the surface normal for spheroids — instead of along world Y.
128
107
  *
129
- * @param payload - Pre-built positions (`[x, height, y]`-packed) and
130
- * per-vertex cell indices produced by the mapgen worker. `undefined`
131
- * yields an empty geometry, which is the expected state before mapgen
132
- * completes.
133
- * @param insetDistance - World-space distance (XZ plane) to pull each vertex toward its cell centroid, producing a uniform-width gap along every cell boundary. `0` (default) leaves the mesh untouched. Per vertex the move is clamped to 80% of its centroid distance to avoid collapsing small cells.
134
- * @returns A `BufferGeometry` with `position`, `aNormal`, and `aCellIndex` attributes.
108
+ * When `insetDistance > 0`, every vertex is pulled toward its cell's 3D centroid in the *tangent plane* perpendicular to the cell normal, producing uniform-width gaps between adjacent cells regardless of the cell's orientation on the surface. The component of the offset along the normal is left untouched so terrain elevation isn't squashed.
135
109
  */
136
110
  function buildTerrainLayer(
137
- payload: { positions: number[]; normals: number[]; cellIndices: number[] } | undefined,
111
+ payload:
112
+ | { positions: number[]; normals: number[]; cellIndices: number[]; heights: number[] }
113
+ | undefined,
114
+ cellNormalsByIndex: Float32Array | undefined,
115
+ cellVertices: number[][][],
116
+ flat: boolean,
138
117
  insetDistance = 0,
139
118
  ): BufferGeometry {
140
119
  const geometry = new BufferGeometry();
141
120
  if (!payload || payload.positions.length === 0) {
142
121
  geometry.setAttribute("position", new BufferAttribute(new Float32Array(0), 3));
143
122
  geometry.setAttribute("aNormal", new BufferAttribute(new Float32Array(0), 3));
123
+ geometry.setAttribute("aCellNormal", new BufferAttribute(new Float32Array(0), 3));
144
124
  geometry.setAttribute("aCellIndex", new BufferAttribute(new Float32Array(0), 1));
125
+ geometry.setAttribute("aHeight", new BufferAttribute(new Float32Array(0), 1));
126
+ geometry.setAttribute("aEdgeDistance", new BufferAttribute(new Float32Array(0), 1));
145
127
  return geometry;
146
128
  }
147
129
 
148
130
  const positions = new Float32Array(payload.positions);
149
- if (insetDistance > 0) {
150
- const cellIndices = payload.cellIndices;
151
- const vertexCount = cellIndices.length;
152
- let maxCell = 0;
131
+ const cellIndices = payload.cellIndices;
132
+ const vertexCount = cellIndices.length;
133
+
134
+ // Measure against the original cell perimeter, not the terrain triangle
135
+ // edges. Undo radial elevation before measuring so outlines follow hills
136
+ // without outlining the interior tessellation.
137
+ const edgeDistances = new Float32Array(vertexCount);
138
+ for (let i = 0; i < vertexCount; i++) {
139
+ const x = positions[i * 3];
140
+ const y = positions[i * 3 + 1];
141
+ const z = positions[i * 3 + 2];
142
+ const radius = Math.hypot(x, y, z);
143
+ const factor = radius > 0 ? 1 - payload.heights[i] / radius : 1;
144
+ const p = flat ? [x, y - payload.heights[i], z] : [x * factor, y * factor, z * factor];
145
+ const polygon = cellVertices[cellIndices[i]];
146
+ let nearest = Infinity;
147
+ for (let j = 0; j < polygon.length; j++) {
148
+ const a = polygon[j];
149
+ const b = polygon[(j + 1) % polygon.length];
150
+ const dx = b[0] - a[0];
151
+ const dy = b[1] - a[1];
152
+ const dz = b[2] - a[2];
153
+ const lengthSquared = dx * dx + dy * dy + dz * dz;
154
+ const t =
155
+ lengthSquared > 0
156
+ ? Math.max(
157
+ 0,
158
+ Math.min(
159
+ 1,
160
+ ((p[0] - a[0]) * dx + (p[1] - a[1]) * dy + (p[2] - a[2]) * dz) / lengthSquared,
161
+ ),
162
+ )
163
+ : 0;
164
+ nearest = Math.min(
165
+ nearest,
166
+ Math.hypot(p[0] - a[0] - t * dx, p[1] - a[1] - t * dy, p[2] - a[2] - t * dz),
167
+ );
168
+ }
169
+ edgeDistances[i] = nearest;
170
+ }
171
+ geometry.setAttribute("aEdgeDistance", new BufferAttribute(edgeDistances, 1));
172
+
173
+ // Compute per-cell 3D centroid from terrain vertices (after de-displacement
174
+ // we'd be on the un-noised surface, but for inset purposes the displaced
175
+ // centroid works fine — the lateral move is tiny relative to elevation).
176
+ let maxCell = 0;
177
+ for (let i = 0; i < vertexCount; i++) {
178
+ if (cellIndices[i] > maxCell) maxCell = cellIndices[i];
179
+ }
180
+ const cellCount = maxCell + 1;
181
+ const sumX = new Float64Array(cellCount);
182
+ const sumY = new Float64Array(cellCount);
183
+ const sumZ = new Float64Array(cellCount);
184
+ const count = new Uint32Array(cellCount);
185
+ for (let i = 0; i < vertexCount; i++) {
186
+ const c = cellIndices[i];
187
+ sumX[c] += positions[i * 3 + 0];
188
+ sumY[c] += positions[i * 3 + 1];
189
+ sumZ[c] += positions[i * 3 + 2];
190
+ count[c]++;
191
+ }
192
+ const cx = new Float32Array(cellCount);
193
+ const cy = new Float32Array(cellCount);
194
+ const cz = new Float32Array(cellCount);
195
+ for (let c = 0; c < cellCount; c++) {
196
+ if (count[c] > 0) {
197
+ cx[c] = sumX[c] / count[c];
198
+ cy[c] = sumY[c] / count[c];
199
+ cz[c] = sumZ[c] / count[c];
200
+ }
201
+ }
202
+
203
+ // Per-vertex cell normal lookup.
204
+ const cellNormalAttr = new Float32Array(vertexCount * 3);
205
+ if (cellNormalsByIndex && cellNormalsByIndex.length >= cellCount * 3) {
153
206
  for (let i = 0; i < vertexCount; i++) {
154
- if (cellIndices[i] > maxCell) maxCell = cellIndices[i];
207
+ const c = cellIndices[i];
208
+ cellNormalAttr[i * 3 + 0] = cellNormalsByIndex[c * 3 + 0];
209
+ cellNormalAttr[i * 3 + 1] = cellNormalsByIndex[c * 3 + 1];
210
+ cellNormalAttr[i * 3 + 2] = cellNormalsByIndex[c * 3 + 2];
155
211
  }
156
- const cellCount = maxCell + 1;
157
- const sumX = new Float64Array(cellCount);
158
- const sumZ = new Float64Array(cellCount);
159
- const count = new Uint32Array(cellCount);
212
+ } else {
213
+ // Fallback: derive cell normals from the average of per-vertex normals.
214
+ const nSum = new Float32Array(cellCount * 3);
160
215
  for (let i = 0; i < vertexCount; i++) {
161
216
  const c = cellIndices[i];
162
- sumX[c] += positions[i * 3 + 0];
163
- sumZ[c] += positions[i * 3 + 2];
164
- count[c]++;
217
+ nSum[c * 3 + 0] += payload.normals[i * 3 + 0];
218
+ nSum[c * 3 + 1] += payload.normals[i * 3 + 1];
219
+ nSum[c * 3 + 2] += payload.normals[i * 3 + 2];
165
220
  }
166
- const cx = new Float32Array(cellCount);
167
- const cz = new Float32Array(cellCount);
168
221
  for (let c = 0; c < cellCount; c++) {
169
- if (count[c] > 0) {
170
- cx[c] = sumX[c] / count[c];
171
- cz[c] = sumZ[c] / count[c];
172
- }
222
+ const nx = nSum[c * 3 + 0];
223
+ const ny = nSum[c * 3 + 1];
224
+ const nz = nSum[c * 3 + 2];
225
+ const len = Math.hypot(nx, ny, nz) || 1;
226
+ nSum[c * 3 + 0] = nx / len;
227
+ nSum[c * 3 + 1] = ny / len;
228
+ nSum[c * 3 + 2] = nz / len;
173
229
  }
230
+ for (let i = 0; i < vertexCount; i++) {
231
+ const c = cellIndices[i];
232
+ cellNormalAttr[i * 3 + 0] = nSum[c * 3 + 0];
233
+ cellNormalAttr[i * 3 + 1] = nSum[c * 3 + 1];
234
+ cellNormalAttr[i * 3 + 2] = nSum[c * 3 + 2];
235
+ }
236
+ }
237
+
238
+ if (insetDistance > 0) {
174
239
  for (let i = 0; i < vertexCount; i++) {
175
240
  const c = cellIndices[i];
176
241
  const dx = positions[i * 3 + 0] - cx[c];
242
+ const dy = positions[i * 3 + 1] - cy[c];
177
243
  const dz = positions[i * 3 + 2] - cz[c];
178
- const d = Math.hypot(dx, dz);
179
- if (d < 1e-6) continue;
180
- const move = Math.min(insetDistance, d);
181
- const k = move / d;
182
- positions[i * 3 + 0] -= dx * k;
183
- positions[i * 3 + 2] -= dz * k;
244
+ const nx = cellNormalAttr[i * 3 + 0];
245
+ const ny = cellNormalAttr[i * 3 + 1];
246
+ const nz = cellNormalAttr[i * 3 + 2];
247
+ const along = dx * nx + dy * ny + dz * nz;
248
+ const tx = dx - along * nx;
249
+ const ty = dy - along * ny;
250
+ const tz = dz - along * nz;
251
+ const tlen = Math.hypot(tx, ty, tz);
252
+ if (tlen < 1e-6) continue;
253
+ const move = Math.min(insetDistance, tlen);
254
+ const k = move / tlen;
255
+ positions[i * 3 + 0] -= tx * k;
256
+ positions[i * 3 + 1] -= ty * k;
257
+ positions[i * 3 + 2] -= tz * k;
184
258
  }
185
259
  }
186
260
 
187
261
  geometry.setAttribute("position", new BufferAttribute(positions, 3));
188
262
  geometry.setAttribute("aNormal", new BufferAttribute(new Float32Array(payload.normals), 3));
263
+ geometry.setAttribute("aCellNormal", new BufferAttribute(cellNormalAttr, 3));
189
264
  geometry.setAttribute(
190
265
  "aCellIndex",
191
266
  new BufferAttribute(new Float32Array(payload.cellIndices), 1),
192
267
  );
268
+ geometry.setAttribute("aHeight", new BufferAttribute(new Float32Array(payload.heights), 1));
193
269
  return geometry;
194
270
  }
195
271
 
@@ -205,6 +281,11 @@
205
281
  private readonly data: Uint8Array;
206
282
  /** Number of texels/cells. */
207
283
  readonly width: number;
284
+ revision = 0;
285
+
286
+ fallProgress(cellIndex: number): number {
287
+ return this.data[cellIndex * 4 + CellMetaChannel.FallProgress] / 255;
288
+ }
208
289
 
209
290
  /**
210
291
  * Allocate a cell metadata texture.
@@ -257,6 +338,7 @@
257
338
 
258
339
  /** Mark the texture dirty so Three.js re-uploads it on the next frame. */
259
340
  flush(): void {
341
+ this.revision++;
260
342
  this.texture.needsUpdate = true;
261
343
  }
262
344
 
@@ -266,10 +348,30 @@
266
348
  }
267
349
  }
268
350
 
269
- // Each cell's vertices are pulled toward its XZ centroid by a constant distance (`CELL_GAP_HALF_WIDTH`). The total visible gap width is ~2× this value.
351
+ // Each cell's vertices are pulled toward its 3D centroid (in the cell's tangent plane) by a constant distance (`CELL_GAP_HALF_WIDTH`). The total visible gap width is ~2× this value.
270
352
  const CELL_GAP_HALF_WIDTH = 0.08;
271
- const cellRadius = $derived(Math.sqrt(MAP_AREA / (Math.PI * Math.max(1, $cells.length))));
272
- const terrainGeometry = $derived(buildTerrainLayer(terrain, CELL_GAP_HALF_WIDTH));
353
+ const cellRadius = $derived(
354
+ Math.sqrt(Math.max(0, surfaceArea) / (Math.PI * Math.max(1, $cells.length))),
355
+ );
356
+ const cellNormalsByIndex = $derived.by(() => {
357
+ const arr = new Float32Array($cells.length * 3);
358
+ for (let i = 0; i < $cells.length; i++) {
359
+ const n = $cells[i].normal;
360
+ arr[i * 3 + 0] = n[0];
361
+ arr[i * 3 + 1] = n[1];
362
+ arr[i * 3 + 2] = n[2];
363
+ }
364
+ return arr;
365
+ });
366
+ const terrainGeometry = $derived(
367
+ buildTerrainLayer(
368
+ terrain,
369
+ cellNormalsByIndex,
370
+ $cells.map((cell) => cell.vertices),
371
+ flat,
372
+ CELL_GAP_HALF_WIDTH,
373
+ ),
374
+ );
273
375
  const cellMeta = $derived(new CellMetaTexture($cells.length));
274
376
 
275
377
  let fallStart = new SvelteMap<number, number>();
@@ -297,14 +399,15 @@
297
399
  fragmentShader,
298
400
  side: DoubleSide,
299
401
  transparent: true,
402
+ depthWrite: false,
403
+ // Triangle sorting handles both sides together, including concave hills.
404
+ forceSinglePass: true,
300
405
  uniforms: {
406
+ uTransparentPass: { value: true },
301
407
  elevationMin: { value: gameState.elevationMin },
302
408
  elevationMax: { value: gameState.elevationMax },
303
409
  uCellMeta: { value: cellMeta.texture },
304
410
  uCellMetaSize: { value: cellMeta.width },
305
- uLightDir: { value: new Vector3(0.45, 1.0, 0.3).normalize() },
306
- uAmbient: { value: 0.55 },
307
- uDiffuse: { value: 0.75 },
308
411
  pulseCount: { value: 0 },
309
412
  pulseTimers: { value: new Array(MAX_PULSES).fill(0) },
310
413
  pulsePositions: {
@@ -327,39 +430,58 @@
327
430
  };
328
431
  });
329
432
 
330
- let terrainMesh = $derived(new Mesh(terrainGeometry, terrainMaterial));
433
+ // Opaque revealed cells populate depth first. The transparent pass blends
434
+ // unexplored/falling cells against that depth without blocking later layers.
435
+ const opaqueMaterial = $derived(
436
+ new ShaderMaterial({
437
+ vertexShader,
438
+ fragmentShader,
439
+ side: DoubleSide,
440
+ transparent: false,
441
+ depthWrite: true,
442
+ uniforms: { ...terrainMaterial.uniforms, uTransparentPass: { value: false } },
443
+ }),
444
+ );
445
+ $effect(() => {
446
+ const material = opaqueMaterial;
447
+ return () => material.dispose();
448
+ });
449
+ const opaqueMesh = $derived(new Mesh(terrainGeometry, opaqueMaterial));
450
+ let terrainMesh = $derived.by(() => {
451
+ const mesh = new Mesh(terrainGeometry, terrainMaterial);
452
+ const sorter = new TerrainDepthSort(terrainGeometry);
453
+ const meta = cellMeta;
454
+ const view = new Matrix4();
455
+ mesh.onBeforeRender = (_renderer, _scene, camera) => {
456
+ view.multiplyMatrices(camera.matrixWorldInverse, mesh.matrixWorld);
457
+ sorter.update(view, meta.revision, (cell) => meta.fallProgress(cell) * VOID_FALL_DISTANCE);
458
+ };
459
+ return mesh;
460
+ });
331
461
 
332
- const LABEL_LIFT_FACTOR = 0.075;
462
+ const LABEL_LIFT_FACTOR = 0.4;
463
+ /// Maximum per-vertex elevation displacement (raw scalar from the noise field) seen inside each cell, used to lift labels above the noisiest part of the terrain.
333
464
  const terrainCellMaxHeights = $derived.by(() => {
334
- const result: number[] = new Array($cells.length).fill(-Infinity);
465
+ const result: number[] = new Array($cells.length).fill(0);
335
466
  if (!terrain) return result;
336
- const positions = terrain.positions;
467
+ const heights = terrain.heights;
337
468
  const cellIndices = terrain.cellIndices;
338
469
  for (let i = 0; i < cellIndices.length; i++) {
339
470
  const ci = cellIndices[i];
340
- const h = positions[i * 3 + 1];
471
+ const h = heights[i];
341
472
  if (h > result[ci]) result[ci] = h;
342
473
  }
343
474
  return result;
344
475
  });
345
476
  const cellLabelAnchors = $derived(
346
477
  $cells.map((cell, idx) => {
347
- const vs = cell.vertices;
348
- if (vs.length === 0) return { x: 0, y: 0, z: 0 };
349
- let sx = 0;
350
- let sz = 0;
351
- let maxH = -Infinity;
352
- for (const [vx, vy, vh] of vs) {
353
- sx += vx;
354
- sz += vy;
355
- if (vh > maxH) maxH = vh;
356
- }
357
- const terrainMax = terrainCellMaxHeights[idx];
358
- if (terrainMax !== undefined && terrainMax > maxH) maxH = terrainMax;
478
+ const [cxv, cyv, czv] = cell.centroid;
479
+ const [nx, ny, nz] = cell.normal;
480
+ const lift = (terrainCellMaxHeights[idx] ?? 0) + cellRadius * LABEL_LIFT_FACTOR;
359
481
  return {
360
- x: sx / vs.length,
361
- y: maxH + cellRadius * LABEL_LIFT_FACTOR,
362
- z: sz / vs.length,
482
+ x: cxv + nx * lift,
483
+ y: cyv + ny * lift,
484
+ z: czv + nz * lift,
363
485
  };
364
486
  }),
365
487
  );
@@ -440,15 +562,39 @@
440
562
  gameState.queueExplorePulse(cellIndex, event.point.x, event.point.y, event.point.z);
441
563
  onCellClicked?.(cellIndex);
442
564
  }
565
+ useTask(
566
+ () => {
567
+ const now = performance.now();
568
+ nowMs = now;
569
+ if (fallStart.size > 0) {
570
+ const meta = cellMeta;
571
+ for (const [cellIndex, startMs] of fallStart) {
572
+ const progress = Math.min(1, (now - startMs) / VOID_FALL_DURATION_MS);
573
+ meta.setFallProgress(cellIndex, progress);
574
+ if (progress >= 1) {
575
+ fallStart.delete(cellIndex);
576
+ fellCells.add(cellIndex);
577
+ }
578
+ }
579
+ meta.flush();
580
+ }
581
+ invalidate();
582
+ },
583
+ {
584
+ autoInvalidate: false,
585
+ running: () => $pulses.length > 0 || fallStart.size > 0 || highlightedCellIndex !== undefined,
586
+ },
587
+ );
443
588
  </script>
444
589
 
590
+ <T is={opaqueMesh} />
445
591
  <T is={terrainMesh} onclick={handleTerrainClick} />
446
592
 
447
593
  {#each $cellMetadata as entry, i (i)}
448
594
  {#if entry.isExplored && !entry.isVoid && entry.voidNeighborCount > 0}
449
595
  {@const anchor = cellLabelAnchors[i]}
450
596
  {#if anchor}
451
- <Billboard position={[anchor.x, anchor.y, anchor.z]}>
597
+ <IdleBillboard position={[anchor.x, anchor.y, anchor.z]}>
452
598
  <Text
453
599
  text={entry.voidNeighborCount.toLocaleString(getLocale())}
454
600
  font={openSans}
@@ -459,7 +605,7 @@
459
605
  outlineWidth={cellRadius * 0.04}
460
606
  outlineColor="#f8fafc"
461
607
  />
462
- </Billboard>
608
+ </IdleBillboard>
463
609
  {/if}
464
610
  {/if}
465
611
  {/each}
@@ -25,7 +25,10 @@ interface Props {
25
25
  positions: number[];
26
26
  normals: number[];
27
27
  cellIndices: number[];
28
+ heights: number[];
28
29
  } | undefined;
30
+ flat?: boolean;
31
+ surfaceArea?: number;
29
32
  interactive?: boolean;
30
33
  highlightedCellIndex?: number | undefined;
31
34
  onCellClicked?: (cellIndex: number) => void;
@@ -1,9 +1,11 @@
1
1
  varying vec3 vWorldPosition;
2
- varying vec3 vNormal;
3
2
  varying float vHeight;
3
+ varying float vEdgeDistance;
4
+ varying float vRelief;
4
5
  varying float vCellIndex;
5
6
  varying float vFallProgress;
6
7
 
8
+ uniform bool uTransparentPass;
7
9
  uniform float elevationMin;
8
10
  uniform float elevationMax;
9
11
  uniform sampler2D uCellMeta;
@@ -14,14 +16,11 @@ uniform vec3 pulsePositions[MAX_PULSES];
14
16
  uniform float pulseOriginCells[MAX_PULSES];
15
17
  uniform float pulseIsRemote[MAX_PULSES];
16
18
  uniform float pulseMaxRadii[MAX_PULSES];
17
- uniform vec3 uLightDir;
18
- uniform float uAmbient;
19
- uniform float uDiffuse;
20
19
  uniform float uHighlightedCell;
21
20
  uniform float uTime;
22
21
 
23
22
  float remapClamped(float value, float inMin, float inMax, float outMin, float outMax) {
24
- float t = clamp((value - inMin) / (inMax - inMin), 0.0, 1.0);
23
+ float t = clamp((value - inMin) / max(inMax - inMin, 0.0001), 0.0, 1.0);
25
24
  return mix(outMin, outMax, t);
26
25
  }
27
26
 
@@ -34,6 +33,17 @@ void main() {
34
33
  // Once an explored void cell has fully fallen, drop every fragment.
35
34
  if (isVoid > 0.5 && isExplored > 0.5 && vFallProgress >= 0.999) discard;
36
35
 
36
+ // Unexplored cells retain slight transparency; revealed solid cells are opaque.
37
+ float alpha = isExplored > 0.5 ? 1.0 : 0.95;
38
+ // Fade alpha while an explored void cell is falling.
39
+ if (isVoid > 0.5 && isExplored > 0.5) {
40
+ alpha = clamp(1.0 - vFallProgress, 0.0, 1.0);
41
+ }
42
+
43
+ // Keep opaque depth separate from blended layers. The two passes must be
44
+ // mutually exclusive so no cell is drawn twice.
45
+ if (uTransparentPass ? alpha >= 1.0 : alpha < 1.0) discard;
46
+
37
47
  float elevation = remapClamped(vHeight, elevationMin, elevationMax, 0.0, 1.0);
38
48
 
39
49
  float totalRing = 0.0;
@@ -48,7 +58,9 @@ void main() {
48
58
  float maxRadius = pulseMaxRadii[i];
49
59
  float ringRadius = pulseProgress * maxRadius;
50
60
  float ringWidth = 1.2;
51
- float distToOrigin = distance(vWorldPosition.xz, pulsePositions[i].xz);
61
+ // Use full 3D distance — pulses radiate outward over the curved surface
62
+ // of the polyhedron/spheroid, not within an XZ plane.
63
+ float distToOrigin = distance(vWorldPosition, pulsePositions[i]);
52
64
  float ringDistance = abs(distToOrigin - ringRadius);
53
65
  float ring = (1.0 - smoothstep(ringWidth, ringWidth + 0.8, ringDistance)) * pulseActive;
54
66
  float pulseFade = 1.0 - pulseProgress;
@@ -69,19 +81,16 @@ void main() {
69
81
 
70
82
  vec3 unexploredLow = vec3(0.2588, 0.2588, 0.2784);
71
83
  vec3 unexploredHigh = vec3(0.4431, 0.451, 0.4706);
72
- vec3 exploredLow = vec3(0.6588, 0.7098, 0.7922);
73
- vec3 exploredHigh = vec3(0.6784, 0.7137, 0.7451);
84
+ vec3 exploredLow = vec3(0.43, 0.5, 0.59);
85
+ vec3 exploredHigh = vec3(0.75, 0.79, 0.84);
74
86
 
75
87
  vec3 lowColor = mix(unexploredLow, exploredLow, colorFactor);
76
88
  vec3 highColor = mix(unexploredHigh, exploredHigh, colorFactor);
77
89
  vec3 terrainColor = mix(lowColor, highColor, elevation);
78
90
 
79
- // Smooth hillshading
80
- vec3 shadingNormal = normalize(vNormal);
81
- if (shadingNormal.y < 0.0) shadingNormal = -shadingNormal;
82
- float ndotl = max(dot(shadingNormal, normalize(uLightDir)), 0.0);
83
- float shade = clamp(uAmbient + uDiffuse * ndotl, 0.0, 1.5);
84
- terrainColor *= shade;
91
+ // Uniform illumination keeps every face readable regardless of its
92
+ // orientation, with a subdued level that avoids near-white revealed cells.
93
+ terrainColor *= 0.9 * mix(0.82, 1.0, vRelief);
85
94
 
86
95
  vec3 localPulseTint = vec3(0.55, 0.95, 1.0);
87
96
  vec3 remotePulseTint = vec3(1.0, 0.42, 0.38);
@@ -97,11 +106,12 @@ void main() {
97
106
  finalColor = mix(finalColor, glowColor, 0.35 + 0.45 * glowPulse);
98
107
  }
99
108
 
100
- float alpha = isExplored > 0.5 ? 1.0 : 0.25;
101
- // Fade alpha while an explored void cell is falling.
102
- if (isVoid > 0.5 && isExplored > 0.5) {
103
- alpha = clamp(1.0 - vFallProgress, 0.0, 1.0);
104
- }
109
+ // Draw an antialiased perimeter on the surface itself. A pixel-based
110
+ // minimum keeps borders visible when zooming out or viewing at an angle.
111
+ float edgePixel = max(fwidth(vEdgeDistance), 0.0001);
112
+ float borderWidth = max(0.04, 1.1 * edgePixel);
113
+ float border = 1.0 - smoothstep(borderWidth, borderWidth + edgePixel, vEdgeDistance);
114
+ finalColor = mix(finalColor, vec3(0.1, 0.13, 0.18), border * 0.9);
105
115
 
106
116
  gl_FragColor = vec4(clamp(finalColor, 0.0, 1.0), alpha);
107
117
  }
@@ -0,0 +1,17 @@
1
+ import { BufferGeometry, Matrix4 } from "three";
2
+ /** Sort individual triangles in a merged surface, including falling cells.
3
+ * Three.js sorts transparent objects, but cannot sort triangles inside a mesh.
4
+ * Only the index buffer changes, preserving all per-vertex cell IDs for picking.
5
+ */
6
+ export declare class TerrainDepthSort {
7
+ private readonly centers;
8
+ private readonly normals;
9
+ private readonly cells;
10
+ private readonly depths;
11
+ private readonly order;
12
+ private readonly index;
13
+ private readonly previousView;
14
+ private previousRevision;
15
+ constructor(geometry: BufferGeometry);
16
+ update(view: Matrix4, revision: number, fallDistance: (cell: number) => number): void;
17
+ }