@pacem/pacem-3d 1.1.0-sierpinski → 2.0.0-babbage
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/browser/pacem-3d.js +1666 -892
- package/dist/browser/pacem-3d.js.map +1 -1
- package/dist/browser/pacem-3d.min.js +2 -2
- package/dist/bundle/pacem-3d.min.mjs +137 -46
- package/dist/bundle/pacem-3d.mjs +1563 -892
- package/dist/bundle/pacem-3d.mjs.map +4 -4
- package/dist/docs/pacem-3d.json +31 -0
- package/dist/esm/constants.js +1 -1
- package/dist/esm/converters.js +1 -1
- package/dist/esm/decorators.js +1 -1
- package/dist/esm/detector.js +1 -1
- package/dist/esm/geometry.js +1 -1
- package/dist/esm/index-components-drawing3d.js +1 -1
- package/dist/esm/index-components.js +1 -1
- package/dist/esm/index-drawing3d.js +1 -1
- package/dist/esm/index-iife.js +1 -1
- package/dist/esm/index-root.js +1 -1
- package/dist/esm/index.js +1 -1
- package/dist/esm/stage.js +1 -1
- package/dist/esm/types.js +1 -1
- package/package.json +1 -1
- package/typings/index.d.ts +12 -0
package/dist/browser/pacem-3d.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/*!
|
|
2
|
-
* @pacem/pacem-3d
|
|
2
|
+
* @pacem/pacem-3d v2.0.0-babbage (https://js.pacem.it)
|
|
3
3
|
* Pacem (https://pacem.it)
|
|
4
4
|
* Licensed under Apache-2.0
|
|
5
5
|
*/
|
|
@@ -3698,6 +3698,20 @@
|
|
|
3698
3698
|
/** WGSL identifier used to reference the accumulated (directional/omni) lighting contribution in generated fragment shader code. */
|
|
3699
3699
|
const LIGHTING_COLOR_REFERENCE = 'lighting';
|
|
3700
3700
|
// #endregion
|
|
3701
|
+
// #region A-buffer (order-independent transparency)
|
|
3702
|
+
/** `@binding` index (within {@link UNIFORM_GROUP_INDEX_CAMERA}) of the A-buffer per-pixel list heads (plus the fragment counter). */
|
|
3703
|
+
const ABUFFER_BINDING_INDEX_HEADS = 2;
|
|
3704
|
+
/** `@binding` index (within {@link UNIFORM_GROUP_INDEX_CAMERA}) of the A-buffer fragment (linked) list. */
|
|
3705
|
+
const ABUFFER_BINDING_INDEX_LIST = 3;
|
|
3706
|
+
/** `@binding` index (within {@link UNIFORM_GROUP_INDEX_CAMERA}) of the A-buffer info uniform (width, height, capacity). */
|
|
3707
|
+
const ABUFFER_BINDING_INDEX_INFO = 4;
|
|
3708
|
+
/** `@binding` index (within {@link UNIFORM_GROUP_INDEX_CAMERA}) of the opaque (multisampled) depth texture, used for the manual depth test. */
|
|
3709
|
+
const ABUFFER_BINDING_INDEX_DEPTH = 5;
|
|
3710
|
+
/** Average translucent layers per pixel the A-buffer fragment list is sized for: fragments beyond capacity are dropped. */
|
|
3711
|
+
const ABUFFER_AVERAGE_LAYERS = 4;
|
|
3712
|
+
/** Maximum translucent layers per pixel sorted and composited: deeper ones are dropped. */
|
|
3713
|
+
const ABUFFER_MAX_SORTED_LAYERS = 16;
|
|
3714
|
+
// #endregion
|
|
3701
3715
|
// #region WGSL
|
|
3702
3716
|
/** Name of the WGSL struct describing per-vertex input attributes, used by generated vertex shader code. */
|
|
3703
3717
|
const WGSL_VERTEXINPUT_STRUCT_NAME = 'VertexInput';
|
|
@@ -3755,12 +3769,24 @@
|
|
|
3755
3769
|
})(WGSLBindingType || (WGSLBindingType = {}));
|
|
3756
3770
|
|
|
3757
3771
|
//namespace Pacem.Drawing3D.WebGPU {
|
|
3772
|
+
/** Creates a {@link GPUBuffer} of the given `usage`, sized to `data` and populated with it via `mappedAtCreation`. */
|
|
3773
|
+
function createPopulated(device, data, usage, label) {
|
|
3774
|
+
const buffer = device.createBuffer({
|
|
3775
|
+
size: data.byteLength, label, usage,
|
|
3776
|
+
mappedAtCreation: true
|
|
3777
|
+
});
|
|
3778
|
+
const mappedRange = buffer.getMappedRange();
|
|
3779
|
+
const target = new Uint8Array(mappedRange);
|
|
3780
|
+
const source = new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
|
|
3781
|
+
target.set(source);
|
|
3782
|
+
buffer.unmap();
|
|
3783
|
+
return buffer;
|
|
3784
|
+
}
|
|
3758
3785
|
/**
|
|
3759
3786
|
* Low-level factory for typed {@link GPUBuffer}s (vertex, uniform, storage, index) used throughout the WebGPU backend
|
|
3760
|
-
* to upload CPU-side geometry/material/uniform data to the GPU.
|
|
3761
|
-
*
|
|
3762
|
-
*
|
|
3763
|
-
* buffer accessors in `renderablebuffer.ts`).
|
|
3787
|
+
* to upload CPU-side geometry/material/uniform data to the GPU. Every buffer is populated at creation (via
|
|
3788
|
+
* `mappedAtCreation`); later changes of same-sized data are uploaded in place by the owning {@link ManagedBuffer}
|
|
3789
|
+
* through {@link Buffers.write}, so consumers never need to write buffers themselves (see `renderablebuffer.ts`).
|
|
3764
3790
|
*/
|
|
3765
3791
|
class Buffers {
|
|
3766
3792
|
/**
|
|
@@ -3780,16 +3806,19 @@
|
|
|
3780
3806
|
return buffer;
|
|
3781
3807
|
}
|
|
3782
3808
|
static createUniform(device, data, label = '') {
|
|
3783
|
-
return device.
|
|
3784
|
-
size: data.byteLength, label,
|
|
3785
|
-
usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST,
|
|
3786
|
-
});
|
|
3809
|
+
return createPopulated(device, data, GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST, label);
|
|
3787
3810
|
}
|
|
3788
3811
|
static createStorage(device, data, label = '') {
|
|
3789
|
-
return device.
|
|
3790
|
-
|
|
3791
|
-
|
|
3792
|
-
|
|
3812
|
+
return createPopulated(device, data, GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_DST, label);
|
|
3813
|
+
}
|
|
3814
|
+
/**
|
|
3815
|
+
* Uploads `data` into an existing `buffer` (same byte length expected), in place, via {@link GPUQueue.writeBuffer}.
|
|
3816
|
+
* @param device The {@link GPUDevice} owning the buffer.
|
|
3817
|
+
* @param buffer The destination buffer.
|
|
3818
|
+
* @param data The new contents.
|
|
3819
|
+
*/
|
|
3820
|
+
static write(device, buffer, data) {
|
|
3821
|
+
device.queue.writeBuffer(buffer, 0, data);
|
|
3793
3822
|
}
|
|
3794
3823
|
/**
|
|
3795
3824
|
* Creates a {@link GPUBuffer} usable as an index buffer (`INDEX | COPY_DST`), writing `data` into it immediately.
|
|
@@ -3833,6 +3862,137 @@
|
|
|
3833
3862
|
}
|
|
3834
3863
|
}
|
|
3835
3864
|
|
|
3865
|
+
//namespace Pacem.Drawing3D.WebGPU {
|
|
3866
|
+
/*
|
|
3867
|
+
* A-buffer (per-pixel linked lists) order-independent transparency, after
|
|
3868
|
+
* https://webgpu.github.io/webgpu-samples/?sample=a-buffer
|
|
3869
|
+
*
|
|
3870
|
+
* - heads: one `u32` per pixel pointing to the most recent fragment (`index + 1`, `0` meaning "none"), preceded by
|
|
3871
|
+
* the global fragment counter; cleared (zeroed) every frame;
|
|
3872
|
+
* - list: `{ color (rgba8 packed), depth, next }` fragments;
|
|
3873
|
+
* - info: render target width/height and list capacity.
|
|
3874
|
+
*/
|
|
3875
|
+
const FRAGMENT_STRUCT = `struct ABufferFragment {
|
|
3876
|
+
color: u32,
|
|
3877
|
+
depth: f32,
|
|
3878
|
+
next: u32,
|
|
3879
|
+
}`;
|
|
3880
|
+
const INFO_STRUCT = `struct ABufferInfo {
|
|
3881
|
+
width: u32,
|
|
3882
|
+
height: u32,
|
|
3883
|
+
capacity: u32,
|
|
3884
|
+
padding: u32,
|
|
3885
|
+
}`;
|
|
3886
|
+
/**
|
|
3887
|
+
* Builds the {@link WGSLFragmentExtra} letting a material fragment shader push its output into the A-buffer via
|
|
3888
|
+
* `aBufferInsert(position, sampleMask, color)`, instead of returning a color. The fragment is tested (manually, since storage
|
|
3889
|
+
* writes are side effects that a late depth test wouldn't prevent) against the opaque depth, and dropped when the
|
|
3890
|
+
* list is full.
|
|
3891
|
+
* @param group `@group` index of the A-buffer bindings (the camera/interaction group, by default).
|
|
3892
|
+
*/
|
|
3893
|
+
function aBufferFragmentExtra(group = UNIFORM_GROUP_INDEX_CAMERA) {
|
|
3894
|
+
return {
|
|
3895
|
+
definitions: [FRAGMENT_STRUCT, INFO_STRUCT, `struct ABufferHeads {
|
|
3896
|
+
count: atomic<u32>,
|
|
3897
|
+
data: array<atomic<u32>>,
|
|
3898
|
+
}`],
|
|
3899
|
+
bindings: [
|
|
3900
|
+
`@group(${group}) @binding(${ABUFFER_BINDING_INDEX_HEADS}) var<storage, read_write> aBufferHeads: ABufferHeads;`,
|
|
3901
|
+
`@group(${group}) @binding(${ABUFFER_BINDING_INDEX_LIST}) var<storage, read_write> aBufferList: array<ABufferFragment>;`,
|
|
3902
|
+
`@group(${group}) @binding(${ABUFFER_BINDING_INDEX_INFO}) var<uniform> aBufferInfo: ABufferInfo;`,
|
|
3903
|
+
`@group(${group}) @binding(${ABUFFER_BINDING_INDEX_DEPTH}) var aBufferOpaqueDepth: texture_depth_multisampled_2d;`,
|
|
3904
|
+
`fn aBufferInsert(position: vec4f, sampleMask: u32, color: vec4f) {
|
|
3905
|
+
// one fragment per surface and pixel: only the triangle covering sample 0 (the one depth is tested against) counts,
|
|
3906
|
+
// otherwise pixels along shared triangle edges would get the surface twice
|
|
3907
|
+
let coversSample0 = (sampleMask & 1u) != 0u;
|
|
3908
|
+
if (!coversSample0 || color.a <= 0.0) {
|
|
3909
|
+
return;
|
|
3910
|
+
}
|
|
3911
|
+
let pixel = vec2u(position.xy);
|
|
3912
|
+
if (pixel.x >= aBufferInfo.width || pixel.y >= aBufferInfo.height) {
|
|
3913
|
+
return;
|
|
3914
|
+
}
|
|
3915
|
+
// manual depth test against the opaque geometry
|
|
3916
|
+
let opaqueDepth = textureLoad(aBufferOpaqueDepth, pixel, 0);
|
|
3917
|
+
if (position.z >= opaqueDepth) {
|
|
3918
|
+
return;
|
|
3919
|
+
}
|
|
3920
|
+
let slot = atomicAdd(&aBufferHeads.count, 1u);
|
|
3921
|
+
if (slot >= aBufferInfo.capacity) {
|
|
3922
|
+
return;
|
|
3923
|
+
}
|
|
3924
|
+
let head = &aBufferHeads.data[pixel.y * aBufferInfo.width + pixel.x];
|
|
3925
|
+
let previous = atomicExchange(head, slot + 1u);
|
|
3926
|
+
let clamped = clamp(color, vec4f(0), vec4f(1));
|
|
3927
|
+
let packed = pack4x8unorm(clamped);
|
|
3928
|
+
aBufferList[slot] = ABufferFragment(packed, position.z, previous);
|
|
3929
|
+
}`
|
|
3930
|
+
],
|
|
3931
|
+
modifiers: []
|
|
3932
|
+
};
|
|
3933
|
+
}
|
|
3934
|
+
/**
|
|
3935
|
+
* Full-screen composite shader: collects (up to {@link ABUFFER_MAX_SORTED_LAYERS}) the pixel's fragments, sorts
|
|
3936
|
+
* them far-to-near and blends them into a premultiplied color, meant to be blended (`one`, `one-minus-src-alpha`)
|
|
3937
|
+
* over the opaque render.
|
|
3938
|
+
*/
|
|
3939
|
+
function getABufferCompositeWgsl() {
|
|
3940
|
+
return `${FRAGMENT_STRUCT}
|
|
3941
|
+
|
|
3942
|
+
${INFO_STRUCT}
|
|
3943
|
+
|
|
3944
|
+
struct ABufferHeads {
|
|
3945
|
+
count: u32,
|
|
3946
|
+
data: array<u32>,
|
|
3947
|
+
}
|
|
3948
|
+
|
|
3949
|
+
@group(0) @binding(0) var<storage, read> heads: ABufferHeads;
|
|
3950
|
+
@group(0) @binding(1) var<storage, read> list: array<ABufferFragment>;
|
|
3951
|
+
@group(0) @binding(2) var<uniform> info: ABufferInfo;
|
|
3952
|
+
|
|
3953
|
+
const MAX_LAYERS = ${ABUFFER_MAX_SORTED_LAYERS}u;
|
|
3954
|
+
|
|
3955
|
+
@vertex fn vertexMain(@builtin(vertex_index) index: u32) -> @builtin(position) vec4f {
|
|
3956
|
+
// full-screen triangle
|
|
3957
|
+
let positions = array(vec2f(-1, -1), vec2f(3, -1), vec2f(-1, 3));
|
|
3958
|
+
return vec4f(positions[index], 0, 1);
|
|
3959
|
+
}
|
|
3960
|
+
|
|
3961
|
+
@fragment fn fragmentMain(@builtin(position) position: vec4f) -> @location(0) vec4f {
|
|
3962
|
+
let pixel = vec2u(position.xy);
|
|
3963
|
+
var layers: array<ABufferFragment, MAX_LAYERS>;
|
|
3964
|
+
var count = 0u;
|
|
3965
|
+
var index = heads.data[pixel.y * info.width + pixel.x];
|
|
3966
|
+
while (index != 0u && count < MAX_LAYERS) {
|
|
3967
|
+
layers[count] = list[index - 1u];
|
|
3968
|
+
index = layers[count].next;
|
|
3969
|
+
count++;
|
|
3970
|
+
}
|
|
3971
|
+
if (count == 0u) {
|
|
3972
|
+
discard;
|
|
3973
|
+
}
|
|
3974
|
+
|
|
3975
|
+
// insertion sort, farthest first
|
|
3976
|
+
for (var i = 1u; i < count; i++) {
|
|
3977
|
+
let item = layers[i];
|
|
3978
|
+
var j = i;
|
|
3979
|
+
while (j > 0u && layers[j - 1u].depth < item.depth) {
|
|
3980
|
+
layers[j] = layers[j - 1u];
|
|
3981
|
+
j--;
|
|
3982
|
+
}
|
|
3983
|
+
layers[j] = item;
|
|
3984
|
+
}
|
|
3985
|
+
|
|
3986
|
+
// back-to-front "over", premultiplied
|
|
3987
|
+
var result = vec4f(0);
|
|
3988
|
+
for (var i = 0u; i < count; i++) {
|
|
3989
|
+
let color = unpack4x8unorm(layers[i].color);
|
|
3990
|
+
result = vec4f(color.rgb * color.a, color.a) + result * (1.0 - color.a);
|
|
3991
|
+
}
|
|
3992
|
+
return result;
|
|
3993
|
+
}`;
|
|
3994
|
+
}
|
|
3995
|
+
|
|
3836
3996
|
/** Fallback options used by {@link getBasicMaterialFragmentWgsl}: mirrors the `VERTEX_OUTPUT_LOCATION_*` layout produced by `mesh-vertex.ts` and reads the diffuse color from {@link MATERIAL_GROUP_INDEX}/{@link STORAGE_MATERIAL_INDEX}. */
|
|
3837
3997
|
const DefaultBasicMaterialFragmentOptions = {
|
|
3838
3998
|
outputNormalLocation: VERTEX_OUTPUT_LOCATION_NORMAL,
|
|
@@ -3872,7 +4032,8 @@
|
|
|
3872
4032
|
* storage buffer, then lets `extensions.modifiers` (lighting/texture snippets) accumulate into the `color`,
|
|
3873
4033
|
* `ambient` and `lighting` WGSL variables ({@link VERTEX_COLOR_REFERENCE}/{@link AMBIENT_COLOR_REFERENCE}/{@link LIGHTING_COLOR_REFERENCE}).
|
|
3874
4034
|
* If nothing wrote a `lighting` color (alpha stays `0`), it is treated as fully lit (`white`) so the material
|
|
3875
|
-
* renders unshaded when no light snippet is attached; the final output is `color * lighting + ambient
|
|
4035
|
+
* renders unshaded when no light snippet is attached; the final output is `color.rgb * lighting.rgb + ambient.rgb`,
|
|
4036
|
+
* keeping `color.a` untouched (lights must not alter the material's opacity).
|
|
3876
4037
|
*
|
|
3877
4038
|
* Splices `extensions.definitions`/`extensions.bindings`/`extensions.modifiers` (see {@link WGSLFragmentExtra}) into
|
|
3878
4039
|
* the `// definitions`, `// bindings` and body sections of the generated source, alongside the fixed
|
|
@@ -3884,8 +4045,17 @@
|
|
|
3884
4045
|
*/
|
|
3885
4046
|
function getBasicMaterialFragmentWgsl(extensions = {}, options = DefaultBasicMaterialFragmentOptions) {
|
|
3886
4047
|
const opts = pacemCore.Utils.extend({}, DefaultBasicMaterialFragmentOptions, options);
|
|
3887
|
-
const
|
|
4048
|
+
const aBuffer = opts.output === 'a-buffer';
|
|
4049
|
+
const aBufferExtra = aBuffer ? aBufferFragmentExtra() : { definitions: [], bindings: [] };
|
|
4050
|
+
const allDefinitions = (extensions.definitions ?? []).concat(aBufferExtra.definitions), allBindings = (extensions.bindings ?? []).concat(aBufferExtra.bindings);
|
|
4051
|
+
const definitions = adaptWGSLStringArray$1(allDefinitions), bindings = adaptWGSLStringArray$1(allBindings), modifiers = adaptWGSLModifierStringArray$1(extensions.modifiers);
|
|
3888
4052
|
const color = VERTEX_COLOR_REFERENCE, lighting = LIGHTING_COLOR_REFERENCE, ambient = AMBIENT_COLOR_REFERENCE;
|
|
4053
|
+
// lighting shades the rgb channels only: the material's alpha must not depend on the number of lights
|
|
4054
|
+
const shaded = `vec4f(${color}.rgb * ${lighting}.rgb + ${ambient}.rgb, ${color}.a)`;
|
|
4055
|
+
// the A-buffer variant pushes the shaded color into the per-pixel lists (see `a-buffer.ts`) instead of returning it
|
|
4056
|
+
const sampleMaskInput = aBuffer ? '\n @builtin(sample_mask) sampleMask: u32, // MSAA coverage' : '';
|
|
4057
|
+
const returnType = aBuffer ? '' : ' -> @location(0) vec4f';
|
|
4058
|
+
const output = aBuffer ? `aBufferInsert(position, sampleMask, ${shaded});` : `return ${shaded};`;
|
|
3889
4059
|
return `// definitions
|
|
3890
4060
|
|
|
3891
4061
|
${definitions}
|
|
@@ -3904,8 +4074,8 @@ const white = vec4f(1,1,1,1);
|
|
|
3904
4074
|
@location(${opts.outputUvLocation}) uv: vec2f,
|
|
3905
4075
|
@location(${opts.outputVertexIndexLocation}) @interpolate(flat) index: u32, // vertex index,
|
|
3906
4076
|
@location(${opts.outputRayIndexLocation}) ray: vec3f, // ray (eye-to-vertex) vector
|
|
3907
|
-
@location(${opts.outputInstanceIndexLocation}) @interpolate(flat) instance : u32, // instance index
|
|
3908
|
-
)
|
|
4077
|
+
@location(${opts.outputInstanceIndexLocation}) @interpolate(flat) instance : u32, // instance index${sampleMaskInput}
|
|
4078
|
+
)${returnType} {
|
|
3909
4079
|
var ${color} = diffuseColor;
|
|
3910
4080
|
var ${ambient}: vec4f = empty;
|
|
3911
4081
|
var ${lighting}: vec4f = empty;
|
|
@@ -3914,7 +4084,7 @@ const white = vec4f(1,1,1,1);
|
|
|
3914
4084
|
${modifiers}
|
|
3915
4085
|
|
|
3916
4086
|
${lighting} = select(white, ${lighting}, ${lighting}.a > 0);
|
|
3917
|
-
|
|
4087
|
+
${output}
|
|
3918
4088
|
}`;
|
|
3919
4089
|
}
|
|
3920
4090
|
|
|
@@ -4013,6 +4183,49 @@ fn getVertexColor(index: u32) -> vec4f {
|
|
|
4013
4183
|
}
|
|
4014
4184
|
throw new TypeError(`Material type '${material.shader}' not supported.`);
|
|
4015
4185
|
}
|
|
4186
|
+
/**
|
|
4187
|
+
* Whether `material` renders (partially) see-through: visible, with an effective diffuse alpha (color alpha times
|
|
4188
|
+
* `opacity`) below `1`. Texture alpha isn't inspected.
|
|
4189
|
+
* @param material The scene material to test (`null`/`undefined` counts as opaque).
|
|
4190
|
+
*/
|
|
4191
|
+
static isTranslucent(material) {
|
|
4192
|
+
if (pacemCore.Utils.isNull(material)) {
|
|
4193
|
+
return false;
|
|
4194
|
+
}
|
|
4195
|
+
// `visible` defaults to true: only an explicit `false` hides
|
|
4196
|
+
const visible = material.visible ?? true;
|
|
4197
|
+
if (!visible) {
|
|
4198
|
+
return false;
|
|
4199
|
+
}
|
|
4200
|
+
const color = diffuseColor(material);
|
|
4201
|
+
return color.a < 1;
|
|
4202
|
+
}
|
|
4203
|
+
}
|
|
4204
|
+
const WHITE = { r: 1, g: 1, b: 1, a: 1 };
|
|
4205
|
+
const TRANSPARENT = { r: 0, g: 0, b: 0, a: 0 };
|
|
4206
|
+
/** Parses (or copies: the material's own color object must never be altered) `color`, white by default. */
|
|
4207
|
+
function parseColor(color) {
|
|
4208
|
+
if (typeof color === 'string') {
|
|
4209
|
+
return pacemFoundation.Colors.parse(color);
|
|
4210
|
+
}
|
|
4211
|
+
const source = color ?? WHITE;
|
|
4212
|
+
return pacemCore.Utils.extend({}, source);
|
|
4213
|
+
}
|
|
4214
|
+
/** Effective diffuse color of `material`: its parsed `color` (white by default) with alpha scaled by `opacity`, or fully transparent black when not `visible`. */
|
|
4215
|
+
function diffuseColor(material) {
|
|
4216
|
+
const { opacity, color } = material;
|
|
4217
|
+
// `visible` defaults to true: only an explicit `false` hides
|
|
4218
|
+
const visible = material.visible ?? true;
|
|
4219
|
+
if (!visible) {
|
|
4220
|
+
return pacemCore.Utils.extend({}, TRANSPARENT);
|
|
4221
|
+
}
|
|
4222
|
+
const retval = parseColor(color);
|
|
4223
|
+
const validOpacity = opacity >= 0 && opacity <= 1;
|
|
4224
|
+
if (!validOpacity) {
|
|
4225
|
+
return retval;
|
|
4226
|
+
}
|
|
4227
|
+
const alpha = (retval.a ?? 1) * opacity;
|
|
4228
|
+
return pacemCore.Utils.extend(retval, { a: alpha });
|
|
4016
4229
|
}
|
|
4017
4230
|
const EmptyMaterialWGSLDelegates = {
|
|
4018
4231
|
// empty delegates
|
|
@@ -4028,21 +4241,15 @@ fn getVertexColor(index: u32) -> vec4f {
|
|
|
4028
4241
|
get wgsl() {
|
|
4029
4242
|
return EmptyMaterialWGSLDelegates;
|
|
4030
4243
|
}
|
|
4031
|
-
buffer(
|
|
4032
|
-
const
|
|
4033
|
-
const
|
|
4034
|
-
|
|
4244
|
+
buffer(ctx, key) {
|
|
4245
|
+
const materialValue = this.value(ctx, key);
|
|
4246
|
+
const label = LABEL_PREFIX + 'material-' + this.shader + '-buffer';
|
|
4247
|
+
const buffer = Buffers.createStorage(ctx.device, materialValue, label);
|
|
4248
|
+
return { buffer, value: materialValue, version: performance.now() };
|
|
4035
4249
|
}
|
|
4036
|
-
|
|
4037
|
-
const {
|
|
4038
|
-
|
|
4039
|
-
return { r: 0, g: 0, b: 0, a: 0 };
|
|
4040
|
-
}
|
|
4041
|
-
const retval = typeof color === 'string' ? pacemFoundation.Colors.parse(color) : (color ?? { r: 1, g: 1, b: 1, a: 1 });
|
|
4042
|
-
if (opacity >= 0 && opacity <= 1) {
|
|
4043
|
-
return pacemCore.Utils.extend(retval, { a: retval.a * opacity });
|
|
4044
|
-
}
|
|
4045
|
-
return retval;
|
|
4250
|
+
value(_, __) {
|
|
4251
|
+
const { r, g, b, a } = diffuseColor(this.material);
|
|
4252
|
+
return new Float32Array([r, g, b, a ?? 1]);
|
|
4046
4253
|
}
|
|
4047
4254
|
}
|
|
4048
4255
|
/**
|
|
@@ -4061,21 +4268,24 @@ fn getVertexColor(index: u32) -> vec4f {
|
|
|
4061
4268
|
}
|
|
4062
4269
|
}
|
|
4063
4270
|
/**
|
|
4064
|
-
* Allocates the
|
|
4271
|
+
* Allocates the {@link GPUTexture} for the material's `texture`, if any, uploads the bitmap into it (once) and
|
|
4272
|
+
* creates its (stable) view.
|
|
4065
4273
|
* @param key Must be `'texture'`; any other {@link MaterialKey} (or a material without a `texture`) yields `null`.
|
|
4066
4274
|
*/
|
|
4067
4275
|
texture({ device }, key = 'texture') {
|
|
4068
|
-
const
|
|
4069
|
-
if (key
|
|
4070
|
-
|
|
4071
|
-
const texture = device.createTexture({
|
|
4072
|
-
format: 'rgba8unorm',
|
|
4073
|
-
usage: GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_DST,
|
|
4074
|
-
size: [texBmp.width, texBmp.height],
|
|
4075
|
-
});
|
|
4076
|
-
return { texture, source: texBmp };
|
|
4276
|
+
const texBmp = this.material.texture;
|
|
4277
|
+
if (key !== 'texture' || pacemCore.Utils.isNull(texBmp)) {
|
|
4278
|
+
return null;
|
|
4077
4279
|
}
|
|
4078
|
-
|
|
4280
|
+
const texture = device.createTexture({
|
|
4281
|
+
label: LABEL_PREFIX + 'material-texture',
|
|
4282
|
+
format: 'rgba8unorm',
|
|
4283
|
+
usage: GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_DST,
|
|
4284
|
+
size: [texBmp.width, texBmp.height],
|
|
4285
|
+
});
|
|
4286
|
+
device.queue.copyExternalImageToTexture({ source: texBmp, flipY: true }, { texture }, { width: texBmp.width, height: texBmp.height });
|
|
4287
|
+
const view = texture.createView({ label: LABEL_PREFIX + 'material-texture-view' });
|
|
4288
|
+
return { texture, view, source: texBmp };
|
|
4079
4289
|
}
|
|
4080
4290
|
// TODO: put it in the material instance/interface
|
|
4081
4291
|
/** Basic-material fragment shader WGSL source generator; see `wgsl/basic-material-fragment.ts`. */
|
|
@@ -4097,7 +4307,7 @@ fn getVertexColor(index: u32) -> vec4f {
|
|
|
4097
4307
|
}
|
|
4098
4308
|
}
|
|
4099
4309
|
/**
|
|
4100
|
-
* Returns the `'line'` uniform buffer (
|
|
4310
|
+
* Returns the `'line'` uniform buffer (render-target width/height and half line-width) for `key === 'line'`; otherwise
|
|
4101
4311
|
* defers to the inherited diffuse-color buffer.
|
|
4102
4312
|
* @param ctx WebGPU context supplying the device and canvas.
|
|
4103
4313
|
* @param key Which buffer to build; only `'line'` is handled specially.
|
|
@@ -4105,14 +4315,24 @@ fn getVertexColor(index: u32) -> vec4f {
|
|
|
4105
4315
|
buffer(ctx, key) {
|
|
4106
4316
|
switch (key) {
|
|
4107
4317
|
case 'line':
|
|
4108
|
-
const
|
|
4109
|
-
const
|
|
4110
|
-
|
|
4111
|
-
return { buffer: Buffers.createUniform(device, lineValue, LABEL_PREFIX + 'line-' + this.shader + '-buffer'), value: lineValue, version: performance.now() };
|
|
4318
|
+
const lineValue = this.value(ctx, key);
|
|
4319
|
+
const lineBuffer = Buffers.createUniform(ctx.device, lineValue, LABEL_PREFIX + 'line-' + this.shader + '-buffer');
|
|
4320
|
+
return { buffer: lineBuffer, value: lineValue, version: performance.now() };
|
|
4112
4321
|
default:
|
|
4113
4322
|
return super.buffer(ctx);
|
|
4114
4323
|
}
|
|
4115
4324
|
}
|
|
4325
|
+
/** `'line'`: canvas width/height (in pixels, i.e. the render target size) and half line-width; otherwise the inherited diffuse color. */
|
|
4326
|
+
value(ctx, key) {
|
|
4327
|
+
switch (key) {
|
|
4328
|
+
case 'line':
|
|
4329
|
+
const { canvas } = ctx;
|
|
4330
|
+
const lineMaterial = this.material;
|
|
4331
|
+
return new Float32Array([canvas.width, canvas.height, lineMaterial.lineWidth / 2]);
|
|
4332
|
+
default:
|
|
4333
|
+
return super.value(ctx);
|
|
4334
|
+
}
|
|
4335
|
+
}
|
|
4116
4336
|
/** Lines have no texture support; always returns `null`. */
|
|
4117
4337
|
texture(_) {
|
|
4118
4338
|
return null;
|
|
@@ -4685,9 +4905,10 @@ fn computeOffsetPosition(p0: vec4f, p1: vec4f, index: u32) -> vec4f {
|
|
|
4685
4905
|
*
|
|
4686
4906
|
* Emits, as `definitions`, an `AmbientLight` struct (`color: vec4f`, `intensity: f32`) and a `computeAmbient` helper
|
|
4687
4907
|
* function; as `bindings`, a `var<uniform>` declaration for the light data at the given `@group`/`@binding`
|
|
4688
|
-
* coordinates; and, as `modifiers`, a statement
|
|
4908
|
+
* coordinates; and, as `modifiers`, a statement accumulating the computed color into `references.outputColor`
|
|
4909
|
+
* (so that several ambient lights add up).
|
|
4689
4910
|
*
|
|
4690
|
-
* @param references WGSL identifiers for the color to shade (`inputColor`) and the variable to
|
|
4911
|
+
* @param references WGSL identifiers for the color to shade (`inputColor`) and the variable to accumulate the ambient-lit result into (`outputColor`). Both are required.
|
|
4691
4912
|
* @param group `@group` index at which the generated `AmbientLight` uniform is bound.
|
|
4692
4913
|
* @param binding `@binding` index (within `group`) at which the generated `AmbientLight` uniform is bound.
|
|
4693
4914
|
* @returns Fragment-shader `definitions`/`bindings`/`modifiers` meant to be spliced into a material fragment shader (see {@link getBasicMaterialFragmentWgsl}/{@link getStandardMaterialFragmentWgsl}).
|
|
@@ -4710,7 +4931,8 @@ fn computeOffsetPosition(p0: vec4f, p1: vec4f, index: u32) -> vec4f {
|
|
|
4710
4931
|
// bindings
|
|
4711
4932
|
bindings: [`@group(${group}) @binding(${binding}) var<uniform> ${lightReference}: AmbientLight;`],
|
|
4712
4933
|
// modifiers
|
|
4713
|
-
|
|
4934
|
+
// accumulate: several ambient lights add up
|
|
4935
|
+
modifiers: [`${outputColor} += computeAmbient(${inputColor}, ${lightReference});`]
|
|
4714
4936
|
};
|
|
4715
4937
|
}
|
|
4716
4938
|
|
|
@@ -4871,12 +5093,25 @@ fn computeOffsetPosition(p0: vec4f, p1: vec4f, index: u32) -> vec4f {
|
|
|
4871
5093
|
//namespace Pacem.Drawing3D.WebGPU {
|
|
4872
5094
|
const Vector3D$2 = pacemNumerical.Geometry.LinearAlgebra.Vector3D;
|
|
4873
5095
|
const Matrix3D$1 = pacemNumerical.Geometry.LinearAlgebra.Matrix3D;
|
|
5096
|
+
const EMPTY_FLAGS = Object.freeze([]);
|
|
5097
|
+
/** Incremented by every {@link RenderLooper.loop}: lets buffers evaluate inherited (parent) stale flags once per pass. */
|
|
5098
|
+
let currentFrame = 0;
|
|
4874
5099
|
function throwBufferRequestError(key, type) {
|
|
4875
5100
|
if (typeof type === 'function') {
|
|
4876
5101
|
type = type.name;
|
|
4877
5102
|
}
|
|
4878
5103
|
throw new RangeError(`Buffer '${key}' not available for ${type}.`);
|
|
4879
5104
|
}
|
|
5105
|
+
/** Uploads `value` into `buffer` in place when the byte length matches (returning `buffer`), otherwise yields `null` so that the caller recreates it. */
|
|
5106
|
+
function writeInPlace(device, buffer, value) {
|
|
5107
|
+
if (pacemCore.Utils.isNull(buffer) || buffer.value.byteLength !== value.byteLength) {
|
|
5108
|
+
return null;
|
|
5109
|
+
}
|
|
5110
|
+
Buffers.write(device, buffer.buffer, value);
|
|
5111
|
+
buffer.value = value;
|
|
5112
|
+
buffer.version = performance.now();
|
|
5113
|
+
return buffer;
|
|
5114
|
+
}
|
|
4880
5115
|
function createRenderableBuffer(item, parent, ...args) {
|
|
4881
5116
|
item.stage ??= parent?.item.stage;
|
|
4882
5117
|
if (isGroup(item)) {
|
|
@@ -4920,6 +5155,7 @@ fn computeOffsetPosition(p0: vec4f, p1: vec4f, index: u32) -> vec4f {
|
|
|
4920
5155
|
* @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).
|
|
4921
5156
|
*/
|
|
4922
5157
|
loop(render) {
|
|
5158
|
+
currentFrame++;
|
|
4923
5159
|
const { meshes, cameras, groups, lights } = this._set;
|
|
4924
5160
|
const camera = cameras[0];
|
|
4925
5161
|
let cameraDone = false, lightsDone = false;
|
|
@@ -4985,7 +5221,7 @@ fn computeOffsetPosition(p0: vec4f, p1: vec4f, index: u32) -> vec4f {
|
|
|
4985
5221
|
* Wraps `item` in the {@link RenderableBuffer} implementation matching its kind (group/mesh/camera/light),
|
|
4986
5222
|
* recursively wrapping a group's children.
|
|
4987
5223
|
* @param item The scene renderable to wrap.
|
|
4988
|
-
* @param args Extra constructor arguments forwarded
|
|
5224
|
+
* @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`).
|
|
4989
5225
|
* @throws {Error} If `item`'s type isn't recognized.
|
|
4990
5226
|
*/
|
|
4991
5227
|
static create(item, ...args) {
|
|
@@ -4998,7 +5234,7 @@ fn computeOffsetPosition(p0: vec4f, p1: vec4f, index: u32) -> vec4f {
|
|
|
4998
5234
|
* @param includeParent Whether to also clear the parent group buffer's flags, recursively up the hierarchy.
|
|
4999
5235
|
*/
|
|
5000
5236
|
static clearFlags(buffer, includeParent = false) {
|
|
5001
|
-
buffer.item.flags
|
|
5237
|
+
buffer.item.flags?.splice(0);
|
|
5002
5238
|
if (includeParent) {
|
|
5003
5239
|
const bufferBase = buffer;
|
|
5004
5240
|
if (!pacemCore.Utils.isNull(bufferBase.parent)) {
|
|
@@ -5041,10 +5277,10 @@ fn computeOffsetPosition(p0: vec4f, p1: vec4f, index: u32) -> vec4f {
|
|
|
5041
5277
|
#garbage = [];
|
|
5042
5278
|
_destroyUnsafe(obj) {
|
|
5043
5279
|
if ('texture' in obj) {
|
|
5044
|
-
obj.texture
|
|
5280
|
+
obj.texture?.destroy();
|
|
5045
5281
|
}
|
|
5046
5282
|
else if ('buffer' in obj) {
|
|
5047
|
-
obj.buffer
|
|
5283
|
+
obj.buffer?.destroy();
|
|
5048
5284
|
}
|
|
5049
5285
|
}
|
|
5050
5286
|
destroySafely(...objects) {
|
|
@@ -5060,8 +5296,23 @@ fn computeOffsetPosition(p0: vec4f, p1: vec4f, index: u32) -> vec4f {
|
|
|
5060
5296
|
}
|
|
5061
5297
|
}
|
|
5062
5298
|
}
|
|
5299
|
+
#refs = 0;
|
|
5300
|
+
/** Registers one more consumer of this (shared) buffer. */
|
|
5301
|
+
retain() {
|
|
5302
|
+
this.#refs++;
|
|
5303
|
+
}
|
|
5304
|
+
/** Unregisters a consumer of this (shared) buffer, destroying it as soon as nobody uses it anymore. */
|
|
5305
|
+
release() {
|
|
5306
|
+
if (--this.#refs <= 0) {
|
|
5307
|
+
this.#refs = 0;
|
|
5308
|
+
this.destroy();
|
|
5309
|
+
}
|
|
5310
|
+
}
|
|
5063
5311
|
#disposed = false;
|
|
5064
5312
|
destroy() {
|
|
5313
|
+
if (this.#disposed) {
|
|
5314
|
+
return;
|
|
5315
|
+
}
|
|
5065
5316
|
this.dispose();
|
|
5066
5317
|
this.#disposed = true;
|
|
5067
5318
|
}
|
|
@@ -5077,17 +5328,50 @@ fn computeOffsetPosition(p0: vec4f, p1: vec4f, index: u32) -> vec4f {
|
|
|
5077
5328
|
}
|
|
5078
5329
|
#u32id;
|
|
5079
5330
|
#parent;
|
|
5080
|
-
#u32idBuffer
|
|
5331
|
+
#u32idBuffer;
|
|
5332
|
+
#reparented = false;
|
|
5081
5333
|
get parent() {
|
|
5082
5334
|
return this.#parent;
|
|
5083
5335
|
}
|
|
5084
5336
|
get id() {
|
|
5085
5337
|
return this.#u32id;
|
|
5086
5338
|
}
|
|
5339
|
+
/** @internal Moves this buffer under a new parent group buffer (when a group gets rebuilt), forcing a world-transform refresh. */
|
|
5340
|
+
reparent(parent) {
|
|
5341
|
+
if (this.#parent === parent) {
|
|
5342
|
+
return;
|
|
5343
|
+
}
|
|
5344
|
+
this.#parent = parent;
|
|
5345
|
+
this.#reparented = true;
|
|
5346
|
+
}
|
|
5347
|
+
/** Returns (and resets) whether the buffer has been moved under a new parent since the last call. */
|
|
5348
|
+
consumeReparented() {
|
|
5349
|
+
const retval = this.#reparented;
|
|
5350
|
+
this.#reparented = false;
|
|
5351
|
+
return retval;
|
|
5352
|
+
}
|
|
5353
|
+
/** Whether this item or any of its ancestors carries stale flags. Allocation-free. */
|
|
5354
|
+
hasFlags() {
|
|
5355
|
+
if (this.item.flags?.length > 0) {
|
|
5356
|
+
return true;
|
|
5357
|
+
}
|
|
5358
|
+
const parent = this.parent;
|
|
5359
|
+
if (pacemCore.Utils.isNull(parent)) {
|
|
5360
|
+
return false;
|
|
5361
|
+
}
|
|
5362
|
+
return parent.hasFlags();
|
|
5363
|
+
}
|
|
5087
5364
|
allFlags() {
|
|
5365
|
+
if (!this.hasFlags()) {
|
|
5366
|
+
return EMPTY_FLAGS;
|
|
5367
|
+
}
|
|
5368
|
+
const ownFlags = this.item.flags ?? [];
|
|
5088
5369
|
const parent = this.parent;
|
|
5089
|
-
|
|
5090
|
-
|
|
5370
|
+
if (pacemCore.Utils.isNull(parent)) {
|
|
5371
|
+
return ownFlags;
|
|
5372
|
+
}
|
|
5373
|
+
const parentFlags = parent.allFlags();
|
|
5374
|
+
return ownFlags.union(parentFlags);
|
|
5091
5375
|
}
|
|
5092
5376
|
buildParentWorldTransform() {
|
|
5093
5377
|
let worldMatrix = Matrix3D$1.identity();
|
|
@@ -5111,21 +5395,31 @@ fn computeOffsetPosition(p0: vec4f, p1: vec4f, index: u32) -> vec4f {
|
|
|
5111
5395
|
}
|
|
5112
5396
|
buffer(context, key) {
|
|
5113
5397
|
if (key === 'u32id') {
|
|
5114
|
-
|
|
5115
|
-
const { pipeline, device } = context;
|
|
5116
|
-
if (u32idBuffer.has(pipeline)) {
|
|
5117
|
-
return pacemCore.Utils.extend({ fresh: false }, u32idBuffer.get(pipeline));
|
|
5118
|
-
}
|
|
5119
|
-
const u32idBufferValue = new Uint32Array([this.id]);
|
|
5120
|
-
const u32idBufferBuffer = Buffers.createUniform(device, u32idBufferValue, LABEL_PREFIX + 'u32id-buffer');
|
|
5121
|
-
const retval = pacemCore.Utils.extend({ buffer: u32idBufferBuffer, value: u32idBufferValue, version: performance.now() }, { fresh: true });
|
|
5122
|
-
this.#u32idBuffer.set(pipeline, retval);
|
|
5123
|
-
return retval;
|
|
5398
|
+
return this._ensureU32idBuffer(context);
|
|
5124
5399
|
}
|
|
5125
5400
|
const retval = this.specificBuffer(context, key);
|
|
5126
|
-
this.#versions.set(key, retval
|
|
5401
|
+
this.#versions.set(key, retval?.version ?? 0);
|
|
5127
5402
|
return retval;
|
|
5128
5403
|
}
|
|
5404
|
+
/** One id buffer per renderable, shared by every (color-picking) pipeline. */
|
|
5405
|
+
_ensureU32idBuffer({ device }) {
|
|
5406
|
+
if (!pacemCore.Utils.isNull(this.#u32idBuffer)) {
|
|
5407
|
+
return this.#u32idBuffer;
|
|
5408
|
+
}
|
|
5409
|
+
const value = new Uint32Array([this.id]);
|
|
5410
|
+
const buffer = Buffers.createUniform(device, value, LABEL_PREFIX + 'u32id-buffer');
|
|
5411
|
+
this.#u32idBuffer = { buffer, value, version: performance.now() };
|
|
5412
|
+
return this.#u32idBuffer;
|
|
5413
|
+
}
|
|
5414
|
+
destroy() {
|
|
5415
|
+
if (this.disposed) {
|
|
5416
|
+
return;
|
|
5417
|
+
}
|
|
5418
|
+
const u32id = this.#u32idBuffer;
|
|
5419
|
+
this.#u32idBuffer = null;
|
|
5420
|
+
this.destroySafely(u32id);
|
|
5421
|
+
super.destroy();
|
|
5422
|
+
}
|
|
5129
5423
|
}
|
|
5130
5424
|
const DefaultMaterial = { shader: KnownShader.Basic, color: '#c0c0c0', flags: [] };
|
|
5131
5425
|
// #region GROUP
|
|
@@ -5133,7 +5427,19 @@ fn computeOffsetPosition(p0: vec4f, p1: vec4f, index: u32) -> vec4f {
|
|
|
5133
5427
|
#children;
|
|
5134
5428
|
constructor(group, parent, ...args) {
|
|
5135
5429
|
super(group, parent);
|
|
5136
|
-
|
|
5430
|
+
const store = args[2];
|
|
5431
|
+
this.#children = group.childRenderables.map(i => {
|
|
5432
|
+
// reuse the buffer of an item that already was a child of this very group (e.g. on `Children` changes),
|
|
5433
|
+
// so that its GPU resources and bind groups survive
|
|
5434
|
+
const existing = store?.get(i);
|
|
5435
|
+
if (!pacemCore.Utils.isNull(existing) && !existing.disposed && existing.parent?.item === group) {
|
|
5436
|
+
existing.reparent(this);
|
|
5437
|
+
return existing;
|
|
5438
|
+
}
|
|
5439
|
+
const created = createRenderableBuffer(i, this, ...args);
|
|
5440
|
+
store?.set(i, created);
|
|
5441
|
+
return created;
|
|
5442
|
+
});
|
|
5137
5443
|
}
|
|
5138
5444
|
get children() {
|
|
5139
5445
|
return this.#children;
|
|
@@ -5145,15 +5451,16 @@ fn computeOffsetPosition(p0: vec4f, p1: vec4f, index: u32) -> vec4f {
|
|
|
5145
5451
|
throw new Error("Method not implemented.");
|
|
5146
5452
|
}
|
|
5147
5453
|
dispose() {
|
|
5148
|
-
|
|
5149
|
-
|
|
5454
|
+
// children that moved under a newer buffer of the same group are not ours anymore
|
|
5455
|
+
const ownChildren = this.#children.filter(i => i.parent === this);
|
|
5456
|
+
ownChildren.forEach(i => i.destroy());
|
|
5150
5457
|
}
|
|
5151
5458
|
}
|
|
5152
5459
|
// #endregion
|
|
5153
5460
|
// #region CAMERA
|
|
5154
5461
|
class RenderableCameraBuffer extends RenderableBufferBase {
|
|
5155
|
-
#viewBag = new Map();
|
|
5156
5462
|
#view;
|
|
5463
|
+
#size = { width: 0, height: 0 };
|
|
5157
5464
|
constructor(camera) {
|
|
5158
5465
|
super(camera);
|
|
5159
5466
|
}
|
|
@@ -5161,166 +5468,164 @@ fn computeOffsetPosition(p0: vec4f, p1: vec4f, index: u32) -> vec4f {
|
|
|
5161
5468
|
throw new Error("Method not implemented.");
|
|
5162
5469
|
}
|
|
5163
5470
|
specificBuffer(context, key) {
|
|
5164
|
-
|
|
5165
|
-
let fresh = false;
|
|
5166
|
-
if (this.allFlags().length > 0 || pacemCore.Utils.isNull(this.#view)) {
|
|
5167
|
-
fresh = true;
|
|
5168
|
-
this.#viewBag.clear();
|
|
5471
|
+
if (this._isStale(context.canvas)) {
|
|
5169
5472
|
this._rebuildMatrices(context);
|
|
5170
5473
|
}
|
|
5171
|
-
const { pipeline } = context;
|
|
5172
|
-
if (!this.#viewBag.has(pipeline)) {
|
|
5173
|
-
fresh = true;
|
|
5174
|
-
this.#viewBag.set(pipeline, this.#view);
|
|
5175
|
-
}
|
|
5176
5474
|
RenderableBuffers.clearFlags(this);
|
|
5177
5475
|
switch (key) {
|
|
5178
5476
|
case 'cameraViewTransform':
|
|
5179
|
-
return
|
|
5477
|
+
return this.#view;
|
|
5180
5478
|
default:
|
|
5181
5479
|
throwBufferRequestError(key, RenderableCameraBuffer);
|
|
5182
5480
|
}
|
|
5183
5481
|
}
|
|
5482
|
+
/** Whether the matrices need a rebuild: stale flags, first use, or a different render target size (the projection depends on it). */
|
|
5483
|
+
_isStale(canvas) {
|
|
5484
|
+
if (pacemCore.Utils.isNull(this.#view) || this.hasFlags()) {
|
|
5485
|
+
return true;
|
|
5486
|
+
}
|
|
5487
|
+
const size = this.#size;
|
|
5488
|
+
return size.width !== canvas.width || size.height !== canvas.height;
|
|
5489
|
+
}
|
|
5184
5490
|
_rebuildMatrices({ device, canvas }) {
|
|
5185
|
-
// this._destroyView();
|
|
5186
5491
|
const cam = this.item;
|
|
5187
5492
|
const camera = Cameras.create(cam);
|
|
5188
5493
|
const { x, y, z } = cam.position;
|
|
5189
5494
|
const view = camera.view();
|
|
5190
5495
|
const projection = camera.projection(canvas);
|
|
5191
5496
|
const viewProjection = Matrix3D$1.multiply(view, projection);
|
|
5497
|
+
const viewArray = Matrix3D$1.toArray(view);
|
|
5498
|
+
const viewProjectionArray = Matrix3D$1.toArray(viewProjection);
|
|
5192
5499
|
const viewValue = new Float32Array(16 + 16 + 4);
|
|
5193
|
-
viewValue.set(
|
|
5194
|
-
viewValue.set(
|
|
5500
|
+
viewValue.set(viewArray, 0);
|
|
5501
|
+
viewValue.set(viewProjectionArray, 16);
|
|
5195
5502
|
viewValue.set([x, y, z], 32);
|
|
5503
|
+
this.#size = { width: canvas.width, height: canvas.height };
|
|
5196
5504
|
// reuse GPUBuffer (always same size)
|
|
5197
|
-
|
|
5198
|
-
|
|
5199
|
-
|
|
5200
|
-
}
|
|
5201
|
-
else {
|
|
5202
|
-
this.#view.value = viewValue;
|
|
5203
|
-
this.#view.version = performance.now().roundoff();
|
|
5505
|
+
const written = writeInPlace(device, this.#view, viewValue);
|
|
5506
|
+
if (!pacemCore.Utils.isNull(written)) {
|
|
5507
|
+
return;
|
|
5204
5508
|
}
|
|
5509
|
+
const viewBuffer = Buffers.createUniform(device, viewValue, LABEL_PREFIX + 'view-buffer');
|
|
5510
|
+
const version = performance.now().roundoff();
|
|
5511
|
+
this.#view = { buffer: viewBuffer, value: viewValue, version };
|
|
5205
5512
|
}
|
|
5206
|
-
|
|
5207
|
-
this.#viewBag.clear();
|
|
5513
|
+
dispose() {
|
|
5208
5514
|
const view = this.#view;
|
|
5209
5515
|
this.#view = null;
|
|
5210
5516
|
this.destroySafely(view);
|
|
5211
5517
|
}
|
|
5212
|
-
dispose() {
|
|
5213
|
-
this._destroyView();
|
|
5214
|
-
}
|
|
5215
5518
|
}
|
|
5216
5519
|
// #endregion
|
|
5217
5520
|
// #region GEOMETRY
|
|
5521
|
+
/**
|
|
5522
|
+
* GPU vertex (mesh) or storage (line) buffers of a {@link NodeGeometry}, possibly shared by several meshes
|
|
5523
|
+
* (ref-counted via `retain`/`release`). Buffers are created lazily per requested key, so that only the layout
|
|
5524
|
+
* actually used by the pipelines (packed vs. split vertex attributes) occupies GPU memory.
|
|
5525
|
+
*/
|
|
5218
5526
|
class GeometryBuffer extends ManagedBufferBase {
|
|
5219
|
-
#
|
|
5220
|
-
#
|
|
5221
|
-
#geometryBuffers;
|
|
5527
|
+
#buffers = new Map();
|
|
5528
|
+
#flat;
|
|
5222
5529
|
constructor(geometry) {
|
|
5223
5530
|
super(geometry);
|
|
5224
5531
|
geometry.flags ??= [];
|
|
5225
5532
|
}
|
|
5226
5533
|
buffer(context, key) {
|
|
5227
|
-
const flags = this.item.flags ?? [];
|
|
5228
|
-
if (pacemCore.Utils.isNull(this.#geometryBuffers) || flags.includes(StalePropertyFlag.Geometry)) {
|
|
5229
|
-
flags.splice(0);
|
|
5230
|
-
this.#bufferBag = /* reset */ {};
|
|
5231
|
-
this._rebuildGeometryBuffers(context);
|
|
5232
|
-
}
|
|
5233
|
-
const freshness = this.#freshness;
|
|
5234
|
-
const geom = this.#geometryBuffers;
|
|
5235
|
-
const { pipeline } = context;
|
|
5236
|
-
const bag = (this.#bufferBag[key] ??= new Map());
|
|
5237
|
-
const newInPipeline = !bag.has(pipeline);
|
|
5238
|
-
const ensureInBag = (buffer) => {
|
|
5239
|
-
if (newInPipeline) {
|
|
5240
|
-
bag.set(pipeline, buffer);
|
|
5241
|
-
}
|
|
5242
|
-
return buffer;
|
|
5243
|
-
};
|
|
5244
5534
|
switch (key) {
|
|
5245
5535
|
case 'geometryPositions':
|
|
5246
|
-
const { positions } = geom, posFresh = freshness.positions;
|
|
5247
|
-
freshness.positions = false;
|
|
5248
|
-
return pacemCore.Utils.extend(ensureInBag(positions), { fresh: posFresh || newInPipeline });
|
|
5249
5536
|
case 'geometryNormals':
|
|
5250
|
-
const { normals } = geom, normFresh = freshness.normals;
|
|
5251
|
-
freshness.normals = false;
|
|
5252
|
-
return pacemCore.Utils.extend(ensureInBag(normals), { fresh: normFresh || newInPipeline });
|
|
5253
5537
|
case 'geometryTexCoords':
|
|
5254
|
-
const { uv } = geom, uvFresh = freshness.uv;
|
|
5255
|
-
freshness.uv = false;
|
|
5256
|
-
return pacemCore.Utils.extend({ fresh: uvFresh || newInPipeline }, ensureInBag(uv));
|
|
5257
5538
|
case 'geometry':
|
|
5258
|
-
|
|
5259
|
-
const { packed } = geom, geomFresh = freshness.packed;
|
|
5260
|
-
freshness.packed = false;
|
|
5261
|
-
return pacemCore.Utils.extend(ensureInBag(packed), { fresh: geomFresh || newInPipeline });
|
|
5539
|
+
break;
|
|
5262
5540
|
default:
|
|
5263
5541
|
throwBufferRequestError(key, GeometryBuffer);
|
|
5264
5542
|
}
|
|
5543
|
+
const flags = this.item.flags ?? [];
|
|
5544
|
+
if (flags.includes(StalePropertyFlag.Geometry)) {
|
|
5545
|
+
flags.splice(0);
|
|
5546
|
+
this._destroyBuffers();
|
|
5547
|
+
}
|
|
5548
|
+
// line (node) geometries expose their positions as a single storage buffer
|
|
5549
|
+
const normalizedKey = isMeshGeometry(this.item) ? key : 'geometryPositions';
|
|
5550
|
+
const buffers = this.#buffers;
|
|
5551
|
+
const existing = buffers.get(normalizedKey);
|
|
5552
|
+
if (!pacemCore.Utils.isNull(existing)) {
|
|
5553
|
+
return existing;
|
|
5554
|
+
}
|
|
5555
|
+
const created = this._createBuffer(context, normalizedKey);
|
|
5556
|
+
buffers.set(normalizedKey, created);
|
|
5557
|
+
return created;
|
|
5265
5558
|
}
|
|
5266
5559
|
texture(_) {
|
|
5267
5560
|
throw new Error("Method not implemented.");
|
|
5268
5561
|
}
|
|
5269
|
-
|
|
5270
|
-
|
|
5562
|
+
_flatten(geometry) {
|
|
5563
|
+
// flatten positions...
|
|
5564
|
+
const hasTriangleIndices = !pacemCore.Utils.isNullOrEmpty(geometry.triangleIndices);
|
|
5565
|
+
const positions = hasTriangleIndices ?
|
|
5566
|
+
geometry.triangleIndices.map(index => geometry.positions[index])
|
|
5567
|
+
: geometry.positions;
|
|
5568
|
+
return { positions, normals: geometry.normals, uvs: geometry.textureCoordinates };
|
|
5569
|
+
}
|
|
5570
|
+
_createBuffer({ device }, key) {
|
|
5271
5571
|
const version = performance.now();
|
|
5272
|
-
const geometry = this.item,
|
|
5273
|
-
if (isMeshGeometry(geometry)) {
|
|
5274
|
-
const
|
|
5275
|
-
|
|
5276
|
-
const
|
|
5277
|
-
|
|
5278
|
-
|
|
5279
|
-
|
|
5280
|
-
|
|
5281
|
-
|
|
5282
|
-
|
|
5283
|
-
|
|
5284
|
-
|
|
5285
|
-
|
|
5286
|
-
|
|
5287
|
-
|
|
5288
|
-
|
|
5289
|
-
|
|
5290
|
-
|
|
5291
|
-
|
|
5292
|
-
|
|
5293
|
-
|
|
5294
|
-
|
|
5295
|
-
|
|
5296
|
-
|
|
5297
|
-
|
|
5298
|
-
|
|
5299
|
-
|
|
5300
|
-
|
|
5301
|
-
|
|
5302
|
-
|
|
5303
|
-
|
|
5304
|
-
|
|
5305
|
-
|
|
5306
|
-
|
|
5307
|
-
|
|
5308
|
-
|
|
5309
|
-
|
|
5310
|
-
|
|
5311
|
-
|
|
5312
|
-
|
|
5313
|
-
|
|
5314
|
-
|
|
5315
|
-
|
|
5572
|
+
const geometry = this.item, geometryKey = geometry.key;
|
|
5573
|
+
if (!isMeshGeometry(geometry)) {
|
|
5574
|
+
const flatPositions = AdapterUtils.flattenVectorArray(geometry.positions);
|
|
5575
|
+
const positionsValue = new Float32Array(flatPositions);
|
|
5576
|
+
const positions = Buffers.createStorage(device, positionsValue, LABEL_PREFIX + 'nodegeometry-' + geometryKey + '-positions-buffer');
|
|
5577
|
+
return { buffer: positions, value: positionsValue, version };
|
|
5578
|
+
}
|
|
5579
|
+
this.#flat ??= this._flatten(geometry);
|
|
5580
|
+
const { positions, normals, uvs } = this.#flat;
|
|
5581
|
+
const count = positions.length;
|
|
5582
|
+
let value, label;
|
|
5583
|
+
switch (key) {
|
|
5584
|
+
case 'geometryPositions':
|
|
5585
|
+
value = new Float32Array(3 * count);
|
|
5586
|
+
for (let j = 0; j < count; j++) {
|
|
5587
|
+
const { x, y, z } = positions[j];
|
|
5588
|
+
value.set([x, y, z], 3 * j);
|
|
5589
|
+
}
|
|
5590
|
+
label = '-positions-buffer';
|
|
5591
|
+
break;
|
|
5592
|
+
case 'geometryNormals':
|
|
5593
|
+
value = new Float32Array(3 * count);
|
|
5594
|
+
for (let j = 0; j < count; j++) {
|
|
5595
|
+
const { x, y, z } = normals[j];
|
|
5596
|
+
value.set([x, y, z], 3 * j);
|
|
5597
|
+
}
|
|
5598
|
+
label = '-normals-buffer';
|
|
5599
|
+
break;
|
|
5600
|
+
case 'geometryTexCoords':
|
|
5601
|
+
value = new Float32Array(2 * count);
|
|
5602
|
+
for (let j = 0; j < count; j++) {
|
|
5603
|
+
const { x, y } = uvs[j];
|
|
5604
|
+
value.set([x, y], 2 * j);
|
|
5605
|
+
}
|
|
5606
|
+
label = '-uvmap-buffer';
|
|
5607
|
+
break;
|
|
5608
|
+
default:
|
|
5609
|
+
// alltogether (position + normal + uv, interleaved)
|
|
5610
|
+
value = new Float32Array(8 * count);
|
|
5611
|
+
for (let j = 0; j < count; j++) {
|
|
5612
|
+
const { x, y, z } = positions[j];
|
|
5613
|
+
const { x: nx, y: ny, z: nz } = normals[j];
|
|
5614
|
+
const { x: u, y: v } = uvs[j];
|
|
5615
|
+
value.set([x, y, z, nx, ny, nz, u, v], 8 * j);
|
|
5616
|
+
}
|
|
5617
|
+
label = '-buffer';
|
|
5618
|
+
break;
|
|
5316
5619
|
}
|
|
5620
|
+
const buffer = Buffers.create(device, value, LABEL_PREFIX + 'meshgeometry-' + geometryKey + label);
|
|
5621
|
+
return { buffer, value, version };
|
|
5317
5622
|
}
|
|
5318
5623
|
_destroyBuffers() {
|
|
5319
|
-
|
|
5320
|
-
const obsolete =
|
|
5321
|
-
|
|
5322
|
-
|
|
5323
|
-
|
|
5624
|
+
const values = this.#buffers.values();
|
|
5625
|
+
const obsolete = Array.from(values);
|
|
5626
|
+
this.#buffers.clear();
|
|
5627
|
+
this.#flat = null;
|
|
5628
|
+
this.destroySafely(...obsolete);
|
|
5324
5629
|
}
|
|
5325
5630
|
dispose() {
|
|
5326
5631
|
this._destroyBuffers();
|
|
@@ -5328,12 +5633,16 @@ fn computeOffsetPosition(p0: vec4f, p1: vec4f, index: u32) -> vec4f {
|
|
|
5328
5633
|
}
|
|
5329
5634
|
// #endregion
|
|
5330
5635
|
// #region MATERIAL
|
|
5636
|
+
/**
|
|
5637
|
+
* GPU buffers/textures of a {@link Material3D}, possibly shared by several meshes (ref-counted via `retain`/`release`).
|
|
5638
|
+
* Same-sized changes (e.g. color, opacity, viewport size for lines) are rewritten in place, so that bind groups
|
|
5639
|
+
* referencing the buffers stay valid.
|
|
5640
|
+
*/
|
|
5331
5641
|
class MaterialBuffer extends ManagedBufferBase {
|
|
5332
|
-
#bufferBag = {};
|
|
5333
|
-
#textureBag = {};
|
|
5334
5642
|
#wgpuMaterial;
|
|
5335
5643
|
#buffers = new Map();
|
|
5336
5644
|
#textures = new Map();
|
|
5645
|
+
#lineSize = { width: 0, height: 0 };
|
|
5337
5646
|
constructor(material) {
|
|
5338
5647
|
super(material);
|
|
5339
5648
|
material.flags ??= [];
|
|
@@ -5341,89 +5650,100 @@ fn computeOffsetPosition(p0: vec4f, p1: vec4f, index: u32) -> vec4f {
|
|
|
5341
5650
|
material.flags.push(StalePropertyFlag.Material);
|
|
5342
5651
|
}
|
|
5343
5652
|
}
|
|
5344
|
-
|
|
5653
|
+
_ensureUpToDate(context) {
|
|
5345
5654
|
const flags = this.item.flags ?? [];
|
|
5346
|
-
|
|
5347
|
-
if (
|
|
5348
|
-
|
|
5655
|
+
const stale = flags.includes(StalePropertyFlag.Material);
|
|
5656
|
+
if (!stale && !pacemCore.Utils.isNull(this.#wgpuMaterial)) {
|
|
5657
|
+
return;
|
|
5658
|
+
}
|
|
5659
|
+
if (stale) {
|
|
5349
5660
|
flags.splice(0);
|
|
5350
|
-
fresh = true;
|
|
5351
|
-
this.#textures.clear();
|
|
5352
|
-
this._resetMaterialBuffers();
|
|
5353
5661
|
}
|
|
5354
|
-
const
|
|
5355
|
-
|
|
5662
|
+
const material = Materials.create(this.item);
|
|
5663
|
+
this.#wgpuMaterial = material;
|
|
5664
|
+
this._rewriteBuffers(context, material);
|
|
5665
|
+
this._destroyTextures();
|
|
5666
|
+
}
|
|
5667
|
+
/** Rewrites the existing buffers in place (or drops them, to be recreated, should their size change). */
|
|
5668
|
+
_rewriteBuffers(context, material) {
|
|
5669
|
+
const buffers = this.#buffers;
|
|
5670
|
+
// deleting the current entry while iterating a Map is safe
|
|
5671
|
+
for (let [key, buffer] of buffers) {
|
|
5672
|
+
const value = material.value(context, key);
|
|
5673
|
+
const written = writeInPlace(context.device, buffer, value);
|
|
5674
|
+
if (!pacemCore.Utils.isNull(written)) {
|
|
5675
|
+
continue;
|
|
5676
|
+
}
|
|
5677
|
+
buffers.delete(key);
|
|
5678
|
+
this.destroySafely(buffer);
|
|
5679
|
+
}
|
|
5680
|
+
}
|
|
5681
|
+
buffer(context, key) {
|
|
5682
|
+
this._ensureUpToDate(context);
|
|
5356
5683
|
switch (key) {
|
|
5357
5684
|
case 'material':
|
|
5358
5685
|
case 'line':
|
|
5359
|
-
|
|
5360
|
-
if (buffer) {
|
|
5361
|
-
if (!bag.has(pipeline)) {
|
|
5362
|
-
fresh = true;
|
|
5363
|
-
bag.set(pipeline, buffer);
|
|
5364
|
-
}
|
|
5365
|
-
return pacemCore.Utils.extend(buffer, { fresh });
|
|
5366
|
-
}
|
|
5367
|
-
return null;
|
|
5686
|
+
return this._ensureMaterialBuffer(context, key);
|
|
5368
5687
|
default:
|
|
5369
5688
|
throwBufferRequestError(key, MaterialBuffer);
|
|
5370
5689
|
}
|
|
5371
5690
|
}
|
|
5372
|
-
_ensureMaterialBuffer(ctx, key
|
|
5373
|
-
const
|
|
5374
|
-
|
|
5375
|
-
|
|
5376
|
-
return retval;
|
|
5691
|
+
_ensureMaterialBuffer(ctx, key) {
|
|
5692
|
+
const existing = this.#buffers.get(key);
|
|
5693
|
+
if (pacemCore.Utils.isNull(existing)) {
|
|
5694
|
+
return this._createMaterialBuffer(ctx, key);
|
|
5377
5695
|
}
|
|
5378
|
-
if (
|
|
5696
|
+
if (key === 'line') {
|
|
5697
|
+
this._refreshLineSize(ctx, existing);
|
|
5698
|
+
}
|
|
5699
|
+
return existing;
|
|
5700
|
+
}
|
|
5701
|
+
_createMaterialBuffer(ctx, key) {
|
|
5702
|
+
const created = this.#wgpuMaterial.buffer(ctx, key);
|
|
5703
|
+
if (pacemCore.Utils.isNull(created)) {
|
|
5379
5704
|
return null;
|
|
5380
5705
|
}
|
|
5381
|
-
|
|
5382
|
-
if (
|
|
5383
|
-
|
|
5706
|
+
this.#buffers.set(key, created);
|
|
5707
|
+
if (key === 'line') {
|
|
5708
|
+
const { canvas } = ctx;
|
|
5709
|
+
this.#lineSize = { width: canvas.width, height: canvas.height };
|
|
5384
5710
|
}
|
|
5385
|
-
return
|
|
5711
|
+
return created;
|
|
5386
5712
|
}
|
|
5387
|
-
|
|
5388
|
-
|
|
5389
|
-
this
|
|
5713
|
+
/** Line params carry the render target size: rewrites them when it changes. */
|
|
5714
|
+
_refreshLineSize(ctx, buffer) {
|
|
5715
|
+
const { canvas } = ctx, size = this.#lineSize;
|
|
5716
|
+
if (size.width === canvas.width && size.height === canvas.height) {
|
|
5717
|
+
return;
|
|
5718
|
+
}
|
|
5719
|
+
this.#lineSize = { width: canvas.width, height: canvas.height };
|
|
5720
|
+
const value = this.#wgpuMaterial.value(ctx, 'line');
|
|
5721
|
+
writeInPlace(ctx.device, buffer, value);
|
|
5390
5722
|
}
|
|
5391
5723
|
texture(ctx, key = 'texture') {
|
|
5724
|
+
this._ensureUpToDate(ctx);
|
|
5392
5725
|
const set = this.#textures;
|
|
5393
|
-
|
|
5394
|
-
if (
|
|
5395
|
-
|
|
5396
|
-
if (!retval) {
|
|
5397
|
-
return null;
|
|
5398
|
-
}
|
|
5399
|
-
set.set(key, retval);
|
|
5400
|
-
fresh = true;
|
|
5401
|
-
//
|
|
5402
|
-
this.#textureBag = /* reset */ {};
|
|
5403
|
-
}
|
|
5404
|
-
const { pipeline } = ctx;
|
|
5405
|
-
const bag = (this.#textureBag[key] ??= new Map());
|
|
5406
|
-
if (!bag.has(pipeline)) {
|
|
5407
|
-
fresh = true;
|
|
5408
|
-
bag.set(pipeline, retval);
|
|
5726
|
+
// `null` is cached too (no texture for that key)
|
|
5727
|
+
if (set.has(key)) {
|
|
5728
|
+
return set.get(key);
|
|
5409
5729
|
}
|
|
5410
|
-
|
|
5730
|
+
const created = this.#wgpuMaterial.texture(ctx, key) ?? null;
|
|
5731
|
+
set.set(key, created);
|
|
5732
|
+
return created;
|
|
5411
5733
|
}
|
|
5412
|
-
|
|
5413
|
-
this.
|
|
5734
|
+
_destroyTextures() {
|
|
5735
|
+
const values = this.#textures.values();
|
|
5736
|
+
const textures = Array.from(values);
|
|
5737
|
+
this.#textures.clear(); // clear before destroying
|
|
5738
|
+
const existing = textures.filter(t => !pacemCore.Utils.isNull(t));
|
|
5739
|
+
this.destroySafely(...existing);
|
|
5414
5740
|
}
|
|
5415
|
-
|
|
5416
|
-
|
|
5417
|
-
|
|
5418
|
-
this.#textureBag = {};
|
|
5419
|
-
// buffers
|
|
5420
|
-
const buffers = this.#buffers.values();
|
|
5741
|
+
dispose() {
|
|
5742
|
+
const values = this.#buffers.values();
|
|
5743
|
+
const buffers = Array.from(values);
|
|
5421
5744
|
this.#buffers.clear(); // clear before destroying
|
|
5422
5745
|
this.destroySafely(...buffers);
|
|
5423
|
-
|
|
5424
|
-
const textures = this.#textures.values();
|
|
5425
|
-
this.#textures.clear(); // clear before destroying
|
|
5426
|
-
textures.forEach(t => t.texture.destroy());
|
|
5746
|
+
this._destroyTextures();
|
|
5427
5747
|
}
|
|
5428
5748
|
}
|
|
5429
5749
|
// #endregion
|
|
@@ -5433,10 +5753,8 @@ fn computeOffsetPosition(p0: vec4f, p1: vec4f, index: u32) -> vec4f {
|
|
|
5433
5753
|
time: 0, cursor: { x: 0, y: 0 }, resolution: { width: 0, height: 0 }
|
|
5434
5754
|
};
|
|
5435
5755
|
#buffer;
|
|
5436
|
-
#bufferBag = new Map();
|
|
5437
5756
|
constructor(data) {
|
|
5438
5757
|
super(data);
|
|
5439
|
-
pacemCore.Utils.extend(this.#fields, data);
|
|
5440
5758
|
}
|
|
5441
5759
|
buffer(context, key) {
|
|
5442
5760
|
switch (key) {
|
|
@@ -5450,42 +5768,42 @@ fn computeOffsetPosition(p0: vec4f, p1: vec4f, index: u32) -> vec4f {
|
|
|
5450
5768
|
texture(_) {
|
|
5451
5769
|
throw new Error("Method not implemented.");
|
|
5452
5770
|
}
|
|
5453
|
-
|
|
5771
|
+
/** Whether the interaction data differs from what was last uploaded. Allocation-free (called per mesh, per frame). */
|
|
5772
|
+
_hasChanged() {
|
|
5773
|
+
if (pacemCore.Utils.isNull(this.#buffer)) {
|
|
5774
|
+
return true;
|
|
5775
|
+
}
|
|
5454
5776
|
const fields = this.#fields, item = this.item;
|
|
5455
|
-
|
|
5456
|
-
|
|
5457
|
-
|
|
5458
|
-
|
|
5459
|
-
|
|
5460
|
-
|
|
5461
|
-
|
|
5462
|
-
|
|
5463
|
-
if (fresh) {
|
|
5464
|
-
// [4bytes cursor.x, 4bytes cursor.y, 4bytes resolution.width, 4bytes resolution.height, 4bytes time] = 20 bytes total]
|
|
5465
|
-
const value = new Float32Array([item.cursor?.x ?? 0, item.cursor?.y ?? 0, item.resolution.width, item.resolution.height, item.time, /* padding */ .0]);
|
|
5466
|
-
const buffer = Buffers.createUniform(ctx.device, value, LABEL_PREFIX + 'interaction-buffer');
|
|
5467
|
-
this.#buffer = { buffer, value, version: performance.now() };
|
|
5468
|
-
this.#bufferBag.clear();
|
|
5469
|
-
}
|
|
5470
|
-
const { pipeline } = ctx;
|
|
5471
|
-
const bag = this.#bufferBag;
|
|
5472
|
-
if (!bag.has(pipeline)) {
|
|
5473
|
-
fresh = true;
|
|
5474
|
-
bag.set(pipeline, this.#buffer);
|
|
5475
|
-
}
|
|
5476
|
-
return pacemCore.Utils.extend(this.#buffer, { fresh });
|
|
5777
|
+
if (item.time !== fields.time) {
|
|
5778
|
+
return true;
|
|
5779
|
+
}
|
|
5780
|
+
if (item.resolution?.width !== fields.resolution.width || item.resolution?.height !== fields.resolution.height) {
|
|
5781
|
+
return true;
|
|
5782
|
+
}
|
|
5783
|
+
const cursorX = item.cursor?.x ?? 0, cursorY = item.cursor?.y ?? 0;
|
|
5784
|
+
return cursorX !== fields.cursor.x || cursorY !== fields.cursor.y;
|
|
5477
5785
|
}
|
|
5478
|
-
|
|
5479
|
-
|
|
5480
|
-
|
|
5481
|
-
|
|
5482
|
-
|
|
5483
|
-
|
|
5484
|
-
|
|
5786
|
+
_ensureInteractionBuffer({ device }) {
|
|
5787
|
+
if (!this._hasChanged()) {
|
|
5788
|
+
return this.#buffer;
|
|
5789
|
+
}
|
|
5790
|
+
// [4bytes cursor.x, 4bytes cursor.y, 4bytes resolution.width, 4bytes resolution.height, 4bytes time] = 20 bytes total]
|
|
5791
|
+
const item = this.item;
|
|
5792
|
+
const cursor = { x: item.cursor?.x ?? 0, y: item.cursor?.y ?? 0 }, resolution = { width: item.resolution?.width ?? 0, height: item.resolution?.height ?? 0 };
|
|
5793
|
+
const value = new Float32Array([cursor.x, cursor.y, resolution.width, resolution.height, item.time, /* padding */ .0]);
|
|
5794
|
+
this.#fields = { time: item.time, cursor, resolution };
|
|
5795
|
+
const written = writeInPlace(device, this.#buffer, value);
|
|
5796
|
+
if (!pacemCore.Utils.isNull(written)) {
|
|
5797
|
+
return written;
|
|
5485
5798
|
}
|
|
5799
|
+
const buffer = Buffers.createUniform(device, value, LABEL_PREFIX + 'interaction-buffer');
|
|
5800
|
+
this.#buffer = { buffer, value, version: performance.now() };
|
|
5801
|
+
return this.#buffer;
|
|
5486
5802
|
}
|
|
5487
5803
|
dispose() {
|
|
5488
|
-
this
|
|
5804
|
+
const obsolete = this.#buffer;
|
|
5805
|
+
this.#buffer = null;
|
|
5806
|
+
this.destroySafely(obsolete);
|
|
5489
5807
|
}
|
|
5490
5808
|
}
|
|
5491
5809
|
// #endregion
|
|
@@ -5496,160 +5814,151 @@ fn computeOffsetPosition(p0: vec4f, p1: vec4f, index: u32) -> vec4f {
|
|
|
5496
5814
|
#materialBuffers;
|
|
5497
5815
|
#materialBuffer;
|
|
5498
5816
|
#worldTransform;
|
|
5499
|
-
#
|
|
5500
|
-
|
|
5501
|
-
};
|
|
5502
|
-
#worldTransformBufferBag = new Map();
|
|
5503
|
-
constructor(mesh, parent, geometries, materials) {
|
|
5817
|
+
#evaluatedAt = -1;
|
|
5818
|
+
constructor(mesh, parent, ...[geometries, materials]) {
|
|
5504
5819
|
super(mesh, parent);
|
|
5505
5820
|
mesh.flags ??= [];
|
|
5506
|
-
if (mesh.flags.indexOf(StalePropertyFlag.Geometry) === -1) {
|
|
5507
|
-
mesh.flags.push(StalePropertyFlag.Geometry);
|
|
5508
|
-
}
|
|
5509
|
-
if (mesh.flags.indexOf(StalePropertyFlag.Material) === -1) {
|
|
5510
|
-
mesh.flags.push(StalePropertyFlag.Material);
|
|
5511
|
-
}
|
|
5512
|
-
if (mesh.flags.indexOf(StalePropertyFlag.Position) === -1 && mesh.flags.indexOf(StalePropertyFlag.Transform) === -1) {
|
|
5513
|
-
mesh.flags.push(StalePropertyFlag.Transform);
|
|
5514
|
-
}
|
|
5515
5821
|
this.#geometryBuffers = geometries;
|
|
5516
5822
|
this.#materialBuffers = materials;
|
|
5517
5823
|
}
|
|
5518
5824
|
texture(ctx, key) {
|
|
5519
|
-
|
|
5520
|
-
return
|
|
5825
|
+
this._refresh(ctx);
|
|
5826
|
+
return this.#materialBuffer?.texture(ctx, key);
|
|
5521
5827
|
}
|
|
5522
|
-
|
|
5523
|
-
|
|
5828
|
+
/**
|
|
5829
|
+
* Brings transform, geometry and material up to date with the stale flags (own and inherited). Inherited flags
|
|
5830
|
+
* (stale ancestor groups, sealed by the looper only at the end of the pass) are evaluated once per pass.
|
|
5831
|
+
*/
|
|
5832
|
+
_refresh(context) {
|
|
5833
|
+
const reparented = this.consumeReparented();
|
|
5834
|
+
if (!reparented && this._isUpToDate()) {
|
|
5835
|
+
return;
|
|
5836
|
+
}
|
|
5524
5837
|
const flags = this.allFlags();
|
|
5525
|
-
|
|
5526
|
-
|
|
5527
|
-
// world transform bind group buffer
|
|
5528
|
-
freshness.transform = true;
|
|
5838
|
+
const transformStale = flags.includes(StalePropertyFlag.Position) || flags.includes(StalePropertyFlag.Transform);
|
|
5839
|
+
if (pacemCore.Utils.isNull(this.#worldTransform) || reparented || transformStale) {
|
|
5529
5840
|
this._rebuildWorldMatrices(context);
|
|
5530
5841
|
}
|
|
5531
5842
|
if (pacemCore.Utils.isNull(this.#geometryBuffer) || flags.includes(StalePropertyFlag.Geometry)) {
|
|
5532
|
-
// vertex buffers
|
|
5533
|
-
freshness.geometry = true;
|
|
5534
5843
|
this._ensureGeometryBuffer();
|
|
5535
5844
|
}
|
|
5536
5845
|
if (pacemCore.Utils.isNull(this.#materialBuffer) || flags.includes(StalePropertyFlag.Material)) {
|
|
5537
|
-
freshness.material = true;
|
|
5538
5846
|
this._ensureMaterialBuffer();
|
|
5539
5847
|
}
|
|
5848
|
+
this.#evaluatedAt = currentFrame;
|
|
5540
5849
|
RenderableBuffers.clearFlags(this);
|
|
5541
|
-
|
|
5542
|
-
|
|
5850
|
+
}
|
|
5851
|
+
/** Whether nothing needs a refresh: resources in place, no own stale flags, and inherited ones already evaluated in this pass (or absent). */
|
|
5852
|
+
_isUpToDate() {
|
|
5853
|
+
const ready = !pacemCore.Utils.isNull(this.#worldTransform) && !pacemCore.Utils.isNull(this.#geometryBuffer) && !pacemCore.Utils.isNull(this.#materialBuffer);
|
|
5854
|
+
if (!ready) {
|
|
5855
|
+
return false;
|
|
5856
|
+
}
|
|
5857
|
+
if (this.item.flags?.length > 0) {
|
|
5858
|
+
return false;
|
|
5859
|
+
}
|
|
5860
|
+
if (this.#evaluatedAt === currentFrame) {
|
|
5861
|
+
return true;
|
|
5862
|
+
}
|
|
5863
|
+
const parent = this.parent;
|
|
5864
|
+
if (pacemCore.Utils.isNull(parent)) {
|
|
5865
|
+
return true;
|
|
5866
|
+
}
|
|
5867
|
+
return !parent.hasFlags();
|
|
5868
|
+
}
|
|
5869
|
+
specificBuffer(context, key) {
|
|
5870
|
+
this._refresh(context);
|
|
5543
5871
|
switch (key) {
|
|
5544
5872
|
case 'geometryPositions':
|
|
5545
5873
|
case 'geometryNormals':
|
|
5546
5874
|
case 'geometryTexCoords':
|
|
5547
5875
|
case 'geometry':
|
|
5548
|
-
return
|
|
5876
|
+
return this.#geometryBuffer.buffer(context, key);
|
|
5549
5877
|
case 'material':
|
|
5550
5878
|
case 'line':
|
|
5551
|
-
return
|
|
5879
|
+
return this.#materialBuffer.buffer(context, key);
|
|
5552
5880
|
case 'objectWorldTransform':
|
|
5553
|
-
|
|
5554
|
-
freshness.transform = false;
|
|
5555
|
-
const bag = this.#worldTransformBufferBag, { pipeline } = context;
|
|
5556
|
-
const newInPipeline = !bag.has(pipeline);
|
|
5557
|
-
if (newInPipeline) {
|
|
5558
|
-
bag.set(pipeline, mat);
|
|
5559
|
-
}
|
|
5560
|
-
return pacemCore.Utils.extend(mat, { fresh: wFresh || newInPipeline });
|
|
5881
|
+
return this.#worldTransform;
|
|
5561
5882
|
default:
|
|
5562
5883
|
throwBufferRequestError(key, RenderableMeshBuffer);
|
|
5563
5884
|
}
|
|
5564
5885
|
}
|
|
5565
5886
|
_ensureGeometryBuffer() {
|
|
5566
5887
|
const current = this.#geometryBuffer;
|
|
5567
|
-
const
|
|
5568
|
-
|
|
5569
|
-
|
|
5570
|
-
// no cache provided? destroy and rebuild
|
|
5571
|
-
if (pacemCore.Utils.isNull(cache)) {
|
|
5572
|
-
current?.destroy();
|
|
5573
|
-
this.#geometryBuffer = new GeometryBuffer(geom);
|
|
5888
|
+
const geom = this.item.geometry;
|
|
5889
|
+
if (current?.item === geom && !current.disposed) {
|
|
5890
|
+
return;
|
|
5574
5891
|
}
|
|
5575
|
-
|
|
5576
|
-
|
|
5577
|
-
|
|
5578
|
-
|
|
5579
|
-
|
|
5580
|
-
}
|
|
5581
|
-
this.#geometryBuffer = buffer;
|
|
5892
|
+
const cache = this.#geometryBuffers;
|
|
5893
|
+
let buffer = cache?.get(geom);
|
|
5894
|
+
if (pacemCore.Utils.isNull(buffer) || buffer.disposed) {
|
|
5895
|
+
buffer = new GeometryBuffer(geom);
|
|
5896
|
+
cache?.set(geom, buffer);
|
|
5582
5897
|
}
|
|
5898
|
+
buffer.retain();
|
|
5899
|
+
this.#geometryBuffer = buffer;
|
|
5900
|
+
current?.release();
|
|
5583
5901
|
}
|
|
5584
5902
|
_ensureMaterialBuffer() {
|
|
5585
5903
|
const current = this.#materialBuffer;
|
|
5586
|
-
const
|
|
5587
|
-
|
|
5588
|
-
|
|
5589
|
-
// no cache provided? destroy and rebuild
|
|
5590
|
-
if (pacemCore.Utils.isNull(cache)) {
|
|
5591
|
-
current?.destroy();
|
|
5592
|
-
this.#materialBuffer = new MaterialBuffer(material);
|
|
5904
|
+
const material = this.item.material ?? DefaultMaterial;
|
|
5905
|
+
if (current?.item === material && !current.disposed) {
|
|
5906
|
+
return;
|
|
5593
5907
|
}
|
|
5594
|
-
|
|
5595
|
-
|
|
5596
|
-
|
|
5597
|
-
|
|
5598
|
-
|
|
5599
|
-
}
|
|
5600
|
-
this.#materialBuffer = buffer;
|
|
5908
|
+
const cache = this.#materialBuffers;
|
|
5909
|
+
let buffer = cache?.get(material);
|
|
5910
|
+
if (pacemCore.Utils.isNull(buffer) || buffer.disposed) {
|
|
5911
|
+
buffer = new MaterialBuffer(material);
|
|
5912
|
+
cache?.set(material, buffer);
|
|
5601
5913
|
}
|
|
5914
|
+
buffer.retain();
|
|
5915
|
+
this.#materialBuffer = buffer;
|
|
5916
|
+
current?.release();
|
|
5602
5917
|
}
|
|
5603
5918
|
_rebuildWorldMatrices({ device }) {
|
|
5604
|
-
//this.destroySafely(this.#worldTransform);
|
|
5605
5919
|
const item = this.item;
|
|
5606
5920
|
const matrix = this.buildWorldTransform();
|
|
5607
|
-
const
|
|
5921
|
+
const inverse = Matrix3D$1.invert(matrix);
|
|
5922
|
+
const normal = Matrix3D$1.transpose(inverse);
|
|
5923
|
+
const matrixArray = Matrix3D$1.toArray(matrix);
|
|
5608
5924
|
const value = new Float32Array(28);
|
|
5609
|
-
value.set(
|
|
5925
|
+
value.set(matrixArray, 0);
|
|
5610
5926
|
value.set([normal.m11, normal.m12, normal.m13, 0, normal.m21, normal.m22, normal.m23, 0, normal.m31, normal.m32, normal.m33, 0], 16);
|
|
5611
|
-
//const current = this.#worldTransform;
|
|
5612
5927
|
// reuse GPUBuffer (always same size)
|
|
5613
|
-
|
|
5614
|
-
|
|
5615
|
-
|
|
5616
|
-
}
|
|
5617
|
-
else {
|
|
5618
|
-
this.#worldTransform.value = value;
|
|
5619
|
-
this.#worldTransform.version = performance.now().roundoff();
|
|
5928
|
+
const written = writeInPlace(device, this.#worldTransform, value);
|
|
5929
|
+
if (!pacemCore.Utils.isNull(written)) {
|
|
5930
|
+
return;
|
|
5620
5931
|
}
|
|
5621
|
-
|
|
5622
|
-
|
|
5623
|
-
|
|
5932
|
+
const buffer = Buffers.createUniform(device, value, LABEL_PREFIX + 'mesh-' + item.key + '-worldmatrix-buffer');
|
|
5933
|
+
const version = performance.now().roundoff();
|
|
5934
|
+
this.#worldTransform = { buffer, value, version };
|
|
5624
5935
|
}
|
|
5625
5936
|
dispose() {
|
|
5626
|
-
// memoizer
|
|
5627
|
-
this.#worldTransformBufferBag.clear();
|
|
5628
5937
|
const world = this.#worldTransform;
|
|
5629
5938
|
this.#worldTransform = null;
|
|
5630
5939
|
this.destroySafely(world);
|
|
5940
|
+
// shared buffers: just unregister
|
|
5631
5941
|
const material = this.#materialBuffer;
|
|
5632
5942
|
this.#materialBuffer = null;
|
|
5633
|
-
material?.
|
|
5943
|
+
material?.release();
|
|
5634
5944
|
const geometry = this.#geometryBuffer;
|
|
5635
5945
|
this.#geometryBuffer = null;
|
|
5636
|
-
geometry?.
|
|
5946
|
+
geometry?.release();
|
|
5637
5947
|
}
|
|
5638
5948
|
}
|
|
5639
5949
|
// #endregion
|
|
5640
5950
|
// #region LIGHTS
|
|
5641
5951
|
class RenderableLightBuffer extends RenderableBufferBase {
|
|
5642
5952
|
#buffer;
|
|
5643
|
-
#bufferBag = new Map();
|
|
5644
5953
|
constructor(light) {
|
|
5645
5954
|
super(light);
|
|
5955
|
+
light.flags ??= [];
|
|
5646
5956
|
light.flags.push(StalePropertyFlag.Light);
|
|
5647
5957
|
}
|
|
5648
5958
|
/**
|
|
5649
|
-
* Ambient light buffer
|
|
5650
|
-
* @param param0
|
|
5959
|
+
* Ambient light buffer values
|
|
5651
5960
|
*/
|
|
5652
|
-
|
|
5961
|
+
_ambientLightValues() {
|
|
5653
5962
|
const light = this.item;
|
|
5654
5963
|
// sizes/offsets
|
|
5655
5964
|
const offsetColor = 0, offsetIntensity = 4;
|
|
@@ -5660,13 +5969,12 @@ fn computeOffsetPosition(p0: vec4f, p1: vec4f, index: u32) -> vec4f {
|
|
|
5660
5969
|
values.set([r, g, b, a], offsetColor);
|
|
5661
5970
|
// intensity
|
|
5662
5971
|
values.set([light.intensity], offsetIntensity);
|
|
5663
|
-
|
|
5972
|
+
return values;
|
|
5664
5973
|
}
|
|
5665
5974
|
/**
|
|
5666
|
-
* Directional light buffer
|
|
5667
|
-
* @param param0
|
|
5975
|
+
* Directional light buffer values
|
|
5668
5976
|
*/
|
|
5669
|
-
|
|
5977
|
+
_directionalLightValues() {
|
|
5670
5978
|
const light = this.item;
|
|
5671
5979
|
// sizes/offsets
|
|
5672
5980
|
const szIntensity = 1, offsetColor = 0, offsetDirection = 4, // see: https://www.w3.org/TR/WGSL/#memory-layouts
|
|
@@ -5681,13 +5989,12 @@ fn computeOffsetPosition(p0: vec4f, p1: vec4f, index: u32) -> vec4f {
|
|
|
5681
5989
|
// direction
|
|
5682
5990
|
const direction = Vector3D$2.subtract(light.position, light.target);
|
|
5683
5991
|
values.set([direction.x, direction.y, direction.z], offsetDirection);
|
|
5684
|
-
|
|
5992
|
+
return values;
|
|
5685
5993
|
}
|
|
5686
5994
|
/**
|
|
5687
|
-
* Omni light buffer
|
|
5688
|
-
* @param param0
|
|
5995
|
+
* Omni light buffer values
|
|
5689
5996
|
*/
|
|
5690
|
-
|
|
5997
|
+
_omniLightValues() {
|
|
5691
5998
|
const light = this.item;
|
|
5692
5999
|
// sizes/offsets
|
|
5693
6000
|
const szIntensity = 1, offsetColor = 0, offsetPosition = 4, // see: https://www.w3.org/TR/WGSL/#memory-layouts
|
|
@@ -5701,48 +6008,47 @@ fn computeOffsetPosition(p0: vec4f, p1: vec4f, index: u32) -> vec4f {
|
|
|
5701
6008
|
values.set([light.intensity], offsetIntensity);
|
|
5702
6009
|
// position
|
|
5703
6010
|
values.set([light.position.x, light.position.y, light.position.z], offsetPosition);
|
|
5704
|
-
|
|
6011
|
+
return values;
|
|
5705
6012
|
}
|
|
5706
|
-
_rebuildLight(
|
|
5707
|
-
this.destroySafely(this.#buffer);
|
|
6013
|
+
_rebuildLight({ device }) {
|
|
5708
6014
|
const light = this.item;
|
|
6015
|
+
let values;
|
|
5709
6016
|
switch (light.type) {
|
|
5710
6017
|
case 'direction':
|
|
5711
|
-
this.
|
|
6018
|
+
values = this._directionalLightValues();
|
|
5712
6019
|
break;
|
|
5713
6020
|
case 'omni':
|
|
5714
|
-
this.
|
|
6021
|
+
values = this._omniLightValues();
|
|
5715
6022
|
break;
|
|
5716
6023
|
case 'ambient':
|
|
5717
|
-
this.
|
|
6024
|
+
values = this._ambientLightValues();
|
|
5718
6025
|
break;
|
|
5719
6026
|
default:
|
|
5720
6027
|
throw new Error(`Light '${light.type}' is not supported.`);
|
|
5721
6028
|
}
|
|
6029
|
+
// same-sized (i.e. same type) lights get rewritten in place
|
|
6030
|
+
const written = writeInPlace(device, this.#buffer, values);
|
|
6031
|
+
if (!pacemCore.Utils.isNull(written)) {
|
|
6032
|
+
return;
|
|
6033
|
+
}
|
|
6034
|
+
this.destroySafely(this.#buffer);
|
|
6035
|
+
const buffer = Buffers.createUniform(device, values, LABEL_PREFIX + light.type + '-light-buffer');
|
|
6036
|
+
this.#buffer = { value: values, buffer, version: performance.now() };
|
|
5722
6037
|
}
|
|
5723
6038
|
texture(_) {
|
|
5724
6039
|
throw new Error("Method not implemented.");
|
|
5725
6040
|
}
|
|
5726
6041
|
specificBuffer(context, key) {
|
|
5727
|
-
|
|
5728
|
-
let fresh = pacemCore.Utils.isNull(this.#buffer) || this.allFlags().length > 0;
|
|
5729
|
-
if (fresh) {
|
|
5730
|
-
bag.clear();
|
|
6042
|
+
if (pacemCore.Utils.isNull(this.#buffer) || this.hasFlags()) {
|
|
5731
6043
|
this._rebuildLight(context);
|
|
5732
6044
|
}
|
|
5733
6045
|
RenderableBuffers.clearFlags(this);
|
|
5734
|
-
const { pipeline } = context;
|
|
5735
|
-
if (!bag.has(pipeline)) {
|
|
5736
|
-
fresh = true;
|
|
5737
|
-
bag.set(pipeline, this.#buffer);
|
|
5738
|
-
}
|
|
5739
6046
|
if (key === 'light') {
|
|
5740
|
-
return
|
|
6047
|
+
return this.#buffer;
|
|
5741
6048
|
}
|
|
5742
6049
|
throwBufferRequestError(key, RenderableLightBuffer);
|
|
5743
6050
|
}
|
|
5744
6051
|
dispose() {
|
|
5745
|
-
this.#bufferBag.clear();
|
|
5746
6052
|
const buffer = this.#buffer;
|
|
5747
6053
|
this.#buffer = null;
|
|
5748
6054
|
this.destroySafely(buffer);
|
|
@@ -5762,13 +6068,79 @@ fn computeOffsetPosition(p0: vec4f, p1: vec4f, index: u32) -> vec4f {
|
|
|
5762
6068
|
cullMode: 'back'
|
|
5763
6069
|
}
|
|
5764
6070
|
};
|
|
6071
|
+
/** Straight (non-premultiplied) "over" blending, applied to both color and alpha so that translucent fragments never lower the coverage already in the target. */
|
|
6072
|
+
const ALPHA_BLENDING = {
|
|
6073
|
+
color: {
|
|
6074
|
+
srcFactor: 'src-alpha',
|
|
6075
|
+
dstFactor: 'one-minus-src-alpha'
|
|
6076
|
+
},
|
|
6077
|
+
alpha: {
|
|
6078
|
+
srcFactor: 'one',
|
|
6079
|
+
dstFactor: 'one-minus-src-alpha'
|
|
6080
|
+
},
|
|
6081
|
+
};
|
|
6082
|
+
/** Part of the pipeline memo key depending on the {@link PipelineOptions} (everything affecting the built {@link GPURenderPipeline}). */
|
|
6083
|
+
function optionsKey(pipelineOptions) {
|
|
6084
|
+
const options = pacemCore.Utils.extend({}, DefaultPipelineOptions, pipelineOptions ?? {});
|
|
6085
|
+
const primitive = options.primitive ?? {};
|
|
6086
|
+
return [options.modifiers?.version ?? '', options.packedVertices ? 'packed' : 'split', options.multisample ? 'msaa' : 'nomsaa',
|
|
6087
|
+
primitive.topology ?? '', primitive.cullMode ?? '', primitive.frontFace ?? ''].join('|');
|
|
6088
|
+
}
|
|
5765
6089
|
const EMPTY_BIND_DELEGATE = (_) => { };
|
|
6090
|
+
/** Maps the indices `0..count-1` through `selector`. */
|
|
6091
|
+
function mapIndices(count, selector) {
|
|
6092
|
+
const indices = Array(count).keys();
|
|
6093
|
+
return Array.from(indices, selector);
|
|
6094
|
+
}
|
|
6095
|
+
const passStates = new WeakMap();
|
|
6096
|
+
function passStateOf(pass) {
|
|
6097
|
+
const existing = passStates.get(pass);
|
|
6098
|
+
if (!pacemCore.Utils.isNull(existing)) {
|
|
6099
|
+
return existing;
|
|
6100
|
+
}
|
|
6101
|
+
const state = { groups: [], vertexBuffers: [] };
|
|
6102
|
+
passStates.set(pass, state);
|
|
6103
|
+
return state;
|
|
6104
|
+
}
|
|
6105
|
+
/**
|
|
6106
|
+
* Thin wrappers around the {@link GPURenderPassEncoder} state setters skipping redundant calls (same pipeline, same
|
|
6107
|
+
* bind group object at the same index, same vertex buffer at the same slot), which are the vast majority when many
|
|
6108
|
+
* meshes share pipelines, cameras, lights, materials and geometries. Bound state persists across `setPipeline` in
|
|
6109
|
+
* WebGPU, so skipping identical objects is always safe.
|
|
6110
|
+
*/
|
|
6111
|
+
const PassUtils = {
|
|
6112
|
+
setPipeline: (pass, pipeline) => {
|
|
6113
|
+
const state = passStateOf(pass);
|
|
6114
|
+
if (state.pipeline === pipeline) {
|
|
6115
|
+
return;
|
|
6116
|
+
}
|
|
6117
|
+
pass.setPipeline(pipeline);
|
|
6118
|
+
state.pipeline = pipeline;
|
|
6119
|
+
},
|
|
6120
|
+
setBindGroup: (pass, index, group) => {
|
|
6121
|
+
const state = passStateOf(pass);
|
|
6122
|
+
if (state.groups[index] === group) {
|
|
6123
|
+
return;
|
|
6124
|
+
}
|
|
6125
|
+
pass.setBindGroup(index, group);
|
|
6126
|
+
state.groups[index] = group;
|
|
6127
|
+
},
|
|
6128
|
+
setVertexBuffer: (pass, slot, buffer) => {
|
|
6129
|
+
const state = passStateOf(pass);
|
|
6130
|
+
if (state.vertexBuffers[slot] === buffer) {
|
|
6131
|
+
return;
|
|
6132
|
+
}
|
|
6133
|
+
pass.setVertexBuffer(slot, buffer);
|
|
6134
|
+
state.vertexBuffers[slot] = buffer;
|
|
6135
|
+
}
|
|
6136
|
+
};
|
|
6137
|
+
// #endregion
|
|
5766
6138
|
/**
|
|
5767
6139
|
* Factory for {@link RenderPipeline}s: given a {@link Context} and a set of {@link RenderableBuffer}s (a mesh/line plus its
|
|
5768
6140
|
* camera and lights), builds the WGSL shaders, {@link GPUBindGroupLayout}s, {@link GPUPipelineLayout} and the underlying
|
|
5769
6141
|
* {@link GPURenderPipeline}(s) needed to draw (and, separately, color-pick/raycast) that combination. Built pipelines are
|
|
5770
6142
|
* memoized per {@link Context} and reused as long as the shader "recipe" (mesh material/shader, light count/types, WGSL
|
|
5771
|
-
* modifier version) doesn't change. This is the machinery {@link Pacem3DWebgpuAdapterElement}'s {@link Renderer} implementation
|
|
6143
|
+
* modifier version, pipeline options) doesn't change. This is the machinery {@link Pacem3DWebgpuAdapterElement}'s {@link Renderer} implementation
|
|
5772
6144
|
* (`renderer.ts`) drives every frame.
|
|
5773
6145
|
*/
|
|
5774
6146
|
class RenderPipelines {
|
|
@@ -5787,16 +6159,16 @@ fn computeOffsetPosition(p0: vec4f, p1: vec4f, index: u32) -> vec4f {
|
|
|
5787
6159
|
* {@link RenderPipeline}, whose `frame` delegate draws object ids into an `r32uint` target instead of the normal color target.
|
|
5788
6160
|
* Returns `null` if the resolved pipeline isn't a mesh or line pipeline (i.e. doesn't support raycasting).
|
|
5789
6161
|
* @param items The mesh/line, camera and lights to raycast, in the same shape expected by {@link create}.
|
|
6162
|
+
* @param pipelineOptions The same options used to render, so that the displayed pipeline (WGSL modifiers included) gets reused.
|
|
5790
6163
|
*/
|
|
5791
|
-
static createColorPicking(ctx, items) {
|
|
5792
|
-
const renderPipeline = RenderPipelines.create(ctx, items);
|
|
5793
|
-
if (renderPipeline
|
|
5794
|
-
|
|
5795
|
-
return {
|
|
5796
|
-
frame: renderPipeline.raycast
|
|
5797
|
-
};
|
|
6164
|
+
static createColorPicking(ctx, items, pipelineOptions) {
|
|
6165
|
+
const renderPipeline = RenderPipelines.create(ctx, items, pipelineOptions);
|
|
6166
|
+
if (pacemCore.Utils.isNull(renderPipeline.raycast)) {
|
|
6167
|
+
return null;
|
|
5798
6168
|
}
|
|
5799
|
-
return
|
|
6169
|
+
return {
|
|
6170
|
+
frame: renderPipeline.raycast
|
|
6171
|
+
};
|
|
5800
6172
|
}
|
|
5801
6173
|
/**
|
|
5802
6174
|
* Builds (or returns the memoized) {@link RenderPipeline} for the given renderables: the first buffer must wrap a
|
|
@@ -5804,8 +6176,8 @@ fn computeOffsetPosition(p0: vec4f, p1: vec4f, index: u32) -> vec4f {
|
|
|
5804
6176
|
* and zero or more {@link Light} buffers. Generates the mesh/line's WGSL vertex and fragment shaders (via
|
|
5805
6177
|
* {@link MeshWGSLBuilder}/{@link LineWGSLBuilder}), compiles them into {@link GPUShaderModule}s, creates the
|
|
5806
6178
|
* {@link GPUBindGroupLayout}s/{@link GPUPipelineLayout} and the resulting {@link GPURenderPipeline} (plus a matching
|
|
5807
|
-
* color-picking pipeline). The pipeline is cached per {@link Context} keyed by shader "recipe" +
|
|
5808
|
-
* so repeated calls with an equivalent recipe skip rebuilding.
|
|
6179
|
+
* color-picking pipeline). The pipeline is cached per {@link Context} keyed by shader "recipe" + pipeline options
|
|
6180
|
+
* (WGSL modifiers version included), so repeated calls with an equivalent recipe skip rebuilding.
|
|
5809
6181
|
* @param ctx WebGPU context (device/canvas/format) to build the pipeline against.
|
|
5810
6182
|
* @param items `[mesh, camera, ...lights]` renderable buffers.
|
|
5811
6183
|
* @param pipelineOptions Optional overrides for primitive topology, multisampling, vertex packing and WGSL modifiers.
|
|
@@ -5813,86 +6185,105 @@ fn computeOffsetPosition(p0: vec4f, p1: vec4f, index: u32) -> vec4f {
|
|
|
5813
6185
|
* @throws {Error} If no mesh is provided, the mesh's geometry/material combination isn't supported, or the first argument isn't a mesh.
|
|
5814
6186
|
*/
|
|
5815
6187
|
static create(ctx, [mesh, camera, ...lights], pipelineOptions) {
|
|
5816
|
-
|
|
5817
|
-
|
|
5818
|
-
if (pacemCore.Utils.isNull(cache)) {
|
|
5819
|
-
memoizer.set(ctx, cache = new Map());
|
|
5820
|
-
}
|
|
5821
|
-
//const camera = items.find(i => isCamera(i.item));
|
|
5822
|
-
//const lights = items.filter(i => isLight(i.item));
|
|
5823
|
-
//// find main object
|
|
5824
|
-
//const mesh = items.find(i => isMesh(i.item));
|
|
5825
|
-
if (!pacemCore.Utils.isNull(mesh)) {
|
|
5826
|
-
if (isMesh(mesh.item)) {
|
|
5827
|
-
const isMesh = isMeshGeometry(mesh.item.geometry);
|
|
5828
|
-
const isLine = !isMesh && isLineMaterial(mesh.item.material);
|
|
5829
|
-
if (!isMesh && !isLine) {
|
|
5830
|
-
throw new Error('Pipeline not implemented, given the provided mesh argument.');
|
|
5831
|
-
}
|
|
5832
|
-
const builder = isMesh ? new MeshWGSLBuilder(mesh, camera, ...lights)
|
|
5833
|
-
: new LineWGSLBuilder(mesh, camera);
|
|
5834
|
-
// cache peek for sudden return
|
|
5835
|
-
const key = builder.key + (pipelineOptions?.modifiers?.version ?? '');
|
|
5836
|
-
const found = cache.get(key);
|
|
5837
|
-
if (found) {
|
|
5838
|
-
return found;
|
|
5839
|
-
}
|
|
5840
|
-
const pipeline = isMesh ? new MeshRenderPipelineClass(ctx, builder)
|
|
5841
|
-
: new LineRenderPipelineClass(ctx, builder);
|
|
5842
|
-
// no cache -> build it
|
|
5843
|
-
pipeline.build(pipelineOptions);
|
|
5844
|
-
const retval = pipeline;
|
|
5845
|
-
pacemCore.Utils.extend(retval, {
|
|
5846
|
-
id: key + '-' + ctx.canvas.width + 'x' + ctx.canvas.height + '-' + pacemCore.Utils.Dates.now().toISOString()
|
|
5847
|
-
});
|
|
5848
|
-
cache.set(key, retval);
|
|
5849
|
-
return retval;
|
|
5850
|
-
}
|
|
5851
|
-
else {
|
|
5852
|
-
throw new ReferenceError('Pipeline not implemented, given thst the first argument is not a mesh.');
|
|
5853
|
-
}
|
|
6188
|
+
if (pacemCore.Utils.isNull(mesh)) {
|
|
6189
|
+
throw new Error('Pipeline not implemented, given the provided arguments.');
|
|
5854
6190
|
}
|
|
5855
|
-
|
|
5856
|
-
throw new
|
|
6191
|
+
if (!isMesh(mesh.item)) {
|
|
6192
|
+
throw new ReferenceError('Pipeline not implemented, given thst the first argument is not a mesh.');
|
|
6193
|
+
}
|
|
6194
|
+
const isMeshPipeline = isMeshGeometry(mesh.item.geometry);
|
|
6195
|
+
const isLinePipeline = !isMeshPipeline && isLineMaterial(mesh.item.material);
|
|
6196
|
+
if (!isMeshPipeline && !isLinePipeline) {
|
|
6197
|
+
throw new Error('Pipeline not implemented, given the provided mesh argument.');
|
|
6198
|
+
}
|
|
6199
|
+
const cache = RenderPipelines._ensureCache(ctx);
|
|
6200
|
+
const builder = isMeshPipeline ? new MeshWGSLBuilder(mesh, camera, ...lights)
|
|
6201
|
+
: new LineWGSLBuilder(mesh, camera);
|
|
6202
|
+
// cache peek for sudden return
|
|
6203
|
+
const recipeKey = optionsKey(pipelineOptions);
|
|
6204
|
+
const key = builder.key + '|' + recipeKey;
|
|
6205
|
+
const found = cache.get(key);
|
|
6206
|
+
if (found) {
|
|
6207
|
+
return found;
|
|
6208
|
+
}
|
|
6209
|
+
const pipeline = isMeshPipeline ? new MeshRenderPipelineClass(ctx, builder)
|
|
6210
|
+
: new LineRenderPipelineClass(ctx, builder);
|
|
6211
|
+
// no cache -> build it
|
|
6212
|
+
pipeline.build(pipelineOptions);
|
|
6213
|
+
const timestamp = pacemCore.Utils.Dates.now().toISOString();
|
|
6214
|
+
pacemCore.Utils.extend(pipeline, {
|
|
6215
|
+
id: key + '-' + ctx.canvas.width + 'x' + ctx.canvas.height + '-' + timestamp
|
|
6216
|
+
});
|
|
6217
|
+
cache.set(key, pipeline);
|
|
6218
|
+
return pipeline;
|
|
6219
|
+
}
|
|
6220
|
+
static _ensureCache(ctx) {
|
|
6221
|
+
const memoizer = RenderPipelines._memoizer;
|
|
6222
|
+
const existing = memoizer.get(ctx);
|
|
6223
|
+
if (!pacemCore.Utils.isNull(existing)) {
|
|
6224
|
+
return existing;
|
|
5857
6225
|
}
|
|
6226
|
+
const cache = new Map();
|
|
6227
|
+
memoizer.set(ctx, cache);
|
|
6228
|
+
return cache;
|
|
6229
|
+
}
|
|
6230
|
+
}
|
|
6231
|
+
/** Gets the map stored under `key`, creating (and storing) an empty one when missing. */
|
|
6232
|
+
function ensureEntry(maps, key) {
|
|
6233
|
+
const existing = maps.get(key);
|
|
6234
|
+
if (!pacemCore.Utils.isNull(existing)) {
|
|
6235
|
+
return existing;
|
|
6236
|
+
}
|
|
6237
|
+
const created = new Map();
|
|
6238
|
+
maps.set(key, created);
|
|
6239
|
+
return created;
|
|
6240
|
+
}
|
|
6241
|
+
/** Whether `cached` was built against the very same layout and resources (identity), hence can be reused. */
|
|
6242
|
+
function isReusable(cached, layout, resources) {
|
|
6243
|
+
if (pacemCore.Utils.isNull(cached) || cached.layout !== layout) {
|
|
6244
|
+
return false;
|
|
5858
6245
|
}
|
|
6246
|
+
if (cached.resources.length !== resources.length) {
|
|
6247
|
+
return false;
|
|
6248
|
+
}
|
|
6249
|
+
return cached.resources.every((r, i) => r === resources[i]);
|
|
5859
6250
|
}
|
|
6251
|
+
function toBindGroupEntry(e) {
|
|
6252
|
+
if (pacemCore.Utils.isNull(e.buffer)) {
|
|
6253
|
+
return { binding: e.binding, resource: e.resource };
|
|
6254
|
+
}
|
|
6255
|
+
return { binding: e.binding, resource: { buffer: e.buffer } };
|
|
6256
|
+
}
|
|
6257
|
+
/**
|
|
6258
|
+
* Per-pipeline {@link GPUBindGroup} cache. A bind group depends only on the identity of the resources it references
|
|
6259
|
+
* (their contents are uploaded by the owning {@link ManagedBuffer}s), so a cached group is reused until any of those
|
|
6260
|
+
* resources (or the layout) is a different object. Entries are kept per `owner` (an object, weakly, or a string key)
|
|
6261
|
+
* and `label`, so they get collected together with the owning renderables.
|
|
6262
|
+
*/
|
|
5860
6263
|
class RenderPipelineCache {
|
|
5861
|
-
|
|
5862
|
-
|
|
5863
|
-
|
|
5864
|
-
|
|
5865
|
-
|
|
5866
|
-
|
|
5867
|
-
|
|
5868
|
-
|
|
5869
|
-
|
|
5870
|
-
|
|
5871
|
-
|
|
5872
|
-
|
|
5873
|
-
|
|
5874
|
-
|
|
5875
|
-
|
|
5876
|
-
|
|
5877
|
-
|
|
5878
|
-
|
|
5879
|
-
|
|
5880
|
-
|
|
5881
|
-
|
|
5882
|
-
|
|
5883
|
-
|
|
5884
|
-
layout,
|
|
5885
|
-
entries
|
|
5886
|
-
};
|
|
5887
|
-
// custom config happens here
|
|
5888
|
-
callback(descriptor);
|
|
5889
|
-
const retval = device.createBindGroup(descriptor);
|
|
5890
|
-
set.set(label, retval);
|
|
5891
|
-
return retval;
|
|
5892
|
-
}
|
|
5893
|
-
else {
|
|
5894
|
-
return set.get(label);
|
|
5895
|
-
}
|
|
6264
|
+
#objects = new WeakMap();
|
|
6265
|
+
#strings = new Map();
|
|
6266
|
+
_ensureSet(owner) {
|
|
6267
|
+
if (typeof owner === 'string') {
|
|
6268
|
+
return ensureEntry(this.#strings, owner);
|
|
6269
|
+
}
|
|
6270
|
+
return ensureEntry(this.#objects, owner);
|
|
6271
|
+
}
|
|
6272
|
+
ensureBindGroup({ device }, owner, label, layout, entries) {
|
|
6273
|
+
const set = this._ensureSet(owner);
|
|
6274
|
+
const cached = set.get(label);
|
|
6275
|
+
const resources = entries.map(e => e.buffer ?? e.resource);
|
|
6276
|
+
if (isReusable(cached, layout, resources)) {
|
|
6277
|
+
return cached.group;
|
|
6278
|
+
}
|
|
6279
|
+
const groupEntries = entries.map(toBindGroupEntry);
|
|
6280
|
+
const group = device.createBindGroup({
|
|
6281
|
+
label,
|
|
6282
|
+
layout,
|
|
6283
|
+
entries: groupEntries
|
|
6284
|
+
});
|
|
6285
|
+
set.set(label, { group, layout, resources });
|
|
6286
|
+
return group;
|
|
5896
6287
|
}
|
|
5897
6288
|
}
|
|
5898
6289
|
class MeshWGSLBuilder {
|
|
@@ -5916,7 +6307,8 @@ fn computeOffsetPosition(p0: vec4f, p1: vec4f, index: u32) -> vec4f {
|
|
|
5916
6307
|
if (pacemCore.Utils.isNull(this.#mesh)) {
|
|
5917
6308
|
this.#mesh = obj;
|
|
5918
6309
|
const material = obj.item.material ?? { shader: KnownShader.Basic };
|
|
5919
|
-
|
|
6310
|
+
// the (loaded) texture, not the map url, decides the shader and layout
|
|
6311
|
+
this.#key.shader = material.shader + '-' + (material.texture ? 'map' : 'nomap');
|
|
5920
6312
|
}
|
|
5921
6313
|
else {
|
|
5922
6314
|
throw new Error('Mesh already added.');
|
|
@@ -5941,7 +6333,7 @@ fn computeOffsetPosition(p0: vec4f, p1: vec4f, index: u32) -> vec4f {
|
|
|
5941
6333
|
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);
|
|
5942
6334
|
const metadata = {
|
|
5943
6335
|
lightCount: this.#lights.length,
|
|
5944
|
-
mapCount:
|
|
6336
|
+
mapCount: data.hasTexture ? 1 : 0
|
|
5945
6337
|
};
|
|
5946
6338
|
return {
|
|
5947
6339
|
vertex,
|
|
@@ -5955,7 +6347,6 @@ fn computeOffsetPosition(p0: vec4f, p1: vec4f, index: u32) -> vec4f {
|
|
|
5955
6347
|
const { shader, lights } = this.#key;
|
|
5956
6348
|
// TODO: consider backMap
|
|
5957
6349
|
return `mesh-` + shader + lights;
|
|
5958
|
-
//return `mesh-${shader}${(hasTexture ? '-map' : '-nomap')}`;
|
|
5959
6350
|
}
|
|
5960
6351
|
bindgroup(type, key, index) {
|
|
5961
6352
|
const set = this.#bindgroups;
|
|
@@ -5970,7 +6361,7 @@ fn computeOffsetPosition(p0: vec4f, p1: vec4f, index: u32) -> vec4f {
|
|
|
5970
6361
|
if (isNaN(index)) {
|
|
5971
6362
|
return filteredArr;
|
|
5972
6363
|
}
|
|
5973
|
-
if (index >= 0 && index <
|
|
6364
|
+
if (index >= 0 && index < filteredArr.length) {
|
|
5974
6365
|
return filteredArr[index];
|
|
5975
6366
|
}
|
|
5976
6367
|
return filteredArr;
|
|
@@ -6006,10 +6397,11 @@ fn computeOffsetPosition(p0: vec4f, p1: vec4f, index: u32) -> vec4f {
|
|
|
6006
6397
|
{ key: 'cameraViewTransform', group: UNIFORM_GROUP_INDEX_CAMERA, binding: UNIFORM_BINDING_INDEX_CAMERA, type: 'buffer' }
|
|
6007
6398
|
]);
|
|
6008
6399
|
// lights
|
|
6009
|
-
const
|
|
6010
|
-
|
|
6400
|
+
const lightDefinitions = lights.map((_, ndx) => {
|
|
6401
|
+
const light = { key: 'light', group: lightingBindGroupIndex, binding: ndx, type: 'buffer' };
|
|
6402
|
+
return light;
|
|
6011
6403
|
});
|
|
6012
|
-
|
|
6404
|
+
bindgroups.set(WGSLBindingType.Light, lightDefinitions);
|
|
6013
6405
|
// interaction
|
|
6014
6406
|
bindgroups.set(WGSLBindingType.Interaction, [{ key: 'interaction', group: UNIFORM_GROUP_INDEX_INTERACTION, type: 'buffer', binding: UNIFORM_BINDING_INDEX_INTERACTION }]);
|
|
6015
6407
|
}
|
|
@@ -6065,73 +6457,19 @@ fn computeOffsetPosition(p0: vec4f, p1: vec4f, index: u32) -> vec4f {
|
|
|
6065
6457
|
}
|
|
6066
6458
|
}
|
|
6067
6459
|
}
|
|
6068
|
-
|
|
6069
|
-
|
|
6070
|
-
|
|
6071
|
-
return;
|
|
6072
|
-
}
|
|
6073
|
-
device.queue.writeBuffer(buffer.buffer, 0, buffer.value);
|
|
6074
|
-
}
|
|
6075
|
-
};
|
|
6460
|
+
function logFrameException(e) {
|
|
6461
|
+
console.error('Pacem.Drawing3D.FrameException', e);
|
|
6462
|
+
}
|
|
6076
6463
|
class MeshRenderPipelineClass {
|
|
6077
6464
|
constructor(_context, _builder, _cache = new RenderPipelineCache()) {
|
|
6078
6465
|
this._context = _context;
|
|
6079
6466
|
this._builder = _builder;
|
|
6080
6467
|
this._cache = _cache;
|
|
6081
6468
|
// #region fields and utils
|
|
6082
|
-
this._ensureU32idBindGroup = (item, buffer, refresh) => {
|
|
6083
|
-
return this._cache.ensureBindGroup(this._context, item, [buffer], refresh, this._pickBindGroupLayout, labelPrefix + 'mesh-colorpick-bind-group');
|
|
6084
|
-
};
|
|
6085
|
-
this._ensureMaterialBindGroup = (item, buffer, texture, refresh, layoutIndex = MATERIAL_GROUP_INDEX) => {
|
|
6086
|
-
const layout = this._bindGroupLayouts[layoutIndex], label = labelPrefix + 'material-bind-group';
|
|
6087
|
-
if (layout.label !== (labelPrefix + 'material-bind-group-layout')) {
|
|
6088
|
-
throw new Error('BindGroupLayout mismatch!');
|
|
6089
|
-
}
|
|
6090
|
-
return this._cache.ensureBindGroup(this._context, item, [buffer], refresh, layout, label, (descriptor) => {
|
|
6091
|
-
const { device } = this.context;
|
|
6092
|
-
const entries = descriptor.entries /* entries are build as array in the method */;
|
|
6093
|
-
if (texture) {
|
|
6094
|
-
entries.push({
|
|
6095
|
-
binding: SAMPLER_BINDING_INDEX, resource: device.createSampler({
|
|
6096
|
-
addressModeU: 'repeat',
|
|
6097
|
-
addressModeV: 'repeat',
|
|
6098
|
-
magFilter: 'linear',
|
|
6099
|
-
minFilter: 'linear',
|
|
6100
|
-
})
|
|
6101
|
-
}, {
|
|
6102
|
-
binding: TEXTURE_BINDING_INDEX, resource: texture.createView()
|
|
6103
|
-
});
|
|
6104
|
-
}
|
|
6105
|
-
});
|
|
6106
|
-
};
|
|
6107
|
-
this._ensureWorldTransformBindGroup = (item, buffer, refresh, layoutIndex = UNIFORM_GROUP_INDEX_TRANSFORM, raycasting = false) => {
|
|
6108
|
-
const layout = this._bindGroupLayouts[layoutIndex];
|
|
6109
|
-
if (layout.label !== (labelPrefix + 'mesh-transforms-bind-group-layout')) {
|
|
6110
|
-
throw new Error('BindGroupLayout mismatch!');
|
|
6111
|
-
}
|
|
6112
|
-
const key = item.key + '-' + (raycasting ? 1 : 0);
|
|
6113
|
-
const label = `${labelPrefix}${raycasting ? 'colorpick' : 'mesh'}-transforms-bind-group`;
|
|
6114
|
-
return this._cache.ensureBindGroup(this._context, key, [buffer], refresh, layout, label);
|
|
6115
|
-
};
|
|
6116
|
-
this._ensureCameraProjectionAndInteractionDataBindGroup = (item, viewBuffer, interactionBuffer, refresh, layoutIndex = UNIFORM_GROUP_INDEX_CAMERA, raycasting = false) => {
|
|
6117
|
-
const layout = this._bindGroupLayouts[layoutIndex];
|
|
6118
|
-
const key = item.key + '-' + (raycasting ? 1 : 0);
|
|
6119
|
-
const label = `${labelPrefix}${raycasting ? 'colorpick' : 'mesh'}-view-bind-group`;
|
|
6120
|
-
return this._cache.ensureBindGroup(this._context, key, [viewBuffer, interactionBuffer], refresh, layout, label);
|
|
6121
|
-
};
|
|
6122
|
-
this._ensureLightingBindGroup = (lights, refresh, layoutIndex = UNIFORM_GROUP_INDEX_LIGHTING) => {
|
|
6123
|
-
const layout = this._bindGroupLayouts[layoutIndex];
|
|
6124
|
-
const key = lights.map(l => l.id).join(':');
|
|
6125
|
-
const buffers = lights.map(l => l.buffer.buffer);
|
|
6126
|
-
return this._cache.ensureBindGroup(this._context, key, buffers, refresh, layout, labelPrefix + 'mesh-lighting-bind-group');
|
|
6127
|
-
};
|
|
6128
|
-
this._bindGroupLayouts = [];
|
|
6129
6469
|
this._bindVertex = EMPTY_BIND_DELEGATE;
|
|
6130
6470
|
this._bindPicker = EMPTY_BIND_DELEGATE;
|
|
6131
6471
|
this._bindWorldTransform = EMPTY_BIND_DELEGATE;
|
|
6132
|
-
this._bindRaycastWorldTransform = EMPTY_BIND_DELEGATE;
|
|
6133
6472
|
this._bindCameraProjectionAndInteractionData = EMPTY_BIND_DELEGATE;
|
|
6134
|
-
this._bindRaycastCameraProjectionAndInteractionData = EMPTY_BIND_DELEGATE;
|
|
6135
6473
|
this._bindLighting = EMPTY_BIND_DELEGATE;
|
|
6136
6474
|
this._bindMaterial = EMPTY_BIND_DELEGATE;
|
|
6137
6475
|
// #endregion
|
|
@@ -6146,9 +6484,9 @@ fn computeOffsetPosition(p0: vec4f, p1: vec4f, index: u32) -> vec4f {
|
|
|
6146
6484
|
throw new Error('Deprecated.');
|
|
6147
6485
|
};
|
|
6148
6486
|
this.frame = (pass, interactionBuffer, meshBuffer, cameraBuffer, ...lightBuffers) => {
|
|
6149
|
-
// set
|
|
6150
|
-
pass.setPipeline(this._pipeline);
|
|
6151
6487
|
try {
|
|
6488
|
+
// set
|
|
6489
|
+
PassUtils.setPipeline(pass, this._pipeline);
|
|
6152
6490
|
// bind
|
|
6153
6491
|
this._bindVertex(pass, meshBuffer);
|
|
6154
6492
|
this._bindWorldTransform(pass, meshBuffer);
|
|
@@ -6156,27 +6494,29 @@ fn computeOffsetPosition(p0: vec4f, p1: vec4f, index: u32) -> vec4f {
|
|
|
6156
6494
|
this._bindCameraProjectionAndInteractionData(pass, cameraBuffer, interactionBuffer);
|
|
6157
6495
|
this._bindLighting(pass, ...lightBuffers);
|
|
6158
6496
|
// draw
|
|
6159
|
-
const
|
|
6160
|
-
pass.draw(
|
|
6497
|
+
const vertexCount = this._vertexCount(meshBuffer);
|
|
6498
|
+
pass.draw(vertexCount);
|
|
6161
6499
|
}
|
|
6162
6500
|
catch (e) {
|
|
6163
|
-
|
|
6501
|
+
logFrameException(e);
|
|
6164
6502
|
}
|
|
6165
6503
|
};
|
|
6166
6504
|
this.raycast = (pass, interactionBuffer, meshBuffer, cameraBuffer) => {
|
|
6167
|
-
// set
|
|
6168
|
-
pass.setPipeline(this._pickPipeline);
|
|
6169
6505
|
try {
|
|
6506
|
+
// set
|
|
6507
|
+
PassUtils.setPipeline(pass, this._pickPipeline);
|
|
6170
6508
|
// bind
|
|
6171
6509
|
this._bindVertex(pass, meshBuffer);
|
|
6172
|
-
this.
|
|
6173
|
-
this.
|
|
6510
|
+
this._bindWorldTransform(pass, meshBuffer);
|
|
6511
|
+
this._bindCameraProjectionAndInteractionData(pass, cameraBuffer, interactionBuffer);
|
|
6174
6512
|
this._bindPicker(pass, meshBuffer);
|
|
6175
6513
|
// draw
|
|
6176
|
-
const
|
|
6177
|
-
pass.draw(
|
|
6514
|
+
const vertexCount = this._vertexCount(meshBuffer);
|
|
6515
|
+
pass.draw(vertexCount);
|
|
6516
|
+
}
|
|
6517
|
+
catch (e) {
|
|
6518
|
+
logFrameException(e);
|
|
6178
6519
|
}
|
|
6179
|
-
catch (e) { }
|
|
6180
6520
|
};
|
|
6181
6521
|
this._key = _builder.key;
|
|
6182
6522
|
}
|
|
@@ -6189,12 +6529,14 @@ fn computeOffsetPosition(p0: vec4f, p1: vec4f, index: u32) -> vec4f {
|
|
|
6189
6529
|
build(pipelineOptions) {
|
|
6190
6530
|
const options = pacemCore.Utils.extend({}, DefaultPipelineOptions, pipelineOptions ?? {});
|
|
6191
6531
|
const builder = this._builder, wgsl = builder.build(options.modifiers);
|
|
6192
|
-
const ctx =
|
|
6532
|
+
const ctx = this._context;
|
|
6193
6533
|
const device = ctx.device;
|
|
6534
|
+
const cache = this._cache;
|
|
6194
6535
|
// #region VERTEX
|
|
6195
6536
|
// build vertex state
|
|
6537
|
+
const vertexModule = device.createShaderModule({ code: wgsl.vertex });
|
|
6196
6538
|
const vertex = {
|
|
6197
|
-
module:
|
|
6539
|
+
module: vertexModule,
|
|
6198
6540
|
buffers: options.packedVertices ?
|
|
6199
6541
|
[
|
|
6200
6542
|
// packed
|
|
@@ -6245,22 +6587,15 @@ fn computeOffsetPosition(p0: vec4f, p1: vec4f, index: u32) -> vec4f {
|
|
|
6245
6587
|
const bindGroupLayouts = [viewBindGroupLayout, worldBindGroupLayout];
|
|
6246
6588
|
// #endregion
|
|
6247
6589
|
// #region FRAGMENT
|
|
6248
|
-
//
|
|
6249
|
-
|
|
6250
|
-
|
|
6590
|
+
// (translucent meshes go through the A-buffer variant built in `translucent`, see `abuffer.ts`)
|
|
6591
|
+
const fragmentModule = device.createShaderModule({
|
|
6592
|
+
code: wgsl.fragment
|
|
6593
|
+
});
|
|
6251
6594
|
const fragment = {
|
|
6252
|
-
module:
|
|
6253
|
-
code: wgsl.fragment
|
|
6254
|
-
}), targets: [
|
|
6595
|
+
module: fragmentModule, targets: [
|
|
6255
6596
|
{
|
|
6256
6597
|
format: ctx.format,
|
|
6257
|
-
blend:
|
|
6258
|
-
color: {
|
|
6259
|
-
srcFactor: 'src-alpha',
|
|
6260
|
-
dstFactor: 'one-minus-src-alpha'
|
|
6261
|
-
},
|
|
6262
|
-
alpha: {},
|
|
6263
|
-
}
|
|
6598
|
+
blend: ALPHA_BLENDING
|
|
6264
6599
|
}
|
|
6265
6600
|
]
|
|
6266
6601
|
};
|
|
@@ -6278,7 +6613,11 @@ fn computeOffsetPosition(p0: vec4f, p1: vec4f, index: u32) -> vec4f {
|
|
|
6278
6613
|
// material / texture
|
|
6279
6614
|
const { mapCount } = wgsl.metadata, hasTex = mapCount > 0;
|
|
6280
6615
|
if (hasTex) {
|
|
6281
|
-
|
|
6616
|
+
const textureEntries = mapIndices(mapCount, index => {
|
|
6617
|
+
const entry = { visibility: GPUShaderStage.FRAGMENT, binding: SAMPLER_BINDING_INDEX + 1 + index, texture: {} };
|
|
6618
|
+
return entry;
|
|
6619
|
+
});
|
|
6620
|
+
materialBindGroupLayoutDescriptorEntries.push({ visibility: GPUShaderStage.FRAGMENT, binding: SAMPLER_BINDING_INDEX, sampler: {} }, ...textureEntries);
|
|
6282
6621
|
}
|
|
6283
6622
|
const materialBindGroupLayoutDescriptor = {
|
|
6284
6623
|
label: labelPrefix + 'material-bind-group-layout',
|
|
@@ -6286,18 +6625,29 @@ fn computeOffsetPosition(p0: vec4f, p1: vec4f, index: u32) -> vec4f {
|
|
|
6286
6625
|
};
|
|
6287
6626
|
const materialBindGroupLayout = device.createBindGroupLayout(materialBindGroupLayoutDescriptor);
|
|
6288
6627
|
bindGroupLayouts.push(materialBindGroupLayout);
|
|
6628
|
+
// one sampler for all the textured meshes drawn by this pipeline
|
|
6629
|
+
const sampler = hasTex ? device.createSampler({
|
|
6630
|
+
label: labelPrefix + 'material-sampler',
|
|
6631
|
+
addressModeU: 'repeat',
|
|
6632
|
+
addressModeV: 'repeat',
|
|
6633
|
+
magFilter: 'linear',
|
|
6634
|
+
minFilter: 'linear',
|
|
6635
|
+
}) : null;
|
|
6289
6636
|
// lighting
|
|
6290
6637
|
const lightingGroupIndex = bindGroupLayouts.length;
|
|
6291
6638
|
const { lightCount } = wgsl.metadata, hasLighting = lightCount > 0;
|
|
6639
|
+
let lightingBindGroupLayout = null;
|
|
6292
6640
|
if (hasLighting) {
|
|
6293
|
-
const
|
|
6294
|
-
|
|
6295
|
-
|
|
6296
|
-
|
|
6297
|
-
|
|
6298
|
-
|
|
6299
|
-
|
|
6300
|
-
|
|
6641
|
+
const lightingEntries = mapIndices(lightCount, index => {
|
|
6642
|
+
const entry = {
|
|
6643
|
+
visibility: GPUShaderStage.FRAGMENT, binding: index, buffer: {
|
|
6644
|
+
type: 'uniform'
|
|
6645
|
+
}
|
|
6646
|
+
};
|
|
6647
|
+
return entry;
|
|
6648
|
+
});
|
|
6649
|
+
lightingBindGroupLayout = device.createBindGroupLayout({
|
|
6650
|
+
entries: lightingEntries,
|
|
6301
6651
|
label: labelPrefix + 'lighting-bind-group-layout'
|
|
6302
6652
|
});
|
|
6303
6653
|
bindGroupLayouts.push(lightingBindGroupLayout);
|
|
@@ -6305,15 +6655,15 @@ fn computeOffsetPosition(p0: vec4f, p1: vec4f, index: u32) -> vec4f {
|
|
|
6305
6655
|
// #endregion
|
|
6306
6656
|
// #region PIPELINE
|
|
6307
6657
|
// full pipeline descriptor
|
|
6658
|
+
const layout = device.createPipelineLayout({
|
|
6659
|
+
label: labelPrefix + 'mesh-render-pipeline-layout',
|
|
6660
|
+
bindGroupLayouts
|
|
6661
|
+
});
|
|
6308
6662
|
const descriptor = {
|
|
6309
6663
|
label: labelPrefix + 'mesh-render-pipeline',
|
|
6310
6664
|
vertex,
|
|
6311
6665
|
fragment,
|
|
6312
|
-
|
|
6313
|
-
layout: device.createPipelineLayout({
|
|
6314
|
-
label: labelPrefix + 'mesh-render-pipeline-layout',
|
|
6315
|
-
bindGroupLayouts: (this._bindGroupLayouts = bindGroupLayouts)
|
|
6316
|
-
}),
|
|
6666
|
+
layout,
|
|
6317
6667
|
primitive: options.primitive
|
|
6318
6668
|
};
|
|
6319
6669
|
if (options.multisample) {
|
|
@@ -6326,7 +6676,7 @@ fn computeOffsetPosition(p0: vec4f, p1: vec4f, index: u32) -> vec4f {
|
|
|
6326
6676
|
}
|
|
6327
6677
|
this._pipeline = device.createRenderPipeline(descriptor);
|
|
6328
6678
|
// raycast pipeline descriptor
|
|
6329
|
-
const pickFragGroupLayout =
|
|
6679
|
+
const pickFragGroupLayout = device.createBindGroupLayout({
|
|
6330
6680
|
label: labelPrefix + 'mesh-colorpick-bind-group-layout',
|
|
6331
6681
|
entries: [
|
|
6332
6682
|
{
|
|
@@ -6336,20 +6686,23 @@ fn computeOffsetPosition(p0: vec4f, p1: vec4f, index: u32) -> vec4f {
|
|
|
6336
6686
|
}
|
|
6337
6687
|
]
|
|
6338
6688
|
});
|
|
6689
|
+
const pickFragmentCode = getColorPickingFragmentWgsl(UNIFORM_GROUP_INDEX_COLORPICKING);
|
|
6690
|
+
const pickFragmentModule = device.createShaderModule({
|
|
6691
|
+
code: pickFragmentCode
|
|
6692
|
+
});
|
|
6693
|
+
const pickLayout = device.createPipelineLayout({
|
|
6694
|
+
label: labelPrefix + 'mesh-colorpick-pipeline-layout',
|
|
6695
|
+
bindGroupLayouts: [viewBindGroupLayout, worldBindGroupLayout, pickFragGroupLayout]
|
|
6696
|
+
});
|
|
6339
6697
|
const pickDescriptor = {
|
|
6340
6698
|
label: labelPrefix + 'mesh-colorpick-pipeline',
|
|
6341
6699
|
vertex,
|
|
6342
6700
|
fragment: {
|
|
6343
|
-
module:
|
|
6344
|
-
code: getColorPickingFragmentWgsl(UNIFORM_GROUP_INDEX_COLORPICKING)
|
|
6345
|
-
}), targets: [
|
|
6701
|
+
module: pickFragmentModule, targets: [
|
|
6346
6702
|
{ format: 'r32uint' }
|
|
6347
6703
|
]
|
|
6348
6704
|
},
|
|
6349
|
-
layout:
|
|
6350
|
-
label: labelPrefix + 'mesh-colorpick-pipeline-layout',
|
|
6351
|
-
bindGroupLayouts: [viewBindGroupLayout, worldBindGroupLayout, pickFragGroupLayout]
|
|
6352
|
-
}),
|
|
6705
|
+
layout: pickLayout,
|
|
6353
6706
|
primitive: options.primitive,
|
|
6354
6707
|
depthStencil: {
|
|
6355
6708
|
depthWriteEnabled: true,
|
|
@@ -6359,6 +6712,13 @@ fn computeOffsetPosition(p0: vec4f, p1: vec4f, index: u32) -> vec4f {
|
|
|
6359
6712
|
};
|
|
6360
6713
|
this._pickPipeline = device.createRenderPipeline(pickDescriptor);
|
|
6361
6714
|
// #endregion
|
|
6715
|
+
// #region bind delegates (binding coordinates are resolved once, here)
|
|
6716
|
+
const { group: worldGroup } = wgsl.bindings(WGSLBindingType.Mesh, 'objectWorldTransform', 0);
|
|
6717
|
+
const { group: cameraGroup } = wgsl.bindings(WGSLBindingType.Camera, 'cameraViewTransform', 0);
|
|
6718
|
+
const { group: interactionGroup } = wgsl.bindings(WGSLBindingType.Interaction, 'interaction', 0);
|
|
6719
|
+
if (cameraGroup !== interactionGroup) {
|
|
6720
|
+
throw new ReferenceError(`Layout bind group mismatch: ${cameraGroup} vs ${interactionGroup}.`);
|
|
6721
|
+
}
|
|
6362
6722
|
// vertex buffers
|
|
6363
6723
|
const bindVertexSplit = (pass, ...buffers) => {
|
|
6364
6724
|
const meshBuffer = buffers.at(0);
|
|
@@ -6368,107 +6728,77 @@ fn computeOffsetPosition(p0: vec4f, p1: vec4f, index: u32) -> vec4f {
|
|
|
6368
6728
|
const { buffer: positions } = meshBuffer.buffer(ctx, 'geometryPositions');
|
|
6369
6729
|
const { buffer: normals } = meshBuffer.buffer(ctx, 'geometryNormals');
|
|
6370
6730
|
const { buffer: uv } = meshBuffer.buffer(ctx, 'geometryTexCoords');
|
|
6371
|
-
|
|
6372
|
-
|
|
6373
|
-
|
|
6731
|
+
PassUtils.setVertexBuffer(pass, VERTEX_BUFFER_INDEX_MESH_POSITION, positions);
|
|
6732
|
+
PassUtils.setVertexBuffer(pass, VERTEX_BUFFER_INDEX_MESH_NORMAL, normals);
|
|
6733
|
+
PassUtils.setVertexBuffer(pass, VERTEX_BUFFER_INDEX_MESH_UV, uv);
|
|
6374
6734
|
};
|
|
6375
6735
|
const bindVertexPacked = (pass, ...buffers) => {
|
|
6376
6736
|
const meshBuffer = buffers.at(0);
|
|
6377
6737
|
if (pacemCore.Utils.isNull(meshBuffer)) {
|
|
6378
6738
|
throw new ReferenceError(`Null ${RenderableBuffers.name} bringing vertex buffers was provided.`);
|
|
6379
6739
|
}
|
|
6380
|
-
const { buffer } = meshBuffer.buffer(ctx, 'geometry');
|
|
6381
|
-
|
|
6740
|
+
const { buffer: packed } = meshBuffer.buffer(ctx, 'geometry');
|
|
6741
|
+
PassUtils.setVertexBuffer(pass, VERTEX_BUFFER_INDEX_MESH_POSITION, packed);
|
|
6382
6742
|
};
|
|
6383
6743
|
this._bindVertex = options.packedVertices ? bindVertexPacked : bindVertexSplit;
|
|
6384
|
-
// world transform
|
|
6385
|
-
|
|
6744
|
+
// world transform (the same bind group serves both the render and the color-picking pipelines)
|
|
6745
|
+
this._bindWorldTransform = (pass, ...buffers) => {
|
|
6746
|
+
const meshBuffer = buffers.at(0);
|
|
6386
6747
|
if (pacemCore.Utils.isNull(meshBuffer)) {
|
|
6387
6748
|
throw new ReferenceError(`Null ${RenderableBuffers.name} bringing world transform buffer was provided.`);
|
|
6388
6749
|
}
|
|
6389
|
-
const
|
|
6390
|
-
|
|
6391
|
-
|
|
6392
|
-
|
|
6393
|
-
|
|
6394
|
-
pass.setBindGroup(group, bindGroup);
|
|
6395
|
-
};
|
|
6396
|
-
this._bindWorldTransform = (pass, ...buffers) => {
|
|
6397
|
-
const meshBuffer = buffers.at(0);
|
|
6398
|
-
bindWorldTransform(pass, meshBuffer, false);
|
|
6399
|
-
};
|
|
6400
|
-
this._bindRaycastWorldTransform = (pass, ...buffers) => {
|
|
6401
|
-
const meshBuffer = buffers.at(0);
|
|
6402
|
-
bindWorldTransform(pass, meshBuffer, true);
|
|
6750
|
+
const { buffer } = meshBuffer.buffer(ctx, 'objectWorldTransform');
|
|
6751
|
+
const bindGroup = cache.ensureBindGroup(ctx, meshBuffer, labelPrefix + 'mesh-transforms-bind-group', worldBindGroupLayout, [
|
|
6752
|
+
{ binding: UNIFORM_BINDING_INDEX_TRANSFORM, buffer }
|
|
6753
|
+
]);
|
|
6754
|
+
PassUtils.setBindGroup(pass, worldGroup, bindGroup);
|
|
6403
6755
|
};
|
|
6404
6756
|
// camera matrices and interaction data
|
|
6405
|
-
|
|
6757
|
+
this._bindCameraProjectionAndInteractionData = (pass, ...buffers) => {
|
|
6758
|
+
const cameraBuffer = buffers.at(0);
|
|
6759
|
+
const interactionBuffer = buffers.at(1);
|
|
6406
6760
|
if (pacemCore.Utils.isNull(cameraBuffer)) {
|
|
6407
6761
|
throw new ReferenceError(`Null ${RenderableBuffers.name} bringing view projection buffers was provided.`);
|
|
6408
6762
|
}
|
|
6409
|
-
// camera view
|
|
6410
|
-
const viewTransformBuffer = cameraBuffer.buffer(ctx, 'cameraViewTransform'), viewTransformBufferBuffer = viewTransformBuffer.buffer;
|
|
6411
|
-
// writes only if buffer is fresh
|
|
6412
|
-
PipelineUtils.writeBufferConditionally(device, viewTransformBuffer);
|
|
6413
|
-
// interaction
|
|
6414
6763
|
if (pacemCore.Utils.isNull(interactionBuffer)) {
|
|
6415
6764
|
throw new ReferenceError(`Null ${RenderableBuffers.name} bringing interaction buffers was provided.`);
|
|
6416
6765
|
}
|
|
6417
|
-
const
|
|
6418
|
-
|
|
6419
|
-
|
|
6420
|
-
|
|
6421
|
-
|
|
6422
|
-
|
|
6423
|
-
|
|
6424
|
-
}
|
|
6425
|
-
const bindGroup = this._ensureCameraProjectionAndInteractionDataBindGroup(cameraBuffer.item, viewTransformBufferBuffer, interactionDataBufferBuffer,
|
|
6426
|
-
// since fresh could mean also "camera switched" (e.g. from ortho to perspective and then back to ortho) there's risk
|
|
6427
|
-
// to target destroyed buffers, this refresh the bind group if either buffer is fresh.
|
|
6428
|
-
// Possibilities for fine-tuning in future.
|
|
6429
|
-
viewTransformBuffer.fresh || interactionDataBuffer.fresh, group, raycasting);
|
|
6430
|
-
pass.setBindGroup(group, bindGroup);
|
|
6431
|
-
};
|
|
6432
|
-
this._bindCameraProjectionAndInteractionData = (pass, ...buffers) => {
|
|
6433
|
-
const cameraBuffer = buffers.at(0);
|
|
6434
|
-
const interactionBuffer = buffers.at(1);
|
|
6435
|
-
bindCameraProjectionAndInteractionData(pass, cameraBuffer, interactionBuffer, false);
|
|
6766
|
+
const { buffer: view } = cameraBuffer.buffer(ctx, 'cameraViewTransform');
|
|
6767
|
+
const { buffer: interaction } = interactionBuffer.buffer(ctx, 'interaction');
|
|
6768
|
+
const bindGroup = cache.ensureBindGroup(ctx, cameraBuffer, labelPrefix + 'mesh-view-bind-group', viewBindGroupLayout, [
|
|
6769
|
+
{ binding: UNIFORM_BINDING_INDEX_CAMERA, buffer: view },
|
|
6770
|
+
{ binding: UNIFORM_BINDING_INDEX_INTERACTION, buffer: interaction }
|
|
6771
|
+
]);
|
|
6772
|
+
PassUtils.setBindGroup(pass, cameraGroup, bindGroup);
|
|
6436
6773
|
};
|
|
6437
|
-
|
|
6438
|
-
const cameraBuffer = buffers.at(0);
|
|
6439
|
-
const interactionBuffer = buffers.at(1);
|
|
6440
|
-
bindCameraProjectionAndInteractionData(pass, cameraBuffer, interactionBuffer, true);
|
|
6441
|
-
};
|
|
6442
|
-
// vertexColors and textures
|
|
6774
|
+
// vertexColors and textures (shared by all the meshes having the same material)
|
|
6443
6775
|
this._bindMaterial = (pass, ...buffers) => {
|
|
6444
6776
|
const meshBuffer = buffers.at(0);
|
|
6445
6777
|
if (pacemCore.Utils.isNull(meshBuffer)) {
|
|
6446
6778
|
throw new ReferenceError(`Null ${RenderableBuffers.name} bringing vertex colors was provided.`);
|
|
6447
6779
|
}
|
|
6448
|
-
const
|
|
6449
|
-
|
|
6450
|
-
PipelineUtils.writeBufferConditionally(device, vertexColorsBuffer);
|
|
6451
|
-
let tex = meshBuffer.texture(ctx);
|
|
6452
|
-
const texBmp = tex?.texture;
|
|
6453
|
-
const bindGroup = this._ensureMaterialBindGroup(meshBuffer.item, vertexColorsBufferBuffer, texBmp, vertexColorsBuffer.fresh, materialGroupIndex);
|
|
6454
|
-
pass.setBindGroup(materialGroupIndex, bindGroup);
|
|
6780
|
+
const material = meshBuffer.buffer(ctx, 'material');
|
|
6781
|
+
const entries = [{ binding: STORAGE_MATERIAL_INDEX, buffer: material.buffer }];
|
|
6455
6782
|
if (hasTex) {
|
|
6456
|
-
|
|
6783
|
+
const tex = meshBuffer.texture(ctx, 'texture');
|
|
6784
|
+
entries.push({ binding: SAMPLER_BINDING_INDEX, resource: sampler }, { binding: TEXTURE_BINDING_INDEX, resource: tex?.view });
|
|
6457
6785
|
}
|
|
6786
|
+
const bindGroup = cache.ensureBindGroup(ctx, material, labelPrefix + 'material-bind-group', materialBindGroupLayout, entries);
|
|
6787
|
+
PassUtils.setBindGroup(pass, materialGroupIndex, bindGroup);
|
|
6458
6788
|
};
|
|
6459
6789
|
// lights
|
|
6460
6790
|
this._bindLighting = (pass, ...buffers) => {
|
|
6461
|
-
if (hasLighting) {
|
|
6462
|
-
|
|
6463
|
-
const lightBuffers = lightArray.map(l => { return { buffer: l.buffer(ctx, 'light'), id: l.item.key }; });
|
|
6464
|
-
const refresh = lightBuffers.some(b => b.buffer.fresh);
|
|
6465
|
-
const bindGroup = this._ensureLightingBindGroup(lightBuffers, refresh, lightingGroupIndex);
|
|
6466
|
-
for (let lightBuffer of lightBuffers) {
|
|
6467
|
-
// writes only if buffer is fresh
|
|
6468
|
-
PipelineUtils.writeBufferConditionally(device, lightBuffer.buffer);
|
|
6469
|
-
}
|
|
6470
|
-
pass.setBindGroup(lightingGroupIndex, bindGroup);
|
|
6791
|
+
if (!hasLighting) {
|
|
6792
|
+
return;
|
|
6471
6793
|
}
|
|
6794
|
+
const owner = buffers.at(0);
|
|
6795
|
+
const entries = buffers.map((l, index) => {
|
|
6796
|
+
const { buffer } = l.buffer(ctx, 'light');
|
|
6797
|
+
const entry = { binding: index, buffer };
|
|
6798
|
+
return entry;
|
|
6799
|
+
});
|
|
6800
|
+
const bindGroup = cache.ensureBindGroup(ctx, owner, labelPrefix + 'mesh-lighting-bind-group', lightingBindGroupLayout, entries);
|
|
6801
|
+
PassUtils.setBindGroup(pass, lightingGroupIndex, bindGroup);
|
|
6472
6802
|
};
|
|
6473
6803
|
// picker
|
|
6474
6804
|
this._bindPicker = (pass, ...buffers) => {
|
|
@@ -6476,14 +6806,92 @@ fn computeOffsetPosition(p0: vec4f, p1: vec4f, index: u32) -> vec4f {
|
|
|
6476
6806
|
if (pacemCore.Utils.isNull(meshBuffer)) {
|
|
6477
6807
|
throw new ReferenceError(`Null ${RenderableBuffers.name} bringing world transform buffer was provided.`);
|
|
6478
6808
|
}
|
|
6479
|
-
const
|
|
6480
|
-
|
|
6481
|
-
|
|
6482
|
-
|
|
6483
|
-
|
|
6484
|
-
|
|
6485
|
-
|
|
6809
|
+
const { buffer } = meshBuffer.buffer(ctx, 'u32id');
|
|
6810
|
+
const bindGroup = cache.ensureBindGroup(ctx, meshBuffer, labelPrefix + 'mesh-colorpick-bind-group', pickFragGroupLayout, [
|
|
6811
|
+
{ binding: 0, buffer }
|
|
6812
|
+
]);
|
|
6813
|
+
PassUtils.setBindGroup(pass, UNIFORM_GROUP_INDEX_COLORPICKING, bindGroup);
|
|
6814
|
+
};
|
|
6815
|
+
// #region translucent (A-buffer) variant, built on first use
|
|
6816
|
+
// the A-buffer tests fragments against the (multisampled) opaque depth
|
|
6817
|
+
if (!options.multisample) {
|
|
6818
|
+
return;
|
|
6819
|
+
}
|
|
6820
|
+
let translucentPipeline = null;
|
|
6821
|
+
let translucentViewBindGroupLayout = null;
|
|
6822
|
+
const ensureTranslucentPipeline = () => {
|
|
6823
|
+
if (!pacemCore.Utils.isNull(translucentPipeline)) {
|
|
6824
|
+
return;
|
|
6825
|
+
}
|
|
6826
|
+
translucentViewBindGroupLayout = device.createBindGroupLayout({
|
|
6827
|
+
label: labelPrefix + 'mesh-abuffer-view-bind-group-layout',
|
|
6828
|
+
entries: [
|
|
6829
|
+
{ binding: UNIFORM_BINDING_INDEX_CAMERA, visibility: GPUShaderStage.VERTEX | GPUShaderStage.FRAGMENT, buffer: { type: 'uniform' } },
|
|
6830
|
+
{ binding: UNIFORM_BINDING_INDEX_INTERACTION, visibility: GPUShaderStage.VERTEX | GPUShaderStage.FRAGMENT, buffer: { type: 'uniform' } },
|
|
6831
|
+
{ binding: ABUFFER_BINDING_INDEX_HEADS, visibility: GPUShaderStage.FRAGMENT, buffer: { type: 'storage' } },
|
|
6832
|
+
{ binding: ABUFFER_BINDING_INDEX_LIST, visibility: GPUShaderStage.FRAGMENT, buffer: { type: 'storage' } },
|
|
6833
|
+
{ binding: ABUFFER_BINDING_INDEX_INFO, visibility: GPUShaderStage.FRAGMENT, buffer: { type: 'uniform' } },
|
|
6834
|
+
{ binding: ABUFFER_BINDING_INDEX_DEPTH, visibility: GPUShaderStage.FRAGMENT, texture: { sampleType: 'depth', multisampled: true } },
|
|
6835
|
+
]
|
|
6836
|
+
});
|
|
6837
|
+
const translucentLayouts = bindGroupLayouts.slice();
|
|
6838
|
+
translucentLayouts[cameraGroup] = translucentViewBindGroupLayout;
|
|
6839
|
+
const translucentFragmentCode = builder.fragment(undefined, { modifier: options.modifiers?.fragment, output: 'a-buffer' });
|
|
6840
|
+
const translucentFragmentModule = device.createShaderModule({
|
|
6841
|
+
label: labelPrefix + 'mesh-abuffer-fragment',
|
|
6842
|
+
code: translucentFragmentCode
|
|
6843
|
+
});
|
|
6844
|
+
const translucentLayout = device.createPipelineLayout({
|
|
6845
|
+
label: labelPrefix + 'mesh-abuffer-pipeline-layout',
|
|
6846
|
+
bindGroupLayouts: translucentLayouts
|
|
6847
|
+
});
|
|
6848
|
+
translucentPipeline = device.createRenderPipeline({
|
|
6849
|
+
label: labelPrefix + 'mesh-abuffer-pipeline',
|
|
6850
|
+
vertex,
|
|
6851
|
+
fragment: {
|
|
6852
|
+
module: translucentFragmentModule,
|
|
6853
|
+
// fragments are pushed into storage buffers, nothing is written to color targets
|
|
6854
|
+
targets: []
|
|
6855
|
+
},
|
|
6856
|
+
layout: translucentLayout,
|
|
6857
|
+
primitive: options.primitive,
|
|
6858
|
+
multisample: { count: 4 },
|
|
6859
|
+
// tested against the opaque depth (read-only), never written
|
|
6860
|
+
depthStencil: { format: 'depth24plus', depthCompare: 'less', depthWriteEnabled: false }
|
|
6861
|
+
});
|
|
6862
|
+
};
|
|
6863
|
+
this.translucent = (pass, interactionBuffer, aBuffer, meshBuffer, cameraBuffer, ...lightBuffers) => {
|
|
6864
|
+
try {
|
|
6865
|
+
ensureTranslucentPipeline();
|
|
6866
|
+
PassUtils.setPipeline(pass, translucentPipeline);
|
|
6867
|
+
this._bindVertex(pass, meshBuffer);
|
|
6868
|
+
this._bindWorldTransform(pass, meshBuffer);
|
|
6869
|
+
this._bindMaterial(pass, meshBuffer);
|
|
6870
|
+
// camera, interaction and A-buffer resources
|
|
6871
|
+
const { buffer: view } = cameraBuffer.buffer(ctx, 'cameraViewTransform');
|
|
6872
|
+
const { buffer: interaction } = interactionBuffer.buffer(ctx, 'interaction');
|
|
6873
|
+
const bindGroup = cache.ensureBindGroup(ctx, cameraBuffer, labelPrefix + 'mesh-abuffer-view-bind-group', translucentViewBindGroupLayout, [
|
|
6874
|
+
{ binding: UNIFORM_BINDING_INDEX_CAMERA, buffer: view },
|
|
6875
|
+
{ binding: UNIFORM_BINDING_INDEX_INTERACTION, buffer: interaction },
|
|
6876
|
+
{ binding: ABUFFER_BINDING_INDEX_HEADS, buffer: aBuffer.heads },
|
|
6877
|
+
{ binding: ABUFFER_BINDING_INDEX_LIST, buffer: aBuffer.list },
|
|
6878
|
+
{ binding: ABUFFER_BINDING_INDEX_INFO, buffer: aBuffer.info },
|
|
6879
|
+
{ binding: ABUFFER_BINDING_INDEX_DEPTH, resource: aBuffer.depth },
|
|
6880
|
+
]);
|
|
6881
|
+
PassUtils.setBindGroup(pass, cameraGroup, bindGroup);
|
|
6882
|
+
this._bindLighting(pass, ...lightBuffers);
|
|
6883
|
+
const vertexCount = this._vertexCount(meshBuffer);
|
|
6884
|
+
pass.draw(vertexCount);
|
|
6885
|
+
}
|
|
6886
|
+
catch (e) {
|
|
6887
|
+
logFrameException(e);
|
|
6888
|
+
}
|
|
6486
6889
|
};
|
|
6890
|
+
// #endregion
|
|
6891
|
+
}
|
|
6892
|
+
_vertexCount(meshBuffer) {
|
|
6893
|
+
const mesh = meshBuffer.item, geometry = mesh.geometry;
|
|
6894
|
+
return geometry.triangleIndices?.length || geometry.positions.length;
|
|
6487
6895
|
}
|
|
6488
6896
|
}
|
|
6489
6897
|
class LineWGSLBuilder {
|
|
@@ -6544,7 +6952,7 @@ fn computeOffsetPosition(p0: vec4f, p1: vec4f, index: u32) -> vec4f {
|
|
|
6544
6952
|
if (isNaN(index)) {
|
|
6545
6953
|
return filteredArr;
|
|
6546
6954
|
}
|
|
6547
|
-
if (index >= 0 && index <
|
|
6955
|
+
if (index >= 0 && index < filteredArr.length) {
|
|
6548
6956
|
return filteredArr[index];
|
|
6549
6957
|
}
|
|
6550
6958
|
return filteredArr;
|
|
@@ -6594,50 +7002,10 @@ fn computeOffsetPosition(p0: vec4f, p1: vec4f, index: u32) -> vec4f {
|
|
|
6594
7002
|
this._lineBuilder = _lineBuilder;
|
|
6595
7003
|
this._cache = _cache;
|
|
6596
7004
|
// #region fields and utils
|
|
6597
|
-
this._ensureLineU32idBindGroup = (item, buffer, refresh) => {
|
|
6598
|
-
const ctx = this.context;
|
|
6599
|
-
return this._cache.ensureBindGroup(ctx, item, [buffer], refresh, this._pickLineBindGroupLayout, labelPrefix + 'line-colorpick-bind-group');
|
|
6600
|
-
};
|
|
6601
|
-
this._ensureLineMaterialBindGroup = (item, buffer, refresh, layoutIndex = MATERIAL_GROUP_INDEX) => {
|
|
6602
|
-
const layout = this._bindLineGroupLayouts[layoutIndex];
|
|
6603
|
-
if (layout.label !== (labelPrefix + 'line-material-bind-group-layout')) {
|
|
6604
|
-
throw new Error('BindGroupLayout mismatch!');
|
|
6605
|
-
}
|
|
6606
|
-
const ctx = this.context;
|
|
6607
|
-
return this._cache.ensureBindGroup(ctx, item, [buffer], refresh, layout, labelPrefix + 'line-material-bind-group');
|
|
6608
|
-
};
|
|
6609
|
-
this._ensureLinePositionsBindGroup = (item, buffers, refresh, layoutIndex) => {
|
|
6610
|
-
const layout = this._bindLineGroupLayouts[layoutIndex];
|
|
6611
|
-
if (layout.label !== (labelPrefix + 'line-positions-bind-group-layout')) {
|
|
6612
|
-
throw new Error('BindGroupLayout mismatch!');
|
|
6613
|
-
}
|
|
6614
|
-
const ctx = this.context;
|
|
6615
|
-
return this._cache.ensureBindGroup(ctx, item, buffers, refresh, layout, labelPrefix + 'line-positions-bind-group');
|
|
6616
|
-
};
|
|
6617
|
-
this._ensureLineWorldTransformBindGroup = (item, buffer, refresh, layoutIndex = UNIFORM_GROUP_INDEX_TRANSFORM, raycasting = false) => {
|
|
6618
|
-
const layout = this._bindLineGroupLayouts[layoutIndex];
|
|
6619
|
-
if (layout.label !== (labelPrefix + 'line-transforms-bind-group-layout')) {
|
|
6620
|
-
throw new Error('BindGroupLayout mismatch!');
|
|
6621
|
-
}
|
|
6622
|
-
const key = item.key + '-line-' + (raycasting ? 1 : 0);
|
|
6623
|
-
const label = `${labelPrefix}${raycasting ? 'colorpick' : ''}-line-transforms-bind-group`;
|
|
6624
|
-
const ctx = this.context;
|
|
6625
|
-
return this._cache.ensureBindGroup(ctx, key, [buffer], refresh, layout, label);
|
|
6626
|
-
};
|
|
6627
|
-
this._ensureLineCameraProjectionBindGroup = (item, viewBuffer, refresh, layoutIndex = UNIFORM_GROUP_INDEX_CAMERA, raycasting = false) => {
|
|
6628
|
-
const layout = this._bindLineGroupLayouts[layoutIndex];
|
|
6629
|
-
const key = item.key + '-line-' + (raycasting ? 1 : 0);
|
|
6630
|
-
const label = `${labelPrefix}${raycasting ? 'colorpick' : ''}-line-view-bind-group`;
|
|
6631
|
-
const ctx = this.context;
|
|
6632
|
-
return this._cache.ensureBindGroup(ctx, key, [viewBuffer], refresh, layout, label);
|
|
6633
|
-
};
|
|
6634
|
-
this._bindLineGroupLayouts = [];
|
|
6635
7005
|
this._bindLinePositions = EMPTY_BIND_DELEGATE;
|
|
6636
7006
|
this._bindLinePicker = EMPTY_BIND_DELEGATE;
|
|
6637
7007
|
this._bindLineWorldTransform = EMPTY_BIND_DELEGATE;
|
|
6638
|
-
this._bindLineRaycastWorldTransform = EMPTY_BIND_DELEGATE;
|
|
6639
7008
|
this._bindLineCameraProjection = EMPTY_BIND_DELEGATE;
|
|
6640
|
-
this._bindLineRaycastCameraProjection = EMPTY_BIND_DELEGATE;
|
|
6641
7009
|
this._bindLineMaterial = EMPTY_BIND_DELEGATE;
|
|
6642
7010
|
this._drawLine = EMPTY_BIND_DELEGATE;
|
|
6643
7011
|
// #endregion
|
|
@@ -6652,9 +7020,9 @@ fn computeOffsetPosition(p0: vec4f, p1: vec4f, index: u32) -> vec4f {
|
|
|
6652
7020
|
throw new Error('Deprecated.');
|
|
6653
7021
|
};
|
|
6654
7022
|
this.frame = (pass, /* unused yet */ interactionBuffer, meshBuffer, cameraBuffer) => {
|
|
6655
|
-
// set
|
|
6656
|
-
pass.setPipeline(this._linePipeline);
|
|
6657
7023
|
try {
|
|
7024
|
+
// set
|
|
7025
|
+
PassUtils.setPipeline(pass, this._linePipeline);
|
|
6658
7026
|
// bind
|
|
6659
7027
|
this._bindLineWorldTransform(pass, meshBuffer);
|
|
6660
7028
|
this._bindLineCameraProjection(pass, cameraBuffer);
|
|
@@ -6664,22 +7032,24 @@ fn computeOffsetPosition(p0: vec4f, p1: vec4f, index: u32) -> vec4f {
|
|
|
6664
7032
|
this._drawLine(pass, meshBuffer);
|
|
6665
7033
|
}
|
|
6666
7034
|
catch (e) {
|
|
6667
|
-
|
|
7035
|
+
logFrameException(e);
|
|
6668
7036
|
}
|
|
6669
7037
|
};
|
|
6670
7038
|
this.raycast = (pass, /* unused yet */ interactionBuffer, meshBuffer, cameraBuffer) => {
|
|
6671
|
-
// set
|
|
6672
|
-
pass.setPipeline(this._pickLinePipeline);
|
|
6673
7039
|
try {
|
|
7040
|
+
// set
|
|
7041
|
+
PassUtils.setPipeline(pass, this._pickLinePipeline);
|
|
6674
7042
|
// bind
|
|
6675
|
-
this.
|
|
6676
|
-
this.
|
|
7043
|
+
this._bindLineWorldTransform(pass, meshBuffer);
|
|
7044
|
+
this._bindLineCameraProjection(pass, cameraBuffer);
|
|
6677
7045
|
this._bindLinePositions(pass, meshBuffer);
|
|
6678
7046
|
this._bindLinePicker(pass, meshBuffer);
|
|
6679
7047
|
// draw
|
|
6680
7048
|
this._drawLine(pass, meshBuffer);
|
|
6681
7049
|
}
|
|
6682
|
-
catch (e) {
|
|
7050
|
+
catch (e) {
|
|
7051
|
+
logFrameException(e);
|
|
7052
|
+
}
|
|
6683
7053
|
};
|
|
6684
7054
|
this.#context = context;
|
|
6685
7055
|
this._lineKey = _lineBuilder.key;
|
|
@@ -6693,14 +7063,16 @@ fn computeOffsetPosition(p0: vec4f, p1: vec4f, index: u32) -> vec4f {
|
|
|
6693
7063
|
build(pipelineOptions) {
|
|
6694
7064
|
const options = pacemCore.Utils.extend({}, DefaultPipelineOptions, pipelineOptions ?? {});
|
|
6695
7065
|
const builder = this._lineBuilder, wgsl = builder.build();
|
|
6696
|
-
const ctx =
|
|
7066
|
+
const ctx = this.#context;
|
|
6697
7067
|
const device = ctx.device;
|
|
7068
|
+
const cache = this._cache;
|
|
6698
7069
|
// TODO: switch topology based on this flag
|
|
6699
7070
|
const fatLines = wgsl.metadata.thickness > 1;
|
|
6700
7071
|
// #region VERTEX
|
|
6701
7072
|
// build vertex state
|
|
7073
|
+
const vertexModule = device.createShaderModule({ code: wgsl.vertex });
|
|
6702
7074
|
const vertex = {
|
|
6703
|
-
module:
|
|
7075
|
+
module: vertexModule,
|
|
6704
7076
|
buffers: []
|
|
6705
7077
|
};
|
|
6706
7078
|
// bind group layouts
|
|
@@ -6765,19 +7137,14 @@ fn computeOffsetPosition(p0: vec4f, p1: vec4f, index: u32) -> vec4f {
|
|
|
6765
7137
|
const bindGroupLayouts = vertexBindGroupLayouts.slice();
|
|
6766
7138
|
// #endregion
|
|
6767
7139
|
// #region FRAGMENT
|
|
7140
|
+
const fragmentModule = device.createShaderModule({
|
|
7141
|
+
code: wgsl.fragment
|
|
7142
|
+
});
|
|
6768
7143
|
const fragment = {
|
|
6769
|
-
module:
|
|
6770
|
-
code: wgsl.fragment
|
|
6771
|
-
}), targets: [
|
|
7144
|
+
module: fragmentModule, targets: [
|
|
6772
7145
|
{
|
|
6773
7146
|
format: ctx.format,
|
|
6774
|
-
blend:
|
|
6775
|
-
color: {
|
|
6776
|
-
srcFactor: 'src-alpha',
|
|
6777
|
-
dstFactor: 'one-minus-src-alpha'
|
|
6778
|
-
},
|
|
6779
|
-
alpha: {},
|
|
6780
|
-
}
|
|
7147
|
+
blend: ALPHA_BLENDING
|
|
6781
7148
|
}
|
|
6782
7149
|
]
|
|
6783
7150
|
};
|
|
@@ -6801,17 +7168,18 @@ fn computeOffsetPosition(p0: vec4f, p1: vec4f, index: u32) -> vec4f {
|
|
|
6801
7168
|
// #endregion
|
|
6802
7169
|
// #region PIPELINE
|
|
6803
7170
|
const topology = fatLines ? options.primitive.topology : 'line-list';
|
|
7171
|
+
const primitive = pacemCore.Utils.extend({}, options.primitive, { topology });
|
|
6804
7172
|
// full pipeline descriptor
|
|
7173
|
+
const layout = device.createPipelineLayout({
|
|
7174
|
+
label: labelPrefix + 'line-render-pipeline-layout',
|
|
7175
|
+
bindGroupLayouts
|
|
7176
|
+
});
|
|
6805
7177
|
const descriptor = {
|
|
6806
7178
|
label: labelPrefix + 'line-render-pipeline',
|
|
6807
7179
|
vertex,
|
|
6808
7180
|
fragment,
|
|
6809
|
-
|
|
6810
|
-
|
|
6811
|
-
label: labelPrefix + 'line-render-pipeline-layout',
|
|
6812
|
-
bindGroupLayouts: (this._bindLineGroupLayouts = bindGroupLayouts)
|
|
6813
|
-
}),
|
|
6814
|
-
primitive: pacemCore.Utils.extend({}, options.primitive, { topology }),
|
|
7181
|
+
layout,
|
|
7182
|
+
primitive,
|
|
6815
7183
|
};
|
|
6816
7184
|
if (options.multisample) {
|
|
6817
7185
|
descriptor.multisample = { count: 4 };
|
|
@@ -6823,7 +7191,7 @@ fn computeOffsetPosition(p0: vec4f, p1: vec4f, index: u32) -> vec4f {
|
|
|
6823
7191
|
}
|
|
6824
7192
|
this._linePipeline = device.createRenderPipeline(descriptor);
|
|
6825
7193
|
// raycast pipeline descriptor
|
|
6826
|
-
const pickFragGroupLayout =
|
|
7194
|
+
const pickFragGroupLayout = device.createBindGroupLayout({
|
|
6827
7195
|
label: labelPrefix + 'line-colorpick-bind-group-layout',
|
|
6828
7196
|
entries: [
|
|
6829
7197
|
{
|
|
@@ -6833,21 +7201,25 @@ fn computeOffsetPosition(p0: vec4f, p1: vec4f, index: u32) -> vec4f {
|
|
|
6833
7201
|
}
|
|
6834
7202
|
]
|
|
6835
7203
|
});
|
|
7204
|
+
const pickFragmentCode = getColorPickingFragmentWgsl(raycastLayoutIndex);
|
|
7205
|
+
const pickFragmentModule = device.createShaderModule({
|
|
7206
|
+
code: pickFragmentCode
|
|
7207
|
+
});
|
|
7208
|
+
const pickBindGroupLayouts = vertexBindGroupLayouts.concat(pickFragGroupLayout);
|
|
7209
|
+
const pickLayout = device.createPipelineLayout({
|
|
7210
|
+
label: labelPrefix + 'line-colorpick-pipeline-layout',
|
|
7211
|
+
bindGroupLayouts: pickBindGroupLayouts
|
|
7212
|
+
});
|
|
6836
7213
|
const pickDescriptor = {
|
|
6837
7214
|
label: labelPrefix + 'line-colorpick-pipeline',
|
|
6838
7215
|
vertex,
|
|
6839
7216
|
fragment: {
|
|
6840
|
-
module:
|
|
6841
|
-
code: getColorPickingFragmentWgsl(raycastLayoutIndex)
|
|
6842
|
-
}), targets: [
|
|
7217
|
+
module: pickFragmentModule, targets: [
|
|
6843
7218
|
{ format: 'r32uint' }
|
|
6844
7219
|
]
|
|
6845
7220
|
},
|
|
6846
|
-
layout:
|
|
6847
|
-
|
|
6848
|
-
bindGroupLayouts: vertexBindGroupLayouts.concat(pickFragGroupLayout)
|
|
6849
|
-
}),
|
|
6850
|
-
primitive: pacemCore.Utils.extend({}, options.primitive, { topology }),
|
|
7221
|
+
layout: pickLayout,
|
|
7222
|
+
primitive,
|
|
6851
7223
|
depthStencil: {
|
|
6852
7224
|
depthWriteEnabled: true,
|
|
6853
7225
|
depthCompare: 'less',
|
|
@@ -6856,47 +7228,33 @@ fn computeOffsetPosition(p0: vec4f, p1: vec4f, index: u32) -> vec4f {
|
|
|
6856
7228
|
};
|
|
6857
7229
|
this._pickLinePipeline = device.createRenderPipeline(pickDescriptor);
|
|
6858
7230
|
// #endregion
|
|
6859
|
-
//
|
|
6860
|
-
const
|
|
7231
|
+
// #region bind delegates (binding coordinates are resolved once, here)
|
|
7232
|
+
const { group: worldGroup } = wgsl.bindings(WGSLBindingType.Mesh, 'objectWorldTransform', 0);
|
|
7233
|
+
const { group: cameraGroup } = wgsl.bindings(WGSLBindingType.Camera, 'cameraViewTransform', 0);
|
|
7234
|
+
const { group: positionsGroup } = wgsl.bindings(WGSLBindingType.Mesh, 'line' /* or 'geometryPositions' */, 0);
|
|
7235
|
+
// world transform (shared by the render and the color-picking pipelines)
|
|
7236
|
+
this._bindLineWorldTransform = (pass, ...buffers) => {
|
|
7237
|
+
const meshBuffer = buffers.at(0);
|
|
6861
7238
|
if (pacemCore.Utils.isNull(meshBuffer)) {
|
|
6862
7239
|
throw new ReferenceError(`Null ${RenderableBuffers.name} bringing world transform buffer was provided.`);
|
|
6863
7240
|
}
|
|
6864
|
-
const
|
|
6865
|
-
|
|
6866
|
-
|
|
6867
|
-
|
|
6868
|
-
|
|
6869
|
-
/*worldTransform.fresh*/ false /* persist the same bindGroup, given the constant size */, group, raycasting);
|
|
6870
|
-
pass.setBindGroup(group, bindGroup);
|
|
6871
|
-
};
|
|
6872
|
-
this._bindLineWorldTransform = (pass, ...buffers) => {
|
|
6873
|
-
const meshBuffer = buffers.at(0);
|
|
6874
|
-
bindLineWorldTransform(pass, meshBuffer, false);
|
|
6875
|
-
};
|
|
6876
|
-
this._bindLineRaycastWorldTransform = (pass, ...buffers) => {
|
|
6877
|
-
const meshBuffer = buffers.at(0);
|
|
6878
|
-
bindLineWorldTransform(pass, meshBuffer, true);
|
|
7241
|
+
const { buffer } = meshBuffer.buffer(ctx, 'objectWorldTransform');
|
|
7242
|
+
const bindGroup = cache.ensureBindGroup(ctx, meshBuffer, labelPrefix + 'line-transforms-bind-group', worldBindGroupLayout, [
|
|
7243
|
+
{ binding: UNIFORM_BINDING_INDEX_TRANSFORM, buffer }
|
|
7244
|
+
]);
|
|
7245
|
+
PassUtils.setBindGroup(pass, worldGroup, bindGroup);
|
|
6879
7246
|
};
|
|
6880
7247
|
// camera matrices
|
|
6881
|
-
|
|
7248
|
+
this._bindLineCameraProjection = (pass, ...buffers) => {
|
|
7249
|
+
const cameraBuffer = buffers.at(0);
|
|
6882
7250
|
if (pacemCore.Utils.isNull(cameraBuffer)) {
|
|
6883
7251
|
throw new ReferenceError(`Null ${RenderableBuffers.name} bringing view projection buffers was provided.`);
|
|
6884
7252
|
}
|
|
6885
|
-
const
|
|
6886
|
-
|
|
6887
|
-
|
|
6888
|
-
|
|
6889
|
-
|
|
6890
|
-
/*viewTransformBuffer.fresh*/ false, group, raycasting);
|
|
6891
|
-
pass.setBindGroup(group, bindGroup);
|
|
6892
|
-
};
|
|
6893
|
-
this._bindLineCameraProjection = (pass, ...buffers) => {
|
|
6894
|
-
const cameraBuffer = buffers.at(0);
|
|
6895
|
-
bindLineCameraProjection(pass, cameraBuffer, false);
|
|
6896
|
-
};
|
|
6897
|
-
this._bindLineRaycastCameraProjection = (pass, ...buffers) => {
|
|
6898
|
-
const cameraBuffer = buffers.at(0);
|
|
6899
|
-
bindLineCameraProjection(pass, cameraBuffer, true);
|
|
7253
|
+
const { buffer } = cameraBuffer.buffer(ctx, 'cameraViewTransform');
|
|
7254
|
+
const bindGroup = cache.ensureBindGroup(ctx, cameraBuffer, labelPrefix + 'line-view-bind-group', viewBindGroupLayout, [
|
|
7255
|
+
{ binding: UNIFORM_BINDING_INDEX_CAMERA, buffer }
|
|
7256
|
+
]);
|
|
7257
|
+
PassUtils.setBindGroup(pass, cameraGroup, bindGroup);
|
|
6900
7258
|
};
|
|
6901
7259
|
// positions storage
|
|
6902
7260
|
this._bindLinePositions = (pass, ...buffers) => {
|
|
@@ -6904,34 +7262,26 @@ fn computeOffsetPosition(p0: vec4f, p1: vec4f, index: u32) -> vec4f {
|
|
|
6904
7262
|
if (pacemCore.Utils.isNull(meshBuffer)) {
|
|
6905
7263
|
throw new ReferenceError(`Null ${RenderableBuffers.name} bringing vertex buffers was provided as index 0.`);
|
|
6906
7264
|
}
|
|
6907
|
-
|
|
6908
|
-
const
|
|
6909
|
-
let refresh = positionsBuffer.fresh;
|
|
6910
|
-
const buffersInput = [positionsBufferBuffer];
|
|
6911
|
-
// writes only if buffer is fresh
|
|
6912
|
-
PipelineUtils.writeBufferConditionally(device, positionsBuffer);
|
|
7265
|
+
const { buffer: positions } = meshBuffer.buffer(ctx, 'geometryPositions');
|
|
7266
|
+
const entries = [{ binding: 0, buffer: positions }];
|
|
6913
7267
|
if (fatLines) {
|
|
6914
|
-
const
|
|
6915
|
-
|
|
6916
|
-
|
|
6917
|
-
|
|
6918
|
-
|
|
6919
|
-
}
|
|
6920
|
-
const { group: groupIndex } = wgsl.bindings(WGSLBindingType.Mesh, 'line' /* or 'geometryPositions' */, 0);
|
|
6921
|
-
const bindGroup = this._ensureLinePositionsBindGroup(meshBuffer.item, buffersInput, refresh, groupIndex);
|
|
6922
|
-
pass.setBindGroup(groupIndex, bindGroup);
|
|
7268
|
+
const { buffer: line } = meshBuffer.buffer(ctx, 'line');
|
|
7269
|
+
entries.push({ binding: 1, buffer: line });
|
|
7270
|
+
}
|
|
7271
|
+
const bindGroup = cache.ensureBindGroup(ctx, meshBuffer, labelPrefix + 'line-positions-bind-group', lineBindGroupLayout, entries);
|
|
7272
|
+
PassUtils.setBindGroup(pass, positionsGroup, bindGroup);
|
|
6923
7273
|
};
|
|
6924
|
-
// vertexColors
|
|
7274
|
+
// vertexColors (shared by all the lines having the same material)
|
|
6925
7275
|
this._bindLineMaterial = (pass, ...buffers) => {
|
|
6926
7276
|
const meshBuffer = buffers.at(0);
|
|
6927
7277
|
if (pacemCore.Utils.isNull(meshBuffer)) {
|
|
6928
7278
|
throw new ReferenceError(`Null ${RenderableBuffers.name} bringing vertex colors was provided.`);
|
|
6929
7279
|
}
|
|
6930
|
-
const
|
|
6931
|
-
|
|
6932
|
-
|
|
6933
|
-
|
|
6934
|
-
|
|
7280
|
+
const material = meshBuffer.buffer(ctx, 'material');
|
|
7281
|
+
const bindGroup = cache.ensureBindGroup(ctx, material, labelPrefix + 'line-material-bind-group', materialBindGroupLayout, [
|
|
7282
|
+
{ binding: STORAGE_MATERIAL_INDEX, buffer: material.buffer }
|
|
7283
|
+
]);
|
|
7284
|
+
PassUtils.setBindGroup(pass, materialGroupIndex, bindGroup);
|
|
6935
7285
|
};
|
|
6936
7286
|
// picker
|
|
6937
7287
|
this._bindLinePicker = (pass, ...buffers) => {
|
|
@@ -6939,11 +7289,11 @@ fn computeOffsetPosition(p0: vec4f, p1: vec4f, index: u32) -> vec4f {
|
|
|
6939
7289
|
if (pacemCore.Utils.isNull(meshBuffer)) {
|
|
6940
7290
|
throw new ReferenceError(`Null ${RenderableBuffers.name} bringing world transform buffer was provided.`);
|
|
6941
7291
|
}
|
|
6942
|
-
const
|
|
6943
|
-
|
|
6944
|
-
|
|
6945
|
-
|
|
6946
|
-
|
|
7292
|
+
const { buffer } = meshBuffer.buffer(ctx, 'u32id');
|
|
7293
|
+
const bindGroup = cache.ensureBindGroup(ctx, meshBuffer, labelPrefix + 'line-colorpick-bind-group', pickFragGroupLayout, [
|
|
7294
|
+
{ binding: 0, buffer }
|
|
7295
|
+
]);
|
|
7296
|
+
PassUtils.setBindGroup(pass, raycastLayoutIndex, bindGroup);
|
|
6947
7297
|
};
|
|
6948
7298
|
this._drawLine = (pass, ...buffers) => {
|
|
6949
7299
|
const meshBuffer = buffers.at(0);
|
|
@@ -6955,6 +7305,7 @@ fn computeOffsetPosition(p0: vec4f, p1: vec4f, index: u32) -> vec4f {
|
|
|
6955
7305
|
pass.draw(geometry.positions.length);
|
|
6956
7306
|
}
|
|
6957
7307
|
};
|
|
7308
|
+
// #endregion
|
|
6958
7309
|
}
|
|
6959
7310
|
}
|
|
6960
7311
|
// #endregion
|
|
@@ -7002,17 +7353,31 @@ fn computeOffsetPosition(p0: vec4f, p1: vec4f, index: u32) -> vec4f {
|
|
|
7002
7353
|
}
|
|
7003
7354
|
}
|
|
7004
7355
|
const NUM_PIXELS = 1;
|
|
7356
|
+
/** `bytesPerRow` must be a multiple of 256 in buffer/texture copies. */
|
|
7357
|
+
const BYTES_PER_ROW = Math.ceil(NUM_PIXELS * 4 / 256) * 256;
|
|
7358
|
+
/** Integer pixel coordinate within `[0, size - 1]` (`0` when missing). */
|
|
7359
|
+
function clampToPixel(coordinate, size) {
|
|
7360
|
+
const floored = Math.floor(coordinate ?? 0);
|
|
7361
|
+
const nonNegative = Math.max(0, floored);
|
|
7362
|
+
return Math.min(size - 1, nonNegative);
|
|
7363
|
+
}
|
|
7364
|
+
/** Texture size within `[1, max]`. */
|
|
7365
|
+
function clampToTextureSize(size, max) {
|
|
7366
|
+
const bounded = Math.min(max, size);
|
|
7367
|
+
return Math.max(1, bounded);
|
|
7368
|
+
}
|
|
7005
7369
|
class ColorPickingRaycaster {
|
|
7006
7370
|
constructor(_context) {
|
|
7007
7371
|
this._context = _context;
|
|
7008
7372
|
this._objects = new Map();
|
|
7009
|
-
this.
|
|
7373
|
+
this._pixel = { x: 0, y: 0 };
|
|
7374
|
+
this.frame = (pipeline, interaction, ...buffers) => {
|
|
7010
7375
|
if (pacemCore.Utils.isNull(this._encoder)) {
|
|
7011
7376
|
throw new Error('Null encoder. Maybe you missed to call the \'begin\' method first.');
|
|
7012
7377
|
}
|
|
7013
7378
|
const objects = Array.from(buffers);
|
|
7014
|
-
|
|
7015
|
-
pipeline?.
|
|
7379
|
+
// reuse the very pipeline used to render (WGSL modifiers included)
|
|
7380
|
+
pipeline?.raycast?.(this._pass, interaction, ...buffers);
|
|
7016
7381
|
for (let buffer of objects) {
|
|
7017
7382
|
const item = buffer.item;
|
|
7018
7383
|
if (item.inert) {
|
|
@@ -7028,21 +7393,24 @@ fn computeOffsetPosition(p0: vec4f, p1: vec4f, index: u32) -> vec4f {
|
|
|
7028
7393
|
}
|
|
7029
7394
|
const pass = this._pass;
|
|
7030
7395
|
const commandEncoder = this._encoder;
|
|
7396
|
+
if (pacemCore.Utils.isNull(commandEncoder)) {
|
|
7397
|
+
return Promise.resolve([]);
|
|
7398
|
+
}
|
|
7031
7399
|
const { device } = this._context;
|
|
7032
7400
|
const { render } = this._textures;
|
|
7033
7401
|
const pickTexture = render.texture;
|
|
7034
7402
|
const pickBuffer = this._ensureBuffer();
|
|
7035
7403
|
pass.end();
|
|
7404
|
+
this._pass = null;
|
|
7405
|
+
// the very pixel the pass was scissored to
|
|
7406
|
+
const { x, y } = this._pixel;
|
|
7036
7407
|
commandEncoder.copyTextureToBuffer({
|
|
7037
7408
|
texture: pickTexture,
|
|
7038
7409
|
// mipLevel: 0,
|
|
7039
|
-
origin: {
|
|
7040
|
-
x: pixel.x,
|
|
7041
|
-
y: pixel.y,
|
|
7042
|
-
}
|
|
7410
|
+
origin: { x, y }
|
|
7043
7411
|
}, {
|
|
7044
7412
|
buffer: pickBuffer,
|
|
7045
|
-
bytesPerRow:
|
|
7413
|
+
bytesPerRow: BYTES_PER_ROW,
|
|
7046
7414
|
rowsPerImage: 1,
|
|
7047
7415
|
}, {
|
|
7048
7416
|
width: NUM_PIXELS,
|
|
@@ -7075,13 +7443,19 @@ fn computeOffsetPosition(p0: vec4f, p1: vec4f, index: u32) -> vec4f {
|
|
|
7075
7443
|
//pickBuffer.destroy();
|
|
7076
7444
|
//pickTexture.destroy();
|
|
7077
7445
|
//objects.values().forEach(b => b.unlock());
|
|
7446
|
+
}, _ => {
|
|
7447
|
+
// e.g. buffer destroyed (resize/dispose) or device lost: don't stay pending forever
|
|
7448
|
+
resetHandle();
|
|
7449
|
+
resolve([]);
|
|
7078
7450
|
});
|
|
7079
7451
|
});
|
|
7080
7452
|
};
|
|
7081
7453
|
}
|
|
7082
7454
|
_createTexture(format) {
|
|
7083
7455
|
const { device, canvas } = this._context;
|
|
7084
|
-
|
|
7456
|
+
// same size as the render target, so that pixel coordinates match
|
|
7457
|
+
const maxSize = device.limits.maxTextureDimension2D;
|
|
7458
|
+
const width = clampToTextureSize(canvas.width, maxSize), height = clampToTextureSize(canvas.height, maxSize);
|
|
7085
7459
|
return device.createTexture({
|
|
7086
7460
|
size: [width, height, 1],
|
|
7087
7461
|
format,
|
|
@@ -7130,10 +7504,16 @@ fn computeOffsetPosition(p0: vec4f, p1: vec4f, index: u32) -> vec4f {
|
|
|
7130
7504
|
this._buffer = null;
|
|
7131
7505
|
}
|
|
7132
7506
|
}
|
|
7133
|
-
|
|
7507
|
+
get pending() {
|
|
7508
|
+
return this._handle ?? null;
|
|
7509
|
+
}
|
|
7510
|
+
begin(pixel) {
|
|
7134
7511
|
const { device } = this._context;
|
|
7135
7512
|
this._encoder = device.createCommandEncoder({ label: LABEL_PREFIX + 'colorpick-raycaster' });
|
|
7136
7513
|
const { render, depth } = this._ensureTextures();
|
|
7514
|
+
const { width, height } = render.texture;
|
|
7515
|
+
const x = clampToPixel(pixel?.x, width), y = clampToPixel(pixel?.y, height);
|
|
7516
|
+
this._pixel = { x, y };
|
|
7137
7517
|
const passDescriptor = {
|
|
7138
7518
|
label: LABEL_PREFIX + 'colorpick-raycaster-pass',
|
|
7139
7519
|
colorAttachments: [
|
|
@@ -7152,10 +7532,127 @@ fn computeOffsetPosition(p0: vec4f, p1: vec4f, index: u32) -> vec4f {
|
|
|
7152
7532
|
},
|
|
7153
7533
|
};
|
|
7154
7534
|
this._pass = this._encoder.beginRenderPass(passDescriptor);
|
|
7535
|
+
// only the picked pixel matters: don't rasterize anything else
|
|
7536
|
+
this._pass.setScissorRect(x, y, 1, 1);
|
|
7155
7537
|
this._objects.clear();
|
|
7156
7538
|
}
|
|
7157
7539
|
}
|
|
7158
7540
|
|
|
7541
|
+
//namespace Pacem.Drawing3D.WebGPU {
|
|
7542
|
+
/** Bytes of one `ABufferFragment` (`color: u32, depth: f32, next: u32`). */
|
|
7543
|
+
const FRAGMENT_SIZE = 12;
|
|
7544
|
+
/**
|
|
7545
|
+
* Factory for {@link ABuffer}s: the GPU resources backing order-independent transparency (per-pixel linked lists of
|
|
7546
|
+
* translucent fragments, sorted and composited by a full-screen pass). The composite pipeline is built once per
|
|
7547
|
+
* {@link Context}; buffers are sized after the render target, so they get recreated on resize.
|
|
7548
|
+
*
|
|
7549
|
+
* Known limits: about {@link ABUFFER_AVERAGE_LAYERS} translucent layers per pixel on average (further fragments are
|
|
7550
|
+
* dropped), and at most `ABUFFER_MAX_SORTED_LAYERS` composited per pixel.
|
|
7551
|
+
*/
|
|
7552
|
+
class ABuffers {
|
|
7553
|
+
static { this._composites = new WeakMap(); }
|
|
7554
|
+
static _ensureComposite(ctx) {
|
|
7555
|
+
const existing = this._composites.get(ctx);
|
|
7556
|
+
if (!pacemCore.Utils.isNull(existing)) {
|
|
7557
|
+
return existing;
|
|
7558
|
+
}
|
|
7559
|
+
const { device, format } = ctx;
|
|
7560
|
+
const layout = device.createBindGroupLayout({
|
|
7561
|
+
label: LABEL_PREFIX + 'abuffer-composite-bind-group-layout',
|
|
7562
|
+
entries: [
|
|
7563
|
+
{ binding: 0, visibility: GPUShaderStage.FRAGMENT, buffer: { type: 'read-only-storage' } },
|
|
7564
|
+
{ binding: 1, visibility: GPUShaderStage.FRAGMENT, buffer: { type: 'read-only-storage' } },
|
|
7565
|
+
{ binding: 2, visibility: GPUShaderStage.FRAGMENT, buffer: { type: 'uniform' } },
|
|
7566
|
+
]
|
|
7567
|
+
});
|
|
7568
|
+
const code = getABufferCompositeWgsl();
|
|
7569
|
+
const module = device.createShaderModule({ label: LABEL_PREFIX + 'abuffer-composite-shader', code });
|
|
7570
|
+
const pipelineLayout = device.createPipelineLayout({ label: LABEL_PREFIX + 'abuffer-composite-pipeline-layout', bindGroupLayouts: [layout] });
|
|
7571
|
+
const pipeline = device.createRenderPipeline({
|
|
7572
|
+
label: LABEL_PREFIX + 'abuffer-composite-pipeline',
|
|
7573
|
+
layout: pipelineLayout,
|
|
7574
|
+
vertex: { module, entryPoint: 'vertexMain' },
|
|
7575
|
+
fragment: {
|
|
7576
|
+
module, entryPoint: 'fragmentMain',
|
|
7577
|
+
targets: [{
|
|
7578
|
+
format,
|
|
7579
|
+
// the composite outputs premultiplied colors
|
|
7580
|
+
blend: {
|
|
7581
|
+
color: { srcFactor: 'one', dstFactor: 'one-minus-src-alpha' },
|
|
7582
|
+
alpha: { srcFactor: 'one', dstFactor: 'one-minus-src-alpha' }
|
|
7583
|
+
}
|
|
7584
|
+
}]
|
|
7585
|
+
},
|
|
7586
|
+
primitive: { topology: 'triangle-list' }
|
|
7587
|
+
});
|
|
7588
|
+
const state = { pipeline, layout };
|
|
7589
|
+
this._composites.set(ctx, state);
|
|
7590
|
+
return state;
|
|
7591
|
+
}
|
|
7592
|
+
/** Fragment list capacity: {@link ABUFFER_AVERAGE_LAYERS} per pixel, within the device storage/buffer size limits. */
|
|
7593
|
+
static _capacity(device, pixels) {
|
|
7594
|
+
const limits = device.limits;
|
|
7595
|
+
const maxBytes = Math.min(limits.maxStorageBufferBindingSize, limits.maxBufferSize);
|
|
7596
|
+
const maxFragments = Math.floor(maxBytes / FRAGMENT_SIZE);
|
|
7597
|
+
const wanted = ABUFFER_AVERAGE_LAYERS * pixels;
|
|
7598
|
+
const capacity = Math.min(wanted, maxFragments);
|
|
7599
|
+
return Math.max(1, capacity);
|
|
7600
|
+
}
|
|
7601
|
+
/** Forgets the composite pipeline built for `ctx` (e.g. on dispose). */
|
|
7602
|
+
static dispose(ctx) {
|
|
7603
|
+
this._composites.delete(ctx);
|
|
7604
|
+
}
|
|
7605
|
+
/**
|
|
7606
|
+
* Creates the A-buffer resources for a `width`×`height` render target.
|
|
7607
|
+
* @param ctx WebGPU context.
|
|
7608
|
+
* @param depth View of the opaque (multisampled) depth texture the translucent fragments get tested against.
|
|
7609
|
+
*/
|
|
7610
|
+
static create(ctx, depth, width, height) {
|
|
7611
|
+
const { device } = ctx;
|
|
7612
|
+
const { pipeline, layout } = this._ensureComposite(ctx);
|
|
7613
|
+
const pixels = Math.max(1, width * height);
|
|
7614
|
+
const capacity = ABuffers._capacity(device, pixels);
|
|
7615
|
+
// counter + one head per pixel
|
|
7616
|
+
const heads = device.createBuffer({
|
|
7617
|
+
label: LABEL_PREFIX + 'abuffer-heads-buffer',
|
|
7618
|
+
size: 4 * (pixels + 1),
|
|
7619
|
+
usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_DST
|
|
7620
|
+
});
|
|
7621
|
+
const list = device.createBuffer({
|
|
7622
|
+
label: LABEL_PREFIX + 'abuffer-list-buffer',
|
|
7623
|
+
size: FRAGMENT_SIZE * capacity,
|
|
7624
|
+
usage: GPUBufferUsage.STORAGE
|
|
7625
|
+
});
|
|
7626
|
+
const infoValue = new Uint32Array([width, height, capacity, 0]);
|
|
7627
|
+
const info = Buffers.createUniform(device, infoValue, LABEL_PREFIX + 'abuffer-info-buffer');
|
|
7628
|
+
const bindGroup = device.createBindGroup({
|
|
7629
|
+
label: LABEL_PREFIX + 'abuffer-composite-bind-group',
|
|
7630
|
+
layout,
|
|
7631
|
+
entries: [
|
|
7632
|
+
{ binding: 0, resource: { buffer: heads } },
|
|
7633
|
+
{ binding: 1, resource: { buffer: list } },
|
|
7634
|
+
{ binding: 2, resource: { buffer: info } },
|
|
7635
|
+
]
|
|
7636
|
+
});
|
|
7637
|
+
return {
|
|
7638
|
+
heads, list, info, depth, width, height,
|
|
7639
|
+
clear: (encoder) => {
|
|
7640
|
+
encoder.clearBuffer(heads);
|
|
7641
|
+
},
|
|
7642
|
+
composite: (pass) => {
|
|
7643
|
+
pass.setPipeline(pipeline);
|
|
7644
|
+
pass.setBindGroup(0, bindGroup);
|
|
7645
|
+
pass.draw(3);
|
|
7646
|
+
},
|
|
7647
|
+
destroy: () => {
|
|
7648
|
+
heads.destroy();
|
|
7649
|
+
list.destroy();
|
|
7650
|
+
info.destroy();
|
|
7651
|
+
}
|
|
7652
|
+
};
|
|
7653
|
+
}
|
|
7654
|
+
}
|
|
7655
|
+
|
|
7159
7656
|
//namespace Pacem.Drawing3D.WebGPU {
|
|
7160
7657
|
const Vector3D$1 = pacemNumerical.Geometry.LinearAlgebra.Vector3D;
|
|
7161
7658
|
/** Reason a WebGPU {@link Renderer} failed to initialize, as reported via a rejected {@link Renderers.create} promise (see {@link WebGPUIssue}). */
|
|
@@ -7209,6 +7706,115 @@ fn computeOffsetPosition(p0: vec4f, p1: vec4f, index: u32) -> vec4f {
|
|
|
7209
7706
|
tex?.destroy();
|
|
7210
7707
|
}
|
|
7211
7708
|
}
|
|
7709
|
+
/** Whether `resolved` was resolved against the very same material (and texture), geometry and lights. */
|
|
7710
|
+
function isResolvedFor(resolved, material, texture, geometry, lightsSignature) {
|
|
7711
|
+
if (pacemCore.Utils.isNull(resolved)) {
|
|
7712
|
+
return false;
|
|
7713
|
+
}
|
|
7714
|
+
if (resolved.material !== material || resolved.texture !== texture) {
|
|
7715
|
+
return false;
|
|
7716
|
+
}
|
|
7717
|
+
return resolved.geometry === geometry && resolved.lights === lightsSignature;
|
|
7718
|
+
}
|
|
7719
|
+
/** Whether `aBuffer` matches the current render targets. */
|
|
7720
|
+
function isABufferFor(aBuffer, depthView, width, height) {
|
|
7721
|
+
if (pacemCore.Utils.isNull(aBuffer) || aBuffer.depth !== depthView) {
|
|
7722
|
+
return false;
|
|
7723
|
+
}
|
|
7724
|
+
return aBuffer.width === width && aBuffer.height === height;
|
|
7725
|
+
}
|
|
7726
|
+
/** Destroys the buffers of `previous` that aren't in `current` anymore. */
|
|
7727
|
+
function destroyMissing(previous, current) {
|
|
7728
|
+
const alive = new Set(current);
|
|
7729
|
+
for (let buffer of previous) {
|
|
7730
|
+
if (alive.has(buffer)) {
|
|
7731
|
+
continue;
|
|
7732
|
+
}
|
|
7733
|
+
buffer.destroy();
|
|
7734
|
+
}
|
|
7735
|
+
}
|
|
7736
|
+
/** Gets the (non-disposed) {@link ManagedBuffer} stored for `item`, creating (and storing) a new one when needed. */
|
|
7737
|
+
function createOrYieldManaged(store, item) {
|
|
7738
|
+
const found = store.get(item);
|
|
7739
|
+
if (!pacemCore.Utils.isNull(found) && !found.disposed) {
|
|
7740
|
+
return found;
|
|
7741
|
+
}
|
|
7742
|
+
const created = ManagedBuffers.create(item);
|
|
7743
|
+
store.set(item, created);
|
|
7744
|
+
return created;
|
|
7745
|
+
}
|
|
7746
|
+
/** Whether `mesh` goes through the A-buffer: a (visible) translucent material on a pipeline supporting it. */
|
|
7747
|
+
function isTranslucent(mesh, pipeline) {
|
|
7748
|
+
if (pacemCore.Utils.isNull(pipeline.translucent)) {
|
|
7749
|
+
return false;
|
|
7750
|
+
}
|
|
7751
|
+
if (!isMeshGeometry(mesh.geometry)) {
|
|
7752
|
+
return false;
|
|
7753
|
+
}
|
|
7754
|
+
return Materials.isTranslucent(mesh.material);
|
|
7755
|
+
}
|
|
7756
|
+
/** Stable small integer per object, used to batch draws sharing the same resources. */
|
|
7757
|
+
const objectIds = new WeakMap();
|
|
7758
|
+
let lastObjectId = 0;
|
|
7759
|
+
function objectId(obj) {
|
|
7760
|
+
if (pacemCore.Utils.isNull(obj)) {
|
|
7761
|
+
return 0;
|
|
7762
|
+
}
|
|
7763
|
+
const existing = objectIds.get(obj);
|
|
7764
|
+
if (!pacemCore.Utils.isNull(existing)) {
|
|
7765
|
+
return existing;
|
|
7766
|
+
}
|
|
7767
|
+
const id = ++lastObjectId;
|
|
7768
|
+
objectIds.set(obj, id);
|
|
7769
|
+
return id;
|
|
7770
|
+
}
|
|
7771
|
+
/** Approximates the pipeline recipe of a mesh (geometry kind, shader, texture, fat lines), cheaply. */
|
|
7772
|
+
function recipeOf(mesh) {
|
|
7773
|
+
const material = mesh.material;
|
|
7774
|
+
const kind = isMeshGeometry(mesh.geometry) ? 'mesh' : 'line';
|
|
7775
|
+
const shader = material?.shader ?? '';
|
|
7776
|
+
const map = material?.texture ? '-map' : '';
|
|
7777
|
+
const fat = material?.lineWidth > 1 ? '-fat' : '';
|
|
7778
|
+
return kind + '-' + shader + map + fat;
|
|
7779
|
+
}
|
|
7780
|
+
/**
|
|
7781
|
+
* Draw-order key for a mesh: opaque meshes first, grouped by pipeline recipe, material and geometry (so that the
|
|
7782
|
+
* redundant state changes get skipped), translucent ones last.
|
|
7783
|
+
*/
|
|
7784
|
+
function drawOrderKey(buffer) {
|
|
7785
|
+
const mesh = buffer.item, material = mesh.material;
|
|
7786
|
+
return {
|
|
7787
|
+
translucent: Materials.isTranslucent(material),
|
|
7788
|
+
recipe: recipeOf(mesh),
|
|
7789
|
+
material: objectId(material),
|
|
7790
|
+
geometry: objectId(mesh.geometry)
|
|
7791
|
+
};
|
|
7792
|
+
}
|
|
7793
|
+
function compareDrawOrder(a, b) {
|
|
7794
|
+
if (a.translucent !== b.translucent) {
|
|
7795
|
+
return a.translucent ? 1 : -1;
|
|
7796
|
+
}
|
|
7797
|
+
// translucent meshes keep their relative (datasource) order
|
|
7798
|
+
if (a.translucent) {
|
|
7799
|
+
return 0;
|
|
7800
|
+
}
|
|
7801
|
+
if (a.recipe !== b.recipe) {
|
|
7802
|
+
return a.recipe < b.recipe ? -1 : 1;
|
|
7803
|
+
}
|
|
7804
|
+
if (a.material !== b.material) {
|
|
7805
|
+
return a.material - b.material;
|
|
7806
|
+
}
|
|
7807
|
+
return a.geometry - b.geometry;
|
|
7808
|
+
}
|
|
7809
|
+
function sortForDrawing(meshes) {
|
|
7810
|
+
const entries = meshes.map(m => [m, drawOrderKey(m)]);
|
|
7811
|
+
const keys = new Map(entries);
|
|
7812
|
+
// Array.prototype.sort is stable
|
|
7813
|
+
meshes.sort((a, b) => {
|
|
7814
|
+
const ka = keys.get(a), kb = keys.get(b);
|
|
7815
|
+
return compareDrawOrder(ka, kb);
|
|
7816
|
+
});
|
|
7817
|
+
}
|
|
7212
7818
|
class RendererClass {
|
|
7213
7819
|
#stage;
|
|
7214
7820
|
#canvas;
|
|
@@ -7216,6 +7822,8 @@ fn computeOffsetPosition(p0: vec4f, p1: vec4f, index: u32) -> vec4f {
|
|
|
7216
7822
|
#renderables;
|
|
7217
7823
|
#geometries;
|
|
7218
7824
|
#materials;
|
|
7825
|
+
#pipelines;
|
|
7826
|
+
#pipelineOptions;
|
|
7219
7827
|
#looper;
|
|
7220
7828
|
#textures;
|
|
7221
7829
|
#config;
|
|
@@ -7228,16 +7836,25 @@ fn computeOffsetPosition(p0: vec4f, p1: vec4f, index: u32) -> vec4f {
|
|
|
7228
7836
|
this.#renderables = new WeakMap();
|
|
7229
7837
|
this.#geometries = new WeakMap();
|
|
7230
7838
|
this.#materials = new WeakMap();
|
|
7839
|
+
this.#pipelines = new WeakMap();
|
|
7840
|
+
this.#pipelineOptions = { multisample: true };
|
|
7231
7841
|
this.#config = { enableValidation: false };
|
|
7232
7842
|
this.#disabled = false;
|
|
7233
7843
|
this._logError = (evt) => {
|
|
7234
|
-
const
|
|
7235
|
-
|
|
7236
|
-
const error = 'error' in evt ? evt.error : evt;
|
|
7237
|
-
logger.log(pacemCore.Logging.LogLevel.Error, error.message, 'WebGPU');
|
|
7238
|
-
}
|
|
7844
|
+
const error = 'error' in evt ? evt.error : evt;
|
|
7845
|
+
this._log(error.message);
|
|
7239
7846
|
};
|
|
7240
7847
|
this.#rebuildingContext = true;
|
|
7848
|
+
/** Set when the {@link GPUDevice} gets lost (not destroyed on purpose): nothing can be rendered anymore. */
|
|
7849
|
+
this.#lost = false;
|
|
7850
|
+
this._onDeviceLost = (info) => {
|
|
7851
|
+
// explicit `destroy()` (see `dispose`) is not a failure
|
|
7852
|
+
if (info.reason === 'destroyed') {
|
|
7853
|
+
return;
|
|
7854
|
+
}
|
|
7855
|
+
this.#lost = true;
|
|
7856
|
+
this._log(`WebGPU device lost: ${info.message}`);
|
|
7857
|
+
};
|
|
7241
7858
|
/** Whether the renderer is affected by vertex or fragment modifiers.
|
|
7242
7859
|
* When true, the renderer must provide updated time, cursor position and canvas size to the pipeline's bind groups.
|
|
7243
7860
|
*/
|
|
@@ -7273,7 +7890,8 @@ fn computeOffsetPosition(p0: vec4f, p1: vec4f, index: u32) -> vec4f {
|
|
|
7273
7890
|
const depthTex = device.createTexture({
|
|
7274
7891
|
label: LABEL_PREFIX + 'depth-texture',
|
|
7275
7892
|
format: 'depth24plus',
|
|
7276
|
-
|
|
7893
|
+
// also read by the A-buffer translucent pass (manual depth test)
|
|
7894
|
+
usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.TEXTURE_BINDING,
|
|
7277
7895
|
size: [canvasTexture.width, canvasTexture.height],
|
|
7278
7896
|
sampleCount: 4,
|
|
7279
7897
|
});
|
|
@@ -7304,48 +7922,65 @@ fn computeOffsetPosition(p0: vec4f, p1: vec4f, index: u32) -> vec4f {
|
|
|
7304
7922
|
depthClearValue: 1,
|
|
7305
7923
|
depthLoadOp: 'clear',
|
|
7306
7924
|
depthStoreOp: 'store',
|
|
7307
|
-
stencilClearValue: 0,
|
|
7308
|
-
stencilReadOnly: true,
|
|
7309
7925
|
};
|
|
7310
7926
|
// override
|
|
7311
7927
|
colorAttachment.view = renderTexView;
|
|
7312
7928
|
colorAttachment.resolveTarget = canvasTexView;
|
|
7313
7929
|
}
|
|
7314
|
-
return
|
|
7930
|
+
return {
|
|
7931
|
+
descriptor: passDescriptor, canvasView: canvasTexView, depthView: multisample ? textures.depth.view : null,
|
|
7932
|
+
width: canvasTexture.width, height: canvasTexture.height
|
|
7933
|
+
};
|
|
7315
7934
|
}
|
|
7316
7935
|
;
|
|
7317
|
-
|
|
7936
|
+
/** Sizes the canvas (i.e. the render target) after `size` (or its current CSS box when omitted). */
|
|
7937
|
+
_applySize(canvas = this.#canvas, size = this.#stage.size) {
|
|
7318
7938
|
size ??= canvas;
|
|
7319
|
-
let w = size.width;
|
|
7320
|
-
let h = size.height;
|
|
7321
7939
|
const devicePixelRatio = 1; // window.devicePixelRatio;
|
|
7322
|
-
canvas.width =
|
|
7323
|
-
canvas.height =
|
|
7940
|
+
canvas.width = size.width * devicePixelRatio;
|
|
7941
|
+
canvas.height = size.height * devicePixelRatio;
|
|
7942
|
+
}
|
|
7943
|
+
_buildContext(canvas = this.#canvas, size = this.#stage.size) {
|
|
7944
|
+
this._applySize(canvas, size);
|
|
7324
7945
|
const context = canvas.getContext('webgpu');
|
|
7325
7946
|
const textureFormat = navigator.gpu.getPreferredCanvasFormat();
|
|
7326
7947
|
return { context, textureFormat };
|
|
7327
7948
|
}
|
|
7949
|
+
/** The canvas alpha mode matching the stage `transparent` flag. */
|
|
7950
|
+
_alphaMode() {
|
|
7951
|
+
return this.#stage.transparent ? 'premultiplied' : 'opaque';
|
|
7952
|
+
}
|
|
7953
|
+
#alphaMode;
|
|
7328
7954
|
_buildUpContext(device, adapter, context, format) {
|
|
7329
|
-
const
|
|
7955
|
+
const alphaMode = this._alphaMode();
|
|
7956
|
+
this.#alphaMode = alphaMode;
|
|
7330
7957
|
context.configure({
|
|
7331
|
-
alphaMode
|
|
7958
|
+
alphaMode,
|
|
7332
7959
|
device,
|
|
7333
7960
|
format,
|
|
7334
7961
|
});
|
|
7335
7962
|
this.#context = { device, adapter, canvas: this.#canvas, context, format };
|
|
7336
7963
|
this.#rebuildingContext = false;
|
|
7337
7964
|
}
|
|
7965
|
+
_log(message) {
|
|
7966
|
+
const stage = this.#stage, logger = stage.logger;
|
|
7967
|
+
if (!pacemCore.Utils.isNull(logger)) {
|
|
7968
|
+
logger.log(pacemCore.Logging.LogLevel.Error, message, 'WebGPU');
|
|
7969
|
+
}
|
|
7970
|
+
}
|
|
7338
7971
|
async init(config) {
|
|
7339
7972
|
this.#config = config;
|
|
7973
|
+
this.#pipelineOptions = { multisample: true, modifiers: config.modifiers };
|
|
7340
7974
|
const adapter = await navigator.gpu.requestAdapter();
|
|
7341
7975
|
if (pacemCore.Utils.isNull(adapter)) {
|
|
7342
7976
|
throw new Error('WebGPU adapter unavalable or disabled.');
|
|
7343
7977
|
}
|
|
7344
7978
|
const device = await adapter.requestDevice();
|
|
7345
|
-
if (pacemCore.Utils.isNull(
|
|
7979
|
+
if (pacemCore.Utils.isNull(device)) {
|
|
7346
7980
|
throw new Error('WebGPU device unavalable or disabled.');
|
|
7347
7981
|
}
|
|
7348
7982
|
device.addEventListener('uncapturederror', this._logError);
|
|
7983
|
+
device.lost.then(this._onDeviceLost);
|
|
7349
7984
|
// set flag for shader modifiers presence, this will be used to determine whether to update the interaction buffer on each render call
|
|
7350
7985
|
this.#hasModifiers = !pacemCore.Utils.isNull(config.modifiers?.version) && !pacemCore.Utils.isNull(config.modifiers)
|
|
7351
7986
|
&& (!pacemCore.Utils.isNull(config.modifiers.vertexInput) || !pacemCore.Utils.isNull(config.modifiers.vertexOutput) || !pacemCore.Utils.isNull(config.modifiers.fragment));
|
|
@@ -7353,15 +7988,86 @@ fn computeOffsetPosition(p0: vec4f, p1: vec4f, index: u32) -> vec4f {
|
|
|
7353
7988
|
this._buildUpContext(device, adapter, context, format);
|
|
7354
7989
|
}
|
|
7355
7990
|
#rebuildingContext;
|
|
7991
|
+
/** Set when the {@link GPUDevice} gets lost (not destroyed on purpose): nothing can be rendered anymore. */
|
|
7992
|
+
#lost;
|
|
7356
7993
|
/** Whether the renderer is affected by vertex or fragment modifiers.
|
|
7357
7994
|
* When true, the renderer must provide updated time, cursor position and canvas size to the pipeline's bind groups.
|
|
7358
7995
|
*/
|
|
7359
7996
|
#hasModifiers;
|
|
7997
|
+
/** Light types signature, part of the cache key of the pipelines resolved per mesh. */
|
|
7998
|
+
_lightsSignature(lights) {
|
|
7999
|
+
return lights.map(l => l.item.type).join('-');
|
|
8000
|
+
}
|
|
8001
|
+
/**
|
|
8002
|
+
* Returns the {@link RenderPipeline} drawing `mesh`, reusing the one resolved in previous frames as long as its
|
|
8003
|
+
* material (and texture), geometry and the scene lights didn't change; otherwise goes through {@link RenderPipelines.create}
|
|
8004
|
+
* (which memoizes the built pipelines by recipe).
|
|
8005
|
+
*/
|
|
8006
|
+
_resolvePipeline(mesh, camera, lights, lightsSignature) {
|
|
8007
|
+
const item = mesh.item, material = item.material, texture = material?.texture, geometry = item.geometry;
|
|
8008
|
+
const pipelines = this.#pipelines;
|
|
8009
|
+
const existing = pipelines.get(mesh);
|
|
8010
|
+
const reusable = isResolvedFor(existing, material, texture, geometry, lightsSignature);
|
|
8011
|
+
if (reusable) {
|
|
8012
|
+
// in-place material changes (flagged) may affect the opacity
|
|
8013
|
+
if (material?.flags?.length > 0) {
|
|
8014
|
+
existing.translucent = isTranslucent(item, existing.pipeline);
|
|
8015
|
+
}
|
|
8016
|
+
return existing;
|
|
8017
|
+
}
|
|
8018
|
+
const pipeline = RenderPipelines.create(this.#context, [mesh, camera, ...lights], this.#pipelineOptions);
|
|
8019
|
+
const translucent = isTranslucent(item, pipeline);
|
|
8020
|
+
const resolved = { material, texture, geometry, lights: lightsSignature, pipeline, translucent };
|
|
8021
|
+
pipelines.set(mesh, resolved);
|
|
8022
|
+
return resolved;
|
|
8023
|
+
}
|
|
8024
|
+
#aBuffer;
|
|
8025
|
+
/** Returns the A-buffer matching the current render targets, (re)creating it when needed. */
|
|
8026
|
+
_ensureABuffer(depthView, width, height) {
|
|
8027
|
+
const current = this.#aBuffer;
|
|
8028
|
+
if (isABufferFor(current, depthView, width, height)) {
|
|
8029
|
+
return current;
|
|
8030
|
+
}
|
|
8031
|
+
current?.destroy();
|
|
8032
|
+
const aBuffer = ABuffers.create(this.#context, depthView, width, height);
|
|
8033
|
+
this.#aBuffer = aBuffer;
|
|
8034
|
+
return aBuffer;
|
|
8035
|
+
}
|
|
8036
|
+
/** Whether a frame can be rendered: context ready, device alive, scene set and a non-empty render target. */
|
|
8037
|
+
_canRender() {
|
|
8038
|
+
if (this.#rebuildingContext || this.#lost || pacemCore.Utils.isNull(this.#looper)) {
|
|
8039
|
+
return false;
|
|
8040
|
+
}
|
|
8041
|
+
const canvas = this.#canvas;
|
|
8042
|
+
return canvas.width > 0 && canvas.height > 0;
|
|
8043
|
+
}
|
|
8044
|
+
/** Pops a validation error scope, logging the error it caught (if any). */
|
|
8045
|
+
_popValidationScope(device) {
|
|
8046
|
+
const popped = device.popErrorScope();
|
|
8047
|
+
popped.then(error => {
|
|
8048
|
+
if (pacemCore.Utils.isNull(error)) {
|
|
8049
|
+
return;
|
|
8050
|
+
}
|
|
8051
|
+
this._logError(error);
|
|
8052
|
+
});
|
|
8053
|
+
}
|
|
8054
|
+
/** Ends the translucent pass, encodes the composite one onto the canvas and returns the A-buffer commands. */
|
|
8055
|
+
_finishTranslucent({ encoder, pass, aBuffer }, canvasView) {
|
|
8056
|
+
pass.end();
|
|
8057
|
+
// sort & composite the translucent fragments over the (resolved) opaque render
|
|
8058
|
+
const compositePass = encoder.beginRenderPass({
|
|
8059
|
+
label: LABEL_PREFIX + 'abuffer-composite-pass',
|
|
8060
|
+
colorAttachments: [{ view: canvasView, loadOp: 'load', storeOp: 'store' }]
|
|
8061
|
+
});
|
|
8062
|
+
aBuffer.composite(compositePass);
|
|
8063
|
+
compositePass.end();
|
|
8064
|
+
return encoder.finish();
|
|
8065
|
+
}
|
|
7360
8066
|
/**
|
|
7361
8067
|
* Render procedure.
|
|
7362
8068
|
*/
|
|
7363
8069
|
render(interaction) {
|
|
7364
|
-
if (
|
|
8070
|
+
if (!this._canRender()) {
|
|
7365
8071
|
return;
|
|
7366
8072
|
}
|
|
7367
8073
|
const context = this.#context, device = context.device,
|
|
@@ -7374,10 +8080,31 @@ fn computeOffsetPosition(p0: vec4f, p1: vec4f, index: u32) -> vec4f {
|
|
|
7374
8080
|
pacemCore.Utils.extend(this.#interaction, interaction);
|
|
7375
8081
|
}
|
|
7376
8082
|
const multisample = true;
|
|
7377
|
-
const passDescriptor = this._buildPassDescriptor({ multisample });
|
|
8083
|
+
const { descriptor: passDescriptor, canvasView, depthView, width, height } = this._buildPassDescriptor({ multisample });
|
|
8084
|
+
const transparency = this.#config?.transparency ?? 'a-buffer';
|
|
8085
|
+
const aBufferMode = transparency === 'a-buffer' && !pacemCore.Utils.isNull(depthView);
|
|
7378
8086
|
// rendering zone
|
|
7379
8087
|
const commandEncoder = device.createCommandEncoder({ label: LABEL_PREFIX + 'renderer' });
|
|
7380
8088
|
const pass = commandEncoder.beginRenderPass(passDescriptor);
|
|
8089
|
+
const lightsSignature = this._lightsSignature(looper.items.lights);
|
|
8090
|
+
// A-buffer (order-independent transparency): a second encoder, lazily started at the first translucent mesh
|
|
8091
|
+
// (so that its buffers refresh while the stale flags are still there), submitted after the opaque one
|
|
8092
|
+
let translucent = null;
|
|
8093
|
+
const ensureTranslucentPass = () => {
|
|
8094
|
+
if (!pacemCore.Utils.isNull(translucent)) {
|
|
8095
|
+
return translucent;
|
|
8096
|
+
}
|
|
8097
|
+
const aBuffer = this._ensureABuffer(depthView, width, height);
|
|
8098
|
+
const encoder = device.createCommandEncoder({ label: LABEL_PREFIX + 'abuffer' });
|
|
8099
|
+
aBuffer.clear(encoder);
|
|
8100
|
+
const translucentPass = encoder.beginRenderPass({
|
|
8101
|
+
label: LABEL_PREFIX + 'abuffer-translucent-pass',
|
|
8102
|
+
colorAttachments: [],
|
|
8103
|
+
depthStencilAttachment: { view: depthView, depthReadOnly: true }
|
|
8104
|
+
});
|
|
8105
|
+
translucent = { encoder, pass: translucentPass, aBuffer };
|
|
8106
|
+
return translucent;
|
|
8107
|
+
};
|
|
7381
8108
|
// loop
|
|
7382
8109
|
looper.loop((mesh, camera, lights) => {
|
|
7383
8110
|
if (mesh.item.hide) {
|
|
@@ -7388,22 +8115,29 @@ fn computeOffsetPosition(p0: vec4f, p1: vec4f, index: u32) -> vec4f {
|
|
|
7388
8115
|
if (validationScope) {
|
|
7389
8116
|
device.pushErrorScope('validation');
|
|
7390
8117
|
}
|
|
7391
|
-
const renderables = [mesh, camera, ...lights];
|
|
7392
8118
|
// inject here (pipeline options) any global rendering data (time, cursor, etc.) that may be needed by the shader modifiers
|
|
7393
|
-
const
|
|
8119
|
+
const resolved = this._resolvePipeline(mesh, camera, lights, lightsSignature);
|
|
7394
8120
|
// render
|
|
7395
|
-
|
|
8121
|
+
if (aBufferMode && resolved.translucent) {
|
|
8122
|
+
const { pass: translucentPass, aBuffer } = ensureTranslucentPass();
|
|
8123
|
+
resolved.pipeline.translucent(translucentPass, this.#interactionBuffer, aBuffer, mesh, camera, ...lights);
|
|
8124
|
+
}
|
|
8125
|
+
else {
|
|
8126
|
+
resolved.pipeline.frame(pass, this.#interactionBuffer, mesh, camera, ...lights);
|
|
8127
|
+
}
|
|
7396
8128
|
if (validationScope) {
|
|
7397
|
-
|
|
7398
|
-
if (error) {
|
|
7399
|
-
this._logError(error);
|
|
7400
|
-
}
|
|
7401
|
-
});
|
|
8129
|
+
this._popValidationScope(device);
|
|
7402
8130
|
}
|
|
7403
8131
|
return true;
|
|
7404
8132
|
});
|
|
7405
8133
|
pass.end();
|
|
7406
|
-
|
|
8134
|
+
const opaqueCommands = commandEncoder.finish();
|
|
8135
|
+
if (pacemCore.Utils.isNull(translucent)) {
|
|
8136
|
+
device.queue.submit([opaqueCommands]);
|
|
8137
|
+
return;
|
|
8138
|
+
}
|
|
8139
|
+
const translucentCommands = this._finishTranslucent(translucent, canvasView);
|
|
8140
|
+
device.queue.submit([opaqueCommands, translucentCommands]);
|
|
7407
8141
|
}
|
|
7408
8142
|
set disabled(v) {
|
|
7409
8143
|
this.#disabled = v;
|
|
@@ -7412,17 +8146,23 @@ fn computeOffsetPosition(p0: vec4f, p1: vec4f, index: u32) -> vec4f {
|
|
|
7412
8146
|
return this.#disabled;
|
|
7413
8147
|
}
|
|
7414
8148
|
raycast(pixel) {
|
|
7415
|
-
if (this.#rebuildingContext || pacemCore.Utils.isNull(this.#looper)) {
|
|
8149
|
+
if (this.#rebuildingContext || this.#lost || pacemCore.Utils.isNull(this.#looper)) {
|
|
7416
8150
|
return Promise.resolve([]);
|
|
7417
8151
|
}
|
|
7418
8152
|
const context = this.#context, device = context.device, looper = this.#looper;
|
|
8153
|
+
const raycaster = Raycasters.createColorPicking(context);
|
|
8154
|
+
// a readback is still in flight: encoding the scene again would be wasted
|
|
8155
|
+
const pending = raycaster.pending;
|
|
8156
|
+
if (!pacemCore.Utils.isNull(pending)) {
|
|
8157
|
+
return pending;
|
|
8158
|
+
}
|
|
7419
8159
|
// enable validation scope? (perf hog)
|
|
7420
8160
|
const validationScope = this.#config?.enableValidation ?? false;
|
|
7421
8161
|
// rendering zone
|
|
7422
|
-
|
|
7423
|
-
|
|
8162
|
+
raycaster.begin(pixel);
|
|
8163
|
+
const lightsSignature = this._lightsSignature(looper.items.lights);
|
|
7424
8164
|
// loop
|
|
7425
|
-
looper.loop((mesh, camera) => {
|
|
8165
|
+
looper.loop((mesh, camera, lights) => {
|
|
7426
8166
|
if (mesh.item.hide) {
|
|
7427
8167
|
// TODO: remove unwraps and move to nested loops
|
|
7428
8168
|
// in order to centralize hidden renderable skip logic
|
|
@@ -7431,13 +8171,10 @@ fn computeOffsetPosition(p0: vec4f, p1: vec4f, index: u32) -> vec4f {
|
|
|
7431
8171
|
if (validationScope) {
|
|
7432
8172
|
device.pushErrorScope('validation');
|
|
7433
8173
|
}
|
|
7434
|
-
|
|
8174
|
+
const { pipeline } = this._resolvePipeline(mesh, camera, lights, lightsSignature);
|
|
8175
|
+
raycaster.frame(pipeline, this.#interactionBuffer, mesh, camera);
|
|
7435
8176
|
if (validationScope) {
|
|
7436
|
-
|
|
7437
|
-
if (error) {
|
|
7438
|
-
this._logError(error);
|
|
7439
|
-
}
|
|
7440
|
-
});
|
|
8177
|
+
this._popValidationScope(device);
|
|
7441
8178
|
}
|
|
7442
8179
|
return true;
|
|
7443
8180
|
});
|
|
@@ -7450,30 +8187,24 @@ fn computeOffsetPosition(p0: vec4f, p1: vec4f, index: u32) -> vec4f {
|
|
|
7450
8187
|
store.delete(item);
|
|
7451
8188
|
}
|
|
7452
8189
|
}
|
|
7453
|
-
_createOrYieldRenderable(item
|
|
8190
|
+
_createOrYieldRenderable(item) {
|
|
7454
8191
|
item.stage ??= this.#stage;
|
|
7455
8192
|
const store = this.#renderables;
|
|
7456
|
-
|
|
7457
|
-
|
|
7458
|
-
|
|
8193
|
+
const found = store.get(item);
|
|
8194
|
+
// top-level items own a parentless buffer (a stored one could belong to a group, or be gone)
|
|
8195
|
+
const usable = !pacemCore.Utils.isNull(found) && !found.disposed && pacemCore.Utils.isNull(found.parent);
|
|
8196
|
+
if (usable) {
|
|
8197
|
+
return found;
|
|
7459
8198
|
}
|
|
7460
|
-
|
|
8199
|
+
const created = RenderableBuffers.create(item, this.#geometries, this.#materials, store);
|
|
8200
|
+
store.set(item, created);
|
|
8201
|
+
return created;
|
|
7461
8202
|
}
|
|
7462
8203
|
_createOrYieldGeometry(item) {
|
|
7463
|
-
|
|
7464
|
-
let found = store.get(item);
|
|
7465
|
-
if (pacemCore.Utils.isNull(found)) {
|
|
7466
|
-
store.set(item, found = ManagedBuffers.create(item));
|
|
7467
|
-
}
|
|
7468
|
-
return found;
|
|
8204
|
+
return createOrYieldManaged(this.#geometries, item);
|
|
7469
8205
|
}
|
|
7470
8206
|
_createOrYieldMaterial(item) {
|
|
7471
|
-
|
|
7472
|
-
let found = store.get(item);
|
|
7473
|
-
if (pacemCore.Utils.isNull(found)) {
|
|
7474
|
-
store.set(item, found = ManagedBuffers.create(item));
|
|
7475
|
-
}
|
|
7476
|
-
return found;
|
|
8207
|
+
return createOrYieldManaged(this.#materials, item);
|
|
7477
8208
|
}
|
|
7478
8209
|
_unwrapBuffers(grp, accumulator) {
|
|
7479
8210
|
accumulator ??= { meshes: [], lights: [], cameras: [], groups: [] };
|
|
@@ -7496,6 +8227,15 @@ fn computeOffsetPosition(p0: vec4f, p1: vec4f, index: u32) -> vec4f {
|
|
|
7496
8227
|
return accumulator;
|
|
7497
8228
|
}
|
|
7498
8229
|
;
|
|
8230
|
+
/** Destroys the buffers of `previous` not taking part in `current` anymore (removed/replaced items). */
|
|
8231
|
+
_destroyLeftovers(previous, current) {
|
|
8232
|
+
if (pacemCore.Utils.isNull(previous)) {
|
|
8233
|
+
return;
|
|
8234
|
+
}
|
|
8235
|
+
for (let category of ['meshes', 'lights', 'cameras', 'groups']) {
|
|
8236
|
+
destroyMissing(previous[category], current[category]);
|
|
8237
|
+
}
|
|
8238
|
+
}
|
|
7499
8239
|
_update(array) {
|
|
7500
8240
|
const groupBuffers = [];
|
|
7501
8241
|
const meshBuffers = [];
|
|
@@ -7514,6 +8254,7 @@ fn computeOffsetPosition(p0: vec4f, p1: vec4f, index: u32) -> vec4f {
|
|
|
7514
8254
|
if (isGroup(item)) {
|
|
7515
8255
|
const g = item;
|
|
7516
8256
|
if (g.flags.includes(StalePropertyFlag.Children)) {
|
|
8257
|
+
// rebuilt group buffers reuse the buffers of the children they already had
|
|
7517
8258
|
this.#renderables.delete(g);
|
|
7518
8259
|
}
|
|
7519
8260
|
groupBuffers.push(factory(g));
|
|
@@ -7545,23 +8286,37 @@ fn computeOffsetPosition(p0: vec4f, p1: vec4f, index: u32) -> vec4f {
|
|
|
7545
8286
|
for (let groupBuffer of groupBuffers) {
|
|
7546
8287
|
accumulator = this._unwrapBuffers(groupBuffer, accumulator);
|
|
7547
8288
|
}
|
|
8289
|
+
// opaque first (batched by pipeline/material/geometry), translucent last
|
|
8290
|
+
sortForDrawing(accumulator.meshes);
|
|
7548
8291
|
// destroy leftovers
|
|
7549
|
-
this.#looper?.items
|
|
7550
|
-
if (!meshBuffers.includes(buffer)) {
|
|
7551
|
-
buffer.destroy();
|
|
7552
|
-
}
|
|
7553
|
-
});
|
|
8292
|
+
this._destroyLeftovers(this.#looper?.items, accumulator);
|
|
7554
8293
|
this.#looper = new RenderLooper(accumulator);
|
|
7555
8294
|
}
|
|
7556
8295
|
update(...items) {
|
|
7557
8296
|
this._update(Array.from(items));
|
|
7558
8297
|
}
|
|
7559
8298
|
dispose() {
|
|
8299
|
+
const looper = this.#looper;
|
|
7560
8300
|
this.#looper = null;
|
|
7561
|
-
|
|
7562
|
-
|
|
7563
|
-
|
|
7564
|
-
|
|
8301
|
+
this._destroyLeftovers(looper?.items, { meshes: [], lights: [], cameras: [], groups: [] });
|
|
8302
|
+
this.#interactionBuffer?.destroy();
|
|
8303
|
+
if (!this._disposeContext()) {
|
|
8304
|
+
return;
|
|
8305
|
+
}
|
|
8306
|
+
const { device } = this.#context;
|
|
8307
|
+
device.removeEventListener('uncapturederror', this._logError);
|
|
8308
|
+
device.destroy();
|
|
8309
|
+
}
|
|
8310
|
+
_destroyRenderTargets() {
|
|
8311
|
+
// the A-buffer is sized after (and bound to) the render targets
|
|
8312
|
+
const aBuffer = this.#aBuffer;
|
|
8313
|
+
this.#aBuffer = null;
|
|
8314
|
+
aBuffer?.destroy();
|
|
8315
|
+
const textures = this.#textures;
|
|
8316
|
+
this.#textures = null;
|
|
8317
|
+
if (!pacemCore.Utils.isNull(textures)) {
|
|
8318
|
+
const { render, depth } = textures;
|
|
8319
|
+
destroyTextures(render?.texture, depth?.texture);
|
|
7565
8320
|
}
|
|
7566
8321
|
}
|
|
7567
8322
|
_disposeContext() {
|
|
@@ -7573,28 +8328,36 @@ fn computeOffsetPosition(p0: vec4f, p1: vec4f, index: u32) -> vec4f {
|
|
|
7573
8328
|
Raycasters.dispose(ctx);
|
|
7574
8329
|
// dispose associated pipelines, if any
|
|
7575
8330
|
RenderPipelines.dispose(ctx);
|
|
8331
|
+
ABuffers.dispose(ctx);
|
|
7576
8332
|
// dispose textures
|
|
7577
|
-
|
|
7578
|
-
this.#textures = null;
|
|
7579
|
-
if (!pacemCore.Utils.isNull(textures)) {
|
|
7580
|
-
const { render, depth } = textures;
|
|
7581
|
-
destroyTextures(render?.texture, depth?.texture);
|
|
7582
|
-
}
|
|
8333
|
+
this._destroyRenderTargets();
|
|
7583
8334
|
// dispose context
|
|
7584
8335
|
ctx.context.unconfigure();
|
|
7585
8336
|
return true;
|
|
7586
8337
|
}
|
|
7587
8338
|
resize(size) {
|
|
7588
|
-
|
|
7589
|
-
if (
|
|
7590
|
-
|
|
7591
|
-
const { context, textureFormat: format } = this._buildContext(this.canvas, size);
|
|
7592
|
-
this._buildUpContext(device, adapter, context, format);
|
|
7593
|
-
// interaction
|
|
7594
|
-
if (this.#hasModifiers) {
|
|
7595
|
-
pacemCore.Utils.extend(this.#interaction, { resolution: size });
|
|
7596
|
-
}
|
|
8339
|
+
const ctx = this.#context;
|
|
8340
|
+
if (pacemCore.Utils.isNull(ctx)) {
|
|
8341
|
+
return;
|
|
7597
8342
|
}
|
|
8343
|
+
// the context (pipelines, buffers) survives: only size-dependent targets get rebuilt
|
|
8344
|
+
this._applySize(this.canvas, size);
|
|
8345
|
+
this._destroyRenderTargets();
|
|
8346
|
+
Raycasters.dispose(ctx);
|
|
8347
|
+
this._ensureAlphaMode(ctx);
|
|
8348
|
+
// interaction
|
|
8349
|
+
if (this.#hasModifiers) {
|
|
8350
|
+
pacemCore.Utils.extend(this.#interaction, { resolution: size });
|
|
8351
|
+
}
|
|
8352
|
+
}
|
|
8353
|
+
/** `transparent` changes come through `resize`, too (see `Pacem3DElement`): reconfigures the canvas only when the alpha mode changes. */
|
|
8354
|
+
_ensureAlphaMode(ctx) {
|
|
8355
|
+
const alphaMode = this._alphaMode();
|
|
8356
|
+
if (alphaMode === this.#alphaMode) {
|
|
8357
|
+
return;
|
|
8358
|
+
}
|
|
8359
|
+
this.#alphaMode = alphaMode;
|
|
8360
|
+
ctx.context.configure({ alphaMode, device: ctx.device, format: ctx.format });
|
|
7598
8361
|
}
|
|
7599
8362
|
get canvas() {
|
|
7600
8363
|
return this.#canvas;
|
|
@@ -7742,9 +8505,16 @@ fn computeOffsetPosition(p0: vec4f, p1: vec4f, index: u32) -> vec4f {
|
|
|
7742
8505
|
if (!scenes.has(scene)) {
|
|
7743
8506
|
scenes.add(scene);
|
|
7744
8507
|
}
|
|
7745
|
-
|
|
8508
|
+
const transparency = this.transparency === 'blend' ? 'blend' : 'a-buffer';
|
|
8509
|
+
const config = { enableValidation: this.enableValidation ?? false, modifiers: this.modifiers, transparency };
|
|
8510
|
+
const creation = Renderers.create(scene, config);
|
|
8511
|
+
return creation
|
|
7746
8512
|
.then(renderer => {
|
|
7747
|
-
|
|
8513
|
+
// a re-initialization supersedes the previous renderer: release its device and GPU resources
|
|
8514
|
+
const previous = set.get(scene);
|
|
8515
|
+
if (previous !== renderer) {
|
|
8516
|
+
previous?.dispose();
|
|
8517
|
+
}
|
|
7748
8518
|
// update dictionary with the actual renderer
|
|
7749
8519
|
set.set(scene, renderer);
|
|
7750
8520
|
// assign datasource immediately
|
|
@@ -7769,6 +8539,7 @@ fn computeOffsetPosition(p0: vec4f, p1: vec4f, index: u32) -> vec4f {
|
|
|
7769
8539
|
switch (name) {
|
|
7770
8540
|
case 'modifiers':
|
|
7771
8541
|
case 'enableValidation':
|
|
8542
|
+
case 'transparency':
|
|
7772
8543
|
// reinitialize
|
|
7773
8544
|
this._reinitialize();
|
|
7774
8545
|
break;
|
|
@@ -7919,6 +8690,9 @@ fn computeOffsetPosition(p0: vec4f, p1: vec4f, index: u32) -> vec4f {
|
|
|
7919
8690
|
__decorate$1([
|
|
7920
8691
|
pacemCore.Watch({ emit: false, converter: pacemCore.PropertyConverters.Boolean })
|
|
7921
8692
|
], Pacem3DWebgpuAdapterElement.prototype, "enableValidation", void 0);
|
|
8693
|
+
__decorate$1([
|
|
8694
|
+
pacemCore.Watch({ emit: false, converter: pacemCore.PropertyConverters.String })
|
|
8695
|
+
], Pacem3DWebgpuAdapterElement.prototype, "transparency", void 0);
|
|
7922
8696
|
Pacem3DWebgpuAdapterElement = __decorate$1([
|
|
7923
8697
|
pacemCore.CustomElement({ tagName: pacemCore.P + '-3d-webgpu-adapter' })
|
|
7924
8698
|
], Pacem3DWebgpuAdapterElement);
|