create-threenative 0.2.7 → 0.2.8

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 (154) hide show
  1. package/README.md +3 -1
  2. package/agent-docs/references/capability-reference.md +177 -7
  3. package/capabilities.json +247 -4
  4. package/dist/index.js +6 -1
  5. package/dist/threenative.js +3 -2
  6. package/package.json +4 -4
  7. package/templates/action-rpg/package.json +1 -1
  8. package/templates/minimal/package.json +1 -1
  9. package/templates/platformer/package.json +1 -1
  10. package/templates/puzzle/package.json +1 -1
  11. package/templates/racing/package.json +1 -1
  12. package/templates/rain/.codex/config.toml +19 -0
  13. package/templates/rain/.cursor/mcp.json +32 -0
  14. package/templates/rain/.gemini/settings.json +32 -0
  15. package/templates/rain/.mcp.json +32 -0
  16. package/templates/rain/.vscode/mcp.json +36 -0
  17. package/templates/rain/.zed/settings.json +36 -0
  18. package/templates/rain/AGENTS.md +96 -0
  19. package/templates/rain/CLAUDE.md +98 -0
  20. package/templates/rain/assets/rain-loop.wav +0 -0
  21. package/templates/rain/assets/thunder.wav +0 -0
  22. package/templates/rain/assets/wind-loop.wav +0 -0
  23. package/templates/rain/index.html +18 -0
  24. package/templates/rain/kit.json +7 -0
  25. package/templates/rain/native-playtests/boot.playtest.json +13 -0
  26. package/templates/rain/native-playtests/lightning.playtest.json +173 -0
  27. package/templates/rain/opencode.json +41 -0
  28. package/templates/rain/package.json +56 -0
  29. package/templates/rain/playtests/auto-lightning-clear.playtest.json +66 -0
  30. package/templates/rain/playtests/auto-lightning.playtest.json +26 -0
  31. package/templates/rain/playtests/automation.playtest.json +133 -0
  32. package/templates/rain/playtests/cinematic.playtest.json +59 -0
  33. package/templates/rain/playtests/flash.playtest.json +27 -0
  34. package/templates/rain/playtests/fly.playtest.json +54 -0
  35. package/templates/rain/playtests/lightning.playtest.json +220 -0
  36. package/templates/rain/playtests/loading.playtest.json +57 -0
  37. package/templates/rain/playtests/paused.playtest.json +59 -0
  38. package/templates/rain/playtests/performance.playtest.json +22 -0
  39. package/templates/rain/playtests/reduced-motion.playtest.json +87 -0
  40. package/templates/rain/playtests/simulation.playtest.json +20 -0
  41. package/templates/rain/playtests/storm.playtest.json +150 -0
  42. package/templates/rain/playtests/survives.playtest.json +58 -0
  43. package/templates/rain/playtests/tiers.playtest.json +179 -0
  44. package/templates/rain/playtests/weather.playtest.json +77 -0
  45. package/templates/rain/public/favicon.svg +5 -0
  46. package/templates/rain/src/audio/storm.ts +314 -0
  47. package/templates/rain/src/game.ts +114 -0
  48. package/templates/rain/src/main.ts +15 -0
  49. package/templates/rain/src/render/bloom-shader.ts +65 -0
  50. package/templates/rain/src/render/camera.ts +160 -0
  51. package/templates/rain/src/render/clouds-shader.ts +242 -0
  52. package/templates/rain/src/render/clouds.ts +142 -0
  53. package/templates/rain/src/render/lighting.ts +39 -0
  54. package/templates/rain/src/render/lightning.ts +360 -0
  55. package/templates/rain/src/render/loading.ts +327 -0
  56. package/templates/rain/src/render/materials.ts +19 -0
  57. package/templates/rain/src/render/noise-volume.ts +159 -0
  58. package/templates/rain/src/render/palette.ts +18 -0
  59. package/templates/rain/src/render/post-shader.ts +178 -0
  60. package/templates/rain/src/render/postprocessing.ts +226 -0
  61. package/templates/rain/src/render/quality.ts +135 -0
  62. package/templates/rain/src/render/rain.ts +299 -0
  63. package/templates/rain/src/render/sky.ts +28 -0
  64. package/templates/rain/src/render/world-shader.ts +680 -0
  65. package/templates/rain/src/render/world.ts +146 -0
  66. package/templates/rain/src/render/worldEnvironment.ts +809 -0
  67. package/templates/rain/src/scenes/Boot.ts +334 -0
  68. package/templates/rain/src/state.ts +257 -0
  69. package/templates/rain/src/style.css +1160 -0
  70. package/templates/rain/src/ui/App.tsx +29 -0
  71. package/templates/rain/src/ui/GameUi.tsx +187 -0
  72. package/templates/rain/src/ui/Hud.tsx +327 -0
  73. package/templates/rain/src/ui/LoadingOverlay.tsx +46 -0
  74. package/templates/rain/src/ui/Menu.tsx +370 -0
  75. package/templates/rain/src/ui/automation.ts +60 -0
  76. package/templates/rain/src/ui/main.tsx +7 -0
  77. package/templates/rain/src/ui/tempest.ts +149 -0
  78. package/templates/rain/tailwind.config.ts +2 -0
  79. package/templates/rain/threenative.config.ts +66 -0
  80. package/templates/rain/tools/generate-shaders.mjs +656 -0
  81. package/templates/rain/tools/make-storm-audio.mjs +387 -0
  82. package/templates/rain/tools/storm-dsp.mjs +177 -0
  83. package/templates/rain/tools/tempest-bloom.frag +10 -0
  84. package/templates/rain/tools/tempest-clouds.frag +86 -0
  85. package/templates/rain/tools/tempest-post.frag +47 -0
  86. package/templates/rain/tools/tempest-world.frag +210 -0
  87. package/templates/rain/tools/verify-noise-volume.mjs +61 -0
  88. package/templates/rain/tsconfig.json +17 -0
  89. package/templates/rain/vite.config.ts +37 -0
  90. package/templates/rts/package.json +1 -1
  91. package/templates/runner/package.json +1 -1
  92. package/templates/sailing/package.json +1 -1
  93. package/templates/shooter/package.json +1 -1
  94. package/templates/snow/.codex/config.toml +19 -0
  95. package/templates/snow/.cursor/mcp.json +32 -0
  96. package/templates/snow/.gemini/settings.json +32 -0
  97. package/templates/snow/.mcp.json +32 -0
  98. package/templates/snow/.vscode/mcp.json +36 -0
  99. package/templates/snow/.zed/settings.json +36 -0
  100. package/templates/snow/AGENTS.md +88 -0
  101. package/templates/snow/CLAUDE.md +90 -0
  102. package/templates/snow/README.md +26 -0
  103. package/templates/snow/assets/crunch.wav +0 -0
  104. package/templates/snow/assets/wind.wav +0 -0
  105. package/templates/snow/index.html +12 -0
  106. package/templates/snow/kit.json +7 -0
  107. package/templates/snow/native-playtests/snow-physics.playtest.json +150 -0
  108. package/templates/snow/native-playtests/survives.playtest.json +47 -0
  109. package/templates/snow/opencode.json +41 -0
  110. package/templates/snow/package.json +58 -0
  111. package/templates/snow/playtests/footsteps.playtest.json +95 -0
  112. package/templates/snow/playtests/performance.playtest.json +36 -0
  113. package/templates/snow/playtests/snow-physics.playtest.json +154 -0
  114. package/templates/snow/playtests/survives.playtest.json +56 -0
  115. package/templates/snow/playtests/touch-controls.playtest.json +71 -0
  116. package/templates/snow/playtests/weather.playtest.json +119 -0
  117. package/templates/snow/public/favicon.svg +5 -0
  118. package/templates/snow/src/audio.ts +58 -0
  119. package/templates/snow/src/commands.ts +8 -0
  120. package/templates/snow/src/entities/Explorer.ts +279 -0
  121. package/templates/snow/src/game.ts +69 -0
  122. package/templates/snow/src/main.ts +15 -0
  123. package/templates/snow/src/render/bootPrint.ts +50 -0
  124. package/templates/snow/src/render/camera.ts +84 -0
  125. package/templates/snow/src/render/explorer.ts +321 -0
  126. package/templates/snow/src/render/lighting.ts +50 -0
  127. package/templates/snow/src/render/loading.ts +325 -0
  128. package/templates/snow/src/render/materials.ts +36 -0
  129. package/templates/snow/src/render/palette.ts +17 -0
  130. package/templates/snow/src/render/postprocessing.ts +44 -0
  131. package/templates/snow/src/render/props.ts +42 -0
  132. package/templates/snow/src/render/quality.ts +135 -0
  133. package/templates/snow/src/render/scenery.ts +244 -0
  134. package/templates/snow/src/render/sky.ts +57 -0
  135. package/templates/snow/src/render/snowSurface.ts +259 -0
  136. package/templates/snow/src/render/touch-controls.ts +143 -0
  137. package/templates/snow/src/render/weather.ts +279 -0
  138. package/templates/snow/src/render/worldEnvironment.ts +809 -0
  139. package/templates/snow/src/scenes/Boot.ts +12 -0
  140. package/templates/snow/src/scenes/Snow.ts +635 -0
  141. package/templates/snow/src/state.ts +46 -0
  142. package/templates/snow/src/style.css +143 -0
  143. package/templates/snow/src/terrain.ts +64 -0
  144. package/templates/snow/src/ui/App.tsx +15 -0
  145. package/templates/snow/src/ui/Controls.tsx +322 -0
  146. package/templates/snow/src/ui/GameUi.tsx +354 -0
  147. package/templates/snow/src/ui/icons.tsx +54 -0
  148. package/templates/snow/src/ui/main.tsx +7 -0
  149. package/templates/snow/tailwind.config.ts +2 -0
  150. package/templates/snow/threenative.config.ts +51 -0
  151. package/templates/snow/tsconfig.json +17 -0
  152. package/templates/snow/vite.config.ts +37 -0
  153. package/templates/starter/package.json +1 -1
  154. package/templates/tower-defense/package.json +1 -1
@@ -0,0 +1,259 @@
1
+ // Generated for you. How the snow looks: its colour, the blue in a pressed footprint, the
2
+ // compaction view, the glints. `SnowField` stores numbers; everything a screenshot shows is here.
3
+ import { BufferAttribute, type BufferGeometry, Mesh, PlaneGeometry } from "three";
4
+ import {
5
+ attribute,
6
+ color,
7
+ dot,
8
+ float,
9
+ floor,
10
+ fwidth,
11
+ hash,
12
+ max,
13
+ mix,
14
+ normalView,
15
+ normalWorld,
16
+ positionViewDirection,
17
+ positionWorld,
18
+ pow,
19
+ smoothstep,
20
+ uniform,
21
+ vec3,
22
+ } from "three/tsl";
23
+ import { MeshStandardNodeMaterial } from "three/webgpu";
24
+ import { terrainHeight } from "../terrain.js";
25
+ import { palette } from "./palette.js";
26
+
27
+ /** Per-vertex snow state the material reads: indentation (m) and compaction (0..1). */
28
+ const STATE = "snowState";
29
+ /** A window up to this many samples is redrawn at once; wider ones are sliced. */
30
+ const URGENT_CELLS = 12_000;
31
+ /** A wide window is spread over about this many frames, never fewer than eight rows a frame. */
32
+ const SLICE_FRAMES = 15;
33
+ const SLICE_ROWS = 8;
34
+
35
+ type Bounds = {
36
+ readonly column: number;
37
+ readonly columns: number;
38
+ readonly row: number;
39
+ readonly rows: number;
40
+ };
41
+
42
+ /** The parts of `SnowField` (and its `Heightfield`) this renderer reads, by shape. */
43
+ export interface ISnowSource {
44
+ readonly depth: number;
45
+ readonly field: {
46
+ readonly columns: number;
47
+ readonly rows: number;
48
+ readonly width: number;
49
+ readonly depth: number;
50
+ readonly origin: { readonly x: number; readonly z: number };
51
+ toGeometry(): BufferGeometry;
52
+ refreshGeometry(geometry: BufferGeometry, bounds?: Bounds): void;
53
+ toColliderHeights(): Float32Array;
54
+ };
55
+ takeDirtyRegion(): Bounds | undefined;
56
+ copyChannel(
57
+ channel: "indent" | "compaction",
58
+ bounds: Bounds,
59
+ target?: Float32Array,
60
+ ): Float32Array;
61
+ }
62
+
63
+ function union(current: Bounds | undefined, next: Bounds): Bounds {
64
+ if (current === undefined) return { ...next };
65
+ const column = Math.min(current.column, next.column);
66
+ const row = Math.min(current.row, next.row);
67
+ return {
68
+ column,
69
+ columns: Math.max(current.column + current.columns, next.column + next.columns) - column,
70
+ row,
71
+ rows: Math.max(current.row + current.rows, next.row + next.rows) - row,
72
+ };
73
+ }
74
+
75
+ export interface ISnowSurface {
76
+ readonly mesh: Mesh;
77
+ readonly outskirts: Mesh;
78
+ /**
79
+ * Take what the field wrote since the last call. Small windows — a footprint, a rolling ball —
80
+ * are drawn on the next frame; a window wider than `URGENT_CELLS` (snowfall refilling every
81
+ * track at once) is spread over the following frames a band of rows at a time.
82
+ */
83
+ collect(): void;
84
+ /** Push collected windows into the mesh; call once per drawn frame. */
85
+ refresh(): void;
86
+ /** Rows still waiting to be redrawn from a wide refill. */
87
+ readonly pendingRows: number;
88
+ /**
89
+ * Largest gap between a rendered vertex and the canonical surface, metres, after drawing every
90
+ * window still waiting: what the next frame shows, not a frame caught mid-redraw.
91
+ */
92
+ renderError(): number;
93
+ setCompactionView(on: boolean): void;
94
+ /** 0 clear .. 1 blizzard: dims the glints with the sun. */
95
+ setStorm(storm: number): void;
96
+ }
97
+
98
+ const floatUniform = () => uniform(0);
99
+ type FloatUniform = ReturnType<typeof floatUniform>;
100
+
101
+ function snowMaterial(compactionView: FloatUniform, sun: FloatUniform) {
102
+ const material = new MeshStandardNodeMaterial({ metalness: 0, roughness: 0.86 });
103
+ const state = attribute(STATE, "vec2" as const);
104
+ const indent = state.x;
105
+ const compaction = state.y;
106
+ // The hollow of a print darkens towards a cold blue; fresh powder keeps a faint grain.
107
+ const hollow = smoothstep(0.002, 0.11, indent);
108
+ const grain = hash(floor(positionWorld.xz.mul(1.8)));
109
+ const powder = color(palette.snow).mul(grain.mul(0.035).add(0.965));
110
+ const pressed = mix(powder, color(palette.shadow), hollow.mul(0.55).add(compaction.mul(0.1)));
111
+ // Print walls face away from the light: darken by slope so a footprint reads at a glance.
112
+ const wall = mix(float(0.8), float(1), smoothstep(0.55, 0.95, normalWorld.y));
113
+ const lit = pressed.mul(float(1).sub(hollow.mul(0.22))).mul(wall);
114
+ const debug = mix(vec3(0.22, 0.51, 0.67), vec3(0.95, 0.47, 0.16), compaction);
115
+ material.colorNode = mix(lit, debug, compactionView);
116
+ material.roughnessNode = mix(float(0.88), float(0.57), compaction);
117
+ // Ice crystals: one in a hundred tiny cells glints when it faces the eye. Faded out where a
118
+ // pixel covers several cells, so distant snow does not shimmer.
119
+ const crystal = hash(floor(positionWorld.xz.mul(120)));
120
+ const facing = pow(max(dot(normalView, positionViewDirection.negate()), 0), 12);
121
+ const fade = float(1).sub(smoothstep(0.01, 0.055, fwidth(positionWorld.x)));
122
+ material.emissiveNode = vec3(0.7, 0.85, 1).mul(
123
+ smoothstep(0.99, 1, crystal).mul(facing).mul(fade).mul(sun).mul(0.55),
124
+ );
125
+ return material;
126
+ }
127
+
128
+ export function createSnowSurface(snow: ISnowSource): ISnowSurface {
129
+ const field = snow.field;
130
+ const compactionView = floatUniform();
131
+ const sun = floatUniform();
132
+ sun.value = 1;
133
+ const material = snowMaterial(compactionView, sun);
134
+
135
+ const geometry = field.toGeometry();
136
+ const state = new BufferAttribute(new Float32Array(field.rows * field.columns * 2), 2);
137
+ geometry.setAttribute(STATE, state);
138
+ const mesh = new Mesh(geometry, material);
139
+ mesh.position.set(field.origin.x, 0, field.origin.z);
140
+ mesh.receiveShadow = true;
141
+ mesh.name = "snow";
142
+
143
+ // Beyond the playable field the ground keeps going under fresh, untouched snow. Inside the
144
+ // field it ducks under the deformable surface, so the seam at the edge never shows.
145
+ const outskirtsGeometry = new PlaneGeometry(340, 340, 110, 110);
146
+ outskirtsGeometry.rotateX(-Math.PI / 2);
147
+ const ring = outskirtsGeometry.getAttribute("position");
148
+ const half = field.width / 2;
149
+ for (let index = 0; index < ring.count; index += 1) {
150
+ const x = ring.getX(index);
151
+ const z = ring.getZ(index);
152
+ const edge = Math.max(Math.abs(x), Math.abs(z));
153
+ const inside = 1 - Math.min(1, Math.max(0, (edge - (half - 1.5)) / 1.4));
154
+ ring.setY(index, terrainHeight(x, z) + snow.depth - 0.72 * inside - 0.015);
155
+ }
156
+ outskirtsGeometry.computeVertexNormals();
157
+ outskirtsGeometry.setAttribute(STATE, new BufferAttribute(new Float32Array(ring.count * 2), 2));
158
+ const outskirts = new Mesh(outskirtsGeometry, material);
159
+ outskirts.receiveShadow = true;
160
+
161
+ let indents: Float32Array = new Float32Array(0);
162
+ let compactions: Float32Array = new Float32Array(0);
163
+ const writeState = (bounds: Bounds): void => {
164
+ indents = snow.copyChannel("indent", bounds, indents);
165
+ compactions = snow.copyChannel("compaction", bounds, compactions);
166
+ const values = state.array as Float32Array;
167
+ for (let row = 0; row < bounds.rows; row += 1) {
168
+ for (let column = 0; column < bounds.columns; column += 1) {
169
+ const cell = row * bounds.columns + column;
170
+ const vertex = (bounds.row + row) * field.columns + bounds.column + column;
171
+ values[vertex * 2] = indents[cell] as number;
172
+ values[vertex * 2 + 1] = compactions[cell] as number;
173
+ }
174
+ }
175
+ state.needsUpdate = true;
176
+ };
177
+
178
+ let urgent: Bounds | undefined;
179
+ let background: Bounds | undefined;
180
+ // `toGeometry` already drew the field as it stands; the field's own first full write is not news.
181
+ snow.takeDirtyRegion();
182
+ const redraw = (written: Bounds): void => {
183
+ // A normal reads its neighbours, so one sample beyond the written window moves too.
184
+ const column = Math.max(0, written.column - 1);
185
+ const row = Math.max(0, written.row - 1);
186
+ const bounds = {
187
+ column,
188
+ columns: Math.min(field.columns, written.column + written.columns + 1) - column,
189
+ row,
190
+ rows: Math.min(field.rows, written.row + written.rows + 1) - row,
191
+ };
192
+ field.refreshGeometry(geometry, bounds);
193
+ writeState(bounds);
194
+ // Upload only the rows that moved: a whole-field upload every frame is megabytes per frame.
195
+ const first = bounds.row * field.columns;
196
+ const count = bounds.rows * field.columns;
197
+ for (const name of ["position", "normal", STATE]) {
198
+ const attribute = geometry.getAttribute(name) as BufferAttribute;
199
+ attribute.addUpdateRange(first * attribute.itemSize, count * attribute.itemSize);
200
+ }
201
+ };
202
+ const collect = (): void => {
203
+ const written = snow.takeDirtyRegion();
204
+ if (written === undefined) return;
205
+ if (written.columns * written.rows <= URGENT_CELLS) urgent = union(urgent, written);
206
+ else background = union(background, written);
207
+ };
208
+
209
+ return {
210
+ collect,
211
+ mesh,
212
+ outskirts,
213
+ get pendingRows() {
214
+ return background?.rows ?? 0;
215
+ },
216
+ refresh() {
217
+ collect();
218
+ if (urgent !== undefined) redraw(urgent);
219
+ urgent = undefined;
220
+ if (background === undefined) return;
221
+ // Proportional to what is waiting, so a refill always finishes before the next one lands.
222
+ const rows = Math.min(
223
+ background.rows,
224
+ Math.max(SLICE_ROWS, Math.ceil(background.rows / SLICE_FRAMES)),
225
+ );
226
+ redraw({ ...background, rows });
227
+ background =
228
+ rows === background.rows
229
+ ? undefined
230
+ : { ...background, row: background.row + rows, rows: background.rows - rows };
231
+ },
232
+ renderError() {
233
+ collect();
234
+ if (urgent !== undefined) redraw(urgent);
235
+ if (background !== undefined) redraw(background);
236
+ urgent = undefined;
237
+ background = undefined;
238
+ const positions = geometry.getAttribute("position");
239
+ const heights = field.toColliderHeights();
240
+ let worst = 0;
241
+ for (let row = 0; row < field.rows; row += 1)
242
+ for (let column = 0; column < field.columns; column += 1)
243
+ worst = Math.max(
244
+ worst,
245
+ Math.abs(
246
+ positions.getY(row * field.columns + column) -
247
+ (heights[column * field.rows + row] as number),
248
+ ),
249
+ );
250
+ return worst;
251
+ },
252
+ setCompactionView(on) {
253
+ compactionView.value = on ? 1 : 0;
254
+ },
255
+ setStorm(storm) {
256
+ sun.value = 1 - storm * 0.85;
257
+ },
258
+ };
259
+ }
@@ -0,0 +1,143 @@
1
+ import {
2
+ CircleGeometry,
3
+ type ColorRepresentation,
4
+ Group,
5
+ MathUtils,
6
+ Mesh,
7
+ MeshBasicMaterial,
8
+ type PerspectiveCamera,
9
+ RingGeometry,
10
+ Vector2,
11
+ } from "three";
12
+ import { palette } from "./palette.js";
13
+
14
+ const MOVE_RADIUS = 72;
15
+ const EDGE = 36;
16
+
17
+ export interface ITouchPointer {
18
+ readonly position: Vector2;
19
+ }
20
+
21
+ export interface ITouchViewport {
22
+ readonly height: number;
23
+ readonly width: number;
24
+ }
25
+
26
+ export interface ITouchInput {
27
+ readonly move: Vector2;
28
+ }
29
+
30
+ function overlayMaterial(color: ColorRepresentation, opacity: number): MeshBasicMaterial {
31
+ return new MeshBasicMaterial({
32
+ color,
33
+ depthTest: false,
34
+ depthWrite: false,
35
+ opacity,
36
+ transparent: true,
37
+ });
38
+ }
39
+
40
+ function ringMesh(radius: number, material: MeshBasicMaterial): Mesh {
41
+ return new Mesh(new RingGeometry(radius - 5, radius, 32), material);
42
+ }
43
+
44
+ function place(mesh: Mesh, point: Vector2): void {
45
+ mesh.position.set(point.x, point.y, 0);
46
+ }
47
+
48
+ function movementPoint(size: ITouchViewport): Vector2 {
49
+ return new Vector2(MOVE_RADIUS + EDGE, size.height - MOVE_RADIUS - EDGE);
50
+ }
51
+
52
+ export class TouchControls {
53
+ readonly root = new Group();
54
+ readonly object = this.root;
55
+ #camera: PerspectiveCamera;
56
+ #input: { move: Vector2 } = { move: new Vector2() };
57
+ #moveAnchor = new Vector2();
58
+ #resting = new Vector2();
59
+ #hasMoveAnchor = false;
60
+ #lastWidth = -1;
61
+ #lastHeight = -1;
62
+ #moveBase: Mesh;
63
+ #moveKnob: Mesh;
64
+ #idleMaterial: MeshBasicMaterial;
65
+ #activeMaterial: MeshBasicMaterial;
66
+
67
+ constructor(camera: PerspectiveCamera) {
68
+ this.#camera = camera;
69
+ // On white snow a faint ring vanishes: a dark stick ring and an accent knob.
70
+ this.#idleMaterial = overlayMaterial(palette.floor, 0.6);
71
+ this.#activeMaterial = overlayMaterial(palette.accent, 0.8);
72
+ this.#moveBase = ringMesh(MOVE_RADIUS, this.#idleMaterial);
73
+ this.#moveKnob = new Mesh(new CircleGeometry(28, 24), this.#activeMaterial);
74
+ this.root.add(this.#moveBase, this.#moveKnob);
75
+ this.root.renderOrder = 10_001;
76
+ camera.add(this.root);
77
+ }
78
+
79
+ update(pointers: ReadonlyMap<number, ITouchPointer>, size: ITouchViewport): ITouchInput {
80
+ this.#ensureLayout(size);
81
+ let movement: ITouchPointer | undefined;
82
+ for (const pointer of pointers.values()) {
83
+ if (pointer.position.x < size.width * 0.5) {
84
+ movement = pointer;
85
+ break;
86
+ }
87
+ }
88
+
89
+ if (movement === undefined) {
90
+ this.#hasMoveAnchor = false;
91
+ this.#input.move.set(0, 0);
92
+ } else {
93
+ if (!this.#hasMoveAnchor) {
94
+ this.#moveAnchor.copy(movement.position);
95
+ this.#hasMoveAnchor = true;
96
+ }
97
+ this.#input.move.set(
98
+ MathUtils.clamp((movement.position.x - this.#moveAnchor.x) / MOVE_RADIUS, -1, 1),
99
+ MathUtils.clamp((this.#moveAnchor.y - movement.position.y) / MOVE_RADIUS, -1, 1),
100
+ );
101
+ }
102
+
103
+ const center = this.#hasMoveAnchor ? this.#moveAnchor : this.#resting;
104
+ place(
105
+ this.#moveKnob,
106
+ new Vector2(
107
+ center.x + this.#input.move.x * MOVE_RADIUS,
108
+ center.y - this.#input.move.y * MOVE_RADIUS,
109
+ ),
110
+ );
111
+ this.#moveKnob.material = this.#hasMoveAnchor ? this.#activeMaterial : this.#idleMaterial;
112
+ this.#layout(size);
113
+ return this.#input;
114
+ }
115
+
116
+ debug(): Record<string, unknown> {
117
+ return { move: this.#input.move.toArray() };
118
+ }
119
+
120
+ dispose(): void {
121
+ this.root.removeFromParent();
122
+ for (const child of this.root.children) {
123
+ if (child instanceof Mesh) child.geometry.dispose();
124
+ }
125
+ this.#idleMaterial.dispose();
126
+ this.#activeMaterial.dispose();
127
+ }
128
+
129
+ #ensureLayout(size: ITouchViewport): void {
130
+ if (size.width === this.#lastWidth && size.height === this.#lastHeight) return;
131
+ this.#lastWidth = size.width;
132
+ this.#lastHeight = size.height;
133
+ this.#resting.copy(movementPoint(size));
134
+ }
135
+
136
+ #layout(size: ITouchViewport): void {
137
+ const worldHeight = 2 * Math.tan(MathUtils.degToRad(this.#camera.fov / 2));
138
+ const pixels = worldHeight / Math.max(1, size.height);
139
+ this.root.position.set(-(size.width * pixels) / 2, worldHeight / 2, -1);
140
+ this.root.scale.set(pixels, -pixels, 1);
141
+ place(this.#moveBase, this.#hasMoveAnchor ? this.#moveAnchor : this.#resting);
142
+ }
143
+ }
@@ -0,0 +1,279 @@
1
+ // Generated for you. Snowfall, the blizzard and the powder a boot kicks up. `GPUParticles3D` (the
2
+ // scene passes it in) owns
3
+ // the buffers, dispatch and lifetime; the flake's shape, colour, size, drift and fall are here.
4
+ import { type Sprite, Vector2 } from "three";
5
+ import {
6
+ Fn,
7
+ atan,
8
+ cameraPosition,
9
+ cos,
10
+ exp,
11
+ float,
12
+ fract,
13
+ hash,
14
+ instanceIndex,
15
+ mod,
16
+ pow,
17
+ sin,
18
+ smoothstep,
19
+ step,
20
+ uniform,
21
+ uv,
22
+ vec2,
23
+ vec3,
24
+ vec4,
25
+ } from "three/tsl";
26
+ import {
27
+ AdditiveBlending,
28
+ type ComputeNode,
29
+ type Node,
30
+ NormalBlending,
31
+ SpriteNodeMaterial,
32
+ type StorageBufferNode,
33
+ } from "three/webgpu";
34
+
35
+ /** Half the width of the box of air around the explorer that flakes fall through, metres. */
36
+ const SPAN = 21;
37
+ const CEILING = 19;
38
+ /** The widest a flake may be drawn, in screen pixels — the study's point-size clamp. */
39
+ const MAX_FLAKE_PIXELS = 24;
40
+ const BURST_PARTICLES = 96;
41
+ const BURST_LIFETIME = 1.05;
42
+
43
+ const random = (salt: number) => hash(instanceIndex.add(salt));
44
+
45
+ /** What a particle mechanism takes: a pool size, a sprite material and two compute passes. */
46
+ export interface IParticleOptions {
47
+ readonly amount: number;
48
+ readonly material: SpriteNodeMaterial;
49
+ readonly start: (buffers: { readonly positions: StorageBufferNode<"vec3"> }) => ComputeNode;
50
+ readonly process: (buffers: { readonly positions: StorageBufferNode<"vec3"> }) => ComputeNode;
51
+ }
52
+
53
+ /** The pooled sprite the scene builds from those options — `GPUParticles3D` in this game. */
54
+ export type ParticleSystem = Sprite & {
55
+ readonly buffers: { readonly positions: StorageBufferNode<"vec3"> };
56
+ };
57
+
58
+ export interface ISnowWeather {
59
+ readonly snowfall: ParticleSystem;
60
+ readonly bursts: readonly ParticleSystem[];
61
+ /** Live wind at the snowfield, m/s, gusts included. */
62
+ readonly wind: number;
63
+ /** 0 clear .. 1 blizzard, eased. */
64
+ readonly storm: number;
65
+ update(
66
+ dt: number,
67
+ centre: { readonly x: number; readonly z: number },
68
+ /** Screen pixels per metre at one metre from the camera: `height / (2 tan(fov / 2))`. */
69
+ pixelScale: number,
70
+ settings: {
71
+ readonly blizzard: boolean;
72
+ readonly snowfall: number;
73
+ readonly fallSpeed: number;
74
+ readonly wind: number;
75
+ },
76
+ ): void;
77
+ /** Kick up powder where a boot landed, deeper prints throwing more. */
78
+ burst(at: { readonly x: number; readonly y: number; readonly z: number }, strength: number): void;
79
+ }
80
+
81
+ const floatUniform = (value: number) => uniform(value);
82
+ type FloatUniform = ReturnType<typeof floatUniform>;
83
+
84
+ /**
85
+ * The flake sprite. `at` is each flake's world position and `pixelScale` the screen's pixels per
86
+ * metre at one metre: a flake is never drawn wider than `MAX_FLAKE_PIXELS`, and fades out right
87
+ * in front of the lens, so the air between the camera and the forest never turns to haze.
88
+ */
89
+ function flakeMaterial(
90
+ storm: FloatUniform,
91
+ visible: FloatUniform,
92
+ at: Node<"vec3">,
93
+ pixelScale: FloatUniform,
94
+ ) {
95
+ const material = new SpriteNodeMaterial({
96
+ blending: NormalBlending,
97
+ depthWrite: false,
98
+ transparent: true,
99
+ });
100
+ // A soft disc with six faint arms, squashed sideways as the storm drives it.
101
+ const p = uv()
102
+ .sub(0.5)
103
+ .mul(vec2(float(1).sub(storm.mul(0.32)), 1));
104
+ const r = p.length();
105
+ const disc = exp(r.mul(r).mul(-18)).mul(float(1).sub(smoothstep(0.36, 0.5, r)));
106
+ const arms = pow(cos(atan(p.y, p.x).mul(3)).abs(), 12)
107
+ .mul(0.2)
108
+ .add(0.8);
109
+ const shown = step(float(instanceIndex).add(1), visible);
110
+ const distance = cameraPosition.distance(at);
111
+ const opacity = random(11)
112
+ .mul(0.55)
113
+ .add(0.28)
114
+ .mul(smoothstep(0.35, 1.2, distance));
115
+ material.colorNode = vec4(0.95, 0.977, 1, disc.mul(arms).mul(opacity).mul(shown));
116
+ const size = pow(random(13), 3).mul(0.063).add(0.016);
117
+ const widest = distance.mul(MAX_FLAKE_PIXELS).div(pixelScale);
118
+ // In a storm each flake streaks along the wind, the study's squashed-disc look made longer.
119
+ const drawn = size.mul(storm.mul(0.5).add(1)).min(widest).mul(shown);
120
+ material.scaleNode = vec2(drawn.mul(storm.mul(1.6).add(1)), drawn);
121
+ return material;
122
+ }
123
+
124
+ /**
125
+ * Every flake's position is a function of how far the air has carried it, not a stored velocity:
126
+ * `drift` and `fall` are integrated on the CPU from the live wind and fall speed, so changing a
127
+ * slider never teleports the flakes, and the box wraps around the explorer wherever they walk.
128
+ */
129
+ function createSnowfall(
130
+ amount: number,
131
+ particlesFor: (options: IParticleOptions) => ParticleSystem,
132
+ ) {
133
+ const storm = floatUniform(0);
134
+ const visible = floatUniform(amount);
135
+ const drift = uniform(new Vector2());
136
+ const fall = uniform(0);
137
+ const centre = uniform(new Vector2());
138
+ const swirl = uniform(0);
139
+ const pixelScale = floatUniform(800);
140
+ const place = (positions: StorageBufferNode<"vec3">): ComputeNode =>
141
+ Fn(() => {
142
+ const seed = random(3).mul(100);
143
+ const start = vec3(random(5), random(7), random(9));
144
+ const speed = fract(seed).add(0.58);
145
+ const height = mod(start.y.mul(CEILING).sub(fall.mul(speed)), CEILING).sub(0.5);
146
+ const phase = swirl.add(seed);
147
+ // Air near the ground is slower than air aloft, as the study's coupling had it.
148
+ const coupling = height.div(7).clamp(0.18, 1);
149
+ const wander = vec2(
150
+ sin(phase.add(start.z.mul(4))),
151
+ cos(phase.mul(0.86).add(start.x.mul(4))),
152
+ ).mul(storm.mul(0.7).add(0.16));
153
+ const span = float(SPAN * 2);
154
+ const raw = start.xz.mul(span).add(drift.mul(coupling)).add(wander);
155
+ const wrapped = mod(raw.sub(centre).add(SPAN), span).sub(SPAN).add(centre);
156
+ positions.element(instanceIndex).assign(vec3(wrapped.x, height, wrapped.y));
157
+ })().compute(amount);
158
+ const material = new SpriteNodeMaterial();
159
+ const particles = particlesFor({
160
+ amount,
161
+ material,
162
+ process: ({ positions }) => place(positions),
163
+ start: ({ positions }) => place(positions),
164
+ });
165
+ // The flake look needs each flake's position, which exists once the particle buffers do.
166
+ const flake = flakeMaterial(
167
+ storm,
168
+ visible,
169
+ particles.buffers.positions.toAttribute(),
170
+ pixelScale,
171
+ );
172
+ flake.positionNode = material.positionNode;
173
+ particles.material = flake;
174
+ particles.renderOrder = 3;
175
+ return { centre, drift, fall, particles, pixelScale, storm, swirl, visible };
176
+ }
177
+
178
+ /** One pooled burst: every particle leaves the boot at once and fades by its own lifetime. */
179
+ function createBurst(particlesFor: (options: IParticleOptions) => ParticleSystem) {
180
+ const age = uniform(BURST_LIFETIME);
181
+ const kick = uniform(1);
182
+ const wind = uniform(0);
183
+ const material = new SpriteNodeMaterial({
184
+ blending: AdditiveBlending,
185
+ depthWrite: false,
186
+ transparent: true,
187
+ });
188
+ const life = random(17).mul(0.65).add(0.38);
189
+ const t = age.min(life);
190
+ const fade = float(1).sub(t.div(life)).max(0);
191
+ const p = uv().sub(0.5);
192
+ const puff = exp(p.dot(p).mul(-16)).mul(float(1).sub(smoothstep(0.34, 0.5, p.length())));
193
+ const alive = step(age, life);
194
+ material.colorNode = vec4(0.9, 0.94, 1, puff.mul(pow(fade, 1.5)).mul(0.5).mul(alive));
195
+ material.scaleNode = vec2(random(19).mul(0.048).add(0.025).mul(t.div(life).mul(1.9).add(1)));
196
+ const place = (positions: StorageBufferNode<"vec3">): ComputeNode =>
197
+ Fn(() => {
198
+ const angle = random(23).mul(Math.PI * 2);
199
+ const outward = random(29).mul(0.58).add(0.22).mul(kick);
200
+ const rise = random(31).mul(0.85).add(0.4).mul(kick);
201
+ const launch = vec3(cos(angle).mul(0.13), 0.035, sin(angle).mul(0.2));
202
+ const across = vec3(cos(angle).mul(outward).add(wind.mul(0.12)), 0, sin(angle).mul(outward));
203
+ // Air drag slows the spray; gravity brings it back to the snow, where it rests.
204
+ const travelled = float(1)
205
+ .sub(exp(t.mul(-1.8)))
206
+ .div(1.8);
207
+ const height = rise.mul(t).sub(t.mul(t).mul(1.25)).max(0);
208
+ positions
209
+ .element(instanceIndex)
210
+ .assign(launch.add(across.mul(travelled)).add(vec3(0, height, 0)));
211
+ })().compute(BURST_PARTICLES);
212
+ const particles = particlesFor({
213
+ amount: BURST_PARTICLES,
214
+ material,
215
+ process: ({ positions }) => place(positions),
216
+ start: ({ positions }) => place(positions),
217
+ });
218
+ particles.renderOrder = 4;
219
+ particles.visible = false;
220
+ return { age, kick, particles, wind };
221
+ }
222
+
223
+ export function createWeather(options: {
224
+ readonly flakes: number;
225
+ /** Builds a pooled particle system; the scene passes `GPUParticles3D`. */
226
+ readonly particles: (options: IParticleOptions) => ParticleSystem;
227
+ }): ISnowWeather {
228
+ const fall = createSnowfall(options.flakes, options.particles);
229
+ const bursts = Array.from({ length: 8 }, () => createBurst(options.particles));
230
+ let cursor = 0;
231
+ let time = 0;
232
+ let storm = 0;
233
+ let wind = 0.4;
234
+ let drifted = { x: 0, z: 0 };
235
+ let fallen = 0;
236
+ const damp = (a: number, b: number, rate: number, dt: number) =>
237
+ a + (b - a) * (1 - Math.exp(-rate * Math.max(0, dt)));
238
+ return {
239
+ bursts: bursts.map((burst) => burst.particles),
240
+ burst(at, strength) {
241
+ const burst = bursts[cursor % bursts.length];
242
+ cursor += 1;
243
+ if (burst === undefined) return;
244
+ burst.particles.position.set(at.x, at.y, at.z);
245
+ burst.particles.visible = true;
246
+ burst.age.value = 0;
247
+ burst.kick.value = 0.8 + Math.min(1, strength * 4);
248
+ },
249
+ snowfall: fall.particles,
250
+ get storm() {
251
+ return storm;
252
+ },
253
+ update(dt, centre, pixelScale, settings) {
254
+ fall.pixelScale.value = pixelScale;
255
+ time += dt;
256
+ storm = damp(storm, settings.blizzard ? 1 : 0, 0.95, dt);
257
+ const gust = 1 + 0.22 * Math.sin(time * 1.1) + 0.12 * Math.sin(time * 2.73 + 1.6);
258
+ const target = (settings.wind * (1 - storm) + (9.5 + settings.wind * 0.5) * storm) * gust;
259
+ wind = damp(wind, target, 2.3, dt);
260
+ drifted = { x: drifted.x + wind * dt, z: drifted.z + wind * 0.24 * dt };
261
+ fallen += settings.fallSpeed * (0.95 + storm * 0.7) * dt;
262
+ fall.drift.value.set(drifted.x, drifted.z);
263
+ fall.fall.value = fallen;
264
+ fall.swirl.value = time * 0.7;
265
+ fall.centre.value.set(centre.x, centre.z);
266
+ fall.storm.value = storm;
267
+ fall.visible.value = Math.round(options.flakes * settings.snowfall * (0.24 + 0.76 * storm));
268
+ for (const burst of bursts) {
269
+ if (!burst.particles.visible) continue;
270
+ burst.age.value += dt;
271
+ burst.wind.value = wind;
272
+ if (burst.age.value > BURST_LIFETIME) burst.particles.visible = false;
273
+ }
274
+ },
275
+ get wind() {
276
+ return wind;
277
+ },
278
+ };
279
+ }