@pacem/pacem-3d 1.0.6-ricci → 2.0.0-abel

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 v1.0.6-ricci (https://js.pacem.it)
2
+ * @pacem/pacem-3d v2.0.0-abel (https://js.pacem.it)
3
3
  * Pacem (https://pacem.it)
4
4
  * Licensed under Apache-2.0
5
5
  */
@@ -3727,11 +3727,11 @@ Pacem3DThreeAdapterElement = __decorate20([
3727
3727
  ], Pacem3DThreeAdapterElement);
3728
3728
 
3729
3729
  // 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 Utils27, Logging as Logging3, Components as Components3 } from "@pacem/pacem-core";
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";
3731
3731
  import { Strings } from "@pacem/pacem-foundation";
3732
3732
 
3733
3733
  // packages/3d/dist/esm/adapters/webgpu/renderer.js
3734
- import { Utils as Utils26, P as P17, Logging as Logging2 } from "@pacem/pacem-core";
3734
+ import { Utils as Utils27, P as P17, Logging as Logging2 } from "@pacem/pacem-core";
3735
3735
  import { Colors as Colors4 } from "@pacem/pacem-foundation";
3736
3736
  import { Geometry as Geometry8 } from "@pacem/pacem-numerical";
3737
3737
 
@@ -3763,6 +3763,12 @@ var TEXTURE_BINDING_INDEX = 2;
3763
3763
  var VERTEX_COLOR_REFERENCE = "color";
3764
3764
  var AMBIENT_COLOR_REFERENCE = "ambient";
3765
3765
  var LIGHTING_COLOR_REFERENCE = "lighting";
3766
+ var ABUFFER_BINDING_INDEX_HEADS = 2;
3767
+ var ABUFFER_BINDING_INDEX_LIST = 3;
3768
+ var ABUFFER_BINDING_INDEX_INFO = 4;
3769
+ var ABUFFER_BINDING_INDEX_DEPTH = 5;
3770
+ var ABUFFER_AVERAGE_LAYERS = 4;
3771
+ var ABUFFER_MAX_SORTED_LAYERS = 16;
3766
3772
  var WGSL_VERTEXINPUT_STRUCT_NAME = "VertexInput";
3767
3773
  var WGSL_VERTEXOUTPUT_STRUCT_NAME = "VertexOutput";
3768
3774
  var WGSL_INTERACTIONDATA_STRUCT_NAME = "InteractionData";
@@ -3813,6 +3819,20 @@ var WGSLBindingType;
3813
3819
  })(WGSLBindingType || (WGSLBindingType = {}));
3814
3820
 
3815
3821
  // packages/3d/dist/esm/adapters/webgpu/buffers.js
3822
+ function createPopulated(device, data, usage, label) {
3823
+ const buffer = device.createBuffer({
3824
+ size: data.byteLength,
3825
+ label,
3826
+ usage,
3827
+ mappedAtCreation: true
3828
+ });
3829
+ const mappedRange = buffer.getMappedRange();
3830
+ const target = new Uint8Array(mappedRange);
3831
+ const source = new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
3832
+ target.set(source);
3833
+ buffer.unmap();
3834
+ return buffer;
3835
+ }
3816
3836
  var Buffers = class {
3817
3837
  /**
3818
3838
  * Creates a {@link GPUBuffer} usable as a vertex buffer (`VERTEX | COPY_DST`), writing `data` into it immediately.
@@ -3832,18 +3852,19 @@ var Buffers = class {
3832
3852
  return buffer;
3833
3853
  }
3834
3854
  static createUniform(device, data, label = "") {
3835
- return device.createBuffer({
3836
- size: data.byteLength,
3837
- label,
3838
- usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST
3839
- });
3855
+ return createPopulated(device, data, GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST, label);
3840
3856
  }
3841
3857
  static createStorage(device, data, label = "") {
3842
- return device.createBuffer({
3843
- size: data.byteLength,
3844
- label,
3845
- usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_DST
3846
- });
3858
+ return createPopulated(device, data, GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_DST, label);
3859
+ }
3860
+ /**
3861
+ * Uploads `data` into an existing `buffer` (same byte length expected), in place, via {@link GPUQueue.writeBuffer}.
3862
+ * @param device The {@link GPUDevice} owning the buffer.
3863
+ * @param buffer The destination buffer.
3864
+ * @param data The new contents.
3865
+ */
3866
+ static write(device, buffer, data) {
3867
+ device.queue.writeBuffer(buffer, 0, data);
3847
3868
  }
3848
3869
  /**
3849
3870
  * Creates a {@link GPUBuffer} usable as an index buffer (`INDEX | COPY_DST`), writing `data` into it immediately.
@@ -3890,6 +3911,118 @@ import { Colors as Colors2 } from "@pacem/pacem-foundation";
3890
3911
 
3891
3912
  // packages/3d/dist/esm/adapters/webgpu/wgsl/basic-material-fragment.js
3892
3913
  import { Utils as Utils14 } from "@pacem/pacem-core";
3914
+
3915
+ // packages/3d/dist/esm/adapters/webgpu/wgsl/a-buffer.js
3916
+ var FRAGMENT_STRUCT = `struct ABufferFragment {
3917
+ color: u32,
3918
+ depth: f32,
3919
+ next: u32,
3920
+ }`;
3921
+ var INFO_STRUCT = `struct ABufferInfo {
3922
+ width: u32,
3923
+ height: u32,
3924
+ capacity: u32,
3925
+ padding: u32,
3926
+ }`;
3927
+ function aBufferFragmentExtra(group = UNIFORM_GROUP_INDEX_CAMERA) {
3928
+ return {
3929
+ definitions: [FRAGMENT_STRUCT, INFO_STRUCT, `struct ABufferHeads {
3930
+ count: atomic<u32>,
3931
+ data: array<atomic<u32>>,
3932
+ }`],
3933
+ bindings: [
3934
+ `@group(${group}) @binding(${ABUFFER_BINDING_INDEX_HEADS}) var<storage, read_write> aBufferHeads: ABufferHeads;`,
3935
+ `@group(${group}) @binding(${ABUFFER_BINDING_INDEX_LIST}) var<storage, read_write> aBufferList: array<ABufferFragment>;`,
3936
+ `@group(${group}) @binding(${ABUFFER_BINDING_INDEX_INFO}) var<uniform> aBufferInfo: ABufferInfo;`,
3937
+ `@group(${group}) @binding(${ABUFFER_BINDING_INDEX_DEPTH}) var aBufferOpaqueDepth: texture_depth_multisampled_2d;`,
3938
+ `fn aBufferInsert(position: vec4f, sampleMask: u32, color: vec4f) {
3939
+ // one fragment per surface and pixel: only the triangle covering sample 0 (the one depth is tested against) counts,
3940
+ // otherwise pixels along shared triangle edges would get the surface twice
3941
+ let coversSample0 = (sampleMask & 1u) != 0u;
3942
+ if (!coversSample0 || color.a <= 0.0) {
3943
+ return;
3944
+ }
3945
+ let pixel = vec2u(position.xy);
3946
+ if (pixel.x >= aBufferInfo.width || pixel.y >= aBufferInfo.height) {
3947
+ return;
3948
+ }
3949
+ // manual depth test against the opaque geometry
3950
+ let opaqueDepth = textureLoad(aBufferOpaqueDepth, pixel, 0);
3951
+ if (position.z >= opaqueDepth) {
3952
+ return;
3953
+ }
3954
+ let slot = atomicAdd(&aBufferHeads.count, 1u);
3955
+ if (slot >= aBufferInfo.capacity) {
3956
+ return;
3957
+ }
3958
+ let head = &aBufferHeads.data[pixel.y * aBufferInfo.width + pixel.x];
3959
+ let previous = atomicExchange(head, slot + 1u);
3960
+ let clamped = clamp(color, vec4f(0), vec4f(1));
3961
+ let packed = pack4x8unorm(clamped);
3962
+ aBufferList[slot] = ABufferFragment(packed, position.z, previous);
3963
+ }`
3964
+ ],
3965
+ modifiers: []
3966
+ };
3967
+ }
3968
+ function getABufferCompositeWgsl() {
3969
+ return `${FRAGMENT_STRUCT}
3970
+
3971
+ ${INFO_STRUCT}
3972
+
3973
+ struct ABufferHeads {
3974
+ count: u32,
3975
+ data: array<u32>,
3976
+ }
3977
+
3978
+ @group(0) @binding(0) var<storage, read> heads: ABufferHeads;
3979
+ @group(0) @binding(1) var<storage, read> list: array<ABufferFragment>;
3980
+ @group(0) @binding(2) var<uniform> info: ABufferInfo;
3981
+
3982
+ const MAX_LAYERS = ${ABUFFER_MAX_SORTED_LAYERS}u;
3983
+
3984
+ @vertex fn vertexMain(@builtin(vertex_index) index: u32) -> @builtin(position) vec4f {
3985
+ // full-screen triangle
3986
+ let positions = array(vec2f(-1, -1), vec2f(3, -1), vec2f(-1, 3));
3987
+ return vec4f(positions[index], 0, 1);
3988
+ }
3989
+
3990
+ @fragment fn fragmentMain(@builtin(position) position: vec4f) -> @location(0) vec4f {
3991
+ let pixel = vec2u(position.xy);
3992
+ var layers: array<ABufferFragment, MAX_LAYERS>;
3993
+ var count = 0u;
3994
+ var index = heads.data[pixel.y * info.width + pixel.x];
3995
+ while (index != 0u && count < MAX_LAYERS) {
3996
+ layers[count] = list[index - 1u];
3997
+ index = layers[count].next;
3998
+ count++;
3999
+ }
4000
+ if (count == 0u) {
4001
+ discard;
4002
+ }
4003
+
4004
+ // insertion sort, farthest first
4005
+ for (var i = 1u; i < count; i++) {
4006
+ let item = layers[i];
4007
+ var j = i;
4008
+ while (j > 0u && layers[j - 1u].depth < item.depth) {
4009
+ layers[j] = layers[j - 1u];
4010
+ j--;
4011
+ }
4012
+ layers[j] = item;
4013
+ }
4014
+
4015
+ // back-to-front "over", premultiplied
4016
+ var result = vec4f(0);
4017
+ for (var i = 0u; i < count; i++) {
4018
+ let color = unpack4x8unorm(layers[i].color);
4019
+ result = vec4f(color.rgb * color.a, color.a) + result * (1.0 - color.a);
4020
+ }
4021
+ return result;
4022
+ }`;
4023
+ }
4024
+
4025
+ // packages/3d/dist/esm/adapters/webgpu/wgsl/basic-material-fragment.js
3893
4026
  var DefaultBasicMaterialFragmentOptions = {
3894
4027
  outputNormalLocation: VERTEX_OUTPUT_LOCATION_NORMAL,
3895
4028
  outputVertexLocation: VERTEX_OUTPUT_LOCATION_VERTEX,
@@ -3918,8 +4051,15 @@ function adaptWGSLModifierStringArray(array = []) {
3918
4051
  }
3919
4052
  function getBasicMaterialFragmentWgsl(extensions = {}, options = DefaultBasicMaterialFragmentOptions) {
3920
4053
  const opts = Utils14.extend({}, DefaultBasicMaterialFragmentOptions, options);
3921
- const definitions = adaptWGSLStringArray(extensions.definitions), bindings = adaptWGSLStringArray(extensions.bindings), modifiers = adaptWGSLModifierStringArray(extensions.modifiers);
4054
+ const aBuffer = opts.output === "a-buffer";
4055
+ const aBufferExtra = aBuffer ? aBufferFragmentExtra() : { definitions: [], bindings: [] };
4056
+ const allDefinitions = (extensions.definitions ?? []).concat(aBufferExtra.definitions), allBindings = (extensions.bindings ?? []).concat(aBufferExtra.bindings);
4057
+ const definitions = adaptWGSLStringArray(allDefinitions), bindings = adaptWGSLStringArray(allBindings), modifiers = adaptWGSLModifierStringArray(extensions.modifiers);
3922
4058
  const color = VERTEX_COLOR_REFERENCE, lighting = LIGHTING_COLOR_REFERENCE, ambient = AMBIENT_COLOR_REFERENCE;
4059
+ const shaded = `vec4f(${color}.rgb * ${lighting}.rgb + ${ambient}.rgb, ${color}.a)`;
4060
+ const sampleMaskInput = aBuffer ? "\n @builtin(sample_mask) sampleMask: u32, // MSAA coverage" : "";
4061
+ const returnType = aBuffer ? "" : " -> @location(0) vec4f";
4062
+ const output = aBuffer ? `aBufferInsert(position, sampleMask, ${shaded});` : `return ${shaded};`;
3923
4063
  return `// definitions
3924
4064
 
3925
4065
  ${definitions}
@@ -3938,8 +4078,8 @@ const white = vec4f(1,1,1,1);
3938
4078
  @location(${opts.outputUvLocation}) uv: vec2f,
3939
4079
  @location(${opts.outputVertexIndexLocation}) @interpolate(flat) index: u32, // vertex index,
3940
4080
  @location(${opts.outputRayIndexLocation}) ray: vec3f, // ray (eye-to-vertex) vector
3941
- @location(${opts.outputInstanceIndexLocation}) @interpolate(flat) instance : u32, // instance index
3942
- ) -> @location(0) vec4f {
4081
+ @location(${opts.outputInstanceIndexLocation}) @interpolate(flat) instance : u32, // instance index${sampleMaskInput}
4082
+ )${returnType} {
3943
4083
  var ${color} = diffuseColor;
3944
4084
  var ${ambient}: vec4f = empty;
3945
4085
  var ${lighting}: vec4f = empty;
@@ -3948,7 +4088,7 @@ const white = vec4f(1,1,1,1);
3948
4088
  ${modifiers}
3949
4089
 
3950
4090
  ${lighting} = select(white, ${lighting}, ${lighting}.a > 0);
3951
- return ${color} * ${lighting} + ${ambient};
4091
+ ${output}
3952
4092
  }`;
3953
4093
  }
3954
4094
 
@@ -4023,7 +4163,46 @@ var Materials = class {
4023
4163
  }
4024
4164
  throw new TypeError(`Material type '${material.shader}' not supported.`);
4025
4165
  }
4166
+ /**
4167
+ * Whether `material` renders (partially) see-through: visible, with an effective diffuse alpha (color alpha times
4168
+ * `opacity`) below `1`. Texture alpha isn't inspected.
4169
+ * @param material The scene material to test (`null`/`undefined` counts as opaque).
4170
+ */
4171
+ static isTranslucent(material) {
4172
+ if (Utils16.isNull(material)) {
4173
+ return false;
4174
+ }
4175
+ const visible = material.visible ?? true;
4176
+ if (!visible) {
4177
+ return false;
4178
+ }
4179
+ const color = diffuseColor(material);
4180
+ return color.a < 1;
4181
+ }
4026
4182
  };
4183
+ var WHITE = { r: 1, g: 1, b: 1, a: 1 };
4184
+ var TRANSPARENT = { r: 0, g: 0, b: 0, a: 0 };
4185
+ function parseColor(color) {
4186
+ if (typeof color === "string") {
4187
+ return Colors2.parse(color);
4188
+ }
4189
+ const source = color ?? WHITE;
4190
+ return Utils16.extend({}, source);
4191
+ }
4192
+ function diffuseColor(material) {
4193
+ const { opacity, color } = material;
4194
+ const visible = material.visible ?? true;
4195
+ if (!visible) {
4196
+ return Utils16.extend({}, TRANSPARENT);
4197
+ }
4198
+ const retval = parseColor(color);
4199
+ const validOpacity = opacity >= 0 && opacity <= 1;
4200
+ if (!validOpacity) {
4201
+ return retval;
4202
+ }
4203
+ const alpha = (retval.a ?? 1) * opacity;
4204
+ return Utils16.extend(retval, { a: alpha });
4205
+ }
4027
4206
  var EmptyMaterialWGSLDelegates = {
4028
4207
  // empty delegates
4029
4208
  };
@@ -4040,21 +4219,15 @@ var MaterialBase = class {
4040
4219
  get wgsl() {
4041
4220
  return EmptyMaterialWGSLDelegates;
4042
4221
  }
4043
- buffer({ device }, label = LABEL_PREFIX + "material-" + this.shader + "-buffer") {
4044
- const { r, g, b, a } = this._diffuseColor();
4045
- const materialValue = new Float32Array([r, g, b, a]);
4046
- return { buffer: Buffers.createStorage(device, materialValue, label), value: materialValue, version: performance.now() };
4222
+ buffer(ctx, key) {
4223
+ const materialValue = this.value(ctx, key);
4224
+ const label = LABEL_PREFIX + "material-" + this.shader + "-buffer";
4225
+ const buffer = Buffers.createStorage(ctx.device, materialValue, label);
4226
+ return { buffer, value: materialValue, version: performance.now() };
4047
4227
  }
4048
- _diffuseColor() {
4049
- const { visible, opacity, color } = this.material;
4050
- if (!(visible ?? true)) {
4051
- return { r: 0, g: 0, b: 0, a: 0 };
4052
- }
4053
- const retval = typeof color === "string" ? Colors2.parse(color) : color ?? { r: 1, g: 1, b: 1, a: 1 };
4054
- if (opacity >= 0 && opacity <= 1) {
4055
- return Utils16.extend(retval, { a: retval.a * opacity });
4056
- }
4057
- return retval;
4228
+ value(_, __) {
4229
+ const { r, g, b, a } = diffuseColor(this.material);
4230
+ return new Float32Array([r, g, b, a ?? 1]);
4058
4231
  }
4059
4232
  };
4060
4233
  var BasicMaterial = class extends MaterialBase {
@@ -4068,21 +4241,24 @@ var BasicMaterial = class extends MaterialBase {
4068
4241
  }
4069
4242
  }
4070
4243
  /**
4071
- * Allocates the (uninitialized) {@link GPUTexture} for the material's `texture`, if any.
4244
+ * Allocates the {@link GPUTexture} for the material's `texture`, if any, uploads the bitmap into it (once) and
4245
+ * creates its (stable) view.
4072
4246
  * @param key Must be `'texture'`; any other {@link MaterialKey} (or a material without a `texture`) yields `null`.
4073
4247
  */
4074
4248
  texture({ device }, key = "texture") {
4075
- const material = this.material;
4076
- if (key === "texture" && !Utils16.isNull(material.texture)) {
4077
- const texBmp = material.texture;
4078
- const texture = device.createTexture({
4079
- format: "rgba8unorm",
4080
- usage: GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_DST,
4081
- size: [texBmp.width, texBmp.height]
4082
- });
4083
- return { texture, source: texBmp };
4249
+ const texBmp = this.material.texture;
4250
+ if (key !== "texture" || Utils16.isNull(texBmp)) {
4251
+ return null;
4084
4252
  }
4085
- return null;
4253
+ const texture = device.createTexture({
4254
+ label: LABEL_PREFIX + "material-texture",
4255
+ format: "rgba8unorm",
4256
+ usage: GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_DST,
4257
+ size: [texBmp.width, texBmp.height]
4258
+ });
4259
+ device.queue.copyExternalImageToTexture({ source: texBmp, flipY: true }, { texture }, { width: texBmp.width, height: texBmp.height });
4260
+ const view2 = texture.createView({ label: LABEL_PREFIX + "material-texture-view" });
4261
+ return { texture, view: view2, source: texBmp };
4086
4262
  }
4087
4263
  static {
4088
4264
  this.fragment = getBasicMaterialFragmentWgsl;
@@ -4099,7 +4275,7 @@ var LineMaterial = class extends MaterialBase {
4099
4275
  }
4100
4276
  }
4101
4277
  /**
4102
- * Returns the `'line'` uniform buffer (canvas width/height and half line-width) for `key === 'line'`; otherwise
4278
+ * Returns the `'line'` uniform buffer (render-target width/height and half line-width) for `key === 'line'`; otherwise
4103
4279
  * defers to the inherited diffuse-color buffer.
4104
4280
  * @param ctx WebGPU context supplying the device and canvas.
4105
4281
  * @param key Which buffer to build; only `'line'` is handled specially.
@@ -4107,14 +4283,24 @@ var LineMaterial = class extends MaterialBase {
4107
4283
  buffer(ctx, key) {
4108
4284
  switch (key) {
4109
4285
  case "line":
4110
- const { device, canvas } = ctx;
4111
- const lineMaterial = this.material;
4112
- const lineValue = new Float32Array([canvas.clientWidth, canvas.clientHeight, lineMaterial.lineWidth / 2]);
4113
- return { buffer: Buffers.createUniform(device, lineValue, LABEL_PREFIX + "line-" + this.shader + "-buffer"), value: lineValue, version: performance.now() };
4286
+ const lineValue = this.value(ctx, key);
4287
+ const lineBuffer = Buffers.createUniform(ctx.device, lineValue, LABEL_PREFIX + "line-" + this.shader + "-buffer");
4288
+ return { buffer: lineBuffer, value: lineValue, version: performance.now() };
4114
4289
  default:
4115
4290
  return super.buffer(ctx);
4116
4291
  }
4117
4292
  }
4293
+ /** `'line'`: canvas width/height (in pixels, i.e. the render target size) and half line-width; otherwise the inherited diffuse color. */
4294
+ value(ctx, key) {
4295
+ switch (key) {
4296
+ case "line":
4297
+ const { canvas } = ctx;
4298
+ const lineMaterial = this.material;
4299
+ return new Float32Array([canvas.width, canvas.height, lineMaterial.lineWidth / 2]);
4300
+ default:
4301
+ return super.value(ctx);
4302
+ }
4303
+ }
4118
4304
  /** Lines have no texture support; always returns `null`. */
4119
4305
  texture(_) {
4120
4306
  return null;
@@ -4574,7 +4760,8 @@ function ambientLight(references, group, binding) {
4574
4760
  // bindings
4575
4761
  bindings: [`@group(${group}) @binding(${binding}) var<uniform> ${lightReference}: AmbientLight;`],
4576
4762
  // modifiers
4577
- modifiers: [`${outputColor} = computeAmbient(${inputColor}, ${lightReference});`]
4763
+ // accumulate: several ambient lights add up
4764
+ modifiers: [`${outputColor} += computeAmbient(${inputColor}, ${lightReference});`]
4578
4765
  };
4579
4766
  }
4580
4767
 
@@ -4706,12 +4893,23 @@ var PerspectiveCamera = class _PerspectiveCamera {
4706
4893
  // packages/3d/dist/esm/adapters/webgpu/renderablebuffer.js
4707
4894
  var Vector3D2 = Geometry7.LinearAlgebra.Vector3D;
4708
4895
  var Matrix3D2 = Geometry7.LinearAlgebra.Matrix3D;
4896
+ var EMPTY_FLAGS = Object.freeze([]);
4897
+ var currentFrame = 0;
4709
4898
  function throwBufferRequestError(key, type) {
4710
4899
  if (typeof type === "function") {
4711
4900
  type = type.name;
4712
4901
  }
4713
4902
  throw new RangeError(`Buffer '${key}' not available for ${type}.`);
4714
4903
  }
4904
+ function writeInPlace(device, buffer, value) {
4905
+ if (Utils23.isNull(buffer) || buffer.value.byteLength !== value.byteLength) {
4906
+ return null;
4907
+ }
4908
+ Buffers.write(device, buffer.buffer, value);
4909
+ buffer.value = value;
4910
+ buffer.version = performance.now();
4911
+ return buffer;
4912
+ }
4715
4913
  function createRenderableBuffer(item, parent, ...args) {
4716
4914
  item.stage ??= parent?.item.stage;
4717
4915
  if (isGroup(item)) {
@@ -4754,6 +4952,7 @@ var RenderLooper = class {
4754
4952
  * @param render Callback invoked once per mesh with its buffer, the (single) camera buffer and all light buffers; return `false` to skip that mesh (its flags are left untouched).
4755
4953
  */
4756
4954
  loop(render) {
4955
+ currentFrame++;
4757
4956
  const { meshes, cameras, groups, lights } = this._set;
4758
4957
  const camera = cameras[0];
4759
4958
  let cameraDone = false, lightsDone = false;
@@ -4805,7 +5004,7 @@ var RenderableBuffers = class _RenderableBuffers {
4805
5004
  * Wraps `item` in the {@link RenderableBuffer} implementation matching its kind (group/mesh/camera/light),
4806
5005
  * recursively wrapping a group's children.
4807
5006
  * @param item The scene renderable to wrap.
4808
- * @param args Extra constructor arguments forwarded to mesh buffers (the shared geometry/material {@link ManagedBuffer} caches; see `renderer.ts`).
5007
+ * @param args Extra constructor arguments forwarded down the tree: the shared geometry/material {@link ManagedBuffer} caches and the renderable-buffer store used to reuse group children (see `renderer.ts`).
4809
5008
  * @throws {Error} If `item`'s type isn't recognized.
4810
5009
  */
4811
5010
  static create(item, ...args) {
@@ -4818,7 +5017,7 @@ var RenderableBuffers = class _RenderableBuffers {
4818
5017
  * @param includeParent Whether to also clear the parent group buffer's flags, recursively up the hierarchy.
4819
5018
  */
4820
5019
  static clearFlags(buffer, includeParent = false) {
4821
- buffer.item.flags.splice(0);
5020
+ buffer.item.flags?.splice(0);
4822
5021
  if (includeParent) {
4823
5022
  const bufferBase = buffer;
4824
5023
  if (!Utils23.isNull(bufferBase.parent)) {
@@ -4861,9 +5060,9 @@ var ManagedBufferBase = class {
4861
5060
  #garbage = [];
4862
5061
  _destroyUnsafe(obj) {
4863
5062
  if ("texture" in obj) {
4864
- obj.texture.destroy();
5063
+ obj.texture?.destroy();
4865
5064
  } else if ("buffer" in obj) {
4866
- obj.buffer.destroy();
5065
+ obj.buffer?.destroy();
4867
5066
  }
4868
5067
  }
4869
5068
  destroySafely(...objects) {
@@ -4878,8 +5077,23 @@ var ManagedBufferBase = class {
4878
5077
  }
4879
5078
  }
4880
5079
  }
5080
+ #refs = 0;
5081
+ /** Registers one more consumer of this (shared) buffer. */
5082
+ retain() {
5083
+ this.#refs++;
5084
+ }
5085
+ /** Unregisters a consumer of this (shared) buffer, destroying it as soon as nobody uses it anymore. */
5086
+ release() {
5087
+ if (--this.#refs <= 0) {
5088
+ this.#refs = 0;
5089
+ this.destroy();
5090
+ }
5091
+ }
4881
5092
  #disposed = false;
4882
5093
  destroy() {
5094
+ if (this.#disposed) {
5095
+ return;
5096
+ }
4883
5097
  this.dispose();
4884
5098
  this.#disposed = true;
4885
5099
  }
@@ -4895,16 +5109,50 @@ var RenderableBufferBase = class extends ManagedBufferBase {
4895
5109
  }
4896
5110
  #u32id;
4897
5111
  #parent;
4898
- #u32idBuffer = /* @__PURE__ */ new Map();
5112
+ #u32idBuffer;
5113
+ #reparented = false;
4899
5114
  get parent() {
4900
5115
  return this.#parent;
4901
5116
  }
4902
5117
  get id() {
4903
5118
  return this.#u32id;
4904
5119
  }
5120
+ /** @internal Moves this buffer under a new parent group buffer (when a group gets rebuilt), forcing a world-transform refresh. */
5121
+ reparent(parent) {
5122
+ if (this.#parent === parent) {
5123
+ return;
5124
+ }
5125
+ this.#parent = parent;
5126
+ this.#reparented = true;
5127
+ }
5128
+ /** Returns (and resets) whether the buffer has been moved under a new parent since the last call. */
5129
+ consumeReparented() {
5130
+ const retval = this.#reparented;
5131
+ this.#reparented = false;
5132
+ return retval;
5133
+ }
5134
+ /** Whether this item or any of its ancestors carries stale flags. Allocation-free. */
5135
+ hasFlags() {
5136
+ if (this.item.flags?.length > 0) {
5137
+ return true;
5138
+ }
5139
+ const parent = this.parent;
5140
+ if (Utils23.isNull(parent)) {
5141
+ return false;
5142
+ }
5143
+ return parent.hasFlags();
5144
+ }
4905
5145
  allFlags() {
5146
+ if (!this.hasFlags()) {
5147
+ return EMPTY_FLAGS;
5148
+ }
5149
+ const ownFlags = this.item.flags ?? [];
4906
5150
  const parent = this.parent;
4907
- return this.item.flags.union(parent?.allFlags() ?? []);
5151
+ if (Utils23.isNull(parent)) {
5152
+ return ownFlags;
5153
+ }
5154
+ const parentFlags = parent.allFlags();
5155
+ return ownFlags.union(parentFlags);
4908
5156
  }
4909
5157
  buildParentWorldTransform() {
4910
5158
  let worldMatrix = Matrix3D2.identity();
@@ -4928,28 +5176,48 @@ var RenderableBufferBase = class extends ManagedBufferBase {
4928
5176
  }
4929
5177
  buffer(context, key) {
4930
5178
  if (key === "u32id") {
4931
- const u32idBuffer = this.#u32idBuffer;
4932
- const { pipeline, device } = context;
4933
- if (u32idBuffer.has(pipeline)) {
4934
- return Utils23.extend({ fresh: false }, u32idBuffer.get(pipeline));
4935
- }
4936
- const u32idBufferValue = new Uint32Array([this.id]);
4937
- const u32idBufferBuffer = Buffers.createUniform(device, u32idBufferValue, LABEL_PREFIX + "u32id-buffer");
4938
- const retval2 = Utils23.extend({ buffer: u32idBufferBuffer, value: u32idBufferValue, version: performance.now() }, { fresh: true });
4939
- this.#u32idBuffer.set(pipeline, retval2);
4940
- return retval2;
5179
+ return this._ensureU32idBuffer(context);
4941
5180
  }
4942
5181
  const retval = this.specificBuffer(context, key);
4943
- this.#versions.set(key, retval.version);
5182
+ this.#versions.set(key, retval?.version ?? 0);
4944
5183
  return retval;
4945
5184
  }
5185
+ /** One id buffer per renderable, shared by every (color-picking) pipeline. */
5186
+ _ensureU32idBuffer({ device }) {
5187
+ if (!Utils23.isNull(this.#u32idBuffer)) {
5188
+ return this.#u32idBuffer;
5189
+ }
5190
+ const value = new Uint32Array([this.id]);
5191
+ const buffer = Buffers.createUniform(device, value, LABEL_PREFIX + "u32id-buffer");
5192
+ this.#u32idBuffer = { buffer, value, version: performance.now() };
5193
+ return this.#u32idBuffer;
5194
+ }
5195
+ destroy() {
5196
+ if (this.disposed) {
5197
+ return;
5198
+ }
5199
+ const u32id = this.#u32idBuffer;
5200
+ this.#u32idBuffer = null;
5201
+ this.destroySafely(u32id);
5202
+ super.destroy();
5203
+ }
4946
5204
  };
4947
5205
  var DefaultMaterial = { shader: KnownShader.Basic, color: "#c0c0c0", flags: [] };
4948
5206
  var RenderableGroupBuffer = class extends RenderableBufferBase {
4949
5207
  #children;
4950
5208
  constructor(group, parent, ...args) {
4951
5209
  super(group, parent);
4952
- this.#children = group.childRenderables.map((i) => createRenderableBuffer(i, this, ...args));
5210
+ const store = args[2];
5211
+ this.#children = group.childRenderables.map((i) => {
5212
+ const existing = store?.get(i);
5213
+ if (!Utils23.isNull(existing) && !existing.disposed && existing.parent?.item === group) {
5214
+ existing.reparent(this);
5215
+ return existing;
5216
+ }
5217
+ const created = createRenderableBuffer(i, this, ...args);
5218
+ store?.set(i, created);
5219
+ return created;
5220
+ });
4953
5221
  }
4954
5222
  get children() {
4955
5223
  return this.#children;
@@ -4961,12 +5229,13 @@ var RenderableGroupBuffer = class extends RenderableBufferBase {
4961
5229
  throw new Error("Method not implemented.");
4962
5230
  }
4963
5231
  dispose() {
4964
- this.#children.forEach((i) => i.destroy());
5232
+ const ownChildren = this.#children.filter((i) => i.parent === this);
5233
+ ownChildren.forEach((i) => i.destroy());
4965
5234
  }
4966
5235
  };
4967
5236
  var RenderableCameraBuffer = class _RenderableCameraBuffer extends RenderableBufferBase {
4968
- #viewBag = /* @__PURE__ */ new Map();
4969
5237
  #view;
5238
+ #size = { width: 0, height: 0 };
4970
5239
  constructor(camera) {
4971
5240
  super(camera);
4972
5241
  }
@@ -4974,25 +5243,25 @@ var RenderableCameraBuffer = class _RenderableCameraBuffer extends RenderableBuf
4974
5243
  throw new Error("Method not implemented.");
4975
5244
  }
4976
5245
  specificBuffer(context, key) {
4977
- let fresh = false;
4978
- if (this.allFlags().length > 0 || Utils23.isNull(this.#view)) {
4979
- fresh = true;
4980
- this.#viewBag.clear();
5246
+ if (this._isStale(context.canvas)) {
4981
5247
  this._rebuildMatrices(context);
4982
5248
  }
4983
- const { pipeline } = context;
4984
- if (!this.#viewBag.has(pipeline)) {
4985
- fresh = true;
4986
- this.#viewBag.set(pipeline, this.#view);
4987
- }
4988
5249
  RenderableBuffers.clearFlags(this);
4989
5250
  switch (key) {
4990
5251
  case "cameraViewTransform":
4991
- return Utils23.extend(this.#view, { fresh });
5252
+ return this.#view;
4992
5253
  default:
4993
5254
  throwBufferRequestError(key, _RenderableCameraBuffer);
4994
5255
  }
4995
5256
  }
5257
+ /** Whether the matrices need a rebuild: stale flags, first use, or a different render target size (the projection depends on it). */
5258
+ _isStale(canvas) {
5259
+ if (Utils23.isNull(this.#view) || this.hasFlags()) {
5260
+ return true;
5261
+ }
5262
+ const size = this.#size;
5263
+ return size.width !== canvas.width || size.height !== canvas.height;
5264
+ }
4996
5265
  _rebuildMatrices({ device, canvas }) {
4997
5266
  const cam = this.item;
4998
5267
  const camera = Cameras.create(cam);
@@ -5000,141 +5269,135 @@ var RenderableCameraBuffer = class _RenderableCameraBuffer extends RenderableBuf
5000
5269
  const view2 = camera.view();
5001
5270
  const projection = camera.projection(canvas);
5002
5271
  const viewProjection = Matrix3D2.multiply(view2, projection);
5272
+ const viewArray = Matrix3D2.toArray(view2);
5273
+ const viewProjectionArray = Matrix3D2.toArray(viewProjection);
5003
5274
  const viewValue = new Float32Array(16 + 16 + 4);
5004
- viewValue.set(Matrix3D2.toArray(view2), 0);
5005
- viewValue.set(Matrix3D2.toArray(viewProjection), 16);
5275
+ viewValue.set(viewArray, 0);
5276
+ viewValue.set(viewProjectionArray, 16);
5006
5277
  viewValue.set([x, y, z], 32);
5007
- if (Utils23.isNull(this.#view)) {
5008
- const viewBuffer = Buffers.createUniform(device, viewValue, LABEL_PREFIX + "view-buffer");
5009
- this.#view = { buffer: viewBuffer, value: viewValue, version: performance.now().roundoff() };
5010
- } else {
5011
- this.#view.value = viewValue;
5012
- this.#view.version = performance.now().roundoff();
5278
+ this.#size = { width: canvas.width, height: canvas.height };
5279
+ const written = writeInPlace(device, this.#view, viewValue);
5280
+ if (!Utils23.isNull(written)) {
5281
+ return;
5013
5282
  }
5283
+ const viewBuffer = Buffers.createUniform(device, viewValue, LABEL_PREFIX + "view-buffer");
5284
+ const version = performance.now().roundoff();
5285
+ this.#view = { buffer: viewBuffer, value: viewValue, version };
5014
5286
  }
5015
- _destroyView() {
5016
- this.#viewBag.clear();
5287
+ dispose() {
5017
5288
  const view2 = this.#view;
5018
5289
  this.#view = null;
5019
5290
  this.destroySafely(view2);
5020
5291
  }
5021
- dispose() {
5022
- this._destroyView();
5023
- }
5024
5292
  };
5025
5293
  var GeometryBuffer = class _GeometryBuffer extends ManagedBufferBase {
5026
- #bufferBag = {};
5027
- #freshness = { positions: true, normals: true, uv: true, packed: true };
5028
- #geometryBuffers;
5294
+ #buffers = /* @__PURE__ */ new Map();
5295
+ #flat;
5029
5296
  constructor(geometry) {
5030
5297
  super(geometry);
5031
5298
  geometry.flags ??= [];
5032
5299
  }
5033
5300
  buffer(context, key) {
5034
- const flags = this.item.flags ?? [];
5035
- if (Utils23.isNull(this.#geometryBuffers) || flags.includes(StalePropertyFlag.Geometry)) {
5036
- flags.splice(0);
5037
- this.#bufferBag = /* reset */
5038
- {};
5039
- this._rebuildGeometryBuffers(context);
5040
- }
5041
- const freshness = this.#freshness;
5042
- const geom = this.#geometryBuffers;
5043
- const { pipeline } = context;
5044
- const bag = this.#bufferBag[key] ??= /* @__PURE__ */ new Map();
5045
- const newInPipeline = !bag.has(pipeline);
5046
- const ensureInBag = (buffer) => {
5047
- if (newInPipeline) {
5048
- bag.set(pipeline, buffer);
5049
- }
5050
- return buffer;
5051
- };
5052
5301
  switch (key) {
5053
5302
  case "geometryPositions":
5054
- const { positions } = geom, posFresh = freshness.positions;
5055
- freshness.positions = false;
5056
- return Utils23.extend(ensureInBag(positions), { fresh: posFresh || newInPipeline });
5057
5303
  case "geometryNormals":
5058
- const { normals } = geom, normFresh = freshness.normals;
5059
- freshness.normals = false;
5060
- return Utils23.extend(ensureInBag(normals), { fresh: normFresh || newInPipeline });
5061
5304
  case "geometryTexCoords":
5062
- const { uv } = geom, uvFresh = freshness.uv;
5063
- freshness.uv = false;
5064
- return Utils23.extend({ fresh: uvFresh || newInPipeline }, ensureInBag(uv));
5065
5305
  case "geometry":
5066
- const { packed } = geom, geomFresh = freshness.packed;
5067
- freshness.packed = false;
5068
- return Utils23.extend(ensureInBag(packed), { fresh: geomFresh || newInPipeline });
5306
+ break;
5069
5307
  default:
5070
5308
  throwBufferRequestError(key, _GeometryBuffer);
5071
5309
  }
5310
+ const flags = this.item.flags ?? [];
5311
+ if (flags.includes(StalePropertyFlag.Geometry)) {
5312
+ flags.splice(0);
5313
+ this._destroyBuffers();
5314
+ }
5315
+ const normalizedKey = isMeshGeometry(this.item) ? key : "geometryPositions";
5316
+ const buffers = this.#buffers;
5317
+ const existing = buffers.get(normalizedKey);
5318
+ if (!Utils23.isNull(existing)) {
5319
+ return existing;
5320
+ }
5321
+ const created = this._createBuffer(context, normalizedKey);
5322
+ buffers.set(normalizedKey, created);
5323
+ return created;
5072
5324
  }
5073
5325
  texture(_) {
5074
5326
  throw new Error("Method not implemented.");
5075
5327
  }
5076
- _rebuildGeometryBuffers({ device }) {
5077
- this._destroyBuffers();
5328
+ _flatten(geometry) {
5329
+ const hasTriangleIndices = !Utils23.isNullOrEmpty(geometry.triangleIndices);
5330
+ const positions = hasTriangleIndices ? geometry.triangleIndices.map((index) => geometry.positions[index]) : geometry.positions;
5331
+ return { positions, normals: geometry.normals, uvs: geometry.textureCoordinates };
5332
+ }
5333
+ _createBuffer({ device }, key) {
5078
5334
  const version = performance.now();
5079
- const geometry = this.item, key = geometry.key;
5080
- if (isMeshGeometry(geometry)) {
5081
- const meshGeometry = geometry;
5082
- const hasTriangleIndices = !Utils23.isNullOrEmpty(meshGeometry.triangleIndices);
5083
- const flatPositions = hasTriangleIndices ? meshGeometry.triangleIndices.map((index) => meshGeometry.positions[index]) : meshGeometry.positions;
5084
- const length2 = flatPositions.length * 2, length3 = length2 + flatPositions.length;
5085
- const positionsValue = new Float32Array(length3);
5086
- const normalsValue = new Float32Array(length3);
5087
- const uvValue = new Float32Array(length2);
5088
- const geomValue = new Float32Array(2 * length3 + length2);
5089
- for (let j = 0; j < flatPositions.length; j++) {
5090
- const offset2 = 2 * j;
5091
- const offset3 = 3 * j;
5092
- const { x, y, z } = flatPositions[j];
5093
- const { x: nx, y: ny, z: nz } = meshGeometry.normals[j];
5094
- const { x: u, y: v } = meshGeometry.textureCoordinates[j];
5095
- positionsValue.set([x, y, z], offset3);
5096
- normalsValue.set([nx, ny, nz], offset3);
5097
- uvValue.set([u, v], offset2);
5098
- geomValue.set([x, y, z, nx, ny, nz, u, v], offset3 * 2 + offset2);
5099
- }
5100
- const positions = Buffers.create(device, positionsValue, LABEL_PREFIX + "meshgeometry-" + key + "-positions-buffer");
5101
- const normals = Buffers.create(device, normalsValue, LABEL_PREFIX + "meshgeometry-" + key + "-normals-buffer");
5102
- const uv = Buffers.create(device, uvValue, LABEL_PREFIX + "meshgeometry-" + key + "-uvmap-buffer");
5103
- const geom = Buffers.create(device, geomValue, LABEL_PREFIX + "meshgeometry-" + key + "-buffer");
5104
- this.#geometryBuffers = {
5105
- packed: { buffer: geom, value: geomValue, version },
5106
- positions: { buffer: positions, value: positionsValue, version },
5107
- normals: { buffer: normals, value: normalsValue, version },
5108
- uv: { buffer: uv, value: uvValue, version }
5109
- };
5110
- this.#freshness = { positions: true, normals: true, uv: true, packed: true };
5111
- } else {
5112
- const positionsValue = new Float32Array(AdapterUtils.flattenVectorArray(geometry.positions));
5113
- const positions = Buffers.createStorage(device, positionsValue, LABEL_PREFIX + "nodegeometry-" + key + "-positions-buffer");
5114
- this.#geometryBuffers = {
5115
- positions: { buffer: positions, value: positionsValue, version },
5116
- packed: { buffer: positions, value: positionsValue, version }
5117
- };
5118
- this.#freshness = { positions: true, packed: true };
5335
+ const geometry = this.item, geometryKey = geometry.key;
5336
+ if (!isMeshGeometry(geometry)) {
5337
+ const flatPositions = AdapterUtils.flattenVectorArray(geometry.positions);
5338
+ const positionsValue = new Float32Array(flatPositions);
5339
+ const positions2 = Buffers.createStorage(device, positionsValue, LABEL_PREFIX + "nodegeometry-" + geometryKey + "-positions-buffer");
5340
+ return { buffer: positions2, value: positionsValue, version };
5341
+ }
5342
+ this.#flat ??= this._flatten(geometry);
5343
+ const { positions, normals, uvs } = this.#flat;
5344
+ const count = positions.length;
5345
+ let value, label;
5346
+ switch (key) {
5347
+ case "geometryPositions":
5348
+ value = new Float32Array(3 * count);
5349
+ for (let j = 0; j < count; j++) {
5350
+ const { x, y, z } = positions[j];
5351
+ value.set([x, y, z], 3 * j);
5352
+ }
5353
+ label = "-positions-buffer";
5354
+ break;
5355
+ case "geometryNormals":
5356
+ value = new Float32Array(3 * count);
5357
+ for (let j = 0; j < count; j++) {
5358
+ const { x, y, z } = normals[j];
5359
+ value.set([x, y, z], 3 * j);
5360
+ }
5361
+ label = "-normals-buffer";
5362
+ break;
5363
+ case "geometryTexCoords":
5364
+ value = new Float32Array(2 * count);
5365
+ for (let j = 0; j < count; j++) {
5366
+ const { x, y } = uvs[j];
5367
+ value.set([x, y], 2 * j);
5368
+ }
5369
+ label = "-uvmap-buffer";
5370
+ break;
5371
+ default:
5372
+ value = new Float32Array(8 * count);
5373
+ for (let j = 0; j < count; j++) {
5374
+ const { x, y, z } = positions[j];
5375
+ const { x: nx, y: ny, z: nz } = normals[j];
5376
+ const { x: u, y: v } = uvs[j];
5377
+ value.set([x, y, z, nx, ny, nz, u, v], 8 * j);
5378
+ }
5379
+ label = "-buffer";
5380
+ break;
5119
5381
  }
5382
+ const buffer = Buffers.create(device, value, LABEL_PREFIX + "meshgeometry-" + geometryKey + label);
5383
+ return { buffer, value, version };
5120
5384
  }
5121
5385
  _destroyBuffers() {
5122
- this.#bufferBag = {};
5123
- const obsolete = this.#geometryBuffers;
5124
- if (!Utils23.isNull(obsolete)) {
5125
- this.destroySafely(obsolete.positions, obsolete.normals, obsolete.uv);
5126
- }
5386
+ const values = this.#buffers.values();
5387
+ const obsolete = Array.from(values);
5388
+ this.#buffers.clear();
5389
+ this.#flat = null;
5390
+ this.destroySafely(...obsolete);
5127
5391
  }
5128
5392
  dispose() {
5129
5393
  this._destroyBuffers();
5130
5394
  }
5131
5395
  };
5132
5396
  var MaterialBuffer = class _MaterialBuffer extends ManagedBufferBase {
5133
- #bufferBag = {};
5134
- #textureBag = {};
5135
5397
  #wgpuMaterial;
5136
5398
  #buffers = /* @__PURE__ */ new Map();
5137
5399
  #textures = /* @__PURE__ */ new Map();
5400
+ #lineSize = { width: 0, height: 0 };
5138
5401
  constructor(material) {
5139
5402
  super(material);
5140
5403
  material.flags ??= [];
@@ -5142,87 +5405,98 @@ var MaterialBuffer = class _MaterialBuffer extends ManagedBufferBase {
5142
5405
  material.flags.push(StalePropertyFlag.Material);
5143
5406
  }
5144
5407
  }
5145
- buffer(context, key) {
5408
+ _ensureUpToDate(context) {
5146
5409
  const flags = this.item.flags ?? [];
5147
- let fresh = Utils23.isNull(this.#wgpuMaterial);
5148
- if (flags.includes(StalePropertyFlag.Material)) {
5149
- this.#bufferBag = /* reset */
5150
- {};
5410
+ const stale = flags.includes(StalePropertyFlag.Material);
5411
+ if (!stale && !Utils23.isNull(this.#wgpuMaterial)) {
5412
+ return;
5413
+ }
5414
+ if (stale) {
5151
5415
  flags.splice(0);
5152
- fresh = true;
5153
- this.#textures.clear();
5154
- this._resetMaterialBuffers();
5155
5416
  }
5156
- const { pipeline } = context;
5157
- const bag = this.#bufferBag[key] ??= /* @__PURE__ */ new Map();
5417
+ const material = Materials.create(this.item);
5418
+ this.#wgpuMaterial = material;
5419
+ this._rewriteBuffers(context, material);
5420
+ this._destroyTextures();
5421
+ }
5422
+ /** Rewrites the existing buffers in place (or drops them, to be recreated, should their size change). */
5423
+ _rewriteBuffers(context, material) {
5424
+ const buffers = this.#buffers;
5425
+ for (let [key, buffer] of buffers) {
5426
+ const value = material.value(context, key);
5427
+ const written = writeInPlace(context.device, buffer, value);
5428
+ if (!Utils23.isNull(written)) {
5429
+ continue;
5430
+ }
5431
+ buffers.delete(key);
5432
+ this.destroySafely(buffer);
5433
+ }
5434
+ }
5435
+ buffer(context, key) {
5436
+ this._ensureUpToDate(context);
5158
5437
  switch (key) {
5159
5438
  case "material":
5160
5439
  case "line":
5161
- const buffer = this._ensureMaterialBuffer(context, key);
5162
- if (buffer) {
5163
- if (!bag.has(pipeline)) {
5164
- fresh = true;
5165
- bag.set(pipeline, buffer);
5166
- }
5167
- return Utils23.extend(buffer, { fresh });
5168
- }
5169
- return null;
5440
+ return this._ensureMaterialBuffer(context, key);
5170
5441
  default:
5171
5442
  throwBufferRequestError(key, _MaterialBuffer);
5172
5443
  }
5173
5444
  }
5174
- _ensureMaterialBuffer(ctx, key = "material") {
5175
- const set = this.#buffers;
5176
- let retval = set.get(key);
5177
- if (retval) {
5178
- return retval;
5445
+ _ensureMaterialBuffer(ctx, key) {
5446
+ const existing = this.#buffers.get(key);
5447
+ if (Utils23.isNull(existing)) {
5448
+ return this._createMaterialBuffer(ctx, key);
5179
5449
  }
5180
- if (set.has(key)) {
5450
+ if (key === "line") {
5451
+ this._refreshLineSize(ctx, existing);
5452
+ }
5453
+ return existing;
5454
+ }
5455
+ _createMaterialBuffer(ctx, key) {
5456
+ const created = this.#wgpuMaterial.buffer(ctx, key);
5457
+ if (Utils23.isNull(created)) {
5181
5458
  return null;
5182
5459
  }
5183
- retval = this.#wgpuMaterial?.buffer(ctx, key);
5184
- if (retval) {
5185
- set.set(key, retval);
5460
+ this.#buffers.set(key, created);
5461
+ if (key === "line") {
5462
+ const { canvas } = ctx;
5463
+ this.#lineSize = { width: canvas.width, height: canvas.height };
5186
5464
  }
5187
- return retval;
5465
+ return created;
5188
5466
  }
5189
- _resetMaterialBuffers() {
5190
- this.#wgpuMaterial = Materials.create(this.item);
5191
- this._destroyBuffers();
5467
+ /** Line params carry the render target size: rewrites them when it changes. */
5468
+ _refreshLineSize(ctx, buffer) {
5469
+ const { canvas } = ctx, size = this.#lineSize;
5470
+ if (size.width === canvas.width && size.height === canvas.height) {
5471
+ return;
5472
+ }
5473
+ this.#lineSize = { width: canvas.width, height: canvas.height };
5474
+ const value = this.#wgpuMaterial.value(ctx, "line");
5475
+ writeInPlace(ctx.device, buffer, value);
5192
5476
  }
5193
5477
  texture(ctx, key = "texture") {
5478
+ this._ensureUpToDate(ctx);
5194
5479
  const set = this.#textures;
5195
- let retval = set.get(key), fresh = false;
5196
- if (!retval) {
5197
- retval = this.#wgpuMaterial?.texture(ctx, key);
5198
- if (!retval) {
5199
- return null;
5200
- }
5201
- set.set(key, retval);
5202
- fresh = true;
5203
- this.#textureBag = /* reset */
5204
- {};
5205
- }
5206
- const { pipeline } = ctx;
5207
- const bag = this.#textureBag[key] ??= /* @__PURE__ */ new Map();
5208
- if (!bag.has(pipeline)) {
5209
- fresh = true;
5210
- bag.set(pipeline, retval);
5480
+ if (set.has(key)) {
5481
+ return set.get(key);
5211
5482
  }
5212
- return Utils23.extend(retval, { fresh });
5483
+ const created = this.#wgpuMaterial.texture(ctx, key) ?? null;
5484
+ set.set(key, created);
5485
+ return created;
5213
5486
  }
5214
- dispose() {
5215
- this._destroyBuffers();
5487
+ _destroyTextures() {
5488
+ const values = this.#textures.values();
5489
+ const textures = Array.from(values);
5490
+ this.#textures.clear();
5491
+ const existing = textures.filter((t) => !Utils23.isNull(t));
5492
+ this.destroySafely(...existing);
5216
5493
  }
5217
- _destroyBuffers() {
5218
- this.#bufferBag = {};
5219
- this.#textureBag = {};
5220
- const buffers = this.#buffers.values();
5494
+ dispose() {
5495
+ const values = this.#buffers.values();
5496
+ const buffers = Array.from(values);
5221
5497
  this.#buffers.clear();
5222
5498
  this.destroySafely(...buffers);
5223
- const textures = this.#textures.values();
5224
- this.#textures.clear();
5225
- textures.forEach((t) => t.texture.destroy());
5499
+ this._destroyTextures();
5226
5500
  }
5227
5501
  };
5228
5502
  var InteractionBuffer = class _InteractionBuffer extends ManagedBufferBase {
@@ -5232,10 +5506,8 @@ var InteractionBuffer = class _InteractionBuffer extends ManagedBufferBase {
5232
5506
  resolution: { width: 0, height: 0 }
5233
5507
  };
5234
5508
  #buffer;
5235
- #bufferBag = /* @__PURE__ */ new Map();
5236
5509
  constructor(data) {
5237
5510
  super(data);
5238
- Utils23.extend(this.#fields, data);
5239
5511
  }
5240
5512
  buffer(context, key) {
5241
5513
  switch (key) {
@@ -5249,43 +5521,49 @@ var InteractionBuffer = class _InteractionBuffer extends ManagedBufferBase {
5249
5521
  texture(_) {
5250
5522
  throw new Error("Method not implemented.");
5251
5523
  }
5252
- _ensureInteractionBuffer(ctx, key = "interaction") {
5524
+ /** Whether the interaction data differs from what was last uploaded. Allocation-free (called per mesh, per frame). */
5525
+ _hasChanged() {
5526
+ if (Utils23.isNull(this.#buffer)) {
5527
+ return true;
5528
+ }
5253
5529
  const fields = this.#fields, item = this.item;
5254
- let fresh = !this.#buffer || item.time !== fields.time || item.resolution?.width !== fields.resolution.width || item.resolution?.height !== fields.resolution.height;
5255
- if (!fresh && !Utils23.isNull(item.cursor)) {
5256
- fresh = item.cursor.x !== fields.cursor.x || item.cursor.y !== fields.cursor.y;
5257
- }
5258
- if (fresh) {
5259
- const value = new Float32Array([
5260
- item.cursor?.x ?? 0,
5261
- item.cursor?.y ?? 0,
5262
- item.resolution.width,
5263
- item.resolution.height,
5264
- item.time,
5265
- /* padding */
5266
- 0
5267
- ]);
5268
- const buffer = Buffers.createUniform(ctx.device, value, LABEL_PREFIX + "interaction-buffer");
5269
- this.#buffer = { buffer, value, version: performance.now() };
5270
- this.#bufferBag.clear();
5530
+ if (item.time !== fields.time) {
5531
+ return true;
5271
5532
  }
5272
- const { pipeline } = ctx;
5273
- const bag = this.#bufferBag;
5274
- if (!bag.has(pipeline)) {
5275
- fresh = true;
5276
- bag.set(pipeline, this.#buffer);
5533
+ if (item.resolution?.width !== fields.resolution.width || item.resolution?.height !== fields.resolution.height) {
5534
+ return true;
5277
5535
  }
5278
- return Utils23.extend(this.#buffer, { fresh });
5536
+ const cursorX = item.cursor?.x ?? 0, cursorY = item.cursor?.y ?? 0;
5537
+ return cursorX !== fields.cursor.x || cursorY !== fields.cursor.y;
5279
5538
  }
5280
- _destroyBuffers() {
5281
- this.#bufferBag.clear();
5282
- const obsolete = this.#buffer;
5283
- if (!Utils23.isNull(obsolete)) {
5284
- this.destroySafely(obsolete);
5539
+ _ensureInteractionBuffer({ device }) {
5540
+ if (!this._hasChanged()) {
5541
+ return this.#buffer;
5542
+ }
5543
+ const item = this.item;
5544
+ const cursor = { x: item.cursor?.x ?? 0, y: item.cursor?.y ?? 0 }, resolution = { width: item.resolution?.width ?? 0, height: item.resolution?.height ?? 0 };
5545
+ const value = new Float32Array([
5546
+ cursor.x,
5547
+ cursor.y,
5548
+ resolution.width,
5549
+ resolution.height,
5550
+ item.time,
5551
+ /* padding */
5552
+ 0
5553
+ ]);
5554
+ this.#fields = { time: item.time, cursor, resolution };
5555
+ const written = writeInPlace(device, this.#buffer, value);
5556
+ if (!Utils23.isNull(written)) {
5557
+ return written;
5285
5558
  }
5559
+ const buffer = Buffers.createUniform(device, value, LABEL_PREFIX + "interaction-buffer");
5560
+ this.#buffer = { buffer, value, version: performance.now() };
5561
+ return this.#buffer;
5286
5562
  }
5287
5563
  dispose() {
5288
- this._destroyBuffers();
5564
+ const obsolete = this.#buffer;
5565
+ this.#buffer = null;
5566
+ this.destroySafely(obsolete);
5289
5567
  }
5290
5568
  };
5291
5569
  var RenderableMeshBuffer = class _RenderableMeshBuffer extends RenderableBufferBase {
@@ -5294,162 +5572,162 @@ var RenderableMeshBuffer = class _RenderableMeshBuffer extends RenderableBufferB
5294
5572
  #materialBuffers;
5295
5573
  #materialBuffer;
5296
5574
  #worldTransform;
5297
- #freshness = {
5298
- geometry: true,
5299
- material: true,
5300
- transform: true
5301
- };
5302
- #worldTransformBufferBag = /* @__PURE__ */ new Map();
5303
- constructor(mesh, parent, geometries, materials) {
5575
+ #evaluatedAt = -1;
5576
+ constructor(mesh, parent, ...[geometries, materials]) {
5304
5577
  super(mesh, parent);
5305
5578
  mesh.flags ??= [];
5306
- if (mesh.flags.indexOf(StalePropertyFlag.Geometry) === -1) {
5307
- mesh.flags.push(StalePropertyFlag.Geometry);
5308
- }
5309
- if (mesh.flags.indexOf(StalePropertyFlag.Material) === -1) {
5310
- mesh.flags.push(StalePropertyFlag.Material);
5311
- }
5312
- if (mesh.flags.indexOf(StalePropertyFlag.Position) === -1 && mesh.flags.indexOf(StalePropertyFlag.Transform) === -1) {
5313
- mesh.flags.push(StalePropertyFlag.Transform);
5314
- }
5315
5579
  this.#geometryBuffers = geometries;
5316
5580
  this.#materialBuffers = materials;
5317
5581
  }
5318
5582
  texture(ctx, key) {
5319
- const material = this.#materialBuffer;
5320
- return material?.texture(ctx, key);
5583
+ this._refresh(ctx);
5584
+ return this.#materialBuffer?.texture(ctx, key);
5321
5585
  }
5322
- specificBuffer(context, key) {
5323
- const freshness = this.#freshness;
5586
+ /**
5587
+ * Brings transform, geometry and material up to date with the stale flags (own and inherited). Inherited flags
5588
+ * (stale ancestor groups, sealed by the looper only at the end of the pass) are evaluated once per pass.
5589
+ */
5590
+ _refresh(context) {
5591
+ const reparented = this.consumeReparented();
5592
+ if (!reparented && this._isUpToDate()) {
5593
+ return;
5594
+ }
5324
5595
  const flags = this.allFlags();
5325
- if (Utils23.isNull(this.#worldTransform) || flags.includes(StalePropertyFlag.Position) || flags.includes(StalePropertyFlag.Transform)) {
5326
- this.#worldTransformBufferBag.clear();
5327
- freshness.transform = true;
5596
+ const transformStale = flags.includes(StalePropertyFlag.Position) || flags.includes(StalePropertyFlag.Transform);
5597
+ if (Utils23.isNull(this.#worldTransform) || reparented || transformStale) {
5328
5598
  this._rebuildWorldMatrices(context);
5329
5599
  }
5330
5600
  if (Utils23.isNull(this.#geometryBuffer) || flags.includes(StalePropertyFlag.Geometry)) {
5331
- freshness.geometry = true;
5332
5601
  this._ensureGeometryBuffer();
5333
5602
  }
5334
5603
  if (Utils23.isNull(this.#materialBuffer) || flags.includes(StalePropertyFlag.Material)) {
5335
- freshness.material = true;
5336
5604
  this._ensureMaterialBuffer();
5337
5605
  }
5606
+ this.#evaluatedAt = currentFrame;
5338
5607
  RenderableBuffers.clearFlags(this);
5339
- const geom = this.#geometryBuffer;
5340
- const mater = this.#materialBuffer;
5608
+ }
5609
+ /** Whether nothing needs a refresh: resources in place, no own stale flags, and inherited ones already evaluated in this pass (or absent). */
5610
+ _isUpToDate() {
5611
+ const ready = !Utils23.isNull(this.#worldTransform) && !Utils23.isNull(this.#geometryBuffer) && !Utils23.isNull(this.#materialBuffer);
5612
+ if (!ready) {
5613
+ return false;
5614
+ }
5615
+ if (this.item.flags?.length > 0) {
5616
+ return false;
5617
+ }
5618
+ if (this.#evaluatedAt === currentFrame) {
5619
+ return true;
5620
+ }
5621
+ const parent = this.parent;
5622
+ if (Utils23.isNull(parent)) {
5623
+ return true;
5624
+ }
5625
+ return !parent.hasFlags();
5626
+ }
5627
+ specificBuffer(context, key) {
5628
+ this._refresh(context);
5341
5629
  switch (key) {
5342
5630
  case "geometryPositions":
5343
5631
  case "geometryNormals":
5344
5632
  case "geometryTexCoords":
5345
5633
  case "geometry":
5346
- return geom.buffer(context, key);
5634
+ return this.#geometryBuffer.buffer(context, key);
5347
5635
  case "material":
5348
5636
  case "line":
5349
- return mater.buffer(context, key);
5637
+ return this.#materialBuffer.buffer(context, key);
5350
5638
  case "objectWorldTransform":
5351
- const mat = this.#worldTransform, wFresh = freshness.transform;
5352
- freshness.transform = false;
5353
- const bag = this.#worldTransformBufferBag, { pipeline } = context;
5354
- const newInPipeline = !bag.has(pipeline);
5355
- if (newInPipeline) {
5356
- bag.set(pipeline, mat);
5357
- }
5358
- return Utils23.extend(mat, { fresh: wFresh || newInPipeline });
5639
+ return this.#worldTransform;
5359
5640
  default:
5360
5641
  throwBufferRequestError(key, _RenderableMeshBuffer);
5361
5642
  }
5362
5643
  }
5363
5644
  _ensureGeometryBuffer() {
5364
5645
  const current = this.#geometryBuffer;
5646
+ const geom = this.item.geometry;
5647
+ if (current?.item === geom && !current.disposed) {
5648
+ return;
5649
+ }
5365
5650
  const cache = this.#geometryBuffers;
5366
- const mesh = this.item;
5367
- const geom = mesh.geometry;
5368
- if (Utils23.isNull(cache)) {
5369
- current?.destroy();
5370
- this.#geometryBuffer = new GeometryBuffer(geom);
5371
- } else {
5372
- let buffer = cache?.get(geom);
5373
- if (buffer?.disposed !== false) {
5374
- buffer = new GeometryBuffer(geom);
5375
- cache.set(geom, buffer);
5376
- }
5377
- this.#geometryBuffer = buffer;
5651
+ let buffer = cache?.get(geom);
5652
+ if (Utils23.isNull(buffer) || buffer.disposed) {
5653
+ buffer = new GeometryBuffer(geom);
5654
+ cache?.set(geom, buffer);
5378
5655
  }
5656
+ buffer.retain();
5657
+ this.#geometryBuffer = buffer;
5658
+ current?.release();
5379
5659
  }
5380
5660
  _ensureMaterialBuffer() {
5381
5661
  const current = this.#materialBuffer;
5662
+ const material = this.item.material ?? DefaultMaterial;
5663
+ if (current?.item === material && !current.disposed) {
5664
+ return;
5665
+ }
5382
5666
  const cache = this.#materialBuffers;
5383
- const mesh = this.item;
5384
- const material = mesh.material ?? DefaultMaterial;
5385
- if (Utils23.isNull(cache)) {
5386
- current?.destroy();
5387
- this.#materialBuffer = new MaterialBuffer(material);
5388
- } else {
5389
- let buffer = cache?.get(material);
5390
- if (buffer?.disposed !== false) {
5391
- buffer = new MaterialBuffer(material);
5392
- cache.set(material, buffer);
5393
- }
5394
- this.#materialBuffer = buffer;
5667
+ let buffer = cache?.get(material);
5668
+ if (Utils23.isNull(buffer) || buffer.disposed) {
5669
+ buffer = new MaterialBuffer(material);
5670
+ cache?.set(material, buffer);
5395
5671
  }
5672
+ buffer.retain();
5673
+ this.#materialBuffer = buffer;
5674
+ current?.release();
5396
5675
  }
5397
5676
  _rebuildWorldMatrices({ device }) {
5398
5677
  const item = this.item;
5399
5678
  const matrix = this.buildWorldTransform();
5400
- const normal = Matrix3D2.transpose(Matrix3D2.invert(matrix));
5679
+ const inverse = Matrix3D2.invert(matrix);
5680
+ const normal = Matrix3D2.transpose(inverse);
5681
+ const matrixArray = Matrix3D2.toArray(matrix);
5401
5682
  const value = new Float32Array(28);
5402
- value.set(Matrix3D2.toArray(matrix), 0);
5683
+ value.set(matrixArray, 0);
5403
5684
  value.set([normal.m11, normal.m12, normal.m13, 0, normal.m21, normal.m22, normal.m23, 0, normal.m31, normal.m32, normal.m33, 0], 16);
5404
- if (Utils23.isNull(this.#worldTransform)) {
5405
- const buffer = Buffers.createUniform(device, value, LABEL_PREFIX + "mesh-" + item.key + "-worldmatrix-buffer");
5406
- this.#worldTransform = { buffer, value, version: performance.now().roundoff() };
5407
- } else {
5408
- this.#worldTransform.value = value;
5409
- this.#worldTransform.version = performance.now().roundoff();
5685
+ const written = writeInPlace(device, this.#worldTransform, value);
5686
+ if (!Utils23.isNull(written)) {
5687
+ return;
5410
5688
  }
5689
+ const buffer = Buffers.createUniform(device, value, LABEL_PREFIX + "mesh-" + item.key + "-worldmatrix-buffer");
5690
+ const version = performance.now().roundoff();
5691
+ this.#worldTransform = { buffer, value, version };
5411
5692
  }
5412
5693
  dispose() {
5413
- this.#worldTransformBufferBag.clear();
5414
5694
  const world = this.#worldTransform;
5415
5695
  this.#worldTransform = null;
5416
5696
  this.destroySafely(world);
5417
5697
  const material = this.#materialBuffer;
5418
5698
  this.#materialBuffer = null;
5419
- material?.destroy();
5699
+ material?.release();
5420
5700
  const geometry = this.#geometryBuffer;
5421
5701
  this.#geometryBuffer = null;
5422
- geometry?.destroy();
5702
+ geometry?.release();
5423
5703
  }
5424
5704
  };
5425
5705
  var RenderableLightBuffer = class _RenderableLightBuffer extends RenderableBufferBase {
5426
5706
  #buffer;
5427
- #bufferBag = /* @__PURE__ */ new Map();
5428
5707
  constructor(light) {
5429
5708
  super(light);
5709
+ light.flags ??= [];
5430
5710
  light.flags.push(StalePropertyFlag.Light);
5431
5711
  }
5432
5712
  /**
5433
- * Ambient light buffer building
5434
- * @param param0
5713
+ * Ambient light buffer values
5435
5714
  */
5436
- _rebuildAmbientLightBuffer({ device }) {
5715
+ _ambientLightValues() {
5437
5716
  const light = this.item;
5438
- const szColor = 4, szIntensity = 1, offsetColor = 0, offsetIntensity = 4;
5717
+ const offsetColor = 0, offsetIntensity = 4;
5439
5718
  const szTotal = 24;
5440
5719
  const values = new Float32Array(szTotal);
5441
5720
  const { r, g, b, a } = Colors3.parse(light.color ?? "#fff");
5442
5721
  values.set([r, g, b, a], offsetColor);
5443
5722
  values.set([light.intensity], offsetIntensity);
5444
- this.#buffer = { value: values, buffer: Buffers.createUniform(device, values, LABEL_PREFIX + "ambient-light-buffer"), version: performance.now() };
5723
+ return values;
5445
5724
  }
5446
5725
  /**
5447
- * Directional light buffer building
5448
- * @param param0
5726
+ * Directional light buffer values
5449
5727
  */
5450
- _rebuildDirectionalLightBuffer({ device }) {
5728
+ _directionalLightValues() {
5451
5729
  const light = this.item;
5452
- const szIntensity = 1, szColor = 4, szDirection = 3, offsetColor = 0, offsetDirection = 4, offsetIntensity = 7;
5730
+ const szIntensity = 1, offsetColor = 0, offsetDirection = 4, offsetIntensity = 7;
5453
5731
  const szTotal = offsetIntensity + szIntensity;
5454
5732
  const values = new Float32Array(szTotal);
5455
5733
  const { r, g, b, a } = Colors3.parse(light.color ?? "#fff");
@@ -5457,63 +5735,60 @@ var RenderableLightBuffer = class _RenderableLightBuffer extends RenderableBuffe
5457
5735
  values.set([light.intensity], offsetIntensity);
5458
5736
  const direction = Vector3D2.subtract(light.position, light.target);
5459
5737
  values.set([direction.x, direction.y, direction.z], offsetDirection);
5460
- this.#buffer = { value: values, buffer: Buffers.createUniform(device, values, LABEL_PREFIX + "directional-light-buffer"), version: performance.now() };
5738
+ return values;
5461
5739
  }
5462
5740
  /**
5463
- * Omni light buffer building
5464
- * @param param0
5741
+ * Omni light buffer values
5465
5742
  */
5466
- _rebuildOmniLightBuffer({ device }) {
5743
+ _omniLightValues() {
5467
5744
  const light = this.item;
5468
- const szIntensity = 1, szColor = 4, szPosition = 3, offsetColor = 0, offsetPosition = 4, offsetIntensity = 7;
5745
+ const szIntensity = 1, offsetColor = 0, offsetPosition = 4, offsetIntensity = 7;
5469
5746
  const szTotal = offsetIntensity + szIntensity;
5470
5747
  const values = new Float32Array(szTotal);
5471
5748
  const { r, g, b, a } = Colors3.parse(light.color ?? "#fff");
5472
5749
  values.set([r, g, b, a], offsetColor);
5473
5750
  values.set([light.intensity], offsetIntensity);
5474
5751
  values.set([light.position.x, light.position.y, light.position.z], offsetPosition);
5475
- this.#buffer = { value: values, buffer: Buffers.createUniform(device, values, LABEL_PREFIX + "omni-light-buffer"), version: performance.now() };
5752
+ return values;
5476
5753
  }
5477
- _rebuildLight(context) {
5478
- this.destroySafely(this.#buffer);
5754
+ _rebuildLight({ device }) {
5479
5755
  const light = this.item;
5756
+ let values;
5480
5757
  switch (light.type) {
5481
5758
  case "direction":
5482
- this._rebuildDirectionalLightBuffer(context);
5759
+ values = this._directionalLightValues();
5483
5760
  break;
5484
5761
  case "omni":
5485
- this._rebuildOmniLightBuffer(context);
5762
+ values = this._omniLightValues();
5486
5763
  break;
5487
5764
  case "ambient":
5488
- this._rebuildAmbientLightBuffer(context);
5765
+ values = this._ambientLightValues();
5489
5766
  break;
5490
5767
  default:
5491
5768
  throw new Error(`Light '${light.type}' is not supported.`);
5492
5769
  }
5770
+ const written = writeInPlace(device, this.#buffer, values);
5771
+ if (!Utils23.isNull(written)) {
5772
+ return;
5773
+ }
5774
+ this.destroySafely(this.#buffer);
5775
+ const buffer = Buffers.createUniform(device, values, LABEL_PREFIX + light.type + "-light-buffer");
5776
+ this.#buffer = { value: values, buffer, version: performance.now() };
5493
5777
  }
5494
5778
  texture(_) {
5495
5779
  throw new Error("Method not implemented.");
5496
5780
  }
5497
5781
  specificBuffer(context, key) {
5498
- const bag = this.#bufferBag;
5499
- let fresh = Utils23.isNull(this.#buffer) || this.allFlags().length > 0;
5500
- if (fresh) {
5501
- bag.clear();
5782
+ if (Utils23.isNull(this.#buffer) || this.hasFlags()) {
5502
5783
  this._rebuildLight(context);
5503
5784
  }
5504
5785
  RenderableBuffers.clearFlags(this);
5505
- const { pipeline } = context;
5506
- if (!bag.has(pipeline)) {
5507
- fresh = true;
5508
- bag.set(pipeline, this.#buffer);
5509
- }
5510
5786
  if (key === "light") {
5511
- return Utils23.extend(this.#buffer, { fresh });
5787
+ return this.#buffer;
5512
5788
  }
5513
5789
  throwBufferRequestError(key, _RenderableLightBuffer);
5514
5790
  }
5515
5791
  dispose() {
5516
- this.#bufferBag.clear();
5517
5792
  const buffer = this.#buffer;
5518
5793
  this.#buffer = null;
5519
5794
  this.destroySafely(buffer);
@@ -5531,8 +5806,70 @@ var DefaultPipelineOptions = {
5531
5806
  cullMode: "back"
5532
5807
  }
5533
5808
  };
5809
+ var ALPHA_BLENDING = {
5810
+ color: {
5811
+ srcFactor: "src-alpha",
5812
+ dstFactor: "one-minus-src-alpha"
5813
+ },
5814
+ alpha: {
5815
+ srcFactor: "one",
5816
+ dstFactor: "one-minus-src-alpha"
5817
+ }
5818
+ };
5819
+ function optionsKey(pipelineOptions) {
5820
+ const options = Utils24.extend({}, DefaultPipelineOptions, pipelineOptions ?? {});
5821
+ const primitive = options.primitive ?? {};
5822
+ return [
5823
+ options.modifiers?.version ?? "",
5824
+ options.packedVertices ? "packed" : "split",
5825
+ options.multisample ? "msaa" : "nomsaa",
5826
+ primitive.topology ?? "",
5827
+ primitive.cullMode ?? "",
5828
+ primitive.frontFace ?? ""
5829
+ ].join("|");
5830
+ }
5534
5831
  var EMPTY_BIND_DELEGATE = (_) => {
5535
5832
  };
5833
+ function mapIndices(count, selector) {
5834
+ const indices = Array(count).keys();
5835
+ return Array.from(indices, selector);
5836
+ }
5837
+ var passStates = /* @__PURE__ */ new WeakMap();
5838
+ function passStateOf(pass) {
5839
+ const existing = passStates.get(pass);
5840
+ if (!Utils24.isNull(existing)) {
5841
+ return existing;
5842
+ }
5843
+ const state = { groups: [], vertexBuffers: [] };
5844
+ passStates.set(pass, state);
5845
+ return state;
5846
+ }
5847
+ var PassUtils = {
5848
+ setPipeline: (pass, pipeline) => {
5849
+ const state = passStateOf(pass);
5850
+ if (state.pipeline === pipeline) {
5851
+ return;
5852
+ }
5853
+ pass.setPipeline(pipeline);
5854
+ state.pipeline = pipeline;
5855
+ },
5856
+ setBindGroup: (pass, index, group) => {
5857
+ const state = passStateOf(pass);
5858
+ if (state.groups[index] === group) {
5859
+ return;
5860
+ }
5861
+ pass.setBindGroup(index, group);
5862
+ state.groups[index] = group;
5863
+ },
5864
+ setVertexBuffer: (pass, slot, buffer) => {
5865
+ const state = passStateOf(pass);
5866
+ if (state.vertexBuffers[slot] === buffer) {
5867
+ return;
5868
+ }
5869
+ pass.setVertexBuffer(slot, buffer);
5870
+ state.vertexBuffers[slot] = buffer;
5871
+ }
5872
+ };
5536
5873
  var RenderPipelines = class _RenderPipelines {
5537
5874
  static {
5538
5875
  this._memoizer = /* @__PURE__ */ new WeakMap();
@@ -5551,15 +5888,16 @@ var RenderPipelines = class _RenderPipelines {
5551
5888
  * {@link RenderPipeline}, whose `frame` delegate draws object ids into an `r32uint` target instead of the normal color target.
5552
5889
  * Returns `null` if the resolved pipeline isn't a mesh or line pipeline (i.e. doesn't support raycasting).
5553
5890
  * @param items The mesh/line, camera and lights to raycast, in the same shape expected by {@link create}.
5891
+ * @param pipelineOptions The same options used to render, so that the displayed pipeline (WGSL modifiers included) gets reused.
5554
5892
  */
5555
- static createColorPicking(ctx, items) {
5556
- const renderPipeline = _RenderPipelines.create(ctx, items);
5557
- if (renderPipeline instanceof MeshRenderPipelineClass || renderPipeline instanceof LineRenderPipelineClass) {
5558
- return {
5559
- frame: renderPipeline.raycast
5560
- };
5893
+ static createColorPicking(ctx, items, pipelineOptions) {
5894
+ const renderPipeline = _RenderPipelines.create(ctx, items, pipelineOptions);
5895
+ if (Utils24.isNull(renderPipeline.raycast)) {
5896
+ return null;
5561
5897
  }
5562
- return null;
5898
+ return {
5899
+ frame: renderPipeline.raycast
5900
+ };
5563
5901
  }
5564
5902
  /**
5565
5903
  * Builds (or returns the memoized) {@link RenderPipeline} for the given renderables: the first buffer must wrap a
@@ -5567,8 +5905,8 @@ var RenderPipelines = class _RenderPipelines {
5567
5905
  * and zero or more {@link Light} buffers. Generates the mesh/line's WGSL vertex and fragment shaders (via
5568
5906
  * {@link MeshWGSLBuilder}/{@link LineWGSLBuilder}), compiles them into {@link GPUShaderModule}s, creates the
5569
5907
  * {@link GPUBindGroupLayout}s/{@link GPUPipelineLayout} and the resulting {@link GPURenderPipeline} (plus a matching
5570
- * color-picking pipeline). The pipeline is cached per {@link Context} keyed by shader "recipe" + WGSL modifiers version,
5571
- * so repeated calls with an equivalent recipe skip rebuilding.
5908
+ * color-picking pipeline). The pipeline is cached per {@link Context} keyed by shader "recipe" + pipeline options
5909
+ * (WGSL modifiers version included), so repeated calls with an equivalent recipe skip rebuilding.
5572
5910
  * @param ctx WebGPU context (device/canvas/format) to build the pipeline against.
5573
5911
  * @param items `[mesh, camera, ...lights]` renderable buffers.
5574
5912
  * @param pipelineOptions Optional overrides for primitive topology, multisampling, vertex packing and WGSL modifiers.
@@ -5576,75 +5914,93 @@ var RenderPipelines = class _RenderPipelines {
5576
5914
  * @throws {Error} If no mesh is provided, the mesh's geometry/material combination isn't supported, or the first argument isn't a mesh.
5577
5915
  */
5578
5916
  static create(ctx, [mesh, camera, ...lights], pipelineOptions) {
5579
- const memoizer = _RenderPipelines._memoizer;
5580
- let cache = memoizer.get(ctx);
5581
- if (Utils24.isNull(cache)) {
5582
- memoizer.set(ctx, cache = /* @__PURE__ */ new Map());
5583
- }
5584
- if (!Utils24.isNull(mesh)) {
5585
- if (isMesh(mesh.item)) {
5586
- const isMesh2 = isMeshGeometry(mesh.item.geometry);
5587
- const isLine = !isMesh2 && isLineMaterial(mesh.item.material);
5588
- if (!isMesh2 && !isLine) {
5589
- throw new Error("Pipeline not implemented, given the provided mesh argument.");
5590
- }
5591
- const builder = isMesh2 ? new MeshWGSLBuilder(mesh, camera, ...lights) : new LineWGSLBuilder(mesh, camera);
5592
- const key = builder.key + (pipelineOptions?.modifiers?.version ?? "");
5593
- const found = cache.get(key);
5594
- if (found) {
5595
- return found;
5596
- }
5597
- const pipeline = isMesh2 ? new MeshRenderPipelineClass(ctx, builder) : new LineRenderPipelineClass(ctx, builder);
5598
- pipeline.build(pipelineOptions);
5599
- const retval = pipeline;
5600
- Utils24.extend(retval, {
5601
- id: key + "-" + ctx.canvas.width + "x" + ctx.canvas.height + "-" + Utils24.Dates.now().toISOString()
5602
- });
5603
- cache.set(key, retval);
5604
- return retval;
5605
- } else {
5606
- throw new ReferenceError("Pipeline not implemented, given thst the first argument is not a mesh.");
5607
- }
5608
- } else {
5917
+ if (Utils24.isNull(mesh)) {
5609
5918
  throw new Error("Pipeline not implemented, given the provided arguments.");
5610
5919
  }
5920
+ if (!isMesh(mesh.item)) {
5921
+ throw new ReferenceError("Pipeline not implemented, given thst the first argument is not a mesh.");
5922
+ }
5923
+ const isMeshPipeline = isMeshGeometry(mesh.item.geometry);
5924
+ const isLinePipeline = !isMeshPipeline && isLineMaterial(mesh.item.material);
5925
+ if (!isMeshPipeline && !isLinePipeline) {
5926
+ throw new Error("Pipeline not implemented, given the provided mesh argument.");
5927
+ }
5928
+ const cache = _RenderPipelines._ensureCache(ctx);
5929
+ const builder = isMeshPipeline ? new MeshWGSLBuilder(mesh, camera, ...lights) : new LineWGSLBuilder(mesh, camera);
5930
+ const recipeKey = optionsKey(pipelineOptions);
5931
+ const key = builder.key + "|" + recipeKey;
5932
+ const found = cache.get(key);
5933
+ if (found) {
5934
+ return found;
5935
+ }
5936
+ const pipeline = isMeshPipeline ? new MeshRenderPipelineClass(ctx, builder) : new LineRenderPipelineClass(ctx, builder);
5937
+ pipeline.build(pipelineOptions);
5938
+ const timestamp = Utils24.Dates.now().toISOString();
5939
+ Utils24.extend(pipeline, {
5940
+ id: key + "-" + ctx.canvas.width + "x" + ctx.canvas.height + "-" + timestamp
5941
+ });
5942
+ cache.set(key, pipeline);
5943
+ return pipeline;
5944
+ }
5945
+ static _ensureCache(ctx) {
5946
+ const memoizer = _RenderPipelines._memoizer;
5947
+ const existing = memoizer.get(ctx);
5948
+ if (!Utils24.isNull(existing)) {
5949
+ return existing;
5950
+ }
5951
+ const cache = /* @__PURE__ */ new Map();
5952
+ memoizer.set(ctx, cache);
5953
+ return cache;
5611
5954
  }
5612
5955
  };
5956
+ function ensureEntry(maps, key) {
5957
+ const existing = maps.get(key);
5958
+ if (!Utils24.isNull(existing)) {
5959
+ return existing;
5960
+ }
5961
+ const created = /* @__PURE__ */ new Map();
5962
+ maps.set(key, created);
5963
+ return created;
5964
+ }
5965
+ function isReusable(cached, layout, resources) {
5966
+ if (Utils24.isNull(cached) || cached.layout !== layout) {
5967
+ return false;
5968
+ }
5969
+ if (cached.resources.length !== resources.length) {
5970
+ return false;
5971
+ }
5972
+ return cached.resources.every((r, i) => r === resources[i]);
5973
+ }
5974
+ function toBindGroupEntry(e) {
5975
+ if (Utils24.isNull(e.buffer)) {
5976
+ return { binding: e.binding, resource: e.resource };
5977
+ }
5978
+ return { binding: e.binding, resource: { buffer: e.buffer } };
5979
+ }
5613
5980
  var RenderPipelineCache = class {
5614
- constructor() {
5615
- this.#cache = /* @__PURE__ */ new Map();
5616
- }
5617
- #cache;
5618
- ensureBindGroup({ device }, item, buffers, refresh, layout, label, callback = () => {
5619
- }) {
5620
- const cache = this.#cache;
5621
- const key = typeof item === "string" ? item : item.key;
5622
- let set = cache.get(key);
5623
- if (Utils24.isNull(set)) {
5624
- cache.set(key, set = /* @__PURE__ */ new Map());
5625
- }
5626
- if (refresh || !set.has(label)) {
5627
- const entries = buffers.map((item2, index) => {
5628
- const entry = {
5629
- binding: index,
5630
- resource: {
5631
- buffer: item2
5632
- }
5633
- };
5634
- return entry;
5635
- });
5636
- const descriptor = {
5637
- label,
5638
- layout,
5639
- entries
5640
- };
5641
- callback(descriptor);
5642
- const retval = device.createBindGroup(descriptor);
5643
- set.set(label, retval);
5644
- return retval;
5645
- } else {
5646
- return set.get(label);
5647
- }
5981
+ #objects = /* @__PURE__ */ new WeakMap();
5982
+ #strings = /* @__PURE__ */ new Map();
5983
+ _ensureSet(owner) {
5984
+ if (typeof owner === "string") {
5985
+ return ensureEntry(this.#strings, owner);
5986
+ }
5987
+ return ensureEntry(this.#objects, owner);
5988
+ }
5989
+ ensureBindGroup({ device }, owner, label, layout, entries) {
5990
+ const set = this._ensureSet(owner);
5991
+ const cached = set.get(label);
5992
+ const resources = entries.map((e) => e.buffer ?? e.resource);
5993
+ if (isReusable(cached, layout, resources)) {
5994
+ return cached.group;
5995
+ }
5996
+ const groupEntries = entries.map(toBindGroupEntry);
5997
+ const group = device.createBindGroup({
5998
+ label,
5999
+ layout,
6000
+ entries: groupEntries
6001
+ });
6002
+ set.set(label, { group, layout, resources });
6003
+ return group;
5648
6004
  }
5649
6005
  };
5650
6006
  var MeshWGSLBuilder = class _MeshWGSLBuilder {
@@ -5668,7 +6024,7 @@ var MeshWGSLBuilder = class _MeshWGSLBuilder {
5668
6024
  if (Utils24.isNull(this.#mesh)) {
5669
6025
  this.#mesh = obj;
5670
6026
  const material = obj.item.material ?? { shader: KnownShader.Basic };
5671
- this.#key.shader = material.shader + "-" + (material.map ? "map" : "nomap");
6027
+ this.#key.shader = material.shader + "-" + (material.texture ? "map" : "nomap");
5672
6028
  } else {
5673
6029
  throw new Error("Mesh already added.");
5674
6030
  }
@@ -5688,7 +6044,7 @@ var MeshWGSLBuilder = class _MeshWGSLBuilder {
5688
6044
  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);
5689
6045
  const metadata = {
5690
6046
  lightCount: this.#lights.length,
5691
- mapCount: this.#mesh.item.material?.map ? 1 : 0
6047
+ mapCount: data.hasTexture ? 1 : 0
5692
6048
  };
5693
6049
  return {
5694
6050
  vertex,
@@ -5715,7 +6071,7 @@ var MeshWGSLBuilder = class _MeshWGSLBuilder {
5715
6071
  if (isNaN(index)) {
5716
6072
  return filteredArr;
5717
6073
  }
5718
- if (index >= 0 && index < arr.length) {
6074
+ if (index >= 0 && index < filteredArr.length) {
5719
6075
  return filteredArr[index];
5720
6076
  }
5721
6077
  return filteredArr;
@@ -5748,10 +6104,11 @@ var MeshWGSLBuilder = class _MeshWGSLBuilder {
5748
6104
  bindgroups.set(WGSLBindingType.Camera, [
5749
6105
  { key: "cameraViewTransform", group: UNIFORM_GROUP_INDEX_CAMERA, binding: UNIFORM_BINDING_INDEX_CAMERA, type: "buffer" }
5750
6106
  ]);
5751
- const lArr = lights.map((_, ndx) => {
5752
- return { key: "light", group: lightingBindGroupIndex, binding: ndx, type: "buffer" };
6107
+ const lightDefinitions = lights.map((_, ndx) => {
6108
+ const light = { key: "light", group: lightingBindGroupIndex, binding: ndx, type: "buffer" };
6109
+ return light;
5753
6110
  });
5754
- lArr.push(...lArr);
6111
+ bindgroups.set(WGSLBindingType.Light, lightDefinitions);
5755
6112
  bindgroups.set(WGSLBindingType.Interaction, [{ key: "interaction", group: UNIFORM_GROUP_INDEX_INTERACTION, type: "buffer", binding: UNIFORM_BINDING_INDEX_INTERACTION }]);
5756
6113
  }
5757
6114
  fragment(data = this._computeBasicData(), options) {
@@ -5810,74 +6167,18 @@ var MeshWGSLBuilder = class _MeshWGSLBuilder {
5810
6167
  }
5811
6168
  }
5812
6169
  };
5813
- var PipelineUtils = {
5814
- writeBufferConditionally: (device, buffer) => {
5815
- if (!buffer.fresh) {
5816
- return;
5817
- }
5818
- device.queue.writeBuffer(buffer.buffer, 0, buffer.value);
5819
- }
5820
- };
6170
+ function logFrameException(e) {
6171
+ console.error("Pacem.Drawing3D.FrameException", e);
6172
+ }
5821
6173
  var MeshRenderPipelineClass = class {
5822
6174
  constructor(_context, _builder, _cache = new RenderPipelineCache()) {
5823
6175
  this._context = _context;
5824
6176
  this._builder = _builder;
5825
6177
  this._cache = _cache;
5826
- this._ensureU32idBindGroup = (item, buffer, refresh) => {
5827
- return this._cache.ensureBindGroup(this._context, item, [buffer], refresh, this._pickBindGroupLayout, labelPrefix + "mesh-colorpick-bind-group");
5828
- };
5829
- this._ensureMaterialBindGroup = (item, buffer, texture, refresh, layoutIndex = MATERIAL_GROUP_INDEX) => {
5830
- const layout = this._bindGroupLayouts[layoutIndex], label = labelPrefix + "material-bind-group";
5831
- if (layout.label !== labelPrefix + "material-bind-group-layout") {
5832
- throw new Error("BindGroupLayout mismatch!");
5833
- }
5834
- return this._cache.ensureBindGroup(this._context, item, [buffer], refresh, layout, label, (descriptor) => {
5835
- const { device } = this.context;
5836
- const entries = descriptor.entries;
5837
- if (texture) {
5838
- entries.push({
5839
- binding: SAMPLER_BINDING_INDEX,
5840
- resource: device.createSampler({
5841
- addressModeU: "repeat",
5842
- addressModeV: "repeat",
5843
- magFilter: "linear",
5844
- minFilter: "linear"
5845
- })
5846
- }, {
5847
- binding: TEXTURE_BINDING_INDEX,
5848
- resource: texture.createView()
5849
- });
5850
- }
5851
- });
5852
- };
5853
- this._ensureWorldTransformBindGroup = (item, buffer, refresh, layoutIndex = UNIFORM_GROUP_INDEX_TRANSFORM, raycasting = false) => {
5854
- const layout = this._bindGroupLayouts[layoutIndex];
5855
- if (layout.label !== labelPrefix + "mesh-transforms-bind-group-layout") {
5856
- throw new Error("BindGroupLayout mismatch!");
5857
- }
5858
- const key = item.key + "-" + (raycasting ? 1 : 0);
5859
- const label = `${labelPrefix}${raycasting ? "colorpick" : "mesh"}-transforms-bind-group`;
5860
- return this._cache.ensureBindGroup(this._context, key, [buffer], refresh, layout, label);
5861
- };
5862
- this._ensureCameraProjectionAndInteractionDataBindGroup = (item, viewBuffer, interactionBuffer, refresh, layoutIndex = UNIFORM_GROUP_INDEX_CAMERA, raycasting = false) => {
5863
- const layout = this._bindGroupLayouts[layoutIndex];
5864
- const key = item.key + "-" + (raycasting ? 1 : 0);
5865
- const label = `${labelPrefix}${raycasting ? "colorpick" : "mesh"}-view-bind-group`;
5866
- return this._cache.ensureBindGroup(this._context, key, [viewBuffer, interactionBuffer], refresh, layout, label);
5867
- };
5868
- this._ensureLightingBindGroup = (lights, refresh, layoutIndex = UNIFORM_GROUP_INDEX_LIGHTING) => {
5869
- const layout = this._bindGroupLayouts[layoutIndex];
5870
- const key = lights.map((l) => l.id).join(":");
5871
- const buffers = lights.map((l) => l.buffer.buffer);
5872
- return this._cache.ensureBindGroup(this._context, key, buffers, refresh, layout, labelPrefix + "mesh-lighting-bind-group");
5873
- };
5874
- this._bindGroupLayouts = [];
5875
6178
  this._bindVertex = EMPTY_BIND_DELEGATE;
5876
6179
  this._bindPicker = EMPTY_BIND_DELEGATE;
5877
6180
  this._bindWorldTransform = EMPTY_BIND_DELEGATE;
5878
- this._bindRaycastWorldTransform = EMPTY_BIND_DELEGATE;
5879
6181
  this._bindCameraProjectionAndInteractionData = EMPTY_BIND_DELEGATE;
5880
- this._bindRaycastCameraProjectionAndInteractionData = EMPTY_BIND_DELEGATE;
5881
6182
  this._bindLighting = EMPTY_BIND_DELEGATE;
5882
6183
  this._bindMaterial = EMPTY_BIND_DELEGATE;
5883
6184
  this.set = (pass) => {
@@ -5890,29 +6191,30 @@ var MeshRenderPipelineClass = class {
5890
6191
  throw new Error("Deprecated.");
5891
6192
  };
5892
6193
  this.frame = (pass, interactionBuffer, meshBuffer, cameraBuffer, ...lightBuffers) => {
5893
- pass.setPipeline(this._pipeline);
5894
6194
  try {
6195
+ PassUtils.setPipeline(pass, this._pipeline);
5895
6196
  this._bindVertex(pass, meshBuffer);
5896
6197
  this._bindWorldTransform(pass, meshBuffer);
5897
6198
  this._bindMaterial(pass, meshBuffer);
5898
6199
  this._bindCameraProjectionAndInteractionData(pass, cameraBuffer, interactionBuffer);
5899
6200
  this._bindLighting(pass, ...lightBuffers);
5900
- const mesh = meshBuffer.item, geometry = mesh.geometry;
5901
- pass.draw(geometry.triangleIndices?.length || geometry.positions.length);
6201
+ const vertexCount = this._vertexCount(meshBuffer);
6202
+ pass.draw(vertexCount);
5902
6203
  } catch (e) {
5903
- console.error("Pacem.Drawing3D.FrameException", e);
6204
+ logFrameException(e);
5904
6205
  }
5905
6206
  };
5906
6207
  this.raycast = (pass, interactionBuffer, meshBuffer, cameraBuffer) => {
5907
- pass.setPipeline(this._pickPipeline);
5908
6208
  try {
6209
+ PassUtils.setPipeline(pass, this._pickPipeline);
5909
6210
  this._bindVertex(pass, meshBuffer);
5910
- this._bindRaycastWorldTransform(pass, meshBuffer);
5911
- this._bindRaycastCameraProjectionAndInteractionData(pass, cameraBuffer, interactionBuffer);
6211
+ this._bindWorldTransform(pass, meshBuffer);
6212
+ this._bindCameraProjectionAndInteractionData(pass, cameraBuffer, interactionBuffer);
5912
6213
  this._bindPicker(pass, meshBuffer);
5913
- const mesh = meshBuffer.item, geometry = mesh.geometry;
5914
- pass.draw(geometry.triangleIndices.length);
6214
+ const vertexCount = this._vertexCount(meshBuffer);
6215
+ pass.draw(vertexCount);
5915
6216
  } catch (e) {
6217
+ logFrameException(e);
5916
6218
  }
5917
6219
  };
5918
6220
  this._key = _builder.key;
@@ -5926,10 +6228,12 @@ var MeshRenderPipelineClass = class {
5926
6228
  build(pipelineOptions) {
5927
6229
  const options = Utils24.extend({}, DefaultPipelineOptions, pipelineOptions ?? {});
5928
6230
  const builder = this._builder, wgsl = builder.build(options.modifiers);
5929
- const ctx = Utils24.extend({ pipeline: this }, this._context);
6231
+ const ctx = this._context;
5930
6232
  const device = ctx.device;
6233
+ const cache = this._cache;
6234
+ const vertexModule = device.createShaderModule({ code: wgsl.vertex });
5931
6235
  const vertex = {
5932
- module: device.createShaderModule({ code: wgsl.vertex }),
6236
+ module: vertexModule,
5933
6237
  buffers: options.packedVertices ? [
5934
6238
  // packed
5935
6239
  BufferLayouts.createVertex(VERTEX_BUFFER_INDEX_MESH_POSITION, 3, 3, 2)
@@ -5977,20 +6281,15 @@ var MeshRenderPipelineClass = class {
5977
6281
  label: labelPrefix + "mesh-transforms-bind-group-layout"
5978
6282
  });
5979
6283
  const bindGroupLayouts = [viewBindGroupLayout, worldBindGroupLayout];
6284
+ const fragmentModule = device.createShaderModule({
6285
+ code: wgsl.fragment
6286
+ });
5980
6287
  const fragment = {
5981
- module: device.createShaderModule({
5982
- code: wgsl.fragment
5983
- }),
6288
+ module: fragmentModule,
5984
6289
  targets: [
5985
6290
  {
5986
6291
  format: ctx.format,
5987
- blend: {
5988
- color: {
5989
- srcFactor: "src-alpha",
5990
- dstFactor: "one-minus-src-alpha"
5991
- },
5992
- alpha: {}
5993
- }
6292
+ blend: ALPHA_BLENDING
5994
6293
  }
5995
6294
  ]
5996
6295
  };
@@ -6005,10 +6304,11 @@ var MeshRenderPipelineClass = class {
6005
6304
  }];
6006
6305
  const { mapCount } = wgsl.metadata, hasTex = mapCount > 0;
6007
6306
  if (hasTex) {
6008
- materialBindGroupLayoutDescriptorEntries.push({ visibility: GPUShaderStage.FRAGMENT, binding: SAMPLER_BINDING_INDEX, sampler: {} }, ...Array(mapCount).keys().map((index) => {
6009
- return { visibility: GPUShaderStage.FRAGMENT, binding: SAMPLER_BINDING_INDEX + 1 + index, texture: {} };
6010
- }));
6011
- } else {
6307
+ const textureEntries = mapIndices(mapCount, (index) => {
6308
+ const entry = { visibility: GPUShaderStage.FRAGMENT, binding: SAMPLER_BINDING_INDEX + 1 + index, texture: {} };
6309
+ return entry;
6310
+ });
6311
+ materialBindGroupLayoutDescriptorEntries.push({ visibility: GPUShaderStage.FRAGMENT, binding: SAMPLER_BINDING_INDEX, sampler: {} }, ...textureEntries);
6012
6312
  }
6013
6313
  const materialBindGroupLayoutDescriptor = {
6014
6314
  label: labelPrefix + "material-bind-group-layout",
@@ -6016,32 +6316,42 @@ var MeshRenderPipelineClass = class {
6016
6316
  };
6017
6317
  const materialBindGroupLayout = device.createBindGroupLayout(materialBindGroupLayoutDescriptor);
6018
6318
  bindGroupLayouts.push(materialBindGroupLayout);
6319
+ const sampler = hasTex ? device.createSampler({
6320
+ label: labelPrefix + "material-sampler",
6321
+ addressModeU: "repeat",
6322
+ addressModeV: "repeat",
6323
+ magFilter: "linear",
6324
+ minFilter: "linear"
6325
+ }) : null;
6019
6326
  const lightingGroupIndex = bindGroupLayouts.length;
6020
6327
  const { lightCount } = wgsl.metadata, hasLighting = lightCount > 0;
6328
+ let lightingBindGroupLayout = null;
6021
6329
  if (hasLighting) {
6022
- const lightingBindGroupLayout = device.createBindGroupLayout({
6023
- entries: [...Array(lightCount).keys()].map((_, index) => {
6024
- return {
6025
- visibility: GPUShaderStage.FRAGMENT,
6026
- binding: index,
6027
- buffer: {
6028
- type: "uniform"
6029
- }
6030
- };
6031
- }),
6330
+ const lightingEntries = mapIndices(lightCount, (index) => {
6331
+ const entry = {
6332
+ visibility: GPUShaderStage.FRAGMENT,
6333
+ binding: index,
6334
+ buffer: {
6335
+ type: "uniform"
6336
+ }
6337
+ };
6338
+ return entry;
6339
+ });
6340
+ lightingBindGroupLayout = device.createBindGroupLayout({
6341
+ entries: lightingEntries,
6032
6342
  label: labelPrefix + "lighting-bind-group-layout"
6033
6343
  });
6034
6344
  bindGroupLayouts.push(lightingBindGroupLayout);
6035
6345
  }
6346
+ const layout = device.createPipelineLayout({
6347
+ label: labelPrefix + "mesh-render-pipeline-layout",
6348
+ bindGroupLayouts
6349
+ });
6036
6350
  const descriptor = {
6037
6351
  label: labelPrefix + "mesh-render-pipeline",
6038
6352
  vertex,
6039
6353
  fragment,
6040
- // pipeline-layout
6041
- layout: device.createPipelineLayout({
6042
- label: labelPrefix + "mesh-render-pipeline-layout",
6043
- bindGroupLayouts: this._bindGroupLayouts = bindGroupLayouts
6044
- }),
6354
+ layout,
6045
6355
  primitive: options.primitive
6046
6356
  };
6047
6357
  if (options.multisample) {
@@ -6053,7 +6363,7 @@ var MeshRenderPipelineClass = class {
6053
6363
  };
6054
6364
  }
6055
6365
  this._pipeline = device.createRenderPipeline(descriptor);
6056
- const pickFragGroupLayout = this._pickBindGroupLayout = device.createBindGroupLayout({
6366
+ const pickFragGroupLayout = device.createBindGroupLayout({
6057
6367
  label: labelPrefix + "mesh-colorpick-bind-group-layout",
6058
6368
  entries: [
6059
6369
  {
@@ -6063,21 +6373,24 @@ var MeshRenderPipelineClass = class {
6063
6373
  }
6064
6374
  ]
6065
6375
  });
6376
+ const pickFragmentCode = getColorPickingFragmentWgsl(UNIFORM_GROUP_INDEX_COLORPICKING);
6377
+ const pickFragmentModule = device.createShaderModule({
6378
+ code: pickFragmentCode
6379
+ });
6380
+ const pickLayout = device.createPipelineLayout({
6381
+ label: labelPrefix + "mesh-colorpick-pipeline-layout",
6382
+ bindGroupLayouts: [viewBindGroupLayout, worldBindGroupLayout, pickFragGroupLayout]
6383
+ });
6066
6384
  const pickDescriptor = {
6067
6385
  label: labelPrefix + "mesh-colorpick-pipeline",
6068
6386
  vertex,
6069
6387
  fragment: {
6070
- module: device.createShaderModule({
6071
- code: getColorPickingFragmentWgsl(UNIFORM_GROUP_INDEX_COLORPICKING)
6072
- }),
6388
+ module: pickFragmentModule,
6073
6389
  targets: [
6074
6390
  { format: "r32uint" }
6075
6391
  ]
6076
6392
  },
6077
- layout: device.createPipelineLayout({
6078
- label: labelPrefix + "mesh-colorpick-pipeline-layout",
6079
- bindGroupLayouts: [viewBindGroupLayout, worldBindGroupLayout, pickFragGroupLayout]
6080
- }),
6393
+ layout: pickLayout,
6081
6394
  primitive: options.primitive,
6082
6395
  depthStencil: {
6083
6396
  depthWriteEnabled: true,
@@ -6086,6 +6399,12 @@ var MeshRenderPipelineClass = class {
6086
6399
  }
6087
6400
  };
6088
6401
  this._pickPipeline = device.createRenderPipeline(pickDescriptor);
6402
+ const { group: worldGroup } = wgsl.bindings(WGSLBindingType.Mesh, "objectWorldTransform", 0);
6403
+ const { group: cameraGroup } = wgsl.bindings(WGSLBindingType.Camera, "cameraViewTransform", 0);
6404
+ const { group: interactionGroup } = wgsl.bindings(WGSLBindingType.Interaction, "interaction", 0);
6405
+ if (cameraGroup !== interactionGroup) {
6406
+ throw new ReferenceError(`Layout bind group mismatch: ${cameraGroup} vs ${interactionGroup}.`);
6407
+ }
6089
6408
  const bindVertexSplit = (pass, ...buffers) => {
6090
6409
  const meshBuffer = buffers.at(0);
6091
6410
  if (Utils24.isNull(meshBuffer)) {
@@ -6094,122 +6413,160 @@ var MeshRenderPipelineClass = class {
6094
6413
  const { buffer: positions } = meshBuffer.buffer(ctx, "geometryPositions");
6095
6414
  const { buffer: normals } = meshBuffer.buffer(ctx, "geometryNormals");
6096
6415
  const { buffer: uv } = meshBuffer.buffer(ctx, "geometryTexCoords");
6097
- pass.setVertexBuffer(VERTEX_BUFFER_INDEX_MESH_POSITION, positions);
6098
- pass.setVertexBuffer(VERTEX_BUFFER_INDEX_MESH_NORMAL, normals);
6099
- pass.setVertexBuffer(VERTEX_BUFFER_INDEX_MESH_UV, uv);
6416
+ PassUtils.setVertexBuffer(pass, VERTEX_BUFFER_INDEX_MESH_POSITION, positions);
6417
+ PassUtils.setVertexBuffer(pass, VERTEX_BUFFER_INDEX_MESH_NORMAL, normals);
6418
+ PassUtils.setVertexBuffer(pass, VERTEX_BUFFER_INDEX_MESH_UV, uv);
6100
6419
  };
6101
6420
  const bindVertexPacked = (pass, ...buffers) => {
6102
6421
  const meshBuffer = buffers.at(0);
6103
6422
  if (Utils24.isNull(meshBuffer)) {
6104
6423
  throw new ReferenceError(`Null ${RenderableBuffers.name} bringing vertex buffers was provided.`);
6105
6424
  }
6106
- const { buffer } = meshBuffer.buffer(ctx, "geometry");
6107
- pass.setVertexBuffer(VERTEX_BUFFER_INDEX_MESH_POSITION, buffer);
6425
+ const { buffer: packed } = meshBuffer.buffer(ctx, "geometry");
6426
+ PassUtils.setVertexBuffer(pass, VERTEX_BUFFER_INDEX_MESH_POSITION, packed);
6108
6427
  };
6109
6428
  this._bindVertex = options.packedVertices ? bindVertexPacked : bindVertexSplit;
6110
- const bindWorldTransform = (pass, meshBuffer, raycasting) => {
6429
+ this._bindWorldTransform = (pass, ...buffers) => {
6430
+ const meshBuffer = buffers.at(0);
6111
6431
  if (Utils24.isNull(meshBuffer)) {
6112
6432
  throw new ReferenceError(`Null ${RenderableBuffers.name} bringing world transform buffer was provided.`);
6113
6433
  }
6114
- const worldTransform = meshBuffer.buffer(ctx, "objectWorldTransform"), worldTransformBuffer = worldTransform.buffer;
6115
- PipelineUtils.writeBufferConditionally(device, worldTransform);
6116
- const { group } = wgsl.bindings(WGSLBindingType.Mesh, "objectWorldTransform", 0);
6117
- const bindGroup = this._ensureWorldTransformBindGroup(meshBuffer.item, worldTransformBuffer, worldTransform.fresh, group, raycasting);
6118
- pass.setBindGroup(group, bindGroup);
6119
- };
6120
- this._bindWorldTransform = (pass, ...buffers) => {
6121
- const meshBuffer = buffers.at(0);
6122
- bindWorldTransform(pass, meshBuffer, false);
6123
- };
6124
- this._bindRaycastWorldTransform = (pass, ...buffers) => {
6125
- const meshBuffer = buffers.at(0);
6126
- bindWorldTransform(pass, meshBuffer, true);
6434
+ const { buffer } = meshBuffer.buffer(ctx, "objectWorldTransform");
6435
+ const bindGroup = cache.ensureBindGroup(ctx, meshBuffer, labelPrefix + "mesh-transforms-bind-group", worldBindGroupLayout, [
6436
+ { binding: UNIFORM_BINDING_INDEX_TRANSFORM, buffer }
6437
+ ]);
6438
+ PassUtils.setBindGroup(pass, worldGroup, bindGroup);
6127
6439
  };
6128
- const bindCameraProjectionAndInteractionData = (pass, cameraBuffer, interactionBuffer, raycasting) => {
6440
+ this._bindCameraProjectionAndInteractionData = (pass, ...buffers) => {
6441
+ const cameraBuffer = buffers.at(0);
6442
+ const interactionBuffer = buffers.at(1);
6129
6443
  if (Utils24.isNull(cameraBuffer)) {
6130
6444
  throw new ReferenceError(`Null ${RenderableBuffers.name} bringing view projection buffers was provided.`);
6131
6445
  }
6132
- const viewTransformBuffer = cameraBuffer.buffer(ctx, "cameraViewTransform"), viewTransformBufferBuffer = viewTransformBuffer.buffer;
6133
- PipelineUtils.writeBufferConditionally(device, viewTransformBuffer);
6134
6446
  if (Utils24.isNull(interactionBuffer)) {
6135
6447
  throw new ReferenceError(`Null ${RenderableBuffers.name} bringing interaction buffers was provided.`);
6136
6448
  }
6137
- const interactionDataBuffer = interactionBuffer.buffer(ctx, "interaction"), interactionDataBufferBuffer = interactionDataBuffer.buffer;
6138
- PipelineUtils.writeBufferConditionally(device, interactionDataBuffer);
6139
- const { group } = wgsl.bindings(WGSLBindingType.Camera, "cameraViewTransform", 0);
6140
- const { group: interactionGroup } = wgsl.bindings(WGSLBindingType.Interaction, "interaction", 0);
6141
- if (group !== interactionGroup) {
6142
- throw new ReferenceError(`Layout bind group mismatch: ${group} vs ${interactionGroup}.`);
6143
- }
6144
- const bindGroup = this._ensureCameraProjectionAndInteractionDataBindGroup(
6145
- cameraBuffer.item,
6146
- viewTransformBufferBuffer,
6147
- interactionDataBufferBuffer,
6148
- // since fresh could mean also "camera switched" (e.g. from ortho to perspective and then back to ortho) there's risk
6149
- // to target destroyed buffers, this refresh the bind group if either buffer is fresh.
6150
- // Possibilities for fine-tuning in future.
6151
- viewTransformBuffer.fresh || interactionDataBuffer.fresh,
6152
- group,
6153
- raycasting
6154
- );
6155
- pass.setBindGroup(group, bindGroup);
6156
- };
6157
- this._bindCameraProjectionAndInteractionData = (pass, ...buffers) => {
6158
- const cameraBuffer = buffers.at(0);
6159
- const interactionBuffer = buffers.at(1);
6160
- bindCameraProjectionAndInteractionData(pass, cameraBuffer, interactionBuffer, false);
6161
- };
6162
- this._bindRaycastCameraProjectionAndInteractionData = (pass, ...buffers) => {
6163
- const cameraBuffer = buffers.at(0);
6164
- const interactionBuffer = buffers.at(1);
6165
- bindCameraProjectionAndInteractionData(pass, cameraBuffer, interactionBuffer, true);
6449
+ const { buffer: view2 } = cameraBuffer.buffer(ctx, "cameraViewTransform");
6450
+ const { buffer: interaction } = interactionBuffer.buffer(ctx, "interaction");
6451
+ const bindGroup = cache.ensureBindGroup(ctx, cameraBuffer, labelPrefix + "mesh-view-bind-group", viewBindGroupLayout, [
6452
+ { binding: UNIFORM_BINDING_INDEX_CAMERA, buffer: view2 },
6453
+ { binding: UNIFORM_BINDING_INDEX_INTERACTION, buffer: interaction }
6454
+ ]);
6455
+ PassUtils.setBindGroup(pass, cameraGroup, bindGroup);
6166
6456
  };
6167
6457
  this._bindMaterial = (pass, ...buffers) => {
6168
6458
  const meshBuffer = buffers.at(0);
6169
6459
  if (Utils24.isNull(meshBuffer)) {
6170
6460
  throw new ReferenceError(`Null ${RenderableBuffers.name} bringing vertex colors was provided.`);
6171
6461
  }
6172
- const vertexColorsBuffer = meshBuffer.buffer(ctx, "material"), vertexColorsBufferBuffer = vertexColorsBuffer.buffer;
6173
- PipelineUtils.writeBufferConditionally(device, vertexColorsBuffer);
6174
- let tex = meshBuffer.texture(ctx);
6175
- const texBmp = tex?.texture;
6176
- const bindGroup = this._ensureMaterialBindGroup(meshBuffer.item, vertexColorsBufferBuffer, texBmp, vertexColorsBuffer.fresh, materialGroupIndex);
6177
- pass.setBindGroup(materialGroupIndex, bindGroup);
6462
+ const material = meshBuffer.buffer(ctx, "material");
6463
+ const entries = [{ binding: STORAGE_MATERIAL_INDEX, buffer: material.buffer }];
6178
6464
  if (hasTex) {
6179
- device.queue.copyExternalImageToTexture({ source: tex.source, flipY: true }, { texture: texBmp }, { width: texBmp.width, height: texBmp.height });
6465
+ const tex = meshBuffer.texture(ctx, "texture");
6466
+ entries.push({ binding: SAMPLER_BINDING_INDEX, resource: sampler }, { binding: TEXTURE_BINDING_INDEX, resource: tex?.view });
6180
6467
  }
6468
+ const bindGroup = cache.ensureBindGroup(ctx, material, labelPrefix + "material-bind-group", materialBindGroupLayout, entries);
6469
+ PassUtils.setBindGroup(pass, materialGroupIndex, bindGroup);
6181
6470
  };
6182
6471
  this._bindLighting = (pass, ...buffers) => {
6183
- if (hasLighting) {
6184
- const lightArray = Array.from(buffers);
6185
- const lightBuffers = lightArray.map((l) => {
6186
- return { buffer: l.buffer(ctx, "light"), id: l.item.key };
6187
- });
6188
- const refresh = lightBuffers.some((b) => b.buffer.fresh);
6189
- const bindGroup = this._ensureLightingBindGroup(lightBuffers, refresh, lightingGroupIndex);
6190
- for (let lightBuffer of lightBuffers) {
6191
- PipelineUtils.writeBufferConditionally(device, lightBuffer.buffer);
6192
- }
6193
- pass.setBindGroup(lightingGroupIndex, bindGroup);
6472
+ if (!hasLighting) {
6473
+ return;
6194
6474
  }
6475
+ const owner = buffers.at(0);
6476
+ const entries = buffers.map((l, index) => {
6477
+ const { buffer } = l.buffer(ctx, "light");
6478
+ const entry = { binding: index, buffer };
6479
+ return entry;
6480
+ });
6481
+ const bindGroup = cache.ensureBindGroup(ctx, owner, labelPrefix + "mesh-lighting-bind-group", lightingBindGroupLayout, entries);
6482
+ PassUtils.setBindGroup(pass, lightingGroupIndex, bindGroup);
6195
6483
  };
6196
6484
  this._bindPicker = (pass, ...buffers) => {
6197
6485
  const meshBuffer = buffers.at(0);
6198
6486
  if (Utils24.isNull(meshBuffer)) {
6199
6487
  throw new ReferenceError(`Null ${RenderableBuffers.name} bringing world transform buffer was provided.`);
6200
6488
  }
6201
- const u32id = meshBuffer.buffer(ctx, "u32id"), u32idBuffer = u32id.buffer;
6202
- PipelineUtils.writeBufferConditionally(device, u32id);
6203
- const group = UNIFORM_GROUP_INDEX_COLORPICKING;
6204
- const refresh = u32id.fresh;
6205
- const bindGroup = this._ensureU32idBindGroup(
6206
- meshBuffer.item,
6207
- u32idBuffer,
6208
- refresh
6209
- /* reuse u32id.fresh*/
6210
- );
6211
- pass.setBindGroup(group, bindGroup);
6489
+ const { buffer } = meshBuffer.buffer(ctx, "u32id");
6490
+ const bindGroup = cache.ensureBindGroup(ctx, meshBuffer, labelPrefix + "mesh-colorpick-bind-group", pickFragGroupLayout, [
6491
+ { binding: 0, buffer }
6492
+ ]);
6493
+ PassUtils.setBindGroup(pass, UNIFORM_GROUP_INDEX_COLORPICKING, bindGroup);
6212
6494
  };
6495
+ if (!options.multisample) {
6496
+ return;
6497
+ }
6498
+ let translucentPipeline = null;
6499
+ let translucentViewBindGroupLayout = null;
6500
+ const ensureTranslucentPipeline = () => {
6501
+ if (!Utils24.isNull(translucentPipeline)) {
6502
+ return;
6503
+ }
6504
+ translucentViewBindGroupLayout = device.createBindGroupLayout({
6505
+ label: labelPrefix + "mesh-abuffer-view-bind-group-layout",
6506
+ entries: [
6507
+ { binding: UNIFORM_BINDING_INDEX_CAMERA, visibility: GPUShaderStage.VERTEX | GPUShaderStage.FRAGMENT, buffer: { type: "uniform" } },
6508
+ { binding: UNIFORM_BINDING_INDEX_INTERACTION, visibility: GPUShaderStage.VERTEX | GPUShaderStage.FRAGMENT, buffer: { type: "uniform" } },
6509
+ { binding: ABUFFER_BINDING_INDEX_HEADS, visibility: GPUShaderStage.FRAGMENT, buffer: { type: "storage" } },
6510
+ { binding: ABUFFER_BINDING_INDEX_LIST, visibility: GPUShaderStage.FRAGMENT, buffer: { type: "storage" } },
6511
+ { binding: ABUFFER_BINDING_INDEX_INFO, visibility: GPUShaderStage.FRAGMENT, buffer: { type: "uniform" } },
6512
+ { binding: ABUFFER_BINDING_INDEX_DEPTH, visibility: GPUShaderStage.FRAGMENT, texture: { sampleType: "depth", multisampled: true } }
6513
+ ]
6514
+ });
6515
+ const translucentLayouts = bindGroupLayouts.slice();
6516
+ translucentLayouts[cameraGroup] = translucentViewBindGroupLayout;
6517
+ const translucentFragmentCode = builder.fragment(void 0, { modifier: options.modifiers?.fragment, output: "a-buffer" });
6518
+ const translucentFragmentModule = device.createShaderModule({
6519
+ label: labelPrefix + "mesh-abuffer-fragment",
6520
+ code: translucentFragmentCode
6521
+ });
6522
+ const translucentLayout = device.createPipelineLayout({
6523
+ label: labelPrefix + "mesh-abuffer-pipeline-layout",
6524
+ bindGroupLayouts: translucentLayouts
6525
+ });
6526
+ translucentPipeline = device.createRenderPipeline({
6527
+ label: labelPrefix + "mesh-abuffer-pipeline",
6528
+ vertex,
6529
+ fragment: {
6530
+ module: translucentFragmentModule,
6531
+ // fragments are pushed into storage buffers, nothing is written to color targets
6532
+ targets: []
6533
+ },
6534
+ layout: translucentLayout,
6535
+ primitive: options.primitive,
6536
+ multisample: { count: 4 },
6537
+ // tested against the opaque depth (read-only), never written
6538
+ depthStencil: { format: "depth24plus", depthCompare: "less", depthWriteEnabled: false }
6539
+ });
6540
+ };
6541
+ this.translucent = (pass, interactionBuffer, aBuffer, meshBuffer, cameraBuffer, ...lightBuffers) => {
6542
+ try {
6543
+ ensureTranslucentPipeline();
6544
+ PassUtils.setPipeline(pass, translucentPipeline);
6545
+ this._bindVertex(pass, meshBuffer);
6546
+ this._bindWorldTransform(pass, meshBuffer);
6547
+ this._bindMaterial(pass, meshBuffer);
6548
+ const { buffer: view2 } = cameraBuffer.buffer(ctx, "cameraViewTransform");
6549
+ const { buffer: interaction } = interactionBuffer.buffer(ctx, "interaction");
6550
+ const bindGroup = cache.ensureBindGroup(ctx, cameraBuffer, labelPrefix + "mesh-abuffer-view-bind-group", translucentViewBindGroupLayout, [
6551
+ { binding: UNIFORM_BINDING_INDEX_CAMERA, buffer: view2 },
6552
+ { binding: UNIFORM_BINDING_INDEX_INTERACTION, buffer: interaction },
6553
+ { binding: ABUFFER_BINDING_INDEX_HEADS, buffer: aBuffer.heads },
6554
+ { binding: ABUFFER_BINDING_INDEX_LIST, buffer: aBuffer.list },
6555
+ { binding: ABUFFER_BINDING_INDEX_INFO, buffer: aBuffer.info },
6556
+ { binding: ABUFFER_BINDING_INDEX_DEPTH, resource: aBuffer.depth }
6557
+ ]);
6558
+ PassUtils.setBindGroup(pass, cameraGroup, bindGroup);
6559
+ this._bindLighting(pass, ...lightBuffers);
6560
+ const vertexCount = this._vertexCount(meshBuffer);
6561
+ pass.draw(vertexCount);
6562
+ } catch (e) {
6563
+ logFrameException(e);
6564
+ }
6565
+ };
6566
+ }
6567
+ _vertexCount(meshBuffer) {
6568
+ const mesh = meshBuffer.item, geometry = mesh.geometry;
6569
+ return geometry.triangleIndices?.length || geometry.positions.length;
6213
6570
  }
6214
6571
  };
6215
6572
  var LineWGSLBuilder = class _LineWGSLBuilder {
@@ -6267,7 +6624,7 @@ var LineWGSLBuilder = class _LineWGSLBuilder {
6267
6624
  if (isNaN(index)) {
6268
6625
  return filteredArr;
6269
6626
  }
6270
- if (index >= 0 && index < arr.length) {
6627
+ if (index >= 0 && index < filteredArr.length) {
6271
6628
  return filteredArr[index];
6272
6629
  }
6273
6630
  return filteredArr;
@@ -6316,50 +6673,10 @@ var LineRenderPipelineClass = class {
6316
6673
  constructor(context, _lineBuilder, _cache = new RenderPipelineCache()) {
6317
6674
  this._lineBuilder = _lineBuilder;
6318
6675
  this._cache = _cache;
6319
- this._ensureLineU32idBindGroup = (item, buffer, refresh) => {
6320
- const ctx = this.context;
6321
- return this._cache.ensureBindGroup(ctx, item, [buffer], refresh, this._pickLineBindGroupLayout, labelPrefix + "line-colorpick-bind-group");
6322
- };
6323
- this._ensureLineMaterialBindGroup = (item, buffer, refresh, layoutIndex = MATERIAL_GROUP_INDEX) => {
6324
- const layout = this._bindLineGroupLayouts[layoutIndex];
6325
- if (layout.label !== labelPrefix + "line-material-bind-group-layout") {
6326
- throw new Error("BindGroupLayout mismatch!");
6327
- }
6328
- const ctx = this.context;
6329
- return this._cache.ensureBindGroup(ctx, item, [buffer], refresh, layout, labelPrefix + "line-material-bind-group");
6330
- };
6331
- this._ensureLinePositionsBindGroup = (item, buffers, refresh, layoutIndex) => {
6332
- const layout = this._bindLineGroupLayouts[layoutIndex];
6333
- if (layout.label !== labelPrefix + "line-positions-bind-group-layout") {
6334
- throw new Error("BindGroupLayout mismatch!");
6335
- }
6336
- const ctx = this.context;
6337
- return this._cache.ensureBindGroup(ctx, item, buffers, refresh, layout, labelPrefix + "line-positions-bind-group");
6338
- };
6339
- this._ensureLineWorldTransformBindGroup = (item, buffer, refresh, layoutIndex = UNIFORM_GROUP_INDEX_TRANSFORM, raycasting = false) => {
6340
- const layout = this._bindLineGroupLayouts[layoutIndex];
6341
- if (layout.label !== labelPrefix + "line-transforms-bind-group-layout") {
6342
- throw new Error("BindGroupLayout mismatch!");
6343
- }
6344
- const key = item.key + "-line-" + (raycasting ? 1 : 0);
6345
- const label = `${labelPrefix}${raycasting ? "colorpick" : ""}-line-transforms-bind-group`;
6346
- const ctx = this.context;
6347
- return this._cache.ensureBindGroup(ctx, key, [buffer], refresh, layout, label);
6348
- };
6349
- this._ensureLineCameraProjectionBindGroup = (item, viewBuffer, refresh, layoutIndex = UNIFORM_GROUP_INDEX_CAMERA, raycasting = false) => {
6350
- const layout = this._bindLineGroupLayouts[layoutIndex];
6351
- const key = item.key + "-line-" + (raycasting ? 1 : 0);
6352
- const label = `${labelPrefix}${raycasting ? "colorpick" : ""}-line-view-bind-group`;
6353
- const ctx = this.context;
6354
- return this._cache.ensureBindGroup(ctx, key, [viewBuffer], refresh, layout, label);
6355
- };
6356
- this._bindLineGroupLayouts = [];
6357
6676
  this._bindLinePositions = EMPTY_BIND_DELEGATE;
6358
6677
  this._bindLinePicker = EMPTY_BIND_DELEGATE;
6359
6678
  this._bindLineWorldTransform = EMPTY_BIND_DELEGATE;
6360
- this._bindLineRaycastWorldTransform = EMPTY_BIND_DELEGATE;
6361
6679
  this._bindLineCameraProjection = EMPTY_BIND_DELEGATE;
6362
- this._bindLineRaycastCameraProjection = EMPTY_BIND_DELEGATE;
6363
6680
  this._bindLineMaterial = EMPTY_BIND_DELEGATE;
6364
6681
  this._drawLine = EMPTY_BIND_DELEGATE;
6365
6682
  this.set = (pass) => {
@@ -6372,26 +6689,27 @@ var LineRenderPipelineClass = class {
6372
6689
  throw new Error("Deprecated.");
6373
6690
  };
6374
6691
  this.frame = (pass, interactionBuffer, meshBuffer, cameraBuffer) => {
6375
- pass.setPipeline(this._linePipeline);
6376
6692
  try {
6693
+ PassUtils.setPipeline(pass, this._linePipeline);
6377
6694
  this._bindLineWorldTransform(pass, meshBuffer);
6378
6695
  this._bindLineCameraProjection(pass, cameraBuffer);
6379
6696
  this._bindLinePositions(pass, meshBuffer);
6380
6697
  this._bindLineMaterial(pass, meshBuffer);
6381
6698
  this._drawLine(pass, meshBuffer);
6382
6699
  } catch (e) {
6383
- console.error("Pacem.Drawing3D.FrameException", e);
6700
+ logFrameException(e);
6384
6701
  }
6385
6702
  };
6386
6703
  this.raycast = (pass, interactionBuffer, meshBuffer, cameraBuffer) => {
6387
- pass.setPipeline(this._pickLinePipeline);
6388
6704
  try {
6389
- this._bindLineRaycastWorldTransform(pass, meshBuffer);
6390
- this._bindLineRaycastCameraProjection(pass, cameraBuffer);
6705
+ PassUtils.setPipeline(pass, this._pickLinePipeline);
6706
+ this._bindLineWorldTransform(pass, meshBuffer);
6707
+ this._bindLineCameraProjection(pass, cameraBuffer);
6391
6708
  this._bindLinePositions(pass, meshBuffer);
6392
6709
  this._bindLinePicker(pass, meshBuffer);
6393
6710
  this._drawLine(pass, meshBuffer);
6394
6711
  } catch (e) {
6712
+ logFrameException(e);
6395
6713
  }
6396
6714
  };
6397
6715
  this.#context = context;
@@ -6406,11 +6724,13 @@ var LineRenderPipelineClass = class {
6406
6724
  build(pipelineOptions) {
6407
6725
  const options = Utils24.extend({}, DefaultPipelineOptions, pipelineOptions ?? {});
6408
6726
  const builder = this._lineBuilder, wgsl = builder.build();
6409
- const ctx = Utils24.extend({ pipeline: this }, this.#context);
6727
+ const ctx = this.#context;
6410
6728
  const device = ctx.device;
6729
+ const cache = this._cache;
6411
6730
  const fatLines = wgsl.metadata.thickness > 1;
6731
+ const vertexModule = device.createShaderModule({ code: wgsl.vertex });
6412
6732
  const vertex = {
6413
- module: device.createShaderModule({ code: wgsl.vertex }),
6733
+ module: vertexModule,
6414
6734
  buffers: []
6415
6735
  };
6416
6736
  const worldBindGroupLayout = device.createBindGroupLayout({
@@ -6476,20 +6796,15 @@ var LineRenderPipelineClass = class {
6476
6796
  const vertexBindGroupLayouts = [viewBindGroupLayout, worldBindGroupLayout, lineBindGroupLayout];
6477
6797
  const raycastLayoutIndex = vertexBindGroupLayouts.length;
6478
6798
  const bindGroupLayouts = vertexBindGroupLayouts.slice();
6799
+ const fragmentModule = device.createShaderModule({
6800
+ code: wgsl.fragment
6801
+ });
6479
6802
  const fragment = {
6480
- module: device.createShaderModule({
6481
- code: wgsl.fragment
6482
- }),
6803
+ module: fragmentModule,
6483
6804
  targets: [
6484
6805
  {
6485
6806
  format: ctx.format,
6486
- blend: {
6487
- color: {
6488
- srcFactor: "src-alpha",
6489
- dstFactor: "one-minus-src-alpha"
6490
- },
6491
- alpha: {}
6492
- }
6807
+ blend: ALPHA_BLENDING
6493
6808
  }
6494
6809
  ]
6495
6810
  };
@@ -6509,16 +6824,17 @@ var LineRenderPipelineClass = class {
6509
6824
  const materialBindGroupLayout = device.createBindGroupLayout(materialBindGroupLayoutDescriptor);
6510
6825
  bindGroupLayouts.push(materialBindGroupLayout);
6511
6826
  const topology = fatLines ? options.primitive.topology : "line-list";
6827
+ const primitive = Utils24.extend({}, options.primitive, { topology });
6828
+ const layout = device.createPipelineLayout({
6829
+ label: labelPrefix + "line-render-pipeline-layout",
6830
+ bindGroupLayouts
6831
+ });
6512
6832
  const descriptor = {
6513
6833
  label: labelPrefix + "line-render-pipeline",
6514
6834
  vertex,
6515
6835
  fragment,
6516
- // pipeline-layout
6517
- layout: device.createPipelineLayout({
6518
- label: labelPrefix + "line-render-pipeline-layout",
6519
- bindGroupLayouts: this._bindLineGroupLayouts = bindGroupLayouts
6520
- }),
6521
- primitive: Utils24.extend({}, options.primitive, { topology })
6836
+ layout,
6837
+ primitive
6522
6838
  };
6523
6839
  if (options.multisample) {
6524
6840
  descriptor.multisample = { count: 4 };
@@ -6529,7 +6845,7 @@ var LineRenderPipelineClass = class {
6529
6845
  };
6530
6846
  }
6531
6847
  this._linePipeline = device.createRenderPipeline(descriptor);
6532
- const pickFragGroupLayout = this._pickLineBindGroupLayout = device.createBindGroupLayout({
6848
+ const pickFragGroupLayout = device.createBindGroupLayout({
6533
6849
  label: labelPrefix + "line-colorpick-bind-group-layout",
6534
6850
  entries: [
6535
6851
  {
@@ -6539,22 +6855,26 @@ var LineRenderPipelineClass = class {
6539
6855
  }
6540
6856
  ]
6541
6857
  });
6858
+ const pickFragmentCode = getColorPickingFragmentWgsl(raycastLayoutIndex);
6859
+ const pickFragmentModule = device.createShaderModule({
6860
+ code: pickFragmentCode
6861
+ });
6862
+ const pickBindGroupLayouts = vertexBindGroupLayouts.concat(pickFragGroupLayout);
6863
+ const pickLayout = device.createPipelineLayout({
6864
+ label: labelPrefix + "line-colorpick-pipeline-layout",
6865
+ bindGroupLayouts: pickBindGroupLayouts
6866
+ });
6542
6867
  const pickDescriptor = {
6543
6868
  label: labelPrefix + "line-colorpick-pipeline",
6544
6869
  vertex,
6545
6870
  fragment: {
6546
- module: device.createShaderModule({
6547
- code: getColorPickingFragmentWgsl(raycastLayoutIndex)
6548
- }),
6871
+ module: pickFragmentModule,
6549
6872
  targets: [
6550
6873
  { format: "r32uint" }
6551
6874
  ]
6552
6875
  },
6553
- layout: device.createPipelineLayout({
6554
- label: labelPrefix + "line-colorpick-pipeline-layout",
6555
- bindGroupLayouts: vertexBindGroupLayouts.concat(pickFragGroupLayout)
6556
- }),
6557
- primitive: Utils24.extend({}, options.primitive, { topology }),
6876
+ layout: pickLayout,
6877
+ primitive,
6558
6878
  depthStencil: {
6559
6879
  depthWriteEnabled: true,
6560
6880
  depthCompare: "less",
@@ -6562,103 +6882,66 @@ var LineRenderPipelineClass = class {
6562
6882
  }
6563
6883
  };
6564
6884
  this._pickLinePipeline = device.createRenderPipeline(pickDescriptor);
6565
- const bindLineWorldTransform = (pass, meshBuffer, raycasting) => {
6885
+ const { group: worldGroup } = wgsl.bindings(WGSLBindingType.Mesh, "objectWorldTransform", 0);
6886
+ const { group: cameraGroup } = wgsl.bindings(WGSLBindingType.Camera, "cameraViewTransform", 0);
6887
+ const { group: positionsGroup } = wgsl.bindings(WGSLBindingType.Mesh, "line", 0);
6888
+ this._bindLineWorldTransform = (pass, ...buffers) => {
6889
+ const meshBuffer = buffers.at(0);
6566
6890
  if (Utils24.isNull(meshBuffer)) {
6567
6891
  throw new ReferenceError(`Null ${RenderableBuffers.name} bringing world transform buffer was provided.`);
6568
6892
  }
6569
- const worldTransform = meshBuffer.buffer(ctx, "objectWorldTransform"), worldTransformBuffer = worldTransform.buffer;
6570
- PipelineUtils.writeBufferConditionally(device, worldTransform);
6571
- const { group } = wgsl.bindings(WGSLBindingType.Mesh, "objectWorldTransform", 0);
6572
- const bindGroup = this._ensureLineWorldTransformBindGroup(
6573
- meshBuffer.item,
6574
- worldTransformBuffer,
6575
- /*worldTransform.fresh*/
6576
- false,
6577
- group,
6578
- raycasting
6579
- );
6580
- pass.setBindGroup(group, bindGroup);
6581
- };
6582
- this._bindLineWorldTransform = (pass, ...buffers) => {
6583
- const meshBuffer = buffers.at(0);
6584
- bindLineWorldTransform(pass, meshBuffer, false);
6585
- };
6586
- this._bindLineRaycastWorldTransform = (pass, ...buffers) => {
6587
- const meshBuffer = buffers.at(0);
6588
- bindLineWorldTransform(pass, meshBuffer, true);
6893
+ const { buffer } = meshBuffer.buffer(ctx, "objectWorldTransform");
6894
+ const bindGroup = cache.ensureBindGroup(ctx, meshBuffer, labelPrefix + "line-transforms-bind-group", worldBindGroupLayout, [
6895
+ { binding: UNIFORM_BINDING_INDEX_TRANSFORM, buffer }
6896
+ ]);
6897
+ PassUtils.setBindGroup(pass, worldGroup, bindGroup);
6589
6898
  };
6590
- const bindLineCameraProjection = (pass, cameraBuffer, raycasting) => {
6899
+ this._bindLineCameraProjection = (pass, ...buffers) => {
6900
+ const cameraBuffer = buffers.at(0);
6591
6901
  if (Utils24.isNull(cameraBuffer)) {
6592
6902
  throw new ReferenceError(`Null ${RenderableBuffers.name} bringing view projection buffers was provided.`);
6593
6903
  }
6594
- const viewTransformBuffer = cameraBuffer.buffer(ctx, "cameraViewTransform"), viewTransformBufferBuffer = viewTransformBuffer.buffer;
6595
- PipelineUtils.writeBufferConditionally(device, viewTransformBuffer);
6596
- const { group } = wgsl.bindings(WGSLBindingType.Camera, "cameraViewTransform", 0);
6597
- const bindGroup = this._ensureLineCameraProjectionBindGroup(
6598
- cameraBuffer.item,
6599
- viewTransformBufferBuffer,
6600
- /*viewTransformBuffer.fresh*/
6601
- false,
6602
- group,
6603
- raycasting
6604
- );
6605
- pass.setBindGroup(group, bindGroup);
6606
- };
6607
- this._bindLineCameraProjection = (pass, ...buffers) => {
6608
- const cameraBuffer = buffers.at(0);
6609
- bindLineCameraProjection(pass, cameraBuffer, false);
6610
- };
6611
- this._bindLineRaycastCameraProjection = (pass, ...buffers) => {
6612
- const cameraBuffer = buffers.at(0);
6613
- bindLineCameraProjection(pass, cameraBuffer, true);
6904
+ const { buffer } = cameraBuffer.buffer(ctx, "cameraViewTransform");
6905
+ const bindGroup = cache.ensureBindGroup(ctx, cameraBuffer, labelPrefix + "line-view-bind-group", viewBindGroupLayout, [
6906
+ { binding: UNIFORM_BINDING_INDEX_CAMERA, buffer }
6907
+ ]);
6908
+ PassUtils.setBindGroup(pass, cameraGroup, bindGroup);
6614
6909
  };
6615
6910
  this._bindLinePositions = (pass, ...buffers) => {
6616
6911
  const meshBuffer = buffers.at(0);
6617
6912
  if (Utils24.isNull(meshBuffer)) {
6618
6913
  throw new ReferenceError(`Null ${RenderableBuffers.name} bringing vertex buffers was provided as index 0.`);
6619
6914
  }
6620
- const positionsBuffer = (
6621
- /* should have a storage buffer here */
6622
- meshBuffer.buffer(ctx, "geometryPositions")
6623
- ), positionsBufferBuffer = positionsBuffer.buffer;
6624
- let refresh = positionsBuffer.fresh;
6625
- const buffersInput = [positionsBufferBuffer];
6626
- PipelineUtils.writeBufferConditionally(device, positionsBuffer);
6915
+ const { buffer: positions } = meshBuffer.buffer(ctx, "geometryPositions");
6916
+ const entries = [{ binding: 0, buffer: positions }];
6627
6917
  if (fatLines) {
6628
- const lineBuffer = meshBuffer.buffer(ctx, "line"), lineBufferBuffer = lineBuffer.buffer;
6629
- refresh ||= lineBuffer.fresh;
6630
- buffersInput.push(lineBufferBuffer);
6631
- PipelineUtils.writeBufferConditionally(device, lineBuffer);
6632
- }
6633
- const { group: groupIndex } = wgsl.bindings(WGSLBindingType.Mesh, "line", 0);
6634
- const bindGroup = this._ensureLinePositionsBindGroup(meshBuffer.item, buffersInput, refresh, groupIndex);
6635
- pass.setBindGroup(groupIndex, bindGroup);
6918
+ const { buffer: line } = meshBuffer.buffer(ctx, "line");
6919
+ entries.push({ binding: 1, buffer: line });
6920
+ }
6921
+ const bindGroup = cache.ensureBindGroup(ctx, meshBuffer, labelPrefix + "line-positions-bind-group", lineBindGroupLayout, entries);
6922
+ PassUtils.setBindGroup(pass, positionsGroup, bindGroup);
6636
6923
  };
6637
6924
  this._bindLineMaterial = (pass, ...buffers) => {
6638
6925
  const meshBuffer = buffers.at(0);
6639
6926
  if (Utils24.isNull(meshBuffer)) {
6640
6927
  throw new ReferenceError(`Null ${RenderableBuffers.name} bringing vertex colors was provided.`);
6641
6928
  }
6642
- const vertexColorsBuffer = meshBuffer.buffer(ctx, "material"), vertexColorsBufferBuffer = vertexColorsBuffer.buffer;
6643
- PipelineUtils.writeBufferConditionally(device, vertexColorsBuffer);
6644
- const bindGroup = this._ensureLineMaterialBindGroup(meshBuffer.item, vertexColorsBufferBuffer, vertexColorsBuffer.fresh, materialGroupIndex);
6645
- pass.setBindGroup(materialGroupIndex, bindGroup);
6929
+ const material = meshBuffer.buffer(ctx, "material");
6930
+ const bindGroup = cache.ensureBindGroup(ctx, material, labelPrefix + "line-material-bind-group", materialBindGroupLayout, [
6931
+ { binding: STORAGE_MATERIAL_INDEX, buffer: material.buffer }
6932
+ ]);
6933
+ PassUtils.setBindGroup(pass, materialGroupIndex, bindGroup);
6646
6934
  };
6647
6935
  this._bindLinePicker = (pass, ...buffers) => {
6648
6936
  const meshBuffer = buffers.at(0);
6649
6937
  if (Utils24.isNull(meshBuffer)) {
6650
6938
  throw new ReferenceError(`Null ${RenderableBuffers.name} bringing world transform buffer was provided.`);
6651
6939
  }
6652
- const u32id = meshBuffer.buffer(ctx, "u32id"), u32idBuffer = u32id.buffer, u32idArray = u32id.value;
6653
- PipelineUtils.writeBufferConditionally(device, u32id);
6654
- const bindGroup = this._ensureLineU32idBindGroup(
6655
- meshBuffer.item,
6656
- u32idBuffer,
6657
- /* reuse */
6658
- false
6659
- /*u32id.fresh*/
6660
- );
6661
- pass.setBindGroup(raycastLayoutIndex, bindGroup);
6940
+ const { buffer } = meshBuffer.buffer(ctx, "u32id");
6941
+ const bindGroup = cache.ensureBindGroup(ctx, meshBuffer, labelPrefix + "line-colorpick-bind-group", pickFragGroupLayout, [
6942
+ { binding: 0, buffer }
6943
+ ]);
6944
+ PassUtils.setBindGroup(pass, raycastLayoutIndex, bindGroup);
6662
6945
  };
6663
6946
  this._drawLine = (pass, ...buffers) => {
6664
6947
  const meshBuffer = buffers.at(0);
@@ -6707,17 +6990,27 @@ var Raycasters = class {
6707
6990
  }
6708
6991
  };
6709
6992
  var NUM_PIXELS = 1;
6993
+ var BYTES_PER_ROW = Math.ceil(NUM_PIXELS * 4 / 256) * 256;
6994
+ function clampToPixel(coordinate, size) {
6995
+ const floored = Math.floor(coordinate ?? 0);
6996
+ const nonNegative = Math.max(0, floored);
6997
+ return Math.min(size - 1, nonNegative);
6998
+ }
6999
+ function clampToTextureSize(size, max) {
7000
+ const bounded = Math.min(max, size);
7001
+ return Math.max(1, bounded);
7002
+ }
6710
7003
  var ColorPickingRaycaster = class {
6711
7004
  constructor(_context) {
6712
7005
  this._context = _context;
6713
7006
  this._objects = /* @__PURE__ */ new Map();
6714
- this.frame = (interaction, ...buffers) => {
7007
+ this._pixel = { x: 0, y: 0 };
7008
+ this.frame = (pipeline, interaction, ...buffers) => {
6715
7009
  if (Utils25.isNull(this._encoder)) {
6716
7010
  throw new Error("Null encoder. Maybe you missed to call the 'begin' method first.");
6717
7011
  }
6718
7012
  const objects = Array.from(buffers);
6719
- const pipeline = RenderPipelines.createColorPicking(this._context, objects);
6720
- pipeline?.frame(this._pass, interaction, ...buffers);
7013
+ pipeline?.raycast?.(this._pass, interaction, ...buffers);
6721
7014
  for (let buffer of objects) {
6722
7015
  const item = buffer.item;
6723
7016
  if (item.inert) {
@@ -6732,21 +7025,23 @@ var ColorPickingRaycaster = class {
6732
7025
  }
6733
7026
  const pass = this._pass;
6734
7027
  const commandEncoder = this._encoder;
7028
+ if (Utils25.isNull(commandEncoder)) {
7029
+ return Promise.resolve([]);
7030
+ }
6735
7031
  const { device } = this._context;
6736
7032
  const { render } = this._textures;
6737
7033
  const pickTexture = render.texture;
6738
7034
  const pickBuffer = this._ensureBuffer();
6739
7035
  pass.end();
7036
+ this._pass = null;
7037
+ const { x, y } = this._pixel;
6740
7038
  commandEncoder.copyTextureToBuffer({
6741
7039
  texture: pickTexture,
6742
7040
  // mipLevel: 0,
6743
- origin: {
6744
- x: pixel.x,
6745
- y: pixel.y
6746
- }
7041
+ origin: { x, y }
6747
7042
  }, {
6748
7043
  buffer: pickBuffer,
6749
- bytesPerRow: (NUM_PIXELS * 4 + 255 | 0) * 256,
7044
+ bytesPerRow: BYTES_PER_ROW,
6750
7045
  rowsPerImage: 1
6751
7046
  }, {
6752
7047
  width: NUM_PIXELS
@@ -6772,13 +7067,17 @@ var ColorPickingRaycaster = class {
6772
7067
  } else {
6773
7068
  resolve([buffer.item]);
6774
7069
  }
7070
+ }, (_2) => {
7071
+ resetHandle();
7072
+ resolve([]);
6775
7073
  });
6776
7074
  });
6777
7075
  };
6778
7076
  }
6779
7077
  _createTexture(format) {
6780
7078
  const { device, canvas } = this._context;
6781
- const width = Math.min(device.limits.maxTextureDimension2D, canvas.clientWidth), height = Math.min(device.limits.maxTextureDimension2D, canvas.clientHeight);
7079
+ const maxSize = device.limits.maxTextureDimension2D;
7080
+ const width = clampToTextureSize(canvas.width, maxSize), height = clampToTextureSize(canvas.height, maxSize);
6782
7081
  return device.createTexture({
6783
7082
  size: [width, height, 1],
6784
7083
  format,
@@ -6826,10 +7125,16 @@ var ColorPickingRaycaster = class {
6826
7125
  this._buffer = null;
6827
7126
  }
6828
7127
  }
6829
- begin() {
7128
+ get pending() {
7129
+ return this._handle ?? null;
7130
+ }
7131
+ begin(pixel) {
6830
7132
  const { device } = this._context;
6831
7133
  this._encoder = device.createCommandEncoder({ label: LABEL_PREFIX + "colorpick-raycaster" });
6832
7134
  const { render, depth } = this._ensureTextures();
7135
+ const { width, height } = render.texture;
7136
+ const x = clampToPixel(pixel?.x, width), y = clampToPixel(pixel?.y, height);
7137
+ this._pixel = { x, y };
6833
7138
  const passDescriptor = {
6834
7139
  label: LABEL_PREFIX + "colorpick-raycaster-pass",
6835
7140
  colorAttachments: [
@@ -6849,10 +7154,125 @@ var ColorPickingRaycaster = class {
6849
7154
  }
6850
7155
  };
6851
7156
  this._pass = this._encoder.beginRenderPass(passDescriptor);
7157
+ this._pass.setScissorRect(x, y, 1, 1);
6852
7158
  this._objects.clear();
6853
7159
  }
6854
7160
  };
6855
7161
 
7162
+ // packages/3d/dist/esm/adapters/webgpu/abuffer.js
7163
+ import { Utils as Utils26 } from "@pacem/pacem-core";
7164
+ var FRAGMENT_SIZE = 12;
7165
+ var ABuffers = class _ABuffers {
7166
+ static {
7167
+ this._composites = /* @__PURE__ */ new WeakMap();
7168
+ }
7169
+ static _ensureComposite(ctx) {
7170
+ const existing = this._composites.get(ctx);
7171
+ if (!Utils26.isNull(existing)) {
7172
+ return existing;
7173
+ }
7174
+ const { device, format } = ctx;
7175
+ const layout = device.createBindGroupLayout({
7176
+ label: LABEL_PREFIX + "abuffer-composite-bind-group-layout",
7177
+ entries: [
7178
+ { binding: 0, visibility: GPUShaderStage.FRAGMENT, buffer: { type: "read-only-storage" } },
7179
+ { binding: 1, visibility: GPUShaderStage.FRAGMENT, buffer: { type: "read-only-storage" } },
7180
+ { binding: 2, visibility: GPUShaderStage.FRAGMENT, buffer: { type: "uniform" } }
7181
+ ]
7182
+ });
7183
+ const code = getABufferCompositeWgsl();
7184
+ const module = device.createShaderModule({ label: LABEL_PREFIX + "abuffer-composite-shader", code });
7185
+ const pipelineLayout = device.createPipelineLayout({ label: LABEL_PREFIX + "abuffer-composite-pipeline-layout", bindGroupLayouts: [layout] });
7186
+ const pipeline = device.createRenderPipeline({
7187
+ label: LABEL_PREFIX + "abuffer-composite-pipeline",
7188
+ layout: pipelineLayout,
7189
+ vertex: { module, entryPoint: "vertexMain" },
7190
+ fragment: {
7191
+ module,
7192
+ entryPoint: "fragmentMain",
7193
+ targets: [{
7194
+ format,
7195
+ // the composite outputs premultiplied colors
7196
+ blend: {
7197
+ color: { srcFactor: "one", dstFactor: "one-minus-src-alpha" },
7198
+ alpha: { srcFactor: "one", dstFactor: "one-minus-src-alpha" }
7199
+ }
7200
+ }]
7201
+ },
7202
+ primitive: { topology: "triangle-list" }
7203
+ });
7204
+ const state = { pipeline, layout };
7205
+ this._composites.set(ctx, state);
7206
+ return state;
7207
+ }
7208
+ /** Fragment list capacity: {@link ABUFFER_AVERAGE_LAYERS} per pixel, within the device storage/buffer size limits. */
7209
+ static _capacity(device, pixels) {
7210
+ const limits = device.limits;
7211
+ const maxBytes = Math.min(limits.maxStorageBufferBindingSize, limits.maxBufferSize);
7212
+ const maxFragments = Math.floor(maxBytes / FRAGMENT_SIZE);
7213
+ const wanted = ABUFFER_AVERAGE_LAYERS * pixels;
7214
+ const capacity = Math.min(wanted, maxFragments);
7215
+ return Math.max(1, capacity);
7216
+ }
7217
+ /** Forgets the composite pipeline built for `ctx` (e.g. on dispose). */
7218
+ static dispose(ctx) {
7219
+ this._composites.delete(ctx);
7220
+ }
7221
+ /**
7222
+ * Creates the A-buffer resources for a `width`×`height` render target.
7223
+ * @param ctx WebGPU context.
7224
+ * @param depth View of the opaque (multisampled) depth texture the translucent fragments get tested against.
7225
+ */
7226
+ static create(ctx, depth, width, height) {
7227
+ const { device } = ctx;
7228
+ const { pipeline, layout } = this._ensureComposite(ctx);
7229
+ const pixels = Math.max(1, width * height);
7230
+ const capacity = _ABuffers._capacity(device, pixels);
7231
+ const heads = device.createBuffer({
7232
+ label: LABEL_PREFIX + "abuffer-heads-buffer",
7233
+ size: 4 * (pixels + 1),
7234
+ usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_DST
7235
+ });
7236
+ const list = device.createBuffer({
7237
+ label: LABEL_PREFIX + "abuffer-list-buffer",
7238
+ size: FRAGMENT_SIZE * capacity,
7239
+ usage: GPUBufferUsage.STORAGE
7240
+ });
7241
+ const infoValue = new Uint32Array([width, height, capacity, 0]);
7242
+ const info = Buffers.createUniform(device, infoValue, LABEL_PREFIX + "abuffer-info-buffer");
7243
+ const bindGroup = device.createBindGroup({
7244
+ label: LABEL_PREFIX + "abuffer-composite-bind-group",
7245
+ layout,
7246
+ entries: [
7247
+ { binding: 0, resource: { buffer: heads } },
7248
+ { binding: 1, resource: { buffer: list } },
7249
+ { binding: 2, resource: { buffer: info } }
7250
+ ]
7251
+ });
7252
+ return {
7253
+ heads,
7254
+ list,
7255
+ info,
7256
+ depth,
7257
+ width,
7258
+ height,
7259
+ clear: (encoder) => {
7260
+ encoder.clearBuffer(heads);
7261
+ },
7262
+ composite: (pass) => {
7263
+ pass.setPipeline(pipeline);
7264
+ pass.setBindGroup(0, bindGroup);
7265
+ pass.draw(3);
7266
+ },
7267
+ destroy: () => {
7268
+ heads.destroy();
7269
+ list.destroy();
7270
+ info.destroy();
7271
+ }
7272
+ };
7273
+ }
7274
+ };
7275
+
6856
7276
  // packages/3d/dist/esm/adapters/webgpu/renderer.js
6857
7277
  var Vector3D3 = Geometry8.LinearAlgebra.Vector3D;
6858
7278
  var WebGPUIssueCause;
@@ -6905,6 +7325,102 @@ function destroyTextures(...textures) {
6905
7325
  tex?.destroy();
6906
7326
  }
6907
7327
  }
7328
+ function isResolvedFor(resolved, material, texture, geometry, lightsSignature) {
7329
+ if (Utils27.isNull(resolved)) {
7330
+ return false;
7331
+ }
7332
+ if (resolved.material !== material || resolved.texture !== texture) {
7333
+ return false;
7334
+ }
7335
+ return resolved.geometry === geometry && resolved.lights === lightsSignature;
7336
+ }
7337
+ function isABufferFor(aBuffer, depthView, width, height) {
7338
+ if (Utils27.isNull(aBuffer) || aBuffer.depth !== depthView) {
7339
+ return false;
7340
+ }
7341
+ return aBuffer.width === width && aBuffer.height === height;
7342
+ }
7343
+ function destroyMissing(previous, current) {
7344
+ const alive = new Set(current);
7345
+ for (let buffer of previous) {
7346
+ if (alive.has(buffer)) {
7347
+ continue;
7348
+ }
7349
+ buffer.destroy();
7350
+ }
7351
+ }
7352
+ function createOrYieldManaged(store, item) {
7353
+ const found = store.get(item);
7354
+ if (!Utils27.isNull(found) && !found.disposed) {
7355
+ return found;
7356
+ }
7357
+ const created = ManagedBuffers.create(item);
7358
+ store.set(item, created);
7359
+ return created;
7360
+ }
7361
+ function isTranslucent(mesh, pipeline) {
7362
+ if (Utils27.isNull(pipeline.translucent)) {
7363
+ return false;
7364
+ }
7365
+ if (!isMeshGeometry(mesh.geometry)) {
7366
+ return false;
7367
+ }
7368
+ return Materials.isTranslucent(mesh.material);
7369
+ }
7370
+ var objectIds = /* @__PURE__ */ new WeakMap();
7371
+ var lastObjectId = 0;
7372
+ function objectId(obj) {
7373
+ if (Utils27.isNull(obj)) {
7374
+ return 0;
7375
+ }
7376
+ const existing = objectIds.get(obj);
7377
+ if (!Utils27.isNull(existing)) {
7378
+ return existing;
7379
+ }
7380
+ const id = ++lastObjectId;
7381
+ objectIds.set(obj, id);
7382
+ return id;
7383
+ }
7384
+ function recipeOf(mesh) {
7385
+ const material = mesh.material;
7386
+ const kind = isMeshGeometry(mesh.geometry) ? "mesh" : "line";
7387
+ const shader = material?.shader ?? "";
7388
+ const map = material?.texture ? "-map" : "";
7389
+ const fat = material?.lineWidth > 1 ? "-fat" : "";
7390
+ return kind + "-" + shader + map + fat;
7391
+ }
7392
+ function drawOrderKey(buffer) {
7393
+ const mesh = buffer.item, material = mesh.material;
7394
+ return {
7395
+ translucent: Materials.isTranslucent(material),
7396
+ recipe: recipeOf(mesh),
7397
+ material: objectId(material),
7398
+ geometry: objectId(mesh.geometry)
7399
+ };
7400
+ }
7401
+ function compareDrawOrder(a, b) {
7402
+ if (a.translucent !== b.translucent) {
7403
+ return a.translucent ? 1 : -1;
7404
+ }
7405
+ if (a.translucent) {
7406
+ return 0;
7407
+ }
7408
+ if (a.recipe !== b.recipe) {
7409
+ return a.recipe < b.recipe ? -1 : 1;
7410
+ }
7411
+ if (a.material !== b.material) {
7412
+ return a.material - b.material;
7413
+ }
7414
+ return a.geometry - b.geometry;
7415
+ }
7416
+ function sortForDrawing(meshes) {
7417
+ const entries = meshes.map((m) => [m, drawOrderKey(m)]);
7418
+ const keys = new Map(entries);
7419
+ meshes.sort((a, b) => {
7420
+ const ka = keys.get(a), kb = keys.get(b);
7421
+ return compareDrawOrder(ka, kb);
7422
+ });
7423
+ }
6908
7424
  var RendererClass = class {
6909
7425
  #stage;
6910
7426
  #canvas;
@@ -6912,6 +7428,8 @@ var RendererClass = class {
6912
7428
  #renderables;
6913
7429
  #geometries;
6914
7430
  #materials;
7431
+ #pipelines;
7432
+ #pipelineOptions;
6915
7433
  #looper;
6916
7434
  #textures;
6917
7435
  #config;
@@ -6924,20 +7442,27 @@ var RendererClass = class {
6924
7442
  this.#renderables = /* @__PURE__ */ new WeakMap();
6925
7443
  this.#geometries = /* @__PURE__ */ new WeakMap();
6926
7444
  this.#materials = /* @__PURE__ */ new WeakMap();
7445
+ this.#pipelines = /* @__PURE__ */ new WeakMap();
7446
+ this.#pipelineOptions = { multisample: true };
6927
7447
  this.#config = { enableValidation: false };
6928
7448
  this.#disabled = false;
6929
7449
  this._logError = (evt) => {
6930
- const stage2 = this.#stage, logger = stage2.logger;
6931
- if (!Utils26.isNull(logger)) {
6932
- const error = "error" in evt ? evt.error : evt;
6933
- logger.log(Logging2.LogLevel.Error, error.message, "WebGPU");
6934
- }
7450
+ const error = "error" in evt ? evt.error : evt;
7451
+ this._log(error.message);
6935
7452
  };
6936
7453
  this.#rebuildingContext = true;
7454
+ this.#lost = false;
7455
+ this._onDeviceLost = (info) => {
7456
+ if (info.reason === "destroyed") {
7457
+ return;
7458
+ }
7459
+ this.#lost = true;
7460
+ this._log(`WebGPU device lost: ${info.message}`);
7461
+ };
6937
7462
  this.#hasModifiers = false;
6938
7463
  const wrapper = (this.#stage = stage).stage;
6939
7464
  const canvas = document.createElement("canvas");
6940
- canvas.id = P17 + "_3d_stage_" + Utils26.uniqueCode();
7465
+ canvas.id = P17 + "_3d_stage_" + Utils27.uniqueCode();
6941
7466
  wrapper.innerHTML = "";
6942
7467
  wrapper.appendChild(this.#canvas = canvas);
6943
7468
  this.#interactionBuffer = ManagedBuffers.create(this.#interaction = {
@@ -6950,7 +7475,7 @@ var RendererClass = class {
6950
7475
  const { context, device } = this.#context;
6951
7476
  const canvasTexture = context.getCurrentTexture();
6952
7477
  let textures = this.#textures;
6953
- if (Utils26.isNull(textures)) {
7478
+ if (Utils27.isNull(textures)) {
6954
7479
  textures = {};
6955
7480
  if (multisample) {
6956
7481
  const renderTex = device.createTexture({
@@ -6967,7 +7492,8 @@ var RendererClass = class {
6967
7492
  const depthTex = device.createTexture({
6968
7493
  label: LABEL_PREFIX + "depth-texture",
6969
7494
  format: "depth24plus",
6970
- usage: GPUTextureUsage.RENDER_ATTACHMENT,
7495
+ // also read by the A-buffer translucent pass (manual depth test)
7496
+ usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.TEXTURE_BINDING,
6971
7497
  size: [canvasTexture.width, canvasTexture.height],
6972
7498
  sampleCount: 4
6973
7499
  });
@@ -6998,72 +7524,180 @@ var RendererClass = class {
6998
7524
  view: depthTexView,
6999
7525
  depthClearValue: 1,
7000
7526
  depthLoadOp: "clear",
7001
- depthStoreOp: "store",
7002
- stencilClearValue: 0,
7003
- stencilReadOnly: true
7527
+ depthStoreOp: "store"
7004
7528
  };
7005
7529
  colorAttachment.view = renderTexView;
7006
7530
  colorAttachment.resolveTarget = canvasTexView;
7007
7531
  }
7008
- return passDescriptor;
7532
+ return {
7533
+ descriptor: passDescriptor,
7534
+ canvasView: canvasTexView,
7535
+ depthView: multisample ? textures.depth.view : null,
7536
+ width: canvasTexture.width,
7537
+ height: canvasTexture.height
7538
+ };
7009
7539
  }
7010
- _buildContext(canvas = this.#canvas, size = this.#stage.size) {
7540
+ /** Sizes the canvas (i.e. the render target) after `size` (or its current CSS box when omitted). */
7541
+ _applySize(canvas = this.#canvas, size = this.#stage.size) {
7011
7542
  size ??= canvas;
7012
- let w = size.width;
7013
- let h = size.height;
7014
7543
  const devicePixelRatio = 1;
7015
- canvas.width = w * devicePixelRatio;
7016
- canvas.height = h * devicePixelRatio;
7544
+ canvas.width = size.width * devicePixelRatio;
7545
+ canvas.height = size.height * devicePixelRatio;
7546
+ }
7547
+ _buildContext(canvas = this.#canvas, size = this.#stage.size) {
7548
+ this._applySize(canvas, size);
7017
7549
  const context = canvas.getContext("webgpu");
7018
7550
  const textureFormat = navigator.gpu.getPreferredCanvasFormat();
7019
7551
  return { context, textureFormat };
7020
7552
  }
7553
+ /** The canvas alpha mode matching the stage `transparent` flag. */
7554
+ _alphaMode() {
7555
+ return this.#stage.transparent ? "premultiplied" : "opaque";
7556
+ }
7557
+ #alphaMode;
7021
7558
  _buildUpContext(device, adapter, context, format) {
7022
- const { transparent } = this.#stage;
7559
+ const alphaMode = this._alphaMode();
7560
+ this.#alphaMode = alphaMode;
7023
7561
  context.configure({
7024
- alphaMode: transparent ? "premultiplied" : "opaque",
7562
+ alphaMode,
7025
7563
  device,
7026
7564
  format
7027
7565
  });
7028
7566
  this.#context = { device, adapter, canvas: this.#canvas, context, format };
7029
7567
  this.#rebuildingContext = false;
7030
7568
  }
7569
+ _log(message) {
7570
+ const stage = this.#stage, logger = stage.logger;
7571
+ if (!Utils27.isNull(logger)) {
7572
+ logger.log(Logging2.LogLevel.Error, message, "WebGPU");
7573
+ }
7574
+ }
7031
7575
  async init(config) {
7032
7576
  this.#config = config;
7577
+ this.#pipelineOptions = { multisample: true, modifiers: config.modifiers };
7033
7578
  const adapter = await navigator.gpu.requestAdapter();
7034
- if (Utils26.isNull(adapter)) {
7579
+ if (Utils27.isNull(adapter)) {
7035
7580
  throw new Error("WebGPU adapter unavalable or disabled.");
7036
7581
  }
7037
7582
  const device = await adapter.requestDevice();
7038
- if (Utils26.isNull(adapter)) {
7583
+ if (Utils27.isNull(device)) {
7039
7584
  throw new Error("WebGPU device unavalable or disabled.");
7040
7585
  }
7041
7586
  device.addEventListener("uncapturederror", this._logError);
7042
- this.#hasModifiers = !Utils26.isNull(config.modifiers?.version) && !Utils26.isNull(config.modifiers) && (!Utils26.isNull(config.modifiers.vertexInput) || !Utils26.isNull(config.modifiers.vertexOutput) || !Utils26.isNull(config.modifiers.fragment));
7587
+ 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));
7043
7589
  const { context, textureFormat: format } = this._buildContext();
7044
7590
  this._buildUpContext(device, adapter, context, format);
7045
7591
  }
7046
7592
  #rebuildingContext;
7593
+ /** Set when the {@link GPUDevice} gets lost (not destroyed on purpose): nothing can be rendered anymore. */
7594
+ #lost;
7047
7595
  /** Whether the renderer is affected by vertex or fragment modifiers.
7048
7596
  * When true, the renderer must provide updated time, cursor position and canvas size to the pipeline's bind groups.
7049
7597
  */
7050
7598
  #hasModifiers;
7599
+ /** Light types signature, part of the cache key of the pipelines resolved per mesh. */
7600
+ _lightsSignature(lights) {
7601
+ return lights.map((l) => l.item.type).join("-");
7602
+ }
7603
+ /**
7604
+ * Returns the {@link RenderPipeline} drawing `mesh`, reusing the one resolved in previous frames as long as its
7605
+ * material (and texture), geometry and the scene lights didn't change; otherwise goes through {@link RenderPipelines.create}
7606
+ * (which memoizes the built pipelines by recipe).
7607
+ */
7608
+ _resolvePipeline(mesh, camera, lights, lightsSignature) {
7609
+ const item = mesh.item, material = item.material, texture = material?.texture, geometry = item.geometry;
7610
+ const pipelines = this.#pipelines;
7611
+ const existing = pipelines.get(mesh);
7612
+ const reusable = isResolvedFor(existing, material, texture, geometry, lightsSignature);
7613
+ if (reusable) {
7614
+ if (material?.flags?.length > 0) {
7615
+ existing.translucent = isTranslucent(item, existing.pipeline);
7616
+ }
7617
+ return existing;
7618
+ }
7619
+ const pipeline = RenderPipelines.create(this.#context, [mesh, camera, ...lights], this.#pipelineOptions);
7620
+ const translucent = isTranslucent(item, pipeline);
7621
+ const resolved = { material, texture, geometry, lights: lightsSignature, pipeline, translucent };
7622
+ pipelines.set(mesh, resolved);
7623
+ return resolved;
7624
+ }
7625
+ #aBuffer;
7626
+ /** Returns the A-buffer matching the current render targets, (re)creating it when needed. */
7627
+ _ensureABuffer(depthView, width, height) {
7628
+ const current = this.#aBuffer;
7629
+ if (isABufferFor(current, depthView, width, height)) {
7630
+ return current;
7631
+ }
7632
+ current?.destroy();
7633
+ const aBuffer = ABuffers.create(this.#context, depthView, width, height);
7634
+ this.#aBuffer = aBuffer;
7635
+ return aBuffer;
7636
+ }
7637
+ /** Whether a frame can be rendered: context ready, device alive, scene set and a non-empty render target. */
7638
+ _canRender() {
7639
+ if (this.#rebuildingContext || this.#lost || Utils27.isNull(this.#looper)) {
7640
+ return false;
7641
+ }
7642
+ const canvas = this.#canvas;
7643
+ return canvas.width > 0 && canvas.height > 0;
7644
+ }
7645
+ /** Pops a validation error scope, logging the error it caught (if any). */
7646
+ _popValidationScope(device) {
7647
+ const popped = device.popErrorScope();
7648
+ popped.then((error) => {
7649
+ if (Utils27.isNull(error)) {
7650
+ return;
7651
+ }
7652
+ this._logError(error);
7653
+ });
7654
+ }
7655
+ /** Ends the translucent pass, encodes the composite one onto the canvas and returns the A-buffer commands. */
7656
+ _finishTranslucent({ encoder, pass, aBuffer }, canvasView) {
7657
+ pass.end();
7658
+ const compositePass = encoder.beginRenderPass({
7659
+ label: LABEL_PREFIX + "abuffer-composite-pass",
7660
+ colorAttachments: [{ view: canvasView, loadOp: "load", storeOp: "store" }]
7661
+ });
7662
+ aBuffer.composite(compositePass);
7663
+ compositePass.end();
7664
+ return encoder.finish();
7665
+ }
7051
7666
  /**
7052
7667
  * Render procedure.
7053
7668
  */
7054
7669
  render(interaction) {
7055
- if (this.#rebuildingContext || Utils26.isNull(this.#looper) || !(this.#canvas.width > 0) || !(this.#canvas.height > 0)) {
7670
+ if (!this._canRender()) {
7056
7671
  return;
7057
7672
  }
7058
7673
  const context = this.#context, device = context.device, looper = this.#looper;
7059
7674
  const validationScope = this.#config?.enableValidation ?? false;
7060
7675
  if (this.#hasModifiers) {
7061
- Utils26.extend(this.#interaction, interaction);
7676
+ Utils27.extend(this.#interaction, interaction);
7062
7677
  }
7063
7678
  const multisample = true;
7064
- const passDescriptor = this._buildPassDescriptor({ multisample });
7679
+ const { descriptor: passDescriptor, canvasView, depthView, width, height } = this._buildPassDescriptor({ multisample });
7680
+ const transparency = this.#config?.transparency ?? "a-buffer";
7681
+ const aBufferMode = transparency === "a-buffer" && !Utils27.isNull(depthView);
7065
7682
  const commandEncoder = device.createCommandEncoder({ label: LABEL_PREFIX + "renderer" });
7066
7683
  const pass = commandEncoder.beginRenderPass(passDescriptor);
7684
+ const lightsSignature = this._lightsSignature(looper.items.lights);
7685
+ let translucent = null;
7686
+ const ensureTranslucentPass = () => {
7687
+ if (!Utils27.isNull(translucent)) {
7688
+ return translucent;
7689
+ }
7690
+ const aBuffer = this._ensureABuffer(depthView, width, height);
7691
+ const encoder = device.createCommandEncoder({ label: LABEL_PREFIX + "abuffer" });
7692
+ aBuffer.clear(encoder);
7693
+ const translucentPass = encoder.beginRenderPass({
7694
+ label: LABEL_PREFIX + "abuffer-translucent-pass",
7695
+ colorAttachments: [],
7696
+ depthStencilAttachment: { view: depthView, depthReadOnly: true }
7697
+ });
7698
+ translucent = { encoder, pass: translucentPass, aBuffer };
7699
+ return translucent;
7700
+ };
7067
7701
  looper.loop((mesh, camera, lights) => {
7068
7702
  if (mesh.item.hide) {
7069
7703
  return false;
@@ -7071,20 +7705,26 @@ var RendererClass = class {
7071
7705
  if (validationScope) {
7072
7706
  device.pushErrorScope("validation");
7073
7707
  }
7074
- const renderables = [mesh, camera, ...lights];
7075
- const pipeline = RenderPipelines.create(context, renderables, { multisample: true, modifiers: this.#config.modifiers });
7076
- pipeline.frame(pass, this.#interactionBuffer, ...renderables);
7708
+ const resolved = this._resolvePipeline(mesh, camera, lights, lightsSignature);
7709
+ if (aBufferMode && resolved.translucent) {
7710
+ const { pass: translucentPass, aBuffer } = ensureTranslucentPass();
7711
+ resolved.pipeline.translucent(translucentPass, this.#interactionBuffer, aBuffer, mesh, camera, ...lights);
7712
+ } else {
7713
+ resolved.pipeline.frame(pass, this.#interactionBuffer, mesh, camera, ...lights);
7714
+ }
7077
7715
  if (validationScope) {
7078
- device.popErrorScope().then((error) => {
7079
- if (error) {
7080
- this._logError(error);
7081
- }
7082
- });
7716
+ this._popValidationScope(device);
7083
7717
  }
7084
7718
  return true;
7085
7719
  });
7086
7720
  pass.end();
7087
- device.queue.submit([commandEncoder.finish()]);
7721
+ const opaqueCommands = commandEncoder.finish();
7722
+ if (Utils27.isNull(translucent)) {
7723
+ device.queue.submit([opaqueCommands]);
7724
+ return;
7725
+ }
7726
+ const translucentCommands = this._finishTranslucent(translucent, canvasView);
7727
+ device.queue.submit([opaqueCommands, translucentCommands]);
7088
7728
  }
7089
7729
  set disabled(v) {
7090
7730
  this.#disabled = v;
@@ -7093,27 +7733,29 @@ var RendererClass = class {
7093
7733
  return this.#disabled;
7094
7734
  }
7095
7735
  raycast(pixel) {
7096
- if (this.#rebuildingContext || Utils26.isNull(this.#looper)) {
7736
+ if (this.#rebuildingContext || this.#lost || Utils27.isNull(this.#looper)) {
7097
7737
  return Promise.resolve([]);
7098
7738
  }
7099
7739
  const context = this.#context, device = context.device, looper = this.#looper;
7100
- const validationScope = this.#config?.enableValidation ?? false;
7101
7740
  const raycaster = Raycasters.createColorPicking(context);
7102
- raycaster.begin();
7103
- looper.loop((mesh, camera) => {
7741
+ const pending = raycaster.pending;
7742
+ if (!Utils27.isNull(pending)) {
7743
+ return pending;
7744
+ }
7745
+ const validationScope = this.#config?.enableValidation ?? false;
7746
+ raycaster.begin(pixel);
7747
+ const lightsSignature = this._lightsSignature(looper.items.lights);
7748
+ looper.loop((mesh, camera, lights) => {
7104
7749
  if (mesh.item.hide) {
7105
7750
  return false;
7106
7751
  }
7107
7752
  if (validationScope) {
7108
7753
  device.pushErrorScope("validation");
7109
7754
  }
7110
- raycaster.frame(this.#interactionBuffer, mesh, camera);
7755
+ const { pipeline } = this._resolvePipeline(mesh, camera, lights, lightsSignature);
7756
+ raycaster.frame(pipeline, this.#interactionBuffer, mesh, camera);
7111
7757
  if (validationScope) {
7112
- device.popErrorScope().then((error) => {
7113
- if (error) {
7114
- this._logError(error);
7115
- }
7116
- });
7758
+ this._popValidationScope(device);
7117
7759
  }
7118
7760
  return true;
7119
7761
  });
@@ -7126,30 +7768,23 @@ var RendererClass = class {
7126
7768
  store.delete(item);
7127
7769
  }
7128
7770
  }
7129
- _createOrYieldRenderable(item, geometries = this.#geometries, materials = this.#materials) {
7771
+ _createOrYieldRenderable(item) {
7130
7772
  item.stage ??= this.#stage;
7131
7773
  const store = this.#renderables;
7132
- let found = store.get(item);
7133
- if (Utils26.isNull(found)) {
7134
- store.set(item, found = RenderableBuffers.create(item, geometries));
7774
+ const found = store.get(item);
7775
+ const usable = !Utils27.isNull(found) && !found.disposed && Utils27.isNull(found.parent);
7776
+ if (usable) {
7777
+ return found;
7135
7778
  }
7136
- return found;
7779
+ const created = RenderableBuffers.create(item, this.#geometries, this.#materials, store);
7780
+ store.set(item, created);
7781
+ return created;
7137
7782
  }
7138
7783
  _createOrYieldGeometry(item) {
7139
- const store = this.#geometries;
7140
- let found = store.get(item);
7141
- if (Utils26.isNull(found)) {
7142
- store.set(item, found = ManagedBuffers.create(item));
7143
- }
7144
- return found;
7784
+ return createOrYieldManaged(this.#geometries, item);
7145
7785
  }
7146
7786
  _createOrYieldMaterial(item) {
7147
- const store = this.#materials;
7148
- let found = store.get(item);
7149
- if (Utils26.isNull(found)) {
7150
- store.set(item, found = ManagedBuffers.create(item));
7151
- }
7152
- return found;
7787
+ return createOrYieldManaged(this.#materials, item);
7153
7788
  }
7154
7789
  _unwrapBuffers(grp, accumulator) {
7155
7790
  accumulator ??= { meshes: [], lights: [], cameras: [], groups: [] };
@@ -7171,6 +7806,15 @@ var RendererClass = class {
7171
7806
  }
7172
7807
  return accumulator;
7173
7808
  }
7809
+ /** Destroys the buffers of `previous` not taking part in `current` anymore (removed/replaced items). */
7810
+ _destroyLeftovers(previous, current) {
7811
+ if (Utils27.isNull(previous)) {
7812
+ return;
7813
+ }
7814
+ for (let category of ["meshes", "lights", "cameras", "groups"]) {
7815
+ destroyMissing(previous[category], current[category]);
7816
+ }
7817
+ }
7174
7818
  _update(array) {
7175
7819
  const groupBuffers = [];
7176
7820
  const meshBuffers = [];
@@ -7192,7 +7836,7 @@ var RendererClass = class {
7192
7836
  }
7193
7837
  if (isMesh(item) && item.geometry) {
7194
7838
  this._createOrYieldGeometry(item.geometry);
7195
- if (!Utils26.isNull(item.material)) {
7839
+ if (!Utils27.isNull(item.material)) {
7196
7840
  this._createOrYieldMaterial(item.material);
7197
7841
  }
7198
7842
  meshBuffers.push(factory(item));
@@ -7215,50 +7859,69 @@ var RendererClass = class {
7215
7859
  for (let groupBuffer of groupBuffers) {
7216
7860
  accumulator = this._unwrapBuffers(groupBuffer, accumulator);
7217
7861
  }
7218
- this.#looper?.items.meshes.forEach((buffer) => {
7219
- if (!meshBuffers.includes(buffer)) {
7220
- buffer.destroy();
7221
- }
7222
- });
7862
+ sortForDrawing(accumulator.meshes);
7863
+ this._destroyLeftovers(this.#looper?.items, accumulator);
7223
7864
  this.#looper = new RenderLooper(accumulator);
7224
7865
  }
7225
7866
  update(...items) {
7226
7867
  this._update(Array.from(items));
7227
7868
  }
7228
7869
  dispose() {
7870
+ const looper = this.#looper;
7229
7871
  this.#looper = null;
7230
- if (this._disposeContext()) {
7231
- const { device } = this.#context;
7232
- device.removeEventListener("uncapturederror", this._logError);
7233
- device.destroy;
7872
+ this._destroyLeftovers(looper?.items, { meshes: [], lights: [], cameras: [], groups: [] });
7873
+ this.#interactionBuffer?.destroy();
7874
+ if (!this._disposeContext()) {
7875
+ return;
7876
+ }
7877
+ const { device } = this.#context;
7878
+ device.removeEventListener("uncapturederror", this._logError);
7879
+ device.destroy();
7880
+ }
7881
+ _destroyRenderTargets() {
7882
+ const aBuffer = this.#aBuffer;
7883
+ this.#aBuffer = null;
7884
+ aBuffer?.destroy();
7885
+ const textures = this.#textures;
7886
+ this.#textures = null;
7887
+ if (!Utils27.isNull(textures)) {
7888
+ const { render, depth } = textures;
7889
+ destroyTextures(render?.texture, depth?.texture);
7234
7890
  }
7235
7891
  }
7236
7892
  _disposeContext() {
7237
7893
  const ctx = this.#context;
7238
- if (Utils26.isNull(ctx)) {
7894
+ if (Utils27.isNull(ctx)) {
7239
7895
  return false;
7240
7896
  }
7241
7897
  Raycasters.dispose(ctx);
7242
7898
  RenderPipelines.dispose(ctx);
7243
- const textures = this.#textures;
7244
- this.#textures = null;
7245
- if (!Utils26.isNull(textures)) {
7246
- const { render, depth } = textures;
7247
- destroyTextures(render?.texture, depth?.texture);
7248
- }
7899
+ ABuffers.dispose(ctx);
7900
+ this._destroyRenderTargets();
7249
7901
  ctx.context.unconfigure();
7250
7902
  return true;
7251
7903
  }
7252
7904
  resize(size) {
7253
- this.#rebuildingContext = true;
7254
- if (this._disposeContext()) {
7255
- const { device, adapter } = this.#context;
7256
- const { context, textureFormat: format } = this._buildContext(this.canvas, size);
7257
- this._buildUpContext(device, adapter, context, format);
7258
- if (this.#hasModifiers) {
7259
- Utils26.extend(this.#interaction, { resolution: size });
7260
- }
7905
+ const ctx = this.#context;
7906
+ if (Utils27.isNull(ctx)) {
7907
+ return;
7908
+ }
7909
+ this._applySize(this.canvas, size);
7910
+ this._destroyRenderTargets();
7911
+ Raycasters.dispose(ctx);
7912
+ this._ensureAlphaMode(ctx);
7913
+ if (this.#hasModifiers) {
7914
+ Utils27.extend(this.#interaction, { resolution: size });
7915
+ }
7916
+ }
7917
+ /** `transparent` changes come through `resize`, too (see `Pacem3DElement`): reconfigures the canvas only when the alpha mode changes. */
7918
+ _ensureAlphaMode(ctx) {
7919
+ const alphaMode = this._alphaMode();
7920
+ if (alphaMode === this.#alphaMode) {
7921
+ return;
7261
7922
  }
7923
+ this.#alphaMode = alphaMode;
7924
+ ctx.context.configure({ alphaMode, device: ctx.device, format: ctx.format });
7262
7925
  }
7263
7926
  get canvas() {
7264
7927
  return this.#canvas;
@@ -7306,7 +7969,7 @@ var Pacem3DWgslScriptElement = class Pacem3DWgslScriptElement2 extends Component
7306
7969
  const old = this.#version;
7307
7970
  const val = v;
7308
7971
  this.#version = val;
7309
- const evt = new PropertyChangeEvent2({ propertyName: "version", oldValue: old, currentValue: val, firstChange: Utils27.isNullOrEmpty(old) });
7972
+ const evt = new PropertyChangeEvent2({ propertyName: "version", oldValue: old, currentValue: val, firstChange: Utils28.isNullOrEmpty(old) });
7310
7973
  this.dispatchEvent(evt);
7311
7974
  }
7312
7975
  });
@@ -7401,10 +8064,14 @@ var Pacem3DWebgpuAdapterElement = class Pacem3DWebgpuAdapterElement2 extends Pac
7401
8064
  if (!scenes.has(scene)) {
7402
8065
  scenes.add(scene);
7403
8066
  }
7404
- return Renderers.create(scene, { enableValidation: this.enableValidation ?? false, modifiers: this.modifiers }).then((renderer) => {
7405
- set.get(scene)?.update(
7406
- /* empty */
7407
- );
8067
+ const transparency = this.transparency === "blend" ? "blend" : "a-buffer";
8068
+ const config = { enableValidation: this.enableValidation ?? false, modifiers: this.modifiers, transparency };
8069
+ const creation = Renderers.create(scene, config);
8070
+ return creation.then((renderer) => {
8071
+ const previous = set.get(scene);
8072
+ if (previous !== renderer) {
8073
+ previous?.dispose();
8074
+ }
7408
8075
  set.set(scene, renderer);
7409
8076
  this._updatePipeline(scene);
7410
8077
  return renderer.canvas;
@@ -7427,6 +8094,7 @@ var Pacem3DWebgpuAdapterElement = class Pacem3DWebgpuAdapterElement2 extends Pac
7427
8094
  switch (name) {
7428
8095
  case "modifiers":
7429
8096
  case "enableValidation":
8097
+ case "transparency":
7430
8098
  this._reinitialize();
7431
8099
  break;
7432
8100
  }
@@ -7475,7 +8143,7 @@ var Pacem3DWebgpuAdapterElement = class Pacem3DWebgpuAdapterElement2 extends Pac
7475
8143
  return;
7476
8144
  }
7477
8145
  const renderer = this._ensureRenderer(scene);
7478
- if (Utils27.isNull(renderer)) {
8146
+ if (Utils28.isNull(renderer)) {
7479
8147
  return;
7480
8148
  }
7481
8149
  if (this.#sceneToUpdate.has(scene)) {
@@ -7488,15 +8156,15 @@ var Pacem3DWebgpuAdapterElement = class Pacem3DWebgpuAdapterElement2 extends Pac
7488
8156
  return;
7489
8157
  }
7490
8158
  const callback = GETVAL(scene, WEBGPU_RAYCAST_CALLBACK_PROP);
7491
- if (Utils27.isNullOrEmpty(callback)) {
8159
+ if (Utils28.isNullOrEmpty(callback)) {
7492
8160
  return;
7493
8161
  }
7494
- if (Utils27.isNullOrEmpty(pixel)) {
8162
+ if (Utils28.isNullOrEmpty(pixel)) {
7495
8163
  callback(null);
7496
8164
  return;
7497
8165
  }
7498
8166
  renderer.raycast(pixel).then((array) => {
7499
- if (Utils27.isNullOrEmpty(array)) {
8167
+ if (Utils28.isNullOrEmpty(array)) {
7500
8168
  callback(null);
7501
8169
  } else {
7502
8170
  const retval = {
@@ -7513,10 +8181,10 @@ var Pacem3DWebgpuAdapterElement = class Pacem3DWebgpuAdapterElement2 extends Pac
7513
8181
  return Promise.resolve(null);
7514
8182
  }
7515
8183
  const { canvas } = renderers.get(scene);
7516
- const jpeg = !Utils27.isNullOrEmpty(background), mime = type ?? (jpeg ? "image/jpeg" : null), compression = quality ?? (jpeg ? 0.9 : null);
8184
+ const jpeg = !Utils28.isNullOrEmpty(background), mime = type ?? (jpeg ? "image/jpeg" : null), compression = quality ?? (jpeg ? 0.9 : null);
7517
8185
  return new Promise((resolve, _) => {
7518
8186
  this.render(scene);
7519
- Utils27.snapshotElement(canvas, background, mime, compression).then(resolve);
8187
+ Utils28.snapshotElement(canvas, background, mime, compression).then(resolve);
7520
8188
  });
7521
8189
  }
7522
8190
  raycast(stage, point, size, callback) {
@@ -7540,7 +8208,7 @@ var Pacem3DWebgpuAdapterElement = class Pacem3DWebgpuAdapterElement2 extends Pac
7540
8208
  this._itemsChanged(stage, item);
7541
8209
  }
7542
8210
  updateItem(stage, item) {
7543
- if (Utils27.isNull(item) || item.flags.indexOf(StalePropertyFlag.Visibility) >= 0 || item.flags.indexOf(StalePropertyFlag.Children) >= 0) {
8211
+ if (Utils28.isNull(item) || item.flags.indexOf(StalePropertyFlag.Visibility) >= 0 || item.flags.indexOf(StalePropertyFlag.Children) >= 0) {
7544
8212
  this._itemsChanged(stage, item);
7545
8213
  }
7546
8214
  }
@@ -7563,12 +8231,15 @@ __decorate21([
7563
8231
  __decorate21([
7564
8232
  Watch18({ emit: false, converter: PropertyConverters18.Boolean })
7565
8233
  ], Pacem3DWebgpuAdapterElement.prototype, "enableValidation", void 0);
8234
+ __decorate21([
8235
+ Watch18({ emit: false, converter: PropertyConverters18.String })
8236
+ ], Pacem3DWebgpuAdapterElement.prototype, "transparency", void 0);
7566
8237
  Pacem3DWebgpuAdapterElement = __decorate21([
7567
8238
  CustomElement17({ tagName: P18 + "-3d-webgpu-adapter" })
7568
8239
  ], Pacem3DWebgpuAdapterElement);
7569
8240
 
7570
8241
  // packages/3d/dist/esm/adapters/webgpu/behaviors/orbit-camera.js
7571
- import { CustomElement as CustomElement18, P as P19, Watch as Watch19, PropertyConverters as PropertyConverters19, Utils as Utils28, CustomEventUtils as CustomEventUtils2, avoidHandler, Behaviors, PropertyChangeEventName as PropertyChangeEventName3 } from "@pacem/pacem-core";
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";
7572
8243
  import { Geometry as Geometry9 } from "@pacem/pacem-numerical";
7573
8244
  var __decorate22 = function(decorators, target, key, desc) {
7574
8245
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
@@ -7633,7 +8304,7 @@ var OrbitCameraBehavior = class _OrbitCameraBehavior {
7633
8304
  this.#rotating = rotating;
7634
8305
  if (this.#panning = panning) {
7635
8306
  this._currentState = _OrbitCameraBehavior._buildState(this._camera);
7636
- Utils28.extend(this._input, Vector3D4.zero());
8307
+ Utils29.extend(this._input, Vector3D4.zero());
7637
8308
  this._progress.x = this._progress.y = 0;
7638
8309
  }
7639
8310
  avoidHandler(evt);
@@ -7701,9 +8372,9 @@ var OrbitCameraBehavior = class _OrbitCameraBehavior {
7701
8372
  static tryAttach(element, config) {
7702
8373
  config ??= DEFAULT_CONFIGURATION;
7703
8374
  const canvas = findCameraStage(element)?.stage;
7704
- if (!Utils28.isNull(canvas)) {
8375
+ if (!Utils29.isNull(canvas)) {
7705
8376
  const { position, lookAt } = element;
7706
- if (Utils28.isNull(position) || Utils28.isNull(lookAt) || Vector3D4.areClose(position, lookAt)) {
8377
+ if (Utils29.isNull(position) || Utils29.isNull(lookAt) || Vector3D4.areClose(position, lookAt)) {
7707
8378
  return null;
7708
8379
  }
7709
8380
  return new _OrbitCameraBehavior(element, config);
@@ -7817,7 +8488,7 @@ var OrbitCameraBehavior = class _OrbitCameraBehavior {
7817
8488
  /** Detaches and removes handlers and resources. */
7818
8489
  dispose() {
7819
8490
  const canvas = this._canvas, scene = this._scene;
7820
- if (!Utils28.isNull(canvas)) {
8491
+ if (!Utils29.isNull(canvas)) {
7821
8492
  canvas.removeEventListener("pointerdown", this._startHandler);
7822
8493
  canvas.removeEventListener("wheel", this._zoomHandler);
7823
8494
  }
@@ -7863,7 +8534,7 @@ var PacemOrbitCameraBehaviorElement = class PacemOrbitCameraBehaviorElement2 ext
7863
8534
  super.disconnectedCallback();
7864
8535
  }
7865
8536
  _buildConfig() {
7866
- return Utils28.extend({}, DEFAULT_CONFIGURATION, {
8537
+ return Utils29.extend({}, DEFAULT_CONFIGURATION, {
7867
8538
  maxAzimuth: this.maxAzimuth ?? Infinity,
7868
8539
  minAzimuth: this.minAzimuth ?? -Infinity,
7869
8540
  minPolar: this.minPolar ?? -Infinity,
@@ -7876,7 +8547,7 @@ var PacemOrbitCameraBehaviorElement = class PacemOrbitCameraBehaviorElement2 ext
7876
8547
  }
7877
8548
  _decorateCore(element) {
7878
8549
  const behavior = OrbitCameraBehavior.tryAttach(element, this._buildConfig());
7879
- if (!Utils28.isNull(behavior)) {
8550
+ if (!Utils29.isNull(behavior)) {
7880
8551
  this.#map.set(element, behavior);
7881
8552
  }
7882
8553
  }