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
@@ -1,7 +1,7 @@
1
1
  import { Color, Vector3 } from '../math/index.js';
2
2
  import { BufferAttribute } from '../core/BufferAttribute.js';
3
3
  import { BufferGeometry } from '../core/BufferGeometry.js';
4
- import { DoubleSide } from '../core/constants.js';
4
+ import { AlwaysStencilFunc, DecrementWrapStencilOp, DoubleSide, IncrementWrapStencilOp, KeepStencilOp, LessDepth, NotEqualStencilFunc, ZeroStencilOp, } from '../core/constants.js';
5
5
  import { ShaderMaterial } from '../materials/ShaderMaterial.js';
6
6
  import { Mesh } from '../core/Mesh.js';
7
7
  import { raycastVoxels } from './VoxelMesher.js';
@@ -20,7 +20,7 @@ export const VOXEL_GRAPHICS_PRESETS = {
20
20
  label: 'Balanced',
21
21
  silhouetteShadows: true,
22
22
  maxRayDistance: 28,
23
- shadowOpacity: 0.34,
23
+ shadowOpacity: 0.42,
24
24
  penumbraSoftness: 0.55,
25
25
  sunAngleThreshold: 0.02,
26
26
  },
@@ -29,7 +29,7 @@ export const VOXEL_GRAPHICS_PRESETS = {
29
29
  label: 'High',
30
30
  silhouetteShadows: true,
31
31
  maxRayDistance: 48,
32
- shadowOpacity: 0.42,
32
+ shadowOpacity: 0.48,
33
33
  penumbraSoftness: 0.68,
34
34
  sunAngleThreshold: 0.008,
35
35
  },
@@ -37,6 +37,8 @@ export const VOXEL_GRAPHICS_PRESETS = {
37
37
  export const VOXEL_SILHOUETTE_SHADOW_VERTEX_SHADER = `
38
38
  attribute float extrudeDist;
39
39
 
40
+ uniform float uDepthClamp;
41
+
40
42
  varying float vExtrudeDist;
41
43
  varying float vFogDepth;
42
44
 
@@ -45,7 +47,11 @@ void main() {
45
47
  vec4 worldPosition = modelMatrix * vec4(position, 1.0);
46
48
  vec4 mvPosition = viewMatrix * worldPosition;
47
49
  vFogDepth = -mvPosition.z;
48
- gl_Position = projectionMatrix * mvPosition;
50
+ vec4 clipPos = projectionMatrix * mvPosition;
51
+ if (uDepthClamp > 0.5 && clipPos.w > 0.0 && clipPos.z > clipPos.w * 0.99999) {
52
+ clipPos.z = clipPos.w * 0.99999;
53
+ }
54
+ gl_Position = clipPos;
49
55
  }
50
56
  `;
51
57
  export const VOXEL_SILHOUETTE_SHADOW_FRAGMENT_SHADER = `
@@ -56,11 +62,19 @@ uniform float uPenumbraSoftness;
56
62
  uniform float uFogEnabled;
57
63
  uniform float uFogNear;
58
64
  uniform float uFogFar;
65
+ uniform float uStencilPass;
59
66
 
60
67
  varying float vExtrudeDist;
61
68
  varying float vFogDepth;
62
69
 
63
70
  void main() {
71
+ // Hardware stencil shadow volume pass must never discard back caps or far side walls,
72
+ // otherwise Z-fail front/back parity breaks and creates camera-dependent shadow inversion.
73
+ if (uStencilPass > 0.5) {
74
+ gl_FragColor = vec4(0.0);
75
+ return;
76
+ }
77
+
64
78
  float normDist = clamp(vExtrudeDist / max(0.001, uMaxExtrudeDist), 0.0, 1.0);
65
79
  // Fake penumbra: crisp near the caster (extrudeDist ~ 0), softly fading further from the caster
66
80
  float fadeStart = 1.0 - clamp(uPenumbraSoftness, 0.05, 0.95);
@@ -77,29 +91,84 @@ void main() {
77
91
  gl_FragColor = vec4(uShadowColor, alpha);
78
92
  }
79
93
  `;
94
+ export const VOXEL_SILHOUETTE_SHADOW_OVERLAY_VERTEX_SHADER = `
95
+ void main() {
96
+ gl_Position = vec4(position.xy, 0.0, 1.0);
97
+ }
98
+ `;
99
+ export const VOXEL_SILHOUETTE_SHADOW_OVERLAY_FRAGMENT_SHADER = `
100
+ uniform vec3 uShadowColor;
101
+ uniform float uBaseOpacity;
102
+
103
+ void main() {
104
+ if (uBaseOpacity < 0.003) discard;
105
+ gl_FragColor = vec4(uShadowColor, uBaseOpacity);
106
+ }
107
+ `;
80
108
  export function createVoxelSilhouetteShadowMaterial(options = {}) {
109
+ const isStencilPass = options.stencilVolumePass === true;
81
110
  return new ShaderMaterial({
82
- name: 'VoxelSilhouetteShadowMaterial',
111
+ name: isStencilPass ? 'VoxelSilhouetteShadowVolumeMaterial' : 'VoxelSilhouetteShadowMaterial',
83
112
  transparent: true,
113
+ colorWrite: !isStencilPass,
84
114
  depthWrite: false,
85
115
  depthTest: true,
116
+ depthFunc: LessDepth,
86
117
  polygonOffset: true,
87
- polygonOffsetFactor: options.polygonOffsetFactor ?? -1,
88
- polygonOffsetUnits: options.polygonOffsetUnits ?? -2,
118
+ polygonOffsetFactor: options.polygonOffsetFactor ?? (isStencilPass ? 1.5 : -1),
119
+ polygonOffsetUnits: options.polygonOffsetUnits ?? (isStencilPass ? 2 : -2),
89
120
  side: DoubleSide,
121
+ stencilWrite: isStencilPass,
122
+ stencilTest: isStencilPass,
123
+ stencilWriteMask: 0xff,
124
+ stencilFunc: AlwaysStencilFunc,
125
+ stencilRef: 0,
126
+ stencilFuncMask: 0xff,
127
+ stencilFail: KeepStencilOp,
128
+ stencilZFail: isStencilPass ? DecrementWrapStencilOp : KeepStencilOp,
129
+ stencilZPass: KeepStencilOp,
130
+ stencilFailBack: isStencilPass ? KeepStencilOp : null,
131
+ stencilZFailBack: isStencilPass ? IncrementWrapStencilOp : null,
132
+ stencilZPassBack: isStencilPass ? KeepStencilOp : null,
90
133
  uniforms: {
91
- uShadowColor: { value: new Color(options.shadowColor ?? 0x0b1320) },
92
- uBaseOpacity: { value: options.baseOpacity ?? 0.36 },
134
+ uShadowColor: { value: new Color(options.shadowColor ?? 0x0b1628) },
135
+ uBaseOpacity: { value: options.baseOpacity ?? 0.42 },
93
136
  uMaxExtrudeDist: { value: Math.max(0.01, options.maxExtrudeDist ?? 28.0) },
94
137
  uPenumbraSoftness: { value: options.penumbraSoftness ?? 0.55 },
95
138
  uFogEnabled: { value: options.fogEnabled ? 1.0 : 0.0 },
96
139
  uFogNear: { value: options.fogNear ?? 60.0 },
97
140
  uFogFar: { value: options.fogFar ?? 320.0 },
141
+ uDepthClamp: { value: isStencilPass ? 1.0 : 0.0 },
142
+ uStencilPass: { value: isStencilPass ? 1.0 : 0.0 },
98
143
  },
99
144
  vertexShader: VOXEL_SILHOUETTE_SHADOW_VERTEX_SHADER,
100
145
  fragmentShader: VOXEL_SILHOUETTE_SHADOW_FRAGMENT_SHADER,
101
146
  });
102
147
  }
148
+ export function createVoxelSilhouetteShadowOverlayMaterial(sharedUniforms) {
149
+ return new ShaderMaterial({
150
+ name: 'VoxelSilhouetteShadowOverlayMaterial',
151
+ transparent: true,
152
+ depthTest: false,
153
+ depthWrite: false,
154
+ side: DoubleSide,
155
+ stencilWrite: true,
156
+ stencilTest: true,
157
+ stencilWriteMask: 0xff,
158
+ stencilFunc: NotEqualStencilFunc,
159
+ stencilRef: 0,
160
+ stencilFuncMask: 0xff,
161
+ stencilFail: KeepStencilOp,
162
+ stencilZFail: KeepStencilOp,
163
+ stencilZPass: ZeroStencilOp,
164
+ uniforms: {
165
+ uShadowColor: sharedUniforms.uShadowColor,
166
+ uBaseOpacity: sharedUniforms.uBaseOpacity,
167
+ },
168
+ vertexShader: VOXEL_SILHOUETTE_SHADOW_OVERLAY_VERTEX_SHADER,
169
+ fragmentShader: VOXEL_SILHOUETTE_SHADOW_OVERLAY_FRAGMENT_SHADER,
170
+ });
171
+ }
103
172
  const CANONICAL_CUBE_EDGES = [
104
173
  // 4 Top horizontal edges (shared between +Y top face and ±X / ±Z side faces)
105
174
  // 0: Top-East (+Y, +X) -> runs along Z at (vx+1, vy+1, vz..vz+1)
@@ -321,6 +390,7 @@ export function detectSilhouetteEdges(options) {
321
390
  }
322
391
  const _rayOrigin0 = new Vector3();
323
392
  const _rayOrigin1 = new Vector3();
393
+ const _rayOriginMid = new Vector3();
324
394
  const _negSunDir = new Vector3();
325
395
  /**
326
396
  * Step 2: Casts 3D DDA rays (`raycastVoxels`) from the endpoints of each merged silhouette edge
@@ -345,6 +415,141 @@ export function projectSilhouetteEdges(options) {
345
415
  const quads = [];
346
416
  for (let i = 0; i < edges.length; i++) {
347
417
  const edge = edges[i];
418
+ if (flattenCaster) {
419
+ // Ground-decal mode: only project horizontal top silhouette edges onto upward-facing terraces.
420
+ // Subdivide merged edges into 1-voxel unit segments so each column snaps cleanly to its own
421
+ // terrace elevation without creating diagonal triangles across stepped terrain.
422
+ if (edge.axis === 1 || edge.sunNormal.y <= 0 || _negSunDir.y >= -0.05) {
423
+ continue;
424
+ }
425
+ const unitCount = Math.max(1, Math.round(edge.mergedUnitCount || 1));
426
+ const stepX = (edge.end.x - edge.start.x) / unitCount;
427
+ const stepY = (edge.end.y - edge.start.y) / unitCount;
428
+ const stepZ = (edge.end.z - edge.start.z) / unitCount;
429
+ const biasX = edge.shadowNormal.x * 1e-3 - edge.sunNormal.x * 1e-4;
430
+ const biasY = edge.shadowNormal.y * 1e-3 - edge.sunNormal.y * 1e-4;
431
+ const biasZ = edge.shadowNormal.z * 1e-3 - edge.sunNormal.z * 1e-4;
432
+ for (let u = 0; u < unitCount; u++) {
433
+ const s0x = edge.start.x + stepX * u;
434
+ const s0y = edge.start.y + stepY * u;
435
+ const s0z = edge.start.z + stepZ * u;
436
+ const s1x = s0x + stepX;
437
+ const s1y = s0y + stepY;
438
+ const s1z = s0z + stepZ;
439
+ const midX = (s0x + s1x) * 0.5;
440
+ const midY = (s0y + s1y) * 0.5;
441
+ const midZ = (s0z + s1z) * 0.5;
442
+ _rayOriginMid.set(midX + biasX, midY + biasY, midZ + biasZ);
443
+ const hitMid = raycastVoxels(_rayOriginMid, _negSunDir, maxRayDist, getVoxel, isSolid);
444
+ if (!hitMid || hitMid.normalY <= 0 || hitMid.distance < 0.12)
445
+ continue;
446
+ const wy = hitMid.wy;
447
+ const gy = wy + 1;
448
+ if (s0y <= gy + 0.05)
449
+ continue;
450
+ // Exact intersection distance from the horizontal caster edge to the receiving terrace plane y = gy
451
+ const dPlane = (gy - s0y) / _negSunDir.y;
452
+ if (dPlane <= 0.12 || dPlane > maxRayDist)
453
+ continue;
454
+ let gx0 = s0x + _negSunDir.x * dPlane;
455
+ let gz0 = s0z + _negSunDir.z * dPlane;
456
+ let gx1 = s1x + _negSunDir.x * dPlane;
457
+ let gz1 = s1z + _negSunDir.z * dPlane;
458
+ const gxMid = (gx0 + gx1) * 0.5;
459
+ const gzMid = (gz0 + gz1) * 0.5;
460
+ // Clamp lateral overhang if either corner extends past the solid terrace voxel boundary at elevation wy
461
+ if (edge.axis === 0) {
462
+ const vz = Math.floor(gzMid);
463
+ const vxMin = Math.floor(Math.min(gx0, gx1));
464
+ const vxMax = Math.floor(Math.max(gx0, gx1) - 1e-4);
465
+ if (!isSolid(getVoxel(vxMin, wy, vz)) || isSolid(getVoxel(vxMin, wy + 1, vz))) {
466
+ const clampedMin = hitMid.wx;
467
+ if (gx0 < gx1)
468
+ gx0 = Math.max(gx0, clampedMin);
469
+ else
470
+ gx1 = Math.max(gx1, clampedMin);
471
+ }
472
+ if (!isSolid(getVoxel(vxMax, wy, vz)) || isSolid(getVoxel(vxMax, wy + 1, vz))) {
473
+ const clampedMax = hitMid.wx + 1;
474
+ if (gx1 >= gx0)
475
+ gx1 = Math.min(gx1, clampedMax);
476
+ else
477
+ gx0 = Math.min(gx0, clampedMax);
478
+ }
479
+ if (Math.abs(gx1 - gx0) < 0.08)
480
+ continue;
481
+ }
482
+ else if (edge.axis === 2) {
483
+ const vx = Math.floor(gxMid);
484
+ const vzMin = Math.floor(Math.min(gz0, gz1));
485
+ const vzMax = Math.floor(Math.max(gz0, gz1) - 1e-4);
486
+ if (!isSolid(getVoxel(vx, wy, vzMin)) || isSolid(getVoxel(vx, wy + 1, vzMin))) {
487
+ const clampedMin = hitMid.wz;
488
+ if (gz0 < gz1)
489
+ gz0 = Math.max(gz0, clampedMin);
490
+ else
491
+ gz1 = Math.max(gz1, clampedMin);
492
+ }
493
+ if (!isSolid(getVoxel(vx, wy, vzMax)) || isSolid(getVoxel(vx, wy + 1, vzMax))) {
494
+ const clampedMax = hitMid.wz + 1;
495
+ if (gz1 >= gz0)
496
+ gz1 = Math.min(gz1, clampedMax);
497
+ else
498
+ gz0 = Math.min(gz0, clampedMax);
499
+ }
500
+ if (Math.abs(gz1 - gz0) < 0.08)
501
+ continue;
502
+ }
503
+ // March backward from the shadow tip (gxMid, gzMid) toward the caster projection (midX, midZ)
504
+ // strictly along the exposed horizontal terrace at elevation wy
505
+ const backDx = midX - gxMid;
506
+ const backDz = midZ - gzMid;
507
+ const backHorizDist = Math.hypot(backDx, backDz);
508
+ if (backHorizDist < 0.08)
509
+ continue;
510
+ const marchSteps = Math.max(6, Math.ceil(backHorizDist * 6));
511
+ let tNear = 0;
512
+ for (let s = 1; s <= marchSteps; s++) {
513
+ const t = s / marchSteps;
514
+ const mx = gxMid + backDx * t;
515
+ const mz = gzMid + backDz * t;
516
+ const vx = Math.floor(mx);
517
+ const vz = Math.floor(mz);
518
+ const hasFloor = isSolid(getVoxel(vx, wy, vz));
519
+ const blockedAbove = isSolid(getVoxel(vx, wy + 1, vz));
520
+ if (hasFloor && !blockedAbove) {
521
+ tNear = t;
522
+ }
523
+ else if (blockedAbove) {
524
+ // Reached the base of the step riser or caster wall at wy + 1
525
+ tNear = t;
526
+ break;
527
+ }
528
+ else {
529
+ // Terrace ended at a cliff drop-off; stop before floating over air
530
+ break;
531
+ }
532
+ }
533
+ if (tNear * backHorizDist < 0.08)
534
+ continue;
535
+ const cx0 = gx0 + backDx * tNear;
536
+ const cz0 = gz0 + backDz * tNear;
537
+ const cx1 = gx1 + backDx * tNear;
538
+ const cz1 = gz1 + backDz * tNear;
539
+ const flatY = offY + (gy + 0.012) * scale;
540
+ const nearDist = dPlane * (1 - tNear) * scale;
541
+ const farDist = dPlane * scale;
542
+ quads.push({
543
+ casterStart: new Vector3(offX + cx0 * scale, flatY, offZ + cz0 * scale),
544
+ casterEnd: new Vector3(offX + cx1 * scale, flatY, offZ + cz1 * scale),
545
+ groundStart: new Vector3(offX + gx0 * scale, flatY, offZ + gz0 * scale),
546
+ groundEnd: new Vector3(offX + gx1 * scale, flatY, offZ + gz1 * scale),
547
+ extrudeDistStart: farDist - nearDist,
548
+ extrudeDistEnd: farDist - nearDist,
549
+ });
550
+ }
551
+ continue;
552
+ }
348
553
  // Bias ray origins into the guaranteed-air voxel adjacent to the shadow-facing face
349
554
  // and slightly inward along the segment axis so Math.floor() never lands inside the caster voxel.
350
555
  const tx = edge.axis === 0 ? 1e-3 : 0;
@@ -400,20 +605,8 @@ export function projectSilhouetteEdges(options) {
400
605
  }
401
606
  const groundStart = new Vector3(offX + gx0 * scale, offY + gy0 * scale, offZ + gz0 * scale);
402
607
  const groundEnd = new Vector3(offX + gx1 * scale, offY + gy1 * scale, offZ + gz1 * scale);
403
- let casterStart;
404
- let casterEnd;
405
- if (flattenCaster && edge.axis !== 1) {
406
- casterStart = new Vector3(offX + edge.start.x * scale, groundStart.y, offZ + edge.start.z * scale);
407
- casterEnd = new Vector3(offX + edge.end.x * scale, groundEnd.y, offZ + edge.end.z * scale);
408
- }
409
- else if (flattenCaster && edge.axis === 1) {
410
- // Vertical edge in flattened ground-decal mode: skip since horizontal top edges cover the ground footprint
411
- continue;
412
- }
413
- else {
414
- casterStart = new Vector3(offX + edge.start.x * scale, offY + edge.start.y * scale, offZ + edge.start.z * scale);
415
- casterEnd = new Vector3(offX + edge.end.x * scale, offY + edge.end.y * scale, offZ + edge.end.z * scale);
416
- }
608
+ const casterStart = new Vector3(offX + edge.start.x * scale, offY + edge.start.y * scale, offZ + edge.start.z * scale);
609
+ const casterEnd = new Vector3(offX + edge.end.x * scale, offY + edge.end.y * scale, offZ + edge.end.z * scale);
417
610
  quads.push({
418
611
  casterStart,
419
612
  casterEnd,
@@ -426,14 +619,390 @@ export function projectSilhouetteEdges(options) {
426
619
  return quads;
427
620
  }
428
621
  /**
429
- * VoxelSilhouetteShadows — Lightweight, event-driven silhouette & sun-ray ground-projected
430
- * shadow system for @voxl optimized for older integrated GPUs (no shadow maps or per-pixel raytracing).
622
+ * Builds a 100% mathematically watertight, T-junction-free closed 3D shadow volume `∂(F × [frontBias, extrudeDistance])`
623
+ * directly from exposed sun-facing voxel faces `F` and their exact oriented silhouette boundary chain `∂F`,
624
+ * extruded along `-sunDirection` with outward CCW winding for two-sided Z-fail hardware stencil shadows.
625
+ */
626
+ export function buildClosedSilhouetteShadowVolume(options) {
627
+ const { originX, originY, originZ, sizeX, sizeY, sizeZ, getVoxel } = options;
628
+ const isSolid = options.isSolid ?? ((id) => id !== 0);
629
+ const scale = options.voxelScale ?? 1.0;
630
+ const offX = options.worldOffset?.x ?? 0;
631
+ const offY = options.worldOffset?.y ?? 0;
632
+ const offZ = options.worldOffset?.z ?? 0;
633
+ const frontBias = Math.max(0.005, options.frontBias ?? 0.06);
634
+ const extrudeDist = Math.max(frontBias + 0.5, options.extrudeDistance ?? 28);
635
+ const sLen = Math.hypot(options.sunDirection.x, options.sunDirection.y, options.sunDirection.z);
636
+ if (sLen < 1e-6) {
637
+ return {
638
+ positions: new Float32Array(0),
639
+ normals: new Float32Array(0),
640
+ extrudeDists: new Float32Array(0),
641
+ indices: new Uint32Array(0),
642
+ frontCapQuadCount: 0,
643
+ silhouetteEdgeCount: 0,
644
+ volumeQuadCount: 0,
645
+ vertexCount: 0,
646
+ indexCount: 0,
647
+ };
648
+ }
649
+ const sx = options.sunDirection.x / sLen;
650
+ const sy = options.sunDirection.y / sLen;
651
+ const sz = options.sunDirection.z / sLen;
652
+ const frontOffX = -sx * frontBias * scale;
653
+ const frontOffY = -sy * frontBias * scale;
654
+ const frontOffZ = -sz * frontBias * scale;
655
+ const backOffX = -sx * extrudeDist * scale;
656
+ const backOffY = -sy * extrudeDist * scale;
657
+ const backOffZ = -sz * extrudeDist * scale;
658
+ const farExtrudeWorld = (extrudeDist - frontBias) * scale;
659
+ const checkX = Math.abs(sx) > 1e-5 ? (sx >= 0 ? 1 : -1) : 0;
660
+ const checkY = Math.abs(sy) > 1e-5 ? (sy >= 0 ? 1 : -1) : 0;
661
+ const checkZ = Math.abs(sz) > 1e-5 ? (sz >= 0 ? 1 : -1) : 0;
662
+ const minY = options.minCasterY !== undefined ? Math.max(originY, options.minCasterY) : originY;
663
+ const maxX = originX + sizeX;
664
+ const maxY = originY + sizeY;
665
+ const maxZ = originZ + sizeZ;
666
+ // Store exposed sun-facing unit faces as flat tuples [faceCode, vx, vy, vz]
667
+ // faceCode: 0=+X, 1=-X, 2=+Y, 3=-Y, 4=+Z, 5=-Z
668
+ const faces = [];
669
+ const edgeMap = new Map();
670
+ const addEdge = (axis, c1, c2, u, dir) => {
671
+ const key = `${axis}:${c1},${c2},${u}`;
672
+ const existing = edgeMap.get(key);
673
+ if (existing !== undefined) {
674
+ existing.count += dir;
675
+ }
676
+ else {
677
+ edgeMap.set(key, { axis, c1, c2, u, count: dir });
678
+ }
679
+ };
680
+ for (let vy = minY; vy < maxY; vy++) {
681
+ for (let vz = originZ; vz < maxZ; vz++) {
682
+ for (let vx = originX; vx < maxX; vx++) {
683
+ if (!isSolid(getVoxel(vx, vy, vz)))
684
+ continue;
685
+ if (checkX === 1 && !isSolid(getVoxel(vx + 1, vy, vz))) {
686
+ faces.push(0, vx, vy, vz);
687
+ const x = vx + 1;
688
+ addEdge(2, x, vy, vz, -1);
689
+ addEdge(1, x, vz, vy, 1);
690
+ addEdge(2, x, vy + 1, vz, 1);
691
+ addEdge(1, x, vz + 1, vy, -1);
692
+ }
693
+ else if (checkX === -1 && !isSolid(getVoxel(vx - 1, vy, vz))) {
694
+ faces.push(1, vx, vy, vz);
695
+ const x = vx;
696
+ addEdge(2, x, vy, vz, 1);
697
+ addEdge(1, x, vz + 1, vy, 1);
698
+ addEdge(2, x, vy + 1, vz, -1);
699
+ addEdge(1, x, vz, vy, -1);
700
+ }
701
+ if (checkY === 1 && !isSolid(getVoxel(vx, vy + 1, vz))) {
702
+ faces.push(2, vx, vy, vz);
703
+ const y = vy + 1;
704
+ addEdge(0, y, vz + 1, vx, 1);
705
+ addEdge(2, vx + 1, y, vz, -1);
706
+ addEdge(0, y, vz, vx, -1);
707
+ addEdge(2, vx, y, vz, 1);
708
+ }
709
+ else if (checkY === -1 && !isSolid(getVoxel(vx, vy - 1, vz))) {
710
+ faces.push(3, vx, vy, vz);
711
+ const y = vy;
712
+ addEdge(0, y, vz, vx, 1);
713
+ addEdge(2, vx + 1, y, vz, 1);
714
+ addEdge(0, y, vz + 1, vx, -1);
715
+ addEdge(2, vx, y, vz, -1);
716
+ }
717
+ if (checkZ === 1 && !isSolid(getVoxel(vx, vy, vz + 1))) {
718
+ faces.push(4, vx, vy, vz);
719
+ const z = vz + 1;
720
+ addEdge(0, vy, z, vx, 1);
721
+ addEdge(1, vx + 1, z, vy, 1);
722
+ addEdge(0, vy + 1, z, vx, -1);
723
+ addEdge(1, vx, z, vy, -1);
724
+ }
725
+ else if (checkZ === -1 && !isSolid(getVoxel(vx, vy, vz - 1))) {
726
+ faces.push(5, vx, vy, vz);
727
+ const z = vz;
728
+ addEdge(0, vy, z, vx, -1);
729
+ addEdge(1, vx, z, vy, 1);
730
+ addEdge(0, vy + 1, z, vx, 1);
731
+ addEdge(1, vx + 1, z, vy, -1);
732
+ }
733
+ }
734
+ }
735
+ }
736
+ const frontCapQuadCount = faces.length / 4;
737
+ let silhouetteEdgeCount = 0;
738
+ for (const entry of edgeMap.values()) {
739
+ if (entry.count !== 0) {
740
+ silhouetteEdgeCount += Math.abs(entry.count);
741
+ }
742
+ }
743
+ const volumeQuadCount = frontCapQuadCount * 2 + silhouetteEdgeCount;
744
+ if (volumeQuadCount === 0) {
745
+ return {
746
+ positions: new Float32Array(0),
747
+ normals: new Float32Array(0),
748
+ extrudeDists: new Float32Array(0),
749
+ indices: new Uint32Array(0),
750
+ frontCapQuadCount: 0,
751
+ silhouetteEdgeCount: 0,
752
+ volumeQuadCount: 0,
753
+ vertexCount: 0,
754
+ indexCount: 0,
755
+ };
756
+ }
757
+ const vertexCount = volumeQuadCount * 4;
758
+ const indexCount = volumeQuadCount * 6;
759
+ const positions = new Float32Array(vertexCount * 3);
760
+ const normals = new Float32Array(vertexCount * 3);
761
+ const extrudeDists = new Float32Array(vertexCount);
762
+ const indices = new Uint32Array(indexCount);
763
+ let qIdx = 0;
764
+ const emitQuad = (x0, y0, z0, e0, x1, y1, z1, e1, x2, y2, z2, e2, x3, y3, z3, e3, nx, ny, nz) => {
765
+ const vBase = qIdx * 4;
766
+ const pBase = vBase * 3;
767
+ const iBase = qIdx * 6;
768
+ positions[pBase] = x0;
769
+ positions[pBase + 1] = y0;
770
+ positions[pBase + 2] = z0;
771
+ extrudeDists[vBase] = e0;
772
+ positions[pBase + 3] = x1;
773
+ positions[pBase + 4] = y1;
774
+ positions[pBase + 5] = z1;
775
+ extrudeDists[vBase + 1] = e1;
776
+ positions[pBase + 6] = x2;
777
+ positions[pBase + 7] = y2;
778
+ positions[pBase + 8] = z2;
779
+ extrudeDists[vBase + 2] = e2;
780
+ positions[pBase + 9] = x3;
781
+ positions[pBase + 10] = y3;
782
+ positions[pBase + 11] = z3;
783
+ extrudeDists[vBase + 3] = e3;
784
+ for (let k = 0; k < 4; k++) {
785
+ const nk = pBase + k * 3;
786
+ normals[nk] = nx;
787
+ normals[nk + 1] = ny;
788
+ normals[nk + 2] = nz;
789
+ }
790
+ indices[iBase] = vBase;
791
+ indices[iBase + 1] = vBase + 1;
792
+ indices[iBase + 2] = vBase + 2;
793
+ indices[iBase + 3] = vBase;
794
+ indices[iBase + 4] = vBase + 2;
795
+ indices[iBase + 5] = vBase + 3;
796
+ qIdx++;
797
+ };
798
+ // 1. Emit front caps (outward CCW, extrudeDist = 0) and back caps (flipped outward, extrudeDist = farExtrudeWorld)
799
+ for (let i = 0; i < faces.length; i += 4) {
800
+ const code = faces[i];
801
+ const vx = faces[i + 1];
802
+ const vy = faces[i + 2];
803
+ const vz = faces[i + 3];
804
+ let gx0 = 0, gy0 = 0, gz0 = 0;
805
+ let gx1 = 0, gy1 = 0, gz1 = 0;
806
+ let gx2 = 0, gy2 = 0, gz2 = 0;
807
+ let gx3 = 0, gy3 = 0, gz3 = 0;
808
+ let nx = 0, ny = 0, nz = 0;
809
+ if (code === 0) {
810
+ // +X
811
+ gx0 = vx + 1;
812
+ gy0 = vy;
813
+ gz0 = vz + 1;
814
+ gx1 = vx + 1;
815
+ gy1 = vy;
816
+ gz1 = vz;
817
+ gx2 = vx + 1;
818
+ gy2 = vy + 1;
819
+ gz2 = vz;
820
+ gx3 = vx + 1;
821
+ gy3 = vy + 1;
822
+ gz3 = vz + 1;
823
+ nx = 1;
824
+ }
825
+ else if (code === 1) {
826
+ // -X
827
+ gx0 = vx;
828
+ gy0 = vy;
829
+ gz0 = vz;
830
+ gx1 = vx;
831
+ gy1 = vy;
832
+ gz1 = vz + 1;
833
+ gx2 = vx;
834
+ gy2 = vy + 1;
835
+ gz2 = vz + 1;
836
+ gx3 = vx;
837
+ gy3 = vy + 1;
838
+ gz3 = vz;
839
+ nx = -1;
840
+ }
841
+ else if (code === 2) {
842
+ // +Y
843
+ gx0 = vx;
844
+ gy0 = vy + 1;
845
+ gz0 = vz + 1;
846
+ gx1 = vx + 1;
847
+ gy1 = vy + 1;
848
+ gz1 = vz + 1;
849
+ gx2 = vx + 1;
850
+ gy2 = vy + 1;
851
+ gz2 = vz;
852
+ gx3 = vx;
853
+ gy3 = vy + 1;
854
+ gz3 = vz;
855
+ ny = 1;
856
+ }
857
+ else if (code === 3) {
858
+ // -Y
859
+ gx0 = vx;
860
+ gy0 = vy;
861
+ gz0 = vz;
862
+ gx1 = vx + 1;
863
+ gy1 = vy;
864
+ gz1 = vz;
865
+ gx2 = vx + 1;
866
+ gy2 = vy;
867
+ gz2 = vz + 1;
868
+ gx3 = vx;
869
+ gy3 = vy;
870
+ gz3 = vz + 1;
871
+ ny = -1;
872
+ }
873
+ else if (code === 4) {
874
+ // +Z
875
+ gx0 = vx;
876
+ gy0 = vy;
877
+ gz0 = vz + 1;
878
+ gx1 = vx + 1;
879
+ gy1 = vy;
880
+ gz1 = vz + 1;
881
+ gx2 = vx + 1;
882
+ gy2 = vy + 1;
883
+ gz2 = vz + 1;
884
+ gx3 = vx;
885
+ gy3 = vy + 1;
886
+ gz3 = vz + 1;
887
+ nz = 1;
888
+ }
889
+ else {
890
+ // -Z
891
+ gx0 = vx + 1;
892
+ gy0 = vy;
893
+ gz0 = vz;
894
+ gx1 = vx;
895
+ gy1 = vy;
896
+ gz1 = vz;
897
+ gx2 = vx;
898
+ gy2 = vy + 1;
899
+ gz2 = vz;
900
+ gx3 = vx + 1;
901
+ gy3 = vy + 1;
902
+ gz3 = vz;
903
+ nz = -1;
904
+ }
905
+ const wx0 = offX + gx0 * scale;
906
+ const wy0 = offY + gy0 * scale;
907
+ const wz0 = offZ + gz0 * scale;
908
+ const wx1 = offX + gx1 * scale;
909
+ const wy1 = offY + gy1 * scale;
910
+ const wz1 = offZ + gz1 * scale;
911
+ const wx2 = offX + gx2 * scale;
912
+ const wy2 = offY + gy2 * scale;
913
+ const wz2 = offZ + gz2 * scale;
914
+ const wx3 = offX + gx3 * scale;
915
+ const wy3 = offY + gy3 * scale;
916
+ const wz3 = offZ + gz3 * scale;
917
+ // Front cap (CCW facing +N)
918
+ emitQuad(wx0 + frontOffX, wy0 + frontOffY, wz0 + frontOffZ, 0, wx1 + frontOffX, wy1 + frontOffY, wz1 + frontOffZ, 0, wx2 + frontOffX, wy2 + frontOffY, wz2 + frontOffZ, 0, wx3 + frontOffX, wy3 + frontOffY, wz3 + frontOffZ, 0, nx, ny, nz);
919
+ // Back cap (reversed winding: 0 -> 3 -> 2 -> 1, facing -N)
920
+ emitQuad(wx0 + backOffX, wy0 + backOffY, wz0 + backOffZ, farExtrudeWorld, wx3 + backOffX, wy3 + backOffY, wz3 + backOffZ, farExtrudeWorld, wx2 + backOffX, wy2 + backOffY, wz2 + backOffZ, farExtrudeWorld, wx1 + backOffX, wy1 + backOffY, wz1 + backOffZ, farExtrudeWorld, -nx, -ny, -nz);
921
+ }
922
+ // 2. Emit extruded silhouette side walls along every uncancelled boundary edge in ∂F
923
+ for (const entry of edgeMap.values()) {
924
+ if (entry.count === 0)
925
+ continue;
926
+ let p0x = 0, p0y = 0, p0z = 0;
927
+ let p1x = 0, p1y = 0, p1z = 0;
928
+ if (entry.axis === 0) {
929
+ p0x = entry.u;
930
+ p0y = entry.c1;
931
+ p0z = entry.c2;
932
+ p1x = entry.u + 1;
933
+ p1y = entry.c1;
934
+ p1z = entry.c2;
935
+ }
936
+ else if (entry.axis === 1) {
937
+ p0x = entry.c1;
938
+ p0y = entry.u;
939
+ p0z = entry.c2;
940
+ p1x = entry.c1;
941
+ p1y = entry.u + 1;
942
+ p1z = entry.c2;
943
+ }
944
+ else {
945
+ p0x = entry.c1;
946
+ p0y = entry.c2;
947
+ p0z = entry.u;
948
+ p1x = entry.c1;
949
+ p1y = entry.c2;
950
+ p1z = entry.u + 1;
951
+ }
952
+ if (entry.count < 0) {
953
+ const tx = p0x;
954
+ const ty = p0y;
955
+ const tz = p0z;
956
+ p0x = p1x;
957
+ p0y = p1y;
958
+ p0z = p1z;
959
+ p1x = tx;
960
+ p1y = ty;
961
+ p1z = tz;
962
+ }
963
+ const wx0 = offX + p0x * scale;
964
+ const wy0 = offY + p0y * scale;
965
+ const wz0 = offZ + p0z * scale;
966
+ const wx1 = offX + p1x * scale;
967
+ const wy1 = offY + p1y * scale;
968
+ const wz1 = offZ + p1z * scale;
969
+ // Outward normal: (p1 - p0) × (+sunDir)
970
+ const edx = p1x - p0x;
971
+ const edy = p1y - p0y;
972
+ const edz = p1z - p0z;
973
+ let nx = edy * sz - edz * sy;
974
+ let ny = edz * sx - edx * sz;
975
+ let nz = edx * sy - edy * sx;
976
+ const nLen = Math.hypot(nx, ny, nz);
977
+ if (nLen > 1e-6) {
978
+ nx /= nLen;
979
+ ny /= nLen;
980
+ nz /= nLen;
981
+ }
982
+ const copies = Math.abs(entry.count);
983
+ for (let c = 0; c < copies; c++) {
984
+ emitQuad(wx0 + frontOffX, wy0 + frontOffY, wz0 + frontOffZ, 0, wx0 + backOffX, wy0 + backOffY, wz0 + backOffZ, farExtrudeWorld, wx1 + backOffX, wy1 + backOffY, wz1 + backOffZ, farExtrudeWorld, wx1 + frontOffX, wy1 + frontOffY, wz1 + frontOffZ, 0, nx, ny, nz);
985
+ }
986
+ }
987
+ return {
988
+ positions,
989
+ normals,
990
+ extrudeDists,
991
+ indices,
992
+ frontCapQuadCount,
993
+ silhouetteEdgeCount,
994
+ volumeQuadCount,
995
+ vertexCount,
996
+ indexCount,
997
+ };
998
+ }
999
+ /**
1000
+ * VoxelSilhouetteShadows — Lightweight, event-driven silhouette & sun-ray shadow volume
1001
+ * system for @voxl optimized for older integrated GPUs (no shadow maps or per-pixel raytracing).
431
1002
  *
432
- * - Scans exposed top/side silhouette edges where sun-facing faces border air or shadow-facing faces.
433
- * - Merges collinear grid edges into longer segments to minimize vertex count.
434
- * - Projects silhouette edge endpoints along `-sunDirection` via 3D DDA (`raycastVoxels`) onto solid ground.
435
- * - Batches all shadow quads into a single merged `Mesh` with `polygonOffset`, `depthWrite: false`,
436
- * and an `extrudeDist` penumbra-fading shader.
1003
+ * - Extracts exposed sun-facing voxel surfaces and their exact oriented silhouette boundary edges.
1004
+ * - Extrudes watertight silhouette shadow volumes along `-sunDirection` for hardware two-sided
1005
+ * Z-fail stencil shadow rendering (zero overlap, crisp architectural shadows on terraces & walls).
437
1006
  * - Event-driven deferred updates: zero per-frame CPU/GPU work when voxels and sun angle are static.
438
1007
  */
439
1008
  export class VoxelSilhouetteShadows {
@@ -468,10 +1037,14 @@ export class VoxelSilhouetteShadows {
468
1037
  this.minCasterY = options.minCasterY;
469
1038
  this.maxSlicesPerUpdate = Math.max(1, Math.floor(options.maxSlicesPerUpdate ?? 64));
470
1039
  this.flattenCasterToGround = options.flattenCasterToGround ?? false;
1040
+ this.renderMode = options.renderMode ?? 'stencil-volume';
1041
+ this.frontBias = Math.max(0.005, options.frontBias ?? 0.06);
1042
+ const useStencil = this.renderMode === 'stencil-volume';
471
1043
  this.material = createVoxelSilhouetteShadowMaterial({
472
1044
  baseOpacity: preset.shadowOpacity,
473
1045
  penumbraSoftness: preset.penumbraSoftness,
474
1046
  ...options.materialOptions,
1047
+ stencilVolumePass: useStencil,
475
1048
  maxExtrudeDist: options.materialOptions?.maxExtrudeDist ?? this.maxRayDistance * this.voxelScale,
476
1049
  });
477
1050
  this.geometry = new BufferGeometry();
@@ -482,7 +1055,32 @@ export class VoxelSilhouetteShadows {
482
1055
  this.mesh = new Mesh(this.geometry, this.material);
483
1056
  this.mesh.name = 'VoxelSilhouetteShadows';
484
1057
  this.mesh.frustumCulled = false;
1058
+ this.mesh.renderOrder = useStencil ? -100 : 0;
485
1059
  this.mesh.visible = this._enabled;
1060
+ if (useStencil) {
1061
+ this.overlayGeometry = new BufferGeometry();
1062
+ this.overlayGeometry.setAttribute('position', new BufferAttribute(new Float32Array([
1063
+ -1, -1, 0,
1064
+ 1, -1, 0,
1065
+ 1, 1, 0,
1066
+ -1, 1, 0,
1067
+ ]), 3));
1068
+ this.overlayGeometry.setIndex(new BufferAttribute(new Uint16Array([0, 1, 2, 0, 2, 3]), 1));
1069
+ this.overlayMaterial = createVoxelSilhouetteShadowOverlayMaterial({
1070
+ uShadowColor: this.material.uniforms.uShadowColor,
1071
+ uBaseOpacity: this.material.uniforms.uBaseOpacity,
1072
+ });
1073
+ this.overlayMesh = new Mesh(this.overlayGeometry, this.overlayMaterial);
1074
+ this.overlayMesh.name = 'VoxelSilhouetteShadowsOverlay';
1075
+ this.overlayMesh.frustumCulled = false;
1076
+ this.overlayMesh.renderOrder = -99;
1077
+ this.mesh.add(this.overlayMesh);
1078
+ }
1079
+ else {
1080
+ this.overlayGeometry = null;
1081
+ this.overlayMaterial = null;
1082
+ this.overlayMesh = null;
1083
+ }
486
1084
  }
487
1085
  get enabled() {
488
1086
  return this._enabled;
@@ -817,6 +1415,28 @@ export class VoxelSilhouetteShadows {
817
1415
  sunDirection: this.sunDirection,
818
1416
  minCasterY: this.minCasterY,
819
1417
  });
1418
+ slice.edges = edges;
1419
+ if (this.renderMode === 'stencil-volume') {
1420
+ const vol = buildClosedSilhouetteShadowVolume({
1421
+ ...slice.bounds,
1422
+ getVoxel: this.getVoxel,
1423
+ isSolid: this.isSolid,
1424
+ sunDirection: this.sunDirection,
1425
+ minCasterY: this.minCasterY,
1426
+ extrudeDistance: this.maxRayDistance,
1427
+ frontBias: this.frontBias,
1428
+ voxelScale: this.voxelScale,
1429
+ worldOffset: this.worldOffset,
1430
+ });
1431
+ slice.quads = [];
1432
+ slice.positions = vol.positions;
1433
+ slice.normals = vol.normals;
1434
+ slice.extrudeDists = vol.extrudeDists;
1435
+ slice.indices = vol.indices;
1436
+ slice.vertexCount = vol.vertexCount;
1437
+ slice.indexCount = vol.indexCount;
1438
+ return;
1439
+ }
820
1440
  const quads = projectSilhouetteEdges({
821
1441
  edges,
822
1442
  sunDirection: this.sunDirection,
@@ -827,7 +1447,6 @@ export class VoxelSilhouetteShadows {
827
1447
  worldOffset: this.worldOffset,
828
1448
  flattenCasterToGround: this.flattenCasterToGround,
829
1449
  });
830
- slice.edges = edges;
831
1450
  slice.quads = quads;
832
1451
  const qCount = quads.length;
833
1452
  const vCount = qCount * 4;
@@ -913,7 +1532,7 @@ export class VoxelSilhouetteShadows {
913
1532
  totalVertices += slice.vertexCount;
914
1533
  totalIndices += slice.indexCount;
915
1534
  totalEdges += slice.edges.length;
916
- totalQuads += slice.quads.length;
1535
+ totalQuads += this.renderMode === 'stencil-volume' ? slice.vertexCount / 4 : slice.quads.length;
917
1536
  }
918
1537
  this.mergedEdgeCount = totalEdges;
919
1538
  this.quadCount = totalQuads;
@@ -952,6 +1571,8 @@ export class VoxelSilhouetteShadows {
952
1571
  dispose() {
953
1572
  this.geometry.dispose();
954
1573
  this.material.dispose();
1574
+ this.overlayGeometry?.dispose();
1575
+ this.overlayMaterial?.dispose();
955
1576
  this._slices.clear();
956
1577
  this._dirtySliceKeys.clear();
957
1578
  this._deferredBreakQueue.length = 0;