@kuncat/avoidant 0.1.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.
@@ -0,0 +1,6 @@
1
+ type AvoidantGameProps = {
2
+ relayServers?: string[];
3
+ };
4
+ declare const AvoidantGame: import("svelte").Component<AvoidantGameProps, {}, "">;
5
+ type AvoidantGame = ReturnType<typeof AvoidantGame>;
6
+ export default AvoidantGame;
@@ -0,0 +1,448 @@
1
+ <script module lang="ts">
2
+ import _vertexShader from "./vertex.glsl?raw";
3
+ import _fragmentShader from "./fragment.glsl?raw";
4
+ import { MAP_AREA, PULSE_SWEEP_BAND } from "../generated/shared-constants";
5
+ import openSans from "../assets/OpenSans-VariableFont_wdth,wght.ttf?url";
6
+ import { getLocale } from "../paraglide/runtime";
7
+
8
+ export const MAX_PULSES = 16;
9
+ export const VOID_FALL_DURATION_MS = 900;
10
+ export const VOID_FALL_DISTANCE = 8;
11
+
12
+ /**
13
+ * Byte offsets within each RGBA8 texel of the per-cell metadata texture.
14
+ *
15
+ * The GLSL side sees these as `#define CELL_META_*` constants (see {@link cellMetaDefines}).
16
+ */
17
+ export const CellMetaChannel = {
18
+ Explored: 0,
19
+ Void: 1,
20
+ // 0..255 fall-out progress for explored void cells; 0 = on the map, 255 = fully gone.
21
+ FallProgress: 2,
22
+ // 255 while a chord auto-reveal pulse is sweeping the cell. The shader uses this to render the pulse-sweep gradient (same effect as the clicked cell).
23
+ Revealing: 3,
24
+ } as const;
25
+
26
+ /**
27
+ * GLSL `#define` block exposing {@link CellMetaChannel} offsets to shaders.
28
+ */
29
+ export const cellMetaDefines = Object.entries(CellMetaChannel)
30
+ .map(([name, offset]) => {
31
+ const screamingSnakeName = name.replace(/([a-z0-9])([A-Z])/g, "$1_$2").toUpperCase();
32
+ return `#define CELL_META_${screamingSnakeName} ${offset}\n`;
33
+ })
34
+ .join("");
35
+
36
+ const fallDefines = `#define VOID_FALL_DISTANCE ${VOID_FALL_DISTANCE.toFixed(1)}\n`;
37
+
38
+ export const vertexShader = cellMetaDefines + fallDefines + _vertexShader;
39
+ export const fragmentShader =
40
+ `#define MAX_PULSES ${MAX_PULSES}\n` +
41
+ `#define SWEEP_BAND ${PULSE_SWEEP_BAND.toFixed(6)}\n` +
42
+ cellMetaDefines +
43
+ _fragmentShader;
44
+ </script>
45
+
46
+ <script lang="ts">
47
+ import { onMount } from "svelte";
48
+ import { SvelteMap, SvelteSet } from "svelte/reactivity";
49
+ import { Pulse } from "../wasm/avoidant_wasm";
50
+ import type { GameState } from "../wasm/avoidant_wasm";
51
+ import { T, useThrelte } from "@threlte/core";
52
+ import { interactivity, Text, Billboard } from "@threlte/extras";
53
+ import {
54
+ BufferAttribute,
55
+ BufferGeometry,
56
+ DataTexture,
57
+ DoubleSide,
58
+ Mesh,
59
+ NearestFilter,
60
+ RGBAFormat,
61
+ ShaderMaterial,
62
+ UnsignedByteType,
63
+ Vector3,
64
+ } from "three";
65
+
66
+ interactivity();
67
+
68
+ const { invalidate } = useThrelte();
69
+
70
+ interface Props {
71
+ gameState: GameState;
72
+ terrain?: { positions: number[]; normals: number[]; cellIndices: number[] } | undefined;
73
+ }
74
+
75
+ let { gameState = $bindable(), terrain = undefined }: Props = $props();
76
+ let cells = $derived(gameState?.cells);
77
+ let cellMetadata = $derived(gameState?.cellMetadata);
78
+ let pulses = $derived(gameState?.uiState?.pulses);
79
+ let nowMs = $state(0);
80
+
81
+ onMount(() => {
82
+ let rafId = 0;
83
+ const tick = () => {
84
+ const now = performance.now();
85
+ const hasActivePulses = $pulses.some((p) => now - p.createdAtMs < Math.max(1, p.durationMs));
86
+ const hasFallingCells = fallStart.size > 0;
87
+ if (hasActivePulses || hasFallingCells) {
88
+ nowMs = now;
89
+
90
+ if (hasFallingCells) {
91
+ const meta = cellMeta;
92
+ for (const [cellIndex, startMs] of fallStart) {
93
+ const progress = Math.min(1, (now - startMs) / VOID_FALL_DURATION_MS);
94
+ meta.setFallProgress(cellIndex, progress);
95
+ if (progress >= 1) {
96
+ fallStart.delete(cellIndex);
97
+ fellCells.add(cellIndex);
98
+ }
99
+ }
100
+ meta.flush();
101
+ }
102
+
103
+ // Invalidate when remote state changes to draw a new frame.
104
+ invalidate();
105
+ }
106
+ rafId = requestAnimationFrame(tick);
107
+ };
108
+ rafId = requestAnimationFrame(tick);
109
+ return () => cancelAnimationFrame(rafId);
110
+ });
111
+
112
+ /**
113
+ * Build a merged triangle mesh for all cell interiors from a Rust-side subdivided terrain payload.
114
+ *
115
+ * 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}.
116
+ *
117
+ * 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.
118
+ *
119
+ * @param payload - Pre-built positions (`[x, height, y]`-packed) and
120
+ * per-vertex cell indices produced by the mapgen worker. `undefined`
121
+ * yields an empty geometry, which is the expected state before mapgen
122
+ * completes.
123
+ * @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.
124
+ * @returns A `BufferGeometry` with `position`, `aNormal`, and `aCellIndex` attributes.
125
+ */
126
+ function buildTerrainLayer(
127
+ payload: { positions: number[]; normals: number[]; cellIndices: number[] } | undefined,
128
+ insetDistance = 0,
129
+ ): BufferGeometry {
130
+ const geometry = new BufferGeometry();
131
+ if (!payload || payload.positions.length === 0) {
132
+ geometry.setAttribute("position", new BufferAttribute(new Float32Array(0), 3));
133
+ geometry.setAttribute("aNormal", new BufferAttribute(new Float32Array(0), 3));
134
+ geometry.setAttribute("aCellIndex", new BufferAttribute(new Float32Array(0), 1));
135
+ return geometry;
136
+ }
137
+
138
+ const positions = new Float32Array(payload.positions);
139
+ if (insetDistance > 0) {
140
+ const cellIndices = payload.cellIndices;
141
+ const vertexCount = cellIndices.length;
142
+ let maxCell = 0;
143
+ for (let i = 0; i < vertexCount; i++) {
144
+ if (cellIndices[i] > maxCell) maxCell = cellIndices[i];
145
+ }
146
+ const cellCount = maxCell + 1;
147
+ const sumX = new Float64Array(cellCount);
148
+ const sumZ = new Float64Array(cellCount);
149
+ const count = new Uint32Array(cellCount);
150
+ for (let i = 0; i < vertexCount; i++) {
151
+ const c = cellIndices[i];
152
+ sumX[c] += positions[i * 3 + 0];
153
+ sumZ[c] += positions[i * 3 + 2];
154
+ count[c]++;
155
+ }
156
+ const cx = new Float32Array(cellCount);
157
+ const cz = new Float32Array(cellCount);
158
+ for (let c = 0; c < cellCount; c++) {
159
+ if (count[c] > 0) {
160
+ cx[c] = sumX[c] / count[c];
161
+ cz[c] = sumZ[c] / count[c];
162
+ }
163
+ }
164
+ for (let i = 0; i < vertexCount; i++) {
165
+ const c = cellIndices[i];
166
+ const dx = positions[i * 3 + 0] - cx[c];
167
+ const dz = positions[i * 3 + 2] - cz[c];
168
+ const d = Math.hypot(dx, dz);
169
+ if (d < 1e-6) continue;
170
+ const move = Math.min(insetDistance, d);
171
+ const k = move / d;
172
+ positions[i * 3 + 0] -= dx * k;
173
+ positions[i * 3 + 2] -= dz * k;
174
+ }
175
+ }
176
+
177
+ geometry.setAttribute("position", new BufferAttribute(positions, 3));
178
+ geometry.setAttribute("aNormal", new BufferAttribute(new Float32Array(payload.normals), 3));
179
+ geometry.setAttribute(
180
+ "aCellIndex",
181
+ new BufferAttribute(new Float32Array(payload.cellIndices), 1),
182
+ );
183
+ return geometry;
184
+ }
185
+
186
+ /**
187
+ * One RGBA8 `DataTexture` of size N×1 holding per-cell metadata.
188
+ *
189
+ * Texel `i` stores the metadata for cell `i`; shaders sample it using `aCellIndex` as the U coordinate, which lets a single byte cover all of a cell's vertices across the terrain and ribbon layers without per-vertex metadata attributes.
190
+ */
191
+ class CellMetaTexture {
192
+ /** Underlying Three.js texture to be bound to shader uniforms. */
193
+ readonly texture: DataTexture;
194
+ /** Backing byte buffer aliased by {@link texture}. Layout: 4 bytes per cell. */
195
+ private readonly data: Uint8Array;
196
+ /** Number of texels/cells. */
197
+ readonly width: number;
198
+
199
+ /**
200
+ * Allocate a cell metadata texture.
201
+ */
202
+ constructor(cellCount: number) {
203
+ // Enforce a minimum width of 1 so the texture is always in a valid GPU-bindable state.
204
+ this.width = Math.max(1, cellCount);
205
+ this.data = new Uint8Array(this.width * 4);
206
+ this.texture = new DataTexture(this.data, this.width, 1, RGBAFormat, UnsignedByteType);
207
+ this.texture.minFilter = NearestFilter;
208
+ this.texture.magFilter = NearestFilter;
209
+ this.texture.generateMipmaps = false;
210
+ this.texture.needsUpdate = true;
211
+ }
212
+
213
+ /**
214
+ * Mark cell `cellIndex` as explored or unexplored.
215
+ *
216
+ * Call {@link flush} once after a batch of updates to schedule the GPU upload.
217
+ */
218
+ setExplored(cellIndex: number, value: boolean): void {
219
+ this.data[cellIndex * 4 + CellMetaChannel.Explored] = value ? 255 : 0;
220
+ }
221
+
222
+ /**
223
+ * Mark cell `cellIndex` as void (renders as a hole) or solid.
224
+ *
225
+ * Call {@link flush} once after a batch of updates to schedule the GPU upload.
226
+ */
227
+ setVoid(cellIndex: number, value: boolean): void {
228
+ this.data[cellIndex * 4 + CellMetaChannel.Void] = value ? 255 : 0;
229
+ }
230
+
231
+ /**
232
+ * Write the falling progress for an explored void cell.
233
+ *
234
+ * @param progress - Normalized fall progress in `[0, 1]`.
235
+ */
236
+ setFallProgress(cellIndex: number, progress: number): void {
237
+ const byte = Math.max(0, Math.min(255, Math.round(progress * 255)));
238
+ this.data[cellIndex * 4 + CellMetaChannel.FallProgress] = byte;
239
+ }
240
+
241
+ /**
242
+ * Mark cell `cellIndex` as currently being revealed by a chord pulse.
243
+ */
244
+ setRevealing(cellIndex: number, value: boolean): void {
245
+ this.data[cellIndex * 4 + CellMetaChannel.Revealing] = value ? 255 : 0;
246
+ }
247
+
248
+ /** Mark the texture dirty so Three.js re-uploads it on the next frame. */
249
+ flush(): void {
250
+ this.texture.needsUpdate = true;
251
+ }
252
+
253
+ /** Release the underlying GPU resources. */
254
+ dispose(): void {
255
+ this.texture.dispose();
256
+ }
257
+ }
258
+
259
+ // 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.
260
+ const CELL_GAP_HALF_WIDTH = 0.08;
261
+ const cellRadius = $derived(Math.sqrt(MAP_AREA / (Math.PI * Math.max(1, $cells.length))));
262
+ const terrainGeometry = $derived(buildTerrainLayer(terrain, CELL_GAP_HALF_WIDTH));
263
+ const cellMeta = $derived(new CellMetaTexture($cells.length));
264
+
265
+ let fallStart = new SvelteMap<number, number>();
266
+ let fellCells = new SvelteSet<number>();
267
+ $effect(() => {
268
+ // Reset every time a fresh metadata texture is built.
269
+ void cellMeta;
270
+ fallStart = new SvelteMap<number, number>();
271
+ fellCells = new SvelteSet<number>();
272
+ });
273
+
274
+ // Dispose old GPU buffers when geometry / metadata texture is rebuilt.
275
+ $effect(() => {
276
+ const layer = terrainGeometry;
277
+ const meta = cellMeta;
278
+ return () => {
279
+ layer.dispose();
280
+ meta.dispose();
281
+ };
282
+ });
283
+
284
+ let terrainMaterial = $derived(
285
+ new ShaderMaterial({
286
+ vertexShader,
287
+ fragmentShader,
288
+ side: DoubleSide,
289
+ transparent: true,
290
+ uniforms: {
291
+ elevationMin: { value: gameState.elevationMin },
292
+ elevationMax: { value: gameState.elevationMax },
293
+ uCellMeta: { value: cellMeta.texture },
294
+ uCellMetaSize: { value: cellMeta.width },
295
+ uLightDir: { value: new Vector3(0.45, 1.0, 0.3).normalize() },
296
+ uAmbient: { value: 0.55 },
297
+ uDiffuse: { value: 0.75 },
298
+ pulseCount: { value: 0 },
299
+ pulseTimers: { value: new Array(MAX_PULSES).fill(0) },
300
+ pulsePositions: {
301
+ value: new Array(MAX_PULSES).fill(null).map(() => new Vector3()),
302
+ },
303
+ pulseOriginCells: { value: new Array(MAX_PULSES).fill(-1) },
304
+ pulseIsRemote: { value: new Array(MAX_PULSES).fill(0) },
305
+ pulseMaxRadii: { value: new Array(MAX_PULSES).fill(0) },
306
+ },
307
+ }),
308
+ );
309
+
310
+ // Dispose materials when re-derived.
311
+ $effect(() => {
312
+ const material = terrainMaterial;
313
+ return () => {
314
+ material.dispose();
315
+ };
316
+ });
317
+
318
+ let terrainMesh = $derived(new Mesh(terrainGeometry, terrainMaterial));
319
+
320
+ const LABEL_LIFT_FACTOR = 0.075;
321
+ const terrainCellMaxHeights = $derived.by(() => {
322
+ const result: number[] = new Array($cells.length).fill(-Infinity);
323
+ if (!terrain) return result;
324
+ const positions = terrain.positions;
325
+ const cellIndices = terrain.cellIndices;
326
+ for (let i = 0; i < cellIndices.length; i++) {
327
+ const ci = cellIndices[i];
328
+ const h = positions[i * 3 + 1];
329
+ if (h > result[ci]) result[ci] = h;
330
+ }
331
+ return result;
332
+ });
333
+ const cellLabelAnchors = $derived(
334
+ $cells.map((cell, idx) => {
335
+ const vs = cell.vertices;
336
+ if (vs.length === 0) return { x: 0, y: 0, z: 0 };
337
+ let sx = 0;
338
+ let sz = 0;
339
+ let maxH = -Infinity;
340
+ for (const [vx, vy, vh] of vs) {
341
+ sx += vx;
342
+ sz += vy;
343
+ if (vh > maxH) maxH = vh;
344
+ }
345
+ const terrainMax = terrainCellMaxHeights[idx];
346
+ if (terrainMax !== undefined && terrainMax > maxH) maxH = terrainMax;
347
+ return {
348
+ x: sx / vs.length,
349
+ y: maxH + cellRadius * LABEL_LIFT_FACTOR,
350
+ z: sz / vs.length,
351
+ };
352
+ }),
353
+ );
354
+
355
+ const LABEL_COLORS = [
356
+ undefined,
357
+ "#1d4ed8",
358
+ "#15803d",
359
+ "#b91c1c",
360
+ "#1e3a8a",
361
+ "#7c2d12",
362
+ "#0e7490",
363
+ "#111827",
364
+ "#374151",
365
+ ];
366
+
367
+ // Push cell metadata to the DataTexture used by shaders which sample it using `aCellIndex` so a single byte covers all of a cell's vertices in all three layers.
368
+ $effect(() => {
369
+ if ($cells.length === 0) return;
370
+ if (!$cellMetadata) return;
371
+
372
+ const meta = cellMeta;
373
+ const now = performance.now();
374
+ for (let i = 0; i < $cellMetadata.length; i++) {
375
+ const entry = $cellMetadata[i];
376
+ meta.setExplored(i, entry.isExplored);
377
+ meta.setVoid(i, entry.isVoid);
378
+ meta.setRevealing(i, entry.isRevealing);
379
+ // Initiate the fall animation the first time we see a void cell as explored. `fellCells` records cells that have already completed their fall so subsequent re-runs of this effect (e.g. unrelated metadata changes) don't restart the animation.
380
+ if (entry.isExplored && entry.isVoid && !fallStart.has(i) && !fellCells.has(i)) {
381
+ fallStart.set(i, now);
382
+ }
383
+ }
384
+ meta.flush();
385
+ invalidate();
386
+ });
387
+
388
+ const pulsesArray = $derived(
389
+ Array.from($pulses)
390
+ .reverse()
391
+ .slice(0, MAX_PULSES)
392
+ .concat(Array(Math.max(0, MAX_PULSES - $pulses.length)).fill(Pulse.nullPulse())),
393
+ );
394
+ let pulseTimersUniform = $derived(
395
+ pulsesArray.map((p) => {
396
+ if (p.id < 0) return 0;
397
+ const elapsed = Math.max(0, nowMs - p.createdAtMs);
398
+ const duration = Math.max(1, p.durationMs);
399
+ return Math.min(1, elapsed / duration);
400
+ }),
401
+ );
402
+ let pulsePositionsUniform = $derived(
403
+ pulsesArray.map((p) => new Vector3(p.position[0], p.position[1], p.position[2])),
404
+ );
405
+ let pulseOriginCellsUniform = $derived(pulsesArray.map((p) => p.originCell));
406
+ let pulseIsRemoteUniform = $derived(pulsesArray.map((p) => (p.isRemote ? 1 : 0)));
407
+ let pulseMaxRadiiUniform = $derived(pulsesArray.map((p) => p.maxRadius));
408
+
409
+ $effect(() => {
410
+ terrainMaterial.uniforms.pulseCount.value = Math.min($pulses.length, MAX_PULSES);
411
+ terrainMaterial.uniforms.pulseTimers.value = pulseTimersUniform;
412
+ terrainMaterial.uniforms.pulsePositions.value = pulsePositionsUniform;
413
+ terrainMaterial.uniforms.pulseOriginCells.value = pulseOriginCellsUniform;
414
+ terrainMaterial.uniforms.pulseIsRemote.value = pulseIsRemoteUniform;
415
+ terrainMaterial.uniforms.pulseMaxRadii.value = pulseMaxRadiiUniform;
416
+ invalidate();
417
+ });
418
+
419
+ function handleTerrainClick(event: { point: Vector3; face: { a: number } | null }) {
420
+ if (!event.face || $cells.length === 0) return;
421
+ const aCellIndexArr = terrainGeometry.attributes.aCellIndex.array as Float32Array;
422
+ const cellIndex = aCellIndexArr[event.face.a];
423
+ if (cellIndex === undefined) return;
424
+ gameState.queueExplorePulse(cellIndex, event.point.x, event.point.y, event.point.z);
425
+ }
426
+ </script>
427
+
428
+ <T is={terrainMesh} onclick={handleTerrainClick} />
429
+
430
+ {#each $cellMetadata as entry, i (i)}
431
+ {#if entry.isExplored && !entry.isVoid && entry.voidNeighborCount > 0}
432
+ {@const anchor = cellLabelAnchors[i]}
433
+ {#if anchor}
434
+ <Billboard position={[anchor.x, anchor.y, anchor.z]}>
435
+ <Text
436
+ text={entry.voidNeighborCount.toLocaleString(getLocale())}
437
+ font={openSans}
438
+ fontSize={cellRadius * 0.7}
439
+ color={LABEL_COLORS[Math.min(entry.voidNeighborCount, LABEL_COLORS.length - 1)]}
440
+ anchorX="center"
441
+ anchorY="middle"
442
+ outlineWidth={cellRadius * 0.04}
443
+ outlineColor="#f8fafc"
444
+ />
445
+ </Billboard>
446
+ {/if}
447
+ {/if}
448
+ {/each}
@@ -0,0 +1,32 @@
1
+ export declare const MAX_PULSES = 16;
2
+ export declare const VOID_FALL_DURATION_MS = 900;
3
+ export declare const VOID_FALL_DISTANCE = 8;
4
+ /**
5
+ * Byte offsets within each RGBA8 texel of the per-cell metadata texture.
6
+ *
7
+ * The GLSL side sees these as `#define CELL_META_*` constants (see {@link cellMetaDefines}).
8
+ */
9
+ export declare const CellMetaChannel: {
10
+ readonly Explored: 0;
11
+ readonly Void: 1;
12
+ readonly FallProgress: 2;
13
+ readonly Revealing: 3;
14
+ };
15
+ /**
16
+ * GLSL `#define` block exposing {@link CellMetaChannel} offsets to shaders.
17
+ */
18
+ export declare const cellMetaDefines: string;
19
+ export declare const vertexShader: string;
20
+ export declare const fragmentShader: string;
21
+ import type { GameState } from "../wasm/avoidant_wasm";
22
+ interface Props {
23
+ gameState: GameState;
24
+ terrain?: {
25
+ positions: number[];
26
+ normals: number[];
27
+ cellIndices: number[];
28
+ } | undefined;
29
+ }
30
+ declare const Board: import("svelte").Component<Props, {}, "gameState">;
31
+ type Board = ReturnType<typeof Board>;
32
+ export default Board;
@@ -0,0 +1,98 @@
1
+ varying vec3 vWorldPosition;
2
+ varying vec3 vNormal;
3
+ varying float vHeight;
4
+ varying float vCellIndex;
5
+ varying float vFallProgress;
6
+
7
+ uniform float elevationMin;
8
+ uniform float elevationMax;
9
+ uniform sampler2D uCellMeta;
10
+ uniform float uCellMetaSize;
11
+ uniform int pulseCount;
12
+ uniform float pulseTimers[MAX_PULSES];
13
+ uniform vec3 pulsePositions[MAX_PULSES];
14
+ uniform float pulseOriginCells[MAX_PULSES];
15
+ uniform float pulseIsRemote[MAX_PULSES];
16
+ uniform float pulseMaxRadii[MAX_PULSES];
17
+ uniform vec3 uLightDir;
18
+ uniform float uAmbient;
19
+ uniform float uDiffuse;
20
+
21
+ float remapClamped(float value, float inMin, float inMax, float outMin, float outMax) {
22
+ float t = clamp((value - inMin) / (inMax - inMin), 0.0, 1.0);
23
+ return mix(outMin, outMax, t);
24
+ }
25
+
26
+ void main() {
27
+ vec2 metaUv = vec2((vCellIndex + 0.5) / uCellMetaSize, 0.5);
28
+ vec4 meta = texture2D(uCellMeta, metaUv);
29
+ float isVoid = meta[CELL_META_VOID];
30
+ float isExplored = meta[CELL_META_EXPLORED];
31
+ float isRevealing = meta[CELL_META_REVEALING];
32
+ // Once an explored void cell has fully fallen, drop every fragment.
33
+ if (isVoid > 0.5 && isExplored > 0.5 && vFallProgress >= 0.999) discard;
34
+
35
+ float elevation = remapClamped(vHeight, elevationMin, elevationMax, 0.0, 1.0);
36
+
37
+ float totalRing = 0.0;
38
+ float remoteRing = 0.0;
39
+ float totalSweep = 0.0;
40
+
41
+ for (int i = 0; i < MAX_PULSES; i++) {
42
+ if (i >= pulseCount) break;
43
+
44
+ float pulseProgress = clamp(pulseTimers[i], 0.0, 1.0);
45
+ float pulseActive = step(0.0001, pulseProgress) * (1.0 - step(0.9999, pulseProgress));
46
+ float maxRadius = pulseMaxRadii[i];
47
+ float ringRadius = pulseProgress * maxRadius;
48
+ float ringWidth = 1.2;
49
+ float distToOrigin = distance(vWorldPosition.xz, pulsePositions[i].xz);
50
+ float ringDistance = abs(distToOrigin - ringRadius);
51
+ float ring = (1.0 - smoothstep(ringWidth, ringWidth + 0.8, ringDistance)) * pulseActive;
52
+ float pulseFade = 1.0 - pulseProgress;
53
+
54
+ float ringContribution = ring * pulseFade;
55
+ totalRing = max(totalRing, ringContribution);
56
+ float isRemote = step(0.5, pulseIsRemote[i]);
57
+ remoteRing = max(remoteRing, ringContribution * isRemote);
58
+
59
+ float normalizedDist = distToOrigin / maxRadius;
60
+ float pulseSweep =
61
+ 1.0 - smoothstep(pulseProgress - SWEEP_BAND, pulseProgress + SWEEP_BAND, normalizedDist);
62
+ totalSweep = max(totalSweep, pulseSweep);
63
+ }
64
+
65
+ // Revealing cells (the clicked cell and every chord-revealed neighbor) show the radial sweep gradient instead of the unexplored color until the pulse finishes and `isExplored` flips to true.
66
+ float colorFactor = mix(isExplored, totalSweep, isRevealing);
67
+
68
+ vec3 unexploredLow = vec3(0.2588, 0.2588, 0.2784);
69
+ vec3 unexploredHigh = vec3(0.4431, 0.451, 0.4706);
70
+ vec3 exploredLow = vec3(0.6588, 0.7098, 0.7922);
71
+ vec3 exploredHigh = vec3(0.6784, 0.7137, 0.7451);
72
+
73
+ vec3 lowColor = mix(unexploredLow, exploredLow, colorFactor);
74
+ vec3 highColor = mix(unexploredHigh, exploredHigh, colorFactor);
75
+ vec3 terrainColor = mix(lowColor, highColor, elevation);
76
+
77
+ // Smooth hillshading
78
+ vec3 shadingNormal = normalize(vNormal);
79
+ if (shadingNormal.y < 0.0) shadingNormal = -shadingNormal;
80
+ float ndotl = max(dot(shadingNormal, normalize(uLightDir)), 0.0);
81
+ float shade = clamp(uAmbient + uDiffuse * ndotl, 0.0, 1.5);
82
+ terrainColor *= shade;
83
+
84
+ vec3 localPulseTint = vec3(0.55, 0.95, 1.0);
85
+ vec3 remotePulseTint = vec3(1.0, 0.42, 0.38);
86
+ float remoteFactor =
87
+ step(0.0001, totalRing) * clamp(remoteRing / (totalRing + 0.00001), 0.0, 1.0);
88
+ vec3 pulseTint = mix(localPulseTint, remotePulseTint, remoteFactor);
89
+ vec3 finalColor = mix(terrainColor, pulseTint, totalRing * 0.85);
90
+
91
+ float alpha = isExplored > 0.5 ? 1.0 : 0.25;
92
+ // Fade alpha while an explored void cell is falling.
93
+ if (isVoid > 0.5 && isExplored > 0.5) {
94
+ alpha = clamp(1.0 - vFallProgress, 0.0, 1.0);
95
+ }
96
+
97
+ gl_FragColor = vec4(clamp(finalColor, 0.0, 1.0), alpha);
98
+ }
@@ -0,0 +1,31 @@
1
+ attribute float aCellIndex;
2
+ attribute vec3 aNormal;
3
+
4
+ uniform sampler2D uCellMeta;
5
+ uniform float uCellMetaSize;
6
+
7
+ varying vec3 vWorldPosition;
8
+ varying vec3 vNormal;
9
+ varying float vHeight;
10
+ varying float vCellIndex;
11
+ varying float vFallProgress;
12
+
13
+ void main() {
14
+ vec2 metaUv = vec2((aCellIndex + 0.5) / uCellMetaSize, 0.5);
15
+ vec4 meta = texture2D(uCellMeta, metaUv);
16
+ float fallProgress = meta[CELL_META_FALL_PROGRESS];
17
+ vFallProgress = fallProgress;
18
+
19
+ vec3 displaced = position;
20
+ displaced.y -= fallProgress * VOID_FALL_DISTANCE;
21
+
22
+ vec4 worldPosition = modelMatrix * vec4(displaced, 1.0);
23
+ vWorldPosition = worldPosition.xyz;
24
+ // Smooth per-vertex normal. Interpolated across the triangle for Phong-style smooth shading instead of faceted flat shading.
25
+ vNormal = normalize(mat3(modelMatrix) * aNormal);
26
+ // Keep the elevation-based color ramp anchored to the cell's original height so falling cells don't shift colors as they drop.
27
+ vHeight = position.y;
28
+ vCellIndex = aCellIndex;
29
+
30
+ gl_Position = projectionMatrix * viewMatrix * worldPosition;
31
+ }
@@ -0,0 +1,6 @@
1
+ export declare const MAP_WIDTH = 100;
2
+ export declare const MAP_HEIGHT = 100;
3
+ export declare const MAP_AREA: number;
4
+ export declare const PULSE_SWEEP_BAND = 0.12;
5
+ export declare const PULSE_SWEEP_VELOCITY = 0.1;
6
+ export declare const PULSE_MIN_DURATION_MS = 80;
@@ -0,0 +1,9 @@
1
+ // AUTO-GENERATED by crates/game/build.rs from
2
+ // crates/game/src/shared_constants.rs.
3
+ // Edit that file, not this one.
4
+ export const MAP_WIDTH = 100.0;
5
+ export const MAP_HEIGHT = 100.0;
6
+ export const MAP_AREA = MAP_WIDTH * MAP_HEIGHT;
7
+ export const PULSE_SWEEP_BAND = 0.12;
8
+ export const PULSE_SWEEP_VELOCITY = 0.1;
9
+ export const PULSE_MIN_DURATION_MS = 80;
@@ -0,0 +1,2 @@
1
+ export { default as favicon } from "./assets/favicon.svg";
2
+ export { default as AvoidantGame } from "./components/AvoidantGame.svelte";
package/dist/index.js ADDED
@@ -0,0 +1,2 @@
1
+ export { default as favicon } from "./assets/favicon.svg";
2
+ export { default as AvoidantGame } from "./components/AvoidantGame.svelte";