@pacem/pacem-3d 2.0.0-babbage → 2.0.0-chebyshev

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.
@@ -1,5 +1,5 @@
1
1
  /*!
2
- * @pacem/pacem-3d v2.0.0-babbage (https://js.pacem.it)
2
+ * @pacem/pacem-3d v2.0.0-chebyshev (https://js.pacem.it)
3
3
  * Pacem (https://pacem.it)
4
4
  * Licensed under Apache-2.0
5
5
  */
@@ -469,6 +469,7 @@ var StalePropertyFlag;
469
469
  StalePropertyFlag2["Light"] = "light";
470
470
  StalePropertyFlag2["Camera"] = "camera";
471
471
  StalePropertyFlag2["Visibility"] = "visibility";
472
+ StalePropertyFlag2["Shadow"] = "shadow";
472
473
  })(StalePropertyFlag || (StalePropertyFlag = {}));
473
474
  function isInteraction(object) {
474
475
  return typeof object === "object" && "time" in object && typeof object["time"] === "number";
@@ -642,6 +643,11 @@ Pacem3DGroupElement = __decorate2([
642
643
  CustomElement2({ tagName: Constants.GROUP_SELECTOR })
643
644
  ], Pacem3DGroupElement);
644
645
  var Pacem3DMeshElement = class Pacem3DMeshElement2 extends Ui3DElement {
646
+ constructor() {
647
+ super(...arguments);
648
+ this.castShadow = true;
649
+ this.receiveShadow = true;
650
+ }
645
651
  propertyChangedCallback(name, old, val, first) {
646
652
  super.propertyChangedCallback(name, old, val, first);
647
653
  switch (name) {
@@ -652,6 +658,10 @@ var Pacem3DMeshElement = class Pacem3DMeshElement2 extends Ui3DElement {
652
658
  case "backMaterial":
653
659
  this.setAsDirty(StalePropertyFlag.Material);
654
660
  break;
661
+ case "castShadow":
662
+ case "receiveShadow":
663
+ this.setAsDirty(StalePropertyFlag.Shadow);
664
+ break;
655
665
  }
656
666
  }
657
667
  };
@@ -664,6 +674,12 @@ __decorate2([
664
674
  __decorate2([
665
675
  Watch2({ emit: false, converter: PropertyConverters2.Json })
666
676
  ], Pacem3DMeshElement.prototype, "backMaterial", void 0);
677
+ __decorate2([
678
+ Watch2({ emit: false, converter: PropertyConverters2.Boolean })
679
+ ], Pacem3DMeshElement.prototype, "castShadow", void 0);
680
+ __decorate2([
681
+ Watch2({ emit: false, converter: PropertyConverters2.Boolean })
682
+ ], Pacem3DMeshElement.prototype, "receiveShadow", void 0);
667
683
  Pacem3DMeshElement = __decorate2([
668
684
  CustomElement2({ tagName: Constants.MESH_SELECTOR })
669
685
  ], Pacem3DMeshElement);
@@ -691,6 +707,9 @@ var Pacem3DLightElement = class Pacem3DLightElement2 extends RenderableElement {
691
707
  this.target = Constants.DEFAULT_COORDS;
692
708
  this.color = "#fff";
693
709
  this.type = "omni";
710
+ this.castShadow = false;
711
+ this.shadowMapSize = 2048;
712
+ this.shadowBias = 2e-3;
694
713
  }
695
714
  propertyChangedCallback(name, old, val, first) {
696
715
  super.propertyChangedCallback(name, old, val, first);
@@ -699,6 +718,9 @@ var Pacem3DLightElement = class Pacem3DLightElement2 extends RenderableElement {
699
718
  case "color":
700
719
  case "intensity":
701
720
  case "target":
721
+ case "castShadow":
722
+ case "shadowMapSize":
723
+ case "shadowBias":
702
724
  this.setAsDirty(StalePropertyFlag.Light);
703
725
  break;
704
726
  }
@@ -716,6 +738,15 @@ __decorate2([
716
738
  __decorate2([
717
739
  Watch2({ emit: false, converter: PropertyConverters2.String })
718
740
  ], Pacem3DLightElement.prototype, "type", void 0);
741
+ __decorate2([
742
+ Watch2({ emit: false, converter: PropertyConverters2.Boolean })
743
+ ], Pacem3DLightElement.prototype, "castShadow", void 0);
744
+ __decorate2([
745
+ Watch2({ emit: false, converter: PropertyConverters2.Number })
746
+ ], Pacem3DLightElement.prototype, "shadowMapSize", void 0);
747
+ __decorate2([
748
+ Watch2({ emit: false, converter: PropertyConverters2.Number })
749
+ ], Pacem3DLightElement.prototype, "shadowBias", void 0);
719
750
  Pacem3DLightElement = __decorate2([
720
751
  CustomElement2({ tagName: Constants.LIGHT_SELECTOR })
721
752
  ], Pacem3DLightElement);
@@ -2195,7 +2226,7 @@ var PacemPlaneElement = PacemPlaneElement_1 = class PacemPlaneElement2 extends P
2195
2226
  const nodes = [];
2196
2227
  const uv = [];
2197
2228
  const indices = [];
2198
- const normals = [], normal = Geometry3.LinearAlgebra.Vector3D.from(0, 0, 1);
2229
+ const normals = [], normal = Geometry3.LinearAlgebra.Vector3D.from(0, 1, 0);
2199
2230
  for (let j = 0; j <= lengthSegments; j++) {
2200
2231
  for (let i = 0; i <= widthSegments; i++) {
2201
2232
  const x = -halfWidth + i * width / (1 * widthSegments);
@@ -3727,13 +3758,13 @@ Pacem3DThreeAdapterElement = __decorate20([
3727
3758
  ], Pacem3DThreeAdapterElement);
3728
3759
 
3729
3760
  // packages/3d/dist/esm/adapters/webgpu/webgpuadapter.js
3730
- import { CustomElementUtils as CustomElementUtils3, CustomElement as CustomElement17, P as P18, Watch as Watch18, PropertyConverters as PropertyConverters18, PropertyChangeEvent as PropertyChangeEvent2, PropertyChangeEventName as PropertyChangeEventName2, Debounce, Utils as Utils28, Logging as Logging3, Components as Components3 } from "@pacem/pacem-core";
3761
+ import { CustomElementUtils as CustomElementUtils3, CustomElement as CustomElement17, P as P18, Watch as Watch18, PropertyConverters as PropertyConverters18, PropertyChangeEvent as PropertyChangeEvent2, PropertyChangeEventName as PropertyChangeEventName2, Debounce, Utils as Utils29, Logging as Logging3, Components as Components3 } from "@pacem/pacem-core";
3731
3762
  import { Strings } from "@pacem/pacem-foundation";
3732
3763
 
3733
3764
  // packages/3d/dist/esm/adapters/webgpu/renderer.js
3734
- import { Utils as Utils27, P as P17, Logging as Logging2 } from "@pacem/pacem-core";
3765
+ import { Utils as Utils28, P as P17, Logging as Logging2 } from "@pacem/pacem-core";
3735
3766
  import { Colors as Colors4 } from "@pacem/pacem-foundation";
3736
- import { Geometry as Geometry8 } from "@pacem/pacem-numerical";
3767
+ import { Geometry as Geometry10 } from "@pacem/pacem-numerical";
3737
3768
 
3738
3769
  // packages/3d/dist/esm/adapters/webgpu/constants.js
3739
3770
  var LABEL_PREFIX = "pacem-3d-";
@@ -3767,6 +3798,12 @@ var ABUFFER_BINDING_INDEX_HEADS = 2;
3767
3798
  var ABUFFER_BINDING_INDEX_LIST = 3;
3768
3799
  var ABUFFER_BINDING_INDEX_INFO = 4;
3769
3800
  var ABUFFER_BINDING_INDEX_DEPTH = 5;
3801
+ var ABUFFER_REVERSED_Z_CONSTANT = "REVERSED_Z";
3802
+ var MAX_SHADOW_LAYERS = 12;
3803
+ var SHADOW_BINDING_MAP = 100;
3804
+ var SHADOW_BINDING_SAMPLER = 101;
3805
+ var SHADOW_BINDING_LIGHTS = 102;
3806
+ var SHADOW_MAP_FORMAT = "depth32float";
3770
3807
  var ABUFFER_AVERAGE_LAYERS = 4;
3771
3808
  var ABUFFER_MAX_SORTED_LAYERS = 16;
3772
3809
  var WGSL_VERTEXINPUT_STRUCT_NAME = "VertexInput";
@@ -3806,7 +3843,7 @@ var GPUMapMode;
3806
3843
  })(GPUMapMode || (GPUMapMode = {}));
3807
3844
 
3808
3845
  // packages/3d/dist/esm/adapters/webgpu/pipelinefactory.js
3809
- import { Utils as Utils24 } from "@pacem/pacem-core";
3846
+ import { Utils as Utils25 } from "@pacem/pacem-core";
3810
3847
 
3811
3848
  // packages/3d/dist/esm/adapters/webgpu/abstractions.js
3812
3849
  var WGSLBindingType;
@@ -3924,9 +3961,17 @@ var INFO_STRUCT = `struct ABufferInfo {
3924
3961
  capacity: u32,
3925
3962
  padding: u32,
3926
3963
  }`;
3964
+ var DEPTH_DIRECTION = `override ${ABUFFER_REVERSED_Z_CONSTANT}: bool = false;
3965
+
3966
+ fn aBufferCloser(depth: f32, other: f32) -> bool {
3967
+ if (${ABUFFER_REVERSED_Z_CONSTANT}) {
3968
+ return depth > other;
3969
+ }
3970
+ return depth < other;
3971
+ }`;
3927
3972
  function aBufferFragmentExtra(group = UNIFORM_GROUP_INDEX_CAMERA) {
3928
3973
  return {
3929
- definitions: [FRAGMENT_STRUCT, INFO_STRUCT, `struct ABufferHeads {
3974
+ definitions: [FRAGMENT_STRUCT, INFO_STRUCT, DEPTH_DIRECTION, `struct ABufferHeads {
3930
3975
  count: atomic<u32>,
3931
3976
  data: array<atomic<u32>>,
3932
3977
  }`],
@@ -3948,7 +3993,7 @@ function aBufferFragmentExtra(group = UNIFORM_GROUP_INDEX_CAMERA) {
3948
3993
  }
3949
3994
  // manual depth test against the opaque geometry
3950
3995
  let opaqueDepth = textureLoad(aBufferOpaqueDepth, pixel, 0);
3951
- if (position.z >= opaqueDepth) {
3996
+ if (!aBufferCloser(position.z, opaqueDepth)) {
3952
3997
  return;
3953
3998
  }
3954
3999
  let slot = atomicAdd(&aBufferHeads.count, 1u);
@@ -3970,6 +4015,8 @@ function getABufferCompositeWgsl() {
3970
4015
 
3971
4016
  ${INFO_STRUCT}
3972
4017
 
4018
+ ${DEPTH_DIRECTION}
4019
+
3973
4020
  struct ABufferHeads {
3974
4021
  count: u32,
3975
4022
  data: array<u32>,
@@ -4005,7 +4052,7 @@ const MAX_LAYERS = ${ABUFFER_MAX_SORTED_LAYERS}u;
4005
4052
  for (var i = 1u; i < count; i++) {
4006
4053
  let item = layers[i];
4007
4054
  var j = i;
4008
- while (j > 0u && layers[j - 1u].depth < item.depth) {
4055
+ while (j > 0u && aBufferCloser(layers[j - 1u].depth, item.depth)) {
4009
4056
  layers[j] = layers[j - 1u];
4010
4057
  j--;
4011
4058
  }
@@ -4670,27 +4717,35 @@ function directionalLight(references, group, binding) {
4670
4717
  const key = Utils20.uniqueCode();
4671
4718
  const lightReference = `directional_${key}`;
4672
4719
  const ref = Utils20.extend({}, DefaultDirectionalLightReferences, references);
4673
- const inputColor = ref.inputColor, outputColor = ref.outputColor, normal = ref.normal ?? "normal";
4720
+ const inputColor = ref.inputColor, outputColor = ref.outputColor, normal = ref.normal ?? "normal", shadowLayer = ref.shadowLayer;
4674
4721
  if (Utils20.isNullOrEmpty(inputColor)) {
4675
4722
  throw new Error("Must provide input vertex color parameter name.");
4676
4723
  }
4724
+ const casting = Number.isInteger(shadowLayer);
4725
+ if (casting && Utils20.isNullOrEmpty(ref.position)) {
4726
+ throw new Error("Must provide the world position parameter name of a shadow-casting light.");
4727
+ }
4728
+ const visibility = casting ? `shadowVisibility(${shadowLayer}u, ${ref.position}, ${normal})` : "1.0";
4729
+ const contribution = `computeDirectional(${normal}, ${inputColor}, ${lightReference}, ${visibility})`;
4677
4730
  return {
4678
4731
  // type definitions
4679
4732
  definitions: [`struct DirectionalLight {
4680
4733
  color: vec4f,
4681
4734
  direction: vec3f,
4682
4735
  intensity: f32
4683
- }`, `fn computeDirectional(normal: vec3f, color: vec4f, light: DirectionalLight) -> vec4f {
4736
+ }`, `fn computeDirectional(normal: vec3f, color: vec4f, light: DirectionalLight, visibility: f32) -> vec4f {
4684
4737
  let n = normalize(normal);
4685
4738
  let d = normalize(light.direction);
4686
- let factor = light.intensity * .5 * (1.0 + dot(n, -d));
4739
+ let ndl = dot(n, -d);
4740
+ // half-Lambert: the shadow (visibility < 1) only dims the lit half
4741
+ let factor = light.intensity * .5 * (1.0 + min(ndl, 0.0) + visibility * max(ndl, 0.0));
4687
4742
  let output = color.rgb * light.color.rgb * factor;
4688
4743
  return vec4f(output, color.a);
4689
4744
  }`],
4690
4745
  // bindings
4691
4746
  bindings: [`@group(${group}) @binding(${binding}) var<uniform> ${lightReference}: DirectionalLight;`],
4692
4747
  // modifiers
4693
- modifiers: outputColor ? [`${outputColor} += computeDirectional(${normal}, ${inputColor}, ${lightReference});`] : [`computeDirectional(${normal}, ${inputColor}, ${lightReference})`]
4748
+ modifiers: outputColor ? [`${outputColor} += ${contribution};`] : [contribution]
4694
4749
  };
4695
4750
  }
4696
4751
 
@@ -4708,27 +4763,31 @@ function omniLight(references, group, binding) {
4708
4763
  const key = Utils21.uniqueCode();
4709
4764
  const lightReference = `omni_${key}`;
4710
4765
  const ref = Utils21.extend({}, DefaultOmniLightReferences, references);
4711
- const inputColor = ref.inputColor, outputColor = ref.outputColor, normal = ref.normal, ray = ref.ray, vertex = ref.position, shininess = ref.shininess, specularColor = ref.specularColor;
4766
+ const inputColor = ref.inputColor, outputColor = ref.outputColor, normal = ref.normal, ray = ref.ray, vertex = ref.position, shininess = ref.shininess, specularColor = ref.specularColor, shadowLayer = ref.shadowLayer;
4712
4767
  if (Utils21.isNullOrEmpty(inputColor)) {
4713
4768
  throw new Error("Must provide input vertex color parameter name.");
4714
4769
  }
4770
+ const casting = Number.isInteger(shadowLayer);
4771
+ const visibility = casting ? `shadowVisibilityOmni(${shadowLayer}u, ${lightReference}.position, ${vertex}, ${normal})` : "1.0";
4772
+ const contribution = `computeOmni(${vertex}, ${normal}, ${ray}, ${inputColor}, ${specularColor}, ${shininess}, ${lightReference}, ${visibility})`;
4715
4773
  return {
4716
4774
  // type definitions
4717
4775
  definitions: [`struct OmniLight {
4718
4776
  color: vec4f,
4719
4777
  position: vec3f,
4720
4778
  intensity: f32
4721
- }`, `fn computeOmni(position: vec3f, normal: vec3f, ray: vec3f, color: vec4f, specularColor: vec4f, shininess: f32, light: OmniLight) -> vec4f {
4779
+ }`, `fn computeOmni(position: vec3f, normal: vec3f, ray: vec3f, color: vec4f, specularColor: vec4f, shininess: f32, light: OmniLight, visibility: f32) -> vec4f {
4722
4780
 
4723
- // color
4781
+ // color (half-Lambert: the shadow, visibility < 1, only dims the lit half)
4724
4782
  let n = normalize(normal);
4725
4783
  let d = normalize(position - light.position);
4726
- let factor = light.intensity * .5 * (1.0 + dot(n, -d));
4784
+ let ndl = dot(n, -d);
4785
+ let factor = light.intensity * .5 * (1.0 + min(ndl, 0.0) + visibility * max(ndl, 0.0));
4727
4786
 
4728
- // specular
4787
+ // specular (no highlight in the shadow)
4729
4788
  let r = normalize(ray);
4730
4789
  let halfVector = normalize(d + r);
4731
- let specular = specularColor.rgb * shininess * dot(n, -halfVector);
4790
+ let specular = specularColor.rgb * shininess * dot(n, -halfVector) * visibility;
4732
4791
 
4733
4792
  let output = color.rgb * light.color.rgb * factor + specular;
4734
4793
  return vec4f(output, color.a);
@@ -4736,7 +4795,7 @@ function omniLight(references, group, binding) {
4736
4795
  // bindings
4737
4796
  bindings: [`@group(${group}) @binding(${binding}) var<uniform> ${lightReference}: OmniLight;`],
4738
4797
  // modifiers
4739
- modifiers: outputColor ? [`${outputColor} += computeOmni(${vertex}, ${normal}, ${ray}, ${inputColor}, ${specularColor}, ${shininess}, ${lightReference});`] : [`computeOmni(${vertex}, ${normal}, ${ray}, ${inputColor}, ${specularColor}, ${shininess}, ${lightReference})`]
4798
+ modifiers: outputColor ? [`${outputColor} += ${contribution};`] : [contribution]
4740
4799
  };
4741
4800
  }
4742
4801
 
@@ -4765,9 +4824,66 @@ function ambientLight(references, group, binding) {
4765
4824
  };
4766
4825
  }
4767
4826
 
4768
- // packages/3d/dist/esm/adapters/webgpu/renderablebuffer.js
4827
+ // packages/3d/dist/esm/adapters/webgpu/wgsl/shadow-fragment.js
4828
+ var SHADOW_LIGHT_STRUCT = `struct ShadowLight {
4829
+ viewProjection: mat4x4f,
4830
+ normalOffset: f32,
4831
+ texelSize: f32,
4832
+ padding0: f32,
4833
+ padding1: f32,
4834
+ }`;
4835
+ var SHADOW_VISIBILITY_FUNCTION = `fn shadowVisibility(layer: u32, position: vec3f, normal: vec3f) -> f32 {
4836
+ let light = shadowLights[layer];
4837
+
4838
+ // normal offset: the receiver is pushed off its surface along the normal before being projected (fights acne)
4839
+ let offsetPosition = position + normalize(normal) * light.normalOffset;
4840
+ let clip = light.viewProjection * vec4f(offsetPosition, 1.0);
4841
+ let ndc = clip.xyz / clip.w;
4842
+
4843
+ // NDC (y up) to texture coordinates (v down)
4844
+ let uv = vec2f(ndc.x * 0.5 + 0.5, 0.5 - ndc.y * 0.5);
4845
+ let outside = any(uv < vec2f(0.0)) || any(uv > vec2f(1.0)) || ndc.z > 1.0;
4846
+ if (outside) {
4847
+ return 1.0;
4848
+ }
4849
+
4850
+ // 3x3 percentage-closer filtering: each tap compares in hardware, bilinearly weighted
4851
+ var lit = 0.0;
4852
+ for (var y = -1; y <= 1; y++) {
4853
+ for (var x = -1; x <= 1; x++) {
4854
+ let offset = vec2f(f32(x), f32(y)) * light.texelSize;
4855
+ lit += textureSampleCompareLevel(shadowMap, shadowSampler, uv + offset, layer, ndc.z);
4856
+ }
4857
+ }
4858
+ return lit / 9.0;
4859
+ }`;
4860
+ var SHADOW_VISIBILITY_OMNI_FUNCTION = `fn shadowVisibilityOmni(firstLayer: u32, lightPosition: vec3f, position: vec3f, normal: vec3f) -> f32 {
4861
+ // the cube face along the major axis of the light-to-fragment vector (+x, -x, +y, -y, +z, -z: see shadows.ts)
4862
+ let v = position - lightPosition;
4863
+ let a = abs(v);
4864
+ var face = select(1u, 0u, v.x > 0.0);
4865
+ if (a.y >= a.x && a.y >= a.z) {
4866
+ face = select(3u, 2u, v.y > 0.0);
4867
+ }
4868
+ if (a.z >= a.x && a.z >= a.y) {
4869
+ face = select(5u, 4u, v.z > 0.0);
4870
+ }
4871
+ return shadowVisibility(firstLayer + face, position, normal);
4872
+ }`;
4873
+ function shadowFragmentExtra(group) {
4874
+ return {
4875
+ definitions: [SHADOW_LIGHT_STRUCT, SHADOW_VISIBILITY_FUNCTION, SHADOW_VISIBILITY_OMNI_FUNCTION],
4876
+ bindings: [
4877
+ `@group(${group}) @binding(${SHADOW_BINDING_MAP}) var shadowMap: texture_depth_2d_array;`,
4878
+ `@group(${group}) @binding(${SHADOW_BINDING_SAMPLER}) var shadowSampler: sampler_comparison;`,
4879
+ `@group(${group}) @binding(${SHADOW_BINDING_LIGHTS}) var<uniform> shadowLights: array<ShadowLight, ${MAX_SHADOW_LAYERS}>;`
4880
+ ],
4881
+ modifiers: []
4882
+ };
4883
+ }
4884
+
4885
+ // packages/3d/dist/esm/adapters/webgpu/shadows.js
4769
4886
  import { Utils as Utils23 } from "@pacem/pacem-core";
4770
- import { Colors as Colors3 } from "@pacem/pacem-foundation";
4771
4887
  import { Geometry as Geometry7 } from "@pacem/pacem-numerical";
4772
4888
 
4773
4889
  // packages/3d/dist/esm/adapters/webgpu/cameras.js
@@ -4890,9 +5006,359 @@ var PerspectiveCamera = class _PerspectiveCamera {
4890
5006
  }
4891
5007
  };
4892
5008
 
4893
- // packages/3d/dist/esm/adapters/webgpu/renderablebuffer.js
5009
+ // packages/3d/dist/esm/adapters/webgpu/shadows.js
4894
5010
  var Vector3D2 = Geometry7.LinearAlgebra.Vector3D;
4895
5011
  var Matrix3D2 = Geometry7.LinearAlgebra.Matrix3D;
5012
+ var SHADOW_LIGHT_FLOATS = 20;
5013
+ var CAMERA_FLOATS = 36;
5014
+ var MIN_MAP_SIZE = 256;
5015
+ var CUBE_FACE_FOV = 95;
5016
+ var CUBE_FACES = [
5017
+ { axis: { x: 1, y: 0, z: 0 }, up: { x: 0, y: 1, z: 0 } },
5018
+ { axis: { x: -1, y: 0, z: 0 }, up: { x: 0, y: 1, z: 0 } },
5019
+ { axis: { x: 0, y: 1, z: 0 }, up: { x: 0, y: 0, z: 1 } },
5020
+ { axis: { x: 0, y: -1, z: 0 }, up: { x: 0, y: 0, z: 1 } },
5021
+ { axis: { x: 0, y: 0, z: 1 }, up: { x: 0, y: 1, z: 0 } },
5022
+ { axis: { x: 0, y: 0, z: -1 }, up: { x: 0, y: 1, z: 0 } }
5023
+ ];
5024
+ function isShadowCaster(light) {
5025
+ if (light.castShadow !== true) {
5026
+ return false;
5027
+ }
5028
+ return light.type === "direction" || light.type === "omni";
5029
+ }
5030
+ function shadowLayerCount(light) {
5031
+ return light.type === "omni" ? CUBE_FACES.length : 1;
5032
+ }
5033
+ function allocateShadowLayers(items, lightOf) {
5034
+ const layers = /* @__PURE__ */ new Map();
5035
+ let next = 0;
5036
+ for (let item of items) {
5037
+ const light = lightOf(item);
5038
+ if (!isShadowCaster(light)) {
5039
+ continue;
5040
+ }
5041
+ const count = shadowLayerCount(light);
5042
+ if (next + count > MAX_SHADOW_LAYERS) {
5043
+ continue;
5044
+ }
5045
+ layers.set(item, next);
5046
+ next += count;
5047
+ }
5048
+ return layers;
5049
+ }
5050
+ function castsShadow(mesh) {
5051
+ return mesh.castShadow !== false;
5052
+ }
5053
+ function receivesShadow(mesh) {
5054
+ return mesh.receiveShadow !== false;
5055
+ }
5056
+ function transformPoint(m, x, y, z) {
5057
+ return {
5058
+ x: x * m[0] + y * m[4] + z * m[8] + m[12],
5059
+ y: x * m[1] + y * m[5] + z * m[9] + m[13],
5060
+ z: x * m[2] + y * m[6] + z * m[10] + m[14]
5061
+ };
5062
+ }
5063
+ function enclose(box, point) {
5064
+ box.minX = Math.min(box.minX, point.x);
5065
+ box.minY = Math.min(box.minY, point.y);
5066
+ box.minZ = Math.min(box.minZ, point.z);
5067
+ box.maxX = Math.max(box.maxX, point.x);
5068
+ box.maxY = Math.max(box.maxY, point.y);
5069
+ box.maxZ = Math.max(box.maxZ, point.z);
5070
+ }
5071
+ function along(origin, direction, scale) {
5072
+ return { x: origin.x + scale * direction.x, y: origin.y + scale * direction.y, z: origin.z + scale * direction.z };
5073
+ }
5074
+ var ShadowCamera = class {
5075
+ #buffer;
5076
+ #disposed = false;
5077
+ constructor(_device, _index) {
5078
+ this._device = _device;
5079
+ this._index = _index;
5080
+ }
5081
+ /** Uploads the layer's view and view-projection matrices (and its eye position). */
5082
+ write(light, viewMatrix, viewProjection, eye) {
5083
+ this.item = light;
5084
+ const viewArray = Matrix3D2.toArray(viewMatrix), viewProjectionArray = Matrix3D2.toArray(viewProjection);
5085
+ const value = new Float32Array(CAMERA_FLOATS);
5086
+ value.set(viewArray, 0);
5087
+ value.set(viewProjectionArray, 16);
5088
+ value.set([eye.x, eye.y, eye.z], 32);
5089
+ const current = this.#buffer;
5090
+ if (!Utils23.isNull(current)) {
5091
+ Buffers.write(this._device, current.buffer, value);
5092
+ current.value = value;
5093
+ current.version = performance.now();
5094
+ return;
5095
+ }
5096
+ const buffer = Buffers.createUniform(this._device, value, LABEL_PREFIX + "shadow-camera-" + this._index + "-buffer");
5097
+ this.#buffer = { buffer, value, version: performance.now() };
5098
+ }
5099
+ buffer(_, key) {
5100
+ if (key !== "cameraViewTransform") {
5101
+ throw new Error(`Buffer "${key}" not available on a shadow camera.`);
5102
+ }
5103
+ return this.#buffer;
5104
+ }
5105
+ texture(_) {
5106
+ throw new Error("Method not implemented.");
5107
+ }
5108
+ lock() {
5109
+ }
5110
+ unlock() {
5111
+ }
5112
+ destroy() {
5113
+ this.#buffer?.buffer.destroy();
5114
+ this.#buffer = null;
5115
+ this.#disposed = true;
5116
+ }
5117
+ get disposed() {
5118
+ return this.#disposed;
5119
+ }
5120
+ };
5121
+ var Shadows = class _Shadows {
5122
+ static {
5123
+ this._instances = /* @__PURE__ */ new WeakMap();
5124
+ }
5125
+ /** Gets the shadow resources of `ctx`, creating them on first use. */
5126
+ static ensure(ctx) {
5127
+ const existing = this._instances.get(ctx);
5128
+ if (!Utils23.isNull(existing)) {
5129
+ return existing;
5130
+ }
5131
+ const created = new _Shadows(ctx);
5132
+ this._instances.set(ctx, created);
5133
+ return created;
5134
+ }
5135
+ /** Gets the shadow resources of `ctx`, if any. */
5136
+ static of(ctx) {
5137
+ return this._instances.get(ctx) ?? null;
5138
+ }
5139
+ /** Destroys the shadow resources of `ctx`, if any. */
5140
+ static dispose(ctx) {
5141
+ const existing = this._instances.get(ctx);
5142
+ this._instances.delete(ctx);
5143
+ existing?.destroy();
5144
+ }
5145
+ #sampler;
5146
+ #lights;
5147
+ #texture;
5148
+ #map;
5149
+ #layers = [];
5150
+ #cameras = [];
5151
+ #layerCount = 0;
5152
+ constructor(_context) {
5153
+ this._context = _context;
5154
+ const { device } = _context;
5155
+ this.#sampler = device.createSampler({
5156
+ label: LABEL_PREFIX + "shadow-sampler",
5157
+ compare: "less",
5158
+ magFilter: "linear",
5159
+ minFilter: "linear",
5160
+ addressModeU: "clamp-to-edge",
5161
+ addressModeV: "clamp-to-edge"
5162
+ });
5163
+ const lights = new Float32Array(SHADOW_LIGHT_FLOATS * MAX_SHADOW_LAYERS);
5164
+ this.#lights = Buffers.createUniform(device, lights, LABEL_PREFIX + "shadow-lights-buffer");
5165
+ }
5166
+ /** View of all the shadow map layers (`texture_depth_2d_array`), bound to the receivers. */
5167
+ get map() {
5168
+ return this.#map;
5169
+ }
5170
+ /** Comparison sampler of the shadow maps. */
5171
+ get sampler() {
5172
+ return this.#sampler;
5173
+ }
5174
+ /** Uniform array of the shadow map layers (`array<ShadowLight, MAX_SHADOW_LAYERS>`). */
5175
+ get lights() {
5176
+ return this.#lights;
5177
+ }
5178
+ /** Number of shadow map layers rendered by the last {@link update}. */
5179
+ get layerCount() {
5180
+ return this.#layerCount;
5181
+ }
5182
+ /** Render target (depth attachment) of the `index`-th shadow map layer. */
5183
+ layer(index) {
5184
+ return this.#layers.at(index);
5185
+ }
5186
+ /** Camera-like buffer the `index`-th shadow map layer renders from. */
5187
+ camera(index) {
5188
+ return this.#cameras.at(index);
5189
+ }
5190
+ /**
5191
+ * Fits the light-space projections of `casters` (as laid out by {@link allocateShadowLayers}) to the visible
5192
+ * `meshes` and uploads them, (re)creating the shadow maps when their size or layer count changes.
5193
+ */
5194
+ update(casters, meshes) {
5195
+ const counts = casters.map((c) => c.firstLayer + shadowLayerCount(c.light));
5196
+ const layerCount = Math.max(0, ...counts);
5197
+ const lights = casters.map((c) => c.light);
5198
+ const size = this._mapSize(lights);
5199
+ this._ensureTexture(size, Math.max(1, layerCount));
5200
+ this._ensureCameras(layerCount);
5201
+ this.#layerCount = layerCount;
5202
+ const sphere = this._boundingSphere(meshes);
5203
+ const values = new Float32Array(SHADOW_LIGHT_FLOATS * MAX_SHADOW_LAYERS);
5204
+ for (let { light, firstLayer } of casters) {
5205
+ if (light.type === "omni") {
5206
+ this._updateOmniLight(light, sphere, size, firstLayer, values);
5207
+ } else {
5208
+ this._updateDirectionalLight(light, sphere, size, firstLayer, values);
5209
+ }
5210
+ }
5211
+ Buffers.write(this._context.device, this.#lights, values);
5212
+ }
5213
+ /** Writes the `layer`-th camera and its `ShadowLight` uniform entry. */
5214
+ _writeLayer(light, layer, viewMatrix, projection, eye, normalOffset, size, values) {
5215
+ const viewProjection = Matrix3D2.multiply(viewMatrix, projection);
5216
+ this.#cameras.at(layer).write(light, viewMatrix, viewProjection, eye);
5217
+ const offset = SHADOW_LIGHT_FLOATS * layer;
5218
+ const viewProjectionArray = Matrix3D2.toArray(viewProjection);
5219
+ values.set(viewProjectionArray, offset);
5220
+ values.set([normalOffset, 1 / size], offset + 16);
5221
+ }
5222
+ _updateDirectionalLight(light, sphere, size, layer, values) {
5223
+ const { center, radius } = sphere;
5224
+ const position = light.position ?? Vector3D2.zero();
5225
+ const target = light.target ?? Vector3D2.zero();
5226
+ const direction = { x: target.x - position.x, y: target.y - position.y, z: target.z - position.z };
5227
+ const length = Vector3D2.mag(direction);
5228
+ const dir = length > 0 ? { x: direction.x / length, y: direction.y / length, z: direction.z / length } : { x: 0, y: -1, z: 0 };
5229
+ const eye = along(center, dir, -2 * radius);
5230
+ const up = Math.abs(dir.y) > 0.99 ? { x: 0, y: 0, z: 1 } : { x: 0, y: 1, z: 0 };
5231
+ const viewMatrix = view(eye, center, up);
5232
+ const projection = orthographic(-radius, radius, radius, -radius, 0.5 * radius, 3.5 * radius);
5233
+ const bias = light.shadowBias ?? 2e-3;
5234
+ this._writeLayer(light, layer, viewMatrix, projection, eye, bias * radius, size, values);
5235
+ }
5236
+ _updateOmniLight(light, sphere, size, firstLayer, values) {
5237
+ const { center, radius } = sphere;
5238
+ const eye = light.position ?? Vector3D2.zero();
5239
+ const toCenter = { x: center.x - eye.x, y: center.y - eye.y, z: center.z - eye.z };
5240
+ const distance = Vector3D2.mag(toCenter);
5241
+ const far = distance + radius;
5242
+ const near = Math.max(2e-3 * far, 0.01);
5243
+ const projection = perspective(CUBE_FACE_FOV, 1, near, far);
5244
+ const bias = light.shadowBias ?? 2e-3;
5245
+ for (let i = 0; i < CUBE_FACES.length; i++) {
5246
+ const { axis, up } = CUBE_FACES[i];
5247
+ const target = along(eye, axis, 1);
5248
+ const viewMatrix = view(eye, target, up);
5249
+ this._writeLayer(light, firstLayer + i, viewMatrix, projection, eye, bias * far, size, values);
5250
+ }
5251
+ }
5252
+ /** World-space bounding sphere of the visible meshes (the one enclosing their world-space bounding box). */
5253
+ _boundingSphere(meshes) {
5254
+ const ctx = this._context;
5255
+ const box = { minX: Infinity, minY: Infinity, minZ: Infinity, maxX: -Infinity, maxY: -Infinity, maxZ: -Infinity };
5256
+ for (let buffer of meshes) {
5257
+ const mesh = buffer.item;
5258
+ const local = mesh.geometry?.boundingBox;
5259
+ if (buffer.disposed || mesh.hide || Utils23.isNull(local) || !Number.isFinite(local.minX)) {
5260
+ continue;
5261
+ }
5262
+ const { value: world } = buffer.buffer(ctx, "objectWorldTransform");
5263
+ for (let x of [local.minX, local.maxX]) {
5264
+ for (let y of [local.minY, local.maxY]) {
5265
+ for (let z of [local.minZ, local.maxZ]) {
5266
+ const corner = transformPoint(world, x, y, z);
5267
+ enclose(box, corner);
5268
+ }
5269
+ }
5270
+ }
5271
+ }
5272
+ if (!Number.isFinite(box.minX)) {
5273
+ return { center: Vector3D2.zero(), radius: 1 };
5274
+ }
5275
+ const center = { x: (box.minX + box.maxX) / 2, y: (box.minY + box.maxY) / 2, z: (box.minZ + box.maxZ) / 2 };
5276
+ const halfDiagonal = { x: (box.maxX - box.minX) / 2, y: (box.maxY - box.minY) / 2, z: (box.maxZ - box.minZ) / 2 };
5277
+ const radius = Vector3D2.mag(halfDiagonal);
5278
+ return { center, radius: radius > 0 ? radius : 1 };
5279
+ }
5280
+ /** Side of the shadow maps: the largest requested one, within the device limits. */
5281
+ _mapSize(casters) {
5282
+ const sizes = casters.map((l) => l.shadowMapSize || 0);
5283
+ const requested = Math.max(MIN_MAP_SIZE, ...sizes);
5284
+ const rounded = Math.round(requested);
5285
+ const limit = this._context.device.limits.maxTextureDimension2D;
5286
+ return Math.min(rounded, limit);
5287
+ }
5288
+ _ensureTexture(size, layers) {
5289
+ const current = this.#texture;
5290
+ if (!Utils23.isNull(current) && current.width === size && current.depthOrArrayLayers === layers) {
5291
+ return;
5292
+ }
5293
+ current?.destroy();
5294
+ const texture = this.#texture = this._context.device.createTexture({
5295
+ label: LABEL_PREFIX + "shadow-map",
5296
+ format: SHADOW_MAP_FORMAT,
5297
+ size: [size, size, layers],
5298
+ usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.TEXTURE_BINDING
5299
+ });
5300
+ this.#map = texture.createView({ label: LABEL_PREFIX + "shadow-map-view", dimension: "2d-array" });
5301
+ this.#layers = Array.from({ length: layers }, (_, i) => texture.createView({
5302
+ label: LABEL_PREFIX + "shadow-map-layer-" + i,
5303
+ dimension: "2d",
5304
+ baseArrayLayer: i,
5305
+ arrayLayerCount: 1
5306
+ }));
5307
+ }
5308
+ _ensureCameras(count) {
5309
+ const cameras = this.#cameras;
5310
+ const { device } = this._context;
5311
+ while (cameras.length < count) {
5312
+ const camera = new ShadowCamera(device, cameras.length);
5313
+ cameras.push(camera);
5314
+ }
5315
+ }
5316
+ destroy() {
5317
+ this.#texture?.destroy();
5318
+ this.#texture = null;
5319
+ this.#lights.destroy();
5320
+ for (let camera of this.#cameras) {
5321
+ camera.destroy();
5322
+ }
5323
+ this.#cameras = [];
5324
+ }
5325
+ };
5326
+
5327
+ // packages/3d/dist/esm/adapters/webgpu/renderablebuffer.js
5328
+ import { Utils as Utils24 } from "@pacem/pacem-core";
5329
+ import { Colors as Colors3 } from "@pacem/pacem-foundation";
5330
+ import { Geometry as Geometry9 } from "@pacem/pacem-numerical";
5331
+
5332
+ // packages/3d/dist/esm/adapters/webgpu/depth.js
5333
+ import { Geometry as Geometry8 } from "@pacem/pacem-numerical";
5334
+ var Matrix3D3 = Geometry8.LinearAlgebra.Matrix3D;
5335
+ var STANDARD_DEPTH = Object.freeze({
5336
+ reversed: false,
5337
+ format: "depth24plus",
5338
+ compare: "less",
5339
+ clearValue: 1
5340
+ });
5341
+ var REVERSED_DEPTH = Object.freeze({
5342
+ reversed: true,
5343
+ format: "depth32float",
5344
+ compare: "greater",
5345
+ clearValue: 0
5346
+ });
5347
+ function toDepthRange(projection, depth) {
5348
+ if (!depth.reversed) {
5349
+ return projection;
5350
+ }
5351
+ const m = Matrix3D3.clone(projection);
5352
+ m.m13 = projection.m14 - projection.m13;
5353
+ m.m23 = projection.m24 - projection.m23;
5354
+ m.m33 = projection.m34 - projection.m33;
5355
+ m.offsetZ = projection.m44 - projection.offsetZ;
5356
+ return m;
5357
+ }
5358
+
5359
+ // packages/3d/dist/esm/adapters/webgpu/renderablebuffer.js
5360
+ var Vector3D3 = Geometry9.LinearAlgebra.Vector3D;
5361
+ var Matrix3D4 = Geometry9.LinearAlgebra.Matrix3D;
4896
5362
  var EMPTY_FLAGS = Object.freeze([]);
4897
5363
  var currentFrame = 0;
4898
5364
  function throwBufferRequestError(key, type) {
@@ -4902,7 +5368,7 @@ function throwBufferRequestError(key, type) {
4902
5368
  throw new RangeError(`Buffer '${key}' not available for ${type}.`);
4903
5369
  }
4904
5370
  function writeInPlace(device, buffer, value) {
4905
- if (Utils23.isNull(buffer) || buffer.value.byteLength !== value.byteLength) {
5371
+ if (Utils24.isNull(buffer) || buffer.value.byteLength !== value.byteLength) {
4906
5372
  return null;
4907
5373
  }
4908
5374
  Buffers.write(device, buffer.buffer, value);
@@ -4913,22 +5379,22 @@ function writeInPlace(device, buffer, value) {
4913
5379
  function createRenderableBuffer(item, parent, ...args) {
4914
5380
  item.stage ??= parent?.item.stage;
4915
5381
  if (isGroup(item)) {
4916
- item.key ??= "group_" + Utils23.uniqueCode();
5382
+ item.key ??= "group_" + Utils24.uniqueCode();
4917
5383
  return new RenderableGroupBuffer(item, parent, ...args);
4918
5384
  }
4919
5385
  if (isMesh(item)) {
4920
- item.key ??= "mesh_" + Utils23.uniqueCode();
5386
+ item.key ??= "mesh_" + Utils24.uniqueCode();
4921
5387
  return new RenderableMeshBuffer(item, parent, ...args);
4922
5388
  }
4923
5389
  if (isCamera(item)) {
4924
- item.key ??= "camera_" + Utils23.uniqueCode();
5390
+ item.key ??= "camera_" + Utils24.uniqueCode();
4925
5391
  return new RenderableCameraBuffer(
4926
5392
  item
4927
5393
  /*, parent*/
4928
5394
  );
4929
5395
  }
4930
5396
  if (isLight(item)) {
4931
- item.key ??= "light_" + item.type + "_" + Utils23.uniqueCode();
5397
+ item.key ??= "light_" + item.type + "_" + Utils24.uniqueCode();
4932
5398
  return new RenderableLightBuffer(
4933
5399
  item
4934
5400
  /*, parent*/
@@ -4987,7 +5453,7 @@ var ManagedBuffers = class {
4987
5453
  */
4988
5454
  static create(item) {
4989
5455
  if (isGeometry(item)) {
4990
- item.key ??= "geometry_" + Utils23.uniqueCode();
5456
+ item.key ??= "geometry_" + Utils24.uniqueCode();
4991
5457
  return new GeometryBuffer(item);
4992
5458
  }
4993
5459
  if (isMaterial(item)) {
@@ -5020,7 +5486,7 @@ var RenderableBuffers = class _RenderableBuffers {
5020
5486
  buffer.item.flags?.splice(0);
5021
5487
  if (includeParent) {
5022
5488
  const bufferBase = buffer;
5023
- if (!Utils23.isNull(bufferBase.parent)) {
5489
+ if (!Utils24.isNull(bufferBase.parent)) {
5024
5490
  _RenderableBuffers.clearFlags(bufferBase.parent, true);
5025
5491
  }
5026
5492
  }
@@ -5033,7 +5499,7 @@ var RenderableBuffers = class _RenderableBuffers {
5033
5499
  static allFlags(buffer) {
5034
5500
  const bufferBase = buffer;
5035
5501
  const parentBufferBase = bufferBase.parent;
5036
- const parentFlags = Utils23.isNull(parentBufferBase) ? [] : _RenderableBuffers.allFlags(parentBufferBase);
5502
+ const parentFlags = Utils24.isNull(parentBufferBase) ? [] : _RenderableBuffers.allFlags(parentBufferBase);
5037
5503
  return bufferBase.item.flags.union(parentFlags);
5038
5504
  }
5039
5505
  };
@@ -5105,7 +5571,7 @@ var RenderableBufferBase = class extends ManagedBufferBase {
5105
5571
  constructor(item, parentBuffer) {
5106
5572
  super(item);
5107
5573
  this.#parent = parentBuffer;
5108
- this.#u32id = Utils23.uniqueId() % U32_MAX;
5574
+ this.#u32id = Utils24.uniqueId() % U32_MAX;
5109
5575
  }
5110
5576
  #u32id;
5111
5577
  #parent;
@@ -5137,7 +5603,7 @@ var RenderableBufferBase = class extends ManagedBufferBase {
5137
5603
  return true;
5138
5604
  }
5139
5605
  const parent = this.parent;
5140
- if (Utils23.isNull(parent)) {
5606
+ if (Utils24.isNull(parent)) {
5141
5607
  return false;
5142
5608
  }
5143
5609
  return parent.hasFlags();
@@ -5148,27 +5614,27 @@ var RenderableBufferBase = class extends ManagedBufferBase {
5148
5614
  }
5149
5615
  const ownFlags = this.item.flags ?? [];
5150
5616
  const parent = this.parent;
5151
- if (Utils23.isNull(parent)) {
5617
+ if (Utils24.isNull(parent)) {
5152
5618
  return ownFlags;
5153
5619
  }
5154
5620
  const parentFlags = parent.allFlags();
5155
5621
  return ownFlags.union(parentFlags);
5156
5622
  }
5157
5623
  buildParentWorldTransform() {
5158
- let worldMatrix = Matrix3D2.identity();
5624
+ let worldMatrix = Matrix3D4.identity();
5159
5625
  let step = this;
5160
- while (!Utils23.isNull(step.parent)) {
5626
+ while (!Utils24.isNull(step.parent)) {
5161
5627
  const parentItem = step.parent.item;
5162
- const parentItemMatrix = Matrix3D2.translate(parentItem.transformMatrix ?? Matrix3D2.identity(), parentItem.position ?? Vector3D2.zero());
5163
- worldMatrix = Matrix3D2.multiply(worldMatrix, parentItemMatrix);
5628
+ const parentItemMatrix = Matrix3D4.translate(parentItem.transformMatrix ?? Matrix3D4.identity(), parentItem.position ?? Vector3D3.zero());
5629
+ worldMatrix = Matrix3D4.multiply(worldMatrix, parentItemMatrix);
5164
5630
  step = step.parent;
5165
5631
  }
5166
5632
  return worldMatrix;
5167
5633
  }
5168
5634
  buildWorldTransform() {
5169
- const itemMatrix = Matrix3D2.translate(this.item.transformMatrix ?? Matrix3D2.identity(), this.item.position ?? Vector3D2.zero());
5635
+ const itemMatrix = Matrix3D4.translate(this.item.transformMatrix ?? Matrix3D4.identity(), this.item.position ?? Vector3D3.zero());
5170
5636
  const parentWorldMatrix = this.buildParentWorldTransform();
5171
- return Matrix3D2.multiply(itemMatrix, parentWorldMatrix);
5637
+ return Matrix3D4.multiply(itemMatrix, parentWorldMatrix);
5172
5638
  }
5173
5639
  #versions = /* @__PURE__ */ new Map();
5174
5640
  version(key) {
@@ -5184,7 +5650,7 @@ var RenderableBufferBase = class extends ManagedBufferBase {
5184
5650
  }
5185
5651
  /** One id buffer per renderable, shared by every (color-picking) pipeline. */
5186
5652
  _ensureU32idBuffer({ device }) {
5187
- if (!Utils23.isNull(this.#u32idBuffer)) {
5653
+ if (!Utils24.isNull(this.#u32idBuffer)) {
5188
5654
  return this.#u32idBuffer;
5189
5655
  }
5190
5656
  const value = new Uint32Array([this.id]);
@@ -5210,7 +5676,7 @@ var RenderableGroupBuffer = class extends RenderableBufferBase {
5210
5676
  const store = args[2];
5211
5677
  this.#children = group.childRenderables.map((i) => {
5212
5678
  const existing = store?.get(i);
5213
- if (!Utils23.isNull(existing) && !existing.disposed && existing.parent?.item === group) {
5679
+ if (!Utils24.isNull(existing) && !existing.disposed && existing.parent?.item === group) {
5214
5680
  existing.reparent(this);
5215
5681
  return existing;
5216
5682
  }
@@ -5256,28 +5722,29 @@ var RenderableCameraBuffer = class _RenderableCameraBuffer extends RenderableBuf
5256
5722
  }
5257
5723
  /** Whether the matrices need a rebuild: stale flags, first use, or a different render target size (the projection depends on it). */
5258
5724
  _isStale(canvas) {
5259
- if (Utils23.isNull(this.#view) || this.hasFlags()) {
5725
+ if (Utils24.isNull(this.#view) || this.hasFlags()) {
5260
5726
  return true;
5261
5727
  }
5262
5728
  const size = this.#size;
5263
5729
  return size.width !== canvas.width || size.height !== canvas.height;
5264
5730
  }
5265
- _rebuildMatrices({ device, canvas }) {
5731
+ _rebuildMatrices({ device, canvas, depth }) {
5266
5732
  const cam = this.item;
5267
5733
  const camera = Cameras.create(cam);
5268
5734
  const { x, y, z } = cam.position;
5269
5735
  const view2 = camera.view();
5270
- const projection = camera.projection(canvas);
5271
- const viewProjection = Matrix3D2.multiply(view2, projection);
5272
- const viewArray = Matrix3D2.toArray(view2);
5273
- const viewProjectionArray = Matrix3D2.toArray(viewProjection);
5736
+ const standardProjection = camera.projection(canvas);
5737
+ const projection = toDepthRange(standardProjection, depth);
5738
+ const viewProjection = Matrix3D4.multiply(view2, projection);
5739
+ const viewArray = Matrix3D4.toArray(view2);
5740
+ const viewProjectionArray = Matrix3D4.toArray(viewProjection);
5274
5741
  const viewValue = new Float32Array(16 + 16 + 4);
5275
5742
  viewValue.set(viewArray, 0);
5276
5743
  viewValue.set(viewProjectionArray, 16);
5277
5744
  viewValue.set([x, y, z], 32);
5278
5745
  this.#size = { width: canvas.width, height: canvas.height };
5279
5746
  const written = writeInPlace(device, this.#view, viewValue);
5280
- if (!Utils23.isNull(written)) {
5747
+ if (!Utils24.isNull(written)) {
5281
5748
  return;
5282
5749
  }
5283
5750
  const viewBuffer = Buffers.createUniform(device, viewValue, LABEL_PREFIX + "view-buffer");
@@ -5315,7 +5782,7 @@ var GeometryBuffer = class _GeometryBuffer extends ManagedBufferBase {
5315
5782
  const normalizedKey = isMeshGeometry(this.item) ? key : "geometryPositions";
5316
5783
  const buffers = this.#buffers;
5317
5784
  const existing = buffers.get(normalizedKey);
5318
- if (!Utils23.isNull(existing)) {
5785
+ if (!Utils24.isNull(existing)) {
5319
5786
  return existing;
5320
5787
  }
5321
5788
  const created = this._createBuffer(context, normalizedKey);
@@ -5326,7 +5793,7 @@ var GeometryBuffer = class _GeometryBuffer extends ManagedBufferBase {
5326
5793
  throw new Error("Method not implemented.");
5327
5794
  }
5328
5795
  _flatten(geometry) {
5329
- const hasTriangleIndices = !Utils23.isNullOrEmpty(geometry.triangleIndices);
5796
+ const hasTriangleIndices = !Utils24.isNullOrEmpty(geometry.triangleIndices);
5330
5797
  const positions = hasTriangleIndices ? geometry.triangleIndices.map((index) => geometry.positions[index]) : geometry.positions;
5331
5798
  return { positions, normals: geometry.normals, uvs: geometry.textureCoordinates };
5332
5799
  }
@@ -5408,7 +5875,7 @@ var MaterialBuffer = class _MaterialBuffer extends ManagedBufferBase {
5408
5875
  _ensureUpToDate(context) {
5409
5876
  const flags = this.item.flags ?? [];
5410
5877
  const stale = flags.includes(StalePropertyFlag.Material);
5411
- if (!stale && !Utils23.isNull(this.#wgpuMaterial)) {
5878
+ if (!stale && !Utils24.isNull(this.#wgpuMaterial)) {
5412
5879
  return;
5413
5880
  }
5414
5881
  if (stale) {
@@ -5425,7 +5892,7 @@ var MaterialBuffer = class _MaterialBuffer extends ManagedBufferBase {
5425
5892
  for (let [key, buffer] of buffers) {
5426
5893
  const value = material.value(context, key);
5427
5894
  const written = writeInPlace(context.device, buffer, value);
5428
- if (!Utils23.isNull(written)) {
5895
+ if (!Utils24.isNull(written)) {
5429
5896
  continue;
5430
5897
  }
5431
5898
  buffers.delete(key);
@@ -5444,7 +5911,7 @@ var MaterialBuffer = class _MaterialBuffer extends ManagedBufferBase {
5444
5911
  }
5445
5912
  _ensureMaterialBuffer(ctx, key) {
5446
5913
  const existing = this.#buffers.get(key);
5447
- if (Utils23.isNull(existing)) {
5914
+ if (Utils24.isNull(existing)) {
5448
5915
  return this._createMaterialBuffer(ctx, key);
5449
5916
  }
5450
5917
  if (key === "line") {
@@ -5454,7 +5921,7 @@ var MaterialBuffer = class _MaterialBuffer extends ManagedBufferBase {
5454
5921
  }
5455
5922
  _createMaterialBuffer(ctx, key) {
5456
5923
  const created = this.#wgpuMaterial.buffer(ctx, key);
5457
- if (Utils23.isNull(created)) {
5924
+ if (Utils24.isNull(created)) {
5458
5925
  return null;
5459
5926
  }
5460
5927
  this.#buffers.set(key, created);
@@ -5488,7 +5955,7 @@ var MaterialBuffer = class _MaterialBuffer extends ManagedBufferBase {
5488
5955
  const values = this.#textures.values();
5489
5956
  const textures = Array.from(values);
5490
5957
  this.#textures.clear();
5491
- const existing = textures.filter((t) => !Utils23.isNull(t));
5958
+ const existing = textures.filter((t) => !Utils24.isNull(t));
5492
5959
  this.destroySafely(...existing);
5493
5960
  }
5494
5961
  dispose() {
@@ -5523,7 +5990,7 @@ var InteractionBuffer = class _InteractionBuffer extends ManagedBufferBase {
5523
5990
  }
5524
5991
  /** Whether the interaction data differs from what was last uploaded. Allocation-free (called per mesh, per frame). */
5525
5992
  _hasChanged() {
5526
- if (Utils23.isNull(this.#buffer)) {
5993
+ if (Utils24.isNull(this.#buffer)) {
5527
5994
  return true;
5528
5995
  }
5529
5996
  const fields = this.#fields, item = this.item;
@@ -5553,7 +6020,7 @@ var InteractionBuffer = class _InteractionBuffer extends ManagedBufferBase {
5553
6020
  ]);
5554
6021
  this.#fields = { time: item.time, cursor, resolution };
5555
6022
  const written = writeInPlace(device, this.#buffer, value);
5556
- if (!Utils23.isNull(written)) {
6023
+ if (!Utils24.isNull(written)) {
5557
6024
  return written;
5558
6025
  }
5559
6026
  const buffer = Buffers.createUniform(device, value, LABEL_PREFIX + "interaction-buffer");
@@ -5594,13 +6061,13 @@ var RenderableMeshBuffer = class _RenderableMeshBuffer extends RenderableBufferB
5594
6061
  }
5595
6062
  const flags = this.allFlags();
5596
6063
  const transformStale = flags.includes(StalePropertyFlag.Position) || flags.includes(StalePropertyFlag.Transform);
5597
- if (Utils23.isNull(this.#worldTransform) || reparented || transformStale) {
6064
+ if (Utils24.isNull(this.#worldTransform) || reparented || transformStale) {
5598
6065
  this._rebuildWorldMatrices(context);
5599
6066
  }
5600
- if (Utils23.isNull(this.#geometryBuffer) || flags.includes(StalePropertyFlag.Geometry)) {
6067
+ if (Utils24.isNull(this.#geometryBuffer) || flags.includes(StalePropertyFlag.Geometry)) {
5601
6068
  this._ensureGeometryBuffer();
5602
6069
  }
5603
- if (Utils23.isNull(this.#materialBuffer) || flags.includes(StalePropertyFlag.Material)) {
6070
+ if (Utils24.isNull(this.#materialBuffer) || flags.includes(StalePropertyFlag.Material)) {
5604
6071
  this._ensureMaterialBuffer();
5605
6072
  }
5606
6073
  this.#evaluatedAt = currentFrame;
@@ -5608,7 +6075,7 @@ var RenderableMeshBuffer = class _RenderableMeshBuffer extends RenderableBufferB
5608
6075
  }
5609
6076
  /** Whether nothing needs a refresh: resources in place, no own stale flags, and inherited ones already evaluated in this pass (or absent). */
5610
6077
  _isUpToDate() {
5611
- const ready = !Utils23.isNull(this.#worldTransform) && !Utils23.isNull(this.#geometryBuffer) && !Utils23.isNull(this.#materialBuffer);
6078
+ const ready = !Utils24.isNull(this.#worldTransform) && !Utils24.isNull(this.#geometryBuffer) && !Utils24.isNull(this.#materialBuffer);
5612
6079
  if (!ready) {
5613
6080
  return false;
5614
6081
  }
@@ -5619,7 +6086,7 @@ var RenderableMeshBuffer = class _RenderableMeshBuffer extends RenderableBufferB
5619
6086
  return true;
5620
6087
  }
5621
6088
  const parent = this.parent;
5622
- if (Utils23.isNull(parent)) {
6089
+ if (Utils24.isNull(parent)) {
5623
6090
  return true;
5624
6091
  }
5625
6092
  return !parent.hasFlags();
@@ -5649,7 +6116,7 @@ var RenderableMeshBuffer = class _RenderableMeshBuffer extends RenderableBufferB
5649
6116
  }
5650
6117
  const cache = this.#geometryBuffers;
5651
6118
  let buffer = cache?.get(geom);
5652
- if (Utils23.isNull(buffer) || buffer.disposed) {
6119
+ if (Utils24.isNull(buffer) || buffer.disposed) {
5653
6120
  buffer = new GeometryBuffer(geom);
5654
6121
  cache?.set(geom, buffer);
5655
6122
  }
@@ -5665,7 +6132,7 @@ var RenderableMeshBuffer = class _RenderableMeshBuffer extends RenderableBufferB
5665
6132
  }
5666
6133
  const cache = this.#materialBuffers;
5667
6134
  let buffer = cache?.get(material);
5668
- if (Utils23.isNull(buffer) || buffer.disposed) {
6135
+ if (Utils24.isNull(buffer) || buffer.disposed) {
5669
6136
  buffer = new MaterialBuffer(material);
5670
6137
  cache?.set(material, buffer);
5671
6138
  }
@@ -5676,14 +6143,14 @@ var RenderableMeshBuffer = class _RenderableMeshBuffer extends RenderableBufferB
5676
6143
  _rebuildWorldMatrices({ device }) {
5677
6144
  const item = this.item;
5678
6145
  const matrix = this.buildWorldTransform();
5679
- const inverse = Matrix3D2.invert(matrix);
5680
- const normal = Matrix3D2.transpose(inverse);
5681
- const matrixArray = Matrix3D2.toArray(matrix);
6146
+ const inverse = Matrix3D4.invert(matrix);
6147
+ const normal = Matrix3D4.transpose(inverse);
6148
+ const matrixArray = Matrix3D4.toArray(matrix);
5682
6149
  const value = new Float32Array(28);
5683
6150
  value.set(matrixArray, 0);
5684
6151
  value.set([normal.m11, normal.m12, normal.m13, 0, normal.m21, normal.m22, normal.m23, 0, normal.m31, normal.m32, normal.m33, 0], 16);
5685
6152
  const written = writeInPlace(device, this.#worldTransform, value);
5686
- if (!Utils23.isNull(written)) {
6153
+ if (!Utils24.isNull(written)) {
5687
6154
  return;
5688
6155
  }
5689
6156
  const buffer = Buffers.createUniform(device, value, LABEL_PREFIX + "mesh-" + item.key + "-worldmatrix-buffer");
@@ -5733,7 +6200,7 @@ var RenderableLightBuffer = class _RenderableLightBuffer extends RenderableBuffe
5733
6200
  const { r, g, b, a } = Colors3.parse(light.color ?? "#fff");
5734
6201
  values.set([r, g, b, a], offsetColor);
5735
6202
  values.set([light.intensity], offsetIntensity);
5736
- const direction = Vector3D2.subtract(light.position, light.target);
6203
+ const direction = Vector3D3.subtract(light.position, light.target);
5737
6204
  values.set([direction.x, direction.y, direction.z], offsetDirection);
5738
6205
  return values;
5739
6206
  }
@@ -5768,7 +6235,7 @@ var RenderableLightBuffer = class _RenderableLightBuffer extends RenderableBuffe
5768
6235
  throw new Error(`Light '${light.type}' is not supported.`);
5769
6236
  }
5770
6237
  const written = writeInPlace(device, this.#buffer, values);
5771
- if (!Utils23.isNull(written)) {
6238
+ if (!Utils24.isNull(written)) {
5772
6239
  return;
5773
6240
  }
5774
6241
  this.destroySafely(this.#buffer);
@@ -5779,7 +6246,7 @@ var RenderableLightBuffer = class _RenderableLightBuffer extends RenderableBuffe
5779
6246
  throw new Error("Method not implemented.");
5780
6247
  }
5781
6248
  specificBuffer(context, key) {
5782
- if (Utils23.isNull(this.#buffer) || this.hasFlags()) {
6249
+ if (Utils24.isNull(this.#buffer) || this.hasFlags()) {
5783
6250
  this._rebuildLight(context);
5784
6251
  }
5785
6252
  RenderableBuffers.clearFlags(this);
@@ -5817,7 +6284,7 @@ var ALPHA_BLENDING = {
5817
6284
  }
5818
6285
  };
5819
6286
  function optionsKey(pipelineOptions) {
5820
- const options = Utils24.extend({}, DefaultPipelineOptions, pipelineOptions ?? {});
6287
+ const options = Utils25.extend({}, DefaultPipelineOptions, pipelineOptions ?? {});
5821
6288
  const primitive = options.primitive ?? {};
5822
6289
  return [
5823
6290
  options.modifiers?.version ?? "",
@@ -5837,7 +6304,7 @@ function mapIndices(count, selector) {
5837
6304
  var passStates = /* @__PURE__ */ new WeakMap();
5838
6305
  function passStateOf(pass) {
5839
6306
  const existing = passStates.get(pass);
5840
- if (!Utils24.isNull(existing)) {
6307
+ if (!Utils25.isNull(existing)) {
5841
6308
  return existing;
5842
6309
  }
5843
6310
  const state = { groups: [], vertexBuffers: [] };
@@ -5878,7 +6345,7 @@ var RenderPipelines = class _RenderPipelines {
5878
6345
  static dispose(ctx) {
5879
6346
  const memoizer = this._memoizer;
5880
6347
  const cache = memoizer.get(ctx);
5881
- if (!Utils24.isNull(cache)) {
6348
+ if (!Utils25.isNull(cache)) {
5882
6349
  cache.clear();
5883
6350
  memoizer.delete(ctx);
5884
6351
  }
@@ -5892,7 +6359,7 @@ var RenderPipelines = class _RenderPipelines {
5892
6359
  */
5893
6360
  static createColorPicking(ctx, items, pipelineOptions) {
5894
6361
  const renderPipeline = _RenderPipelines.create(ctx, items, pipelineOptions);
5895
- if (Utils24.isNull(renderPipeline.raycast)) {
6362
+ if (Utils25.isNull(renderPipeline.raycast)) {
5896
6363
  return null;
5897
6364
  }
5898
6365
  return {
@@ -5914,7 +6381,7 @@ var RenderPipelines = class _RenderPipelines {
5914
6381
  * @throws {Error} If no mesh is provided, the mesh's geometry/material combination isn't supported, or the first argument isn't a mesh.
5915
6382
  */
5916
6383
  static create(ctx, [mesh, camera, ...lights], pipelineOptions) {
5917
- if (Utils24.isNull(mesh)) {
6384
+ if (Utils25.isNull(mesh)) {
5918
6385
  throw new Error("Pipeline not implemented, given the provided arguments.");
5919
6386
  }
5920
6387
  if (!isMesh(mesh.item)) {
@@ -5935,8 +6402,8 @@ var RenderPipelines = class _RenderPipelines {
5935
6402
  }
5936
6403
  const pipeline = isMeshPipeline ? new MeshRenderPipelineClass(ctx, builder) : new LineRenderPipelineClass(ctx, builder);
5937
6404
  pipeline.build(pipelineOptions);
5938
- const timestamp = Utils24.Dates.now().toISOString();
5939
- Utils24.extend(pipeline, {
6405
+ const timestamp = Utils25.Dates.now().toISOString();
6406
+ Utils25.extend(pipeline, {
5940
6407
  id: key + "-" + ctx.canvas.width + "x" + ctx.canvas.height + "-" + timestamp
5941
6408
  });
5942
6409
  cache.set(key, pipeline);
@@ -5945,7 +6412,7 @@ var RenderPipelines = class _RenderPipelines {
5945
6412
  static _ensureCache(ctx) {
5946
6413
  const memoizer = _RenderPipelines._memoizer;
5947
6414
  const existing = memoizer.get(ctx);
5948
- if (!Utils24.isNull(existing)) {
6415
+ if (!Utils25.isNull(existing)) {
5949
6416
  return existing;
5950
6417
  }
5951
6418
  const cache = /* @__PURE__ */ new Map();
@@ -5955,7 +6422,7 @@ var RenderPipelines = class _RenderPipelines {
5955
6422
  };
5956
6423
  function ensureEntry(maps, key) {
5957
6424
  const existing = maps.get(key);
5958
- if (!Utils24.isNull(existing)) {
6425
+ if (!Utils25.isNull(existing)) {
5959
6426
  return existing;
5960
6427
  }
5961
6428
  const created = /* @__PURE__ */ new Map();
@@ -5963,7 +6430,7 @@ function ensureEntry(maps, key) {
5963
6430
  return created;
5964
6431
  }
5965
6432
  function isReusable(cached, layout, resources) {
5966
- if (Utils24.isNull(cached) || cached.layout !== layout) {
6433
+ if (Utils25.isNull(cached) || cached.layout !== layout) {
5967
6434
  return false;
5968
6435
  }
5969
6436
  if (cached.resources.length !== resources.length) {
@@ -5972,7 +6439,7 @@ function isReusable(cached, layout, resources) {
5972
6439
  return cached.resources.every((r, i) => r === resources[i]);
5973
6440
  }
5974
6441
  function toBindGroupEntry(e) {
5975
- if (Utils24.isNull(e.buffer)) {
6442
+ if (Utils25.isNull(e.buffer)) {
5976
6443
  return { binding: e.binding, resource: e.resource };
5977
6444
  }
5978
6445
  return { binding: e.binding, resource: { buffer: e.buffer } };
@@ -6009,11 +6476,14 @@ var MeshWGSLBuilder = class _MeshWGSLBuilder {
6009
6476
  #camera;
6010
6477
  #bindgroups = /* @__PURE__ */ new Map();
6011
6478
  #key = { shader: "basic", lights: "" };
6479
+ /** First shadow map layer of each casting light buffer that fits (see `allocateShadowLayers`). */
6480
+ #shadowLayers = /* @__PURE__ */ new Map();
6012
6481
  constructor(...objects) {
6013
6482
  this.add(...objects);
6014
6483
  }
6015
6484
  reset() {
6016
6485
  this.#lights.splice(0);
6486
+ this.#shadowLayers.clear();
6017
6487
  this.#mesh = null;
6018
6488
  this.#bindgroups.clear();
6019
6489
  this.#key = { shader: "basic", lights: "" };
@@ -6021,7 +6491,7 @@ var MeshWGSLBuilder = class _MeshWGSLBuilder {
6021
6491
  add(...objects) {
6022
6492
  for (let obj of objects ?? []) {
6023
6493
  if (isMesh(obj.item)) {
6024
- if (Utils24.isNull(this.#mesh)) {
6494
+ if (Utils25.isNull(this.#mesh)) {
6025
6495
  this.#mesh = obj;
6026
6496
  const material = obj.item.material ?? { shader: KnownShader.Basic };
6027
6497
  this.#key.shader = material.shader + "-" + (material.texture ? "map" : "nomap");
@@ -6032,6 +6502,10 @@ var MeshWGSLBuilder = class _MeshWGSLBuilder {
6032
6502
  const lights = this.#lights;
6033
6503
  lights.push(obj);
6034
6504
  this.#key.lights += "-" + obj.item.type;
6505
+ this.#shadowLayers = allocateShadowLayers(lights, (l) => l.item);
6506
+ if (this.#shadowLayers.has(obj)) {
6507
+ this.#key.lights += "+shadow";
6508
+ }
6035
6509
  } else if (isCamera(obj.item)) {
6036
6510
  this.#camera ??= obj;
6037
6511
  } else {
@@ -6044,7 +6518,8 @@ var MeshWGSLBuilder = class _MeshWGSLBuilder {
6044
6518
  const key = this.key, vertex = this.vertex({ inputModifier: modifiers?.vertexInput, outputModifier: modifiers?.vertexOutput }), fragment = this.fragment(data, { modifier: modifiers?.fragment }), bindings = (...args) => _MeshWGSLBuilder.prototype.bindgroup.apply(this, args);
6045
6519
  const metadata = {
6046
6520
  lightCount: this.#lights.length,
6047
- mapCount: data.hasTexture ? 1 : 0
6521
+ mapCount: data.hasTexture ? 1 : 0,
6522
+ shadows: this._receivesShadows()
6048
6523
  };
6049
6524
  return {
6050
6525
  vertex,
@@ -6056,15 +6531,24 @@ var MeshWGSLBuilder = class _MeshWGSLBuilder {
6056
6531
  }
6057
6532
  get key() {
6058
6533
  const { shader, lights } = this.#key;
6059
- return `mesh-` + shader + lights;
6534
+ const shadows = this._receivesShadows() ? "|receiver" : "";
6535
+ return `mesh-` + shader + lights + shadows;
6536
+ }
6537
+ /** Whether the mesh reads the shadow maps: it receives shadows and at least one light casts them. */
6538
+ _receivesShadows() {
6539
+ const mesh = this.#mesh?.item;
6540
+ if (Utils25.isNull(mesh) || this.#shadowLayers.size === 0) {
6541
+ return false;
6542
+ }
6543
+ return receivesShadow(mesh);
6060
6544
  }
6061
6545
  bindgroup(type, key, index) {
6062
6546
  const set = this.#bindgroups;
6063
6547
  const arr = set.get(type);
6064
- if (Utils24.isNull(arr)) {
6548
+ if (Utils25.isNull(arr)) {
6065
6549
  return null;
6066
6550
  }
6067
- if (Utils24.isNullOrEmpty(key)) {
6551
+ if (Utils25.isNullOrEmpty(key)) {
6068
6552
  return arr;
6069
6553
  }
6070
6554
  const filteredArr = arr.filter((i) => i.key === key);
@@ -6080,8 +6564,8 @@ var MeshWGSLBuilder = class _MeshWGSLBuilder {
6080
6564
  return getMeshVertexWgsl(options);
6081
6565
  }
6082
6566
  _computeBasicData() {
6083
- const mesh = this.#mesh.item, lights = this.#lights, material = mesh.material, hasTexture = !Utils24.isNull(material?.texture), hasLighting = !Utils24.isNullOrEmpty(lights);
6084
- const shader = Utils24.isNull(mesh) ? KnownShader.Basic : mesh.material?.shader ?? KnownShader.Basic;
6567
+ const mesh = this.#mesh.item, lights = this.#lights, material = mesh.material, hasTexture = !Utils25.isNull(material?.texture), hasLighting = !Utils25.isNullOrEmpty(lights);
6568
+ const shader = Utils25.isNull(mesh) ? KnownShader.Basic : mesh.material?.shader ?? KnownShader.Basic;
6085
6569
  const materialBindGroupIndex = MATERIAL_GROUP_INDEX, lightingBindGroupIndex = UNIFORM_GROUP_INDEX_LIGHTING;
6086
6570
  return {
6087
6571
  hasTexture,
@@ -6124,10 +6608,10 @@ var MeshWGSLBuilder = class _MeshWGSLBuilder {
6124
6608
  extra.definitions.push(definition);
6125
6609
  }
6126
6610
  }
6127
- if (!Utils24.isNullOrEmpty(x.bindings)) {
6611
+ if (!Utils25.isNullOrEmpty(x.bindings)) {
6128
6612
  extra.bindings.push(...x.bindings);
6129
6613
  }
6130
- if (!Utils24.isNullOrEmpty(x.modifiers)) {
6614
+ if (!Utils25.isNullOrEmpty(x.modifiers)) {
6131
6615
  extra.modifiers.push(...x.modifiers);
6132
6616
  }
6133
6617
  };
@@ -6138,20 +6622,28 @@ var MeshWGSLBuilder = class _MeshWGSLBuilder {
6138
6622
  const wgslTex = textureMap({ inputColor: VERTEX_COLOR_REFERENCE, outputColors: [VERTEX_COLOR_REFERENCE], uv: "uv" }, materialGroupIndex);
6139
6623
  merge(wgslTex);
6140
6624
  }
6625
+ const receiver = this._receivesShadows();
6626
+ if (receiver) {
6627
+ const shadowExtra = shadowFragmentExtra(data.lightingBindGroupIndex);
6628
+ merge(shadowExtra);
6629
+ }
6141
6630
  let lightIndex = 0;
6142
6631
  const lights = this.#lights;
6143
6632
  for (let lightBuffer of lights) {
6144
6633
  const light = lightBuffer.item;
6145
6634
  switch (light.type) {
6146
6635
  case "direction":
6147
- const dirLightExtra = directionalLight({ outputColor: LIGHTING_COLOR_REFERENCE, normal: "normal" }, data.lightingBindGroupIndex, lightIndex);
6636
+ const shadowLayer = receiver ? this.#shadowLayers.get(lightBuffer) : void 0;
6637
+ const dirLightExtra = directionalLight({ outputColor: LIGHTING_COLOR_REFERENCE, normal: "normal", position: "vertex", shadowLayer }, data.lightingBindGroupIndex, lightIndex);
6148
6638
  merge(dirLightExtra);
6149
6639
  break;
6150
6640
  case "omni":
6641
+ const omniShadowLayer = receiver ? this.#shadowLayers.get(lightBuffer) : void 0;
6151
6642
  const omniLightExtra = omniLight({
6152
6643
  outputColor: LIGHTING_COLOR_REFERENCE,
6153
6644
  normal: "normal",
6154
- position: "vertex"
6645
+ position: "vertex",
6646
+ shadowLayer: omniShadowLayer
6155
6647
  /*specularColor: MATERIAL_REFERENCE + '.specularColor', shininess: MATERIAL_REFERENCE + '.shininess'*/
6156
6648
  }, data.lightingBindGroupIndex, lightIndex);
6157
6649
  merge(omniLightExtra);
@@ -6226,10 +6718,11 @@ var MeshRenderPipelineClass = class {
6226
6718
  return this._key;
6227
6719
  }
6228
6720
  build(pipelineOptions) {
6229
- const options = Utils24.extend({}, DefaultPipelineOptions, pipelineOptions ?? {});
6721
+ const options = Utils25.extend({}, DefaultPipelineOptions, pipelineOptions ?? {});
6230
6722
  const builder = this._builder, wgsl = builder.build(options.modifiers);
6231
6723
  const ctx = this._context;
6232
6724
  const device = ctx.device;
6725
+ const depth = ctx.depth;
6233
6726
  const cache = this._cache;
6234
6727
  const vertexModule = device.createShaderModule({ code: wgsl.vertex });
6235
6728
  const vertex = {
@@ -6324,7 +6817,7 @@ var MeshRenderPipelineClass = class {
6324
6817
  minFilter: "linear"
6325
6818
  }) : null;
6326
6819
  const lightingGroupIndex = bindGroupLayouts.length;
6327
- const { lightCount } = wgsl.metadata, hasLighting = lightCount > 0;
6820
+ const { lightCount, shadows: receivesShadows } = wgsl.metadata, hasLighting = lightCount > 0;
6328
6821
  let lightingBindGroupLayout = null;
6329
6822
  if (hasLighting) {
6330
6823
  const lightingEntries = mapIndices(lightCount, (index) => {
@@ -6337,6 +6830,9 @@ var MeshRenderPipelineClass = class {
6337
6830
  };
6338
6831
  return entry;
6339
6832
  });
6833
+ if (receivesShadows) {
6834
+ lightingEntries.push({ visibility: GPUShaderStage.FRAGMENT, binding: SHADOW_BINDING_MAP, texture: { sampleType: "depth", viewDimension: "2d-array" } }, { visibility: GPUShaderStage.FRAGMENT, binding: SHADOW_BINDING_SAMPLER, sampler: { type: "comparison" } }, { visibility: GPUShaderStage.FRAGMENT, binding: SHADOW_BINDING_LIGHTS, buffer: { type: "uniform" } });
6835
+ }
6340
6836
  lightingBindGroupLayout = device.createBindGroupLayout({
6341
6837
  entries: lightingEntries,
6342
6838
  label: labelPrefix + "lighting-bind-group-layout"
@@ -6357,8 +6853,8 @@ var MeshRenderPipelineClass = class {
6357
6853
  if (options.multisample) {
6358
6854
  descriptor.multisample = { count: 4 };
6359
6855
  descriptor.depthStencil = {
6360
- depthCompare: "less",
6361
- format: "depth24plus",
6856
+ depthCompare: depth.compare,
6857
+ format: depth.format,
6362
6858
  depthWriteEnabled: true
6363
6859
  };
6364
6860
  }
@@ -6394,11 +6890,30 @@ var MeshRenderPipelineClass = class {
6394
6890
  primitive: options.primitive,
6395
6891
  depthStencil: {
6396
6892
  depthWriteEnabled: true,
6397
- depthCompare: "less",
6398
- format: "depth24plus"
6893
+ depthCompare: depth.compare,
6894
+ format: depth.format
6399
6895
  }
6400
6896
  };
6401
6897
  this._pickPipeline = device.createRenderPipeline(pickDescriptor);
6898
+ let shadowPipeline = null;
6899
+ const ensureShadowPipeline = () => {
6900
+ if (!Utils25.isNull(shadowPipeline)) {
6901
+ return shadowPipeline;
6902
+ }
6903
+ const shadowLayout = device.createPipelineLayout({
6904
+ label: labelPrefix + "mesh-shadow-pipeline-layout",
6905
+ bindGroupLayouts: [viewBindGroupLayout, worldBindGroupLayout]
6906
+ });
6907
+ shadowPipeline = device.createRenderPipeline({
6908
+ label: labelPrefix + "mesh-shadow-pipeline",
6909
+ vertex,
6910
+ layout: shadowLayout,
6911
+ primitive: options.primitive,
6912
+ // slope-scaled bias: the steeper the surface (as seen from the light), the farther its stored depth
6913
+ depthStencil: { format: SHADOW_MAP_FORMAT, depthCompare: "less", depthWriteEnabled: true, depthBias: 2, depthBiasSlopeScale: 2 }
6914
+ });
6915
+ return shadowPipeline;
6916
+ };
6402
6917
  const { group: worldGroup } = wgsl.bindings(WGSLBindingType.Mesh, "objectWorldTransform", 0);
6403
6918
  const { group: cameraGroup } = wgsl.bindings(WGSLBindingType.Camera, "cameraViewTransform", 0);
6404
6919
  const { group: interactionGroup } = wgsl.bindings(WGSLBindingType.Interaction, "interaction", 0);
@@ -6407,7 +6922,7 @@ var MeshRenderPipelineClass = class {
6407
6922
  }
6408
6923
  const bindVertexSplit = (pass, ...buffers) => {
6409
6924
  const meshBuffer = buffers.at(0);
6410
- if (Utils24.isNull(meshBuffer)) {
6925
+ if (Utils25.isNull(meshBuffer)) {
6411
6926
  throw new ReferenceError(`Null ${RenderableBuffers.name} bringing vertex buffers was provided.`);
6412
6927
  }
6413
6928
  const { buffer: positions } = meshBuffer.buffer(ctx, "geometryPositions");
@@ -6419,7 +6934,7 @@ var MeshRenderPipelineClass = class {
6419
6934
  };
6420
6935
  const bindVertexPacked = (pass, ...buffers) => {
6421
6936
  const meshBuffer = buffers.at(0);
6422
- if (Utils24.isNull(meshBuffer)) {
6937
+ if (Utils25.isNull(meshBuffer)) {
6423
6938
  throw new ReferenceError(`Null ${RenderableBuffers.name} bringing vertex buffers was provided.`);
6424
6939
  }
6425
6940
  const { buffer: packed } = meshBuffer.buffer(ctx, "geometry");
@@ -6428,7 +6943,7 @@ var MeshRenderPipelineClass = class {
6428
6943
  this._bindVertex = options.packedVertices ? bindVertexPacked : bindVertexSplit;
6429
6944
  this._bindWorldTransform = (pass, ...buffers) => {
6430
6945
  const meshBuffer = buffers.at(0);
6431
- if (Utils24.isNull(meshBuffer)) {
6946
+ if (Utils25.isNull(meshBuffer)) {
6432
6947
  throw new ReferenceError(`Null ${RenderableBuffers.name} bringing world transform buffer was provided.`);
6433
6948
  }
6434
6949
  const { buffer } = meshBuffer.buffer(ctx, "objectWorldTransform");
@@ -6440,10 +6955,10 @@ var MeshRenderPipelineClass = class {
6440
6955
  this._bindCameraProjectionAndInteractionData = (pass, ...buffers) => {
6441
6956
  const cameraBuffer = buffers.at(0);
6442
6957
  const interactionBuffer = buffers.at(1);
6443
- if (Utils24.isNull(cameraBuffer)) {
6958
+ if (Utils25.isNull(cameraBuffer)) {
6444
6959
  throw new ReferenceError(`Null ${RenderableBuffers.name} bringing view projection buffers was provided.`);
6445
6960
  }
6446
- if (Utils24.isNull(interactionBuffer)) {
6961
+ if (Utils25.isNull(interactionBuffer)) {
6447
6962
  throw new ReferenceError(`Null ${RenderableBuffers.name} bringing interaction buffers was provided.`);
6448
6963
  }
6449
6964
  const { buffer: view2 } = cameraBuffer.buffer(ctx, "cameraViewTransform");
@@ -6456,7 +6971,7 @@ var MeshRenderPipelineClass = class {
6456
6971
  };
6457
6972
  this._bindMaterial = (pass, ...buffers) => {
6458
6973
  const meshBuffer = buffers.at(0);
6459
- if (Utils24.isNull(meshBuffer)) {
6974
+ if (Utils25.isNull(meshBuffer)) {
6460
6975
  throw new ReferenceError(`Null ${RenderableBuffers.name} bringing vertex colors was provided.`);
6461
6976
  }
6462
6977
  const material = meshBuffer.buffer(ctx, "material");
@@ -6478,12 +6993,18 @@ var MeshRenderPipelineClass = class {
6478
6993
  const entry = { binding: index, buffer };
6479
6994
  return entry;
6480
6995
  });
6481
- const bindGroup = cache.ensureBindGroup(ctx, owner, labelPrefix + "mesh-lighting-bind-group", lightingBindGroupLayout, entries);
6996
+ let label = labelPrefix + "mesh-lighting-bind-group";
6997
+ if (receivesShadows) {
6998
+ const shadows = Shadows.of(ctx);
6999
+ entries.push({ binding: SHADOW_BINDING_MAP, resource: shadows.map }, { binding: SHADOW_BINDING_SAMPLER, resource: shadows.sampler }, { binding: SHADOW_BINDING_LIGHTS, buffer: shadows.lights });
7000
+ label += "-shadows";
7001
+ }
7002
+ const bindGroup = cache.ensureBindGroup(ctx, owner, label, lightingBindGroupLayout, entries);
6482
7003
  PassUtils.setBindGroup(pass, lightingGroupIndex, bindGroup);
6483
7004
  };
6484
7005
  this._bindPicker = (pass, ...buffers) => {
6485
7006
  const meshBuffer = buffers.at(0);
6486
- if (Utils24.isNull(meshBuffer)) {
7007
+ if (Utils25.isNull(meshBuffer)) {
6487
7008
  throw new ReferenceError(`Null ${RenderableBuffers.name} bringing world transform buffer was provided.`);
6488
7009
  }
6489
7010
  const { buffer } = meshBuffer.buffer(ctx, "u32id");
@@ -6492,13 +7013,26 @@ var MeshRenderPipelineClass = class {
6492
7013
  ]);
6493
7014
  PassUtils.setBindGroup(pass, UNIFORM_GROUP_INDEX_COLORPICKING, bindGroup);
6494
7015
  };
7016
+ this.shadow = (pass, interactionBuffer, meshBuffer, lightCamera) => {
7017
+ try {
7018
+ const pipeline = ensureShadowPipeline();
7019
+ PassUtils.setPipeline(pass, pipeline);
7020
+ this._bindVertex(pass, meshBuffer);
7021
+ this._bindWorldTransform(pass, meshBuffer);
7022
+ this._bindCameraProjectionAndInteractionData(pass, lightCamera, interactionBuffer);
7023
+ const vertexCount = this._vertexCount(meshBuffer);
7024
+ pass.draw(vertexCount);
7025
+ } catch (e) {
7026
+ logFrameException(e);
7027
+ }
7028
+ };
6495
7029
  if (!options.multisample) {
6496
7030
  return;
6497
7031
  }
6498
7032
  let translucentPipeline = null;
6499
7033
  let translucentViewBindGroupLayout = null;
6500
7034
  const ensureTranslucentPipeline = () => {
6501
- if (!Utils24.isNull(translucentPipeline)) {
7035
+ if (!Utils25.isNull(translucentPipeline)) {
6502
7036
  return;
6503
7037
  }
6504
7038
  translucentViewBindGroupLayout = device.createBindGroupLayout({
@@ -6529,13 +7063,15 @@ var MeshRenderPipelineClass = class {
6529
7063
  fragment: {
6530
7064
  module: translucentFragmentModule,
6531
7065
  // fragments are pushed into storage buffers, nothing is written to color targets
6532
- targets: []
7066
+ targets: [],
7067
+ // the manual depth test follows the depth direction
7068
+ constants: { [ABUFFER_REVERSED_Z_CONSTANT]: depth.reversed ? 1 : 0 }
6533
7069
  },
6534
7070
  layout: translucentLayout,
6535
7071
  primitive: options.primitive,
6536
7072
  multisample: { count: 4 },
6537
7073
  // tested against the opaque depth (read-only), never written
6538
- depthStencil: { format: "depth24plus", depthCompare: "less", depthWriteEnabled: false }
7074
+ depthStencil: { format: depth.format, depthCompare: depth.compare, depthWriteEnabled: false }
6539
7075
  });
6540
7076
  };
6541
7077
  this.translucent = (pass, interactionBuffer, aBuffer, meshBuffer, cameraBuffer, ...lightBuffers) => {
@@ -6583,7 +7119,7 @@ var LineWGSLBuilder = class _LineWGSLBuilder {
6583
7119
  add(...objects) {
6584
7120
  for (let obj of objects ?? []) {
6585
7121
  if (isMesh(obj.item)) {
6586
- if (Utils24.isNull(this.#line)) {
7122
+ if (Utils25.isNull(this.#line)) {
6587
7123
  this.#line = obj;
6588
7124
  } else {
6589
7125
  throw new Error("Line already added.");
@@ -6614,10 +7150,10 @@ var LineWGSLBuilder = class _LineWGSLBuilder {
6614
7150
  bindgroup(type, key, index) {
6615
7151
  const set = this.#bindgroups;
6616
7152
  const arr = set.get(type);
6617
- if (Utils24.isNull(arr)) {
7153
+ if (Utils25.isNull(arr)) {
6618
7154
  return null;
6619
7155
  }
6620
- if (Utils24.isNullOrEmpty(key)) {
7156
+ if (Utils25.isNullOrEmpty(key)) {
6621
7157
  return arr;
6622
7158
  }
6623
7159
  const filteredArr = arr.filter((i) => i.key === key);
@@ -6634,7 +7170,7 @@ var LineWGSLBuilder = class _LineWGSLBuilder {
6634
7170
  }
6635
7171
  _computeBasicData() {
6636
7172
  const mesh = this.#line.item;
6637
- const shader = Utils24.isNull(mesh) ? KnownShader.Line : mesh.material?.shader ?? KnownShader.Line;
7173
+ const shader = Utils25.isNull(mesh) ? KnownShader.Line : mesh.material?.shader ?? KnownShader.Line;
6638
7174
  const material = mesh.material;
6639
7175
  const thickness = material?.lineWidth ?? 1;
6640
7176
  const dashPattern = material?.dashArray;
@@ -6722,10 +7258,11 @@ var LineRenderPipelineClass = class {
6722
7258
  return this._lineKey;
6723
7259
  }
6724
7260
  build(pipelineOptions) {
6725
- const options = Utils24.extend({}, DefaultPipelineOptions, pipelineOptions ?? {});
7261
+ const options = Utils25.extend({}, DefaultPipelineOptions, pipelineOptions ?? {});
6726
7262
  const builder = this._lineBuilder, wgsl = builder.build();
6727
7263
  const ctx = this.#context;
6728
7264
  const device = ctx.device;
7265
+ const depth = ctx.depth;
6729
7266
  const cache = this._cache;
6730
7267
  const fatLines = wgsl.metadata.thickness > 1;
6731
7268
  const vertexModule = device.createShaderModule({ code: wgsl.vertex });
@@ -6824,7 +7361,7 @@ var LineRenderPipelineClass = class {
6824
7361
  const materialBindGroupLayout = device.createBindGroupLayout(materialBindGroupLayoutDescriptor);
6825
7362
  bindGroupLayouts.push(materialBindGroupLayout);
6826
7363
  const topology = fatLines ? options.primitive.topology : "line-list";
6827
- const primitive = Utils24.extend({}, options.primitive, { topology });
7364
+ const primitive = Utils25.extend({}, options.primitive, { topology });
6828
7365
  const layout = device.createPipelineLayout({
6829
7366
  label: labelPrefix + "line-render-pipeline-layout",
6830
7367
  bindGroupLayouts
@@ -6839,8 +7376,8 @@ var LineRenderPipelineClass = class {
6839
7376
  if (options.multisample) {
6840
7377
  descriptor.multisample = { count: 4 };
6841
7378
  descriptor.depthStencil = {
6842
- depthCompare: "less",
6843
- format: "depth24plus",
7379
+ depthCompare: depth.compare,
7380
+ format: depth.format,
6844
7381
  depthWriteEnabled: true
6845
7382
  };
6846
7383
  }
@@ -6877,8 +7414,8 @@ var LineRenderPipelineClass = class {
6877
7414
  primitive,
6878
7415
  depthStencil: {
6879
7416
  depthWriteEnabled: true,
6880
- depthCompare: "less",
6881
- format: "depth24plus"
7417
+ depthCompare: depth.compare,
7418
+ format: depth.format
6882
7419
  }
6883
7420
  };
6884
7421
  this._pickLinePipeline = device.createRenderPipeline(pickDescriptor);
@@ -6887,7 +7424,7 @@ var LineRenderPipelineClass = class {
6887
7424
  const { group: positionsGroup } = wgsl.bindings(WGSLBindingType.Mesh, "line", 0);
6888
7425
  this._bindLineWorldTransform = (pass, ...buffers) => {
6889
7426
  const meshBuffer = buffers.at(0);
6890
- if (Utils24.isNull(meshBuffer)) {
7427
+ if (Utils25.isNull(meshBuffer)) {
6891
7428
  throw new ReferenceError(`Null ${RenderableBuffers.name} bringing world transform buffer was provided.`);
6892
7429
  }
6893
7430
  const { buffer } = meshBuffer.buffer(ctx, "objectWorldTransform");
@@ -6898,7 +7435,7 @@ var LineRenderPipelineClass = class {
6898
7435
  };
6899
7436
  this._bindLineCameraProjection = (pass, ...buffers) => {
6900
7437
  const cameraBuffer = buffers.at(0);
6901
- if (Utils24.isNull(cameraBuffer)) {
7438
+ if (Utils25.isNull(cameraBuffer)) {
6902
7439
  throw new ReferenceError(`Null ${RenderableBuffers.name} bringing view projection buffers was provided.`);
6903
7440
  }
6904
7441
  const { buffer } = cameraBuffer.buffer(ctx, "cameraViewTransform");
@@ -6909,7 +7446,7 @@ var LineRenderPipelineClass = class {
6909
7446
  };
6910
7447
  this._bindLinePositions = (pass, ...buffers) => {
6911
7448
  const meshBuffer = buffers.at(0);
6912
- if (Utils24.isNull(meshBuffer)) {
7449
+ if (Utils25.isNull(meshBuffer)) {
6913
7450
  throw new ReferenceError(`Null ${RenderableBuffers.name} bringing vertex buffers was provided as index 0.`);
6914
7451
  }
6915
7452
  const { buffer: positions } = meshBuffer.buffer(ctx, "geometryPositions");
@@ -6923,7 +7460,7 @@ var LineRenderPipelineClass = class {
6923
7460
  };
6924
7461
  this._bindLineMaterial = (pass, ...buffers) => {
6925
7462
  const meshBuffer = buffers.at(0);
6926
- if (Utils24.isNull(meshBuffer)) {
7463
+ if (Utils25.isNull(meshBuffer)) {
6927
7464
  throw new ReferenceError(`Null ${RenderableBuffers.name} bringing vertex colors was provided.`);
6928
7465
  }
6929
7466
  const material = meshBuffer.buffer(ctx, "material");
@@ -6934,7 +7471,7 @@ var LineRenderPipelineClass = class {
6934
7471
  };
6935
7472
  this._bindLinePicker = (pass, ...buffers) => {
6936
7473
  const meshBuffer = buffers.at(0);
6937
- if (Utils24.isNull(meshBuffer)) {
7474
+ if (Utils25.isNull(meshBuffer)) {
6938
7475
  throw new ReferenceError(`Null ${RenderableBuffers.name} bringing world transform buffer was provided.`);
6939
7476
  }
6940
7477
  const { buffer } = meshBuffer.buffer(ctx, "u32id");
@@ -6956,7 +7493,7 @@ var LineRenderPipelineClass = class {
6956
7493
  };
6957
7494
 
6958
7495
  // packages/3d/dist/esm/adapters/webgpu/raycaster.js
6959
- import { Utils as Utils25 } from "@pacem/pacem-core";
7496
+ import { Utils as Utils26 } from "@pacem/pacem-core";
6960
7497
  var Raycasters = class {
6961
7498
  static {
6962
7499
  this._memoizer = /* @__PURE__ */ new WeakMap();
@@ -7006,7 +7543,7 @@ var ColorPickingRaycaster = class {
7006
7543
  this._objects = /* @__PURE__ */ new Map();
7007
7544
  this._pixel = { x: 0, y: 0 };
7008
7545
  this.frame = (pipeline, interaction, ...buffers) => {
7009
- if (Utils25.isNull(this._encoder)) {
7546
+ if (Utils26.isNull(this._encoder)) {
7010
7547
  throw new Error("Null encoder. Maybe you missed to call the 'begin' method first.");
7011
7548
  }
7012
7549
  const objects = Array.from(buffers);
@@ -7020,12 +7557,12 @@ var ColorPickingRaycaster = class {
7020
7557
  }
7021
7558
  };
7022
7559
  this.end = (pixel) => {
7023
- if (!Utils25.isNull(this._handle)) {
7560
+ if (!Utils26.isNull(this._handle)) {
7024
7561
  return this._handle;
7025
7562
  }
7026
7563
  const pass = this._pass;
7027
7564
  const commandEncoder = this._encoder;
7028
- if (Utils25.isNull(commandEncoder)) {
7565
+ if (Utils26.isNull(commandEncoder)) {
7029
7566
  return Promise.resolve([]);
7030
7567
  }
7031
7568
  const { device } = this._context;
@@ -7086,7 +7623,7 @@ var ColorPickingRaycaster = class {
7086
7623
  }
7087
7624
  _ensureBuffer() {
7088
7625
  const buffer = this._buffer;
7089
- if (!Utils25.isNull(buffer)) {
7626
+ if (!Utils26.isNull(buffer)) {
7090
7627
  return buffer;
7091
7628
  }
7092
7629
  const { device } = this._context;
@@ -7098,29 +7635,30 @@ var ColorPickingRaycaster = class {
7098
7635
  }
7099
7636
  _ensureTextures() {
7100
7637
  const textures = this._textures;
7101
- if (!Utils25.isNull(textures)) {
7638
+ if (!Utils26.isNull(textures)) {
7102
7639
  return textures;
7103
7640
  }
7104
- const renderTex = this._createTexture("r32uint"), depthTex = this._createTexture("depth24plus");
7641
+ const depthFormat = this._context.depth.format;
7642
+ const renderTex = this._createTexture("r32uint"), depthTex = this._createTexture(depthFormat);
7105
7643
  const render = { texture: renderTex, view: renderTex.createView() };
7106
7644
  const depth = { texture: depthTex, view: depthTex.createView() };
7107
7645
  return this._textures = { render, depth };
7108
7646
  }
7109
7647
  _destroyTexture(texture) {
7110
- if (Utils25.isNull(texture)) {
7648
+ if (Utils26.isNull(texture)) {
7111
7649
  return;
7112
7650
  }
7113
7651
  texture.texture?.destroy();
7114
7652
  }
7115
7653
  destroy() {
7116
7654
  const textures = this._textures, buffer = this._buffer;
7117
- if (!Utils25.isNullOrEmpty(textures)) {
7655
+ if (!Utils26.isNullOrEmpty(textures)) {
7118
7656
  const { render, depth } = textures;
7119
7657
  this._destroyTexture(render);
7120
7658
  this._destroyTexture(depth);
7121
7659
  this._textures = null;
7122
7660
  }
7123
- if (!Utils25.isNull(buffer)) {
7661
+ if (!Utils26.isNull(buffer)) {
7124
7662
  buffer.destroy();
7125
7663
  this._buffer = null;
7126
7664
  }
@@ -7129,7 +7667,7 @@ var ColorPickingRaycaster = class {
7129
7667
  return this._handle ?? null;
7130
7668
  }
7131
7669
  begin(pixel) {
7132
- const { device } = this._context;
7670
+ const { device, depth: depthState } = this._context;
7133
7671
  this._encoder = device.createCommandEncoder({ label: LABEL_PREFIX + "colorpick-raycaster" });
7134
7672
  const { render, depth } = this._ensureTextures();
7135
7673
  const { width, height } = render.texture;
@@ -7148,7 +7686,7 @@ var ColorPickingRaycaster = class {
7148
7686
  depthStencilAttachment: {
7149
7687
  view: depth.view,
7150
7688
  // Assigned later
7151
- depthClearValue: 1,
7689
+ depthClearValue: depthState.clearValue,
7152
7690
  depthLoadOp: "clear",
7153
7691
  depthStoreOp: "store"
7154
7692
  }
@@ -7160,7 +7698,7 @@ var ColorPickingRaycaster = class {
7160
7698
  };
7161
7699
 
7162
7700
  // packages/3d/dist/esm/adapters/webgpu/abuffer.js
7163
- import { Utils as Utils26 } from "@pacem/pacem-core";
7701
+ import { Utils as Utils27 } from "@pacem/pacem-core";
7164
7702
  var FRAGMENT_SIZE = 12;
7165
7703
  var ABuffers = class _ABuffers {
7166
7704
  static {
@@ -7168,7 +7706,7 @@ var ABuffers = class _ABuffers {
7168
7706
  }
7169
7707
  static _ensureComposite(ctx) {
7170
7708
  const existing = this._composites.get(ctx);
7171
- if (!Utils26.isNull(existing)) {
7709
+ if (!Utils27.isNull(existing)) {
7172
7710
  return existing;
7173
7711
  }
7174
7712
  const { device, format } = ctx;
@@ -7190,6 +7728,8 @@ var ABuffers = class _ABuffers {
7190
7728
  fragment: {
7191
7729
  module,
7192
7730
  entryPoint: "fragmentMain",
7731
+ // the far-to-near sort follows the depth direction
7732
+ constants: { [ABUFFER_REVERSED_Z_CONSTANT]: ctx.depth.reversed ? 1 : 0 },
7193
7733
  targets: [{
7194
7734
  format,
7195
7735
  // the composite outputs premultiplied colors
@@ -7274,7 +7814,7 @@ var ABuffers = class _ABuffers {
7274
7814
  };
7275
7815
 
7276
7816
  // packages/3d/dist/esm/adapters/webgpu/renderer.js
7277
- var Vector3D3 = Geometry8.LinearAlgebra.Vector3D;
7817
+ var Vector3D4 = Geometry10.LinearAlgebra.Vector3D;
7278
7818
  var WebGPUIssueCause;
7279
7819
  (function(WebGPUIssueCause2) {
7280
7820
  WebGPUIssueCause2[WebGPUIssueCause2["NotSupported"] = 0] = "NotSupported";
@@ -7312,9 +7852,9 @@ function getDefaultCamera(stage) {
7312
7852
  right: 1,
7313
7853
  near: 0.1,
7314
7854
  far: 200,
7315
- lookAt: Vector3D3.from(0, 0, 0),
7316
- up: Vector3D3.j(),
7317
- position: Vector3D3.from(0, 0, 1),
7855
+ lookAt: Vector3D4.from(0, 0, 0),
7856
+ up: Vector3D4.j(),
7857
+ position: Vector3D4.from(0, 0, 1),
7318
7858
  type: "orthographic",
7319
7859
  flags: [],
7320
7860
  stage
@@ -7325,17 +7865,20 @@ function destroyTextures(...textures) {
7325
7865
  tex?.destroy();
7326
7866
  }
7327
7867
  }
7328
- function isResolvedFor(resolved, material, texture, geometry, lightsSignature) {
7329
- if (Utils27.isNull(resolved)) {
7868
+ function isResolvedFor(resolved, material, texture, geometry, lightsSignature, receiveShadow) {
7869
+ if (Utils28.isNull(resolved)) {
7330
7870
  return false;
7331
7871
  }
7332
7872
  if (resolved.material !== material || resolved.texture !== texture) {
7333
7873
  return false;
7334
7874
  }
7875
+ if (resolved.receiveShadow !== receiveShadow) {
7876
+ return false;
7877
+ }
7335
7878
  return resolved.geometry === geometry && resolved.lights === lightsSignature;
7336
7879
  }
7337
7880
  function isABufferFor(aBuffer, depthView, width, height) {
7338
- if (Utils27.isNull(aBuffer) || aBuffer.depth !== depthView) {
7881
+ if (Utils28.isNull(aBuffer) || aBuffer.depth !== depthView) {
7339
7882
  return false;
7340
7883
  }
7341
7884
  return aBuffer.width === width && aBuffer.height === height;
@@ -7351,7 +7894,7 @@ function destroyMissing(previous, current) {
7351
7894
  }
7352
7895
  function createOrYieldManaged(store, item) {
7353
7896
  const found = store.get(item);
7354
- if (!Utils27.isNull(found) && !found.disposed) {
7897
+ if (!Utils28.isNull(found) && !found.disposed) {
7355
7898
  return found;
7356
7899
  }
7357
7900
  const created = ManagedBuffers.create(item);
@@ -7359,7 +7902,7 @@ function createOrYieldManaged(store, item) {
7359
7902
  return created;
7360
7903
  }
7361
7904
  function isTranslucent(mesh, pipeline) {
7362
- if (Utils27.isNull(pipeline.translucent)) {
7905
+ if (Utils28.isNull(pipeline.translucent)) {
7363
7906
  return false;
7364
7907
  }
7365
7908
  if (!isMeshGeometry(mesh.geometry)) {
@@ -7370,11 +7913,11 @@ function isTranslucent(mesh, pipeline) {
7370
7913
  var objectIds = /* @__PURE__ */ new WeakMap();
7371
7914
  var lastObjectId = 0;
7372
7915
  function objectId(obj) {
7373
- if (Utils27.isNull(obj)) {
7916
+ if (Utils28.isNull(obj)) {
7374
7917
  return 0;
7375
7918
  }
7376
7919
  const existing = objectIds.get(obj);
7377
- if (!Utils27.isNull(existing)) {
7920
+ if (!Utils28.isNull(existing)) {
7378
7921
  return existing;
7379
7922
  }
7380
7923
  const id = ++lastObjectId;
@@ -7460,9 +8003,10 @@ var RendererClass = class {
7460
8003
  this._log(`WebGPU device lost: ${info.message}`);
7461
8004
  };
7462
8005
  this.#hasModifiers = false;
8006
+ this.#shadowLimitLogged = false;
7463
8007
  const wrapper = (this.#stage = stage).stage;
7464
8008
  const canvas = document.createElement("canvas");
7465
- canvas.id = P17 + "_3d_stage_" + Utils27.uniqueCode();
8009
+ canvas.id = P17 + "_3d_stage_" + Utils28.uniqueCode();
7466
8010
  wrapper.innerHTML = "";
7467
8011
  wrapper.appendChild(this.#canvas = canvas);
7468
8012
  this.#interactionBuffer = ManagedBuffers.create(this.#interaction = {
@@ -7472,10 +8016,10 @@ var RendererClass = class {
7472
8016
  });
7473
8017
  }
7474
8018
  _buildPassDescriptor({ multisample, format }) {
7475
- const { context, device } = this.#context;
8019
+ const { context, device, depth } = this.#context;
7476
8020
  const canvasTexture = context.getCurrentTexture();
7477
8021
  let textures = this.#textures;
7478
- if (Utils27.isNull(textures)) {
8022
+ if (Utils28.isNull(textures)) {
7479
8023
  textures = {};
7480
8024
  if (multisample) {
7481
8025
  const renderTex = device.createTexture({
@@ -7491,7 +8035,7 @@ var RendererClass = class {
7491
8035
  };
7492
8036
  const depthTex = device.createTexture({
7493
8037
  label: LABEL_PREFIX + "depth-texture",
7494
- format: "depth24plus",
8038
+ format: depth.format,
7495
8039
  // also read by the A-buffer translucent pass (manual depth test)
7496
8040
  usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.TEXTURE_BINDING,
7497
8041
  size: [canvasTexture.width, canvasTexture.height],
@@ -7522,7 +8066,7 @@ var RendererClass = class {
7522
8066
  const depthTexView = textures.depth.view;
7523
8067
  passDescriptor.depthStencilAttachment = {
7524
8068
  view: depthTexView,
7525
- depthClearValue: 1,
8069
+ depthClearValue: depth.clearValue,
7526
8070
  depthLoadOp: "clear",
7527
8071
  depthStoreOp: "store"
7528
8072
  };
@@ -7563,12 +8107,13 @@ var RendererClass = class {
7563
8107
  device,
7564
8108
  format
7565
8109
  });
7566
- this.#context = { device, adapter, canvas: this.#canvas, context, format };
8110
+ const depth = this.#config.reversedZ ? REVERSED_DEPTH : STANDARD_DEPTH;
8111
+ this.#context = { device, adapter, canvas: this.#canvas, context, format, depth };
7567
8112
  this.#rebuildingContext = false;
7568
8113
  }
7569
8114
  _log(message) {
7570
8115
  const stage = this.#stage, logger = stage.logger;
7571
- if (!Utils27.isNull(logger)) {
8116
+ if (!Utils28.isNull(logger)) {
7572
8117
  logger.log(Logging2.LogLevel.Error, message, "WebGPU");
7573
8118
  }
7574
8119
  }
@@ -7576,16 +8121,16 @@ var RendererClass = class {
7576
8121
  this.#config = config;
7577
8122
  this.#pipelineOptions = { multisample: true, modifiers: config.modifiers };
7578
8123
  const adapter = await navigator.gpu.requestAdapter();
7579
- if (Utils27.isNull(adapter)) {
8124
+ if (Utils28.isNull(adapter)) {
7580
8125
  throw new Error("WebGPU adapter unavalable or disabled.");
7581
8126
  }
7582
8127
  const device = await adapter.requestDevice();
7583
- if (Utils27.isNull(device)) {
8128
+ if (Utils28.isNull(device)) {
7584
8129
  throw new Error("WebGPU device unavalable or disabled.");
7585
8130
  }
7586
8131
  device.addEventListener("uncapturederror", this._logError);
7587
8132
  device.lost.then(this._onDeviceLost);
7588
- this.#hasModifiers = !Utils27.isNull(config.modifiers?.version) && !Utils27.isNull(config.modifiers) && (!Utils27.isNull(config.modifiers.vertexInput) || !Utils27.isNull(config.modifiers.vertexOutput) || !Utils27.isNull(config.modifiers.fragment));
8133
+ this.#hasModifiers = !Utils28.isNull(config.modifiers?.version) && !Utils28.isNull(config.modifiers) && (!Utils28.isNull(config.modifiers.vertexInput) || !Utils28.isNull(config.modifiers.vertexOutput) || !Utils28.isNull(config.modifiers.fragment));
7589
8134
  const { context, textureFormat: format } = this._buildContext();
7590
8135
  this._buildUpContext(device, adapter, context, format);
7591
8136
  }
@@ -7596,9 +8141,13 @@ var RendererClass = class {
7596
8141
  * When true, the renderer must provide updated time, cursor position and canvas size to the pipeline's bind groups.
7597
8142
  */
7598
8143
  #hasModifiers;
7599
- /** Light types signature, part of the cache key of the pipelines resolved per mesh. */
8144
+ /** Light types (and shadow casting) signature, part of the cache key of the pipelines resolved per mesh. */
7600
8145
  _lightsSignature(lights) {
7601
- return lights.map((l) => l.item.type).join("-");
8146
+ const signatures = lights.map((l) => {
8147
+ const light = l.item;
8148
+ return isShadowCaster(light) ? light.type + "+shadow" : light.type;
8149
+ });
8150
+ return signatures.join("-");
7602
8151
  }
7603
8152
  /**
7604
8153
  * Returns the {@link RenderPipeline} drawing `mesh`, reusing the one resolved in previous frames as long as its
@@ -7606,10 +8155,10 @@ var RendererClass = class {
7606
8155
  * (which memoizes the built pipelines by recipe).
7607
8156
  */
7608
8157
  _resolvePipeline(mesh, camera, lights, lightsSignature) {
7609
- const item = mesh.item, material = item.material, texture = material?.texture, geometry = item.geometry;
8158
+ const item = mesh.item, material = item.material, texture = material?.texture, geometry = item.geometry, receiveShadow = receivesShadow(item);
7610
8159
  const pipelines = this.#pipelines;
7611
8160
  const existing = pipelines.get(mesh);
7612
- const reusable = isResolvedFor(existing, material, texture, geometry, lightsSignature);
8161
+ const reusable = isResolvedFor(existing, material, texture, geometry, lightsSignature, receiveShadow);
7613
8162
  if (reusable) {
7614
8163
  if (material?.flags?.length > 0) {
7615
8164
  existing.translucent = isTranslucent(item, existing.pipeline);
@@ -7618,11 +8167,59 @@ var RendererClass = class {
7618
8167
  }
7619
8168
  const pipeline = RenderPipelines.create(this.#context, [mesh, camera, ...lights], this.#pipelineOptions);
7620
8169
  const translucent = isTranslucent(item, pipeline);
7621
- const resolved = { material, texture, geometry, lights: lightsSignature, pipeline, translucent };
8170
+ const resolved = { material, texture, geometry, lights: lightsSignature, receiveShadow, pipeline, translucent };
7622
8171
  pipelines.set(mesh, resolved);
7623
8172
  return resolved;
7624
8173
  }
7625
8174
  #aBuffer;
8175
+ /** Whether the "too many shadow-casting lights" warning was already logged. */
8176
+ #shadowLimitLogged;
8177
+ /**
8178
+ * Renders the depth of the shadow-casting meshes into the shadow map layers of the shadow-casting lights (one
8179
+ * depth-only pass per layer: one per directional light, six per omni light, see `shadows.ts`). Translucent
8180
+ * meshes and lines don't cast.
8181
+ */
8182
+ _renderShadows(encoder, lightsSignature) {
8183
+ const looper = this.#looper, { meshes, cameras, lights } = looper.items;
8184
+ const allocation = allocateShadowLayers(lights, (l) => l.item);
8185
+ if (allocation.size === 0) {
8186
+ return;
8187
+ }
8188
+ const requested = lights.filter((l) => isShadowCaster(l.item));
8189
+ if (requested.length > allocation.size && !this.#shadowLimitLogged) {
8190
+ this.#shadowLimitLogged = true;
8191
+ this._log(`Not enough shadow map layers: ${requested.length - allocation.size} light(s) won't cast shadows.`);
8192
+ }
8193
+ const ctx = this.#context;
8194
+ const shadows = Shadows.ensure(ctx);
8195
+ const casters = [];
8196
+ for (let [buffer, firstLayer] of allocation) {
8197
+ casters.push({ light: buffer.item, firstLayer });
8198
+ }
8199
+ shadows.update(casters, meshes);
8200
+ const camera = cameras[0];
8201
+ const count = shadows.layerCount;
8202
+ for (let i = 0; i < count; i++) {
8203
+ const pass = encoder.beginRenderPass({
8204
+ label: LABEL_PREFIX + "shadow-pass-" + i,
8205
+ colorAttachments: [],
8206
+ depthStencilAttachment: { view: shadows.layer(i), depthClearValue: 1, depthLoadOp: "clear", depthStoreOp: "store" }
8207
+ });
8208
+ const lightCamera = shadows.camera(i);
8209
+ for (let mesh of meshes) {
8210
+ const item = mesh.item;
8211
+ if (mesh.disposed || item.hide || !castsShadow(item)) {
8212
+ continue;
8213
+ }
8214
+ const resolved = this._resolvePipeline(mesh, camera, lights, lightsSignature);
8215
+ if (resolved.translucent || Utils28.isNull(resolved.pipeline.shadow)) {
8216
+ continue;
8217
+ }
8218
+ resolved.pipeline.shadow(pass, this.#interactionBuffer, mesh, lightCamera);
8219
+ }
8220
+ pass.end();
8221
+ }
8222
+ }
7626
8223
  /** Returns the A-buffer matching the current render targets, (re)creating it when needed. */
7627
8224
  _ensureABuffer(depthView, width, height) {
7628
8225
  const current = this.#aBuffer;
@@ -7636,7 +8233,7 @@ var RendererClass = class {
7636
8233
  }
7637
8234
  /** Whether a frame can be rendered: context ready, device alive, scene set and a non-empty render target. */
7638
8235
  _canRender() {
7639
- if (this.#rebuildingContext || this.#lost || Utils27.isNull(this.#looper)) {
8236
+ if (this.#rebuildingContext || this.#lost || Utils28.isNull(this.#looper)) {
7640
8237
  return false;
7641
8238
  }
7642
8239
  const canvas = this.#canvas;
@@ -7646,7 +8243,7 @@ var RendererClass = class {
7646
8243
  _popValidationScope(device) {
7647
8244
  const popped = device.popErrorScope();
7648
8245
  popped.then((error) => {
7649
- if (Utils27.isNull(error)) {
8246
+ if (Utils28.isNull(error)) {
7650
8247
  return;
7651
8248
  }
7652
8249
  this._logError(error);
@@ -7673,18 +8270,19 @@ var RendererClass = class {
7673
8270
  const context = this.#context, device = context.device, looper = this.#looper;
7674
8271
  const validationScope = this.#config?.enableValidation ?? false;
7675
8272
  if (this.#hasModifiers) {
7676
- Utils27.extend(this.#interaction, interaction);
8273
+ Utils28.extend(this.#interaction, interaction);
7677
8274
  }
7678
8275
  const multisample = true;
7679
8276
  const { descriptor: passDescriptor, canvasView, depthView, width, height } = this._buildPassDescriptor({ multisample });
7680
8277
  const transparency = this.#config?.transparency ?? "a-buffer";
7681
- const aBufferMode = transparency === "a-buffer" && !Utils27.isNull(depthView);
8278
+ const aBufferMode = transparency === "a-buffer" && !Utils28.isNull(depthView);
7682
8279
  const commandEncoder = device.createCommandEncoder({ label: LABEL_PREFIX + "renderer" });
7683
- const pass = commandEncoder.beginRenderPass(passDescriptor);
7684
8280
  const lightsSignature = this._lightsSignature(looper.items.lights);
8281
+ this._renderShadows(commandEncoder, lightsSignature);
8282
+ const pass = commandEncoder.beginRenderPass(passDescriptor);
7685
8283
  let translucent = null;
7686
8284
  const ensureTranslucentPass = () => {
7687
- if (!Utils27.isNull(translucent)) {
8285
+ if (!Utils28.isNull(translucent)) {
7688
8286
  return translucent;
7689
8287
  }
7690
8288
  const aBuffer = this._ensureABuffer(depthView, width, height);
@@ -7719,7 +8317,7 @@ var RendererClass = class {
7719
8317
  });
7720
8318
  pass.end();
7721
8319
  const opaqueCommands = commandEncoder.finish();
7722
- if (Utils27.isNull(translucent)) {
8320
+ if (Utils28.isNull(translucent)) {
7723
8321
  device.queue.submit([opaqueCommands]);
7724
8322
  return;
7725
8323
  }
@@ -7733,13 +8331,13 @@ var RendererClass = class {
7733
8331
  return this.#disabled;
7734
8332
  }
7735
8333
  raycast(pixel) {
7736
- if (this.#rebuildingContext || this.#lost || Utils27.isNull(this.#looper)) {
8334
+ if (this.#rebuildingContext || this.#lost || Utils28.isNull(this.#looper)) {
7737
8335
  return Promise.resolve([]);
7738
8336
  }
7739
8337
  const context = this.#context, device = context.device, looper = this.#looper;
7740
8338
  const raycaster = Raycasters.createColorPicking(context);
7741
8339
  const pending = raycaster.pending;
7742
- if (!Utils27.isNull(pending)) {
8340
+ if (!Utils28.isNull(pending)) {
7743
8341
  return pending;
7744
8342
  }
7745
8343
  const validationScope = this.#config?.enableValidation ?? false;
@@ -7772,7 +8370,7 @@ var RendererClass = class {
7772
8370
  item.stage ??= this.#stage;
7773
8371
  const store = this.#renderables;
7774
8372
  const found = store.get(item);
7775
- const usable = !Utils27.isNull(found) && !found.disposed && Utils27.isNull(found.parent);
8373
+ const usable = !Utils28.isNull(found) && !found.disposed && Utils28.isNull(found.parent);
7776
8374
  if (usable) {
7777
8375
  return found;
7778
8376
  }
@@ -7808,7 +8406,7 @@ var RendererClass = class {
7808
8406
  }
7809
8407
  /** Destroys the buffers of `previous` not taking part in `current` anymore (removed/replaced items). */
7810
8408
  _destroyLeftovers(previous, current) {
7811
- if (Utils27.isNull(previous)) {
8409
+ if (Utils28.isNull(previous)) {
7812
8410
  return;
7813
8411
  }
7814
8412
  for (let category of ["meshes", "lights", "cameras", "groups"]) {
@@ -7836,7 +8434,7 @@ var RendererClass = class {
7836
8434
  }
7837
8435
  if (isMesh(item) && item.geometry) {
7838
8436
  this._createOrYieldGeometry(item.geometry);
7839
- if (!Utils27.isNull(item.material)) {
8437
+ if (!Utils28.isNull(item.material)) {
7840
8438
  this._createOrYieldMaterial(item.material);
7841
8439
  }
7842
8440
  meshBuffers.push(factory(item));
@@ -7884,17 +8482,18 @@ var RendererClass = class {
7884
8482
  aBuffer?.destroy();
7885
8483
  const textures = this.#textures;
7886
8484
  this.#textures = null;
7887
- if (!Utils27.isNull(textures)) {
8485
+ if (!Utils28.isNull(textures)) {
7888
8486
  const { render, depth } = textures;
7889
8487
  destroyTextures(render?.texture, depth?.texture);
7890
8488
  }
7891
8489
  }
7892
8490
  _disposeContext() {
7893
8491
  const ctx = this.#context;
7894
- if (Utils27.isNull(ctx)) {
8492
+ if (Utils28.isNull(ctx)) {
7895
8493
  return false;
7896
8494
  }
7897
8495
  Raycasters.dispose(ctx);
8496
+ Shadows.dispose(ctx);
7898
8497
  RenderPipelines.dispose(ctx);
7899
8498
  ABuffers.dispose(ctx);
7900
8499
  this._destroyRenderTargets();
@@ -7903,7 +8502,7 @@ var RendererClass = class {
7903
8502
  }
7904
8503
  resize(size) {
7905
8504
  const ctx = this.#context;
7906
- if (Utils27.isNull(ctx)) {
8505
+ if (Utils28.isNull(ctx)) {
7907
8506
  return;
7908
8507
  }
7909
8508
  this._applySize(this.canvas, size);
@@ -7911,7 +8510,7 @@ var RendererClass = class {
7911
8510
  Raycasters.dispose(ctx);
7912
8511
  this._ensureAlphaMode(ctx);
7913
8512
  if (this.#hasModifiers) {
7914
- Utils27.extend(this.#interaction, { resolution: size });
8513
+ Utils28.extend(this.#interaction, { resolution: size });
7915
8514
  }
7916
8515
  }
7917
8516
  /** `transparent` changes come through `resize`, too (see `Pacem3DElement`): reconfigures the canvas only when the alpha mode changes. */
@@ -7969,7 +8568,7 @@ var Pacem3DWgslScriptElement = class Pacem3DWgslScriptElement2 extends Component
7969
8568
  const old = this.#version;
7970
8569
  const val = v;
7971
8570
  this.#version = val;
7972
- const evt = new PropertyChangeEvent2({ propertyName: "version", oldValue: old, currentValue: val, firstChange: Utils28.isNullOrEmpty(old) });
8571
+ const evt = new PropertyChangeEvent2({ propertyName: "version", oldValue: old, currentValue: val, firstChange: Utils29.isNullOrEmpty(old) });
7973
8572
  this.dispatchEvent(evt);
7974
8573
  }
7975
8574
  });
@@ -8065,7 +8664,7 @@ var Pacem3DWebgpuAdapterElement = class Pacem3DWebgpuAdapterElement2 extends Pac
8065
8664
  scenes.add(scene);
8066
8665
  }
8067
8666
  const transparency = this.transparency === "blend" ? "blend" : "a-buffer";
8068
- const config = { enableValidation: this.enableValidation ?? false, modifiers: this.modifiers, transparency };
8667
+ const config = { enableValidation: this.enableValidation ?? false, modifiers: this.modifiers, transparency, reversedZ: this.reversedZ ?? false };
8069
8668
  const creation = Renderers.create(scene, config);
8070
8669
  return creation.then((renderer) => {
8071
8670
  const previous = set.get(scene);
@@ -8095,6 +8694,7 @@ var Pacem3DWebgpuAdapterElement = class Pacem3DWebgpuAdapterElement2 extends Pac
8095
8694
  case "modifiers":
8096
8695
  case "enableValidation":
8097
8696
  case "transparency":
8697
+ case "reversedZ":
8098
8698
  this._reinitialize();
8099
8699
  break;
8100
8700
  }
@@ -8143,7 +8743,7 @@ var Pacem3DWebgpuAdapterElement = class Pacem3DWebgpuAdapterElement2 extends Pac
8143
8743
  return;
8144
8744
  }
8145
8745
  const renderer = this._ensureRenderer(scene);
8146
- if (Utils28.isNull(renderer)) {
8746
+ if (Utils29.isNull(renderer)) {
8147
8747
  return;
8148
8748
  }
8149
8749
  if (this.#sceneToUpdate.has(scene)) {
@@ -8156,15 +8756,15 @@ var Pacem3DWebgpuAdapterElement = class Pacem3DWebgpuAdapterElement2 extends Pac
8156
8756
  return;
8157
8757
  }
8158
8758
  const callback = GETVAL(scene, WEBGPU_RAYCAST_CALLBACK_PROP);
8159
- if (Utils28.isNullOrEmpty(callback)) {
8759
+ if (Utils29.isNullOrEmpty(callback)) {
8160
8760
  return;
8161
8761
  }
8162
- if (Utils28.isNullOrEmpty(pixel)) {
8762
+ if (Utils29.isNullOrEmpty(pixel)) {
8163
8763
  callback(null);
8164
8764
  return;
8165
8765
  }
8166
8766
  renderer.raycast(pixel).then((array) => {
8167
- if (Utils28.isNullOrEmpty(array)) {
8767
+ if (Utils29.isNullOrEmpty(array)) {
8168
8768
  callback(null);
8169
8769
  } else {
8170
8770
  const retval = {
@@ -8181,10 +8781,10 @@ var Pacem3DWebgpuAdapterElement = class Pacem3DWebgpuAdapterElement2 extends Pac
8181
8781
  return Promise.resolve(null);
8182
8782
  }
8183
8783
  const { canvas } = renderers.get(scene);
8184
- const jpeg = !Utils28.isNullOrEmpty(background), mime = type ?? (jpeg ? "image/jpeg" : null), compression = quality ?? (jpeg ? 0.9 : null);
8784
+ const jpeg = !Utils29.isNullOrEmpty(background), mime = type ?? (jpeg ? "image/jpeg" : null), compression = quality ?? (jpeg ? 0.9 : null);
8185
8785
  return new Promise((resolve, _) => {
8186
8786
  this.render(scene);
8187
- Utils28.snapshotElement(canvas, background, mime, compression).then(resolve);
8787
+ Utils29.snapshotElement(canvas, background, mime, compression).then(resolve);
8188
8788
  });
8189
8789
  }
8190
8790
  raycast(stage, point, size, callback) {
@@ -8208,7 +8808,7 @@ var Pacem3DWebgpuAdapterElement = class Pacem3DWebgpuAdapterElement2 extends Pac
8208
8808
  this._itemsChanged(stage, item);
8209
8809
  }
8210
8810
  updateItem(stage, item) {
8211
- if (Utils28.isNull(item) || item.flags.indexOf(StalePropertyFlag.Visibility) >= 0 || item.flags.indexOf(StalePropertyFlag.Children) >= 0) {
8811
+ if (Utils29.isNull(item) || item.flags.indexOf(StalePropertyFlag.Visibility) >= 0 || item.flags.indexOf(StalePropertyFlag.Children) >= 0) {
8212
8812
  this._itemsChanged(stage, item);
8213
8813
  }
8214
8814
  }
@@ -8234,23 +8834,26 @@ __decorate21([
8234
8834
  __decorate21([
8235
8835
  Watch18({ emit: false, converter: PropertyConverters18.String })
8236
8836
  ], Pacem3DWebgpuAdapterElement.prototype, "transparency", void 0);
8837
+ __decorate21([
8838
+ Watch18({ emit: false, converter: PropertyConverters18.Boolean })
8839
+ ], Pacem3DWebgpuAdapterElement.prototype, "reversedZ", void 0);
8237
8840
  Pacem3DWebgpuAdapterElement = __decorate21([
8238
8841
  CustomElement17({ tagName: P18 + "-3d-webgpu-adapter" })
8239
8842
  ], Pacem3DWebgpuAdapterElement);
8240
8843
 
8241
8844
  // packages/3d/dist/esm/adapters/webgpu/behaviors/orbit-camera.js
8242
- import { CustomElement as CustomElement18, P as P19, Watch as Watch19, PropertyConverters as PropertyConverters19, Utils as Utils29, CustomEventUtils as CustomEventUtils2, avoidHandler, Behaviors, PropertyChangeEventName as PropertyChangeEventName3 } from "@pacem/pacem-core";
8243
- import { Geometry as Geometry9 } from "@pacem/pacem-numerical";
8845
+ import { CustomElement as CustomElement18, P as P19, Watch as Watch19, PropertyConverters as PropertyConverters19, Utils as Utils30, CustomEventUtils as CustomEventUtils2, avoidHandler, Behaviors, PropertyChangeEventName as PropertyChangeEventName3 } from "@pacem/pacem-core";
8846
+ import { Geometry as Geometry11 } from "@pacem/pacem-numerical";
8244
8847
  var __decorate22 = function(decorators, target, key, desc) {
8245
8848
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
8246
8849
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
8247
8850
  else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
8248
8851
  return c > 3 && r && Object.defineProperty(target, key, r), r;
8249
8852
  };
8250
- var Vector3D4 = Geometry9.LinearAlgebra.Vector3D;
8251
- var Matrix3D3 = Geometry9.LinearAlgebra.Matrix3D;
8252
- var Quaternion = Geometry9.LinearAlgebra.Quaternion;
8253
- var Spherical = Geometry9.LinearAlgebra.Spherical;
8853
+ var Vector3D5 = Geometry11.LinearAlgebra.Vector3D;
8854
+ var Matrix3D5 = Geometry11.LinearAlgebra.Matrix3D;
8855
+ var Quaternion = Geometry11.LinearAlgebra.Quaternion;
8856
+ var Spherical = Geometry11.LinearAlgebra.Spherical;
8254
8857
  function findCameraStage(element) {
8255
8858
  if (isCamera(element)) {
8256
8859
  return element.stage;
@@ -8304,7 +8907,7 @@ var OrbitCameraBehavior = class _OrbitCameraBehavior {
8304
8907
  this.#rotating = rotating;
8305
8908
  if (this.#panning = panning) {
8306
8909
  this._currentState = _OrbitCameraBehavior._buildState(this._camera);
8307
- Utils29.extend(this._input, Vector3D4.zero());
8910
+ Utils30.extend(this._input, Vector3D5.zero());
8308
8911
  this._progress.x = this._progress.y = 0;
8309
8912
  }
8310
8913
  avoidHandler(evt);
@@ -8360,9 +8963,9 @@ var OrbitCameraBehavior = class _OrbitCameraBehavior {
8360
8963
  scene.addEventListener("render", this._renderHandler, false);
8361
8964
  }
8362
8965
  static _buildState(camera) {
8363
- const vector = Vector3D4.subtract(camera.position, camera.lookAt);
8364
- const radius = Vector3D4.mag(vector);
8365
- return { target: camera.lookAt, versor: Vector3D4.unit(vector), up: camera.up, radius, position: camera.position };
8966
+ const vector = Vector3D5.subtract(camera.position, camera.lookAt);
8967
+ const radius = Vector3D5.mag(vector);
8968
+ return { target: camera.lookAt, versor: Vector3D5.unit(vector), up: camera.up, radius, position: camera.position };
8366
8969
  }
8367
8970
  /**
8368
8971
  * Tries to attach a new {@link OrbitCameraBehavior} to the provided element, if the element is a proper renderable and it is ready.
@@ -8372,9 +8975,9 @@ var OrbitCameraBehavior = class _OrbitCameraBehavior {
8372
8975
  static tryAttach(element, config) {
8373
8976
  config ??= DEFAULT_CONFIGURATION;
8374
8977
  const canvas = findCameraStage(element)?.stage;
8375
- if (!Utils29.isNull(canvas)) {
8978
+ if (!Utils30.isNull(canvas)) {
8376
8979
  const { position, lookAt } = element;
8377
- if (Utils29.isNull(position) || Utils29.isNull(lookAt) || Vector3D4.areClose(position, lookAt)) {
8980
+ if (Utils30.isNull(position) || Utils30.isNull(lookAt) || Vector3D5.areClose(position, lookAt)) {
8378
8981
  return null;
8379
8982
  }
8380
8983
  return new _OrbitCameraBehavior(element, config);
@@ -8405,10 +9008,10 @@ var OrbitCameraBehavior = class _OrbitCameraBehavior {
8405
9008
  }
8406
9009
  static _getViewXYZ(state) {
8407
9010
  const { versor, up: initUp } = state;
8408
- const right = Vector3D4.cross(versor, initUp);
8409
- const up = Vector3D4.cross(right, versor);
8410
- Vector3D4.normalize(right);
8411
- Vector3D4.normalize(up);
9011
+ const right = Vector3D5.cross(versor, initUp);
9012
+ const up = Vector3D5.cross(right, versor);
9013
+ Vector3D5.normalize(right);
9014
+ Vector3D5.normalize(up);
8412
9015
  return { right, up, versor };
8413
9016
  }
8414
9017
  #updating;
@@ -8439,8 +9042,8 @@ var OrbitCameraBehavior = class _OrbitCameraBehavior {
8439
9042
  }
8440
9043
  progress.rho = rho0;
8441
9044
  const scale = Math.pow(0.95, rho0 * ZOOM_FACTOR);
8442
- const zoom = Vector3D4.scale(versor, -scale * radius);
8443
- newPosition = Vector3D4.add(newPosition, zoom);
9045
+ const zoom = Vector3D5.scale(versor, -scale * radius);
9046
+ newPosition = Vector3D5.add(newPosition, zoom);
8444
9047
  let phi0 = phi_;
8445
9048
  let theta0 = theta_;
8446
9049
  if (inertiaSpecified) {
@@ -8452,15 +9055,15 @@ var OrbitCameraBehavior = class _OrbitCameraBehavior {
8452
9055
  }
8453
9056
  const PHI = this._getSafePolar({ phi: progress.phi = phi0 });
8454
9057
  const THETA = this._getSafeAzimuth({ theta: progress.theta = theta0 });
8455
- const pivot = Vector3D4.negate(initTarget);
8456
- let m = Matrix3D3.translate(Matrix3D3.identity(), pivot);
9058
+ const pivot = Vector3D5.negate(initTarget);
9059
+ let m = Matrix3D5.translate(Matrix3D5.identity(), pivot);
8457
9060
  const qy = Quaternion.fromAxisAngle(up, PHI);
8458
9061
  const qx = Quaternion.fromAxisAngle(right, THETA);
8459
- const rot = Matrix3D3.multiply(Quaternion.toRotationMatrix(qx), Quaternion.toRotationMatrix(qy));
8460
- m = Matrix3D3.multiply(m, rot);
8461
- m = Matrix3D3.translate(m, Vector3D4.negate(pivot));
8462
- newPosition = Matrix3D3.transform(newPosition, m);
8463
- newUp = Matrix3D3.transform(newUp, Matrix3D3.clone(m, (m0) => {
9062
+ const rot = Matrix3D5.multiply(Quaternion.toRotationMatrix(qx), Quaternion.toRotationMatrix(qy));
9063
+ m = Matrix3D5.multiply(m, rot);
9064
+ m = Matrix3D5.translate(m, Vector3D5.negate(pivot));
9065
+ newPosition = Matrix3D5.transform(newPosition, m);
9066
+ newUp = Matrix3D5.transform(newUp, Matrix3D5.clone(m, (m0) => {
8464
9067
  m0.offsetX = m0.offsetY = m0.offsetZ = 0;
8465
9068
  }));
8466
9069
  const x1 = x_, y1 = y_;
@@ -8475,9 +9078,9 @@ var OrbitCameraBehavior = class _OrbitCameraBehavior {
8475
9078
  progress.x = x0;
8476
9079
  progress.y = y0;
8477
9080
  const { right: currentRight, up: currentUp } = _OrbitCameraBehavior._getViewXYZ(this._currentState);
8478
- const r = Vector3D4.scale(currentRight, x0), u = Vector3D4.scale(currentUp, y0);
8479
- const offset = Vector3D4.add(r, u);
8480
- newLookAt = Vector3D4.add(trackedLookAt, offset);
9081
+ const r = Vector3D5.scale(currentRight, x0), u = Vector3D5.scale(currentUp, y0);
9082
+ const offset = Vector3D5.add(r, u);
9083
+ newLookAt = Vector3D5.add(trackedLookAt, offset);
8481
9084
  camera.lookAt = newLookAt;
8482
9085
  camera.position = newPosition;
8483
9086
  camera.up = newUp;
@@ -8488,7 +9091,7 @@ var OrbitCameraBehavior = class _OrbitCameraBehavior {
8488
9091
  /** Detaches and removes handlers and resources. */
8489
9092
  dispose() {
8490
9093
  const canvas = this._canvas, scene = this._scene;
8491
- if (!Utils29.isNull(canvas)) {
9094
+ if (!Utils30.isNull(canvas)) {
8492
9095
  canvas.removeEventListener("pointerdown", this._startHandler);
8493
9096
  canvas.removeEventListener("wheel", this._zoomHandler);
8494
9097
  }
@@ -8534,7 +9137,7 @@ var PacemOrbitCameraBehaviorElement = class PacemOrbitCameraBehaviorElement2 ext
8534
9137
  super.disconnectedCallback();
8535
9138
  }
8536
9139
  _buildConfig() {
8537
- return Utils29.extend({}, DEFAULT_CONFIGURATION, {
9140
+ return Utils30.extend({}, DEFAULT_CONFIGURATION, {
8538
9141
  maxAzimuth: this.maxAzimuth ?? Infinity,
8539
9142
  minAzimuth: this.minAzimuth ?? -Infinity,
8540
9143
  minPolar: this.minPolar ?? -Infinity,
@@ -8547,7 +9150,7 @@ var PacemOrbitCameraBehaviorElement = class PacemOrbitCameraBehaviorElement2 ext
8547
9150
  }
8548
9151
  _decorateCore(element) {
8549
9152
  const behavior = OrbitCameraBehavior.tryAttach(element, this._buildConfig());
8550
- if (!Utils29.isNull(behavior)) {
9153
+ if (!Utils30.isNull(behavior)) {
8551
9154
  this.#map.set(element, behavior);
8552
9155
  }
8553
9156
  }