@es3d/es3d 0.0.0-stage → 1.0.0
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/LICENSE +201 -0
- package/README.md +86 -3
- package/docs/REFERENCE.md +581 -0
- package/docs/SPEC.md +417 -0
- package/package.json +50 -4
- package/scripts/es3d-cli.mjs +377 -0
- package/src/cache/geometry-store.js +392 -0
- package/src/cache/mesh-bundle.js +123 -0
- package/src/cache/sha256.js +73 -0
- package/src/format/ast.js +238 -0
- package/src/format/colors.js +93 -0
- package/src/format/compact-parser.js +171 -0
- package/src/format/compact-tokenizer.js +165 -0
- package/src/format/errors.js +247 -0
- package/src/format/json.js +55 -0
- package/src/format/limits.js +14 -0
- package/src/format/parse.js +92 -0
- package/src/format/schema.js +617 -0
- package/src/format/serializer.js +333 -0
- package/src/format/validator.js +330 -0
- package/src/format/value-error.js +12 -0
- package/src/format/value-format.js +314 -0
- package/src/format/values.js +459 -0
- package/src/format/xml-parser.js +136 -0
- package/src/format/xml-tokenizer.js +237 -0
- package/src/geometry/contour.js +86 -0
- package/src/geometry/extrude.js +175 -0
- package/src/geometry/gear.js +85 -0
- package/src/geometry/geometry-cache.js +159 -0
- package/src/geometry/lod-error.js +178 -0
- package/src/geometry/mesh.js +458 -0
- package/src/geometry/primitives.js +299 -0
- package/src/geometry/registry.js +645 -0
- package/src/geometry/revolve.js +136 -0
- package/src/geometry/sweep.js +441 -0
- package/src/index.js +47 -0
- package/src/io/compression.js +67 -0
- package/src/io/convert.js +236 -0
- package/src/io/download.js +13 -0
- package/src/io/external-scene.js +127 -0
- package/src/io/file-loader.js +28 -0
- package/src/io/gltf.js +630 -0
- package/src/io/mesh-import.js +104 -0
- package/src/io/obj.js +352 -0
- package/src/io/step-brep.js +439 -0
- package/src/io/step-exact.js +1149 -0
- package/src/io/step.js +1418 -0
- package/src/io/stl.js +193 -0
- package/src/io/svg-import.js +787 -0
- package/src/material/materials.js +154 -0
- package/src/math/mat4.js +475 -0
- package/src/math/random.js +30 -0
- package/src/math/trig.js +65 -0
- package/src/math/vec3.js +81 -0
- package/src/optimize/optimizer.js +579 -0
- package/src/path/path-flatten.js +322 -0
- package/src/path/path-parser.js +332 -0
- package/src/path/shapes.js +129 -0
- package/src/path/triangulate.js +517 -0
- package/src/pipeline.js +74 -0
- package/src/render/camera.js +168 -0
- package/src/render/frame-builder.js +362 -0
- package/src/render/geometry-pool.js +149 -0
- package/src/render/lighting.js +149 -0
- package/src/render/orbit-controls.js +237 -0
- package/src/render/renderer.js +249 -0
- package/src/render/scroll-timeline.js +104 -0
- package/src/render/shaders/glsl.js +285 -0
- package/src/render/shaders/wgsl.js +252 -0
- package/src/render/stage.js +352 -0
- package/src/render/texture-cache.js +40 -0
- package/src/render/textures.js +223 -0
- package/src/render/webgl2/webgl2-backend.js +532 -0
- package/src/render/webgpu/webgpu-backend.js +480 -0
- package/src/scene/animation.js +171 -0
- package/src/scene/camera-constraints.js +117 -0
- package/src/scene/flatten.js +754 -0
- package/src/scene/picking.js +161 -0
- package/src/scene/scene-graph.js +320 -0
- package/src/transform/transform.js +211 -0
- package/src/wasm/kernels-binary.js +3 -0
- package/src/wasm/kernels.js +385 -0
|
@@ -0,0 +1,480 @@
|
|
|
1
|
+
// WebGPU rendering backend.
|
|
2
|
+
//
|
|
3
|
+
// Same architecture as the WebGL2 backend: one shared vertex buffer, one
|
|
4
|
+
// shared uint32 index buffer, one instance buffer, explicit bind group
|
|
5
|
+
// layouts and a cache of pipeline variants (shader specialised per material
|
|
6
|
+
// features and light setup, cull mode, winding, blending, topology). Each
|
|
7
|
+
// batch is one drawIndexed call using firstInstance.
|
|
8
|
+
|
|
9
|
+
import { meshShader, LINE_WGSL } from '../shaders/wgsl.js';
|
|
10
|
+
import { FRAME_BYTES, MATERIAL_FLOATS, packMaterial, packOverlay, lightTypes } from '../lighting.js';
|
|
11
|
+
import { VERTEX_BYTES } from '../geometry-pool.js';
|
|
12
|
+
import { buildMips } from '../textures.js';
|
|
13
|
+
|
|
14
|
+
const SAMPLE_COUNT = 4;
|
|
15
|
+
|
|
16
|
+
const VERTEX_LAYOUTS = [
|
|
17
|
+
{
|
|
18
|
+
arrayStride: VERTEX_BYTES,
|
|
19
|
+
stepMode: 'vertex',
|
|
20
|
+
attributes: [
|
|
21
|
+
{ shaderLocation: 0, offset: 0, format: 'float32x3' },
|
|
22
|
+
{ shaderLocation: 1, offset: 12, format: 'float32x3' },
|
|
23
|
+
{ shaderLocation: 2, offset: 24, format: 'float32x2' },
|
|
24
|
+
],
|
|
25
|
+
},
|
|
26
|
+
{
|
|
27
|
+
arrayStride: 64,
|
|
28
|
+
stepMode: 'instance',
|
|
29
|
+
attributes: [
|
|
30
|
+
{ shaderLocation: 3, offset: 0, format: 'float32x4' },
|
|
31
|
+
{ shaderLocation: 4, offset: 16, format: 'float32x4' },
|
|
32
|
+
{ shaderLocation: 5, offset: 32, format: 'float32x4' },
|
|
33
|
+
{ shaderLocation: 6, offset: 48, format: 'float32x4' },
|
|
34
|
+
],
|
|
35
|
+
},
|
|
36
|
+
];
|
|
37
|
+
|
|
38
|
+
const pow2 = (n, min) => {
|
|
39
|
+
let c = min;
|
|
40
|
+
while (c < n) c *= 2;
|
|
41
|
+
return c;
|
|
42
|
+
};
|
|
43
|
+
|
|
44
|
+
export class WebGPUBackend {
|
|
45
|
+
/**
|
|
46
|
+
* @param {HTMLCanvasElement} canvas
|
|
47
|
+
* @param {{present?: 'canvas'|'readback'}} [opts] 'readback' renders offscreen and
|
|
48
|
+
* copies pixels into a 2D canvas (headless testing, screenshots without a swap chain)
|
|
49
|
+
*/
|
|
50
|
+
constructor(canvas, opts = {}) {
|
|
51
|
+
this.canvas = canvas;
|
|
52
|
+
this.present = opts.present || 'canvas';
|
|
53
|
+
this.kind = 'webgpu';
|
|
54
|
+
this.zeroToOne = true;
|
|
55
|
+
this.pipelines = new Map();
|
|
56
|
+
this.meshModules = new Map();
|
|
57
|
+
this.materialBindings = new Map();
|
|
58
|
+
this.overlayBindings = new Map();
|
|
59
|
+
this.poolGeneration = -1;
|
|
60
|
+
this.vertexBuffer = null;
|
|
61
|
+
this.indexBuffer = null;
|
|
62
|
+
this.instanceBuffer = null;
|
|
63
|
+
this.gpuBytes = 0;
|
|
64
|
+
this.lost = false;
|
|
65
|
+
this.info = '';
|
|
66
|
+
this.errors = [];
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
async init() {
|
|
70
|
+
if (!navigator.gpu) throw new Error('WebGPU is not available in this browser.');
|
|
71
|
+
const adapter = await navigator.gpu.requestAdapter({ powerPreference: 'high-performance' });
|
|
72
|
+
if (!adapter) throw new Error('No WebGPU adapter is available.');
|
|
73
|
+
this.adapter = adapter;
|
|
74
|
+
const info = adapter.info || {};
|
|
75
|
+
this.info = [info.vendor, info.architecture, info.description].filter(Boolean).join(' ') || 'WebGPU adapter';
|
|
76
|
+
const device = await adapter.requestDevice();
|
|
77
|
+
this.device = device;
|
|
78
|
+
device.lost.then((i) => {
|
|
79
|
+
this.lost = true;
|
|
80
|
+
this.errors.push(`WebGPU device lost: ${i.message}`);
|
|
81
|
+
});
|
|
82
|
+
device.onuncapturederror = (e) => {
|
|
83
|
+
this.errors.push(e.error && e.error.message ? e.error.message : String(e));
|
|
84
|
+
};
|
|
85
|
+
if (this.present === 'readback') {
|
|
86
|
+
this.format = 'rgba8unorm';
|
|
87
|
+
this.ctx2d = this.canvas.getContext('2d');
|
|
88
|
+
if (!this.ctx2d) throw new Error('Cannot create a 2D context for WebGPU readback presentation.');
|
|
89
|
+
} else {
|
|
90
|
+
const ctx = this.canvas.getContext('webgpu');
|
|
91
|
+
if (!ctx) throw new Error('Cannot create a WebGPU canvas context.');
|
|
92
|
+
this.context = ctx;
|
|
93
|
+
this.format = navigator.gpu.getPreferredCanvasFormat();
|
|
94
|
+
// colours are written already encoded as sRGB and tone mapped to 0..1: pin the
|
|
95
|
+
// colour space and standard range so HDR and wide-gamut screens show them unchanged
|
|
96
|
+
ctx.configure({ device, format: this.format, alphaMode: 'opaque', colorSpace: 'srgb', toneMapping: { mode: 'standard' } });
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
this.frameLayout = device.createBindGroupLayout({
|
|
100
|
+
entries: [{ binding: 0, visibility: GPUShaderStage.VERTEX | GPUShaderStage.FRAGMENT, buffer: { type: 'uniform' } }],
|
|
101
|
+
});
|
|
102
|
+
this.materialLayout = device.createBindGroupLayout({
|
|
103
|
+
entries: [
|
|
104
|
+
{ binding: 0, visibility: GPUShaderStage.VERTEX | GPUShaderStage.FRAGMENT, buffer: { type: 'uniform' } },
|
|
105
|
+
{ binding: 1, visibility: GPUShaderStage.FRAGMENT, sampler: { type: 'filtering' } },
|
|
106
|
+
{ binding: 2, visibility: GPUShaderStage.FRAGMENT, texture: { sampleType: 'float' } },
|
|
107
|
+
{ binding: 3, visibility: GPUShaderStage.FRAGMENT, texture: { sampleType: 'float' } },
|
|
108
|
+
{ binding: 4, visibility: GPUShaderStage.FRAGMENT, texture: { sampleType: 'float' } },
|
|
109
|
+
{ binding: 5, visibility: GPUShaderStage.FRAGMENT, texture: { sampleType: 'float' } },
|
|
110
|
+
{ binding: 6, visibility: GPUShaderStage.FRAGMENT, texture: { sampleType: 'float' } },
|
|
111
|
+
],
|
|
112
|
+
});
|
|
113
|
+
this.pipelineLayout = device.createPipelineLayout({ bindGroupLayouts: [this.frameLayout, this.materialLayout] });
|
|
114
|
+
device.pushErrorScope('validation');
|
|
115
|
+
this.lineModule = device.createShaderModule({ code: LINE_WGSL, label: 'es3d lines' });
|
|
116
|
+
for (const [name, mod] of [['mesh', this.meshModule(0, '0')], ['lines', this.lineModule]]) {
|
|
117
|
+
const info2 = await mod.getCompilationInfo();
|
|
118
|
+
const errs = info2.messages.filter((m) => m.type === 'error');
|
|
119
|
+
if (errs.length) throw new Error(`WGSL ${name} shader error: ${errs.map((m) => `${m.lineNum}:${m.linePos} ${m.message}`).join('; ')}`);
|
|
120
|
+
}
|
|
121
|
+
const err = await device.popErrorScope();
|
|
122
|
+
if (err) throw new Error(`WebGPU initialisation error: ${err.message}`);
|
|
123
|
+
|
|
124
|
+
this.frameBuffer = device.createBuffer({ size: FRAME_BYTES, usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST });
|
|
125
|
+
this.frameBindGroup = device.createBindGroup({ layout: this.frameLayout, entries: [{ binding: 0, resource: { buffer: this.frameBuffer } }] });
|
|
126
|
+
this.sampler = device.createSampler({
|
|
127
|
+
addressModeU: 'repeat',
|
|
128
|
+
addressModeV: 'repeat',
|
|
129
|
+
magFilter: 'linear',
|
|
130
|
+
minFilter: 'linear',
|
|
131
|
+
mipmapFilter: 'linear',
|
|
132
|
+
maxAnisotropy: 8,
|
|
133
|
+
});
|
|
134
|
+
this.whiteTex = this.createTexture({ width: 1, height: 1, data: new Uint8Array([255, 255, 255, 255]) }, true);
|
|
135
|
+
this.flatNormalTex = this.createTexture({ width: 1, height: 1, data: new Uint8Array([128, 128, 255, 255]) }, false);
|
|
136
|
+
this.matData = new Float32Array(MATERIAL_FLOATS);
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
createTexture(px, srgb) {
|
|
140
|
+
const levels = px.width > 1 || px.height > 1 ? buildMips(px) : [px];
|
|
141
|
+
const tex = this.device.createTexture({
|
|
142
|
+
size: [px.width, px.height],
|
|
143
|
+
format: srgb ? 'rgba8unorm-srgb' : 'rgba8unorm',
|
|
144
|
+
mipLevelCount: levels.length,
|
|
145
|
+
usage: GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_DST,
|
|
146
|
+
});
|
|
147
|
+
levels.forEach((lv, i) => {
|
|
148
|
+
const data = lv.data instanceof Uint8Array ? lv.data : new Uint8Array(lv.data.buffer, lv.data.byteOffset, lv.data.byteLength);
|
|
149
|
+
this.device.queue.writeTexture({ texture: tex, mipLevel: i }, data, { bytesPerRow: lv.width * 4, rowsPerImage: lv.height }, [lv.width, lv.height]);
|
|
150
|
+
this.gpuBytes += lv.width * lv.height * 4;
|
|
151
|
+
});
|
|
152
|
+
return { texture: tex, view: tex.createView() };
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
destroyTexture(t) {
|
|
156
|
+
t.texture.destroy();
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/** The shader module for a material's feature flags under the frame's lights, compiled on first use. */
|
|
160
|
+
meshModule(flags, lights) {
|
|
161
|
+
const key = `${flags}|${lights}`;
|
|
162
|
+
let m = this.meshModules.get(key);
|
|
163
|
+
if (!m) {
|
|
164
|
+
m = this.device.createShaderModule({ code: meshShader(flags, lights), label: `es3d mesh ${key}` });
|
|
165
|
+
this.meshModules.set(key, m);
|
|
166
|
+
}
|
|
167
|
+
return m;
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
pipeline(kind, { cull = 'back', frontFace = 'ccw', blend = false, depthWrite = true, depthCompare = 'less-equal', flags = 0, lights = '' } = {}) {
|
|
171
|
+
const isMesh = kind === 'mesh';
|
|
172
|
+
const key = `${kind}|${cull}|${frontFace}|${blend}|${depthWrite}|${depthCompare}${isMesh ? `|${flags}|${lights}` : ''}`;
|
|
173
|
+
let p = this.pipelines.get(key);
|
|
174
|
+
if (p) return p;
|
|
175
|
+
const module = isMesh ? this.meshModule(flags, lights) : this.lineModule;
|
|
176
|
+
const entry = isMesh ? 'vs_main' : kind === 'normals' ? 'vs_normals' : 'vs_line';
|
|
177
|
+
p = this.device.createRenderPipeline({
|
|
178
|
+
label: key,
|
|
179
|
+
layout: this.pipelineLayout,
|
|
180
|
+
vertex: { module, entryPoint: entry, buffers: VERTEX_LAYOUTS },
|
|
181
|
+
fragment: {
|
|
182
|
+
module,
|
|
183
|
+
entryPoint: isMesh ? 'fs_main' : 'fs_line',
|
|
184
|
+
targets: [
|
|
185
|
+
{
|
|
186
|
+
format: this.format,
|
|
187
|
+
blend: blend
|
|
188
|
+
? {
|
|
189
|
+
color: { srcFactor: 'src-alpha', dstFactor: 'one-minus-src-alpha', operation: 'add' },
|
|
190
|
+
alpha: { srcFactor: 'one', dstFactor: 'one-minus-src-alpha', operation: 'add' },
|
|
191
|
+
}
|
|
192
|
+
: undefined,
|
|
193
|
+
},
|
|
194
|
+
],
|
|
195
|
+
},
|
|
196
|
+
primitive: { topology: isMesh ? 'triangle-list' : 'line-list', cullMode: isMesh ? cull : 'none', frontFace },
|
|
197
|
+
depthStencil: { format: 'depth24plus', depthWriteEnabled: depthWrite, depthCompare },
|
|
198
|
+
multisample: { count: SAMPLE_COUNT },
|
|
199
|
+
});
|
|
200
|
+
this.pipelines.set(key, p);
|
|
201
|
+
return p;
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
ensureTargets() {
|
|
205
|
+
const w = this.canvas.width, h = this.canvas.height;
|
|
206
|
+
if (this.targetW === w && this.targetH === h && this.msaa) return;
|
|
207
|
+
if (this.msaa) this.msaa.destroy();
|
|
208
|
+
if (this.depth) this.depth.destroy();
|
|
209
|
+
this.msaa = this.device.createTexture({ size: [w, h], sampleCount: SAMPLE_COUNT, format: this.format, usage: GPUTextureUsage.RENDER_ATTACHMENT });
|
|
210
|
+
this.depth = this.device.createTexture({ size: [w, h], sampleCount: SAMPLE_COUNT, format: 'depth24plus', usage: GPUTextureUsage.RENDER_ATTACHMENT });
|
|
211
|
+
this.msaaView = this.msaa.createView();
|
|
212
|
+
this.depthView = this.depth.createView();
|
|
213
|
+
if (this.present === 'readback') {
|
|
214
|
+
if (this.offscreen) this.offscreen.destroy();
|
|
215
|
+
if (this.readBuffer && !this.readPending) this.readBuffer.destroy();
|
|
216
|
+
this.offscreen = this.device.createTexture({ size: [w, h], format: this.format, usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC });
|
|
217
|
+
this.offscreenView = this.offscreen.createView();
|
|
218
|
+
this.readStride = Math.ceil((w * 4) / 256) * 256;
|
|
219
|
+
this.readBuffer = this.device.createBuffer({ size: this.readStride * h, usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ });
|
|
220
|
+
}
|
|
221
|
+
this.targetW = w;
|
|
222
|
+
this.targetH = h;
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
/** Copy the offscreen frame into the 2D canvas (readback presentation). */
|
|
226
|
+
readback(encoder) {
|
|
227
|
+
if (this.readPending) return false;
|
|
228
|
+
const w = this.targetW, h = this.targetH;
|
|
229
|
+
encoder.copyTextureToBuffer({ texture: this.offscreen }, { buffer: this.readBuffer, bytesPerRow: this.readStride }, [w, h]);
|
|
230
|
+
return true;
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
startReadback() {
|
|
234
|
+
const buf = this.readBuffer;
|
|
235
|
+
const w = this.targetW, h = this.targetH, stride = this.readStride;
|
|
236
|
+
this.readPending = buf.mapAsync(GPUMapMode.READ).then(() => {
|
|
237
|
+
const raw = new Uint8Array(buf.getMappedRange());
|
|
238
|
+
const px = new Uint8ClampedArray(w * h * 4);
|
|
239
|
+
for (let y = 0; y < h; y++) px.set(raw.subarray(y * stride, y * stride + w * 4), y * w * 4);
|
|
240
|
+
buf.unmap();
|
|
241
|
+
this.ctx2d.putImageData(new ImageData(px, w, h), 0, 0);
|
|
242
|
+
this.readPending = null;
|
|
243
|
+
// A frame drawn while this copy was in flight was not copied. A page that
|
|
244
|
+
// draws only on change may draw nothing more, so show that frame now.
|
|
245
|
+
if (!this.lastFrameCopied && this.offscreen && !this.lost) {
|
|
246
|
+
const encoder = this.device.createCommandEncoder();
|
|
247
|
+
this.readback(encoder);
|
|
248
|
+
this.device.queue.submit([encoder.finish()]);
|
|
249
|
+
this.lastFrameCopied = true;
|
|
250
|
+
this.startReadback();
|
|
251
|
+
}
|
|
252
|
+
});
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
syncPool(pool) {
|
|
256
|
+
const d = this.device;
|
|
257
|
+
const vBytes = pool.vertices.byteLength;
|
|
258
|
+
const iBytes = pool.indices.byteLength;
|
|
259
|
+
let uploaded = 0;
|
|
260
|
+
if (pool.generation !== this.poolGeneration || !this.vertexBuffer || this.vertexBuffer.size < vBytes || this.indexBuffer.size < iBytes) {
|
|
261
|
+
if (this.vertexBuffer) this.vertexBuffer.destroy();
|
|
262
|
+
if (this.indexBuffer) this.indexBuffer.destroy();
|
|
263
|
+
this.vertexBuffer = d.createBuffer({ size: pow2(vBytes, 1 << 16), usage: GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_DST });
|
|
264
|
+
this.indexBuffer = d.createBuffer({ size: pow2(iBytes, 1 << 16), usage: GPUBufferUsage.INDEX | GPUBufferUsage.COPY_DST });
|
|
265
|
+
this.poolGeneration = pool.generation;
|
|
266
|
+
pool.uploadedVertices = 0;
|
|
267
|
+
pool.uploadedIndices = 0;
|
|
268
|
+
}
|
|
269
|
+
const p = pool.pending();
|
|
270
|
+
if (p.vertexEnd > p.vertexStart) {
|
|
271
|
+
const src = pool.vertices.subarray(p.vertexStart * 8, p.vertexEnd * 8);
|
|
272
|
+
d.queue.writeBuffer(this.vertexBuffer, p.vertexStart * VERTEX_BYTES, src.buffer, src.byteOffset, src.byteLength);
|
|
273
|
+
uploaded += src.byteLength;
|
|
274
|
+
}
|
|
275
|
+
if (p.indexEnd > p.indexStart) {
|
|
276
|
+
const src = pool.indices.subarray(p.indexStart, p.indexEnd);
|
|
277
|
+
d.queue.writeBuffer(this.indexBuffer, p.indexStart * 4, src.buffer, src.byteOffset, src.byteLength);
|
|
278
|
+
uploaded += src.byteLength;
|
|
279
|
+
}
|
|
280
|
+
pool.markUploaded();
|
|
281
|
+
return uploaded;
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
uploadInstances(data, count) {
|
|
285
|
+
const bytes = Math.max(64, count * 64);
|
|
286
|
+
if (!this.instanceBuffer || this.instanceBuffer.size < bytes) {
|
|
287
|
+
if (this.instanceBuffer) this.instanceBuffer.destroy();
|
|
288
|
+
this.instanceBuffer = this.device.createBuffer({ size: pow2(bytes, 64 * 256), usage: GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_DST });
|
|
289
|
+
}
|
|
290
|
+
if (count) this.device.queue.writeBuffer(this.instanceBuffer, 0, data.buffer, data.byteOffset, count * 64);
|
|
291
|
+
return count * 64;
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
readyTexture(entry, srgb) {
|
|
295
|
+
if (entry && entry.status === 'ready' && !entry.gpu) entry.gpu = this.createTexture(entry.pixels, srgb);
|
|
296
|
+
return entry && entry.gpu ? entry.gpu : null;
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
materialEntries(buffer, map, normal, mr, occlusion, emissive) {
|
|
300
|
+
return [
|
|
301
|
+
{ binding: 0, resource: { buffer } },
|
|
302
|
+
{ binding: 1, resource: this.sampler },
|
|
303
|
+
{ binding: 2, resource: map.view },
|
|
304
|
+
{ binding: 3, resource: normal.view },
|
|
305
|
+
{ binding: 4, resource: mr.view },
|
|
306
|
+
{ binding: 5, resource: occlusion.view },
|
|
307
|
+
{ binding: 6, resource: emissive.view },
|
|
308
|
+
];
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
materialBinding(material, textures, doubleSided) {
|
|
312
|
+
const id = doubleSided ? 'ds' : 'ss';
|
|
313
|
+
let rec = this.materialBindings.get(material);
|
|
314
|
+
if (!rec) {
|
|
315
|
+
rec = {};
|
|
316
|
+
this.materialBindings.set(material, rec);
|
|
317
|
+
}
|
|
318
|
+
const mapGpu = this.readyTexture(material.map ? textures.get(material.map, 'color') : null, true);
|
|
319
|
+
const nrmGpu = this.readyTexture(material.normalMap ? textures.get(material.normalMap, 'normal') : null, false);
|
|
320
|
+
const mrGpu = this.readyTexture(material.metallicRoughnessMap ? textures.get(material.metallicRoughnessMap, 'linear') : null, false);
|
|
321
|
+
const occGpu = this.readyTexture(material.occlusionMap ? textures.get(material.occlusionMap, 'linear') : null, false);
|
|
322
|
+
const emGpu = this.readyTexture(material.emissiveMap ? textures.get(material.emissiveMap, 'color') : null, true);
|
|
323
|
+
const hasMap = !!mapGpu;
|
|
324
|
+
const hasNormalMap = !!nrmGpu;
|
|
325
|
+
const hasMrMap = !!mrGpu;
|
|
326
|
+
const hasOcclusionMap = !!occGpu;
|
|
327
|
+
const hasEmissiveMap = !!emGpu;
|
|
328
|
+
const key = `${hasMap}|${hasNormalMap}|${hasMrMap}|${hasOcclusionMap}|${hasEmissiveMap}`;
|
|
329
|
+
let b = rec[id];
|
|
330
|
+
if (!b || b.key !== key) {
|
|
331
|
+
if (b) b.buffer.destroy();
|
|
332
|
+
packMaterial(this.matData, material, { hasMap, hasNormalMap, hasMrMap, hasOcclusionMap, hasEmissiveMap, doubleSided: doubleSided || material.doubleSided });
|
|
333
|
+
const buffer = this.device.createBuffer({ size: MATERIAL_FLOATS * 4, usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST });
|
|
334
|
+
this.device.queue.writeBuffer(buffer, 0, this.matData);
|
|
335
|
+
const bindGroup = this.device.createBindGroup({
|
|
336
|
+
layout: this.materialLayout,
|
|
337
|
+
entries: this.materialEntries(buffer, mapGpu || this.whiteTex, nrmGpu || this.flatNormalTex, mrGpu || this.whiteTex, occGpu || this.whiteTex, emGpu || this.whiteTex),
|
|
338
|
+
});
|
|
339
|
+
b = rec[id] = { key, buffer, bindGroup, flags: this.matData[10] };
|
|
340
|
+
}
|
|
341
|
+
return b;
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
overlayBinding(name, rgba) {
|
|
345
|
+
let b = this.overlayBindings.get(name);
|
|
346
|
+
if (b) return b;
|
|
347
|
+
packOverlay(this.matData, rgba);
|
|
348
|
+
const buffer = this.device.createBuffer({ size: MATERIAL_FLOATS * 4, usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST });
|
|
349
|
+
this.device.queue.writeBuffer(buffer, 0, this.matData);
|
|
350
|
+
b = this.device.createBindGroup({
|
|
351
|
+
layout: this.materialLayout,
|
|
352
|
+
entries: this.materialEntries(buffer, this.whiteTex, this.flatNormalTex, this.whiteTex, this.whiteTex, this.whiteTex),
|
|
353
|
+
});
|
|
354
|
+
this.overlayBindings.set(name, b);
|
|
355
|
+
return b;
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
releaseMaterials(keep) {
|
|
359
|
+
for (const [m, rec] of this.materialBindings) {
|
|
360
|
+
if (keep.has(m)) continue;
|
|
361
|
+
for (const b of Object.values(rec)) b.buffer.destroy();
|
|
362
|
+
this.materialBindings.delete(m);
|
|
363
|
+
}
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
/** What this backend renders with (Renderer.caps). */
|
|
367
|
+
get caps() {
|
|
368
|
+
return {
|
|
369
|
+
msaaSamples: SAMPLE_COUNT,
|
|
370
|
+
anisotropy: 8,
|
|
371
|
+
maxTextureSize: this.device ? this.device.limits.maxTextureDimension2D : 0,
|
|
372
|
+
colorSpace: 'srgb',
|
|
373
|
+
};
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
resize(width, height) {
|
|
377
|
+
if (this.canvas.width !== width || this.canvas.height !== height) {
|
|
378
|
+
this.canvas.width = width;
|
|
379
|
+
this.canvas.height = height;
|
|
380
|
+
}
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
render(draw, frameData, ctx) {
|
|
384
|
+
if (this.lost) return;
|
|
385
|
+
const d = this.device;
|
|
386
|
+
this.ensureTargets();
|
|
387
|
+
d.queue.writeBuffer(this.frameBuffer, 0, frameData.buffer, frameData.byteOffset, frameData.byteLength);
|
|
388
|
+
this.uploadInstances(draw.instanceData, draw.instanceCount);
|
|
389
|
+
const encoder = d.createCommandEncoder();
|
|
390
|
+
const pass = encoder.beginRenderPass({
|
|
391
|
+
colorAttachments: [
|
|
392
|
+
{
|
|
393
|
+
view: this.msaaView,
|
|
394
|
+
resolveTarget: this.present === 'readback' ? this.offscreenView : this.context.getCurrentTexture().createView(),
|
|
395
|
+
clearValue: { r: ctx.background[0], g: ctx.background[1], b: ctx.background[2], a: 1 },
|
|
396
|
+
loadOp: 'clear',
|
|
397
|
+
storeOp: 'discard',
|
|
398
|
+
},
|
|
399
|
+
],
|
|
400
|
+
depthStencilAttachment: { view: this.depthView, depthClearValue: 1, depthLoadOp: 'clear', depthStoreOp: 'discard' },
|
|
401
|
+
});
|
|
402
|
+
pass.setBindGroup(0, this.frameBindGroup);
|
|
403
|
+
if (this.vertexBuffer) {
|
|
404
|
+
pass.setVertexBuffer(0, this.vertexBuffer);
|
|
405
|
+
pass.setIndexBuffer(this.indexBuffer, 'uint32');
|
|
406
|
+
}
|
|
407
|
+
pass.setVertexBuffer(1, this.instanceBuffer);
|
|
408
|
+
let currentPipeline = null;
|
|
409
|
+
const setPipe = (p) => {
|
|
410
|
+
if (p !== currentPipeline) {
|
|
411
|
+
pass.setPipeline(p);
|
|
412
|
+
currentPipeline = p;
|
|
413
|
+
}
|
|
414
|
+
};
|
|
415
|
+
if (this.vertexBuffer) {
|
|
416
|
+
let boundGroup = null;
|
|
417
|
+
const lights = lightTypes(frameData);
|
|
418
|
+
for (const b of draw.batches) {
|
|
419
|
+
const lines = b.kind === 'lines';
|
|
420
|
+
const binding = this.materialBinding(b.material, ctx.textures, b.doubleSided && !b.material.doubleSided);
|
|
421
|
+
const pipe = lines
|
|
422
|
+
? this.pipeline('lines', { blend: b.transparent, depthWrite: !b.transparent })
|
|
423
|
+
: this.pipeline('mesh', {
|
|
424
|
+
cull: b.doubleSided ? 'none' : 'back',
|
|
425
|
+
frontFace: b.mirrored ? 'cw' : 'ccw',
|
|
426
|
+
blend: b.transparent,
|
|
427
|
+
depthWrite: !b.transparent,
|
|
428
|
+
flags: binding.flags,
|
|
429
|
+
lights,
|
|
430
|
+
});
|
|
431
|
+
setPipe(pipe);
|
|
432
|
+
const group = binding.bindGroup;
|
|
433
|
+
if (group !== boundGroup) {
|
|
434
|
+
pass.setBindGroup(1, group);
|
|
435
|
+
boundGroup = group;
|
|
436
|
+
}
|
|
437
|
+
pass.drawIndexed(b.range.indexCount, b.count, b.range.firstIndex, 0, b.firstInstance);
|
|
438
|
+
}
|
|
439
|
+
const ov = draw.overlays;
|
|
440
|
+
const drawLines = (kind, name, color, list, depthCompare = 'less-equal') => {
|
|
441
|
+
if (!list.length) return;
|
|
442
|
+
setPipe(this.pipeline(kind, { blend: true, depthWrite: false, depthCompare }));
|
|
443
|
+
pass.setBindGroup(1, this.overlayBinding(name, color));
|
|
444
|
+
for (const o of list) pass.drawIndexed(o.range.indexCount, o.count, o.range.firstIndex, 0, o.firstInstance);
|
|
445
|
+
};
|
|
446
|
+
drawLines('lines', 'wireframe', ctx.overlayColors.wireframe, ov.wireframe);
|
|
447
|
+
drawLines('normals', 'normals', ctx.overlayColors.normals, ov.normals);
|
|
448
|
+
if (ov.bbox && ov.bbox.count) drawLines('lines', 'bbox', ctx.overlayColors.bbox, [{ ...ov.bbox, range: ctx.cubeRange }]);
|
|
449
|
+
if (ov.selection && ov.selection.count) drawLines('lines', 'selection', ctx.overlayColors.selection, [{ ...ov.selection, range: ctx.cubeRange }], 'always');
|
|
450
|
+
}
|
|
451
|
+
pass.end();
|
|
452
|
+
const copied = this.present === 'readback' && this.readback(encoder);
|
|
453
|
+
d.queue.submit([encoder.finish()]);
|
|
454
|
+
if (copied) this.startReadback();
|
|
455
|
+
this.lastFrameCopied = copied;
|
|
456
|
+
}
|
|
457
|
+
|
|
458
|
+
async finish() {
|
|
459
|
+
await this.device.queue.onSubmittedWorkDone();
|
|
460
|
+
if (this.readPending) await this.readPending;
|
|
461
|
+
if (this.present === 'readback' && !this.lastFrameCopied && this.offscreen) {
|
|
462
|
+
// the latest frame was rendered while an older readback was in flight
|
|
463
|
+
const encoder = this.device.createCommandEncoder();
|
|
464
|
+
this.readback(encoder);
|
|
465
|
+
this.device.queue.submit([encoder.finish()]);
|
|
466
|
+
this.startReadback();
|
|
467
|
+
await this.readPending;
|
|
468
|
+
this.lastFrameCopied = true;
|
|
469
|
+
}
|
|
470
|
+
}
|
|
471
|
+
|
|
472
|
+
dispose() {
|
|
473
|
+
if (!this.device) return;
|
|
474
|
+
for (const b of [this.vertexBuffer, this.indexBuffer, this.instanceBuffer, this.frameBuffer]) if (b) b.destroy();
|
|
475
|
+
for (const rec of this.materialBindings.values()) for (const b of Object.values(rec)) b.buffer.destroy();
|
|
476
|
+
if (this.msaa) this.msaa.destroy();
|
|
477
|
+
if (this.depth) this.depth.destroy();
|
|
478
|
+
this.device.destroy();
|
|
479
|
+
}
|
|
480
|
+
}
|
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
// Animation of a transform (and of a camera's target and fov).
|
|
2
|
+
//
|
|
3
|
+
// An animation has a timeline and a value source.
|
|
4
|
+
//
|
|
5
|
+
// Timeline. "time" (the default): nothing happens before `begin`; then the
|
|
6
|
+
// animation plays `repeat` cycles of length `dur` (optionally reversing
|
|
7
|
+
// direction) and holds the end value. "scroll": progress is the page scroll
|
|
8
|
+
// position mapped to 0..1 by the viewer, and dur/begin/repeat are not used.
|
|
9
|
+
// Either way the result is a fraction f in 0..1, shaped by `easing`.
|
|
10
|
+
//
|
|
11
|
+
// Value source. from/to: a straight interpolation. values (+ keyTimes): key
|
|
12
|
+
// values reached at the given fractions, linear or on a centripetal
|
|
13
|
+
// Catmull-Rom curve (smooth). along: a 3D path walked at constant speed, so
|
|
14
|
+
// equal scroll moves the camera an equal distance. This is not SMIL. It is the
|
|
15
|
+
// whole animation model.
|
|
16
|
+
|
|
17
|
+
import { valueOf } from '../format/schema.js';
|
|
18
|
+
import { spinePolylines } from '../geometry/sweep.js';
|
|
19
|
+
|
|
20
|
+
const EASINGS = {
|
|
21
|
+
linear: (t) => t,
|
|
22
|
+
'ease-in': (t) => t * t,
|
|
23
|
+
'ease-out': (t) => 1 - (1 - t) * (1 - t),
|
|
24
|
+
'ease-in-out': (t) => (t < 0.5 ? 2 * t * t : 1 - 2 * (1 - t) * (1 - t)),
|
|
25
|
+
};
|
|
26
|
+
|
|
27
|
+
const clamp01 = (x) => (x < 0 ? 0 : x > 1 ? 1 : x);
|
|
28
|
+
|
|
29
|
+
export function animationFromElement(el, base) {
|
|
30
|
+
const attr = valueOf(el, 'attr');
|
|
31
|
+
const expand = (v) => (attr === 'scale' && v.length === 1 ? [v[0], v[0], v[0]] : v.slice());
|
|
32
|
+
const v = el.values;
|
|
33
|
+
const a = {
|
|
34
|
+
attr,
|
|
35
|
+
dur: valueOf(el, 'dur') || 1,
|
|
36
|
+
begin: valueOf(el, 'begin'),
|
|
37
|
+
repeat: valueOf(el, 'repeat'),
|
|
38
|
+
alternate: valueOf(el, 'alternate'),
|
|
39
|
+
ease: EASINGS[valueOf(el, 'easing')] || EASINGS.linear,
|
|
40
|
+
timeline: valueOf(el, 'timeline'),
|
|
41
|
+
smooth: valueOf(el, 'smooth'),
|
|
42
|
+
from: null,
|
|
43
|
+
to: null,
|
|
44
|
+
keys: null,
|
|
45
|
+
keyTimes: null,
|
|
46
|
+
path: null,
|
|
47
|
+
};
|
|
48
|
+
if (v.along) {
|
|
49
|
+
a.path = arcLengthPath(v.along, a.smooth);
|
|
50
|
+
} else if (v.values) {
|
|
51
|
+
a.keys = v.values.map(expand);
|
|
52
|
+
const n = a.keys.length;
|
|
53
|
+
a.keyTimes = v.keyTimes && v.keyTimes.length === n ? v.keyTimes.slice() : a.keys.map((_, i) => i / (n - 1));
|
|
54
|
+
} else {
|
|
55
|
+
a.from = v.from !== undefined ? expand(v.from) : base[attr];
|
|
56
|
+
a.to = expand(v.to);
|
|
57
|
+
}
|
|
58
|
+
return a;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** Fraction 0..1 of an animation at a time and scroll progress, or -1 when it has no effect yet. */
|
|
62
|
+
export function animationFraction(a, t, progress = 0) {
|
|
63
|
+
if (a.timeline === 'scroll') return a.ease(clamp01(progress));
|
|
64
|
+
const elapsed = t - a.begin;
|
|
65
|
+
if (elapsed < 0) return -1;
|
|
66
|
+
const cycles = elapsed / a.dur;
|
|
67
|
+
let f;
|
|
68
|
+
if (cycles >= a.repeat) {
|
|
69
|
+
const whole = Math.ceil(a.repeat) - 1;
|
|
70
|
+
f = a.repeat - whole;
|
|
71
|
+
if (a.alternate && whole % 2 === 1) f = 1 - f;
|
|
72
|
+
} else {
|
|
73
|
+
const k = Math.floor(cycles);
|
|
74
|
+
f = cycles - k;
|
|
75
|
+
if (a.alternate && k % 2 === 1) f = 1 - f;
|
|
76
|
+
}
|
|
77
|
+
return a.ease(f);
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** Value of an animation at time t (seconds) and scroll progress, or null when it has no effect yet. */
|
|
81
|
+
export function sampleAnimation(a, t, progress = 0) {
|
|
82
|
+
const e = animationFraction(a, t, progress);
|
|
83
|
+
if (e < 0) return null;
|
|
84
|
+
if (a.path) return samplePath(a.path, e);
|
|
85
|
+
if (a.keys) return sampleKeys(a, e);
|
|
86
|
+
const out = new Array(a.from.length);
|
|
87
|
+
for (let k = 0; k < out.length; k++) out[k] = a.from[k] + (a.to[k] - a.from[k]) * e;
|
|
88
|
+
return out;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
// ---------------------------------------------------------------------------
|
|
92
|
+
// key values
|
|
93
|
+
|
|
94
|
+
function sampleKeys(a, e) {
|
|
95
|
+
const keys = a.keys;
|
|
96
|
+
const kt = a.keyTimes;
|
|
97
|
+
const n = keys.length;
|
|
98
|
+
let i = 0;
|
|
99
|
+
while (i < n - 2 && e >= kt[i + 1]) i++;
|
|
100
|
+
const span = kt[i + 1] - kt[i];
|
|
101
|
+
const u = span > 0 ? clamp01((e - kt[i]) / span) : 1;
|
|
102
|
+
const p1 = keys[i], p2 = keys[i + 1];
|
|
103
|
+
if (!a.smooth || n < 3) return p1.map((x, k) => x + (p2[k] - x) * u);
|
|
104
|
+
// end tangents mirror the neighbouring key, as for sweep spines
|
|
105
|
+
const p0 = i > 0 ? keys[i - 1] : p1.map((x, k) => 2 * x - p2[k]);
|
|
106
|
+
const p3 = i + 2 < n ? keys[i + 2] : p2.map((x, k) => 2 * x - p1[k]);
|
|
107
|
+
return centripetal(p0, p1, p2, p3, u);
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/** Point at u (0..1) between p1 and p2 on the centripetal Catmull-Rom curve (Barry-Goldman). */
|
|
111
|
+
function centripetal(p0, p1, p2, p3, u) {
|
|
112
|
+
const knot = (a, b) => {
|
|
113
|
+
let d = 0;
|
|
114
|
+
for (let k = 0; k < a.length; k++) d += (b[k] - a[k]) ** 2;
|
|
115
|
+
return Math.max(Math.sqrt(Math.sqrt(d)), 1e-9);
|
|
116
|
+
};
|
|
117
|
+
const t0 = 0;
|
|
118
|
+
const t1 = t0 + knot(p0, p1);
|
|
119
|
+
const t2 = t1 + knot(p1, p2);
|
|
120
|
+
const t3 = t2 + knot(p2, p3);
|
|
121
|
+
const t = t1 + (t2 - t1) * u;
|
|
122
|
+
const lerp = (a, b, ta, tb) => a.map((x, k) => x + ((b[k] - x) * (t - ta)) / (tb - ta));
|
|
123
|
+
const A1 = lerp(p0, p1, t0, t1), A2 = lerp(p1, p2, t1, t2), A3 = lerp(p2, p3, t2, t3);
|
|
124
|
+
const B1 = lerp(A1, A2, t0, t2), B2 = lerp(A2, A3, t1, t3);
|
|
125
|
+
return lerp(B1, B2, t1, t2);
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
// ---------------------------------------------------------------------------
|
|
129
|
+
// paths
|
|
130
|
+
|
|
131
|
+
/** Flatten an `along` value into one polyline with cumulative arc lengths. */
|
|
132
|
+
export function arcLengthPath(spine, smooth) {
|
|
133
|
+
const opts = (tolerance) => ({ tolerance, segmentsPerTurn: 64, smooth, subdivisions: 24 });
|
|
134
|
+
// path data needs a tolerance relative to its size: measure it coarsely first
|
|
135
|
+
let lines = spinePolylines(spine, opts(1e-2));
|
|
136
|
+
if (spine.kind === 'path') {
|
|
137
|
+
let ext = 0;
|
|
138
|
+
for (const l of lines) for (let i = 0; i < l.points.length; i++) ext = Math.max(ext, Math.abs(l.points[i]));
|
|
139
|
+
lines = spinePolylines(spine, opts(Math.max(ext, 1e-6) * 1e-4));
|
|
140
|
+
}
|
|
141
|
+
const pts = [];
|
|
142
|
+
for (const l of lines) {
|
|
143
|
+
for (let i = 0; i < l.points.length; i++) pts.push(l.points[i]);
|
|
144
|
+
if (l.closed && l.points.length >= 3) pts.push(l.points[0], l.points[1], l.points[2]);
|
|
145
|
+
}
|
|
146
|
+
const n = pts.length / 3;
|
|
147
|
+
const lengths = new Float64Array(Math.max(n, 1));
|
|
148
|
+
for (let i = 1; i < n; i++) {
|
|
149
|
+
lengths[i] = lengths[i - 1] + Math.hypot(pts[i * 3] - pts[i * 3 - 3], pts[i * 3 + 1] - pts[i * 3 - 2], pts[i * 3 + 2] - pts[i * 3 - 1]);
|
|
150
|
+
}
|
|
151
|
+
return { points: Float64Array.from(pts), lengths, total: n ? lengths[n - 1] : 0 };
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/** Point at fraction e of a path's length. */
|
|
155
|
+
export function samplePath(path, e) {
|
|
156
|
+
const P = path.points;
|
|
157
|
+
const L = path.lengths;
|
|
158
|
+
const n = P.length / 3;
|
|
159
|
+
if (n === 0) return [0, 0, 0];
|
|
160
|
+
if (n === 1 || path.total <= 0) return [P[0], P[1], P[2]];
|
|
161
|
+
const s = clamp01(e) * path.total;
|
|
162
|
+
let lo = 0, hi = n - 1;
|
|
163
|
+
while (hi - lo > 1) {
|
|
164
|
+
const mid = (lo + hi) >> 1;
|
|
165
|
+
if (L[mid] <= s) lo = mid;
|
|
166
|
+
else hi = mid;
|
|
167
|
+
}
|
|
168
|
+
const seg = L[hi] - L[lo];
|
|
169
|
+
const u = seg > 0 ? (s - L[lo]) / seg : 0;
|
|
170
|
+
return [P[lo * 3] + (P[hi * 3] - P[lo * 3]) * u, P[lo * 3 + 1] + (P[hi * 3 + 1] - P[lo * 3 + 1]) * u, P[lo * 3 + 2] + (P[hi * 3 + 2] - P[lo * 3 + 2]) * u];
|
|
171
|
+
}
|