voxljs 0.1.0 → 0.1.1

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 (72) hide show
  1. package/dist/audio/SpatialAudioEngine.d.ts +10 -0
  2. package/dist/audio/SpatialAudioEngine.js +80 -0
  3. package/dist/audio/SpatialAudioEngine.js.map +1 -1
  4. package/dist/core/VoxelEngine.d.ts +99 -0
  5. package/dist/core/VoxelEngine.js +181 -0
  6. package/dist/core/VoxelEngine.js.map +1 -0
  7. package/dist/core/index.d.ts +1 -0
  8. package/dist/core/index.js +1 -0
  9. package/dist/core/index.js.map +1 -1
  10. package/dist/index.d.ts +2 -1
  11. package/dist/index.js +2 -1
  12. package/dist/index.js.map +1 -1
  13. package/dist/input/InputManager.d.ts +45 -6
  14. package/dist/input/InputManager.js +178 -31
  15. package/dist/input/InputManager.js.map +1 -1
  16. package/dist/input/index.d.ts +1 -1
  17. package/dist/input/index.js +1 -1
  18. package/dist/input/index.js.map +1 -1
  19. package/dist/materials/Material.d.ts +6 -0
  20. package/dist/materials/Material.js +12 -0
  21. package/dist/materials/Material.js.map +1 -1
  22. package/dist/perf/EntityTickScheduler.d.ts +71 -0
  23. package/dist/perf/EntityTickScheduler.js +202 -0
  24. package/dist/perf/EntityTickScheduler.js.map +1 -0
  25. package/dist/perf/SpatialEntityGrid.d.ts +47 -0
  26. package/dist/perf/SpatialEntityGrid.js +200 -0
  27. package/dist/perf/SpatialEntityGrid.js.map +1 -0
  28. package/dist/perf/index.d.ts +2 -0
  29. package/dist/perf/index.js +2 -0
  30. package/dist/perf/index.js.map +1 -1
  31. package/dist/physics/VoxelPhysicsWorld.d.ts +308 -0
  32. package/dist/physics/VoxelPhysicsWorld.js +1020 -0
  33. package/dist/physics/VoxelPhysicsWorld.js.map +1 -0
  34. package/dist/physics/index.d.ts +1 -0
  35. package/dist/physics/index.js +1 -0
  36. package/dist/physics/index.js.map +1 -1
  37. package/dist/renderers/WebGLRenderer.js +1 -0
  38. package/dist/renderers/WebGLRenderer.js.map +1 -1
  39. package/dist/renderers/webgl/WebGLProgram.js +18 -19
  40. package/dist/renderers/webgl/WebGLProgram.js.map +1 -1
  41. package/dist/renderers/webgl/WebGLState.d.ts +17 -0
  42. package/dist/renderers/webgl/WebGLState.js +115 -1
  43. package/dist/renderers/webgl/WebGLState.js.map +1 -1
  44. package/dist/voxel/GrassFieldSystem.d.ts +186 -0
  45. package/dist/voxel/GrassFieldSystem.js +723 -0
  46. package/dist/voxel/GrassFieldSystem.js.map +1 -0
  47. package/dist/voxel/SilhouetteLightVolumes.d.ts +13 -2
  48. package/dist/voxel/SilhouetteLightVolumes.js +384 -78
  49. package/dist/voxel/SilhouetteLightVolumes.js.map +1 -1
  50. package/dist/voxel/VoxImporter.d.ts +32 -0
  51. package/dist/voxel/VoxImporter.js +228 -0
  52. package/dist/voxel/VoxImporter.js.map +1 -1
  53. package/dist/voxel/VoxelBrushes.d.ts +110 -0
  54. package/dist/voxel/VoxelBrushes.js +248 -0
  55. package/dist/voxel/VoxelBrushes.js.map +1 -0
  56. package/dist/voxel/VoxelPotatoShader.d.ts +8 -2
  57. package/dist/voxel/VoxelPotatoShader.js +68 -4
  58. package/dist/voxel/VoxelPotatoShader.js.map +1 -1
  59. package/dist/voxel/VoxelSilhouetteShadows.d.ts +69 -11
  60. package/dist/voxel/VoxelSilhouetteShadows.js +653 -32
  61. package/dist/voxel/VoxelSilhouetteShadows.js.map +1 -1
  62. package/dist/voxel/index.d.ts +4 -2
  63. package/dist/voxel/index.js +4 -2
  64. package/dist/voxel/index.js.map +1 -1
  65. package/dist/world/VoxelMobAISystem.d.ts +183 -0
  66. package/dist/world/VoxelMobAISystem.js +492 -0
  67. package/dist/world/VoxelMobAISystem.js.map +1 -0
  68. package/dist/world/index.d.ts +1 -0
  69. package/dist/world/index.js +1 -0
  70. package/dist/world/index.js.map +1 -1
  71. package/llms.txt +301 -0
  72. package/package.json +2 -1
@@ -0,0 +1,723 @@
1
+ import { DoubleSide } from '../constants.js';
2
+ import { BufferAttribute, BufferGeometry, DynamicDrawUsage, InstancedBufferAttribute } from '../core/index.js';
3
+ import { ShaderMaterial } from '../materials/ShaderMaterial.js';
4
+ import { Color, Vector2, Vector3 } from '../math/index.js';
5
+ import { InstancedMesh } from '../objects/InstancedMesh.js';
6
+ import { VOLUME_WAKE_MAX_SLOTS } from './VolumeWakeField.js';
7
+ export const GRASS_DENSITY_PRESETS = {
8
+ off: {
9
+ id: 'off',
10
+ label: 'Off',
11
+ gridDim: 0,
12
+ bladesPerCell: 0,
13
+ maxInstances: 0,
14
+ },
15
+ low: {
16
+ id: 'low',
17
+ label: 'Low',
18
+ gridDim: 48,
19
+ bladesPerCell: 1,
20
+ maxInstances: 48 * 48,
21
+ },
22
+ high: {
23
+ id: 'high',
24
+ label: 'High',
25
+ gridDim: 76,
26
+ bladesPerCell: 1,
27
+ maxInstances: 76 * 76,
28
+ },
29
+ };
30
+ export const GRASS_VERTEX_SHADER = `
31
+ uniform float uTime;
32
+ uniform vec3 uCameraPos;
33
+ uniform float uFadeStartRadius;
34
+ uniform float uRadius;
35
+ uniform vec2 uWindDir;
36
+ uniform float uWindSpeed;
37
+ uniform float uWindStrength;
38
+ uniform float uWakeEnabled;
39
+
40
+ uniform vec4 uWakePos[${VOLUME_WAKE_MAX_SLOTS}];
41
+ uniform vec4 uWakeParams[${VOLUME_WAKE_MAX_SLOTS}];
42
+ uniform int uActiveWakeCount;
43
+ uniform float uWakeTime;
44
+
45
+ varying vec3 vColor;
46
+ varying vec3 vNormal;
47
+ varying vec3 vWorldPos;
48
+ varying vec2 vUv;
49
+ varying float vTrample;
50
+ varying float vFogDepth;
51
+
52
+ void main() {
53
+ vUv = uv;
54
+
55
+ #ifdef USE_INSTANCING
56
+ mat4 worldMat = modelMatrix * instanceMatrix;
57
+ vec3 rootPos = (worldMat * vec4(0.0, 0.0, 0.0, 1.0)).xyz;
58
+ #ifdef USE_INSTANCING_COLOR
59
+ vColor = color * instanceColor;
60
+ #else
61
+ vColor = color;
62
+ #endif
63
+ #else
64
+ mat4 worldMat = modelMatrix;
65
+ vec3 rootPos = (worldMat * vec4(0.0, 0.0, 0.0, 1.0)).xyz;
66
+ vColor = color;
67
+ #endif
68
+
69
+ // Smooth distance shrink from fadeStartRadius (e.g. 24m) down to 0 at outer radius (32m) — zero pop-in
70
+ float distXZ = length(rootPos.xz - uCameraPos.xz);
71
+ float distScale = 1.0 - smoothstep(uFadeStartRadius, uRadius, distXZ);
72
+
73
+ // Local scaled blade vertex transformed into world space
74
+ vec3 localPos = position * distScale;
75
+ vec3 worldPos = (worldMat * vec4(localPos, 1.0)).xyz;
76
+ vec3 rawNormal = mat3(worldMat) * normal;
77
+ float rawNormalLen = length(rawNormal);
78
+ vec3 worldNormal = rawNormalLen > 0.0001 ? (rawNormal / rawNormalLen) : vec3(0.0, 1.0, 0.0);
79
+
80
+ // Root-anchored flexibility factor (0 at root -> 1 at tip)
81
+ float bend = uv.y * uv.y;
82
+ float tipMask = uv.y;
83
+ float trampleAmount = 0.0;
84
+
85
+ if (distScale > 0.001) {
86
+ vec3 relPos = worldPos - rootPos;
87
+ float segLen = length(relPos);
88
+ float bladeH = max(0.0, relPos.y);
89
+
90
+ // 1. Traveling wind gusts + subtle high-frequency flutter scaled by uv.y * uv.y and blade height
91
+ vec2 wDir = normalize(uWindDir + vec2(0.0001, 0.0));
92
+ float gustWave = sin(dot(rootPos.xz, wDir) * 0.24 - uTime * uWindSpeed);
93
+ float crossWave = cos(rootPos.x * 0.41 - rootPos.z * 0.37 - uTime * (uWindSpeed * 0.72));
94
+ float flutter = sin(rootPos.x * 1.35 + rootPos.z * 1.15 - uTime * (uWindSpeed * 2.15)) * 0.22;
95
+ float gustStrength = (0.38 + 0.62 * (gustWave * 0.5 + 0.5)) * (0.8 + 0.25 * crossWave) + flutter;
96
+ float swayScale = min(bladeH * 0.85, uWindStrength * distScale);
97
+ float sway = gustStrength * swayScale * bend;
98
+
99
+ vec2 horizDisp = wDir * sway + vec2(-wDir.y, wDir.x) * (flutter * swayScale * 0.45 * bend);
100
+ float vertDip = -min(abs(sway) * 0.28, bladeH * 0.35);
101
+
102
+ // 2. VolumeWakeField trampling (Mode 0 paths) & C4 radial shockwaves (Mode 1 blasts)
103
+ if (uWakeEnabled > 0.5 && uActiveWakeCount > 0) {
104
+ vec2 wakePush = vec2(0.0);
105
+ float wakeFlatten = 0.0;
106
+
107
+ for (int i = 0; i < ${VOLUME_WAKE_MAX_SLOTS}; i++) {
108
+ if (i >= uActiveWakeCount) break;
109
+ vec4 wp = uWakePos[i];
110
+ vec4 param = uWakeParams[i];
111
+ float age = uWakeTime - wp.w;
112
+ float duration = max(param.z, 0.001);
113
+ if (age < 0.0 || age >= duration) continue;
114
+
115
+ float progress = clamp(age / duration, 0.0, 1.0);
116
+ vec3 delta = rootPos - wp.xyz;
117
+ float distXZWake = length(delta.xz);
118
+
119
+ if (param.w < 0.5) {
120
+ // Mode 0: Player/vehicle ground trample trail that gradually springs back up over healDuration
121
+ float heal = 1.0 - smoothstep(0.15, 1.0, progress);
122
+ float activeRadius = mix(param.x, param.y, smoothstep(0.0, 0.1, progress));
123
+ // Vertical gate so high-altitude flying cloud wakes don't flatten ground grass far below
124
+ float vertGate = 1.0 - smoothstep(activeRadius + 1.2, activeRadius + 3.4, abs(delta.y));
125
+ if (distXZWake < activeRadius && vertGate > 0.001 && heal > 0.001) {
126
+ float falloff = (1.0 - smoothstep(0.0, activeRadius, distXZWake)) * heal * vertGate;
127
+ vec2 outDir = distXZWake > 0.001 ? (delta.xz / distXZWake) : wDir;
128
+ wakePush += outDir * (falloff * 0.65);
129
+ wakeFlatten = max(wakeFlatten, falloff * 0.85);
130
+ }
131
+ } else {
132
+ // Mode 1: Expanding C4 shockwave blasting grass outward radially
133
+ float curRadius = mix(param.x, param.y, pow(progress, 0.65));
134
+ float strength = 1.0 - smoothstep(0.45, 1.0, progress);
135
+ float shellThickness = max(curRadius * 0.32, 1.2);
136
+ float vertGate = 1.0 - smoothstep(curRadius * 0.75 + 2.0, curRadius + 6.0, abs(delta.y));
137
+ if (distXZWake < curRadius + shellThickness && vertGate > 0.001 && strength > 0.001) {
138
+ vec2 outDir = distXZWake > 0.001 ? (delta.xz / distXZWake) : wDir;
139
+ float insideMask = 1.0 - smoothstep(curRadius * 0.65, curRadius * 1.08, distXZWake);
140
+ float shellBand = 1.0 - smoothstep(0.0, shellThickness, abs(distXZWake - curRadius));
141
+ float blast = clamp((shellBand * 1.05 + insideMask * 0.55) * strength * vertGate, 0.0, 1.0);
142
+ wakePush += outDir * (blast * 0.88);
143
+ wakeFlatten = max(wakeFlatten, blast * 0.88);
144
+ }
145
+ }
146
+ }
147
+
148
+ // Clamp accumulated push vector & scale strictly to the blade's real height so blades bend instead of stretching
149
+ float wakePushLen = length(wakePush);
150
+ if (wakePushLen > 0.9) {
151
+ wakePush *= (0.9 / wakePushLen);
152
+ }
153
+ horizDisp = horizDisp * (1.0 - wakeFlatten * 0.75) + wakePush * (segLen * 0.92 * tipMask);
154
+ vertDip -= bladeH * wakeFlatten * 0.78;
155
+ trampleAmount = clamp(wakeFlatten, 0.0, 1.0);
156
+ }
157
+
158
+ // Strict arc-length-preserving bend: tip can whip flat to the ground but can NEVER exceed original blade length
159
+ vec3 bentRel = vec3(
160
+ relPos.x + horizDisp.x,
161
+ max(segLen * 0.04, relPos.y + vertDip),
162
+ relPos.z + horizDisp.y
163
+ );
164
+ float bentLen = length(bentRel);
165
+ if (segLen > 0.0001 && bentLen > segLen) {
166
+ bentRel *= (segLen / bentLen);
167
+ }
168
+ worldPos = rootPos + bentRel;
169
+ }
170
+
171
+ vWorldPos = worldPos;
172
+ vNormal = worldNormal;
173
+ vTrample = trampleAmount;
174
+
175
+ vec4 mvPos = viewMatrix * vec4(worldPos, 1.0);
176
+ vFogDepth = -mvPos.z;
177
+ gl_Position = projectionMatrix * mvPos;
178
+ }
179
+ `;
180
+ export const GRASS_FRAGMENT_SHADER = `
181
+ uniform vec3 uSunDir;
182
+ uniform vec3 uSunColor;
183
+ uniform vec3 uShadowColor;
184
+ uniform float uFogEnabled;
185
+ uniform vec3 uFogColor;
186
+ uniform float uFogNear;
187
+ uniform float uFogFar;
188
+
189
+ varying vec3 vColor;
190
+ varying vec3 vNormal;
191
+ varying vec3 vWorldPos;
192
+ varying vec2 vUv;
193
+ varying float vTrample;
194
+ varying float vFogDepth;
195
+
196
+ void main() {
197
+ vec3 N = normalize(vNormal);
198
+ if (!gl_FrontFacing) N = -N;
199
+ vec3 L = normalize(uSunDir);
200
+ vec3 V = normalize(cameraPosition - vWorldPos);
201
+
202
+ // Soft grass wrap-diffuse lighting (lush, never harsh black backsides)
203
+ float wrapNdotL = clamp(dot(N, L) * 0.5 + 0.5, 0.0, 1.0);
204
+ float skyBias = mix(0.58, 1.0, vUv.y);
205
+ vec3 lightTint = mix(uShadowColor, uSunColor, wrapNdotL * skyBias);
206
+
207
+ // Subsurface sunlit tip translucency when looking toward the sun
208
+ float backlit = clamp(dot(-V, L), 0.0, 1.0);
209
+ float sss = backlit * backlit * backlit * vUv.y * 0.28;
210
+
211
+ // Slightly darken trampled/flattened grass blades for visible trail contrast
212
+ float trampleShade = 1.0 - vTrample * 0.22;
213
+
214
+ vec3 col = vColor * lightTint * trampleShade + uSunColor * (vColor * sss);
215
+
216
+ if (uFogEnabled > 0.5) {
217
+ float fogFactor = clamp((vFogDepth - uFogNear) / max(1.0, uFogFar - uFogNear), 0.0, 1.0);
218
+ col = mix(col, uFogColor, fogFactor);
219
+ }
220
+
221
+ gl_FragColor = vec4(col, 1.0);
222
+ }
223
+ `;
224
+ /**
225
+ * Builds a lightweight 3-triangle (5-vertex) tapered grass blade `BufferGeometry`
226
+ * with vertical root-to-tip vertex color shading (dark base to bright sunlit tip)
227
+ * and `uv.y` ranging cleanly from `0.0` at the root to `1.0` at the tip.
228
+ */
229
+ export function createGrassBladeGeometry(options = {}) {
230
+ const halfW = Math.max(0.005, (options.width ?? 0.075) * 0.5);
231
+ const h = Math.max(0.02, options.height ?? 0.42);
232
+ const curveZ = options.curveZ ?? 0.06;
233
+ const rootCol = new Color(options.rootColor ?? 0x3b5e2c);
234
+ const midCol = new Color(options.midColor ?? 0x659e40);
235
+ const tipCol = new Color(options.tipColor ?? 0xa7d965);
236
+ const midY = h * 0.54;
237
+ const midHalfW = halfW * 0.56;
238
+ const midZ = curveZ * 0.32;
239
+ // 5 vertices: [0: root-L, 1: root-R, 2: mid-L, 3: mid-R, 4: tip]
240
+ const positions = new Float32Array([
241
+ -halfW, 0.0, 0.0,
242
+ halfW, 0.0, 0.0,
243
+ -midHalfW, midY, midZ,
244
+ midHalfW, midY, midZ,
245
+ 0.0, h, curveZ,
246
+ ]);
247
+ // Smooth upward-tilted normals for soft foliage shading
248
+ const nLen = Math.hypot(0.0, 0.45, 0.89);
249
+ const ny = 0.45 / nLen;
250
+ const nz = 0.89 / nLen;
251
+ const normals = new Float32Array([
252
+ -0.25, ny, nz,
253
+ 0.25, ny, nz,
254
+ -0.18, ny * 1.1, nz * 0.94,
255
+ 0.18, ny * 1.1, nz * 0.94,
256
+ 0.0, 0.72, 0.69,
257
+ ]);
258
+ const uvs = new Float32Array([
259
+ 0.0, 0.0,
260
+ 1.0, 0.0,
261
+ 0.15, 0.54,
262
+ 0.85, 0.54,
263
+ 0.5, 1.0,
264
+ ]);
265
+ const colors = new Float32Array([
266
+ rootCol.r, rootCol.g, rootCol.b,
267
+ rootCol.r, rootCol.g, rootCol.b,
268
+ midCol.r, midCol.g, midCol.b,
269
+ midCol.r, midCol.g, midCol.b,
270
+ tipCol.r, tipCol.g, tipCol.b,
271
+ ]);
272
+ // Exactly 3 triangles (9 indices)
273
+ const indices = new Uint16Array([
274
+ 0, 1, 3,
275
+ 0, 3, 2,
276
+ 2, 3, 4,
277
+ ]);
278
+ const geo = new BufferGeometry();
279
+ geo.setAttribute('position', new BufferAttribute(positions, 3));
280
+ geo.setAttribute('normal', new BufferAttribute(normals, 3));
281
+ geo.setAttribute('uv', new BufferAttribute(uvs, 2));
282
+ geo.setAttribute('color', new BufferAttribute(colors, 3));
283
+ geo.setIndex(new BufferAttribute(indices, 1));
284
+ return geo;
285
+ }
286
+ export function createGrassFieldMaterial(options = {}) {
287
+ const radius = Math.max(0.5, options.radius ?? 32);
288
+ const fadeStart = Math.max(0.25, Math.min(radius - 0.1, options.fadeStartRadius ?? radius * 0.75));
289
+ const sun = options.sunDir ?? { x: 0.45, y: 0.82, z: 0.35 };
290
+ const sunVec = new Vector3(sun.x, sun.y, sun.z).normalize();
291
+ const wind = options.windDir ?? [0.86, 0.51];
292
+ const uniforms = {
293
+ uTime: { value: 0.0 },
294
+ uCameraPos: { value: new Vector3(0, 0, 0) },
295
+ uFadeStartRadius: { value: fadeStart },
296
+ uRadius: { value: radius },
297
+ uWindDir: { value: new Vector2(wind[0], wind[1]).normalize() },
298
+ uWindSpeed: { value: options.windSpeed ?? 2.1 },
299
+ uWindStrength: { value: options.windStrength ?? 0.16 },
300
+ uSunDir: { value: sunVec },
301
+ uSunColor: { value: new Color(options.sunColor ?? 0xfff5db) },
302
+ uShadowColor: { value: new Color(options.shadowColor ?? 0x5c746e) },
303
+ uFogEnabled: { value: options.fogEnabled ? 1.0 : 0.0 },
304
+ uFogColor: { value: new Color(options.fogColor ?? 0x9fc2de) },
305
+ uFogNear: { value: options.fogNear ?? 60.0 },
306
+ uFogFar: { value: options.fogFar ?? 240.0 },
307
+ uWakeEnabled: { value: options.wakeField ? 1.0 : 0.0 },
308
+ uWakePos: { value: new Float32Array(VOLUME_WAKE_MAX_SLOTS * 4) },
309
+ uWakeParams: { value: new Float32Array(VOLUME_WAKE_MAX_SLOTS * 4) },
310
+ uActiveWakeCount: { value: 0 },
311
+ uWakeTime: { value: 0.0 },
312
+ };
313
+ if (options.wakeField) {
314
+ options.wakeField.bindToUniforms(uniforms);
315
+ }
316
+ return new ShaderMaterial({
317
+ name: 'GrassFieldMaterial',
318
+ vertexColors: true,
319
+ transparent: false,
320
+ depthWrite: true,
321
+ depthTest: true,
322
+ side: DoubleSide,
323
+ uniforms,
324
+ vertexShader: GRASS_VERTEX_SHADER,
325
+ fragmentShader: GRASS_FRAGMENT_SHADER,
326
+ });
327
+ }
328
+ const INVALID_CELL = 0x7fffffff;
329
+ function hash2D(ix, iz, salt) {
330
+ let h = (Math.imul(ix, 374761393) + Math.imul(iz, 668265263) + Math.imul(salt, 2246822519)) | 0;
331
+ h = Math.imul(h ^ (h >>> 13), 1274126177);
332
+ h ^= h >>> 16;
333
+ return (h >>> 0) / 4294967296;
334
+ }
335
+ function posMod(n, m) {
336
+ const r = n % m;
337
+ return r < 0 ? r + m : r;
338
+ }
339
+ /**
340
+ * Lightweight, zero-dependency, single-draw-call instanced grass field designed for low-end WebGL2 GPUs.
341
+ *
342
+ * - Renders all blades in a single `InstancedMesh` draw call using a 3-triangle tapered blade geometry.
343
+ * - Toroidally recycles blade instance slots in a ring around the camera with zero per-frame heap allocations.
344
+ * - Animates traveling wind waves scaled by `uv.y * uv.y`, smoothly shrinks blades across `fadeStartRadius -> radius`,
345
+ * and reacts to shared `VolumeWakeField` trampling paths & C4 shockwaves.
346
+ */
347
+ export class GrassFieldSystem {
348
+ constructor(options) {
349
+ this._density = 'low';
350
+ this._activeGridDim = 0;
351
+ this._cellSize = 1;
352
+ this._lastCenterGx = INVALID_CELL;
353
+ this._lastCenterGz = INVALID_CELL;
354
+ this._fullRefreshPending = true;
355
+ this._scratchSample = {
356
+ y: 0,
357
+ isGrass: false,
358
+ tintR: 1,
359
+ tintG: 1,
360
+ tintB: 1,
361
+ };
362
+ /** Diagnostic counters for tests and profiling. */
363
+ this.activeBladeCount = 0;
364
+ this.reseatedLastUpdate = 0;
365
+ this.totalReseated = 0;
366
+ this.radius = Math.max(0.5, options.radius ?? 32);
367
+ this.fadeStartRadius = Math.max(0.25, Math.min(this.radius - 0.1, options.fadeStartRadius ?? (this.radius >= 30 ? 24 : this.radius * 0.75)));
368
+ this._seed = (options.seed ?? 1337) | 0;
369
+ this.wakeField = options.wakeField ?? options.materialOptions?.wakeField ?? null;
370
+ this._lowGridDim = Math.max(8, Math.floor(options.lowGridDim ?? GRASS_DENSITY_PRESETS.low.gridDim));
371
+ this._highGridDim = Math.max(this._lowGridDim, Math.floor(options.highGridDim ?? GRASS_DENSITY_PRESETS.high.gridDim));
372
+ this._maxCapacity = this._highGridDim * this._highGridDim;
373
+ if (options.sampleSurface) {
374
+ this._sampleSurface = options.sampleSurface;
375
+ }
376
+ else if (options.getVoxel) {
377
+ const getVoxel = options.getVoxel;
378
+ const isGrass = options.isGrassVoxel ?? ((id) => id === 1);
379
+ const isAir = options.isAirVoxel ?? ((id) => id === 0);
380
+ const scale = options.voxelScale ?? 1.0;
381
+ const invScale = 1.0 / scale;
382
+ const offX = options.worldOffset?.x ?? 0;
383
+ const offY = options.worldOffset?.y ?? 0;
384
+ const offZ = options.worldOffset?.z ?? 0;
385
+ const minVy = Math.floor(options.minVoxelY ?? 0);
386
+ const maxVy = Math.floor(options.maxVoxelY ?? 31);
387
+ this._sampleSurface = (worldX, worldZ, out) => {
388
+ const vx = Math.floor((worldX - offX) * invScale);
389
+ const vz = Math.floor((worldZ - offZ) * invScale);
390
+ for (let vy = maxVy; vy >= minVy; vy--) {
391
+ const id = getVoxel(vx, vy, vz);
392
+ if (!isAir(id)) {
393
+ if (isGrass(id) && isAir(getVoxel(vx, vy + 1, vz))) {
394
+ out.y = offY + (vy + 1) * scale;
395
+ out.isGrass = true;
396
+ out.tintR = 1;
397
+ out.tintG = 1;
398
+ out.tintB = 1;
399
+ }
400
+ else {
401
+ out.y = 0;
402
+ out.isGrass = false;
403
+ out.tintR = 1;
404
+ out.tintG = 1;
405
+ out.tintB = 1;
406
+ }
407
+ return;
408
+ }
409
+ }
410
+ out.y = 0;
411
+ out.isGrass = false;
412
+ out.tintR = 1;
413
+ out.tintG = 1;
414
+ out.tintB = 1;
415
+ };
416
+ }
417
+ else {
418
+ throw new Error('GrassFieldSystem requires either `sampleSurface` or `getVoxel`.');
419
+ }
420
+ this.geometry = createGrassBladeGeometry(options.bladeOptions);
421
+ this.material = createGrassFieldMaterial({
422
+ ...options.materialOptions,
423
+ radius: this.radius,
424
+ fadeStartRadius: this.fadeStartRadius,
425
+ wakeField: this.wakeField,
426
+ });
427
+ this.mesh = new InstancedMesh(this.geometry, this.material, this._maxCapacity);
428
+ this.mesh.name = 'GrassFieldInstancedMesh';
429
+ this.mesh.frustumCulled = false;
430
+ this.mesh.count = 0;
431
+ // Pre-allocate instanceColor once so per-blade tint writes never allocate at runtime
432
+ const colorArr = new Float32Array(this._maxCapacity * 3);
433
+ colorArr.fill(1.0);
434
+ this.mesh.instanceColor = new InstancedBufferAttribute(colorArr, 3);
435
+ this.mesh.instanceColor.setUsage(DynamicDrawUsage);
436
+ this._slotCellX = new Int32Array(this._maxCapacity);
437
+ this._slotCellZ = new Int32Array(this._maxCapacity);
438
+ this._slotActive = new Uint8Array(this._maxCapacity);
439
+ this._slotCellX.fill(INVALID_CELL);
440
+ this._slotCellZ.fill(INVALID_CELL);
441
+ this.setDensity(options.density ?? 'low');
442
+ }
443
+ get density() {
444
+ return this._density;
445
+ }
446
+ get maxCapacity() {
447
+ return this._maxCapacity;
448
+ }
449
+ get drawCallCount() {
450
+ return this._density !== 'off' && this.mesh.visible && this.mesh.count > 0 ? 1 : 0;
451
+ }
452
+ /**
453
+ * Current normalized grass density amount in `[0..1]`.
454
+ */
455
+ get amount() {
456
+ if (this._density === 'off' || this._activeGridDim <= 0)
457
+ return 0;
458
+ return Math.min(1, this._activeGridDim / this._highGridDim);
459
+ }
460
+ /**
461
+ * Smoothly adjusts grass blade density using a normalized `[0..1]` amount without reallocating GPU buffers.
462
+ * `0` disables grass (`'off'`); values in `(0..1]` scale the toroidal grid up to `highGridDim`.
463
+ */
464
+ setAmount(amount) {
465
+ const clamped = Math.max(0, Math.min(1, amount));
466
+ if (clamped <= 0.001) {
467
+ this.setDensity('off');
468
+ return;
469
+ }
470
+ const minGrid = Math.min(8, this._lowGridDim);
471
+ const nextDim = Math.max(minGrid, Math.min(this._highGridDim, Math.round(minGrid + clamped * (this._highGridDim - minGrid))));
472
+ this._density = nextDim > this._lowGridDim ? 'high' : 'low';
473
+ this._activeGridDim = nextDim;
474
+ this._cellSize = (this.radius * 2) / this._activeGridDim;
475
+ this.mesh.count = this._activeGridDim * this._activeGridDim;
476
+ this.mesh.visible = true;
477
+ this._fullRefreshPending = true;
478
+ this._lastCenterGx = INVALID_CELL;
479
+ this._lastCenterGz = INVALID_CELL;
480
+ this._slotCellX.fill(INVALID_CELL);
481
+ this._slotCellZ.fill(INVALID_CELL);
482
+ this._slotActive.fill(0);
483
+ this.activeBladeCount = 0;
484
+ }
485
+ /**
486
+ * Switches grass density between `'off'`, `'low'`, and `'high'` without reallocating GPU buffers.
487
+ */
488
+ setDensity(density) {
489
+ this._density = density;
490
+ if (density === 'off') {
491
+ this._activeGridDim = 0;
492
+ this.mesh.count = 0;
493
+ this.mesh.visible = false;
494
+ this.activeBladeCount = 0;
495
+ this._lastCenterGx = INVALID_CELL;
496
+ this._lastCenterGz = INVALID_CELL;
497
+ return;
498
+ }
499
+ this._activeGridDim = density === 'high' ? this._highGridDim : this._lowGridDim;
500
+ this._cellSize = (this.radius * 2) / this._activeGridDim;
501
+ this.mesh.count = this._activeGridDim * this._activeGridDim;
502
+ this.mesh.visible = true;
503
+ this._fullRefreshPending = true;
504
+ this._lastCenterGx = INVALID_CELL;
505
+ this._lastCenterGz = INVALID_CELL;
506
+ this._slotCellX.fill(INVALID_CELL);
507
+ this._slotCellZ.fill(INVALID_CELL);
508
+ this._slotActive.fill(0);
509
+ this.activeBladeCount = 0;
510
+ }
511
+ /**
512
+ * Marks all grass slots dirty so the next `update()` re-samples terrain heights & surface blocks
513
+ * (e.g. after world seed reset).
514
+ */
515
+ markDirty() {
516
+ this._fullRefreshPending = true;
517
+ this._slotCellX.fill(INVALID_CELL);
518
+ this._slotCellZ.fill(INVALID_CELL);
519
+ this._slotActive.fill(0);
520
+ this.activeBladeCount = 0;
521
+ }
522
+ /**
523
+ * Invalidates only the grass slots within `radiusMeters` of `(worldX, worldZ)` so mined craters
524
+ * or newly placed blocks immediately clear/re-seat nearby blades on the next `update()`.
525
+ */
526
+ invalidateArea(worldX, worldZ, radiusMeters = 2.0) {
527
+ if (this._density === 'off' || this._activeGridDim <= 0)
528
+ return;
529
+ const gridDim = this._activeGridDim;
530
+ const invCell = 1 / this._cellSize;
531
+ const pad = Math.max(1, Math.ceil(radiusMeters * invCell) + 1);
532
+ const cgx = Math.floor(worldX * invCell);
533
+ const cgz = Math.floor(worldZ * invCell);
534
+ for (let dz = -pad; dz <= pad; dz++) {
535
+ const gz = cgz + dz;
536
+ const tz = posMod(gz, gridDim);
537
+ for (let dx = -pad; dx <= pad; dx++) {
538
+ const gx = cgx + dx;
539
+ const tx = posMod(gx, gridDim);
540
+ const slot = tz * gridDim + tx;
541
+ if (this._slotCellX[slot] === gx && this._slotCellZ[slot] === gz) {
542
+ this._slotCellX[slot] = INVALID_CELL;
543
+ this._slotCellZ[slot] = INVALID_CELL;
544
+ if (this._slotActive[slot] === 1) {
545
+ this._slotActive[slot] = 0;
546
+ this.activeBladeCount = Math.max(0, this.activeBladeCount - 1);
547
+ }
548
+ }
549
+ }
550
+ }
551
+ this._fullRefreshPending = true;
552
+ }
553
+ /**
554
+ * Updates atmospheric lighting & fog uniforms to match sky/weather presets.
555
+ */
556
+ applyAtmosphere(options) {
557
+ const u = this.material.uniforms;
558
+ if (options.sunDir) {
559
+ u.uSunDir.value.set(options.sunDir.x, options.sunDir.y, options.sunDir.z).normalize();
560
+ }
561
+ if (options.sunColor !== undefined) {
562
+ u.uSunColor.value.set(options.sunColor);
563
+ }
564
+ if (options.shadowColor !== undefined) {
565
+ u.uShadowColor.value.set(options.shadowColor);
566
+ }
567
+ if (options.fogEnabled !== undefined) {
568
+ u.uFogEnabled.value = options.fogEnabled ? 1.0 : 0.0;
569
+ }
570
+ if (options.fogColor !== undefined) {
571
+ u.uFogColor.value.set(options.fogColor);
572
+ }
573
+ if (options.fogNear !== undefined) {
574
+ u.uFogNear.value = options.fogNear;
575
+ }
576
+ if (options.fogFar !== undefined) {
577
+ u.uFogFar.value = options.fogFar;
578
+ }
579
+ this.material.uniformsNeedUpdate = true;
580
+ }
581
+ /**
582
+ * Zero-allocation per-frame update:
583
+ * - Advances wind animation time (`uTime`) & syncs `uCameraPos` + shared `VolumeWakeField` uniforms.
584
+ * - Recycles & re-seats only the newly entered toroidal ring cells when the camera moves across cell boundaries.
585
+ * Returns the number of blade instances re-seated during this frame.
586
+ */
587
+ update(cameraPos, elapsedTime) {
588
+ this.reseatedLastUpdate = 0;
589
+ if (this._density === 'off' || this._activeGridDim <= 0) {
590
+ this.mesh.visible = false;
591
+ this.mesh.count = 0;
592
+ return 0;
593
+ }
594
+ const u = this.material.uniforms;
595
+ u.uTime.value = elapsedTime;
596
+ u.uCameraPos.value.set(cameraPos.x, cameraPos.y, cameraPos.z);
597
+ if (this.wakeField) {
598
+ u.uWakeEnabled.value = 1.0;
599
+ this.wakeField.syncUniforms(u);
600
+ }
601
+ else {
602
+ u.uWakeEnabled.value = 0.0;
603
+ }
604
+ this.material.uniformsNeedUpdate = true;
605
+ const gridDim = this._activeGridDim;
606
+ const cellSize = this._cellSize;
607
+ const centerGx = Math.floor(cameraPos.x / cellSize);
608
+ const centerGz = Math.floor(cameraPos.z / cellSize);
609
+ if (!this._fullRefreshPending &&
610
+ centerGx === this._lastCenterGx &&
611
+ centerGz === this._lastCenterGz) {
612
+ return 0;
613
+ }
614
+ const halfGrid = Math.floor(gridDim / 2);
615
+ const minGx = centerGx - halfGrid;
616
+ const minGz = centerGz - halfGrid;
617
+ const matArr = this.mesh.instanceMatrix.array;
618
+ const colArr = this.mesh.instanceColor ? this.mesh.instanceColor.array : null;
619
+ const sample = this._scratchSample;
620
+ const seed = this._seed;
621
+ let reseated = 0;
622
+ for (let dz = 0; dz < gridDim; dz++) {
623
+ const gz = minGz + dz;
624
+ const tz = posMod(gz, gridDim);
625
+ const rowOffset = tz * gridDim;
626
+ for (let dx = 0; dx < gridDim; dx++) {
627
+ const gx = minGx + dx;
628
+ const tx = posMod(gx, gridDim);
629
+ const slot = rowOffset + tx;
630
+ if (this._slotCellX[slot] === gx && this._slotCellZ[slot] === gz) {
631
+ continue;
632
+ }
633
+ const prevActive = this._slotActive[slot];
634
+ this._slotCellX[slot] = gx;
635
+ this._slotCellZ[slot] = gz;
636
+ // Deterministic jittered world coordinates inside cell (gx, gz)
637
+ const jx = hash2D(gx, gz, seed ^ 0x1a2b3c);
638
+ const jz = hash2D(gx, gz, seed ^ 0x4d5e6f);
639
+ const wx = (gx + 0.12 + jx * 0.76) * cellSize;
640
+ const wz = (gz + 0.12 + jz * 0.76) * cellSize;
641
+ this._sampleSurface(wx, wz, sample);
642
+ const mOff = slot * 16;
643
+ if (sample.isGrass) {
644
+ const yaw = hash2D(gx, gz, seed ^ 0x718293) * Math.PI * 2;
645
+ const hScale = 0.72 + hash2D(gx, gz, seed ^ 0x938271) * 0.68;
646
+ const wScale = 0.82 + hash2D(gx, gz, seed ^ 0x55aa33) * 0.42;
647
+ const cosY = Math.cos(yaw);
648
+ const sinY = Math.sin(yaw);
649
+ // Direct column-major TRS matrix write (scale(wScale, hScale, wScale) * rotY(yaw) * translate(wx, y, wz))
650
+ matArr[mOff] = cosY * wScale;
651
+ matArr[mOff + 1] = 0;
652
+ matArr[mOff + 2] = -sinY * wScale;
653
+ matArr[mOff + 3] = 0;
654
+ matArr[mOff + 4] = 0;
655
+ matArr[mOff + 5] = hScale;
656
+ matArr[mOff + 6] = 0;
657
+ matArr[mOff + 7] = 0;
658
+ matArr[mOff + 8] = sinY * wScale;
659
+ matArr[mOff + 9] = 0;
660
+ matArr[mOff + 10] = cosY * wScale;
661
+ matArr[mOff + 11] = 0;
662
+ matArr[mOff + 12] = wx;
663
+ matArr[mOff + 13] = sample.y - 0.01;
664
+ matArr[mOff + 14] = wz;
665
+ matArr[mOff + 15] = 1;
666
+ if (colArr) {
667
+ const shade = 0.84 + hash2D(gx, gz, seed ^ 0x2468ac) * 0.30;
668
+ const cOff = slot * 3;
669
+ colArr[cOff] = sample.tintR * shade;
670
+ colArr[cOff + 1] = sample.tintG * shade;
671
+ colArr[cOff + 2] = sample.tintB * shade;
672
+ }
673
+ if (prevActive === 0) {
674
+ this._slotActive[slot] = 1;
675
+ this.activeBladeCount++;
676
+ }
677
+ }
678
+ else {
679
+ // Collapse non-grass slot to zero scale cleanly with zero rasterization cost
680
+ matArr[mOff] = 0;
681
+ matArr[mOff + 1] = 0;
682
+ matArr[mOff + 2] = 0;
683
+ matArr[mOff + 3] = 0;
684
+ matArr[mOff + 4] = 0;
685
+ matArr[mOff + 5] = 0;
686
+ matArr[mOff + 6] = 0;
687
+ matArr[mOff + 7] = 0;
688
+ matArr[mOff + 8] = 0;
689
+ matArr[mOff + 9] = 0;
690
+ matArr[mOff + 10] = 0;
691
+ matArr[mOff + 11] = 0;
692
+ matArr[mOff + 12] = wx;
693
+ matArr[mOff + 13] = -9999;
694
+ matArr[mOff + 14] = wz;
695
+ matArr[mOff + 15] = 1;
696
+ if (prevActive === 1) {
697
+ this._slotActive[slot] = 0;
698
+ this.activeBladeCount = Math.max(0, this.activeBladeCount - 1);
699
+ }
700
+ }
701
+ reseated++;
702
+ }
703
+ }
704
+ this._lastCenterGx = centerGx;
705
+ this._lastCenterGz = centerGz;
706
+ this._fullRefreshPending = false;
707
+ if (reseated > 0) {
708
+ this.mesh.instanceMatrix.needsUpdate = true;
709
+ if (this.mesh.instanceColor) {
710
+ this.mesh.instanceColor.needsUpdate = true;
711
+ }
712
+ this.reseatedLastUpdate = reseated;
713
+ this.totalReseated += reseated;
714
+ }
715
+ return reseated;
716
+ }
717
+ dispose() {
718
+ this.geometry.dispose();
719
+ this.material.dispose();
720
+ this.mesh.dispose();
721
+ }
722
+ }
723
+ //# sourceMappingURL=GrassFieldSystem.js.map