@hello-terrain/three 0.0.0-alpha.3 → 0.0.0-alpha.5

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.
package/dist/index.mjs CHANGED
@@ -1,30 +1,24 @@
1
- import * as THREE from 'three';
2
- import { BufferGeometry, BufferAttribute } from 'three';
3
- import { Fn, int, vertexIndex, uv, float } from 'three/tsl';
1
+ import { BufferGeometry, BufferAttribute, Vector3 as Vector3$1 } from 'three';
2
+ import { MeshStandardNodeMaterial, InstancedMesh, InstancedBufferAttribute, StorageBufferAttribute, Vector3 } from 'three/webgpu';
3
+ import { param, task, graph } from '@hello-terrain/work';
4
+ import { uniform, Fn, float, globalId, int, vec2, uint, workgroupBarrier, If, instanceIndex, min, max, pow, vec3, storage, packHalf2x16, remap, dot, vertexIndex, uv, select, positionLocal, unpackHalf2x16, normalLocal, varyingProperty, mx_noise_float, Loop, mix } from 'three/tsl';
5
+ import { Fn as Fn$1 } from 'three/src/nodes/TSL.js';
4
6
 
5
7
  class TerrainGeometry extends BufferGeometry {
6
8
  constructor(innerSegments = 14, extendUV = false) {
7
9
  super();
8
10
  if (innerSegments < 1 || !Number.isFinite(innerSegments) || !Number.isInteger(innerSegments)) {
9
- throw new Error(
10
- `Invalid innerSegments: ${innerSegments}. Must be a positive integer.`
11
- );
11
+ throw new Error(`Invalid innerSegments: ${innerSegments}. Must be a positive integer.`);
12
12
  }
13
13
  try {
14
14
  this.setIndex(this.generateIndices(innerSegments));
15
15
  this.setAttribute(
16
16
  "position",
17
- new BufferAttribute(
18
- new Float32Array(this.generatePositions(innerSegments)),
19
- 3
20
- )
17
+ new BufferAttribute(new Float32Array(this.generatePositions(innerSegments)), 3)
21
18
  );
22
19
  this.setAttribute(
23
20
  "normal",
24
- new BufferAttribute(
25
- new Float32Array(this.generateNormals(innerSegments)),
26
- 3
27
- )
21
+ new BufferAttribute(new Float32Array(this.generateNormals(innerSegments)), 3)
28
22
  );
29
23
  this.setAttribute(
30
24
  "uv",
@@ -214,501 +208,1288 @@ class TerrainGeometry extends BufferGeometry {
214
208
  }
215
209
  }
216
210
 
217
- const isSkirtVertex = Fn(([segments]) => {
218
- const segmentsNode = typeof segments === "number" ? int(segments) : segments;
219
- const vIndex = int(vertexIndex);
220
- const segmentEdges = int(segmentsNode.add(3));
221
- const vx = vIndex.mod(segmentEdges);
222
- const vy = vIndex.div(segmentEdges);
223
- const last = segmentEdges.sub(int(1));
224
- return vx.equal(int(0)).or(vx.equal(last)).or(vy.equal(int(0))).or(vy.equal(last));
225
- });
226
- const isSkirtUV = Fn(([segments]) => {
227
- const segmentsNode = typeof segments === "number" ? int(segments) : segments;
228
- const ux = uv().x;
229
- const uy = uv().y;
230
- const segmentCount = segmentsNode.add(2);
231
- const segmentStep = float(1).div(segmentCount);
232
- const innerX = ux.greaterThan(segmentStep).and(ux.lessThan(segmentStep.oneMinus()));
233
- const innerY = uy.greaterThan(segmentStep).and(uy.lessThan(segmentStep.oneMinus()));
234
- return innerX.and(innerY).not();
235
- });
236
-
237
- const CHILDREN_STRIDE = 4;
238
- const NEIGHBORS_STRIDE = 4;
239
- const NODE_STRIDE = 4;
240
- const U_INT_16_MAX_VALUE = 65535;
241
- const EMPTY_SENTINEL_VALUE = U_INT_16_MAX_VALUE;
242
- class QuadtreeNodeView {
243
- maxNodeCount;
244
- childrenIndicesBuffer;
245
- neighborsIndicesBuffer;
246
- nodeBuffer;
247
- leafNodeMask;
248
- leafNodeCountBuffer;
249
- activeLeafIndices;
250
- activeLeafCount = 0;
251
- constructor(maxNodeCount, childrenIndicesBuffer, neighborsIndicesBuffer, nodeBuffer, leafNodeMask, leafNodeCountBuffer) {
252
- this.maxNodeCount = maxNodeCount;
253
- this.childrenIndicesBuffer = childrenIndicesBuffer ?? new Uint16Array(CHILDREN_STRIDE * maxNodeCount);
254
- this.neighborsIndicesBuffer = neighborsIndicesBuffer ?? new Uint16Array(NEIGHBORS_STRIDE * maxNodeCount);
255
- this.nodeBuffer = nodeBuffer ?? new Int32Array(NODE_STRIDE * maxNodeCount);
256
- this.leafNodeMask = leafNodeMask ?? new Uint8Array(maxNodeCount);
257
- this.leafNodeCountBuffer = leafNodeCountBuffer ?? new Uint16Array(1);
258
- this.activeLeafIndices = new Uint16Array(maxNodeCount);
259
- this.clear();
260
- }
261
- /**
262
- * Clear all buffers
263
- */
264
- clear() {
265
- this.nodeBuffer.fill(0);
266
- this.childrenIndicesBuffer.fill(EMPTY_SENTINEL_VALUE);
267
- this.neighborsIndicesBuffer.fill(EMPTY_SENTINEL_VALUE);
268
- this.leafNodeMask.fill(0);
269
- this.leafNodeCountBuffer[0] = 0;
270
- this.activeLeafCount = 0;
271
- }
272
- /**
273
- * Get buffer references for direct access (useful for GPU operations)
274
- */
275
- getBuffers() {
276
- return {
277
- childrenIndicesBuffer: this.childrenIndicesBuffer,
278
- neighborsIndicesBuffer: this.neighborsIndicesBuffer,
279
- nodeBuffer: this.nodeBuffer,
280
- leafNodeMask: this.leafNodeMask
281
- };
282
- }
283
- /**
284
- * Get the maximum node count
285
- */
286
- getMaxNodeCount() {
287
- return this.maxNodeCount;
288
- }
289
- // Getters for individual buffer values
290
- getLevel(index) {
291
- return this.nodeBuffer[index * NODE_STRIDE];
211
+ const defaultTerrainMeshParams = {
212
+ innerTileSegments: 14,
213
+ maxNodes: 1024,
214
+ material: new MeshStandardNodeMaterial()
215
+ };
216
+ class TerrainMesh extends InstancedMesh {
217
+ _innerTileSegments;
218
+ _maxNodes;
219
+ constructor(params = defaultTerrainMeshParams) {
220
+ const mergedParams = { ...defaultTerrainMeshParams, ...params };
221
+ const { innerTileSegments, maxNodes, material } = mergedParams;
222
+ const geometry = new TerrainGeometry(innerTileSegments, true);
223
+ super(geometry, material, maxNodes);
224
+ this.frustumCulled = false;
225
+ this._innerTileSegments = innerTileSegments;
226
+ this._maxNodes = maxNodes;
292
227
  }
293
- getX(index) {
294
- return this.nodeBuffer[index * NODE_STRIDE + 1];
228
+ get innerTileSegments() {
229
+ return this._innerTileSegments;
295
230
  }
296
- getY(index) {
297
- return this.nodeBuffer[index * NODE_STRIDE + 2];
231
+ set innerTileSegments(tileSegments) {
232
+ const oldGeometry = this.geometry;
233
+ this.geometry = new TerrainGeometry(tileSegments, true);
234
+ this._innerTileSegments = tileSegments;
235
+ setTimeout(oldGeometry.dispose);
298
236
  }
299
- getLeafNodeCount() {
300
- return this.leafNodeCountBuffer[0];
237
+ get maxNodes() {
238
+ return this._maxNodes;
301
239
  }
302
- getLeaf(index) {
303
- return this.leafNodeMask[index] === 1;
304
- }
305
- getChildren(index) {
306
- const offset = index * CHILDREN_STRIDE;
307
- return [
308
- this.childrenIndicesBuffer[offset],
309
- this.childrenIndicesBuffer[offset + 1],
310
- this.childrenIndicesBuffer[offset + 2],
311
- this.childrenIndicesBuffer[offset + 3]
312
- ];
313
- }
314
- getNeighbors(index) {
315
- const offset = index * NEIGHBORS_STRIDE;
316
- return [
317
- this.neighborsIndicesBuffer[offset],
318
- this.neighborsIndicesBuffer[offset + 1],
319
- this.neighborsIndicesBuffer[offset + 2],
320
- this.neighborsIndicesBuffer[offset + 3]
321
- ];
322
- }
323
- // Setters for individual buffer values
324
- setLevel(index, level) {
325
- this.nodeBuffer[index * NODE_STRIDE] = level;
326
- }
327
- setX(index, x) {
328
- this.nodeBuffer[index * NODE_STRIDE + 1] = x;
329
- }
330
- setY(index, y) {
331
- this.nodeBuffer[index * NODE_STRIDE + 2] = y;
332
- }
333
- setLeaf(index, leaf) {
334
- const wasLeaf = this.leafNodeMask[index] === 1;
335
- const newValue = leaf ? 1 : 0;
336
- if (leaf && !wasLeaf) {
337
- this.leafNodeCountBuffer[0]++;
338
- this.leafNodeMask[index] = 1;
339
- this.activeLeafIndices[this.activeLeafCount] = index;
340
- this.activeLeafCount++;
341
- this.setChildren(index, [
342
- EMPTY_SENTINEL_VALUE,
343
- EMPTY_SENTINEL_VALUE,
344
- EMPTY_SENTINEL_VALUE,
345
- EMPTY_SENTINEL_VALUE
346
- ]);
347
- } else if (!leaf && wasLeaf) {
348
- this.leafNodeCountBuffer[0]--;
349
- this.leafNodeMask[index] = 0;
240
+ set maxNodes(maxNodes) {
241
+ if (!Number.isInteger(maxNodes) || maxNodes < 1) {
242
+ throw new Error(`Invalid maxNodes: ${maxNodes}. Must be a positive integer.`);
243
+ }
244
+ if (maxNodes === this._maxNodes) return;
245
+ const oldMax = this._maxNodes;
246
+ const nextMatrix = new Float32Array(maxNodes * 16);
247
+ const oldMatrixArray = this.instanceMatrix.array;
248
+ nextMatrix.set(oldMatrixArray.subarray(0, Math.min(oldMatrixArray.length, nextMatrix.length)));
249
+ this.instanceMatrix = new InstancedBufferAttribute(nextMatrix, 16);
250
+ if (this.instanceColor) {
251
+ const itemSize = this.instanceColor.itemSize;
252
+ const nextColor = new Float32Array(maxNodes * itemSize);
253
+ const oldColorArray = this.instanceColor.array;
254
+ nextColor.set(oldColorArray.subarray(0, Math.min(oldColorArray.length, nextColor.length)));
255
+ this.instanceColor = new InstancedBufferAttribute(nextColor, itemSize);
256
+ }
257
+ this._maxNodes = maxNodes;
258
+ this.count = Math.min(this.count, maxNodes);
259
+ this.instanceMatrix.needsUpdate = true;
260
+ if (this.instanceColor) this.instanceColor.needsUpdate = true;
261
+ if (maxNodes < oldMax && this.count >= maxNodes) {
262
+ this.count = maxNodes;
350
263
  }
351
- this.nodeBuffer[index * NODE_STRIDE + 3] = newValue;
352
- }
353
- setChildren(index, children) {
354
- const offset = index * CHILDREN_STRIDE;
355
- this.childrenIndicesBuffer[offset] = children[0];
356
- this.childrenIndicesBuffer[offset + 1] = children[1];
357
- this.childrenIndicesBuffer[offset + 2] = children[2];
358
- this.childrenIndicesBuffer[offset + 3] = children[3];
359
- }
360
- setNeighbors(index, neighbors) {
361
- const offset = index * NEIGHBORS_STRIDE;
362
- this.neighborsIndicesBuffer[offset] = neighbors[0];
363
- this.neighborsIndicesBuffer[offset + 1] = neighbors[1];
364
- this.neighborsIndicesBuffer[offset + 2] = neighbors[2];
365
- this.neighborsIndicesBuffer[offset + 3] = neighbors[3];
366
- }
367
- /**
368
- * Get array of active leaf node indices with count (zero-copy, no allocation)
369
- */
370
- getActiveLeafNodeIndices() {
371
- return {
372
- indices: this.activeLeafIndices,
373
- count: this.activeLeafCount
374
- };
375
264
  }
376
- /**
377
- * Release internal buffers and mark this view as destroyed
378
- */
379
- destroy() {
380
- this.childrenIndicesBuffer = new Uint16Array(0);
381
- this.neighborsIndicesBuffer = new Uint16Array(0);
382
- this.nodeBuffer = new Int32Array(0);
383
- this.leafNodeMask = new Uint8Array(0);
384
- this.leafNodeCountBuffer = new Uint16Array(0);
385
- this.maxNodeCount = 0;
265
+ }
266
+
267
+ const WORKGROUP_X = 16;
268
+ const WORKGROUP_Y = 16;
269
+ function compileComputePipeline(stages, width, bindings) {
270
+ const workgroupSize = [WORKGROUP_X, WORKGROUP_Y, 1];
271
+ const dispatchX = Math.ceil(width / WORKGROUP_X);
272
+ const dispatchY = Math.ceil(width / WORKGROUP_Y);
273
+ const uInstanceCount = uniform(0, "uint");
274
+ const computeShader = Fn(() => {
275
+ const fWidth = float(width);
276
+ const activeIndex = globalId.z;
277
+ const nodeIndex = int(activeIndex).toVar();
278
+ const iWidth = int(width);
279
+ const ix = int(globalId.x);
280
+ const iy = int(globalId.y);
281
+ const texelSize = vec2(1, 1).div(fWidth);
282
+ const localCoordinates = vec2(globalId.x, globalId.y);
283
+ const localUVCoords = localCoordinates.div(fWidth);
284
+ const verticesPerNode = iWidth.mul(iWidth);
285
+ const globalIndex = int(nodeIndex).mul(verticesPerNode).add(iy.mul(iWidth).add(ix));
286
+ const inBounds = ix.lessThan(iWidth).and(iy.lessThan(iWidth)).and(uint(activeIndex).lessThan(uInstanceCount)).toVar();
287
+ for (let i = 0; i < stages.length; i++) {
288
+ if (i > 0) {
289
+ workgroupBarrier();
290
+ }
291
+ If(inBounds, () => {
292
+ stages[i](nodeIndex, globalIndex, localUVCoords, localCoordinates, texelSize);
293
+ });
294
+ }
295
+ })().computeKernel(workgroupSize);
296
+ function execute(renderer, instanceCount) {
297
+ uInstanceCount.value = instanceCount;
298
+ renderer.compute(computeShader, [dispatchX, dispatchY, instanceCount]);
386
299
  }
387
- clone() {
388
- return new QuadtreeNodeView(
389
- this.maxNodeCount,
390
- this.childrenIndicesBuffer,
391
- this.neighborsIndicesBuffer,
392
- this.nodeBuffer,
393
- this.leafNodeMask,
394
- this.leafNodeCountBuffer
300
+ return { execute };
301
+ }
302
+
303
+ const createElevation = (tile, uniforms, elevationFn) => {
304
+ return function perVertexElevation(nodeIndex, localCoordinates) {
305
+ const ix = int(localCoordinates.x);
306
+ const iy = int(localCoordinates.y);
307
+ const edgeVertexCount = uniforms.uInnerTileSegments.toVar().add(int(3));
308
+ const tileUV = localCoordinates.toFloat().div(edgeVertexCount.toFloat());
309
+ const rootUV = tile.rootUVCompute(nodeIndex, ix, iy);
310
+ const worldPosition = tile.tileVertexWorldPositionCompute(nodeIndex, ix, iy).setName("worldPositionWithSkirt");
311
+ const rootSize = uniforms.uRootSize.toVar();
312
+ return elevationFn({
313
+ worldPosition,
314
+ rootSize,
315
+ rootUV,
316
+ tileOriginVec2: tile.tileOriginVec2(nodeIndex),
317
+ tileSize: tile.tileSize(nodeIndex),
318
+ tileLevel: tile.tileLevel(nodeIndex),
319
+ nodeIndex: int(nodeIndex),
320
+ tileUV
321
+ });
322
+ };
323
+ };
324
+ const readElevationFieldAtPositionLocal = (elevationFieldBuffer, edgeVertexCount, positionLocal) => Fn(() => {
325
+ const nodeIndex = int(instanceIndex);
326
+ const intEdge = int(edgeVertexCount);
327
+ const innerSegments = int(edgeVertexCount).sub(3);
328
+ const fInnerSegments = float(innerSegments);
329
+ const last = intEdge.sub(int(1));
330
+ const u = positionLocal.x.add(float(0.5));
331
+ const v = positionLocal.z.add(float(0.5));
332
+ const x = u.mul(fInnerSegments).round().toInt().add(int(1));
333
+ const y = v.mul(fInnerSegments).round().toInt().add(int(1));
334
+ const xClamped = min(max(x, int(0)), last);
335
+ const yClamped = min(max(y, int(0)), last);
336
+ const verticesPerNode = intEdge.mul(intEdge);
337
+ const perNodeVertexIndex = yClamped.mul(intEdge).add(xClamped);
338
+ const globalVertexIndex = nodeIndex.mul(verticesPerNode).add(perNodeVertexIndex);
339
+ return elevationFieldBuffer.element(globalVertexIndex);
340
+ });
341
+
342
+ function createTileCompute(leafStorage, uniforms) {
343
+ const tileLevel = Fn(([nodeIndex]) => {
344
+ const nodeOffset = nodeIndex.mul(int(4));
345
+ return leafStorage.node.element(nodeOffset).toInt();
346
+ });
347
+ const tileOriginVec2 = Fn(([nodeIndex]) => {
348
+ const nodeOffset = nodeIndex.mul(int(4));
349
+ const nodeX = leafStorage.node.element(nodeOffset.add(int(1))).toFloat();
350
+ const nodeY = leafStorage.node.element(nodeOffset.add(int(2))).toFloat();
351
+ return vec2(nodeX, nodeY);
352
+ });
353
+ const tileSize = Fn(([nodeIndex]) => {
354
+ const rootSize = uniforms.uRootSize.toVar();
355
+ const level = tileLevel(nodeIndex);
356
+ return float(rootSize).div(pow(float(2), level.toFloat()));
357
+ });
358
+ const rootUVCompute = Fn(([nodeIndex, ix, iy]) => {
359
+ const nodeVec2 = tileOriginVec2(nodeIndex);
360
+ const nodeX = nodeVec2.x;
361
+ const nodeY = nodeVec2.y;
362
+ const rootSize = uniforms.uRootSize.toVar();
363
+ const rootOrigin = uniforms.uRootOrigin.toVar();
364
+ const size = tileSize(nodeIndex);
365
+ const half = float(0.5);
366
+ const halfRoot = float(rootSize).mul(half);
367
+ const fInnerSegments = uniforms.uInnerTileSegments.toVar().toFloat();
368
+ const texelSpacing = size.div(fInnerSegments);
369
+ const absX = nodeX.mul(fInnerSegments).add(int(ix).toFloat().sub(float(1)));
370
+ const absY = nodeY.mul(fInnerSegments).add(int(iy).toFloat().sub(float(1)));
371
+ const worldX = rootOrigin.x.add(absX.mul(texelSpacing)).sub(halfRoot);
372
+ const worldZ = rootOrigin.z.add(absY.mul(texelSpacing)).sub(halfRoot);
373
+ const centeredX = worldX.sub(rootOrigin.x);
374
+ const centeredZ = worldZ.sub(rootOrigin.z);
375
+ return vec2(
376
+ centeredX.div(rootSize).add(half),
377
+ centeredZ.div(rootSize).mul(float(-1)).add(half)
395
378
  );
379
+ });
380
+ const tileVertexWorldPositionCompute = Fn(
381
+ ([nodeIndex, ix, iy]) => {
382
+ const rootOrigin = uniforms.uRootOrigin.toVar();
383
+ const nodeVec2 = tileOriginVec2(nodeIndex);
384
+ const nodeX = nodeVec2.x;
385
+ const nodeY = nodeVec2.y;
386
+ const rootSize = uniforms.uRootSize.toVar();
387
+ const size = tileSize(nodeIndex);
388
+ const half = float(0.5);
389
+ const halfRoot = float(rootSize).mul(half);
390
+ const fInnerSegments = uniforms.uInnerTileSegments.toVar().toFloat();
391
+ const texelSpacing = size.div(fInnerSegments);
392
+ const absX = nodeX.mul(fInnerSegments).add(int(ix).toFloat().sub(float(1)));
393
+ const absY = nodeY.mul(fInnerSegments).add(int(iy).toFloat().sub(float(1)));
394
+ const worldX = rootOrigin.x.add(absX.mul(texelSpacing)).sub(halfRoot);
395
+ const worldZ = rootOrigin.z.add(absY.mul(texelSpacing)).sub(halfRoot);
396
+ return vec3(worldX, rootOrigin.y, worldZ);
397
+ }
398
+ );
399
+ return {
400
+ tileLevel,
401
+ tileOriginVec2,
402
+ tileSize,
403
+ rootUVCompute,
404
+ tileVertexWorldPositionCompute
405
+ };
406
+ }
407
+
408
+ const rootSize = param(256).displayName("rootSize");
409
+ const origin = param({
410
+ x: 0,
411
+ y: 0,
412
+ z: 0
413
+ }).displayName("origin");
414
+ const innerTileSegments = param(13).displayName("innerTileSegments");
415
+ const skirtScale = param(100).displayName("skirtScale");
416
+ const elevationScale = param(1).displayName("elevationScale");
417
+ const maxNodes = param(1024).displayName("maxNodes");
418
+ const maxLevel = param(16).displayName("maxLevel");
419
+ const quadtreeUpdate = param({
420
+ cameraOrigin: { x: 0, y: 0, z: 0 },
421
+ mode: "distance",
422
+ distanceFactor: 1.5
423
+ }).displayName("quadtreeUpdate");
424
+ const surface = param(null).displayName("surface");
425
+ const elevationFn = param(() => float(0));
426
+
427
+ function createLeafStorage(maxNodes) {
428
+ const data = new Int32Array(maxNodes * 4);
429
+ const attribute = new StorageBufferAttribute(data, 4);
430
+ const node = storage(attribute, "i32", 1).toReadOnly().setName("leafStorage");
431
+ return { data, attribute, node };
432
+ }
433
+
434
+ const Dir = {
435
+ LEFT: 0,
436
+ RIGHT: 1,
437
+ TOP: 2,
438
+ BOTTOM: 3
439
+ };
440
+ const U32_EMPTY = 4294967295;
441
+ function allocLeafSet(capacity) {
442
+ return {
443
+ capacity,
444
+ count: 0,
445
+ space: new Uint8Array(capacity),
446
+ level: new Uint8Array(capacity),
447
+ x: new Int32Array(capacity),
448
+ y: new Int32Array(capacity)
449
+ };
450
+ }
451
+ function resetLeafSet(leaves) {
452
+ leaves.count = 0;
453
+ }
454
+ function allocSeamTable(capacity) {
455
+ return {
456
+ capacity,
457
+ count: 0,
458
+ stride: 8,
459
+ neighbors: new Uint32Array(capacity * 8)
460
+ };
461
+ }
462
+ function resetSeamTable(seams) {
463
+ seams.count = 0;
464
+ }
465
+
466
+ function createNodeStore(maxNodes, spaceCount) {
467
+ return {
468
+ maxNodes,
469
+ nodesUsed: 0,
470
+ currentGen: 1,
471
+ gen: new Uint16Array(maxNodes),
472
+ space: new Uint8Array(maxNodes),
473
+ level: new Uint8Array(maxNodes),
474
+ x: new Int32Array(maxNodes),
475
+ y: new Int32Array(maxNodes),
476
+ firstChild: new Uint32Array(maxNodes),
477
+ flags: new Uint8Array(maxNodes),
478
+ roots: new Uint32Array(spaceCount)
479
+ };
480
+ }
481
+ function beginFrame(store) {
482
+ store.nodesUsed = 0;
483
+ store.currentGen = store.currentGen + 1 & 65535;
484
+ if (store.currentGen === 0) {
485
+ store.gen.fill(0);
486
+ store.currentGen = 1;
396
487
  }
397
488
  }
489
+ function allocNode(store, tile) {
490
+ const id = store.nodesUsed;
491
+ if (id >= store.maxNodes) return U32_EMPTY;
492
+ store.nodesUsed = id + 1;
493
+ store.gen[id] = store.currentGen;
494
+ store.space[id] = tile.space;
495
+ store.level[id] = tile.level;
496
+ store.x[id] = tile.x;
497
+ store.y[id] = tile.y;
498
+ store.firstChild[id] = U32_EMPTY;
499
+ store.flags[id] = 0;
500
+ return id;
501
+ }
502
+ function hasChildren(store, nodeId) {
503
+ return store.firstChild[nodeId] !== U32_EMPTY;
504
+ }
505
+ function ensureChildren(store, parentId) {
506
+ const existing = store.firstChild[parentId];
507
+ if (existing !== U32_EMPTY) return existing;
508
+ const childBase = store.nodesUsed;
509
+ if (childBase + 4 > store.maxNodes) return U32_EMPTY;
510
+ const space = store.space[parentId];
511
+ const level = store.level[parentId] + 1;
512
+ const px = store.x[parentId] << 1;
513
+ const py = store.y[parentId] << 1;
514
+ allocNode(store, { space, level, x: px, y: py });
515
+ allocNode(store, { space, level, x: px + 1, y: py });
516
+ allocNode(store, { space, level, x: px, y: py + 1 });
517
+ allocNode(store, { space, level, x: px + 1, y: py + 1 });
518
+ store.firstChild[parentId] = childBase;
519
+ return childBase;
520
+ }
398
521
 
399
- function distanceBasedSubdivision(factor = 2) {
400
- return (ctx) => {
401
- if (ctx.nodeSize <= ctx.minNodeSize) {
402
- return false;
403
- }
404
- return ctx.distance < ctx.nodeSize * factor;
522
+ function nextPow2(n) {
523
+ let x = 1;
524
+ while (x < n) x <<= 1;
525
+ return x;
526
+ }
527
+ function mix32(x) {
528
+ x >>>= 0;
529
+ x ^= x >>> 16;
530
+ x = Math.imul(x, 2146121005) >>> 0;
531
+ x ^= x >>> 15;
532
+ x = Math.imul(x, 2221713035) >>> 0;
533
+ x ^= x >>> 16;
534
+ return x >>> 0;
535
+ }
536
+ function hashKey(space, level, x, y) {
537
+ const h = space & 255 ^ (level & 255) << 8 ^ mix32(x) >>> 0 ^ mix32(y) >>> 0;
538
+ return mix32(h);
539
+ }
540
+ function createSpatialIndex(maxEntries) {
541
+ const size = nextPow2(Math.max(2, maxEntries * 2));
542
+ return {
543
+ size,
544
+ mask: size - 1,
545
+ stampGen: 1,
546
+ stamp: new Uint16Array(size),
547
+ keysSpace: new Uint8Array(size),
548
+ keysLevel: new Uint8Array(size),
549
+ keysX: new Uint32Array(size),
550
+ keysY: new Uint32Array(size),
551
+ values: new Uint32Array(size)
405
552
  };
406
553
  }
407
- function screenSpaceSubdivision(options) {
408
- const targetTrianglePixels = options.targetTrianglePixels ?? 6;
409
- const tileSegments = options.tileSegments ?? 13;
410
- return (ctx) => {
411
- if (ctx.nodeSize <= ctx.minNodeSize) {
412
- return false;
554
+ function resetSpatialIndex(index) {
555
+ index.stampGen = index.stampGen + 1 & 65535;
556
+ if (index.stampGen === 0) {
557
+ index.stamp.fill(0);
558
+ index.stampGen = 1;
559
+ }
560
+ }
561
+ function insertSpatialIndexRaw(index, space, level, x, y, value) {
562
+ const s = space & 255;
563
+ const l = level & 255;
564
+ const xx = x >>> 0;
565
+ const yy = y >>> 0;
566
+ let slot = hashKey(s, l, xx, yy) & index.mask;
567
+ for (let probes = 0; probes < index.size; probes++) {
568
+ if (index.stamp[slot] !== index.stampGen) {
569
+ index.stamp[slot] = index.stampGen;
570
+ index.keysSpace[slot] = s;
571
+ index.keysLevel[slot] = l;
572
+ index.keysX[slot] = xx;
573
+ index.keysY[slot] = yy;
574
+ index.values[slot] = value >>> 0;
575
+ return;
576
+ }
577
+ if (index.keysSpace[slot] === s && index.keysLevel[slot] === l && index.keysX[slot] === xx && index.keysY[slot] === yy) {
578
+ index.values[slot] = value >>> 0;
579
+ return;
413
580
  }
414
- const screenInfo = options.getScreenSpaceInfo();
415
- if (!screenInfo) {
416
- return ctx.distance < ctx.nodeSize * 2;
581
+ slot = slot + 1 & index.mask;
582
+ }
583
+ throw new Error("SpatialIndex is full (no empty slot found).");
584
+ }
585
+ function lookupSpatialIndexRaw(index, space, level, x, y) {
586
+ const s = space & 255;
587
+ const l = level & 255;
588
+ const xx = x >>> 0;
589
+ const yy = y >>> 0;
590
+ let slot = hashKey(s, l, xx, yy) & index.mask;
591
+ for (let probes = 0; probes < index.size; probes++) {
592
+ if (index.stamp[slot] !== index.stampGen) return U32_EMPTY;
593
+ if (index.keysSpace[slot] === s && index.keysLevel[slot] === l && index.keysX[slot] === xx && index.keysY[slot] === yy) {
594
+ return index.values[slot];
417
595
  }
418
- const safeDistance = Math.max(ctx.distance, 1e-3);
419
- const tileScreenSize = ctx.nodeSize / safeDistance * screenInfo.projectionFactor;
420
- const triangleScreenSize = tileScreenSize / tileSegments;
421
- return triangleScreenSize > targetTrianglePixels;
596
+ slot = slot + 1 & index.mask;
597
+ }
598
+ return U32_EMPTY;
599
+ }
600
+
601
+ function buildLeafIndex(leaves, out) {
602
+ const index = out ?? createSpatialIndex(leaves.count);
603
+ resetSpatialIndex(index);
604
+ for (let i = 0; i < leaves.count; i++) {
605
+ insertSpatialIndexRaw(index, leaves.space[i], leaves.level[i], leaves.x[i], leaves.y[i], i);
606
+ }
607
+ return index;
608
+ }
609
+
610
+ function createState(cfg, surface) {
611
+ const store = createNodeStore(cfg.maxNodes, surface.spaceCount);
612
+ const scratchRootTiles = [];
613
+ for (let i = 0; i < surface.maxRootCount; i++) {
614
+ scratchRootTiles.push({ space: 0, level: 0, x: 0, y: 0 });
615
+ }
616
+ return {
617
+ cfg,
618
+ store,
619
+ leaves: allocLeafSet(cfg.maxNodes),
620
+ leafNodeIds: new Uint32Array(cfg.maxNodes),
621
+ leafIndex: createSpatialIndex(cfg.maxNodes),
622
+ stack: new Uint32Array(cfg.maxNodes),
623
+ rootNodeIds: new Uint32Array(surface.maxRootCount),
624
+ rootCount: 0,
625
+ splitQueue: new Uint32Array(cfg.maxNodes),
626
+ splitStamp: new Uint16Array(cfg.maxNodes),
627
+ splitGen: 1,
628
+ scratchTile: { space: 0, level: 0, x: 0, y: 0 },
629
+ scratchNeighbor: { space: 0, level: 0, x: 0, y: 0 },
630
+ scratchBounds: { cx: 0, cy: 0, cz: 0, r: 0 },
631
+ scratchRootTiles,
632
+ spaceCount: surface.spaceCount
422
633
  };
423
634
  }
424
- function computeScreenSpaceInfo(fovY, screenHeight) {
425
- const projectionFactor = screenHeight / (2 * Math.tan(fovY / 2));
426
- return { projectionFactor, screenHeight };
427
- }
428
-
429
- const tempVector3 = new THREE.Vector3();
430
- const tempBox3 = new THREE.Box3();
431
- const tempMin = new THREE.Vector3();
432
- const tempMax = new THREE.Vector3();
433
- class Quadtree {
434
- nodeCount = 0;
435
- deepestLevel = 0;
436
- config;
437
- nodeView;
438
- subdivisionStrategy;
439
- // Pre-allocated buffers to avoid object creation
440
- tempChildIndices = [-1, -1, -1, -1];
441
- tempNeighborIndices = [-1, -1, -1, -1];
442
- /**
443
- * Create a new Quadtree.
444
- *
445
- * @param config Quadtree configuration parameters
446
- * @param subdivisionStrategy Strategy function for subdivision decisions.
447
- * Defaults to distanceBasedSubdivision(2).
448
- * @param nodeView Optional pre-allocated NodeView for buffer reuse
449
- */
450
- constructor(config, subdivisionStrategy, nodeView) {
451
- this.config = config;
452
- this.subdivisionStrategy = subdivisionStrategy ?? distanceBasedSubdivision(2);
453
- this.nodeView = nodeView ?? new QuadtreeNodeView(config.maxNodes);
454
- this.initialize();
635
+ function beginUpdate(state, surface, params) {
636
+ if (surface.spaceCount !== state.spaceCount) {
637
+ throw new Error(
638
+ `Surface spaceCount changed (${state.spaceCount} -> ${surface.spaceCount}). Create a new quadtree state.`
639
+ );
455
640
  }
456
- /**
457
- * Set the subdivision strategy.
458
- * Use this to change LOD behavior at runtime.
459
- *
460
- * @param strategy The subdivision strategy function
461
- */
462
- setSubdivisionStrategy(strategy) {
463
- this.subdivisionStrategy = strategy;
641
+ if (surface.maxRootCount !== state.rootNodeIds.length) {
642
+ throw new Error(
643
+ `Surface maxRootCount changed (${state.rootNodeIds.length} -> ${surface.maxRootCount}). Create a new quadtree state.`
644
+ );
464
645
  }
465
- /**
466
- * Get the current subdivision strategy
467
- */
468
- getSubdivisionStrategy() {
469
- return this.subdivisionStrategy;
646
+ beginFrame(state.store);
647
+ state.rootCount = 0;
648
+ const rootCount = surface.rootTiles(params.cameraOrigin, state.scratchRootTiles);
649
+ if (rootCount < 0 || rootCount > surface.maxRootCount) {
650
+ throw new Error(`Surface returned invalid root count (${rootCount}).`);
470
651
  }
471
- initialize() {
472
- this.nodeView.clear();
473
- this.nodeCount = 0;
474
- this.deepestLevel = 0;
475
- this.createNode(0, 0, 0);
652
+ for (let i = 0; i < rootCount; i++) {
653
+ const rootId = allocNode(state.store, state.scratchRootTiles[i]);
654
+ if (rootId === U32_EMPTY) {
655
+ throw new Error("Failed to allocate root node (maxNodes too small).");
656
+ }
657
+ state.rootNodeIds[i] = rootId;
658
+ state.rootCount = i + 1;
476
659
  }
477
- /**
478
- * Update the quadtree based on the given position and return the index
479
- * of the leaf node that best corresponds to the position (closest leaf).
480
- */
481
- update(position, frustum) {
482
- this.reset();
483
- const closestLeafIndex = this.updateNode(0, position, frustum);
484
- return closestLeafIndex;
660
+ }
661
+
662
+ function shouldSplit(bounds, level, maxLevel, params) {
663
+ if (level >= maxLevel) return false;
664
+ const mode = params.mode ?? "distance";
665
+ const cx = bounds.cx;
666
+ const cy = bounds.cy;
667
+ const cz = bounds.cz;
668
+ const distSq = cx * cx + cy * cy + cz * cz;
669
+ const safeDistSq = distSq > 1e-12 ? distSq : 1e-12;
670
+ if (mode === "screen") {
671
+ const proj = params.projectionFactor ?? 0;
672
+ const target = params.targetPixels ?? 0;
673
+ if (proj <= 0 || target <= 0) {
674
+ const f2 = params.distanceFactor ?? 2;
675
+ const threshold2 = bounds.r * f2;
676
+ return safeDistSq < threshold2 * threshold2;
677
+ }
678
+ const left = bounds.r * bounds.r * proj * proj;
679
+ const right = safeDistSq * target * target;
680
+ return left > right;
485
681
  }
486
- /**
487
- * Recursively update a node and its children based on distance and size criteria
488
- * and return the closest leaf node index to the provided position.
489
- */
490
- updateNode(nodeIndex, position, frustum) {
491
- const level = this.nodeView.getLevel(nodeIndex);
492
- const nodeSize = this.config.rootSize / (1 << level);
493
- const nodeX = this.nodeView.getX(nodeIndex);
494
- const nodeY = this.nodeView.getY(nodeIndex);
495
- const minX = this.config.origin.x + (nodeX * nodeSize - 0.5 * this.config.rootSize);
496
- const minZ = this.config.origin.z + (nodeY * nodeSize - 0.5 * this.config.rootSize);
497
- const worldX = minX + 0.5 * nodeSize;
498
- const worldZ = minZ + 0.5 * nodeSize;
499
- if (frustum) {
500
- const altitude = Math.abs(position.y - this.config.origin.y);
501
- const verticalHalfExtent = this.config.rootSize + altitude;
502
- const minY = this.config.origin.y - verticalHalfExtent;
503
- const maxY = this.config.origin.y + verticalHalfExtent;
504
- tempMin.set(minX, minY, minZ);
505
- tempMax.set(minX + nodeSize, maxY, minZ + nodeSize);
506
- tempBox3.set(tempMin, tempMax);
507
- if (!frustum.intersectsBox(tempBox3)) {
508
- this.nodeView.setLeaf(nodeIndex, false);
509
- return -1;
510
- }
682
+ const f = params.distanceFactor ?? 2;
683
+ const threshold = bounds.r * f;
684
+ return safeDistSq < threshold * threshold;
685
+ }
686
+
687
+ function refineLeaves(state, surface, params, outLeaves) {
688
+ const leaves = outLeaves ?? state.leaves;
689
+ resetLeafSet(leaves);
690
+ const store = state.store;
691
+ const stack = state.stack;
692
+ let sp = 0;
693
+ for (let i = 0; i < state.rootCount; i++) {
694
+ stack[sp++] = state.rootNodeIds[i];
695
+ }
696
+ while (sp > 0) {
697
+ const nodeId = stack[--sp];
698
+ const level = store.level[nodeId];
699
+ const space = store.space[nodeId];
700
+ const x = store.x[nodeId];
701
+ const y = store.y[nodeId];
702
+ const tile = state.scratchTile;
703
+ tile.space = space;
704
+ tile.level = level;
705
+ tile.x = x;
706
+ tile.y = y;
707
+ const bounds = state.scratchBounds;
708
+ surface.tileBounds(tile, params.cameraOrigin, bounds);
709
+ if (hasChildren(store, nodeId)) {
710
+ const base = store.firstChild[nodeId];
711
+ stack[sp++] = base + 3;
712
+ stack[sp++] = base + 2;
713
+ stack[sp++] = base + 1;
714
+ stack[sp++] = base + 0;
715
+ continue;
511
716
  }
512
- tempVector3.set(worldX, this.config.origin.y, worldZ);
513
- const distance = position.distanceTo(tempVector3);
514
- const shouldSubdivide = this.shouldSubdivide(level, distance, nodeSize);
515
- if (shouldSubdivide && level < this.config.maxLevel) {
516
- if (this.nodeCount + 4 > this.config.maxNodes) {
517
- this.nodeView.setLeaf(nodeIndex, true);
518
- return nodeIndex;
717
+ const split = shouldSplit(bounds, level, state.cfg.maxLevel, params);
718
+ if (split) {
719
+ const base = ensureChildren(store, nodeId);
720
+ if (base !== U32_EMPTY) {
721
+ stack[sp++] = base + 3;
722
+ stack[sp++] = base + 2;
723
+ stack[sp++] = base + 1;
724
+ stack[sp++] = base + 0;
725
+ continue;
519
726
  }
520
- this.subdivideNode(nodeIndex);
521
- const children = this.nodeView.getChildren(nodeIndex);
522
- let bestLeafIndex = -1;
523
- let bestDistSq = Number.POSITIVE_INFINITY;
524
- for (let i = 0; i < 4; i++) {
525
- if (children[i] !== -1) {
526
- const leafIdx = this.updateNode(children[i], position, frustum);
527
- if (leafIdx !== -1) {
528
- const leafLevel = this.nodeView.getLevel(leafIdx);
529
- const size = this.config.rootSize / (1 << leafLevel);
530
- const x = this.nodeView.getX(leafIdx);
531
- const y = this.nodeView.getY(leafIdx);
532
- const cx = this.config.origin.x + ((x + 0.5) * size - 0.5 * this.config.rootSize);
533
- const cz = this.config.origin.z + ((y + 0.5) * size - 0.5 * this.config.rootSize);
534
- const dx = position.x - cx;
535
- const dz = position.z - cz;
536
- const d2 = dx * dx + dz * dz;
537
- if (d2 < bestDistSq) {
538
- bestDistSq = d2;
539
- bestLeafIndex = leafIdx;
540
- }
727
+ }
728
+ const i = leaves.count;
729
+ if (i >= leaves.capacity) {
730
+ throw new Error("LeafSet capacity exceeded.");
731
+ }
732
+ leaves.space[i] = space;
733
+ leaves.level[i] = level;
734
+ leaves.x[i] = x;
735
+ leaves.y[i] = y;
736
+ state.leafNodeIds[i] = nodeId;
737
+ leaves.count = i + 1;
738
+ }
739
+ return leaves;
740
+ }
741
+
742
+ function resetSplitMarks(state) {
743
+ state.splitGen = state.splitGen + 1 & 65535;
744
+ if (state.splitGen === 0) {
745
+ state.splitStamp.fill(0);
746
+ state.splitGen = 1;
747
+ }
748
+ }
749
+ function scheduleSplit(state, nodeId, count) {
750
+ if (nodeId === U32_EMPTY) return count;
751
+ if (state.splitStamp[nodeId] === state.splitGen) return count;
752
+ state.splitStamp[nodeId] = state.splitGen;
753
+ state.splitQueue[count] = nodeId;
754
+ return count + 1;
755
+ }
756
+ function balance2to1(state, surface, params, leaves) {
757
+ const maxIters = state.cfg.maxLevel + 1;
758
+ for (let iter = 0; iter < maxIters; iter++) {
759
+ const index = buildLeafIndex(leaves, state.leafIndex);
760
+ resetSplitMarks(state);
761
+ let splitCount = 0;
762
+ for (let i = 0; i < leaves.count; i++) {
763
+ const leafLevel = leaves.level[i];
764
+ if (leafLevel < 2) continue;
765
+ const leafSpace = leaves.space[i];
766
+ const leafX = leaves.x[i];
767
+ const leafY = leaves.y[i];
768
+ for (let dir = 0; dir < 4; dir++) {
769
+ for (let candidateLevel = leafLevel - 2; candidateLevel >= 0; candidateLevel--) {
770
+ const shift = leafLevel - candidateLevel;
771
+ const tile = state.scratchTile;
772
+ tile.space = leafSpace;
773
+ tile.level = candidateLevel;
774
+ tile.x = leafX >>> shift;
775
+ tile.y = leafY >>> shift;
776
+ const neighbor = state.scratchNeighbor;
777
+ if (!surface.neighborSameLevel(tile, dir, neighbor)) break;
778
+ const j = lookupSpatialIndexRaw(
779
+ index,
780
+ neighbor.space,
781
+ neighbor.level,
782
+ neighbor.x,
783
+ neighbor.y
784
+ );
785
+ if (j !== U32_EMPTY) {
786
+ splitCount = scheduleSplit(state, state.leafNodeIds[j], splitCount);
787
+ break;
541
788
  }
542
789
  }
543
790
  }
544
- this.nodeView.setLeaf(nodeIndex, false);
545
- return bestLeafIndex;
546
791
  }
547
- this.nodeView.setLeaf(nodeIndex, true);
548
- return nodeIndex;
792
+ if (splitCount === 0) return leaves;
793
+ let anySplit = false;
794
+ for (let k = 0; k < splitCount; k++) {
795
+ const nodeId = state.splitQueue[k];
796
+ if (state.store.level[nodeId] >= state.cfg.maxLevel) continue;
797
+ const base = ensureChildren(state.store, nodeId);
798
+ if (base !== U32_EMPTY) anySplit = true;
799
+ }
800
+ if (!anySplit) return leaves;
801
+ refineLeaves(state, surface, params, leaves);
549
802
  }
550
- /**
551
- * Determine if a node should be subdivided using the configured strategy
552
- */
553
- shouldSubdivide(level, distance, nodeSize) {
554
- const context = {
555
- level,
556
- distance,
557
- nodeSize,
558
- minNodeSize: this.config.minNodeSize,
559
- rootSize: this.config.rootSize
560
- };
561
- return this.subdivisionStrategy(context);
803
+ return leaves;
804
+ }
805
+
806
+ function update(state, surface, params, outLeaves) {
807
+ beginUpdate(state, surface, params);
808
+ const leaves = refineLeaves(state, surface, params, outLeaves);
809
+ return balance2to1(state, surface, params, leaves);
810
+ }
811
+
812
+ const scratchTile = { space: 0, level: 0, x: 0, y: 0 };
813
+ const scratchNbr = { space: 0, level: 0, x: 0, y: 0 };
814
+ const scratchParentTile = { space: 0, level: 0, x: 0, y: 0 };
815
+ const scratchParentNbr = { space: 0, level: 0, x: 0, y: 0 };
816
+ function buildSeams2to1(surface, leaves, outSeams, outIndex) {
817
+ if (outSeams.capacity < leaves.count) {
818
+ throw new Error("SeamTable capacity is smaller than LeafSet.count.");
562
819
  }
563
- /**
564
- * Create a new node and return its index
565
- */
566
- createNode(level, x, y) {
567
- if (this.nodeCount >= this.config.maxNodes) {
568
- console.warn("Maximum node count reached, skipping node creation");
569
- return -1;
570
- }
571
- if (level > this.deepestLevel) {
572
- this.deepestLevel = level;
820
+ const index = buildLeafIndex(leaves, outIndex);
821
+ outSeams.count = leaves.count;
822
+ const neighbors = outSeams.neighbors;
823
+ for (let i = 0; i < leaves.count; i++) {
824
+ const base = i * 8;
825
+ const space = leaves.space[i];
826
+ const level = leaves.level[i];
827
+ const x = leaves.x[i];
828
+ const y = leaves.y[i];
829
+ for (let dir = 0; dir < 4; dir++) {
830
+ const outOffset = base + dir * 2;
831
+ neighbors[outOffset + 0] = U32_EMPTY;
832
+ neighbors[outOffset + 1] = U32_EMPTY;
833
+ scratchTile.space = space;
834
+ scratchTile.level = level;
835
+ scratchTile.x = x;
836
+ scratchTile.y = y;
837
+ if (!surface.neighborSameLevel(scratchTile, dir, scratchNbr)) continue;
838
+ let j = lookupSpatialIndexRaw(index, scratchNbr.space, scratchNbr.level, scratchNbr.x, scratchNbr.y);
839
+ if (j !== U32_EMPTY) {
840
+ neighbors[outOffset + 0] = j;
841
+ continue;
842
+ }
843
+ if (level > 0) {
844
+ const px = x >>> 1;
845
+ const py = y >>> 1;
846
+ scratchParentTile.space = space;
847
+ scratchParentTile.level = level - 1;
848
+ scratchParentTile.x = px;
849
+ scratchParentTile.y = py;
850
+ if (surface.neighborSameLevel(scratchParentTile, dir, scratchParentNbr)) {
851
+ j = lookupSpatialIndexRaw(
852
+ index,
853
+ scratchParentNbr.space,
854
+ scratchParentNbr.level,
855
+ scratchParentNbr.x,
856
+ scratchParentNbr.y
857
+ );
858
+ if (j !== U32_EMPTY) {
859
+ neighbors[outOffset + 0] = j;
860
+ continue;
861
+ }
862
+ }
863
+ }
864
+ const childLevel = scratchNbr.level + 1;
865
+ const x2 = scratchNbr.x << 1 >>> 0;
866
+ const y2 = scratchNbr.y << 1 >>> 0;
867
+ let ax = 0;
868
+ let ay = 0;
869
+ let bx = 0;
870
+ let by = 0;
871
+ switch (dir) {
872
+ case Dir.LEFT:
873
+ ax = x2 + 1;
874
+ ay = y2;
875
+ bx = x2 + 1;
876
+ by = y2 + 1;
877
+ break;
878
+ case Dir.RIGHT:
879
+ ax = x2;
880
+ ay = y2;
881
+ bx = x2;
882
+ by = y2 + 1;
883
+ break;
884
+ case Dir.TOP:
885
+ ax = x2;
886
+ ay = y2 + 1;
887
+ bx = x2 + 1;
888
+ by = y2 + 1;
889
+ break;
890
+ case Dir.BOTTOM:
891
+ ax = x2;
892
+ ay = y2;
893
+ bx = x2 + 1;
894
+ by = y2;
895
+ break;
896
+ }
897
+ j = lookupSpatialIndexRaw(index, scratchNbr.space, childLevel, ax, ay);
898
+ if (j !== U32_EMPTY) neighbors[outOffset + 0] = j;
899
+ j = lookupSpatialIndexRaw(index, scratchNbr.space, childLevel, bx, by);
900
+ if (j !== U32_EMPTY) neighbors[outOffset + 1] = j;
573
901
  }
574
- this.tempChildIndices[0] = EMPTY_SENTINEL_VALUE;
575
- this.tempChildIndices[1] = EMPTY_SENTINEL_VALUE;
576
- this.tempChildIndices[2] = EMPTY_SENTINEL_VALUE;
577
- this.tempChildIndices[3] = EMPTY_SENTINEL_VALUE;
578
- this.tempNeighborIndices[0] = EMPTY_SENTINEL_VALUE;
579
- this.tempNeighborIndices[1] = EMPTY_SENTINEL_VALUE;
580
- this.tempNeighborIndices[2] = EMPTY_SENTINEL_VALUE;
581
- this.tempNeighborIndices[3] = EMPTY_SENTINEL_VALUE;
582
- const nodeIndex = this.nodeCount++;
583
- this.nodeView.setLevel(nodeIndex, level);
584
- this.nodeView.setX(nodeIndex, x);
585
- this.nodeView.setY(nodeIndex, y);
586
- this.nodeView.setChildren(nodeIndex, this.tempChildIndices);
587
- this.nodeView.setNeighbors(nodeIndex, this.tempNeighborIndices);
588
- this.nodeView.setLeaf(nodeIndex, false);
589
- return nodeIndex;
590
902
  }
591
- /**
592
- * Subdivide a node by creating its four children
593
- */
594
- subdivideNode(nodeIndex) {
595
- const childLevel = this.nodeView.getLevel(nodeIndex) + 1;
596
- const childX = this.nodeView.getX(nodeIndex) * 2;
597
- const childY = this.nodeView.getY(nodeIndex) * 2;
598
- const childIndices = [
599
- this.createNode(childLevel, childX, childY),
600
- // top-left
601
- this.createNode(childLevel, childX + 1, childY),
602
- // top-right
603
- this.createNode(childLevel, childX, childY + 1),
604
- // bottom-left
605
- this.createNode(childLevel, childX + 1, childY + 1)
606
- // bottom-right
607
- ];
608
- if (childIndices.some((index) => index === -1)) {
609
- console.warn("Failed to create all children, skipping subdivision");
610
- return;
903
+ return outSeams;
904
+ }
905
+
906
+ function createFlatSurface(cfg) {
907
+ const halfRoot = 0.5 * cfg.rootSize;
908
+ const maxHeight = cfg.maxHeight ?? 0;
909
+ const surface = {
910
+ spaceCount: 1,
911
+ maxRootCount: 1,
912
+ neighborSameLevel(tile, dir, out) {
913
+ const level = tile.level;
914
+ const x = tile.x;
915
+ const y = tile.y;
916
+ let nx = x;
917
+ let ny = y;
918
+ switch (dir) {
919
+ case Dir.LEFT:
920
+ nx = x - 1;
921
+ break;
922
+ case Dir.RIGHT:
923
+ nx = x + 1;
924
+ break;
925
+ case Dir.TOP:
926
+ ny = y - 1;
927
+ break;
928
+ case Dir.BOTTOM:
929
+ ny = y + 1;
930
+ break;
931
+ }
932
+ if (nx < 0 || ny < 0) return false;
933
+ const maxCoord = (1 << level) - 1;
934
+ if (nx > maxCoord || ny > maxCoord) return false;
935
+ out.space = 0;
936
+ out.level = level;
937
+ out.x = nx;
938
+ out.y = ny;
939
+ return true;
940
+ },
941
+ tileBounds(tile, cameraOrigin, out) {
942
+ const level = tile.level;
943
+ const scale = 1 / (1 << level);
944
+ const size = cfg.rootSize * scale;
945
+ const minX = cfg.origin.x + (tile.x * size - halfRoot);
946
+ const minZ = cfg.origin.z + (tile.y * size - halfRoot);
947
+ const centerX = minX + 0.5 * size;
948
+ const centerY = cfg.origin.y;
949
+ const centerZ = minZ + 0.5 * size;
950
+ out.cx = centerX - cameraOrigin.x;
951
+ out.cy = centerY - cameraOrigin.y;
952
+ out.cz = centerZ - cameraOrigin.z;
953
+ out.r = 0.7071067811865476 * size + maxHeight;
954
+ },
955
+ rootTiles(_cameraOrigin, out) {
956
+ const root = out[0];
957
+ root.space = 0;
958
+ root.level = 0;
959
+ root.x = 0;
960
+ root.y = 0;
961
+ return 1;
611
962
  }
612
- this.nodeView.setChildren(nodeIndex, childIndices);
613
- this.updateChildNeighbors(nodeIndex, childIndices);
614
- }
615
- /**
616
- * Update neighbor relationships for child nodes
617
- */
618
- updateChildNeighbors(_parentIndex, childIndices) {
619
- for (let i = 0; i < 4; i++) {
620
- const childIndex = childIndices[i];
621
- this.tempNeighborIndices[0] = EMPTY_SENTINEL_VALUE;
622
- this.tempNeighborIndices[1] = EMPTY_SENTINEL_VALUE;
623
- this.tempNeighborIndices[2] = EMPTY_SENTINEL_VALUE;
624
- this.tempNeighborIndices[3] = EMPTY_SENTINEL_VALUE;
625
- const childX = i % 2;
626
- const childY = Math.floor(i / 2);
627
- if (childX === 0 && i + 1 < 4) {
628
- this.tempNeighborIndices[1] = childIndices[i + 1];
629
- } else if (childX === 1 && i - 1 >= 0) {
630
- this.tempNeighborIndices[0] = childIndices[i - 1];
963
+ };
964
+ return surface;
965
+ }
966
+
967
+ function createInfiniteFlatSurface(cfg) {
968
+ const halfRoot = 0.5 * cfg.rootSize;
969
+ const maxHeight = cfg.maxHeight ?? 0;
970
+ const rootGridRadius = Math.max(0, Math.floor(cfg.rootGridRadius ?? 1));
971
+ const rootWidth = rootGridRadius * 2 + 1;
972
+ return {
973
+ spaceCount: 1,
974
+ maxRootCount: rootWidth * rootWidth,
975
+ neighborSameLevel(tile, dir, out) {
976
+ let nx = tile.x;
977
+ let ny = tile.y;
978
+ switch (dir) {
979
+ case Dir.LEFT:
980
+ nx = tile.x - 1;
981
+ break;
982
+ case Dir.RIGHT:
983
+ nx = tile.x + 1;
984
+ break;
985
+ case Dir.TOP:
986
+ ny = tile.y - 1;
987
+ break;
988
+ case Dir.BOTTOM:
989
+ ny = tile.y + 1;
990
+ break;
631
991
  }
632
- if (childY === 0 && i + 2 < 4) {
633
- this.tempNeighborIndices[3] = childIndices[i + 2];
634
- } else if (childY === 1 && i - 2 >= 0) {
635
- this.tempNeighborIndices[2] = childIndices[i - 2];
992
+ out.space = tile.space;
993
+ out.level = tile.level;
994
+ out.x = nx;
995
+ out.y = ny;
996
+ return true;
997
+ },
998
+ tileBounds(tile, cameraOrigin, out) {
999
+ const level = tile.level;
1000
+ const scale = 1 / (1 << level);
1001
+ const size = cfg.rootSize * scale;
1002
+ const minX = cfg.origin.x + (tile.x * size - halfRoot);
1003
+ const minZ = cfg.origin.z + (tile.y * size - halfRoot);
1004
+ const centerX = minX + 0.5 * size;
1005
+ const centerY = cfg.origin.y;
1006
+ const centerZ = minZ + 0.5 * size;
1007
+ out.cx = centerX - cameraOrigin.x;
1008
+ out.cy = centerY - cameraOrigin.y;
1009
+ out.cz = centerZ - cameraOrigin.z;
1010
+ out.r = 0.7071067811865476 * size + maxHeight;
1011
+ },
1012
+ rootTiles(cameraOrigin, out) {
1013
+ const camRootX = Math.floor((cameraOrigin.x - cfg.origin.x + halfRoot) / cfg.rootSize);
1014
+ const camRootY = Math.floor((cameraOrigin.z - cfg.origin.z + halfRoot) / cfg.rootSize);
1015
+ let index = 0;
1016
+ for (let dy = -rootGridRadius; dy <= rootGridRadius; dy++) {
1017
+ for (let dx = -rootGridRadius; dx <= rootGridRadius; dx++) {
1018
+ const root = out[index];
1019
+ root.space = 0;
1020
+ root.level = 0;
1021
+ root.x = camRootX + dx;
1022
+ root.y = camRootY + dy;
1023
+ index++;
1024
+ }
636
1025
  }
637
- this.nodeView.setNeighbors(childIndex, this.tempNeighborIndices);
1026
+ return index;
638
1027
  }
639
- }
640
- /**
641
- * Get the deepest subdivision level currently in the quadtree
642
- */
643
- getDeepestLevel() {
644
- return this.deepestLevel;
645
- }
646
- /**
647
- * Get the total number of nodes
648
- */
649
- getNodeCount() {
650
- return this.nodeCount;
651
- }
652
- getLeafNodeCount() {
653
- return this.nodeView.getLeafNodeCount();
654
- }
655
- /**
656
- * Get active leaf node indices for efficient GPU processing
657
- */
658
- getActiveLeafNodeIndices() {
659
- return this.nodeView.getActiveLeafNodeIndices();
660
- }
661
- /**
662
- * Get the configuration
663
- */
664
- getConfig() {
665
- return this.config;
666
- }
667
- /**
668
- * Get all leaf nodes as an array of node objects
669
- */
670
- getLeafNodes() {
671
- const leafNodes = [];
672
- for (let i = 0; i < this.nodeCount; i++) {
673
- if (this.nodeView.getLeaf(i)) {
674
- leafNodes.push({
675
- level: this.nodeView.getLevel(i),
676
- x: this.nodeView.getX(i),
677
- y: this.nodeView.getY(i)
678
- });
1028
+ };
1029
+ }
1030
+
1031
+ function createCubeSphereSurface(_cfg) {
1032
+ return {
1033
+ spaceCount: 6,
1034
+ maxRootCount: 6,
1035
+ neighborSameLevel(_tile, _dir, _out) {
1036
+ return false;
1037
+ },
1038
+ tileBounds(_tile, _cameraOrigin, out) {
1039
+ out.cx = 0;
1040
+ out.cy = 0;
1041
+ out.cz = 0;
1042
+ out.r = Number.MAX_VALUE;
1043
+ },
1044
+ rootTiles(_cameraOrigin, out) {
1045
+ for (let s = 0; s < 6; s++) {
1046
+ const root = out[s];
1047
+ root.space = s;
1048
+ root.level = 0;
1049
+ root.x = 0;
1050
+ root.y = 0;
679
1051
  }
1052
+ return 6;
680
1053
  }
681
- return leafNodes;
682
- }
683
- /**
684
- * Reset the quadtree
685
- */
686
- reset() {
687
- this.initialize();
688
- }
689
- /**
690
- * Get the NodeView instance for direct access
691
- */
692
- getNodeView() {
693
- return this.nodeView;
694
- }
695
- /**
696
- * Release internal resources associated with this quadtree
697
- */
698
- destroy() {
699
- this.nodeView.destroy();
700
- this.nodeCount = 0;
701
- this.deepestLevel = 0;
702
- }
703
- /**
704
- * Set the configuration
705
- */
706
- setConfig(config, reset = false) {
707
- this.config = config;
708
- if (reset) {
709
- this.initialize();
1054
+ };
1055
+ }
1056
+
1057
+ const surfaceTask = task((get, work) => {
1058
+ const customSurface = get(surface);
1059
+ const rootSizeVal = get(rootSize);
1060
+ const originVal = get(origin);
1061
+ return work(() => {
1062
+ if (customSurface) return customSurface;
1063
+ return createFlatSurface({ rootSize: rootSizeVal, origin: originVal });
1064
+ });
1065
+ }).displayName("surfaceTask");
1066
+ const quadtreeConfigTask = task((get, work) => {
1067
+ const surfaceVal = get(surfaceTask);
1068
+ const maxNodesVal = get(maxNodes);
1069
+ const maxLevelVal = get(maxLevel);
1070
+ return work(() => {
1071
+ const state = createState({ maxNodes: maxNodesVal, maxLevel: maxLevelVal }, surfaceVal);
1072
+ return {
1073
+ state,
1074
+ surface: surfaceVal
1075
+ };
1076
+ });
1077
+ }).displayName("quadtreeConfigTask");
1078
+ const quadtreeUpdateTask = task((get, work) => {
1079
+ const quadtreeConfig = get(quadtreeConfigTask);
1080
+ const quadtreeUpdateConfig = get(quadtreeUpdate);
1081
+ let outLeaves = void 0;
1082
+ return work(() => {
1083
+ outLeaves = update(
1084
+ quadtreeConfig.state,
1085
+ quadtreeConfig.surface,
1086
+ quadtreeUpdateConfig,
1087
+ outLeaves
1088
+ );
1089
+ return outLeaves;
1090
+ });
1091
+ }).displayName("quadtreeUpdateTask");
1092
+ const leafStorageTask = task((get, work) => {
1093
+ const maxNodesVal = get(maxNodes);
1094
+ return work(() => createLeafStorage(maxNodesVal));
1095
+ }).displayName("leafStorageTask");
1096
+ const leafGpuBufferTask = task((get, work) => {
1097
+ const leafSet = get(quadtreeUpdateTask);
1098
+ const leafStorage = get(leafStorageTask);
1099
+ return work(() => {
1100
+ const bufferCapacity = leafStorage.data.length / 4;
1101
+ const leafCount = Math.min(leafSet.count, bufferCapacity);
1102
+ for (let i = 0; i < leafCount; i += 1) {
1103
+ const offset = i * 4;
1104
+ leafStorage.data[offset] = leafSet.level[i] ?? 0;
1105
+ leafStorage.data[offset + 1] = leafSet.x[i] ?? 0;
1106
+ leafStorage.data[offset + 2] = leafSet.y[i] ?? 0;
1107
+ leafStorage.data[offset + 3] = 1;
710
1108
  }
711
- }
1109
+ leafStorage.attribute.needsUpdate = true;
1110
+ leafStorage.node.needsUpdate = true;
1111
+ return {
1112
+ count: leafCount,
1113
+ data: leafStorage.data,
1114
+ attribute: leafStorage.attribute,
1115
+ node: leafStorage.node
1116
+ };
1117
+ });
1118
+ }).displayName("leafGpuBufferTask");
1119
+
1120
+ function createElevationFunction(callback) {
1121
+ const tslFunction = (args) => {
1122
+ const params = {
1123
+ worldPosition: args.worldPosition,
1124
+ rootSize: args.rootSize,
1125
+ rootUV: args.rootUV,
1126
+ tileUV: args.tileUV,
1127
+ tileLevel: args.tileLevel,
1128
+ tileSize: args.tileSize,
1129
+ tileOriginVec2: args.tileOriginVec2,
1130
+ nodeIndex: args.nodeIndex
1131
+ };
1132
+ return callback(params);
1133
+ };
1134
+ return Fn$1(tslFunction);
1135
+ }
1136
+
1137
+ function createTerrainUniforms(params) {
1138
+ const sanitizedId = params.instanceId?.replace(/-/g, "_");
1139
+ const suffix = sanitizedId ? `_${sanitizedId}` : "";
1140
+ const uRootOrigin = uniform(
1141
+ new Vector3(params.rootOrigin.x, params.rootOrigin.y, params.rootOrigin.z)
1142
+ ).setName(`uRootOrigin${suffix}`);
1143
+ const uRootSize = uniform(float(params.rootSize)).setName(`uRootSize${suffix}`);
1144
+ const uInnerTileSegments = uniform(int(params.innerTileSegments)).setName(
1145
+ `uInnerTileSegments${suffix}`
1146
+ );
1147
+ const uSkirtScale = uniform(float(params.skirtScale)).setName(`uSkirtScale${suffix}`);
1148
+ const uElevationScale = uniform(float(params.elevationScale)).setName(`uElevationScale${suffix}`);
1149
+ return {
1150
+ uRootOrigin,
1151
+ uRootSize,
1152
+ uInnerTileSegments,
1153
+ uSkirtScale,
1154
+ uElevationScale
1155
+ };
1156
+ }
1157
+
1158
+ const instanceIdTask = task(() => crypto.randomUUID()).displayName("instanceIdTask").cache("once");
1159
+
1160
+ const scratchVector3 = new Vector3$1();
1161
+ const createUniformsTask = task((get, work) => {
1162
+ const uniformParams = {
1163
+ rootOrigin: get(origin),
1164
+ rootSize: get(rootSize),
1165
+ innerTileSegments: get(innerTileSegments),
1166
+ skirtScale: get(skirtScale),
1167
+ elevationScale: get(elevationScale),
1168
+ instanceId: get(instanceIdTask)
1169
+ };
1170
+ return work(() => createTerrainUniforms(uniformParams));
1171
+ }).displayName("createUniformsTask").cache("once");
1172
+ const updateUniformsTask = task((get, work) => {
1173
+ const terrainUniformsContext = get(createUniformsTask);
1174
+ const rootSizeVal = get(rootSize);
1175
+ const rootOrigin = get(origin);
1176
+ const innerTileSegmentsVal = get(innerTileSegments);
1177
+ const skirtScaleVal = get(skirtScale);
1178
+ const elevationScaleVal = get(elevationScale);
1179
+ return work(() => {
1180
+ terrainUniformsContext.uRootSize.value = rootSizeVal;
1181
+ terrainUniformsContext.uRootOrigin.value = scratchVector3.set(
1182
+ rootOrigin.x,
1183
+ rootOrigin.y,
1184
+ rootOrigin.z
1185
+ );
1186
+ terrainUniformsContext.uInnerTileSegments.value = innerTileSegmentsVal;
1187
+ terrainUniformsContext.uSkirtScale.value = skirtScaleVal;
1188
+ terrainUniformsContext.uElevationScale.value = elevationScaleVal;
1189
+ return terrainUniformsContext;
1190
+ });
1191
+ }).displayName("updateUniformsTask");
1192
+
1193
+ const createElevationFieldContextTask = task((get, work) => {
1194
+ const edgeVertexCount = get(innerTileSegments) + 3;
1195
+ const verticesPerNode = edgeVertexCount * edgeVertexCount;
1196
+ const totalElements = get(maxNodes) * verticesPerNode;
1197
+ return work(() => {
1198
+ const data = new Float32Array(totalElements);
1199
+ const attribute = new StorageBufferAttribute(data, 1);
1200
+ const node = storage(attribute, "float", totalElements);
1201
+ return {
1202
+ data,
1203
+ attribute,
1204
+ node
1205
+ };
1206
+ });
1207
+ }).displayName("createElevationFieldContextTask");
1208
+ const tileNodesTask = task((get, work) => {
1209
+ const leafStorage = get(leafStorageTask);
1210
+ const uniforms = get(createUniformsTask);
1211
+ return work(() => {
1212
+ return createTileCompute(leafStorage, uniforms);
1213
+ });
1214
+ }).displayName("tileNodesTask");
1215
+ const elevationFieldStageTask = task((get, work) => {
1216
+ const tile = get(tileNodesTask);
1217
+ const uniforms = get(createUniformsTask);
1218
+ const elevationFieldContext = get(createElevationFieldContextTask);
1219
+ const userElevationFn = get(elevationFn);
1220
+ return work(() => {
1221
+ const heightFn = createElevationFunction(userElevationFn);
1222
+ const heightWriteFn = createElevation(tile, uniforms, heightFn);
1223
+ return [
1224
+ (nodeIndex, globalVertexIndex, _uv, localCoordinates) => {
1225
+ const height = heightWriteFn(nodeIndex, localCoordinates);
1226
+ elevationFieldContext.node.element(globalVertexIndex).assign(height);
1227
+ }
1228
+ ];
1229
+ });
1230
+ }).displayName("elevationFieldStageTask");
1231
+
1232
+ const createNormalFieldContextTask = task((get, work) => {
1233
+ const edgeVertexCount = get(innerTileSegments) + 3;
1234
+ const verticesPerNode = edgeVertexCount * edgeVertexCount;
1235
+ const totalElements = get(maxNodes) * verticesPerNode;
1236
+ return work(() => {
1237
+ const data = new Uint32Array(totalElements);
1238
+ const attribute = new StorageBufferAttribute(data, 1);
1239
+ const node = storage(attribute, "uint", totalElements);
1240
+ return {
1241
+ data,
1242
+ attribute,
1243
+ node
1244
+ };
1245
+ });
1246
+ }).displayName("createNormalFieldContextTask");
1247
+ function createNormalFromElevationField(elevationFieldNode, edgeVertexCount) {
1248
+ return Fn(
1249
+ ([nodeIndex, tileSize, ix, iy, elevationScale]) => {
1250
+ const iEdge = int(edgeVertexCount);
1251
+ const verticesPerNode = iEdge.mul(iEdge);
1252
+ const baseOffset = int(nodeIndex).mul(verticesPerNode);
1253
+ const xLeft = int(ix).sub(int(1));
1254
+ const xRight = int(ix).add(int(1));
1255
+ const yUp = int(iy).sub(int(1));
1256
+ const yDown = int(iy).add(int(1));
1257
+ const hLeft = elevationFieldNode.element(baseOffset.add(int(iy).mul(iEdge).add(xLeft))).mul(elevationScale);
1258
+ const hRight = elevationFieldNode.element(baseOffset.add(int(iy).mul(iEdge).add(xRight))).mul(elevationScale);
1259
+ const hUp = elevationFieldNode.element(baseOffset.add(yUp.mul(iEdge).add(int(ix)))).mul(elevationScale);
1260
+ const hDown = elevationFieldNode.element(baseOffset.add(yDown.mul(iEdge).add(int(ix)))).mul(elevationScale);
1261
+ const innerSegments = float(iEdge).sub(float(3));
1262
+ const stepWorld = tileSize.div(innerSegments);
1263
+ const inv2Step = float(0.5).div(stepWorld);
1264
+ const dhdx = float(hRight).sub(float(hLeft)).mul(inv2Step);
1265
+ const dhdz = float(hDown).sub(float(hUp)).mul(inv2Step);
1266
+ const normal = vec3(dhdx.negate(), float(1), dhdz.negate()).normalize();
1267
+ return vec2(normal.x, normal.z);
1268
+ }
1269
+ );
1270
+ }
1271
+ const normalFieldStageTask = task((get, work) => {
1272
+ const upstream = get(elevationFieldStageTask);
1273
+ const elevationFieldContext = get(createElevationFieldContextTask);
1274
+ const normalFieldContext = get(createNormalFieldContextTask);
1275
+ const tileEdgeVertexCount = get(innerTileSegments) + 3;
1276
+ const tile = get(tileNodesTask);
1277
+ const uniforms = get(createUniformsTask);
1278
+ return work(() => {
1279
+ const computeNormal = createNormalFromElevationField(
1280
+ elevationFieldContext.node,
1281
+ tileEdgeVertexCount
1282
+ );
1283
+ return [
1284
+ ...upstream,
1285
+ (nodeIndex, globalVertexIndex, _uv, localCoordinates) => {
1286
+ const ix = int(localCoordinates.x);
1287
+ const iy = int(localCoordinates.y);
1288
+ const tileSize = tile.tileSize(nodeIndex);
1289
+ const normalXZ = computeNormal(
1290
+ nodeIndex,
1291
+ tileSize,
1292
+ ix,
1293
+ iy,
1294
+ uniforms.uElevationScale
1295
+ );
1296
+ normalFieldContext.node.element(globalVertexIndex).assign(packHalf2x16(normalXZ));
1297
+ }
1298
+ ];
1299
+ });
1300
+ }).displayName("normalFieldStageTask");
1301
+
1302
+ const compileComputeTask = task((get, work) => {
1303
+ const pipeline = get(normalFieldStageTask);
1304
+ const edgeVertexCount = get(innerTileSegments) + 3;
1305
+ return work(() => compileComputePipeline(pipeline, edgeVertexCount));
1306
+ }).displayName("compileComputeTask");
1307
+ const executeComputeTask = task((get, work, { resources }) => {
1308
+ const { execute } = get(compileComputeTask);
1309
+ const leafState = get(leafGpuBufferTask);
1310
+ return work(
1311
+ () => resources?.renderer ? execute(resources.renderer, leafState.count) : () => {
1312
+ }
1313
+ );
1314
+ }).displayName("executeComputeTask").lane("gpu");
1315
+ function createComputePipelineTasks(leafStageTask) {
1316
+ const compile = task((get, work) => {
1317
+ const pipeline = get(leafStageTask);
1318
+ const edgeVertexCount = get(innerTileSegments) + 3;
1319
+ return work(() => compileComputePipeline(pipeline, edgeVertexCount));
1320
+ }).displayName("compileComputeTask");
1321
+ const execute = task((get, work, { resources }) => {
1322
+ const { execute: run } = get(compile);
1323
+ const leafState = get(leafGpuBufferTask);
1324
+ return work(() => resources?.renderer ? run(resources.renderer, leafState.count) : () => {
1325
+ });
1326
+ }).displayName("executeComputeTask").lane("gpu");
1327
+ return { compile, execute };
1328
+ }
1329
+
1330
+ const textureSpaceToVectorSpace = Fn(([value]) => {
1331
+ return remap(value, float(0), float(1), float(-1), float(1));
1332
+ });
1333
+ const vectorSpaceToTextureSpace = Fn(([value]) => {
1334
+ return remap(value, float(-1), float(1), float(0), float(1));
1335
+ });
1336
+ const blendAngleCorrectedNormals = Fn(([n1, n2]) => {
1337
+ const t = vec3(n1.x, n1.y, n1.z.add(1));
1338
+ const u = vec3(n2.x.negate(), n2.y.negate(), n2.z);
1339
+ const r = t.mul(dot(t, u)).sub(u.mul(t.z)).normalize();
1340
+ return r;
1341
+ });
1342
+ const deriveNormalZ = Fn(([normalXY]) => {
1343
+ const xy = normalXY.toVar();
1344
+ const z = xy.x.mul(xy.x).add(xy.y.mul(xy.y)).oneMinus().max(0).sqrt();
1345
+ return vec3(xy.x, xy.y, z);
1346
+ });
1347
+
1348
+ const isSkirtVertex = Fn(([segments]) => {
1349
+ const segmentsNode = typeof segments === "number" ? int(segments) : segments;
1350
+ const vIndex = int(vertexIndex);
1351
+ const segmentEdges = int(segmentsNode.add(3));
1352
+ const vx = vIndex.mod(segmentEdges);
1353
+ const vy = vIndex.div(segmentEdges);
1354
+ const last = segmentEdges.sub(int(1));
1355
+ return vx.equal(int(0)).or(vx.equal(last)).or(vy.equal(int(0))).or(vy.equal(last));
1356
+ });
1357
+ const isSkirtUV = Fn(([segments]) => {
1358
+ const segmentsNode = typeof segments === "number" ? int(segments) : segments;
1359
+ const ux = uv().x;
1360
+ const uy = uv().y;
1361
+ const segmentCount = segmentsNode.add(2);
1362
+ const segmentStep = float(1).div(segmentCount);
1363
+ const innerX = ux.greaterThan(segmentStep).and(ux.lessThan(segmentStep.oneMinus()));
1364
+ const innerY = uy.greaterThan(segmentStep).and(uy.lessThan(segmentStep.oneMinus()));
1365
+ return innerX.and(innerY).not();
1366
+ });
1367
+
1368
+ function createTileBaseWorldPosition(leafStorage, terrainUniforms) {
1369
+ return Fn(() => {
1370
+ const nodeIndex = int(instanceIndex);
1371
+ const nodeOffset = nodeIndex.mul(int(4));
1372
+ const nodeLevel = leafStorage.node.element(nodeOffset).toInt();
1373
+ const nodeX = leafStorage.node.element(nodeOffset.add(int(1))).toFloat();
1374
+ const nodeY = leafStorage.node.element(nodeOffset.add(int(2))).toFloat();
1375
+ const rootSize = terrainUniforms.uRootSize.toVar();
1376
+ const rootOrigin = terrainUniforms.uRootOrigin.toVar();
1377
+ const half = float(0.5);
1378
+ const size = rootSize.div(pow(float(2), nodeLevel.toFloat()));
1379
+ const halfRoot = rootSize.mul(half);
1380
+ const centerX = rootOrigin.x.add(nodeX.add(half).mul(size)).sub(halfRoot);
1381
+ const centerZ = rootOrigin.z.add(nodeY.add(half).mul(size)).sub(halfRoot);
1382
+ const clampedX = positionLocal.x.max(half.negate()).min(half);
1383
+ const clampedZ = positionLocal.z.max(half.negate()).min(half);
1384
+ const worldX = centerX.add(clampedX.mul(size));
1385
+ const worldZ = centerZ.add(clampedZ.mul(size));
1386
+ return vec3(worldX, rootOrigin.y, worldZ);
1387
+ });
1388
+ }
1389
+ function createTileElevation(terrainUniforms, elevationFieldBufferNode) {
1390
+ if (!elevationFieldBufferNode) return float(0);
1391
+ const edgeVertexCount = terrainUniforms.uInnerTileSegments.add(3);
1392
+ return readElevationFieldAtPositionLocal(
1393
+ elevationFieldBufferNode,
1394
+ edgeVertexCount,
1395
+ positionLocal
1396
+ )().mul(
1397
+ terrainUniforms.uElevationScale
1398
+ );
1399
+ }
1400
+ function createNormalAssignment(terrainUniforms, normalFieldBufferNode) {
1401
+ if (!normalFieldBufferNode) return;
1402
+ const nodeIndex = int(instanceIndex);
1403
+ const intEdge = int(terrainUniforms.uInnerTileSegments.add(3));
1404
+ const verticesPerNode = intEdge.mul(intEdge);
1405
+ const globalVertexIndex = nodeIndex.mul(verticesPerNode).add(int(vertexIndex));
1406
+ const packed = normalFieldBufferNode.element(globalVertexIndex);
1407
+ const normalXZ = unpackHalf2x16(packed);
1408
+ const reconstructed = deriveNormalZ(normalXZ);
1409
+ normalLocal.assign(vec3(reconstructed.x, reconstructed.z, reconstructed.y));
712
1410
  }
1411
+ function createTileWorldPosition(leafStorage, terrainUniforms, elevationFieldBufferNode, normalFieldBufferNode) {
1412
+ const baseWorldPosition = createTileBaseWorldPosition(leafStorage, terrainUniforms);
1413
+ return Fn(() => {
1414
+ const base = baseWorldPosition();
1415
+ const yElevation = createTileElevation(terrainUniforms, elevationFieldBufferNode);
1416
+ const skirtVertex = isSkirtVertex(terrainUniforms.uInnerTileSegments);
1417
+ const skirtY = base.y.add(yElevation).sub(terrainUniforms.uSkirtScale.toVar());
1418
+ const worldY = select(skirtVertex, skirtY, base.y.add(yElevation));
1419
+ createNormalAssignment(terrainUniforms, normalFieldBufferNode);
1420
+ return vec3(base.x, worldY, base.z);
1421
+ })();
1422
+ }
1423
+
1424
+ const positionNodeTask = task((get, work) => {
1425
+ const leafStorage = get(leafStorageTask);
1426
+ const terrainUniforms = get(createUniformsTask);
1427
+ const elevationFieldContext = get(createElevationFieldContextTask);
1428
+ const normalFieldContext = get(createNormalFieldContextTask);
1429
+ return work(
1430
+ () => createTileWorldPosition(
1431
+ leafStorage,
1432
+ terrainUniforms,
1433
+ elevationFieldContext.node,
1434
+ normalFieldContext.node
1435
+ )
1436
+ );
1437
+ }).displayName("positionNodeTask");
1438
+
1439
+ function terrainGraph() {
1440
+ return graph().add(instanceIdTask).add(quadtreeConfigTask).add(quadtreeUpdateTask).add(leafStorageTask).add(surfaceTask).add(leafGpuBufferTask).add(createUniformsTask).add(updateUniformsTask).add(positionNodeTask).add(createElevationFieldContextTask).add(tileNodesTask).add(createNormalFieldContextTask).add(elevationFieldStageTask).add(normalFieldStageTask).add(compileComputeTask).add(executeComputeTask);
1441
+ }
1442
+ const terrainTasks = {
1443
+ instanceId: instanceIdTask,
1444
+ quadtreeConfig: quadtreeConfigTask,
1445
+ quadtreeUpdate: quadtreeUpdateTask,
1446
+ leafStorage: leafStorageTask,
1447
+ surface: surfaceTask,
1448
+ leafGpuBuffer: leafGpuBufferTask,
1449
+ createUniforms: createUniformsTask,
1450
+ updateUniforms: updateUniformsTask,
1451
+ positionNode: positionNodeTask,
1452
+ createElevationFieldContext: createElevationFieldContextTask,
1453
+ createTileNodes: tileNodesTask,
1454
+ createNormalFieldContext: createNormalFieldContextTask,
1455
+ elevationFieldStage: elevationFieldStageTask,
1456
+ normalFieldStage: normalFieldStageTask,
1457
+ compileCompute: compileComputeTask,
1458
+ executeCompute: executeComputeTask
1459
+ };
1460
+
1461
+ const vGlobalVertexIndex = /* @__PURE__ */ varyingProperty("int", "vGlobalVertexIndex");
1462
+ const vElevation = /* @__PURE__ */ varyingProperty("f32", "vElevation");
1463
+
1464
+ const cellCenter = Fn(({ cell }) => {
1465
+ return cell.add(mx_noise_float(cell.mul(Math.PI)));
1466
+ });
1467
+ const voronoiCells = Fn((params) => {
1468
+ const scale = float(params.scale);
1469
+ const facet = float(params.facet);
1470
+ const seed = float(params.seed);
1471
+ const pos = params.uv.mul(scale).add(seed);
1472
+ const midCell = pos.round().toVar();
1473
+ const minCell = midCell.toVar();
1474
+ const minDist = float(1).toVar();
1475
+ const cell = vec3(0, 0, 0).toVar();
1476
+ const dist = float().toVar();
1477
+ const i = float(0).toVar();
1478
+ Loop(27, () => {
1479
+ const ix = i.mod(3).sub(1);
1480
+ const iy = i.div(3).floor().mod(3).sub(1);
1481
+ const iz = i.div(9).floor().sub(1);
1482
+ cell.assign(midCell.add(vec3(ix, iy, iz)));
1483
+ dist.assign(pos.distance(cellCenter({ cell })).add(mx_noise_float(pos).div(5)));
1484
+ If(dist.lessThan(minDist), () => {
1485
+ minDist.assign(dist);
1486
+ minCell.assign(cell);
1487
+ });
1488
+ i.addAssign(1);
1489
+ });
1490
+ const n = mx_noise_float(minCell.mul(Math.PI)).toVar();
1491
+ const k = mix(minDist, n.add(1).div(2), facet);
1492
+ return k;
1493
+ });
713
1494
 
714
- export { Quadtree, TerrainGeometry, computeScreenSpaceInfo, distanceBasedSubdivision, isSkirtUV, isSkirtVertex, screenSpaceSubdivision };
1495
+ export { Dir, TerrainGeometry, TerrainMesh, U32_EMPTY, allocLeafSet, allocSeamTable, beginUpdate, blendAngleCorrectedNormals, buildLeafIndex, buildSeams2to1, compileComputeTask, createComputePipelineTasks, createCubeSphereSurface, createElevationFieldContextTask, createFlatSurface, createInfiniteFlatSurface, createNormalFieldContextTask, createSpatialIndex, createState, createTerrainUniforms, createUniformsTask, deriveNormalZ, elevationFieldStageTask, elevationFn, elevationScale, executeComputeTask, innerTileSegments, instanceIdTask, isSkirtUV, isSkirtVertex, leafGpuBufferTask, leafStorageTask, maxLevel, maxNodes, normalFieldStageTask, origin, positionNodeTask, quadtreeConfigTask, quadtreeUpdate, quadtreeUpdateTask, resetLeafSet, resetSeamTable, rootSize, skirtScale, surface, surfaceTask, terrainGraph, terrainTasks, textureSpaceToVectorSpace, tileNodesTask, update, updateUniformsTask, vElevation, vGlobalVertexIndex, vectorSpaceToTextureSpace, voronoiCells };