@kuncat/avoidant 0.1.5 → 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 (50) 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 +240 -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/wasm/avoidant_wasm.d.ts +77 -35
  44. package/dist/wasm/avoidant_wasm.js +236 -223
  45. package/dist/wasm/avoidant_wasm_bg.wasm +0 -0
  46. package/dist/wasm/avoidant_wasm_bg.wasm.d.ts +27 -27
  47. package/dist/workers/mapgen-client.js +2 -0
  48. package/dist/workers/mapgen.worker.d.ts +2 -0
  49. package/dist/workers/mapgen.worker.js +3 -0
  50. package/package.json +1 -1
@@ -1,7 +1,7 @@
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
7
  import { installTroikaWebGL2AtlasFix } from "../troika-webgl2-atlas";
@@ -49,18 +49,20 @@
49
49
  </script>
50
50
 
51
51
  <script lang="ts">
52
- import { onMount } from "svelte";
52
+ import IdleBillboard from "./IdleBillboard.svelte";
53
+ import { TerrainDepthSort } from "./terrain-depth-sort";
53
54
  import { SvelteMap, SvelteSet } from "svelte/reactivity";
54
55
  import { Pulse } from "../wasm/avoidant_wasm";
55
56
  import type { GameState } from "../wasm/avoidant_wasm";
56
- import { T, useThrelte } from "@threlte/core";
57
- import { interactivity, Text, Billboard } from "@threlte/extras";
57
+ import { T, useTask, useThrelte } from "@threlte/core";
58
+ import { interactivity, Text } from "@threlte/extras";
58
59
  import {
59
60
  BufferAttribute,
60
61
  BufferGeometry,
61
62
  DataTexture,
62
63
  DoubleSide,
63
64
  Mesh,
65
+ Matrix4,
64
66
  NearestFilter,
65
67
  RGBAFormat,
66
68
  ShaderMaterial,
@@ -74,7 +76,11 @@
74
76
 
75
77
  interface Props {
76
78
  gameState: GameState;
77
- 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;
78
84
  interactive?: boolean;
79
85
  highlightedCellIndex?: number | undefined;
80
86
  onCellClicked?: (cellIndex: number) => void;
@@ -83,6 +89,8 @@
83
89
  let {
84
90
  gameState = $bindable(),
85
91
  terrain = undefined,
92
+ flat = false,
93
+ surfaceArea = 0,
86
94
  interactive = true,
87
95
  highlightedCellIndex = undefined,
88
96
  onCellClicked = undefined,
@@ -92,109 +100,172 @@
92
100
  let pulses = $derived(gameState?.uiState?.pulses);
93
101
  let nowMs = $state(0);
94
102
 
95
- onMount(() => {
96
- let rafId = 0;
97
- const tick = () => {
98
- const now = performance.now();
99
- const hasActivePulses = $pulses.some((p) => now - p.createdAtMs < Math.max(1, p.durationMs));
100
- const hasFallingCells = fallStart.size > 0;
101
- const hasHighlight = highlightedCellIndex !== undefined;
102
- if (hasActivePulses || hasFallingCells || hasHighlight) {
103
- nowMs = now;
104
-
105
- if (hasFallingCells) {
106
- const meta = cellMeta;
107
- for (const [cellIndex, startMs] of fallStart) {
108
- const progress = Math.min(1, (now - startMs) / VOID_FALL_DURATION_MS);
109
- meta.setFallProgress(cellIndex, progress);
110
- if (progress >= 1) {
111
- fallStart.delete(cellIndex);
112
- fellCells.add(cellIndex);
113
- }
114
- }
115
- meta.flush();
116
- }
117
-
118
- // Invalidate when remote state changes to draw a new frame.
119
- invalidate();
120
- }
121
- rafId = requestAnimationFrame(tick);
122
- };
123
- rafId = requestAnimationFrame(tick);
124
- return () => cancelAnimationFrame(rafId);
125
- });
126
-
127
103
  /**
128
104
  * Build a merged triangle mesh for all cell interiors from a Rust-side subdivided terrain payload.
129
105
  *
130
- * 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}.
131
- *
132
- * 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.
133
107
  *
134
- * @param payload - Pre-built positions (`[x, height, y]`-packed) and
135
- * per-vertex cell indices produced by the mapgen worker. `undefined`
136
- * yields an empty geometry, which is the expected state before mapgen
137
- * completes.
138
- * @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.
139
- * @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.
140
109
  */
141
110
  function buildTerrainLayer(
142
- 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,
143
117
  insetDistance = 0,
144
118
  ): BufferGeometry {
145
119
  const geometry = new BufferGeometry();
146
120
  if (!payload || payload.positions.length === 0) {
147
121
  geometry.setAttribute("position", new BufferAttribute(new Float32Array(0), 3));
148
122
  geometry.setAttribute("aNormal", new BufferAttribute(new Float32Array(0), 3));
123
+ geometry.setAttribute("aCellNormal", new BufferAttribute(new Float32Array(0), 3));
149
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));
150
127
  return geometry;
151
128
  }
152
129
 
153
130
  const positions = new Float32Array(payload.positions);
154
- if (insetDistance > 0) {
155
- const cellIndices = payload.cellIndices;
156
- const vertexCount = cellIndices.length;
157
- 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) {
158
206
  for (let i = 0; i < vertexCount; i++) {
159
- 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];
160
211
  }
161
- const cellCount = maxCell + 1;
162
- const sumX = new Float64Array(cellCount);
163
- const sumZ = new Float64Array(cellCount);
164
- 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);
165
215
  for (let i = 0; i < vertexCount; i++) {
166
216
  const c = cellIndices[i];
167
- sumX[c] += positions[i * 3 + 0];
168
- sumZ[c] += positions[i * 3 + 2];
169
- 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];
170
220
  }
171
- const cx = new Float32Array(cellCount);
172
- const cz = new Float32Array(cellCount);
173
221
  for (let c = 0; c < cellCount; c++) {
174
- if (count[c] > 0) {
175
- cx[c] = sumX[c] / count[c];
176
- cz[c] = sumZ[c] / count[c];
177
- }
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;
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];
178
235
  }
236
+ }
237
+
238
+ if (insetDistance > 0) {
179
239
  for (let i = 0; i < vertexCount; i++) {
180
240
  const c = cellIndices[i];
181
241
  const dx = positions[i * 3 + 0] - cx[c];
242
+ const dy = positions[i * 3 + 1] - cy[c];
182
243
  const dz = positions[i * 3 + 2] - cz[c];
183
- const d = Math.hypot(dx, dz);
184
- if (d < 1e-6) continue;
185
- const move = Math.min(insetDistance, d);
186
- const k = move / d;
187
- positions[i * 3 + 0] -= dx * k;
188
- 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;
189
258
  }
190
259
  }
191
260
 
192
261
  geometry.setAttribute("position", new BufferAttribute(positions, 3));
193
262
  geometry.setAttribute("aNormal", new BufferAttribute(new Float32Array(payload.normals), 3));
263
+ geometry.setAttribute("aCellNormal", new BufferAttribute(cellNormalAttr, 3));
194
264
  geometry.setAttribute(
195
265
  "aCellIndex",
196
266
  new BufferAttribute(new Float32Array(payload.cellIndices), 1),
197
267
  );
268
+ geometry.setAttribute("aHeight", new BufferAttribute(new Float32Array(payload.heights), 1));
198
269
  return geometry;
199
270
  }
200
271
 
@@ -210,6 +281,11 @@
210
281
  private readonly data: Uint8Array;
211
282
  /** Number of texels/cells. */
212
283
  readonly width: number;
284
+ revision = 0;
285
+
286
+ fallProgress(cellIndex: number): number {
287
+ return this.data[cellIndex * 4 + CellMetaChannel.FallProgress] / 255;
288
+ }
213
289
 
214
290
  /**
215
291
  * Allocate a cell metadata texture.
@@ -262,6 +338,7 @@
262
338
 
263
339
  /** Mark the texture dirty so Three.js re-uploads it on the next frame. */
264
340
  flush(): void {
341
+ this.revision++;
265
342
  this.texture.needsUpdate = true;
266
343
  }
267
344
 
@@ -271,10 +348,30 @@
271
348
  }
272
349
  }
273
350
 
274
- // 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.
275
352
  const CELL_GAP_HALF_WIDTH = 0.08;
276
- const cellRadius = $derived(Math.sqrt(MAP_AREA / (Math.PI * Math.max(1, $cells.length))));
277
- 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
+ );
278
375
  const cellMeta = $derived(new CellMetaTexture($cells.length));
279
376
 
280
377
  let fallStart = new SvelteMap<number, number>();
@@ -302,14 +399,15 @@
302
399
  fragmentShader,
303
400
  side: DoubleSide,
304
401
  transparent: true,
402
+ depthWrite: false,
403
+ // Triangle sorting handles both sides together, including concave hills.
404
+ forceSinglePass: true,
305
405
  uniforms: {
406
+ uTransparentPass: { value: true },
306
407
  elevationMin: { value: gameState.elevationMin },
307
408
  elevationMax: { value: gameState.elevationMax },
308
409
  uCellMeta: { value: cellMeta.texture },
309
410
  uCellMetaSize: { value: cellMeta.width },
310
- uLightDir: { value: new Vector3(0.45, 1.0, 0.3).normalize() },
311
- uAmbient: { value: 0.55 },
312
- uDiffuse: { value: 0.75 },
313
411
  pulseCount: { value: 0 },
314
412
  pulseTimers: { value: new Array(MAX_PULSES).fill(0) },
315
413
  pulsePositions: {
@@ -332,39 +430,58 @@
332
430
  };
333
431
  });
334
432
 
335
- 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
+ });
336
461
 
337
- 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.
338
464
  const terrainCellMaxHeights = $derived.by(() => {
339
- const result: number[] = new Array($cells.length).fill(-Infinity);
465
+ const result: number[] = new Array($cells.length).fill(0);
340
466
  if (!terrain) return result;
341
- const positions = terrain.positions;
467
+ const heights = terrain.heights;
342
468
  const cellIndices = terrain.cellIndices;
343
469
  for (let i = 0; i < cellIndices.length; i++) {
344
470
  const ci = cellIndices[i];
345
- const h = positions[i * 3 + 1];
471
+ const h = heights[i];
346
472
  if (h > result[ci]) result[ci] = h;
347
473
  }
348
474
  return result;
349
475
  });
350
476
  const cellLabelAnchors = $derived(
351
477
  $cells.map((cell, idx) => {
352
- const vs = cell.vertices;
353
- if (vs.length === 0) return { x: 0, y: 0, z: 0 };
354
- let sx = 0;
355
- let sz = 0;
356
- let maxH = -Infinity;
357
- for (const [vx, vy, vh] of vs) {
358
- sx += vx;
359
- sz += vy;
360
- if (vh > maxH) maxH = vh;
361
- }
362
- const terrainMax = terrainCellMaxHeights[idx];
363
- 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;
364
481
  return {
365
- x: sx / vs.length,
366
- y: maxH + cellRadius * LABEL_LIFT_FACTOR,
367
- z: sz / vs.length,
482
+ x: cxv + nx * lift,
483
+ y: cyv + ny * lift,
484
+ z: czv + nz * lift,
368
485
  };
369
486
  }),
370
487
  );
@@ -445,15 +562,39 @@
445
562
  gameState.queueExplorePulse(cellIndex, event.point.x, event.point.y, event.point.z);
446
563
  onCellClicked?.(cellIndex);
447
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
+ );
448
588
  </script>
449
589
 
590
+ <T is={opaqueMesh} />
450
591
  <T is={terrainMesh} onclick={handleTerrainClick} />
451
592
 
452
593
  {#each $cellMetadata as entry, i (i)}
453
594
  {#if entry.isExplored && !entry.isVoid && entry.voidNeighborCount > 0}
454
595
  {@const anchor = cellLabelAnchors[i]}
455
596
  {#if anchor}
456
- <Billboard position={[anchor.x, anchor.y, anchor.z]}>
597
+ <IdleBillboard position={[anchor.x, anchor.y, anchor.z]}>
457
598
  <Text
458
599
  text={entry.voidNeighborCount.toLocaleString(getLocale())}
459
600
  font={openSans}
@@ -464,7 +605,7 @@
464
605
  outlineWidth={cellRadius * 0.04}
465
606
  outlineColor="#f8fafc"
466
607
  />
467
- </Billboard>
608
+ </IdleBillboard>
468
609
  {/if}
469
610
  {/if}
470
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
+ }