@plasius/gpu-renderer 0.1.12 → 0.1.14
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/CHANGELOG.md +68 -0
- package/README.md +118 -3
- package/dist/index.cjs +3447 -4
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +3421 -3
- package/dist/index.js.map +1 -1
- package/package.json +2 -3
- package/src/index.d.ts +582 -0
- package/src/index.js +213 -0
- package/src/wavefront-compute.js +3460 -0
package/dist/index.js
CHANGED
|
@@ -1,3 +1,3221 @@
|
|
|
1
|
+
// src/wavefront-compute.js
|
|
2
|
+
var DEFAULT_WIDTH = 1280;
|
|
3
|
+
var DEFAULT_HEIGHT = 720;
|
|
4
|
+
var DEFAULT_MAX_DEPTH = 6;
|
|
5
|
+
var DEFAULT_TILE_SIZE = 128;
|
|
6
|
+
var DEFAULT_SAMPLES_PER_PIXEL = 1;
|
|
7
|
+
var DEFAULT_SCENE_OBJECT_CAPACITY = 128;
|
|
8
|
+
var WORKGROUP_SIZE = 64;
|
|
9
|
+
var RAY_RECORD_BYTES = 80;
|
|
10
|
+
var HIT_RECORD_BYTES = 208;
|
|
11
|
+
var SCENE_OBJECT_RECORD_BYTES = 96;
|
|
12
|
+
var MESH_VERTEX_RECORD_BYTES = 48;
|
|
13
|
+
var MESH_RANGE_RECORD_BYTES = 96;
|
|
14
|
+
var TRIANGLE_RECORD_BYTES = 208;
|
|
15
|
+
var BVH_NODE_RECORD_BYTES = 48;
|
|
16
|
+
var BVH_LEAF_REF_RECORD_BYTES = 16;
|
|
17
|
+
var EMISSIVE_TRIANGLE_INDEX_BYTES = 4;
|
|
18
|
+
var ACCUMULATION_RECORD_BYTES = 16;
|
|
19
|
+
var CONFIG_BUFFER_BYTES = 256;
|
|
20
|
+
var COUNTER_BUFFER_BYTES = 16;
|
|
21
|
+
var MATERIAL_DIFFUSE = 0;
|
|
22
|
+
var MATERIAL_METAL = 1;
|
|
23
|
+
var MATERIAL_DIELECTRIC = 2;
|
|
24
|
+
var MATERIAL_TRANSPARENT = 3;
|
|
25
|
+
var MATERIAL_EMISSIVE = 4;
|
|
26
|
+
var OBJECT_KIND_SPHERE = 1;
|
|
27
|
+
var OBJECT_KIND_BOX = 2;
|
|
28
|
+
var DEFAULT_CAMERA = Object.freeze({
|
|
29
|
+
position: Object.freeze([0, 1.15, 5.6]),
|
|
30
|
+
target: Object.freeze([0, 0.65, 0]),
|
|
31
|
+
up: Object.freeze([0, 1, 0]),
|
|
32
|
+
fovYDegrees: 46
|
|
33
|
+
});
|
|
34
|
+
var DEFAULT_ENVIRONMENT_COLOR = Object.freeze([0.35, 0.43, 0.49, 1]);
|
|
35
|
+
var DEFAULT_AMBIENT_COLOR = Object.freeze([0.018, 0.022, 0.026, 1]);
|
|
36
|
+
var DEFAULT_ENVIRONMENT_LIGHTING = Object.freeze({
|
|
37
|
+
horizonColor: Object.freeze([0.46, 0.56, 0.68, 1]),
|
|
38
|
+
zenithColor: Object.freeze([0.04, 0.08, 0.16, 1]),
|
|
39
|
+
sunDirection: Object.freeze([0.22, 0.88, 0.42]),
|
|
40
|
+
sunColor: Object.freeze([2.8, 2.65, 2.35, 1]),
|
|
41
|
+
intensity: 1,
|
|
42
|
+
mode: 0,
|
|
43
|
+
exposure: 1
|
|
44
|
+
});
|
|
45
|
+
var wavefrontPathTracingComputeLimits = Object.freeze({
|
|
46
|
+
workgroupSize: WORKGROUP_SIZE,
|
|
47
|
+
rayRecordBytes: RAY_RECORD_BYTES,
|
|
48
|
+
hitRecordBytes: HIT_RECORD_BYTES,
|
|
49
|
+
sceneObjectRecordBytes: SCENE_OBJECT_RECORD_BYTES,
|
|
50
|
+
meshVertexRecordBytes: MESH_VERTEX_RECORD_BYTES,
|
|
51
|
+
meshRangeRecordBytes: MESH_RANGE_RECORD_BYTES,
|
|
52
|
+
triangleRecordBytes: TRIANGLE_RECORD_BYTES,
|
|
53
|
+
bvhNodeRecordBytes: BVH_NODE_RECORD_BYTES,
|
|
54
|
+
bvhLeafReferenceRecordBytes: BVH_LEAF_REF_RECORD_BYTES,
|
|
55
|
+
emissiveTriangleIndexBytes: EMISSIVE_TRIANGLE_INDEX_BYTES,
|
|
56
|
+
emissiveTriangleMetadataRecordBytes: BVH_NODE_RECORD_BYTES,
|
|
57
|
+
accumulationRecordBytes: ACCUMULATION_RECORD_BYTES
|
|
58
|
+
});
|
|
59
|
+
var wavefrontSceneObjectKinds = Object.freeze({
|
|
60
|
+
sphere: OBJECT_KIND_SPHERE,
|
|
61
|
+
box: OBJECT_KIND_BOX
|
|
62
|
+
});
|
|
63
|
+
var wavefrontMaterialKinds = Object.freeze({
|
|
64
|
+
diffuse: MATERIAL_DIFFUSE,
|
|
65
|
+
metal: MATERIAL_METAL,
|
|
66
|
+
dielectric: MATERIAL_DIELECTRIC,
|
|
67
|
+
transparent: MATERIAL_TRANSPARENT,
|
|
68
|
+
emissive: MATERIAL_EMISSIVE
|
|
69
|
+
});
|
|
70
|
+
function readPositiveInteger(name, value, fallback) {
|
|
71
|
+
if (value === void 0 || value === null) {
|
|
72
|
+
return fallback;
|
|
73
|
+
}
|
|
74
|
+
const numeric = Number(value);
|
|
75
|
+
if (!Number.isInteger(numeric) || numeric <= 0) {
|
|
76
|
+
throw new Error(`${name} must be a positive integer.`);
|
|
77
|
+
}
|
|
78
|
+
return numeric;
|
|
79
|
+
}
|
|
80
|
+
function readNonNegativeInteger(name, value, fallback) {
|
|
81
|
+
if (value === void 0 || value === null) {
|
|
82
|
+
return fallback;
|
|
83
|
+
}
|
|
84
|
+
const numeric = Number(value);
|
|
85
|
+
if (!Number.isInteger(numeric) || numeric < 0) {
|
|
86
|
+
throw new Error(`${name} must be a non-negative integer.`);
|
|
87
|
+
}
|
|
88
|
+
return numeric;
|
|
89
|
+
}
|
|
90
|
+
function readFiniteNumber(name, value, fallback) {
|
|
91
|
+
if (value === void 0 || value === null) {
|
|
92
|
+
return fallback;
|
|
93
|
+
}
|
|
94
|
+
const numeric = Number(value);
|
|
95
|
+
if (!Number.isFinite(numeric)) {
|
|
96
|
+
throw new Error(`${name} must be a finite number.`);
|
|
97
|
+
}
|
|
98
|
+
return numeric;
|
|
99
|
+
}
|
|
100
|
+
function assertAnalyticDisplayQualityPolicy(options = {}) {
|
|
101
|
+
const meshes = Array.isArray(options.meshes) ? options.meshes : options.mesh ? [options.mesh] : [];
|
|
102
|
+
if (options.displayQuality === true && meshes.length === 0) {
|
|
103
|
+
throw new Error(
|
|
104
|
+
"Display-quality path tracing requires mesh BVH triangle intersections. The analytic sphere/box wavefront renderer is debug-only."
|
|
105
|
+
);
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
function clamp(value, min, max) {
|
|
109
|
+
return Math.max(min, Math.min(max, value));
|
|
110
|
+
}
|
|
111
|
+
function asVec3(value, fallback) {
|
|
112
|
+
if (!Array.isArray(value) && !(ArrayBuffer.isView(value) && value.length >= 3)) {
|
|
113
|
+
return [...fallback];
|
|
114
|
+
}
|
|
115
|
+
return [
|
|
116
|
+
readFiniteNumber("vector[0]", value[0], fallback[0]),
|
|
117
|
+
readFiniteNumber("vector[1]", value[1], fallback[1]),
|
|
118
|
+
readFiniteNumber("vector[2]", value[2], fallback[2])
|
|
119
|
+
];
|
|
120
|
+
}
|
|
121
|
+
function asColor(value, fallback = [1, 1, 1, 1]) {
|
|
122
|
+
if (!Array.isArray(value) && !(ArrayBuffer.isView(value) && value.length >= 3)) {
|
|
123
|
+
return [...fallback];
|
|
124
|
+
}
|
|
125
|
+
return [
|
|
126
|
+
clamp(readFiniteNumber("color[0]", value[0], fallback[0]), 0, 64),
|
|
127
|
+
clamp(readFiniteNumber("color[1]", value[1], fallback[1]), 0, 64),
|
|
128
|
+
clamp(readFiniteNumber("color[2]", value[2], fallback[2]), 0, 64),
|
|
129
|
+
clamp(readFiniteNumber("color[3]", value[3], fallback[3] ?? 1), 0, 1)
|
|
130
|
+
];
|
|
131
|
+
}
|
|
132
|
+
function emissionPower(emission) {
|
|
133
|
+
return Math.max(0, emission?.[0] ?? 0) + Math.max(0, emission?.[1] ?? 0) + Math.max(0, emission?.[2] ?? 0);
|
|
134
|
+
}
|
|
135
|
+
function asUnitVec3(value, fallback) {
|
|
136
|
+
const vector = asVec3(value, fallback);
|
|
137
|
+
return normalize(vector, fallback);
|
|
138
|
+
}
|
|
139
|
+
function add(a, b) {
|
|
140
|
+
return [a[0] + b[0], a[1] + b[1], a[2] + b[2]];
|
|
141
|
+
}
|
|
142
|
+
function subtract(a, b) {
|
|
143
|
+
return [a[0] - b[0], a[1] - b[1], a[2] - b[2]];
|
|
144
|
+
}
|
|
145
|
+
function scale(a, scalar) {
|
|
146
|
+
return [a[0] * scalar, a[1] * scalar, a[2] * scalar];
|
|
147
|
+
}
|
|
148
|
+
function cross(a, b) {
|
|
149
|
+
return [
|
|
150
|
+
a[1] * b[2] - a[2] * b[1],
|
|
151
|
+
a[2] * b[0] - a[0] * b[2],
|
|
152
|
+
a[0] * b[1] - a[1] * b[0]
|
|
153
|
+
];
|
|
154
|
+
}
|
|
155
|
+
function normalize(value, fallback = [0, 0, 1]) {
|
|
156
|
+
const length = Math.hypot(value[0], value[1], value[2]);
|
|
157
|
+
if (!Number.isFinite(length) || length <= 1e-6) {
|
|
158
|
+
return [...fallback];
|
|
159
|
+
}
|
|
160
|
+
return [value[0] / length, value[1] / length, value[2] / length];
|
|
161
|
+
}
|
|
162
|
+
function getArrayLikeLength(value) {
|
|
163
|
+
return Array.isArray(value) || ArrayBuffer.isView(value) ? value.length : 0;
|
|
164
|
+
}
|
|
165
|
+
function readVector(values, index, componentCount, fallback) {
|
|
166
|
+
const offset = index * componentCount;
|
|
167
|
+
const output = [];
|
|
168
|
+
for (let component = 0; component < componentCount; component += 1) {
|
|
169
|
+
output.push(readFiniteNumber("mesh attribute", values?.[offset + component], fallback[component] ?? 0));
|
|
170
|
+
}
|
|
171
|
+
return output;
|
|
172
|
+
}
|
|
173
|
+
function readVector2(values, index, fallback = [0, 0]) {
|
|
174
|
+
return readVector(values, index, 2, fallback);
|
|
175
|
+
}
|
|
176
|
+
function triangleBounds(v0, v1, v2) {
|
|
177
|
+
return {
|
|
178
|
+
min: [
|
|
179
|
+
Math.min(v0[0], v1[0], v2[0]),
|
|
180
|
+
Math.min(v0[1], v1[1], v2[1]),
|
|
181
|
+
Math.min(v0[2], v1[2], v2[2])
|
|
182
|
+
],
|
|
183
|
+
max: [
|
|
184
|
+
Math.max(v0[0], v1[0], v2[0]),
|
|
185
|
+
Math.max(v0[1], v1[1], v2[1]),
|
|
186
|
+
Math.max(v0[2], v1[2], v2[2])
|
|
187
|
+
]
|
|
188
|
+
};
|
|
189
|
+
}
|
|
190
|
+
function mergeBounds(left, right) {
|
|
191
|
+
if (!left) {
|
|
192
|
+
return {
|
|
193
|
+
min: [...right.min],
|
|
194
|
+
max: [...right.max]
|
|
195
|
+
};
|
|
196
|
+
}
|
|
197
|
+
return {
|
|
198
|
+
min: [
|
|
199
|
+
Math.min(left.min[0], right.min[0]),
|
|
200
|
+
Math.min(left.min[1], right.min[1]),
|
|
201
|
+
Math.min(left.min[2], right.min[2])
|
|
202
|
+
],
|
|
203
|
+
max: [
|
|
204
|
+
Math.max(left.max[0], right.max[0]),
|
|
205
|
+
Math.max(left.max[1], right.max[1]),
|
|
206
|
+
Math.max(left.max[2], right.max[2])
|
|
207
|
+
]
|
|
208
|
+
};
|
|
209
|
+
}
|
|
210
|
+
function boundsCentroid(bounds) {
|
|
211
|
+
return [
|
|
212
|
+
(bounds.min[0] + bounds.max[0]) * 0.5,
|
|
213
|
+
(bounds.min[1] + bounds.max[1]) * 0.5,
|
|
214
|
+
(bounds.min[2] + bounds.max[2]) * 0.5
|
|
215
|
+
];
|
|
216
|
+
}
|
|
217
|
+
function readMaterialKind(value) {
|
|
218
|
+
if (typeof value === "number") {
|
|
219
|
+
return clamp(Math.trunc(value), MATERIAL_DIFFUSE, MATERIAL_EMISSIVE);
|
|
220
|
+
}
|
|
221
|
+
switch (value) {
|
|
222
|
+
case "metal":
|
|
223
|
+
case "reflective":
|
|
224
|
+
return MATERIAL_METAL;
|
|
225
|
+
case "dielectric":
|
|
226
|
+
case "refractive":
|
|
227
|
+
case "glass":
|
|
228
|
+
return MATERIAL_DIELECTRIC;
|
|
229
|
+
case "transparent":
|
|
230
|
+
case "transmission":
|
|
231
|
+
return MATERIAL_TRANSPARENT;
|
|
232
|
+
case "emissive":
|
|
233
|
+
case "light":
|
|
234
|
+
return MATERIAL_EMISSIVE;
|
|
235
|
+
case "diffuse":
|
|
236
|
+
default:
|
|
237
|
+
return MATERIAL_DIFFUSE;
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
function readObjectKind(value) {
|
|
241
|
+
if (typeof value === "number") {
|
|
242
|
+
return value === OBJECT_KIND_BOX ? OBJECT_KIND_BOX : OBJECT_KIND_SPHERE;
|
|
243
|
+
}
|
|
244
|
+
switch (value) {
|
|
245
|
+
case "box":
|
|
246
|
+
case "aabb":
|
|
247
|
+
case "bounds":
|
|
248
|
+
return OBJECT_KIND_BOX;
|
|
249
|
+
case "sphere":
|
|
250
|
+
default:
|
|
251
|
+
return OBJECT_KIND_SPHERE;
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
function deriveBounds(input) {
|
|
255
|
+
if (Array.isArray(input?.min) && Array.isArray(input?.max)) {
|
|
256
|
+
const min = asVec3(input.min, [-0.5, -0.5, -0.5]);
|
|
257
|
+
const max = asVec3(input.max, [0.5, 0.5, 0.5]);
|
|
258
|
+
return {
|
|
259
|
+
center: scale(add(min, max), 0.5),
|
|
260
|
+
halfExtent: scale(subtract(max, min), 0.5).map((value) => Math.max(value, 1e-3))
|
|
261
|
+
};
|
|
262
|
+
}
|
|
263
|
+
if (Array.isArray(input?.bounds?.min) && Array.isArray(input?.bounds?.max)) {
|
|
264
|
+
return deriveBounds(input.bounds);
|
|
265
|
+
}
|
|
266
|
+
return null;
|
|
267
|
+
}
|
|
268
|
+
function normalizeWavefrontSceneObject(input = {}, index = 0) {
|
|
269
|
+
const bounds = deriveBounds(input);
|
|
270
|
+
const kind = readObjectKind(input.kind ?? input.type ?? (bounds ? "box" : "sphere"));
|
|
271
|
+
const center = asVec3(input.center ?? input.position ?? bounds?.center, [0, 0, 0]);
|
|
272
|
+
const radius = readFiniteNumber("radius", input.radius, 0.5);
|
|
273
|
+
const halfExtent = kind === OBJECT_KIND_SPHERE ? [Math.max(radius, 1e-3), Math.max(radius, 1e-3), Math.max(radius, 1e-3)] : asVec3(
|
|
274
|
+
input.halfExtent ?? input.halfExtents ?? input.extents ?? bounds?.halfExtent,
|
|
275
|
+
[0.5, 0.5, 0.5]
|
|
276
|
+
).map((value) => Math.max(value, 1e-3));
|
|
277
|
+
const materialKind = readMaterialKind(input.materialKind ?? input.material?.kind);
|
|
278
|
+
const color = asColor(
|
|
279
|
+
input.color ?? input.baseColor ?? input.albedo ?? input.material?.color ?? input.material?.baseColor,
|
|
280
|
+
[0.72, 0.72, 0.68, 1]
|
|
281
|
+
);
|
|
282
|
+
const emission = asColor(
|
|
283
|
+
input.emission ?? input.emissive ?? input.material?.emission ?? input.material?.emissive,
|
|
284
|
+
[0, 0, 0, 1]
|
|
285
|
+
);
|
|
286
|
+
return Object.freeze({
|
|
287
|
+
id: readNonNegativeInteger("id", input.id, index + 1),
|
|
288
|
+
kind,
|
|
289
|
+
materialKind: emission[0] > 0 || emission[1] > 0 || emission[2] > 0 ? MATERIAL_EMISSIVE : materialKind,
|
|
290
|
+
flags: readNonNegativeInteger("flags", input.flags, 0),
|
|
291
|
+
center: Object.freeze(center),
|
|
292
|
+
halfExtent: Object.freeze(halfExtent),
|
|
293
|
+
color: Object.freeze(color),
|
|
294
|
+
emission: Object.freeze(emission),
|
|
295
|
+
roughness: clamp(readFiniteNumber("roughness", input.roughness ?? input.material?.roughness, 0.72), 0, 1),
|
|
296
|
+
metallic: clamp(readFiniteNumber("metallic", input.metallic ?? input.material?.metallic, 0), 0, 1),
|
|
297
|
+
opacity: clamp(readFiniteNumber("opacity", input.opacity ?? input.material?.opacity, color[3] ?? 1), 0, 1),
|
|
298
|
+
ior: clamp(readFiniteNumber("ior", input.ior ?? input.material?.ior, 1.45), 1, 3)
|
|
299
|
+
});
|
|
300
|
+
}
|
|
301
|
+
function createDefaultWavefrontSceneObjects() {
|
|
302
|
+
return Object.freeze([
|
|
303
|
+
normalizeWavefrontSceneObject({
|
|
304
|
+
type: "box",
|
|
305
|
+
id: 1,
|
|
306
|
+
center: [0, -0.08, 0],
|
|
307
|
+
halfExtent: [3.25, 0.08, 3.25],
|
|
308
|
+
color: [0.45, 0.53, 0.54, 1],
|
|
309
|
+
roughness: 0.5
|
|
310
|
+
}),
|
|
311
|
+
normalizeWavefrontSceneObject({
|
|
312
|
+
type: "box",
|
|
313
|
+
id: 2,
|
|
314
|
+
center: [0, 1.25, -1.65],
|
|
315
|
+
halfExtent: [2.45, 1.45, 0.08],
|
|
316
|
+
color: [0.42, 0.41, 0.38, 1],
|
|
317
|
+
roughness: 0.85
|
|
318
|
+
}),
|
|
319
|
+
normalizeWavefrontSceneObject({
|
|
320
|
+
type: "sphere",
|
|
321
|
+
id: 3,
|
|
322
|
+
center: [-0.9, 0.72, 0.05],
|
|
323
|
+
radius: 0.72,
|
|
324
|
+
color: [0.76, 0.72, 0.64, 1],
|
|
325
|
+
materialKind: "metal",
|
|
326
|
+
roughness: 0.08,
|
|
327
|
+
metallic: 0.7
|
|
328
|
+
}),
|
|
329
|
+
normalizeWavefrontSceneObject({
|
|
330
|
+
type: "sphere",
|
|
331
|
+
id: 4,
|
|
332
|
+
center: [0.85, 0.65, -0.05],
|
|
333
|
+
radius: 0.58,
|
|
334
|
+
color: [0.68, 0.82, 0.86, 0.72],
|
|
335
|
+
materialKind: "dielectric",
|
|
336
|
+
roughness: 0.02,
|
|
337
|
+
opacity: 0.72,
|
|
338
|
+
ior: 1.35
|
|
339
|
+
}),
|
|
340
|
+
normalizeWavefrontSceneObject({
|
|
341
|
+
type: "sphere",
|
|
342
|
+
id: 5,
|
|
343
|
+
center: [0, 2.55, -0.65],
|
|
344
|
+
radius: 0.34,
|
|
345
|
+
color: [1, 0.94, 0.78, 1],
|
|
346
|
+
emission: [7.2, 6.5, 4.2, 1],
|
|
347
|
+
materialKind: "emissive"
|
|
348
|
+
})
|
|
349
|
+
]);
|
|
350
|
+
}
|
|
351
|
+
function normalizeWavefrontMesh(input = {}, meshIndex = 0) {
|
|
352
|
+
const positions = input.positions;
|
|
353
|
+
const positionLength = getArrayLikeLength(positions);
|
|
354
|
+
if (positionLength < 9 || positionLength % 3 !== 0) {
|
|
355
|
+
throw new Error("Wavefront mesh positions must contain at least three vec3 vertices.");
|
|
356
|
+
}
|
|
357
|
+
const vertexCount = positionLength / 3;
|
|
358
|
+
const indices = getArrayLikeLength(input.indices) > 0 ? Array.from(input.indices, (value) => readNonNegativeInteger("mesh index", value, 0)) : Array.from({ length: vertexCount }, (_, index) => index);
|
|
359
|
+
if (indices.length < 3 || indices.length % 3 !== 0) {
|
|
360
|
+
throw new Error("Wavefront mesh indices must contain complete triangles.");
|
|
361
|
+
}
|
|
362
|
+
if (indices.some((index) => index >= vertexCount)) {
|
|
363
|
+
throw new Error("Wavefront mesh index references a vertex outside the position buffer.");
|
|
364
|
+
}
|
|
365
|
+
const normals = getArrayLikeLength(input.normals) >= positionLength ? Array.from(input.normals, (value) => readFiniteNumber("mesh normal", value, 0)) : null;
|
|
366
|
+
const uvs = getArrayLikeLength(input.uvs ?? input.texcoords ?? input.uv) >= vertexCount * 2 ? Array.from(
|
|
367
|
+
input.uvs ?? input.texcoords ?? input.uv,
|
|
368
|
+
(value) => readFiniteNumber("mesh uv", value, 0)
|
|
369
|
+
) : null;
|
|
370
|
+
const materialKind = readMaterialKind(input.materialKind ?? input.material?.kind);
|
|
371
|
+
const color = asColor(
|
|
372
|
+
input.color ?? input.baseColor ?? input.albedo ?? input.material?.color ?? input.material?.baseColor,
|
|
373
|
+
[0.72, 0.72, 0.68, 1]
|
|
374
|
+
);
|
|
375
|
+
const emission = asColor(
|
|
376
|
+
input.emission ?? input.emissive ?? input.material?.emission ?? input.material?.emissive,
|
|
377
|
+
[0, 0, 0, 1]
|
|
378
|
+
);
|
|
379
|
+
return Object.freeze({
|
|
380
|
+
id: readNonNegativeInteger("mesh id", input.id, meshIndex + 1),
|
|
381
|
+
positions: Object.freeze(Array.from(positions, (value) => readFiniteNumber("mesh position", value, 0))),
|
|
382
|
+
indices: Object.freeze(indices),
|
|
383
|
+
normals: normals ? Object.freeze(normals) : null,
|
|
384
|
+
uvs: uvs ? Object.freeze(uvs) : null,
|
|
385
|
+
materialKind: emission[0] > 0 || emission[1] > 0 || emission[2] > 0 ? MATERIAL_EMISSIVE : materialKind,
|
|
386
|
+
flags: readNonNegativeInteger("mesh flags", input.flags, 0),
|
|
387
|
+
materialRefId: readNonNegativeInteger(
|
|
388
|
+
"mesh materialRefId",
|
|
389
|
+
input.materialRefId ?? input.material?.id ?? input.materialId,
|
|
390
|
+
meshIndex
|
|
391
|
+
),
|
|
392
|
+
mediumRefId: readNonNegativeInteger(
|
|
393
|
+
"mesh mediumRefId",
|
|
394
|
+
input.mediumRefId ?? input.medium?.id ?? input.mediumId,
|
|
395
|
+
0
|
|
396
|
+
),
|
|
397
|
+
color: Object.freeze(color),
|
|
398
|
+
emission: Object.freeze(emission),
|
|
399
|
+
roughness: clamp(readFiniteNumber("roughness", input.roughness ?? input.material?.roughness, 0.72), 0, 1),
|
|
400
|
+
metallic: clamp(readFiniteNumber("metallic", input.metallic ?? input.material?.metallic, 0), 0, 1),
|
|
401
|
+
opacity: clamp(readFiniteNumber("opacity", input.opacity ?? input.material?.opacity, color[3] ?? 1), 0, 1),
|
|
402
|
+
ior: clamp(readFiniteNumber("ior", input.ior ?? input.material?.ior, 1.45), 1, 3)
|
|
403
|
+
});
|
|
404
|
+
}
|
|
405
|
+
function createMeshTriangleRecords(meshes) {
|
|
406
|
+
const source = Array.isArray(meshes) ? meshes : [];
|
|
407
|
+
let nextTriangleId = 0;
|
|
408
|
+
return source.flatMap((meshInput, meshIndex) => {
|
|
409
|
+
const mesh = normalizeWavefrontMesh(meshInput, meshIndex);
|
|
410
|
+
const triangles = [];
|
|
411
|
+
for (let index = 0; index < mesh.indices.length; index += 3) {
|
|
412
|
+
const a = mesh.indices[index];
|
|
413
|
+
const b = mesh.indices[index + 1];
|
|
414
|
+
const c = mesh.indices[index + 2];
|
|
415
|
+
const v0 = readVector(mesh.positions, a, 3, [0, 0, 0]);
|
|
416
|
+
const v1 = readVector(mesh.positions, b, 3, [0, 0, 0]);
|
|
417
|
+
const v2 = readVector(mesh.positions, c, 3, [0, 0, 0]);
|
|
418
|
+
const faceNormal = normalize(cross(subtract(v1, v0), subtract(v2, v0)), [0, 1, 0]);
|
|
419
|
+
const n0 = mesh.normals ? normalize(readVector(mesh.normals, a, 3, faceNormal), faceNormal) : faceNormal;
|
|
420
|
+
const n1 = mesh.normals ? normalize(readVector(mesh.normals, b, 3, faceNormal), faceNormal) : faceNormal;
|
|
421
|
+
const n2 = mesh.normals ? normalize(readVector(mesh.normals, c, 3, faceNormal), faceNormal) : faceNormal;
|
|
422
|
+
const uv0 = mesh.uvs ? readVector2(mesh.uvs, a) : [0, 0];
|
|
423
|
+
const uv1 = mesh.uvs ? readVector2(mesh.uvs, b) : [0, 0];
|
|
424
|
+
const uv2 = mesh.uvs ? readVector2(mesh.uvs, c) : [0, 0];
|
|
425
|
+
const bounds = triangleBounds(v0, v1, v2);
|
|
426
|
+
triangles.push(
|
|
427
|
+
Object.freeze({
|
|
428
|
+
triangleId: nextTriangleId,
|
|
429
|
+
meshId: mesh.id,
|
|
430
|
+
materialKind: mesh.materialKind,
|
|
431
|
+
flags: mesh.flags,
|
|
432
|
+
materialRefId: mesh.materialRefId,
|
|
433
|
+
mediumRefId: mesh.mediumRefId,
|
|
434
|
+
v0: Object.freeze(v0),
|
|
435
|
+
v1: Object.freeze(v1),
|
|
436
|
+
v2: Object.freeze(v2),
|
|
437
|
+
n0: Object.freeze(n0),
|
|
438
|
+
n1: Object.freeze(n1),
|
|
439
|
+
n2: Object.freeze(n2),
|
|
440
|
+
uv0: Object.freeze(uv0),
|
|
441
|
+
uv1: Object.freeze(uv1),
|
|
442
|
+
uv2: Object.freeze(uv2),
|
|
443
|
+
color: mesh.color,
|
|
444
|
+
emission: mesh.emission,
|
|
445
|
+
material: Object.freeze([mesh.roughness, mesh.metallic, mesh.opacity, mesh.ior]),
|
|
446
|
+
bounds: Object.freeze({
|
|
447
|
+
min: Object.freeze(bounds.min),
|
|
448
|
+
max: Object.freeze(bounds.max)
|
|
449
|
+
}),
|
|
450
|
+
centroid: Object.freeze(boundsCentroid(bounds))
|
|
451
|
+
})
|
|
452
|
+
);
|
|
453
|
+
nextTriangleId += 1;
|
|
454
|
+
}
|
|
455
|
+
return triangles;
|
|
456
|
+
});
|
|
457
|
+
}
|
|
458
|
+
function chooseSplitAxis(triangles) {
|
|
459
|
+
const centroidBounds = triangles.reduce(
|
|
460
|
+
(bounds, triangle) => {
|
|
461
|
+
const pointBounds = { min: triangle.centroid, max: triangle.centroid };
|
|
462
|
+
return mergeBounds(bounds, pointBounds);
|
|
463
|
+
},
|
|
464
|
+
null
|
|
465
|
+
);
|
|
466
|
+
const extent = subtract(centroidBounds.max, centroidBounds.min);
|
|
467
|
+
if (extent[0] >= extent[1] && extent[0] >= extent[2]) {
|
|
468
|
+
return 0;
|
|
469
|
+
}
|
|
470
|
+
return extent[1] >= extent[2] ? 1 : 2;
|
|
471
|
+
}
|
|
472
|
+
function buildBvh(triangles, maxLeafTriangles = 4) {
|
|
473
|
+
if (triangles.length === 0) {
|
|
474
|
+
return Object.freeze({ nodes: Object.freeze([]), triangles: Object.freeze([]) });
|
|
475
|
+
}
|
|
476
|
+
const nodes = [];
|
|
477
|
+
const orderedTriangles = [];
|
|
478
|
+
function buildNode(nodeTriangles) {
|
|
479
|
+
const nodeIndex = nodes.length;
|
|
480
|
+
nodes.push(null);
|
|
481
|
+
const bounds = nodeTriangles.reduce((current, triangle) => mergeBounds(current, triangle.bounds), null);
|
|
482
|
+
if (nodeTriangles.length <= maxLeafTriangles) {
|
|
483
|
+
const firstTriangle = orderedTriangles.length;
|
|
484
|
+
orderedTriangles.push(...nodeTriangles);
|
|
485
|
+
nodes[nodeIndex] = Object.freeze({
|
|
486
|
+
bounds: Object.freeze({
|
|
487
|
+
min: Object.freeze(bounds.min),
|
|
488
|
+
max: Object.freeze(bounds.max)
|
|
489
|
+
}),
|
|
490
|
+
firstTriangle,
|
|
491
|
+
triangleCount: nodeTriangles.length,
|
|
492
|
+
leftChild: 0,
|
|
493
|
+
rightChild: 0
|
|
494
|
+
});
|
|
495
|
+
return nodeIndex;
|
|
496
|
+
}
|
|
497
|
+
const axis = chooseSplitAxis(nodeTriangles);
|
|
498
|
+
const sorted = [...nodeTriangles].sort((left, right) => left.centroid[axis] - right.centroid[axis]);
|
|
499
|
+
const midpoint = Math.max(1, Math.floor(sorted.length / 2));
|
|
500
|
+
const leftChild = buildNode(sorted.slice(0, midpoint));
|
|
501
|
+
const rightChild = buildNode(sorted.slice(midpoint));
|
|
502
|
+
nodes[nodeIndex] = Object.freeze({
|
|
503
|
+
bounds: Object.freeze({
|
|
504
|
+
min: Object.freeze(bounds.min),
|
|
505
|
+
max: Object.freeze(bounds.max)
|
|
506
|
+
}),
|
|
507
|
+
firstTriangle: leftChild,
|
|
508
|
+
triangleCount: 0,
|
|
509
|
+
leftChild,
|
|
510
|
+
rightChild
|
|
511
|
+
});
|
|
512
|
+
return nodeIndex;
|
|
513
|
+
}
|
|
514
|
+
buildNode(triangles);
|
|
515
|
+
return Object.freeze({
|
|
516
|
+
nodes: Object.freeze(nodes),
|
|
517
|
+
triangles: Object.freeze(orderedTriangles)
|
|
518
|
+
});
|
|
519
|
+
}
|
|
520
|
+
function createWavefrontMeshAcceleration(meshes = []) {
|
|
521
|
+
const source = Array.isArray(meshes) ? meshes : [meshes];
|
|
522
|
+
const triangles = createMeshTriangleRecords(source);
|
|
523
|
+
return buildBvh(triangles);
|
|
524
|
+
}
|
|
525
|
+
function estimateMeshSourceShape(meshes) {
|
|
526
|
+
const source = Array.isArray(meshes) ? meshes : [];
|
|
527
|
+
return source.reduce(
|
|
528
|
+
(shape, meshInput, meshIndex) => {
|
|
529
|
+
const mesh = normalizeWavefrontMesh(meshInput, meshIndex);
|
|
530
|
+
return {
|
|
531
|
+
vertexCount: shape.vertexCount + mesh.positions.length / 3,
|
|
532
|
+
indexCount: shape.indexCount + mesh.indices.length,
|
|
533
|
+
meshCount: shape.meshCount + 1,
|
|
534
|
+
triangleCount: shape.triangleCount + mesh.indices.length / 3
|
|
535
|
+
};
|
|
536
|
+
},
|
|
537
|
+
{
|
|
538
|
+
vertexCount: 0,
|
|
539
|
+
indexCount: 0,
|
|
540
|
+
meshCount: 0,
|
|
541
|
+
triangleCount: 0
|
|
542
|
+
}
|
|
543
|
+
);
|
|
544
|
+
}
|
|
545
|
+
function estimateBinaryBvhNodeCapacity(triangleCount) {
|
|
546
|
+
return triangleCount <= 0 ? 0 : Math.max(1, triangleCount * 2 - 1);
|
|
547
|
+
}
|
|
548
|
+
function nextPowerOfTwo(value) {
|
|
549
|
+
if (value <= 1) {
|
|
550
|
+
return Math.max(0, value);
|
|
551
|
+
}
|
|
552
|
+
return 2 ** Math.ceil(Math.log2(value));
|
|
553
|
+
}
|
|
554
|
+
function estimateBvhLeafSortCapacity(triangleCount) {
|
|
555
|
+
return triangleCount <= 0 ? 0 : nextPowerOfTwo(triangleCount);
|
|
556
|
+
}
|
|
557
|
+
function createWavefrontBvhSortStages(itemCountInput) {
|
|
558
|
+
const itemCount = readNonNegativeInteger("itemCount", itemCountInput, 0);
|
|
559
|
+
const sortCount = estimateBvhLeafSortCapacity(itemCount);
|
|
560
|
+
if (sortCount <= 1) {
|
|
561
|
+
return Object.freeze([]);
|
|
562
|
+
}
|
|
563
|
+
const stages = [];
|
|
564
|
+
for (let sequenceSize = 2; sequenceSize <= sortCount; sequenceSize *= 2) {
|
|
565
|
+
for (let compareDistance = sequenceSize / 2; compareDistance >= 1; compareDistance /= 2) {
|
|
566
|
+
stages.push(
|
|
567
|
+
Object.freeze({
|
|
568
|
+
compareDistance,
|
|
569
|
+
sequenceSize
|
|
570
|
+
})
|
|
571
|
+
);
|
|
572
|
+
}
|
|
573
|
+
}
|
|
574
|
+
return Object.freeze(stages);
|
|
575
|
+
}
|
|
576
|
+
function createWavefrontBvhBuildLevels(triangleCountInput) {
|
|
577
|
+
const triangleCount = readNonNegativeInteger("triangleCount", triangleCountInput, 0);
|
|
578
|
+
const internalCount = Math.max(0, triangleCount - 1);
|
|
579
|
+
if (internalCount === 0) {
|
|
580
|
+
return Object.freeze([]);
|
|
581
|
+
}
|
|
582
|
+
const levels = [];
|
|
583
|
+
let depth = 0;
|
|
584
|
+
while (Math.pow(2, depth) - 1 < internalCount) {
|
|
585
|
+
depth += 1;
|
|
586
|
+
}
|
|
587
|
+
for (let level = depth - 1; level >= 0; level -= 1) {
|
|
588
|
+
const start = Math.pow(2, level) - 1;
|
|
589
|
+
const end = Math.min(Math.pow(2, level + 1) - 2, internalCount - 1);
|
|
590
|
+
if (end >= start) {
|
|
591
|
+
levels.push(
|
|
592
|
+
Object.freeze({
|
|
593
|
+
start,
|
|
594
|
+
count: end - start + 1
|
|
595
|
+
})
|
|
596
|
+
);
|
|
597
|
+
}
|
|
598
|
+
}
|
|
599
|
+
return Object.freeze(levels);
|
|
600
|
+
}
|
|
601
|
+
function resolveAccelerationBuildMode(options = {}) {
|
|
602
|
+
const mode = options.accelerationBuildMode ?? (options.displayQuality === true ? "gpu" : "cpu-debug");
|
|
603
|
+
if (mode !== "gpu" && mode !== "cpu-debug") {
|
|
604
|
+
throw new Error('accelerationBuildMode must be either "gpu" or "cpu-debug".');
|
|
605
|
+
}
|
|
606
|
+
if (options.displayQuality === true && mode !== "gpu") {
|
|
607
|
+
throw new Error("Display-quality path tracing requires GPU-built mesh acceleration.");
|
|
608
|
+
}
|
|
609
|
+
return mode;
|
|
610
|
+
}
|
|
611
|
+
function createWavefrontGpuMeshSource(meshes = []) {
|
|
612
|
+
const source = Array.isArray(meshes) ? meshes : [meshes];
|
|
613
|
+
const normalized = source.map((meshInput, meshIndex) => normalizeWavefrontMesh(meshInput, meshIndex));
|
|
614
|
+
const vertexCount = normalized.reduce((count, mesh) => count + mesh.positions.length / 3, 0);
|
|
615
|
+
const indexCount = normalized.reduce((count, mesh) => count + mesh.indices.length, 0);
|
|
616
|
+
const triangleCount = Math.floor(indexCount / 3);
|
|
617
|
+
const vertexBytes = new ArrayBuffer(Math.max(1, vertexCount) * MESH_VERTEX_RECORD_BYTES);
|
|
618
|
+
const indexBytes = new ArrayBuffer(Math.max(1, indexCount) * 4);
|
|
619
|
+
const meshBytes = new ArrayBuffer(Math.max(1, normalized.length) * MESH_RANGE_RECORD_BYTES);
|
|
620
|
+
const vertexFloats = new Float32Array(vertexBytes);
|
|
621
|
+
const indexUints = new Uint32Array(indexBytes);
|
|
622
|
+
const meshUints = new Uint32Array(meshBytes);
|
|
623
|
+
const meshFloats = new Float32Array(meshBytes);
|
|
624
|
+
let vertexCursor = 0;
|
|
625
|
+
let indexCursor = 0;
|
|
626
|
+
let triangleCursor = 0;
|
|
627
|
+
normalized.forEach((mesh, meshIndex) => {
|
|
628
|
+
const meshVertexBase = vertexCursor;
|
|
629
|
+
const meshIndexBase = indexCursor;
|
|
630
|
+
const meshTriangleBase = triangleCursor;
|
|
631
|
+
const meshVertexCount = mesh.positions.length / 3;
|
|
632
|
+
for (let vertexIndex = 0; vertexIndex < meshVertexCount; vertexIndex += 1) {
|
|
633
|
+
const recordOffset = (vertexCursor + vertexIndex) * (MESH_VERTEX_RECORD_BYTES / 4);
|
|
634
|
+
const position = readVector(mesh.positions, vertexIndex, 3, [0, 0, 0]);
|
|
635
|
+
const normal = mesh.normals ? readVector(mesh.normals, vertexIndex, 3, [0, 0, 0]) : [0, 0, 0];
|
|
636
|
+
const uv = mesh.uvs ? readVector2(mesh.uvs, vertexIndex) : [0, 0];
|
|
637
|
+
vertexFloats[recordOffset] = position[0];
|
|
638
|
+
vertexFloats[recordOffset + 1] = position[1];
|
|
639
|
+
vertexFloats[recordOffset + 2] = position[2];
|
|
640
|
+
vertexFloats[recordOffset + 3] = 1;
|
|
641
|
+
vertexFloats[recordOffset + 4] = normal[0];
|
|
642
|
+
vertexFloats[recordOffset + 5] = normal[1];
|
|
643
|
+
vertexFloats[recordOffset + 6] = normal[2];
|
|
644
|
+
vertexFloats[recordOffset + 7] = mesh.normals ? 1 : 0;
|
|
645
|
+
vertexFloats[recordOffset + 8] = uv[0];
|
|
646
|
+
vertexFloats[recordOffset + 9] = uv[1];
|
|
647
|
+
vertexFloats[recordOffset + 10] = mesh.uvs ? 1 : 0;
|
|
648
|
+
vertexFloats[recordOffset + 11] = 0;
|
|
649
|
+
}
|
|
650
|
+
mesh.indices.forEach((indexValue, localIndex) => {
|
|
651
|
+
indexUints[indexCursor + localIndex] = meshVertexBase + indexValue;
|
|
652
|
+
});
|
|
653
|
+
const meshOffset = meshIndex * (MESH_RANGE_RECORD_BYTES / 4);
|
|
654
|
+
meshUints[meshOffset] = mesh.id;
|
|
655
|
+
meshUints[meshOffset + 1] = mesh.materialKind;
|
|
656
|
+
meshUints[meshOffset + 2] = mesh.flags;
|
|
657
|
+
meshUints[meshOffset + 3] = mesh.materialRefId;
|
|
658
|
+
meshUints[meshOffset + 4] = mesh.mediumRefId;
|
|
659
|
+
meshUints[meshOffset + 5] = meshIndexBase;
|
|
660
|
+
meshUints[meshOffset + 6] = mesh.indices.length;
|
|
661
|
+
meshUints[meshOffset + 7] = meshTriangleBase;
|
|
662
|
+
meshUints[meshOffset + 8] = mesh.indices.length / 3;
|
|
663
|
+
meshUints[meshOffset + 9] = meshVertexBase;
|
|
664
|
+
meshUints[meshOffset + 10] = meshVertexCount;
|
|
665
|
+
meshUints[meshOffset + 11] = 0;
|
|
666
|
+
const floatOffset = meshOffset;
|
|
667
|
+
writeVec4(meshFloats, floatOffset * 4 + 48, mesh.color);
|
|
668
|
+
writeVec4(meshFloats, floatOffset * 4 + 64, mesh.emission);
|
|
669
|
+
writeVec4(meshFloats, floatOffset * 4 + 80, [
|
|
670
|
+
mesh.roughness,
|
|
671
|
+
mesh.metallic,
|
|
672
|
+
mesh.opacity,
|
|
673
|
+
mesh.ior
|
|
674
|
+
]);
|
|
675
|
+
vertexCursor += meshVertexCount;
|
|
676
|
+
indexCursor += mesh.indices.length;
|
|
677
|
+
triangleCursor += mesh.indices.length / 3;
|
|
678
|
+
});
|
|
679
|
+
return Object.freeze({
|
|
680
|
+
vertices: Object.freeze({
|
|
681
|
+
buffer: vertexBytes,
|
|
682
|
+
count: vertexCount,
|
|
683
|
+
recordBytes: MESH_VERTEX_RECORD_BYTES
|
|
684
|
+
}),
|
|
685
|
+
indices: Object.freeze({
|
|
686
|
+
buffer: indexBytes,
|
|
687
|
+
count: indexCount,
|
|
688
|
+
recordBytes: 4
|
|
689
|
+
}),
|
|
690
|
+
meshes: Object.freeze({
|
|
691
|
+
buffer: meshBytes,
|
|
692
|
+
records: Object.freeze(normalized),
|
|
693
|
+
count: normalized.length,
|
|
694
|
+
recordBytes: MESH_RANGE_RECORD_BYTES
|
|
695
|
+
}),
|
|
696
|
+
triangleCount,
|
|
697
|
+
bvhNodeCapacity: estimateBinaryBvhNodeCapacity(triangleCount)
|
|
698
|
+
});
|
|
699
|
+
}
|
|
700
|
+
function createWavefrontEmissiveTriangleIndexSource(meshes = [], capacityInput) {
|
|
701
|
+
const source = Array.isArray(meshes) ? meshes : [meshes];
|
|
702
|
+
const normalized = source.map((meshInput, meshIndex) => normalizeWavefrontMesh(meshInput, meshIndex));
|
|
703
|
+
const indices = [];
|
|
704
|
+
let triangleCursor = 0;
|
|
705
|
+
normalized.forEach((mesh) => {
|
|
706
|
+
const triangleCount = Math.floor(mesh.indices.length / 3);
|
|
707
|
+
const isEmissive = mesh.materialKind === MATERIAL_EMISSIVE || emissionPower(mesh.emission) > 1e-4;
|
|
708
|
+
if (isEmissive) {
|
|
709
|
+
for (let triangleOffset = 0; triangleOffset < triangleCount; triangleOffset += 1) {
|
|
710
|
+
indices.push(triangleCursor + triangleOffset);
|
|
711
|
+
}
|
|
712
|
+
}
|
|
713
|
+
triangleCursor += triangleCount;
|
|
714
|
+
});
|
|
715
|
+
const capacity = Math.max(
|
|
716
|
+
indices.length,
|
|
717
|
+
readNonNegativeInteger("emissiveTriangleCapacity", capacityInput, indices.length)
|
|
718
|
+
);
|
|
719
|
+
const bytes = new ArrayBuffer(capacity * EMISSIVE_TRIANGLE_INDEX_BYTES);
|
|
720
|
+
const uints = new Uint32Array(bytes);
|
|
721
|
+
uints.fill(4294967295);
|
|
722
|
+
indices.forEach((triangleIndex, index) => {
|
|
723
|
+
uints[index] = triangleIndex;
|
|
724
|
+
});
|
|
725
|
+
return Object.freeze({
|
|
726
|
+
buffer: bytes,
|
|
727
|
+
indices: Object.freeze(indices),
|
|
728
|
+
count: indices.length,
|
|
729
|
+
capacity,
|
|
730
|
+
recordBytes: EMISSIVE_TRIANGLE_INDEX_BYTES
|
|
731
|
+
});
|
|
732
|
+
}
|
|
733
|
+
function normalizeSceneObjects(sceneObjects, useDefaultScene = true) {
|
|
734
|
+
const source = Array.isArray(sceneObjects) && sceneObjects.length > 0 ? sceneObjects : useDefaultScene ? createDefaultWavefrontSceneObjects() : [];
|
|
735
|
+
return source.map((object, index) => normalizeWavefrontSceneObject(object, index));
|
|
736
|
+
}
|
|
737
|
+
function normalizeMeshes(options = {}) {
|
|
738
|
+
if (Array.isArray(options.meshes)) {
|
|
739
|
+
return options.meshes;
|
|
740
|
+
}
|
|
741
|
+
if (options.mesh) {
|
|
742
|
+
return [options.mesh];
|
|
743
|
+
}
|
|
744
|
+
return [];
|
|
745
|
+
}
|
|
746
|
+
function resolveEnvironmentLighting(input, environmentColor, ambientColor) {
|
|
747
|
+
const source = input ?? {};
|
|
748
|
+
return Object.freeze({
|
|
749
|
+
environmentColor: Object.freeze(asColor(source.environmentColor, environmentColor)),
|
|
750
|
+
ambientColor: Object.freeze(asColor(source.ambientColor, ambientColor)),
|
|
751
|
+
horizonColor: Object.freeze(asColor(source.horizonColor, environmentColor)),
|
|
752
|
+
zenithColor: Object.freeze(asColor(source.zenithColor, DEFAULT_ENVIRONMENT_LIGHTING.zenithColor)),
|
|
753
|
+
sunDirection: Object.freeze(asUnitVec3(source.sunDirection, DEFAULT_ENVIRONMENT_LIGHTING.sunDirection)),
|
|
754
|
+
sunColor: Object.freeze(asColor(source.sunColor, DEFAULT_ENVIRONMENT_LIGHTING.sunColor)),
|
|
755
|
+
intensity: Math.max(1e-4, readFiniteNumber("environmentLighting.intensity", source.intensity, DEFAULT_ENVIRONMENT_LIGHTING.intensity)),
|
|
756
|
+
mode: readNonNegativeInteger("environmentLighting.mode", source.mode, DEFAULT_ENVIRONMENT_LIGHTING.mode),
|
|
757
|
+
exposure: Math.max(1e-4, readFiniteNumber("environmentLighting.exposure", source.exposure, DEFAULT_ENVIRONMENT_LIGHTING.exposure))
|
|
758
|
+
});
|
|
759
|
+
}
|
|
760
|
+
function getCanvasDimension(canvas, key, fallback) {
|
|
761
|
+
const value = Number(canvas?.[key]);
|
|
762
|
+
if (Number.isFinite(value) && value > 0) {
|
|
763
|
+
return Math.trunc(value);
|
|
764
|
+
}
|
|
765
|
+
return fallback;
|
|
766
|
+
}
|
|
767
|
+
function resolveCamera(input, width, height) {
|
|
768
|
+
const camera = input ?? DEFAULT_CAMERA;
|
|
769
|
+
const position = asVec3(camera.position, DEFAULT_CAMERA.position);
|
|
770
|
+
const target = asVec3(camera.target, DEFAULT_CAMERA.target);
|
|
771
|
+
const upInput = normalize(asVec3(camera.up, DEFAULT_CAMERA.up), DEFAULT_CAMERA.up);
|
|
772
|
+
const forward = normalize(subtract(target, position), [0, 0, -1]);
|
|
773
|
+
const right = normalize(cross(forward, upInput), [1, 0, 0]);
|
|
774
|
+
const up = normalize(cross(right, forward), [0, 1, 0]);
|
|
775
|
+
const fovYDegrees = clamp(
|
|
776
|
+
readFiniteNumber("camera.fovYDegrees", camera.fovYDegrees ?? camera.fov, DEFAULT_CAMERA.fovYDegrees),
|
|
777
|
+
10,
|
|
778
|
+
120
|
|
779
|
+
);
|
|
780
|
+
const aspect = width / Math.max(1, height);
|
|
781
|
+
const tanHalfFovY = Math.tan(fovYDegrees * Math.PI / 360);
|
|
782
|
+
return Object.freeze({
|
|
783
|
+
position: Object.freeze(position),
|
|
784
|
+
forward: Object.freeze(forward),
|
|
785
|
+
right: Object.freeze(right),
|
|
786
|
+
up: Object.freeze(up),
|
|
787
|
+
fovYDegrees,
|
|
788
|
+
aspect,
|
|
789
|
+
tanHalfFovY
|
|
790
|
+
});
|
|
791
|
+
}
|
|
792
|
+
function estimateWavefrontPathTracingMemory(options = {}) {
|
|
793
|
+
const tilePixelCapacity = readPositiveInteger(
|
|
794
|
+
"tilePixelCapacity",
|
|
795
|
+
options.tilePixelCapacity,
|
|
796
|
+
DEFAULT_TILE_SIZE * DEFAULT_TILE_SIZE
|
|
797
|
+
);
|
|
798
|
+
const sceneObjectCapacity = readPositiveInteger(
|
|
799
|
+
"sceneObjectCapacity",
|
|
800
|
+
options.sceneObjectCapacity,
|
|
801
|
+
DEFAULT_SCENE_OBJECT_CAPACITY
|
|
802
|
+
);
|
|
803
|
+
const triangleCapacity = readNonNegativeInteger("triangleCapacity", options.triangleCapacity, 0);
|
|
804
|
+
const bvhNodeCapacity = readNonNegativeInteger("bvhNodeCapacity", options.bvhNodeCapacity, 0);
|
|
805
|
+
const bvhLeafSortCapacity = readNonNegativeInteger(
|
|
806
|
+
"bvhLeafSortCapacity",
|
|
807
|
+
options.bvhLeafSortCapacity,
|
|
808
|
+
0
|
|
809
|
+
);
|
|
810
|
+
const emissiveTriangleCapacity = readNonNegativeInteger(
|
|
811
|
+
"emissiveTriangleCapacity",
|
|
812
|
+
options.emissiveTriangleCapacity,
|
|
813
|
+
0
|
|
814
|
+
);
|
|
815
|
+
const queueBytes = tilePixelCapacity * RAY_RECORD_BYTES;
|
|
816
|
+
const hitBytes = tilePixelCapacity * HIT_RECORD_BYTES;
|
|
817
|
+
const accumulationBytes = tilePixelCapacity * ACCUMULATION_RECORD_BYTES;
|
|
818
|
+
const sceneObjectBytes = sceneObjectCapacity * SCENE_OBJECT_RECORD_BYTES;
|
|
819
|
+
const triangleBytes = triangleCapacity * TRIANGLE_RECORD_BYTES;
|
|
820
|
+
const bvhNodeBytes = bvhNodeCapacity * BVH_NODE_RECORD_BYTES;
|
|
821
|
+
const bvhLeafReferenceBytes = bvhLeafSortCapacity * BVH_LEAF_REF_RECORD_BYTES;
|
|
822
|
+
const emissiveTriangleMetadataBytes = emissiveTriangleCapacity * BVH_NODE_RECORD_BYTES;
|
|
823
|
+
return Object.freeze({
|
|
824
|
+
queueBytes,
|
|
825
|
+
queuePairBytes: queueBytes * 2,
|
|
826
|
+
hitBytes,
|
|
827
|
+
accumulationBytes,
|
|
828
|
+
sceneObjectBytes,
|
|
829
|
+
triangleBytes,
|
|
830
|
+
bvhNodeBytes,
|
|
831
|
+
bvhLeafReferenceBytes,
|
|
832
|
+
emissiveTriangleMetadataBytes,
|
|
833
|
+
configBytes: CONFIG_BUFFER_BYTES,
|
|
834
|
+
counterBytes: COUNTER_BUFFER_BYTES,
|
|
835
|
+
totalHotBufferBytes: queueBytes * 2 + hitBytes + accumulationBytes + sceneObjectBytes + triangleBytes + bvhNodeBytes + bvhLeafReferenceBytes + emissiveTriangleMetadataBytes + CONFIG_BUFFER_BYTES + COUNTER_BUFFER_BYTES
|
|
836
|
+
});
|
|
837
|
+
}
|
|
838
|
+
function createWavefrontPathTracingComputeConfig(options = {}) {
|
|
839
|
+
assertAnalyticDisplayQualityPolicy(options);
|
|
840
|
+
const accelerationBuildMode = resolveAccelerationBuildMode(options);
|
|
841
|
+
const canvas = options.canvas;
|
|
842
|
+
const width = readPositiveInteger("width", options.width, getCanvasDimension(canvas, "width", DEFAULT_WIDTH));
|
|
843
|
+
const height = readPositiveInteger("height", options.height, getCanvasDimension(canvas, "height", DEFAULT_HEIGHT));
|
|
844
|
+
const maxDepth = clamp(readPositiveInteger("maxDepth", options.maxDepth, DEFAULT_MAX_DEPTH), 1, 16);
|
|
845
|
+
const tileSize = clamp(readPositiveInteger("tileSize", options.tileSize, DEFAULT_TILE_SIZE), 16, 512);
|
|
846
|
+
const samplesPerPixel = clamp(
|
|
847
|
+
readPositiveInteger("samplesPerPixel", options.samplesPerPixel, DEFAULT_SAMPLES_PER_PIXEL),
|
|
848
|
+
1,
|
|
849
|
+
64
|
|
850
|
+
);
|
|
851
|
+
const tilePixelCapacity = readPositiveInteger(
|
|
852
|
+
"tilePixelCapacity",
|
|
853
|
+
options.tilePixelCapacity,
|
|
854
|
+
tileSize * tileSize
|
|
855
|
+
);
|
|
856
|
+
const meshes = normalizeMeshes(options);
|
|
857
|
+
const meshSourceShape = estimateMeshSourceShape(meshes);
|
|
858
|
+
const gpuMeshSource = meshes.length > 0 ? createWavefrontGpuMeshSource(meshes) : createWavefrontGpuMeshSource([]);
|
|
859
|
+
const meshAcceleration = accelerationBuildMode === "cpu-debug" ? createWavefrontMeshAcceleration(meshes) : Object.freeze({ nodes: Object.freeze([]), triangles: Object.freeze([]) });
|
|
860
|
+
const emissiveTriangleIndices = createWavefrontEmissiveTriangleIndexSource(
|
|
861
|
+
meshes,
|
|
862
|
+
options.emissiveTriangleCapacity
|
|
863
|
+
);
|
|
864
|
+
const triangleCount = accelerationBuildMode === "gpu" ? meshSourceShape.triangleCount : meshAcceleration.triangles.length;
|
|
865
|
+
const bvhNodeCount = accelerationBuildMode === "gpu" ? estimateBinaryBvhNodeCapacity(triangleCount) : meshAcceleration.nodes.length;
|
|
866
|
+
const sceneObjects = Object.freeze(
|
|
867
|
+
normalizeSceneObjects(options.sceneObjects, meshes.length === 0)
|
|
868
|
+
);
|
|
869
|
+
const sceneObjectCapacity = Math.max(
|
|
870
|
+
sceneObjects.length,
|
|
871
|
+
readPositiveInteger("sceneObjectCapacity", options.sceneObjectCapacity, DEFAULT_SCENE_OBJECT_CAPACITY)
|
|
872
|
+
);
|
|
873
|
+
const triangleCapacity = Math.max(
|
|
874
|
+
triangleCount,
|
|
875
|
+
readNonNegativeInteger("triangleCapacity", options.triangleCapacity, triangleCount)
|
|
876
|
+
);
|
|
877
|
+
const bvhNodeCapacity = Math.max(
|
|
878
|
+
accelerationBuildMode === "gpu" ? estimateBinaryBvhNodeCapacity(triangleCount) : bvhNodeCount,
|
|
879
|
+
readNonNegativeInteger(
|
|
880
|
+
"bvhNodeCapacity",
|
|
881
|
+
options.bvhNodeCapacity,
|
|
882
|
+
accelerationBuildMode === "gpu" ? estimateBinaryBvhNodeCapacity(triangleCount) : bvhNodeCount
|
|
883
|
+
)
|
|
884
|
+
);
|
|
885
|
+
const bvhLeafSortCapacity = accelerationBuildMode === "gpu" ? estimateBvhLeafSortCapacity(triangleCount) : 0;
|
|
886
|
+
const bvhSortStages = accelerationBuildMode === "gpu" ? createWavefrontBvhSortStages(triangleCount) : Object.freeze([]);
|
|
887
|
+
const bvhBuildLevels = accelerationBuildMode === "gpu" ? createWavefrontBvhBuildLevels(triangleCount) : Object.freeze([]);
|
|
888
|
+
const camera = resolveCamera(options.camera, width, height);
|
|
889
|
+
const environmentColor = Object.freeze(asColor(options.environmentColor, DEFAULT_ENVIRONMENT_COLOR));
|
|
890
|
+
const ambientColor = Object.freeze(asColor(options.ambientColor, DEFAULT_AMBIENT_COLOR));
|
|
891
|
+
const environmentLighting = resolveEnvironmentLighting(
|
|
892
|
+
options.environmentLighting,
|
|
893
|
+
environmentColor,
|
|
894
|
+
ambientColor
|
|
895
|
+
);
|
|
896
|
+
return Object.freeze({
|
|
897
|
+
width,
|
|
898
|
+
height,
|
|
899
|
+
maxDepth,
|
|
900
|
+
tileSize,
|
|
901
|
+
samplesPerPixel,
|
|
902
|
+
tilePixelCapacity,
|
|
903
|
+
sceneObjects,
|
|
904
|
+
sceneObjectCount: sceneObjects.length,
|
|
905
|
+
sceneObjectCapacity,
|
|
906
|
+
accelerationBuildMode,
|
|
907
|
+
gpuAccelerationBuildRequired: accelerationBuildMode === "gpu" && triangleCount > 0,
|
|
908
|
+
gpuMeshSource,
|
|
909
|
+
meshAcceleration,
|
|
910
|
+
emissiveTriangleIndices,
|
|
911
|
+
emissiveTriangleCount: emissiveTriangleIndices.count,
|
|
912
|
+
emissiveTriangleCapacity: emissiveTriangleIndices.capacity,
|
|
913
|
+
triangleCount,
|
|
914
|
+
triangleCapacity,
|
|
915
|
+
bvhNodeCount,
|
|
916
|
+
bvhNodeCapacity,
|
|
917
|
+
bvhLeafSortCapacity,
|
|
918
|
+
bvhSortStages,
|
|
919
|
+
bvhBuildLevels,
|
|
920
|
+
camera,
|
|
921
|
+
environmentColor: environmentLighting.environmentColor,
|
|
922
|
+
ambientColor: environmentLighting.ambientColor,
|
|
923
|
+
environmentLighting,
|
|
924
|
+
displayQuality: options.displayQuality === true,
|
|
925
|
+
requiresMeshBvhForDisplayQuality: true,
|
|
926
|
+
denoise: options.denoise !== false,
|
|
927
|
+
frameIndex: readNonNegativeInteger("frameIndex", options.frameIndex, 0),
|
|
928
|
+
memory: estimateWavefrontPathTracingMemory({
|
|
929
|
+
tilePixelCapacity,
|
|
930
|
+
sceneObjectCapacity,
|
|
931
|
+
triangleCapacity,
|
|
932
|
+
bvhNodeCapacity,
|
|
933
|
+
bvhLeafSortCapacity,
|
|
934
|
+
emissiveTriangleCapacity: emissiveTriangleIndices.capacity
|
|
935
|
+
})
|
|
936
|
+
});
|
|
937
|
+
}
|
|
938
|
+
function supportsWavefrontPathTracingCompute(options = {}) {
|
|
939
|
+
const navigatorRef = options.navigator ?? globalThis.navigator;
|
|
940
|
+
return typeof navigatorRef?.gpu?.requestAdapter === "function";
|
|
941
|
+
}
|
|
942
|
+
function getGpuUsageConstants() {
|
|
943
|
+
if (typeof GPUBufferUsage === "undefined" || typeof GPUTextureUsage === "undefined" || typeof GPUShaderStage === "undefined") {
|
|
944
|
+
throw new Error("WebGPU runtime unavailable. Required GPU constants are missing.");
|
|
945
|
+
}
|
|
946
|
+
return {
|
|
947
|
+
buffer: GPUBufferUsage,
|
|
948
|
+
texture: GPUTextureUsage,
|
|
949
|
+
shader: GPUShaderStage,
|
|
950
|
+
map: typeof GPUMapMode === "undefined" ? null : GPUMapMode
|
|
951
|
+
};
|
|
952
|
+
}
|
|
953
|
+
function resolveCanvas(canvasOrSelector, documentRef = globalThis.document) {
|
|
954
|
+
if (typeof canvasOrSelector === "string") {
|
|
955
|
+
const resolved = documentRef?.querySelector?.(canvasOrSelector);
|
|
956
|
+
if (!resolved) {
|
|
957
|
+
throw new Error(`Unable to find canvas for selector: ${canvasOrSelector}`);
|
|
958
|
+
}
|
|
959
|
+
return resolved;
|
|
960
|
+
}
|
|
961
|
+
if (canvasOrSelector?.getContext) {
|
|
962
|
+
return canvasOrSelector;
|
|
963
|
+
}
|
|
964
|
+
const fallback = documentRef?.querySelector?.("canvas[data-plasius-wavefront-path-tracing]");
|
|
965
|
+
if (!fallback) {
|
|
966
|
+
throw new Error("A canvas is required for WebGPU wavefront path tracing.");
|
|
967
|
+
}
|
|
968
|
+
return fallback;
|
|
969
|
+
}
|
|
970
|
+
function writeVec4(floatView, byteOffset, value) {
|
|
971
|
+
const index = byteOffset / 4;
|
|
972
|
+
floatView[index] = value[0] ?? 0;
|
|
973
|
+
floatView[index + 1] = value[1] ?? 0;
|
|
974
|
+
floatView[index + 2] = value[2] ?? 0;
|
|
975
|
+
floatView[index + 3] = value[3] ?? 0;
|
|
976
|
+
}
|
|
977
|
+
function packWavefrontSceneObjects(sceneObjects, capacity = sceneObjects.length) {
|
|
978
|
+
const normalized = Array.isArray(sceneObjects) && sceneObjects.length === 0 ? [] : normalizeSceneObjects(sceneObjects);
|
|
979
|
+
if (normalized.length > capacity) {
|
|
980
|
+
throw new Error(
|
|
981
|
+
`Scene object capacity ${capacity} is too small for ${normalized.length} objects.`
|
|
982
|
+
);
|
|
983
|
+
}
|
|
984
|
+
const bytes = new ArrayBuffer(Math.max(1, capacity) * SCENE_OBJECT_RECORD_BYTES);
|
|
985
|
+
const uintView = new Uint32Array(bytes);
|
|
986
|
+
const floatView = new Float32Array(bytes);
|
|
987
|
+
normalized.forEach((object, index) => {
|
|
988
|
+
const byteOffset = index * SCENE_OBJECT_RECORD_BYTES;
|
|
989
|
+
const u32 = byteOffset / 4;
|
|
990
|
+
uintView[u32] = object.kind;
|
|
991
|
+
uintView[u32 + 1] = object.id;
|
|
992
|
+
uintView[u32 + 2] = object.materialKind;
|
|
993
|
+
uintView[u32 + 3] = object.flags;
|
|
994
|
+
writeVec4(floatView, byteOffset + 16, [...object.center, 0]);
|
|
995
|
+
writeVec4(floatView, byteOffset + 32, [...object.halfExtent, 0]);
|
|
996
|
+
writeVec4(floatView, byteOffset + 48, object.color);
|
|
997
|
+
writeVec4(floatView, byteOffset + 64, object.emission);
|
|
998
|
+
writeVec4(floatView, byteOffset + 80, [
|
|
999
|
+
object.roughness,
|
|
1000
|
+
object.metallic,
|
|
1001
|
+
object.opacity,
|
|
1002
|
+
object.ior
|
|
1003
|
+
]);
|
|
1004
|
+
});
|
|
1005
|
+
return Object.freeze({
|
|
1006
|
+
buffer: bytes,
|
|
1007
|
+
objects: Object.freeze(normalized),
|
|
1008
|
+
count: normalized.length,
|
|
1009
|
+
capacity
|
|
1010
|
+
});
|
|
1011
|
+
}
|
|
1012
|
+
function packWavefrontTriangles(triangles, capacity = triangles.length) {
|
|
1013
|
+
if (triangles.length > capacity) {
|
|
1014
|
+
throw new Error(`Triangle capacity ${capacity} is too small for ${triangles.length} triangles.`);
|
|
1015
|
+
}
|
|
1016
|
+
const bytes = new ArrayBuffer(Math.max(1, capacity) * TRIANGLE_RECORD_BYTES);
|
|
1017
|
+
const uintView = new Uint32Array(bytes);
|
|
1018
|
+
const floatView = new Float32Array(bytes);
|
|
1019
|
+
triangles.forEach((triangle, index) => {
|
|
1020
|
+
const byteOffset = index * TRIANGLE_RECORD_BYTES;
|
|
1021
|
+
const u32 = byteOffset / 4;
|
|
1022
|
+
uintView[u32] = triangle.triangleId;
|
|
1023
|
+
uintView[u32 + 1] = triangle.meshId;
|
|
1024
|
+
uintView[u32 + 2] = triangle.materialKind;
|
|
1025
|
+
uintView[u32 + 3] = triangle.flags;
|
|
1026
|
+
uintView[u32 + 4] = triangle.materialRefId;
|
|
1027
|
+
uintView[u32 + 5] = triangle.mediumRefId;
|
|
1028
|
+
uintView[u32 + 6] = 0;
|
|
1029
|
+
uintView[u32 + 7] = 0;
|
|
1030
|
+
writeVec4(floatView, byteOffset + 32, [...triangle.v0, 0]);
|
|
1031
|
+
writeVec4(floatView, byteOffset + 48, [...triangle.v1, 0]);
|
|
1032
|
+
writeVec4(floatView, byteOffset + 64, [...triangle.v2, 0]);
|
|
1033
|
+
writeVec4(floatView, byteOffset + 80, [...triangle.n0, 0]);
|
|
1034
|
+
writeVec4(floatView, byteOffset + 96, [...triangle.n1, 0]);
|
|
1035
|
+
writeVec4(floatView, byteOffset + 112, [...triangle.n2, 0]);
|
|
1036
|
+
writeVec4(floatView, byteOffset + 128, [...triangle.uv0, ...triangle.uv1]);
|
|
1037
|
+
writeVec4(floatView, byteOffset + 144, [...triangle.uv2, 0, 0]);
|
|
1038
|
+
writeVec4(floatView, byteOffset + 160, triangle.color);
|
|
1039
|
+
writeVec4(floatView, byteOffset + 176, triangle.emission);
|
|
1040
|
+
writeVec4(floatView, byteOffset + 192, triangle.material);
|
|
1041
|
+
});
|
|
1042
|
+
return Object.freeze({
|
|
1043
|
+
buffer: bytes,
|
|
1044
|
+
triangles: Object.freeze(triangles),
|
|
1045
|
+
count: triangles.length,
|
|
1046
|
+
capacity
|
|
1047
|
+
});
|
|
1048
|
+
}
|
|
1049
|
+
function packWavefrontBvhNodes(nodes, capacity = nodes.length) {
|
|
1050
|
+
if (nodes.length > capacity) {
|
|
1051
|
+
throw new Error(`BVH node capacity ${capacity} is too small for ${nodes.length} nodes.`);
|
|
1052
|
+
}
|
|
1053
|
+
const bytes = new ArrayBuffer(Math.max(1, capacity) * BVH_NODE_RECORD_BYTES);
|
|
1054
|
+
const uintView = new Uint32Array(bytes);
|
|
1055
|
+
const floatView = new Float32Array(bytes);
|
|
1056
|
+
nodes.forEach((node, index) => {
|
|
1057
|
+
const byteOffset = index * BVH_NODE_RECORD_BYTES;
|
|
1058
|
+
const u32 = byteOffset / 4;
|
|
1059
|
+
writeVec4(floatView, byteOffset, [...node.bounds.min, 0]);
|
|
1060
|
+
writeVec4(floatView, byteOffset + 16, [...node.bounds.max, 0]);
|
|
1061
|
+
uintView[u32 + 8] = node.triangleCount > 0 ? node.firstTriangle : node.leftChild;
|
|
1062
|
+
uintView[u32 + 9] = node.triangleCount;
|
|
1063
|
+
uintView[u32 + 10] = node.rightChild;
|
|
1064
|
+
uintView[u32 + 11] = 0;
|
|
1065
|
+
});
|
|
1066
|
+
return Object.freeze({
|
|
1067
|
+
buffer: bytes,
|
|
1068
|
+
nodes: Object.freeze(nodes),
|
|
1069
|
+
count: nodes.length,
|
|
1070
|
+
capacity
|
|
1071
|
+
});
|
|
1072
|
+
}
|
|
1073
|
+
function createConfigPayload(config, tile, frameIndex, buildRange = {}) {
|
|
1074
|
+
const bytes = new ArrayBuffer(CONFIG_BUFFER_BYTES);
|
|
1075
|
+
const data = new DataView(bytes);
|
|
1076
|
+
const floatView = new Float32Array(bytes);
|
|
1077
|
+
const sampleIndex = buildRange.sampleIndex ?? 0;
|
|
1078
|
+
const sampleWeight = buildRange.sampleWeight ?? 1;
|
|
1079
|
+
data.setUint32(0, config.width, true);
|
|
1080
|
+
data.setUint32(4, config.height, true);
|
|
1081
|
+
data.setUint32(8, tile.x, true);
|
|
1082
|
+
data.setUint32(12, tile.y, true);
|
|
1083
|
+
data.setUint32(16, tile.width, true);
|
|
1084
|
+
data.setUint32(20, tile.height, true);
|
|
1085
|
+
data.setUint32(24, tile.width * tile.height, true);
|
|
1086
|
+
data.setUint32(28, config.maxDepth, true);
|
|
1087
|
+
data.setUint32(32, config.sceneObjectCount, true);
|
|
1088
|
+
data.setUint32(36, frameIndex, true);
|
|
1089
|
+
data.setUint32(40, config.denoise ? 1 : 0, true);
|
|
1090
|
+
data.setUint32(44, config.triangleCount, true);
|
|
1091
|
+
data.setUint32(48, config.bvhNodeCount, true);
|
|
1092
|
+
data.setUint32(52, config.displayQuality ? 1 : 0, true);
|
|
1093
|
+
data.setUint32(56, config.gpuMeshSource.meshes.count, true);
|
|
1094
|
+
data.setUint32(60, config.bvhNodeCapacity, true);
|
|
1095
|
+
writeVec4(floatView, 64, [...config.camera.position, 1]);
|
|
1096
|
+
writeVec4(floatView, 80, [...config.camera.forward, 0]);
|
|
1097
|
+
writeVec4(floatView, 96, [...config.camera.right, 0]);
|
|
1098
|
+
writeVec4(floatView, 112, [...config.camera.up, 0]);
|
|
1099
|
+
writeVec4(floatView, 128, [
|
|
1100
|
+
config.camera.tanHalfFovY,
|
|
1101
|
+
config.camera.aspect,
|
|
1102
|
+
sampleWeight,
|
|
1103
|
+
sampleIndex
|
|
1104
|
+
]);
|
|
1105
|
+
writeVec4(floatView, 144, config.environmentColor);
|
|
1106
|
+
writeVec4(floatView, 160, config.ambientColor);
|
|
1107
|
+
writeVec4(floatView, 176, config.environmentLighting.horizonColor);
|
|
1108
|
+
writeVec4(floatView, 192, config.environmentLighting.zenithColor);
|
|
1109
|
+
writeVec4(floatView, 208, [
|
|
1110
|
+
...config.environmentLighting.sunDirection,
|
|
1111
|
+
config.environmentLighting.intensity
|
|
1112
|
+
]);
|
|
1113
|
+
writeVec4(floatView, 224, config.environmentLighting.sunColor);
|
|
1114
|
+
data.setUint32(240, buildRange.start ?? 0, true);
|
|
1115
|
+
data.setUint32(244, buildRange.count ?? 0, true);
|
|
1116
|
+
data.setUint32(248, buildRange.sortItemCount ?? 0, true);
|
|
1117
|
+
data.setUint32(252, config.emissiveTriangleCount ?? 0, true);
|
|
1118
|
+
return bytes;
|
|
1119
|
+
}
|
|
1120
|
+
function createTiles(width, height, tileSize) {
|
|
1121
|
+
const tiles = [];
|
|
1122
|
+
for (let y = 0; y < height; y += tileSize) {
|
|
1123
|
+
for (let x = 0; x < width; x += tileSize) {
|
|
1124
|
+
tiles.push(
|
|
1125
|
+
Object.freeze({
|
|
1126
|
+
x,
|
|
1127
|
+
y,
|
|
1128
|
+
width: Math.min(tileSize, width - x),
|
|
1129
|
+
height: Math.min(tileSize, height - y)
|
|
1130
|
+
})
|
|
1131
|
+
);
|
|
1132
|
+
}
|
|
1133
|
+
}
|
|
1134
|
+
return Object.freeze(tiles);
|
|
1135
|
+
}
|
|
1136
|
+
function clampTileSizeForDevice(config, device) {
|
|
1137
|
+
const limit = Number(device?.limits?.maxStorageBufferBindingSize);
|
|
1138
|
+
if (!Number.isFinite(limit) || limit <= 0) {
|
|
1139
|
+
return config.tileSize;
|
|
1140
|
+
}
|
|
1141
|
+
const maxPixelsByRay = Math.floor(limit / RAY_RECORD_BYTES);
|
|
1142
|
+
const maxPixelsByHit = Math.floor(limit / HIT_RECORD_BYTES);
|
|
1143
|
+
const maxPixels = Math.max(256, Math.min(maxPixelsByRay, maxPixelsByHit));
|
|
1144
|
+
if (config.tilePixelCapacity <= maxPixels) {
|
|
1145
|
+
return config.tileSize;
|
|
1146
|
+
}
|
|
1147
|
+
return Math.max(16, Math.floor(Math.sqrt(maxPixels)));
|
|
1148
|
+
}
|
|
1149
|
+
function createBuffer(device, usage, size, label) {
|
|
1150
|
+
return device.createBuffer({
|
|
1151
|
+
label,
|
|
1152
|
+
size: Math.max(4, size),
|
|
1153
|
+
usage
|
|
1154
|
+
});
|
|
1155
|
+
}
|
|
1156
|
+
function alignTo(value, alignment) {
|
|
1157
|
+
const resolvedAlignment = Math.max(1, alignment);
|
|
1158
|
+
return Math.ceil(value / resolvedAlignment) * resolvedAlignment;
|
|
1159
|
+
}
|
|
1160
|
+
async function getPipelineDiagnostics(shaderModule) {
|
|
1161
|
+
if (typeof shaderModule?.compilationInfo !== "function") {
|
|
1162
|
+
return "";
|
|
1163
|
+
}
|
|
1164
|
+
try {
|
|
1165
|
+
const info = await shaderModule.compilationInfo();
|
|
1166
|
+
const messages = info.messages ?? [];
|
|
1167
|
+
if (messages.length === 0) {
|
|
1168
|
+
return "";
|
|
1169
|
+
}
|
|
1170
|
+
return messages.map((message) => {
|
|
1171
|
+
const line = message.lineNum ?? "?";
|
|
1172
|
+
const column = message.linePos ?? "?";
|
|
1173
|
+
return `line ${line}:${column} ${message.message}`;
|
|
1174
|
+
}).join("\n");
|
|
1175
|
+
} catch {
|
|
1176
|
+
return "";
|
|
1177
|
+
}
|
|
1178
|
+
}
|
|
1179
|
+
async function createComputePipeline(device, shaderModule, layout, entryPoint, label) {
|
|
1180
|
+
const descriptor = {
|
|
1181
|
+
label,
|
|
1182
|
+
layout,
|
|
1183
|
+
compute: {
|
|
1184
|
+
module: shaderModule,
|
|
1185
|
+
entryPoint
|
|
1186
|
+
}
|
|
1187
|
+
};
|
|
1188
|
+
try {
|
|
1189
|
+
if (typeof device.createComputePipelineAsync === "function") {
|
|
1190
|
+
return await device.createComputePipelineAsync(descriptor);
|
|
1191
|
+
}
|
|
1192
|
+
return device.createComputePipeline(descriptor);
|
|
1193
|
+
} catch (error) {
|
|
1194
|
+
const diagnostics = await getPipelineDiagnostics(shaderModule);
|
|
1195
|
+
const suffix = diagnostics ? `
|
|
1196
|
+
${diagnostics}` : "";
|
|
1197
|
+
throw new Error(`WGSL compilation failed for ${label}: ${error.message}${suffix}`, {
|
|
1198
|
+
cause: error
|
|
1199
|
+
});
|
|
1200
|
+
}
|
|
1201
|
+
}
|
|
1202
|
+
async function createRenderPipeline(device, descriptor) {
|
|
1203
|
+
if (typeof device.createRenderPipelineAsync === "function") {
|
|
1204
|
+
return device.createRenderPipelineAsync(descriptor);
|
|
1205
|
+
}
|
|
1206
|
+
return device.createRenderPipeline(descriptor);
|
|
1207
|
+
}
|
|
1208
|
+
var WAVEFRONT_COMPUTE_WGSL = `
|
|
1209
|
+
const RAY_FLAG_GUIDED_EMISSIVE: u32 = 1u;
|
|
1210
|
+
|
|
1211
|
+
struct RayRecord {
|
|
1212
|
+
rayId: u32,
|
|
1213
|
+
parentRayId: u32,
|
|
1214
|
+
sourcePixelId: u32,
|
|
1215
|
+
sampleId: u32,
|
|
1216
|
+
bounce: u32,
|
|
1217
|
+
mediumRefId: u32,
|
|
1218
|
+
flags: u32,
|
|
1219
|
+
pad0: u32,
|
|
1220
|
+
origin: vec4<f32>,
|
|
1221
|
+
direction: vec4<f32>,
|
|
1222
|
+
throughput: vec4<f32>,
|
|
1223
|
+
};
|
|
1224
|
+
|
|
1225
|
+
struct HitRecord {
|
|
1226
|
+
rayId: u32,
|
|
1227
|
+
sourcePixelId: u32,
|
|
1228
|
+
hitType: u32,
|
|
1229
|
+
objectId: u32,
|
|
1230
|
+
materialKind: u32,
|
|
1231
|
+
frontFace: u32,
|
|
1232
|
+
primitiveId: u32,
|
|
1233
|
+
materialRefId: u32,
|
|
1234
|
+
mediumRefId: u32,
|
|
1235
|
+
pad0: u32,
|
|
1236
|
+
pad1: u32,
|
|
1237
|
+
pad2: u32,
|
|
1238
|
+
distance: f32,
|
|
1239
|
+
pad3: vec3<f32>,
|
|
1240
|
+
position: vec4<f32>,
|
|
1241
|
+
geometricNormal: vec4<f32>,
|
|
1242
|
+
shadingNormal: vec4<f32>,
|
|
1243
|
+
barycentric: vec4<f32>,
|
|
1244
|
+
uv: vec4<f32>,
|
|
1245
|
+
color: vec4<f32>,
|
|
1246
|
+
emission: vec4<f32>,
|
|
1247
|
+
material: vec4<f32>,
|
|
1248
|
+
};
|
|
1249
|
+
|
|
1250
|
+
struct SceneObject {
|
|
1251
|
+
kind: u32,
|
|
1252
|
+
objectId: u32,
|
|
1253
|
+
materialKind: u32,
|
|
1254
|
+
flags: u32,
|
|
1255
|
+
center: vec4<f32>,
|
|
1256
|
+
halfExtent: vec4<f32>,
|
|
1257
|
+
color: vec4<f32>,
|
|
1258
|
+
emission: vec4<f32>,
|
|
1259
|
+
material: vec4<f32>,
|
|
1260
|
+
};
|
|
1261
|
+
|
|
1262
|
+
struct TriangleRecord {
|
|
1263
|
+
triangleId: u32,
|
|
1264
|
+
meshId: u32,
|
|
1265
|
+
materialKind: u32,
|
|
1266
|
+
flags: u32,
|
|
1267
|
+
materialRefId: u32,
|
|
1268
|
+
mediumRefId: u32,
|
|
1269
|
+
pad0: u32,
|
|
1270
|
+
pad1: u32,
|
|
1271
|
+
v0: vec4<f32>,
|
|
1272
|
+
v1: vec4<f32>,
|
|
1273
|
+
v2: vec4<f32>,
|
|
1274
|
+
n0: vec4<f32>,
|
|
1275
|
+
n1: vec4<f32>,
|
|
1276
|
+
n2: vec4<f32>,
|
|
1277
|
+
uv0uv1: vec4<f32>,
|
|
1278
|
+
uv2Pad: vec4<f32>,
|
|
1279
|
+
color: vec4<f32>,
|
|
1280
|
+
emission: vec4<f32>,
|
|
1281
|
+
material: vec4<f32>,
|
|
1282
|
+
};
|
|
1283
|
+
|
|
1284
|
+
struct BvhNode {
|
|
1285
|
+
boundsMin: vec4<f32>,
|
|
1286
|
+
boundsMax: vec4<f32>,
|
|
1287
|
+
childOrFirst: u32,
|
|
1288
|
+
triangleCount: u32,
|
|
1289
|
+
rightChild: u32,
|
|
1290
|
+
pad0: u32,
|
|
1291
|
+
};
|
|
1292
|
+
|
|
1293
|
+
struct BvhLeafRef {
|
|
1294
|
+
key: u32,
|
|
1295
|
+
triangleIndex: u32,
|
|
1296
|
+
pad0: u32,
|
|
1297
|
+
pad1: u32,
|
|
1298
|
+
};
|
|
1299
|
+
|
|
1300
|
+
struct ScatterResult {
|
|
1301
|
+
direction: vec4<f32>,
|
|
1302
|
+
flags: u32,
|
|
1303
|
+
pad0: u32,
|
|
1304
|
+
pad1: u32,
|
|
1305
|
+
pad2: u32,
|
|
1306
|
+
};
|
|
1307
|
+
|
|
1308
|
+
struct MeshVertex {
|
|
1309
|
+
position: vec4<f32>,
|
|
1310
|
+
normal: vec4<f32>,
|
|
1311
|
+
uv: vec4<f32>,
|
|
1312
|
+
};
|
|
1313
|
+
|
|
1314
|
+
struct MeshRange {
|
|
1315
|
+
meshId: u32,
|
|
1316
|
+
materialKind: u32,
|
|
1317
|
+
flags: u32,
|
|
1318
|
+
materialRefId: u32,
|
|
1319
|
+
mediumRefId: u32,
|
|
1320
|
+
firstIndex: u32,
|
|
1321
|
+
indexCount: u32,
|
|
1322
|
+
firstTriangle: u32,
|
|
1323
|
+
triangleCount: u32,
|
|
1324
|
+
firstVertex: u32,
|
|
1325
|
+
vertexCount: u32,
|
|
1326
|
+
pad0: u32,
|
|
1327
|
+
color: vec4<f32>,
|
|
1328
|
+
emission: vec4<f32>,
|
|
1329
|
+
material: vec4<f32>,
|
|
1330
|
+
};
|
|
1331
|
+
|
|
1332
|
+
struct FrameConfig {
|
|
1333
|
+
canvasWidth: u32,
|
|
1334
|
+
canvasHeight: u32,
|
|
1335
|
+
tileX: u32,
|
|
1336
|
+
tileY: u32,
|
|
1337
|
+
tileWidth: u32,
|
|
1338
|
+
tileHeight: u32,
|
|
1339
|
+
tilePixelCount: u32,
|
|
1340
|
+
maxDepth: u32,
|
|
1341
|
+
sceneObjectCount: u32,
|
|
1342
|
+
frameIndex: u32,
|
|
1343
|
+
denoise: u32,
|
|
1344
|
+
triangleCount: u32,
|
|
1345
|
+
bvhNodeCount: u32,
|
|
1346
|
+
displayQuality: u32,
|
|
1347
|
+
meshSourceCount: u32,
|
|
1348
|
+
bvhNodeCapacity: u32,
|
|
1349
|
+
cameraPosition: vec4<f32>,
|
|
1350
|
+
cameraForward: vec4<f32>,
|
|
1351
|
+
cameraRight: vec4<f32>,
|
|
1352
|
+
cameraUp: vec4<f32>,
|
|
1353
|
+
projectionAndSampling: vec4<f32>,
|
|
1354
|
+
environmentColor: vec4<f32>,
|
|
1355
|
+
ambientColor: vec4<f32>,
|
|
1356
|
+
environmentHorizonColor: vec4<f32>,
|
|
1357
|
+
environmentZenithColor: vec4<f32>,
|
|
1358
|
+
environmentSunDirectionIntensity: vec4<f32>,
|
|
1359
|
+
environmentSunColor: vec4<f32>,
|
|
1360
|
+
bvhBuildNodeStart: u32,
|
|
1361
|
+
bvhBuildNodeCount: u32,
|
|
1362
|
+
bvhSortItemCount: u32,
|
|
1363
|
+
emissiveTriangleCount: u32,
|
|
1364
|
+
};
|
|
1365
|
+
|
|
1366
|
+
struct Counters {
|
|
1367
|
+
activeCount: atomic<u32>,
|
|
1368
|
+
nextCount: atomic<u32>,
|
|
1369
|
+
terminatedCount: atomic<u32>,
|
|
1370
|
+
hitCount: atomic<u32>,
|
|
1371
|
+
};
|
|
1372
|
+
|
|
1373
|
+
struct Candidate {
|
|
1374
|
+
hit: u32,
|
|
1375
|
+
distance: f32,
|
|
1376
|
+
geometricNormal: vec3<f32>,
|
|
1377
|
+
shadingNormal: vec3<f32>,
|
|
1378
|
+
barycentric: vec3<f32>,
|
|
1379
|
+
uv: vec2<f32>,
|
|
1380
|
+
frontFace: u32,
|
|
1381
|
+
triangleIndex: u32,
|
|
1382
|
+
primitiveId: u32,
|
|
1383
|
+
materialRefId: u32,
|
|
1384
|
+
mediumRefId: u32,
|
|
1385
|
+
};
|
|
1386
|
+
|
|
1387
|
+
@group(0) @binding(0) var<storage, read_write> activeQueue: array<RayRecord>;
|
|
1388
|
+
@group(0) @binding(1) var<storage, read_write> nextQueue: array<RayRecord>;
|
|
1389
|
+
@group(0) @binding(2) var<storage, read_write> hits: array<HitRecord>;
|
|
1390
|
+
@group(0) @binding(3) var<storage, read_write> accumulation: array<vec4<f32>>;
|
|
1391
|
+
@group(0) @binding(4) var<storage, read> sceneObjects: array<SceneObject>;
|
|
1392
|
+
@group(0) @binding(5) var<uniform> config: FrameConfig;
|
|
1393
|
+
@group(0) @binding(6) var<storage, read_write> counters: Counters;
|
|
1394
|
+
@group(0) @binding(7) var outputImage: texture_storage_2d<rgba8unorm, write>;
|
|
1395
|
+
@group(0) @binding(8) var<storage, read_write> triangles: array<TriangleRecord>;
|
|
1396
|
+
@group(0) @binding(9) var<storage, read_write> bvhNodes: array<BvhNode>;
|
|
1397
|
+
@group(0) @binding(10) var<storage, read> meshVertices: array<MeshVertex>;
|
|
1398
|
+
@group(0) @binding(11) var<storage, read> meshIndices: array<u32>;
|
|
1399
|
+
@group(0) @binding(12) var<storage, read> meshRanges: array<MeshRange>;
|
|
1400
|
+
@group(0) @binding(13) var<storage, read_write> bvhLeafRefs: array<BvhLeafRef>;
|
|
1401
|
+
@group(0) @binding(14) var denoiseInputRadiance: texture_2d<f32>;
|
|
1402
|
+
@group(0) @binding(15) var denoisedRadianceImage: texture_storage_2d<rgba16float, write>;
|
|
1403
|
+
@group(0) @binding(16) var radianceImage: texture_storage_2d<rgba16float, write>;
|
|
1404
|
+
@group(0) @binding(17) var finalDenoiseInputRadiance: texture_2d<f32>;
|
|
1405
|
+
@group(0) @binding(18) var denoisedOutputImage: texture_storage_2d<rgba8unorm, write>;
|
|
1406
|
+
|
|
1407
|
+
fn hash_u32(value: u32) -> u32 {
|
|
1408
|
+
var x = value;
|
|
1409
|
+
x = ((x >> 16u) ^ x) * 0x45d9f3bu;
|
|
1410
|
+
x = ((x >> 16u) ^ x) * 0x45d9f3bu;
|
|
1411
|
+
x = (x >> 16u) ^ x;
|
|
1412
|
+
return x;
|
|
1413
|
+
}
|
|
1414
|
+
|
|
1415
|
+
fn mix_seed(pixelId: u32, sampleId: u32, bounce: u32, frameIndex: u32, dimension: u32) -> u32 {
|
|
1416
|
+
var x =
|
|
1417
|
+
(pixelId * 747796405u) ^
|
|
1418
|
+
(sampleId * 2891336453u) ^
|
|
1419
|
+
(bounce * 277803737u) ^
|
|
1420
|
+
(frameIndex * 1442695041u) ^
|
|
1421
|
+
(dimension * 1597334677u);
|
|
1422
|
+
x = x ^ (x >> 16u);
|
|
1423
|
+
x = x * 0x7feb352du;
|
|
1424
|
+
x = x ^ (x >> 15u);
|
|
1425
|
+
x = x * 0x846ca68bu;
|
|
1426
|
+
x = x ^ (x >> 16u);
|
|
1427
|
+
return x;
|
|
1428
|
+
}
|
|
1429
|
+
|
|
1430
|
+
fn random01(seed: u32) -> f32 {
|
|
1431
|
+
return f32(hash_u32(seed) & 0x00ffffffu) / 16777215.0;
|
|
1432
|
+
}
|
|
1433
|
+
|
|
1434
|
+
fn safe_normalize(value: vec3<f32>, fallback: vec3<f32>) -> vec3<f32> {
|
|
1435
|
+
let len = length(value);
|
|
1436
|
+
if (len <= 0.000001) {
|
|
1437
|
+
return fallback;
|
|
1438
|
+
}
|
|
1439
|
+
return value / len;
|
|
1440
|
+
}
|
|
1441
|
+
|
|
1442
|
+
fn saturate(value: f32) -> f32 {
|
|
1443
|
+
return clamp(value, 0.0, 1.0);
|
|
1444
|
+
}
|
|
1445
|
+
|
|
1446
|
+
fn environment_radiance(direction: vec3<f32>) -> vec3<f32> {
|
|
1447
|
+
let rayDirection = safe_normalize(direction, vec3<f32>(0.0, 1.0, 0.0));
|
|
1448
|
+
let upFactor = saturate(rayDirection.y * 0.5 + 0.5);
|
|
1449
|
+
let sunDirection = safe_normalize(
|
|
1450
|
+
config.environmentSunDirectionIntensity.xyz,
|
|
1451
|
+
vec3<f32>(0.0, 1.0, 0.0)
|
|
1452
|
+
);
|
|
1453
|
+
let sunGlow = pow(saturate(dot(rayDirection, sunDirection)), 192.0);
|
|
1454
|
+
let gradient =
|
|
1455
|
+
config.environmentHorizonColor.xyz * (1.0 - upFactor) +
|
|
1456
|
+
config.environmentZenithColor.xyz * upFactor;
|
|
1457
|
+
return (
|
|
1458
|
+
gradient +
|
|
1459
|
+
config.environmentSunColor.xyz * sunGlow
|
|
1460
|
+
) * max(config.environmentSunDirectionIntensity.w, 0.0001);
|
|
1461
|
+
}
|
|
1462
|
+
|
|
1463
|
+
fn default_mesh_range() -> MeshRange {
|
|
1464
|
+
return MeshRange(
|
|
1465
|
+
0u,
|
|
1466
|
+
0u,
|
|
1467
|
+
0u,
|
|
1468
|
+
0u,
|
|
1469
|
+
0u,
|
|
1470
|
+
0u,
|
|
1471
|
+
0u,
|
|
1472
|
+
0u,
|
|
1473
|
+
0u,
|
|
1474
|
+
0u,
|
|
1475
|
+
0u,
|
|
1476
|
+
0u,
|
|
1477
|
+
vec4<f32>(0.72, 0.72, 0.68, 1.0),
|
|
1478
|
+
vec4<f32>(0.0),
|
|
1479
|
+
vec4<f32>(0.72, 0.0, 1.0, 1.45)
|
|
1480
|
+
);
|
|
1481
|
+
}
|
|
1482
|
+
|
|
1483
|
+
fn mesh_range_for_triangle(triangleIndex: u32) -> MeshRange {
|
|
1484
|
+
var selected = default_mesh_range();
|
|
1485
|
+
for (var meshIndex = 0u; meshIndex < config.meshSourceCount; meshIndex = meshIndex + 1u) {
|
|
1486
|
+
let mesh = meshRanges[meshIndex];
|
|
1487
|
+
let triangleStart = mesh.firstTriangle;
|
|
1488
|
+
let triangleEnd = mesh.firstTriangle + mesh.triangleCount;
|
|
1489
|
+
if (triangleIndex >= triangleStart && triangleIndex < triangleEnd) {
|
|
1490
|
+
selected = mesh;
|
|
1491
|
+
break;
|
|
1492
|
+
}
|
|
1493
|
+
}
|
|
1494
|
+
return selected;
|
|
1495
|
+
}
|
|
1496
|
+
|
|
1497
|
+
fn node_bounds_min(left: BvhNode, right: BvhNode) -> vec3<f32> {
|
|
1498
|
+
return min(left.boundsMin.xyz, right.boundsMin.xyz);
|
|
1499
|
+
}
|
|
1500
|
+
|
|
1501
|
+
fn node_bounds_max(left: BvhNode, right: BvhNode) -> vec3<f32> {
|
|
1502
|
+
return max(left.boundsMax.xyz, right.boundsMax.xyz);
|
|
1503
|
+
}
|
|
1504
|
+
|
|
1505
|
+
fn ordered_float_key(value: f32) -> u32 {
|
|
1506
|
+
let bits = bitcast<u32>(value);
|
|
1507
|
+
let sign = bits & 0x80000000u;
|
|
1508
|
+
let mask = select(0x80000000u, 0xffffffffu, sign != 0u);
|
|
1509
|
+
return bits ^ mask;
|
|
1510
|
+
}
|
|
1511
|
+
|
|
1512
|
+
fn split_by_3(value: u32) -> u32 {
|
|
1513
|
+
var x = value & 0x000003ffu;
|
|
1514
|
+
x = (x | (x << 16u)) & 0x030000ffu;
|
|
1515
|
+
x = (x | (x << 8u)) & 0x0300f00fu;
|
|
1516
|
+
x = (x | (x << 4u)) & 0x030c30c3u;
|
|
1517
|
+
x = (x | (x << 2u)) & 0x09249249u;
|
|
1518
|
+
return x;
|
|
1519
|
+
}
|
|
1520
|
+
|
|
1521
|
+
fn morton_key_from_centroid(centroid: vec3<f32>) -> u32 {
|
|
1522
|
+
let x = (ordered_float_key(centroid.x) >> 12u) & 0x000003ffu;
|
|
1523
|
+
let y = (ordered_float_key(centroid.y) >> 12u) & 0x000003ffu;
|
|
1524
|
+
let z = (ordered_float_key(centroid.z) >> 12u) & 0x000003ffu;
|
|
1525
|
+
return (split_by_3(x) << 2u) | (split_by_3(y) << 1u) | split_by_3(z);
|
|
1526
|
+
}
|
|
1527
|
+
|
|
1528
|
+
fn leaf_ref_less(left: BvhLeafRef, right: BvhLeafRef) -> bool {
|
|
1529
|
+
if (left.key < right.key) {
|
|
1530
|
+
return true;
|
|
1531
|
+
}
|
|
1532
|
+
if (left.key > right.key) {
|
|
1533
|
+
return false;
|
|
1534
|
+
}
|
|
1535
|
+
return left.triangleIndex < right.triangleIndex;
|
|
1536
|
+
}
|
|
1537
|
+
|
|
1538
|
+
@compute @workgroup_size(64)
|
|
1539
|
+
fn prepareMeshTrianglesAndLeaves(@builtin(global_invocation_id) globalId: vec3<u32>) {
|
|
1540
|
+
let triangleIndex = globalId.x;
|
|
1541
|
+
if (triangleIndex >= config.triangleCount) {
|
|
1542
|
+
if (triangleIndex < config.bvhSortItemCount) {
|
|
1543
|
+
bvhLeafRefs[triangleIndex] = BvhLeafRef(0xffffffffu, 0xffffffffu, 0u, 0u);
|
|
1544
|
+
}
|
|
1545
|
+
return;
|
|
1546
|
+
}
|
|
1547
|
+
|
|
1548
|
+
let mesh = mesh_range_for_triangle(triangleIndex);
|
|
1549
|
+
let localTriangle = triangleIndex - mesh.firstTriangle;
|
|
1550
|
+
let indexOffset = mesh.firstIndex + localTriangle * 3u;
|
|
1551
|
+
let index0 = meshIndices[indexOffset];
|
|
1552
|
+
let index1 = meshIndices[indexOffset + 1u];
|
|
1553
|
+
let index2 = meshIndices[indexOffset + 2u];
|
|
1554
|
+
let vertex0 = meshVertices[index0];
|
|
1555
|
+
let vertex1 = meshVertices[index1];
|
|
1556
|
+
let vertex2 = meshVertices[index2];
|
|
1557
|
+
let edge1 = vertex1.position.xyz - vertex0.position.xyz;
|
|
1558
|
+
let edge2 = vertex2.position.xyz - vertex0.position.xyz;
|
|
1559
|
+
let centroid = (vertex0.position.xyz + vertex1.position.xyz + vertex2.position.xyz) / 3.0;
|
|
1560
|
+
let faceNormal = safe_normalize(cross(edge1, edge2), vec3<f32>(0.0, 1.0, 0.0));
|
|
1561
|
+
let n0 = select(faceNormal, safe_normalize(vertex0.normal.xyz, faceNormal), vertex0.normal.w > 0.5);
|
|
1562
|
+
let n1 = select(faceNormal, safe_normalize(vertex1.normal.xyz, faceNormal), vertex1.normal.w > 0.5);
|
|
1563
|
+
let n2 = select(faceNormal, safe_normalize(vertex2.normal.xyz, faceNormal), vertex2.normal.w > 0.5);
|
|
1564
|
+
let uv0 = select(vec2<f32>(0.0), vertex0.uv.xy, vertex0.uv.z > 0.5);
|
|
1565
|
+
let uv1 = select(vec2<f32>(0.0), vertex1.uv.xy, vertex1.uv.z > 0.5);
|
|
1566
|
+
let uv2 = select(vec2<f32>(0.0), vertex2.uv.xy, vertex2.uv.z > 0.5);
|
|
1567
|
+
|
|
1568
|
+
triangles[triangleIndex] = TriangleRecord(
|
|
1569
|
+
triangleIndex,
|
|
1570
|
+
mesh.meshId,
|
|
1571
|
+
mesh.materialKind,
|
|
1572
|
+
mesh.flags,
|
|
1573
|
+
mesh.materialRefId,
|
|
1574
|
+
mesh.mediumRefId,
|
|
1575
|
+
0u,
|
|
1576
|
+
0u,
|
|
1577
|
+
vec4<f32>(vertex0.position.xyz, 0.0),
|
|
1578
|
+
vec4<f32>(vertex1.position.xyz, 0.0),
|
|
1579
|
+
vec4<f32>(vertex2.position.xyz, 0.0),
|
|
1580
|
+
vec4<f32>(n0, 0.0),
|
|
1581
|
+
vec4<f32>(n1, 0.0),
|
|
1582
|
+
vec4<f32>(n2, 0.0),
|
|
1583
|
+
vec4<f32>(uv0, uv1),
|
|
1584
|
+
vec4<f32>(uv2, 0.0, 0.0),
|
|
1585
|
+
mesh.color,
|
|
1586
|
+
mesh.emission,
|
|
1587
|
+
mesh.material
|
|
1588
|
+
);
|
|
1589
|
+
|
|
1590
|
+
let leafBase = config.triangleCount - 1u;
|
|
1591
|
+
let nodeIndex = leafBase + triangleIndex;
|
|
1592
|
+
let boundsMin = min(vertex0.position.xyz, min(vertex1.position.xyz, vertex2.position.xyz));
|
|
1593
|
+
let boundsMax = max(vertex0.position.xyz, max(vertex1.position.xyz, vertex2.position.xyz));
|
|
1594
|
+
bvhLeafRefs[triangleIndex] = BvhLeafRef(
|
|
1595
|
+
morton_key_from_centroid(centroid),
|
|
1596
|
+
triangleIndex,
|
|
1597
|
+
0u,
|
|
1598
|
+
0u
|
|
1599
|
+
);
|
|
1600
|
+
bvhNodes[nodeIndex] = BvhNode(
|
|
1601
|
+
vec4<f32>(boundsMin, 0.0),
|
|
1602
|
+
vec4<f32>(boundsMax, 0.0),
|
|
1603
|
+
triangleIndex,
|
|
1604
|
+
1u,
|
|
1605
|
+
0u,
|
|
1606
|
+
0u
|
|
1607
|
+
);
|
|
1608
|
+
}
|
|
1609
|
+
|
|
1610
|
+
@compute @workgroup_size(64)
|
|
1611
|
+
fn sortBvhLeafRefs(@builtin(global_invocation_id) globalId: vec3<u32>) {
|
|
1612
|
+
let index = globalId.x;
|
|
1613
|
+
let sortCount = config.bvhSortItemCount;
|
|
1614
|
+
if (sortCount <= 1u || index >= sortCount) {
|
|
1615
|
+
return;
|
|
1616
|
+
}
|
|
1617
|
+
|
|
1618
|
+
let compareDistance = config.bvhBuildNodeStart;
|
|
1619
|
+
let sequenceSize = config.bvhBuildNodeCount;
|
|
1620
|
+
if (compareDistance == 0u || sequenceSize == 0u) {
|
|
1621
|
+
return;
|
|
1622
|
+
}
|
|
1623
|
+
|
|
1624
|
+
let partner = index ^ compareDistance;
|
|
1625
|
+
if (partner <= index || partner >= sortCount) {
|
|
1626
|
+
return;
|
|
1627
|
+
}
|
|
1628
|
+
|
|
1629
|
+
let left = bvhLeafRefs[index];
|
|
1630
|
+
let right = bvhLeafRefs[partner];
|
|
1631
|
+
let ascending = (index & sequenceSize) == 0u;
|
|
1632
|
+
let leftIsLess = leaf_ref_less(left, right);
|
|
1633
|
+
let rightIsLess = leaf_ref_less(right, left);
|
|
1634
|
+
let shouldSwap = select(leftIsLess, rightIsLess, ascending);
|
|
1635
|
+
if (shouldSwap) {
|
|
1636
|
+
bvhLeafRefs[index] = right;
|
|
1637
|
+
bvhLeafRefs[partner] = left;
|
|
1638
|
+
}
|
|
1639
|
+
}
|
|
1640
|
+
|
|
1641
|
+
@compute @workgroup_size(64)
|
|
1642
|
+
fn writeSortedBvhLeaves(@builtin(global_invocation_id) globalId: vec3<u32>) {
|
|
1643
|
+
let sortedIndex = globalId.x;
|
|
1644
|
+
if (sortedIndex >= config.triangleCount || config.triangleCount == 0u) {
|
|
1645
|
+
return;
|
|
1646
|
+
}
|
|
1647
|
+
|
|
1648
|
+
let leafRef = bvhLeafRefs[sortedIndex];
|
|
1649
|
+
if (leafRef.triangleIndex >= config.triangleCount) {
|
|
1650
|
+
return;
|
|
1651
|
+
}
|
|
1652
|
+
|
|
1653
|
+
let triangle = triangles[leafRef.triangleIndex];
|
|
1654
|
+
let boundsMin = min(triangle.v0.xyz, min(triangle.v1.xyz, triangle.v2.xyz));
|
|
1655
|
+
let boundsMax = max(triangle.v0.xyz, max(triangle.v1.xyz, triangle.v2.xyz));
|
|
1656
|
+
let leafBase = config.triangleCount - 1u;
|
|
1657
|
+
let nodeIndex = leafBase + sortedIndex;
|
|
1658
|
+
bvhNodes[nodeIndex] = BvhNode(
|
|
1659
|
+
vec4<f32>(boundsMin, 0.0),
|
|
1660
|
+
vec4<f32>(boundsMax, 0.0),
|
|
1661
|
+
leafRef.triangleIndex,
|
|
1662
|
+
1u,
|
|
1663
|
+
0u,
|
|
1664
|
+
0u
|
|
1665
|
+
);
|
|
1666
|
+
}
|
|
1667
|
+
|
|
1668
|
+
@compute @workgroup_size(64)
|
|
1669
|
+
fn buildBvhInternalLevel(@builtin(global_invocation_id) globalId: vec3<u32>) {
|
|
1670
|
+
if (config.triangleCount <= 1u || globalId.x >= config.bvhBuildNodeCount) {
|
|
1671
|
+
return;
|
|
1672
|
+
}
|
|
1673
|
+
|
|
1674
|
+
let internalCount = config.triangleCount - 1u;
|
|
1675
|
+
let nodeIndex = config.bvhBuildNodeStart + globalId.x;
|
|
1676
|
+
if (nodeIndex >= internalCount || nodeIndex >= config.bvhNodeCapacity) {
|
|
1677
|
+
return;
|
|
1678
|
+
}
|
|
1679
|
+
|
|
1680
|
+
let leftIndex = nodeIndex * 2u + 1u;
|
|
1681
|
+
let rightIndex = nodeIndex * 2u + 2u;
|
|
1682
|
+
if (rightIndex >= config.bvhNodeCapacity || rightIndex >= config.bvhNodeCount) {
|
|
1683
|
+
return;
|
|
1684
|
+
}
|
|
1685
|
+
|
|
1686
|
+
let left = bvhNodes[leftIndex];
|
|
1687
|
+
let right = bvhNodes[rightIndex];
|
|
1688
|
+
bvhNodes[nodeIndex] = BvhNode(
|
|
1689
|
+
vec4<f32>(node_bounds_min(left, right), 0.0),
|
|
1690
|
+
vec4<f32>(node_bounds_max(left, right), 0.0),
|
|
1691
|
+
leftIndex,
|
|
1692
|
+
0u,
|
|
1693
|
+
rightIndex,
|
|
1694
|
+
0u
|
|
1695
|
+
);
|
|
1696
|
+
}
|
|
1697
|
+
|
|
1698
|
+
fn make_ray(pixelIndex: u32) -> RayRecord {
|
|
1699
|
+
let localX = pixelIndex % config.tileWidth;
|
|
1700
|
+
let localY = pixelIndex / config.tileWidth;
|
|
1701
|
+
let px = config.tileX + localX;
|
|
1702
|
+
let py = config.tileY + localY;
|
|
1703
|
+
let sampleId = u32(config.projectionAndSampling.w);
|
|
1704
|
+
let sourcePixelId = py * config.canvasWidth + px;
|
|
1705
|
+
let jitterX = random01(mix_seed(sourcePixelId, sampleId, 0u, config.frameIndex, 1u)) - 0.5;
|
|
1706
|
+
let jitterY = random01(mix_seed(sourcePixelId, sampleId, 0u, config.frameIndex, 2u)) - 0.5;
|
|
1707
|
+
let ndcX = ((f32(px) + 0.5 + jitterX * 0.35) / f32(config.canvasWidth)) * 2.0 - 1.0;
|
|
1708
|
+
let ndcY = 1.0 - ((f32(py) + 0.5 + jitterY * 0.35) / f32(config.canvasHeight)) * 2.0;
|
|
1709
|
+
let viewX = ndcX * config.projectionAndSampling.x * config.projectionAndSampling.y;
|
|
1710
|
+
let viewY = ndcY * config.projectionAndSampling.x;
|
|
1711
|
+
let direction = safe_normalize(
|
|
1712
|
+
config.cameraForward.xyz + config.cameraRight.xyz * viewX + config.cameraUp.xyz * viewY,
|
|
1713
|
+
config.cameraForward.xyz
|
|
1714
|
+
);
|
|
1715
|
+
return RayRecord(
|
|
1716
|
+
pixelIndex,
|
|
1717
|
+
0xffffffffu,
|
|
1718
|
+
sourcePixelId,
|
|
1719
|
+
sampleId,
|
|
1720
|
+
0u,
|
|
1721
|
+
0u,
|
|
1722
|
+
0u,
|
|
1723
|
+
0u,
|
|
1724
|
+
vec4<f32>(config.cameraPosition.xyz, 1.0),
|
|
1725
|
+
vec4<f32>(direction, 0.0),
|
|
1726
|
+
vec4<f32>(1.0, 1.0, 1.0, 1.0)
|
|
1727
|
+
);
|
|
1728
|
+
}
|
|
1729
|
+
|
|
1730
|
+
fn make_miss(ray: RayRecord) -> HitRecord {
|
|
1731
|
+
let radiance = environment_radiance(ray.direction.xyz);
|
|
1732
|
+
return HitRecord(
|
|
1733
|
+
ray.rayId,
|
|
1734
|
+
ray.sourcePixelId,
|
|
1735
|
+
2u,
|
|
1736
|
+
0u,
|
|
1737
|
+
0u,
|
|
1738
|
+
1u,
|
|
1739
|
+
0u,
|
|
1740
|
+
0u,
|
|
1741
|
+
0u,
|
|
1742
|
+
0u,
|
|
1743
|
+
0u,
|
|
1744
|
+
0u,
|
|
1745
|
+
-1.0,
|
|
1746
|
+
vec3<f32>(0.0),
|
|
1747
|
+
vec4<f32>(ray.origin.xyz + ray.direction.xyz * 1000.0, 1.0),
|
|
1748
|
+
vec4<f32>(-ray.direction.xyz, 0.0),
|
|
1749
|
+
vec4<f32>(-ray.direction.xyz, 0.0),
|
|
1750
|
+
vec4<f32>(0.0),
|
|
1751
|
+
vec4<f32>(0.0),
|
|
1752
|
+
vec4<f32>(radiance, 1.0),
|
|
1753
|
+
vec4<f32>(0.0),
|
|
1754
|
+
vec4<f32>(1.0, 0.0, 1.0, 1.0)
|
|
1755
|
+
);
|
|
1756
|
+
}
|
|
1757
|
+
|
|
1758
|
+
fn intersect_sphere(ray: RayRecord, object: SceneObject) -> Candidate {
|
|
1759
|
+
let oc = ray.origin.xyz - object.center.xyz;
|
|
1760
|
+
let radius = max(object.halfExtent.x, 0.001);
|
|
1761
|
+
let halfB = dot(oc, ray.direction.xyz);
|
|
1762
|
+
let c = dot(oc, oc) - radius * radius;
|
|
1763
|
+
let discriminant = halfB * halfB - c;
|
|
1764
|
+
if (discriminant < 0.0) {
|
|
1765
|
+
return no_candidate();
|
|
1766
|
+
}
|
|
1767
|
+
let sqrtD = sqrt(discriminant);
|
|
1768
|
+
var distance = -halfB - sqrtD;
|
|
1769
|
+
if (distance <= 0.001) {
|
|
1770
|
+
distance = -halfB + sqrtD;
|
|
1771
|
+
}
|
|
1772
|
+
if (distance <= 0.001) {
|
|
1773
|
+
return no_candidate();
|
|
1774
|
+
}
|
|
1775
|
+
let position = ray.origin.xyz + ray.direction.xyz * distance;
|
|
1776
|
+
let outward = safe_normalize((position - object.center.xyz) / radius, vec3<f32>(0.0, 1.0, 0.0));
|
|
1777
|
+
let frontFace = select(0u, 1u, dot(ray.direction.xyz, outward) < 0.0);
|
|
1778
|
+
let normal = select(-outward, outward, frontFace == 1u);
|
|
1779
|
+
return surface_candidate(
|
|
1780
|
+
distance,
|
|
1781
|
+
normal,
|
|
1782
|
+
normal,
|
|
1783
|
+
vec3<f32>(1.0, 0.0, 0.0),
|
|
1784
|
+
vec2<f32>(0.0),
|
|
1785
|
+
frontFace,
|
|
1786
|
+
0xffffffffu,
|
|
1787
|
+
object.objectId,
|
|
1788
|
+
object.objectId,
|
|
1789
|
+
0u
|
|
1790
|
+
);
|
|
1791
|
+
}
|
|
1792
|
+
|
|
1793
|
+
fn safe_inverse(value: f32) -> f32 {
|
|
1794
|
+
if (abs(value) < 0.000001) {
|
|
1795
|
+
return select(-1000000.0, 1000000.0, value >= 0.0);
|
|
1796
|
+
}
|
|
1797
|
+
return 1.0 / value;
|
|
1798
|
+
}
|
|
1799
|
+
|
|
1800
|
+
fn intersect_box(ray: RayRecord, object: SceneObject) -> Candidate {
|
|
1801
|
+
let boxMin = object.center.xyz - object.halfExtent.xyz;
|
|
1802
|
+
let boxMax = object.center.xyz + object.halfExtent.xyz;
|
|
1803
|
+
let inv = vec3<f32>(
|
|
1804
|
+
safe_inverse(ray.direction.x),
|
|
1805
|
+
safe_inverse(ray.direction.y),
|
|
1806
|
+
safe_inverse(ray.direction.z)
|
|
1807
|
+
);
|
|
1808
|
+
let t0 = (boxMin - ray.origin.xyz) * inv;
|
|
1809
|
+
let t1 = (boxMax - ray.origin.xyz) * inv;
|
|
1810
|
+
let tNear = min(t0, t1);
|
|
1811
|
+
let tFar = max(t0, t1);
|
|
1812
|
+
let entry = max(max(tNear.x, tNear.y), tNear.z);
|
|
1813
|
+
let exit = min(min(tFar.x, tFar.y), tFar.z);
|
|
1814
|
+
if (exit < max(entry, 0.001)) {
|
|
1815
|
+
return no_candidate();
|
|
1816
|
+
}
|
|
1817
|
+
let distance = max(entry, 0.001);
|
|
1818
|
+
let position = ray.origin.xyz + ray.direction.xyz * distance;
|
|
1819
|
+
let rel = (position - object.center.xyz) / max(object.halfExtent.xyz, vec3<f32>(0.001));
|
|
1820
|
+
let absRel = abs(rel);
|
|
1821
|
+
var outward = vec3<f32>(0.0, 1.0, 0.0);
|
|
1822
|
+
if (absRel.x >= absRel.y && absRel.x >= absRel.z) {
|
|
1823
|
+
outward = vec3<f32>(select(-1.0, 1.0, rel.x >= 0.0), 0.0, 0.0);
|
|
1824
|
+
} else if (absRel.y >= absRel.z) {
|
|
1825
|
+
outward = vec3<f32>(0.0, select(-1.0, 1.0, rel.y >= 0.0), 0.0);
|
|
1826
|
+
} else {
|
|
1827
|
+
outward = vec3<f32>(0.0, 0.0, select(-1.0, 1.0, rel.z >= 0.0));
|
|
1828
|
+
}
|
|
1829
|
+
let frontFace = select(0u, 1u, dot(ray.direction.xyz, outward) < 0.0);
|
|
1830
|
+
let normal = select(-outward, outward, frontFace == 1u);
|
|
1831
|
+
return surface_candidate(
|
|
1832
|
+
distance,
|
|
1833
|
+
normal,
|
|
1834
|
+
normal,
|
|
1835
|
+
vec3<f32>(1.0, 0.0, 0.0),
|
|
1836
|
+
vec2<f32>(0.0),
|
|
1837
|
+
frontFace,
|
|
1838
|
+
0xffffffffu,
|
|
1839
|
+
object.objectId,
|
|
1840
|
+
object.objectId,
|
|
1841
|
+
0u
|
|
1842
|
+
);
|
|
1843
|
+
}
|
|
1844
|
+
|
|
1845
|
+
fn intersect_bounds(ray: RayRecord, boundsMin: vec3<f32>, boundsMax: vec3<f32>, nearest: f32) -> bool {
|
|
1846
|
+
let inv = vec3<f32>(
|
|
1847
|
+
safe_inverse(ray.direction.x),
|
|
1848
|
+
safe_inverse(ray.direction.y),
|
|
1849
|
+
safe_inverse(ray.direction.z)
|
|
1850
|
+
);
|
|
1851
|
+
let t0 = (boundsMin - ray.origin.xyz) * inv;
|
|
1852
|
+
let t1 = (boundsMax - ray.origin.xyz) * inv;
|
|
1853
|
+
let tNear = min(t0, t1);
|
|
1854
|
+
let tFar = max(t0, t1);
|
|
1855
|
+
let entry = max(max(tNear.x, tNear.y), tNear.z);
|
|
1856
|
+
let exit = min(min(tFar.x, tFar.y), tFar.z);
|
|
1857
|
+
return exit >= max(entry, 0.001) && entry <= nearest;
|
|
1858
|
+
}
|
|
1859
|
+
|
|
1860
|
+
fn repair_shading_normal(geometricNormal: vec3<f32>, shadingNormal: vec3<f32>) -> vec3<f32> {
|
|
1861
|
+
var normal = safe_normalize(shadingNormal, geometricNormal);
|
|
1862
|
+
if (dot(normal, geometricNormal) < 0.0) {
|
|
1863
|
+
normal = -normal;
|
|
1864
|
+
}
|
|
1865
|
+
return normal;
|
|
1866
|
+
}
|
|
1867
|
+
|
|
1868
|
+
fn no_candidate() -> Candidate {
|
|
1869
|
+
return Candidate(
|
|
1870
|
+
0u,
|
|
1871
|
+
0.0,
|
|
1872
|
+
vec3<f32>(0.0, 1.0, 0.0),
|
|
1873
|
+
vec3<f32>(0.0, 1.0, 0.0),
|
|
1874
|
+
vec3<f32>(0.0),
|
|
1875
|
+
vec2<f32>(0.0),
|
|
1876
|
+
1u,
|
|
1877
|
+
0xffffffffu,
|
|
1878
|
+
0xffffffffu,
|
|
1879
|
+
0u,
|
|
1880
|
+
0u
|
|
1881
|
+
);
|
|
1882
|
+
}
|
|
1883
|
+
|
|
1884
|
+
fn surface_candidate(
|
|
1885
|
+
distance: f32,
|
|
1886
|
+
geometricNormal: vec3<f32>,
|
|
1887
|
+
shadingNormal: vec3<f32>,
|
|
1888
|
+
barycentric: vec3<f32>,
|
|
1889
|
+
uv: vec2<f32>,
|
|
1890
|
+
frontFace: u32,
|
|
1891
|
+
triangleIndex: u32,
|
|
1892
|
+
primitiveId: u32,
|
|
1893
|
+
materialRefId: u32,
|
|
1894
|
+
mediumRefId: u32
|
|
1895
|
+
) -> Candidate {
|
|
1896
|
+
return Candidate(
|
|
1897
|
+
1u,
|
|
1898
|
+
distance,
|
|
1899
|
+
geometricNormal,
|
|
1900
|
+
shadingNormal,
|
|
1901
|
+
barycentric,
|
|
1902
|
+
uv,
|
|
1903
|
+
frontFace,
|
|
1904
|
+
triangleIndex,
|
|
1905
|
+
primitiveId,
|
|
1906
|
+
materialRefId,
|
|
1907
|
+
mediumRefId
|
|
1908
|
+
);
|
|
1909
|
+
}
|
|
1910
|
+
|
|
1911
|
+
fn intersect_triangle(ray: RayRecord, triangle: TriangleRecord, triangleIndex: u32) -> Candidate {
|
|
1912
|
+
let edge1 = triangle.v1.xyz - triangle.v0.xyz;
|
|
1913
|
+
let edge2 = triangle.v2.xyz - triangle.v0.xyz;
|
|
1914
|
+
let pvec = cross(ray.direction.xyz, edge2);
|
|
1915
|
+
let det = dot(edge1, pvec);
|
|
1916
|
+
if (abs(det) < 0.0000001) {
|
|
1917
|
+
return no_candidate();
|
|
1918
|
+
}
|
|
1919
|
+
|
|
1920
|
+
let invDet = 1.0 / det;
|
|
1921
|
+
let tvec = ray.origin.xyz - triangle.v0.xyz;
|
|
1922
|
+
let u = dot(tvec, pvec) * invDet;
|
|
1923
|
+
if (u < 0.0 || u > 1.0) {
|
|
1924
|
+
return no_candidate();
|
|
1925
|
+
}
|
|
1926
|
+
|
|
1927
|
+
let qvec = cross(tvec, edge1);
|
|
1928
|
+
let v = dot(ray.direction.xyz, qvec) * invDet;
|
|
1929
|
+
if (v < 0.0 || u + v > 1.0) {
|
|
1930
|
+
return no_candidate();
|
|
1931
|
+
}
|
|
1932
|
+
|
|
1933
|
+
let distance = dot(edge2, qvec) * invDet;
|
|
1934
|
+
if (distance <= 0.001) {
|
|
1935
|
+
return no_candidate();
|
|
1936
|
+
}
|
|
1937
|
+
|
|
1938
|
+
let geometric = safe_normalize(cross(edge1, edge2), vec3<f32>(0.0, 1.0, 0.0));
|
|
1939
|
+
let frontFace = select(0u, 1u, dot(ray.direction.xyz, geometric) < 0.0);
|
|
1940
|
+
let orientedGeometric = select(-geometric, geometric, frontFace == 1u);
|
|
1941
|
+
let w = 1.0 - u - v;
|
|
1942
|
+
let interpolated =
|
|
1943
|
+
triangle.n0.xyz * w +
|
|
1944
|
+
triangle.n1.xyz * u +
|
|
1945
|
+
triangle.n2.xyz * v;
|
|
1946
|
+
let shading = repair_shading_normal(orientedGeometric, interpolated);
|
|
1947
|
+
let barycentric = vec3<f32>(w, u, v);
|
|
1948
|
+
let uv =
|
|
1949
|
+
triangle.uv0uv1.xy * w +
|
|
1950
|
+
triangle.uv0uv1.zw * u +
|
|
1951
|
+
triangle.uv2Pad.xy * v;
|
|
1952
|
+
return surface_candidate(
|
|
1953
|
+
distance,
|
|
1954
|
+
orientedGeometric,
|
|
1955
|
+
shading,
|
|
1956
|
+
barycentric,
|
|
1957
|
+
uv,
|
|
1958
|
+
frontFace,
|
|
1959
|
+
triangleIndex,
|
|
1960
|
+
triangle.triangleId,
|
|
1961
|
+
triangle.materialRefId,
|
|
1962
|
+
triangle.mediumRefId
|
|
1963
|
+
);
|
|
1964
|
+
}
|
|
1965
|
+
|
|
1966
|
+
fn intersect_bvh(ray: RayRecord, initialNearest: f32) -> Candidate {
|
|
1967
|
+
var nearest = initialNearest;
|
|
1968
|
+
var best = no_candidate();
|
|
1969
|
+
if (config.bvhNodeCount == 0u || config.triangleCount == 0u) {
|
|
1970
|
+
return best;
|
|
1971
|
+
}
|
|
1972
|
+
|
|
1973
|
+
var stack = array<u32, 64>();
|
|
1974
|
+
var stackSize = 1u;
|
|
1975
|
+
stack[0] = 0u;
|
|
1976
|
+
|
|
1977
|
+
loop {
|
|
1978
|
+
if (stackSize == 0u) {
|
|
1979
|
+
break;
|
|
1980
|
+
}
|
|
1981
|
+
|
|
1982
|
+
stackSize = stackSize - 1u;
|
|
1983
|
+
let nodeIndex = stack[stackSize];
|
|
1984
|
+
if (nodeIndex >= config.bvhNodeCount) {
|
|
1985
|
+
continue;
|
|
1986
|
+
}
|
|
1987
|
+
|
|
1988
|
+
let node = bvhNodes[nodeIndex];
|
|
1989
|
+
if (!intersect_bounds(ray, node.boundsMin.xyz, node.boundsMax.xyz, nearest)) {
|
|
1990
|
+
continue;
|
|
1991
|
+
}
|
|
1992
|
+
|
|
1993
|
+
if (node.triangleCount > 0u) {
|
|
1994
|
+
for (var offset = 0u; offset < node.triangleCount; offset = offset + 1u) {
|
|
1995
|
+
let triangleIndex = node.childOrFirst + offset;
|
|
1996
|
+
if (triangleIndex >= config.triangleCount) {
|
|
1997
|
+
continue;
|
|
1998
|
+
}
|
|
1999
|
+
let current = intersect_triangle(ray, triangles[triangleIndex], triangleIndex);
|
|
2000
|
+
if (current.hit == 1u && current.distance < nearest) {
|
|
2001
|
+
nearest = current.distance;
|
|
2002
|
+
best = current;
|
|
2003
|
+
}
|
|
2004
|
+
}
|
|
2005
|
+
} else {
|
|
2006
|
+
if (stackSize + 2u <= 64u) {
|
|
2007
|
+
stack[stackSize] = node.childOrFirst;
|
|
2008
|
+
stack[stackSize + 1u] = node.rightChild;
|
|
2009
|
+
stackSize = stackSize + 2u;
|
|
2010
|
+
}
|
|
2011
|
+
}
|
|
2012
|
+
}
|
|
2013
|
+
|
|
2014
|
+
return best;
|
|
2015
|
+
}
|
|
2016
|
+
|
|
2017
|
+
fn emission_power(emission: vec4<f32>) -> f32 {
|
|
2018
|
+
return emission.x + emission.y + emission.z;
|
|
2019
|
+
}
|
|
2020
|
+
|
|
2021
|
+
fn sample_weight() -> f32 {
|
|
2022
|
+
return max(config.projectionAndSampling.z, 0.000001);
|
|
2023
|
+
}
|
|
2024
|
+
|
|
2025
|
+
fn clamp_sample_radiance(value: vec3<f32>) -> vec3<f32> {
|
|
2026
|
+
return min(max(value, vec3<f32>(0.0)), vec3<f32>(4.0));
|
|
2027
|
+
}
|
|
2028
|
+
|
|
2029
|
+
fn tone_map_radiance(value: vec3<f32>) -> vec3<f32> {
|
|
2030
|
+
let mapped = value / (vec3<f32>(1.0) + value);
|
|
2031
|
+
return pow(clamp(mapped, vec3<f32>(0.0), vec3<f32>(1.0)), vec3<f32>(1.0 / 2.2));
|
|
2032
|
+
}
|
|
2033
|
+
|
|
2034
|
+
fn denoise_range_space(value: vec3<f32>) -> vec3<f32> {
|
|
2035
|
+
return value / (vec3<f32>(1.0) + value);
|
|
2036
|
+
}
|
|
2037
|
+
|
|
2038
|
+
@compute @workgroup_size(64)
|
|
2039
|
+
fn generatePrimaryRays(@builtin(global_invocation_id) globalId: vec3<u32>) {
|
|
2040
|
+
let index = globalId.x;
|
|
2041
|
+
if (index == 0u) {
|
|
2042
|
+
atomicStore(&counters.activeCount, config.tilePixelCount);
|
|
2043
|
+
atomicStore(&counters.nextCount, 0u);
|
|
2044
|
+
atomicStore(&counters.terminatedCount, 0u);
|
|
2045
|
+
atomicStore(&counters.hitCount, 0u);
|
|
2046
|
+
}
|
|
2047
|
+
if (index >= config.tilePixelCount) {
|
|
2048
|
+
return;
|
|
2049
|
+
}
|
|
2050
|
+
activeQueue[index] = make_ray(index);
|
|
2051
|
+
if (u32(config.projectionAndSampling.w) == 0u) {
|
|
2052
|
+
accumulation[index] = vec4<f32>(0.0);
|
|
2053
|
+
}
|
|
2054
|
+
}
|
|
2055
|
+
|
|
2056
|
+
@compute @workgroup_size(64)
|
|
2057
|
+
fn intersectActiveQueue(@builtin(global_invocation_id) globalId: vec3<u32>) {
|
|
2058
|
+
let index = globalId.x;
|
|
2059
|
+
let activeCount = atomicLoad(&counters.activeCount);
|
|
2060
|
+
if (index >= activeCount) {
|
|
2061
|
+
return;
|
|
2062
|
+
}
|
|
2063
|
+
let ray = activeQueue[index];
|
|
2064
|
+
var nearest = 1000000.0;
|
|
2065
|
+
var hitObject = SceneObject(
|
|
2066
|
+
0u,
|
|
2067
|
+
0u,
|
|
2068
|
+
0u,
|
|
2069
|
+
0u,
|
|
2070
|
+
vec4<f32>(0.0),
|
|
2071
|
+
vec4<f32>(0.0),
|
|
2072
|
+
vec4<f32>(0.0),
|
|
2073
|
+
vec4<f32>(0.0),
|
|
2074
|
+
vec4<f32>(1.0, 0.0, 1.0, 1.0)
|
|
2075
|
+
);
|
|
2076
|
+
var candidate = no_candidate();
|
|
2077
|
+
var hitTriangle = TriangleRecord(
|
|
2078
|
+
0u,
|
|
2079
|
+
0u,
|
|
2080
|
+
0u,
|
|
2081
|
+
0u,
|
|
2082
|
+
0u,
|
|
2083
|
+
0u,
|
|
2084
|
+
0u,
|
|
2085
|
+
0u,
|
|
2086
|
+
vec4<f32>(0.0),
|
|
2087
|
+
vec4<f32>(0.0),
|
|
2088
|
+
vec4<f32>(0.0),
|
|
2089
|
+
vec4<f32>(0.0, 1.0, 0.0, 0.0),
|
|
2090
|
+
vec4<f32>(0.0, 1.0, 0.0, 0.0),
|
|
2091
|
+
vec4<f32>(0.0, 1.0, 0.0, 0.0),
|
|
2092
|
+
vec4<f32>(0.0),
|
|
2093
|
+
vec4<f32>(0.0),
|
|
2094
|
+
vec4<f32>(0.0),
|
|
2095
|
+
vec4<f32>(0.0),
|
|
2096
|
+
vec4<f32>(1.0, 0.0, 1.0, 1.0)
|
|
2097
|
+
);
|
|
2098
|
+
|
|
2099
|
+
for (var objectIndex = 0u; objectIndex < config.sceneObjectCount; objectIndex = objectIndex + 1u) {
|
|
2100
|
+
let object = sceneObjects[objectIndex];
|
|
2101
|
+
var current = no_candidate();
|
|
2102
|
+
if (object.kind == 1u) {
|
|
2103
|
+
current = intersect_sphere(ray, object);
|
|
2104
|
+
} else if (object.kind == 2u) {
|
|
2105
|
+
current = intersect_box(ray, object);
|
|
2106
|
+
}
|
|
2107
|
+
if (current.hit == 1u && current.distance < nearest) {
|
|
2108
|
+
nearest = current.distance;
|
|
2109
|
+
hitObject = object;
|
|
2110
|
+
candidate = current;
|
|
2111
|
+
}
|
|
2112
|
+
}
|
|
2113
|
+
|
|
2114
|
+
let meshCandidate = intersect_bvh(ray, nearest);
|
|
2115
|
+
if (meshCandidate.hit == 1u && meshCandidate.distance < nearest) {
|
|
2116
|
+
nearest = meshCandidate.distance;
|
|
2117
|
+
candidate = meshCandidate;
|
|
2118
|
+
hitTriangle = triangles[meshCandidate.triangleIndex];
|
|
2119
|
+
}
|
|
2120
|
+
|
|
2121
|
+
if (candidate.hit == 0u) {
|
|
2122
|
+
hits[index] = make_miss(ray);
|
|
2123
|
+
return;
|
|
2124
|
+
}
|
|
2125
|
+
|
|
2126
|
+
let position = ray.origin.xyz + ray.direction.xyz * candidate.distance;
|
|
2127
|
+
let hitMaterialKind = select(hitObject.materialKind, hitTriangle.materialKind, candidate.triangleIndex != 0xffffffffu);
|
|
2128
|
+
let hitObjectId = select(hitObject.objectId, hitTriangle.meshId, candidate.triangleIndex != 0xffffffffu);
|
|
2129
|
+
let hitColor = select(hitObject.color, hitTriangle.color, candidate.triangleIndex != 0xffffffffu);
|
|
2130
|
+
let hitEmission = select(hitObject.emission, hitTriangle.emission, candidate.triangleIndex != 0xffffffffu);
|
|
2131
|
+
let hitMaterial = select(hitObject.material, hitTriangle.material, candidate.triangleIndex != 0xffffffffu);
|
|
2132
|
+
let hitPrimitiveId = select(candidate.primitiveId, hitTriangle.triangleId, candidate.triangleIndex != 0xffffffffu);
|
|
2133
|
+
let hitMaterialRefId = select(candidate.materialRefId, hitTriangle.materialRefId, candidate.triangleIndex != 0xffffffffu);
|
|
2134
|
+
let hitMediumRefId = select(candidate.mediumRefId, hitTriangle.mediumRefId, candidate.triangleIndex != 0xffffffffu);
|
|
2135
|
+
var hitType = 0u;
|
|
2136
|
+
if (hitMaterialKind == 4u || emission_power(hitEmission) > 0.0001) {
|
|
2137
|
+
hitType = 1u;
|
|
2138
|
+
} else if (hitMaterialKind == 3u || hitMaterial.z < 0.999) {
|
|
2139
|
+
hitType = 3u;
|
|
2140
|
+
}
|
|
2141
|
+
atomicAdd(&counters.hitCount, 1u);
|
|
2142
|
+
hits[index] = HitRecord(
|
|
2143
|
+
ray.rayId,
|
|
2144
|
+
ray.sourcePixelId,
|
|
2145
|
+
hitType,
|
|
2146
|
+
hitObjectId,
|
|
2147
|
+
hitMaterialKind,
|
|
2148
|
+
candidate.frontFace,
|
|
2149
|
+
hitPrimitiveId,
|
|
2150
|
+
hitMaterialRefId,
|
|
2151
|
+
hitMediumRefId,
|
|
2152
|
+
0u,
|
|
2153
|
+
0u,
|
|
2154
|
+
0u,
|
|
2155
|
+
candidate.distance,
|
|
2156
|
+
vec3<f32>(0.0),
|
|
2157
|
+
vec4<f32>(position, 1.0),
|
|
2158
|
+
vec4<f32>(candidate.geometricNormal, 0.0),
|
|
2159
|
+
vec4<f32>(candidate.shadingNormal, 0.0),
|
|
2160
|
+
vec4<f32>(candidate.barycentric, 0.0),
|
|
2161
|
+
vec4<f32>(candidate.uv, 0.0, 0.0),
|
|
2162
|
+
hitColor,
|
|
2163
|
+
hitEmission,
|
|
2164
|
+
hitMaterial
|
|
2165
|
+
);
|
|
2166
|
+
}
|
|
2167
|
+
|
|
2168
|
+
fn offset_origin(position: vec3<f32>, normal: vec3<f32>) -> vec3<f32> {
|
|
2169
|
+
return position + normal * 0.0025;
|
|
2170
|
+
}
|
|
2171
|
+
|
|
2172
|
+
fn random_unit_vector(seed: u32) -> vec3<f32> {
|
|
2173
|
+
let z = random01(seed) * 2.0 - 1.0;
|
|
2174
|
+
let a = random01(seed + 11u) * 6.28318530718;
|
|
2175
|
+
let r = sqrt(max(0.0, 1.0 - z * z));
|
|
2176
|
+
return vec3<f32>(r * cos(a), r * sin(a), z);
|
|
2177
|
+
}
|
|
2178
|
+
|
|
2179
|
+
fn schlick(cosine: f32, refractionRatio: f32) -> f32 {
|
|
2180
|
+
var r0 = (1.0 - refractionRatio) / (1.0 + refractionRatio);
|
|
2181
|
+
r0 = r0 * r0;
|
|
2182
|
+
return r0 + (1.0 - r0) * pow(1.0 - cosine, 5.0);
|
|
2183
|
+
}
|
|
2184
|
+
|
|
2185
|
+
fn refract_direction(unitDirection: vec3<f32>, normal: vec3<f32>, etaRatio: f32) -> vec3<f32> {
|
|
2186
|
+
let cosTheta = min(dot(-unitDirection, normal), 1.0);
|
|
2187
|
+
let rOutPerp = etaRatio * (unitDirection + cosTheta * normal);
|
|
2188
|
+
let rOutParallel = -sqrt(abs(1.0 - dot(rOutPerp, rOutPerp))) * normal;
|
|
2189
|
+
return safe_normalize(rOutPerp + rOutParallel, reflect(unitDirection, normal));
|
|
2190
|
+
}
|
|
2191
|
+
|
|
2192
|
+
fn sample_emissive_triangle_direction(hit: HitRecord, seed: u32, fallback: vec3<f32>) -> vec3<f32> {
|
|
2193
|
+
if (config.emissiveTriangleCount == 0u) {
|
|
2194
|
+
return fallback;
|
|
2195
|
+
}
|
|
2196
|
+
let lightSlot = min(u32(random01(seed + 71u) * f32(config.emissiveTriangleCount)), config.emissiveTriangleCount - 1u);
|
|
2197
|
+
let lightMetadata = bvhNodes[config.bvhNodeCapacity + lightSlot];
|
|
2198
|
+
let triangleIndex = lightMetadata.childOrFirst;
|
|
2199
|
+
if (triangleIndex >= config.triangleCount) {
|
|
2200
|
+
return fallback;
|
|
2201
|
+
}
|
|
2202
|
+
|
|
2203
|
+
let lightTriangle = triangles[triangleIndex];
|
|
2204
|
+
let r1 = random01(seed + 101u);
|
|
2205
|
+
let r2 = random01(seed + 193u);
|
|
2206
|
+
let root = sqrt(r1);
|
|
2207
|
+
let b0 = 1.0 - root;
|
|
2208
|
+
let b1 = root * (1.0 - r2);
|
|
2209
|
+
let b2 = root * r2;
|
|
2210
|
+
let lightPoint =
|
|
2211
|
+
lightTriangle.v0.xyz * b0 +
|
|
2212
|
+
lightTriangle.v1.xyz * b1 +
|
|
2213
|
+
lightTriangle.v2.xyz * b2;
|
|
2214
|
+
return safe_normalize(lightPoint - hit.position.xyz, fallback);
|
|
2215
|
+
}
|
|
2216
|
+
|
|
2217
|
+
fn scatter_direction(ray: RayRecord, hit: HitRecord, seed: u32) -> ScatterResult {
|
|
2218
|
+
let roughness = clamp(hit.material.x, 0.0, 1.0);
|
|
2219
|
+
if (hit.materialKind == 1u) {
|
|
2220
|
+
return ScatterResult(
|
|
2221
|
+
vec4<f32>(
|
|
2222
|
+
safe_normalize(
|
|
2223
|
+
reflect(ray.direction.xyz, hit.shadingNormal.xyz) + random_unit_vector(seed) * roughness,
|
|
2224
|
+
hit.shadingNormal.xyz
|
|
2225
|
+
),
|
|
2226
|
+
0.0
|
|
2227
|
+
),
|
|
2228
|
+
0u,
|
|
2229
|
+
0u,
|
|
2230
|
+
0u,
|
|
2231
|
+
0u
|
|
2232
|
+
);
|
|
2233
|
+
}
|
|
2234
|
+
|
|
2235
|
+
if (hit.materialKind == 2u || hit.materialKind == 3u) {
|
|
2236
|
+
let ior = max(hit.material.w, 1.01);
|
|
2237
|
+
let etaRatio = select(ior, 1.0 / ior, hit.frontFace == 1u);
|
|
2238
|
+
let cosTheta = min(dot(-ray.direction.xyz, hit.shadingNormal.xyz), 1.0);
|
|
2239
|
+
let sinTheta = sqrt(max(0.0, 1.0 - cosTheta * cosTheta));
|
|
2240
|
+
let cannotRefract = etaRatio * sinTheta > 1.0;
|
|
2241
|
+
let reflectChance = schlick(cosTheta, etaRatio);
|
|
2242
|
+
if (cannotRefract || random01(seed + 23u) < reflectChance) {
|
|
2243
|
+
return ScatterResult(vec4<f32>(reflect(ray.direction.xyz, hit.shadingNormal.xyz), 0.0), 0u, 0u, 0u, 0u);
|
|
2244
|
+
}
|
|
2245
|
+
return ScatterResult(vec4<f32>(refract_direction(ray.direction.xyz, hit.shadingNormal.xyz, etaRatio), 0.0), 0u, 0u, 0u, 0u);
|
|
2246
|
+
}
|
|
2247
|
+
|
|
2248
|
+
let randomDiffuse = safe_normalize(
|
|
2249
|
+
hit.shadingNormal.xyz + random_unit_vector(seed),
|
|
2250
|
+
hit.shadingNormal.xyz
|
|
2251
|
+
);
|
|
2252
|
+
let guidedLight = sample_emissive_triangle_direction(hit, seed, randomDiffuse);
|
|
2253
|
+
let canSampleLight = dot(hit.shadingNormal.xyz, guidedLight) > -0.04;
|
|
2254
|
+
let guideProbability = select(0.38, 0.72, ray.bounce == 0u);
|
|
2255
|
+
let useGuidedLight = canSampleLight && random01(seed + 37u) < guideProbability;
|
|
2256
|
+
return ScatterResult(
|
|
2257
|
+
vec4<f32>(select(randomDiffuse, guidedLight, useGuidedLight), 0.0),
|
|
2258
|
+
select(0u, RAY_FLAG_GUIDED_EMISSIVE, useGuidedLight),
|
|
2259
|
+
0u,
|
|
2260
|
+
0u,
|
|
2261
|
+
0u
|
|
2262
|
+
);
|
|
2263
|
+
}
|
|
2264
|
+
|
|
2265
|
+
@compute @workgroup_size(64)
|
|
2266
|
+
fn resolveSurfaceRecords(@builtin(global_invocation_id) globalId: vec3<u32>) {
|
|
2267
|
+
let index = globalId.x;
|
|
2268
|
+
let activeCount = atomicLoad(&counters.activeCount);
|
|
2269
|
+
if (index >= activeCount) {
|
|
2270
|
+
return;
|
|
2271
|
+
}
|
|
2272
|
+
|
|
2273
|
+
let ray = activeQueue[index];
|
|
2274
|
+
let hit = hits[index];
|
|
2275
|
+
var contribution = vec3<f32>(0.0);
|
|
2276
|
+
|
|
2277
|
+
if (hit.hitType == 1u) {
|
|
2278
|
+
let guidedLightWeight = select(1.0, 0.24, (ray.flags & RAY_FLAG_GUIDED_EMISSIVE) != 0u);
|
|
2279
|
+
contribution = clamp_sample_radiance(
|
|
2280
|
+
ray.throughput.xyz * max(hit.emission.xyz, hit.color.xyz) * guidedLightWeight
|
|
2281
|
+
);
|
|
2282
|
+
accumulation[ray.rayId] =
|
|
2283
|
+
accumulation[ray.rayId] + vec4<f32>(contribution * sample_weight(), 1.0);
|
|
2284
|
+
atomicAdd(&counters.terminatedCount, 1u);
|
|
2285
|
+
return;
|
|
2286
|
+
}
|
|
2287
|
+
|
|
2288
|
+
if (hit.hitType == 2u) {
|
|
2289
|
+
contribution = clamp_sample_radiance(ray.throughput.xyz * max(hit.color.xyz, config.ambientColor.xyz));
|
|
2290
|
+
accumulation[ray.rayId] =
|
|
2291
|
+
accumulation[ray.rayId] + vec4<f32>(contribution * sample_weight(), 1.0);
|
|
2292
|
+
atomicAdd(&counters.terminatedCount, 1u);
|
|
2293
|
+
return;
|
|
2294
|
+
}
|
|
2295
|
+
|
|
2296
|
+
if (ray.bounce + 1u >= config.maxDepth) {
|
|
2297
|
+
accumulation[ray.rayId] =
|
|
2298
|
+
accumulation[ray.rayId] +
|
|
2299
|
+
vec4<f32>(ray.throughput.xyz * config.ambientColor.xyz * sample_weight(), 1.0);
|
|
2300
|
+
atomicAdd(&counters.terminatedCount, 1u);
|
|
2301
|
+
return;
|
|
2302
|
+
}
|
|
2303
|
+
|
|
2304
|
+
let seed = mix_seed(ray.sourcePixelId, ray.sampleId, ray.bounce, config.frameIndex, 11u);
|
|
2305
|
+
let scatter = scatter_direction(ray, hit, seed);
|
|
2306
|
+
let nextIndex = atomicAdd(&counters.nextCount, 1u);
|
|
2307
|
+
if (nextIndex >= config.tilePixelCount) {
|
|
2308
|
+
return;
|
|
2309
|
+
}
|
|
2310
|
+
let color = clamp(hit.color.xyz, vec3<f32>(0.0), vec3<f32>(1.0));
|
|
2311
|
+
let opacity = clamp(hit.material.z, 0.0, 1.0);
|
|
2312
|
+
let materialEnergy = select(0.68, 0.92, hit.materialKind == 1u || hit.materialKind == 2u);
|
|
2313
|
+
let transparentEnergy = select(materialEnergy, 0.9, hit.hitType == 3u);
|
|
2314
|
+
let throughput = ray.throughput.xyz * mix(vec3<f32>(1.0), color, max(opacity, 0.18)) * transparentEnergy;
|
|
2315
|
+
nextQueue[nextIndex] = RayRecord(
|
|
2316
|
+
ray.rayId,
|
|
2317
|
+
ray.rayId,
|
|
2318
|
+
ray.sourcePixelId,
|
|
2319
|
+
ray.sampleId,
|
|
2320
|
+
ray.bounce + 1u,
|
|
2321
|
+
ray.mediumRefId,
|
|
2322
|
+
scatter.flags,
|
|
2323
|
+
0u,
|
|
2324
|
+
vec4<f32>(offset_origin(hit.position.xyz, hit.shadingNormal.xyz), 1.0),
|
|
2325
|
+
scatter.direction,
|
|
2326
|
+
vec4<f32>(throughput, ray.throughput.w)
|
|
2327
|
+
);
|
|
2328
|
+
}
|
|
2329
|
+
|
|
2330
|
+
@compute @workgroup_size(1)
|
|
2331
|
+
fn compactAndSwapQueues(@builtin(global_invocation_id) globalId: vec3<u32>) {
|
|
2332
|
+
if (globalId.x > 0u) {
|
|
2333
|
+
return;
|
|
2334
|
+
}
|
|
2335
|
+
let nextCount = atomicLoad(&counters.nextCount);
|
|
2336
|
+
atomicStore(&counters.activeCount, min(nextCount, config.tilePixelCount));
|
|
2337
|
+
atomicStore(&counters.nextCount, 0u);
|
|
2338
|
+
}
|
|
2339
|
+
|
|
2340
|
+
@compute @workgroup_size(64)
|
|
2341
|
+
fn accumulateTerminalRadiance(@builtin(global_invocation_id) globalId: vec3<u32>) {
|
|
2342
|
+
let index = globalId.x;
|
|
2343
|
+
if (index >= config.tilePixelCount) {
|
|
2344
|
+
return;
|
|
2345
|
+
}
|
|
2346
|
+
let localX = index % config.tileWidth;
|
|
2347
|
+
let localY = index / config.tileWidth;
|
|
2348
|
+
let pixel = vec2<i32>(i32(config.tileX + localX), i32(config.tileY + localY));
|
|
2349
|
+
let radiance = max(accumulation[index].xyz, vec3<f32>(0.0));
|
|
2350
|
+
|
|
2351
|
+
textureStore(radianceImage, pixel, vec4<f32>(radiance, 1.0));
|
|
2352
|
+
if (config.denoise == 0u) {
|
|
2353
|
+
textureStore(outputImage, pixel, vec4<f32>(tone_map_radiance(radiance), 1.0));
|
|
2354
|
+
}
|
|
2355
|
+
}
|
|
2356
|
+
|
|
2357
|
+
@compute @workgroup_size(8, 8)
|
|
2358
|
+
fn denoiseLinearRadiance(@builtin(global_invocation_id) globalId: vec3<u32>) {
|
|
2359
|
+
let x = globalId.x;
|
|
2360
|
+
let y = globalId.y;
|
|
2361
|
+
if (x >= config.canvasWidth || y >= config.canvasHeight) {
|
|
2362
|
+
return;
|
|
2363
|
+
}
|
|
2364
|
+
|
|
2365
|
+
let pixel = vec2<i32>(i32(x), i32(y));
|
|
2366
|
+
let center = textureLoad(denoiseInputRadiance, pixel, 0).xyz;
|
|
2367
|
+
var sum = center * 1.4;
|
|
2368
|
+
var totalWeight = 1.4;
|
|
2369
|
+
let centerRange = denoise_range_space(center);
|
|
2370
|
+
|
|
2371
|
+
for (var oy = -2i; oy <= 2i; oy = oy + 1i) {
|
|
2372
|
+
for (var ox = -2i; ox <= 2i; ox = ox + 1i) {
|
|
2373
|
+
if (ox == 0i && oy == 0i) {
|
|
2374
|
+
continue;
|
|
2375
|
+
}
|
|
2376
|
+
let sx = clamp(i32(x) + ox, 0i, i32(config.canvasWidth) - 1i);
|
|
2377
|
+
let sy = clamp(i32(y) + oy, 0i, i32(config.canvasHeight) - 1i);
|
|
2378
|
+
let sampleColor = textureLoad(denoiseInputRadiance, vec2<i32>(sx, sy), 0).xyz;
|
|
2379
|
+
let colorDistance = length(denoise_range_space(sampleColor) - centerRange);
|
|
2380
|
+
let rangeWeight = 1.0 / (1.0 + colorDistance * 7.0);
|
|
2381
|
+
let distanceWeight = 1.0 / (1.0 + f32(ox * ox + oy * oy) * 0.24);
|
|
2382
|
+
let diagonalWeight = select(1.0, 0.78, abs(ox) + abs(oy) > 2i);
|
|
2383
|
+
let weight = rangeWeight * diagonalWeight * distanceWeight;
|
|
2384
|
+
sum = sum + sampleColor * weight;
|
|
2385
|
+
totalWeight = totalWeight + weight;
|
|
2386
|
+
}
|
|
2387
|
+
}
|
|
2388
|
+
|
|
2389
|
+
let filtered = sum / max(totalWeight, 0.0001);
|
|
2390
|
+
let outlier = saturate(length(denoise_range_space(center) - denoise_range_space(filtered)) * 2.4);
|
|
2391
|
+
let color = min(mix(center, filtered, 0.52 + outlier * 0.18), vec3<f32>(16.0));
|
|
2392
|
+
textureStore(denoisedRadianceImage, pixel, vec4<f32>(color, 1.0));
|
|
2393
|
+
}
|
|
2394
|
+
|
|
2395
|
+
@compute @workgroup_size(8, 8)
|
|
2396
|
+
fn resolveDenoisedOutputImage(@builtin(global_invocation_id) globalId: vec3<u32>) {
|
|
2397
|
+
let x = globalId.x;
|
|
2398
|
+
let y = globalId.y;
|
|
2399
|
+
if (x >= config.canvasWidth || y >= config.canvasHeight) {
|
|
2400
|
+
return;
|
|
2401
|
+
}
|
|
2402
|
+
|
|
2403
|
+
let pixel = vec2<i32>(i32(x), i32(y));
|
|
2404
|
+
let center = textureLoad(finalDenoiseInputRadiance, pixel, 0).xyz;
|
|
2405
|
+
var sum = center * 1.25;
|
|
2406
|
+
var totalWeight = 1.25;
|
|
2407
|
+
let centerRange = denoise_range_space(center);
|
|
2408
|
+
|
|
2409
|
+
for (var oy = -1i; oy <= 1i; oy = oy + 1i) {
|
|
2410
|
+
for (var ox = -1i; ox <= 1i; ox = ox + 1i) {
|
|
2411
|
+
if (ox == 0i && oy == 0i) {
|
|
2412
|
+
continue;
|
|
2413
|
+
}
|
|
2414
|
+
let sx = clamp(i32(x) + ox, 0i, i32(config.canvasWidth) - 1i);
|
|
2415
|
+
let sy = clamp(i32(y) + oy, 0i, i32(config.canvasHeight) - 1i);
|
|
2416
|
+
let sampleColor = textureLoad(finalDenoiseInputRadiance, vec2<i32>(sx, sy), 0).xyz;
|
|
2417
|
+
let colorDistance = length(denoise_range_space(sampleColor) - centerRange);
|
|
2418
|
+
let rangeWeight = 1.0 / (1.0 + colorDistance * 9.0);
|
|
2419
|
+
let distanceWeight = 1.0 / (1.0 + f32(ox * ox + oy * oy) * 0.4);
|
|
2420
|
+
let weight = rangeWeight * distanceWeight;
|
|
2421
|
+
sum = sum + sampleColor * weight;
|
|
2422
|
+
totalWeight = totalWeight + weight;
|
|
2423
|
+
}
|
|
2424
|
+
}
|
|
2425
|
+
|
|
2426
|
+
let filtered = sum / max(totalWeight, 0.0001);
|
|
2427
|
+
let outlier = saturate(length(denoise_range_space(center) - denoise_range_space(filtered)) * 2.8);
|
|
2428
|
+
let radiance = min(mix(center, filtered, 0.28 + outlier * 0.12), vec3<f32>(16.0));
|
|
2429
|
+
textureStore(denoisedOutputImage, pixel, vec4<f32>(tone_map_radiance(radiance), 1.0));
|
|
2430
|
+
}
|
|
2431
|
+
`;
|
|
2432
|
+
var PRESENT_WGSL = `
|
|
2433
|
+
struct VertexOut {
|
|
2434
|
+
@builtin(position) position: vec4<f32>,
|
|
2435
|
+
@location(0) uv: vec2<f32>,
|
|
2436
|
+
};
|
|
2437
|
+
|
|
2438
|
+
@vertex
|
|
2439
|
+
fn vertexMain(@builtin(vertex_index) vertexIndex: u32) -> VertexOut {
|
|
2440
|
+
var positions = array<vec2<f32>, 3>(
|
|
2441
|
+
vec2<f32>(-1.0, -1.0),
|
|
2442
|
+
vec2<f32>(3.0, -1.0),
|
|
2443
|
+
vec2<f32>(-1.0, 3.0)
|
|
2444
|
+
);
|
|
2445
|
+
var uvs = array<vec2<f32>, 3>(
|
|
2446
|
+
vec2<f32>(0.0, 1.0),
|
|
2447
|
+
vec2<f32>(2.0, 1.0),
|
|
2448
|
+
vec2<f32>(0.0, -1.0)
|
|
2449
|
+
);
|
|
2450
|
+
var out: VertexOut;
|
|
2451
|
+
out.position = vec4<f32>(positions[vertexIndex], 0.0, 1.0);
|
|
2452
|
+
out.uv = uvs[vertexIndex];
|
|
2453
|
+
return out;
|
|
2454
|
+
}
|
|
2455
|
+
|
|
2456
|
+
@group(0) @binding(0) var renderTexture: texture_2d<f32>;
|
|
2457
|
+
@group(0) @binding(1) var renderSampler: sampler;
|
|
2458
|
+
|
|
2459
|
+
@fragment
|
|
2460
|
+
fn fragmentMain(in: VertexOut) -> @location(0) vec4<f32> {
|
|
2461
|
+
return textureSample(renderTexture, renderSampler, in.uv);
|
|
2462
|
+
}
|
|
2463
|
+
`;
|
|
2464
|
+
async function createWavefrontPathTracingComputeRenderer(options = {}) {
|
|
2465
|
+
assertAnalyticDisplayQualityPolicy(options);
|
|
2466
|
+
const constants = getGpuUsageConstants();
|
|
2467
|
+
const navigatorRef = options.navigator ?? globalThis.navigator;
|
|
2468
|
+
if (!supportsWavefrontPathTracingCompute({ navigator: navigatorRef })) {
|
|
2469
|
+
throw new Error("WebGPU wavefront path tracing requires navigator.gpu.");
|
|
2470
|
+
}
|
|
2471
|
+
const canvas = resolveCanvas(options.canvas, options.document);
|
|
2472
|
+
const initialConfig = createWavefrontPathTracingComputeConfig({
|
|
2473
|
+
...options,
|
|
2474
|
+
canvas
|
|
2475
|
+
});
|
|
2476
|
+
const adapter = await navigatorRef.gpu.requestAdapter({
|
|
2477
|
+
powerPreference: options.powerPreference ?? "high-performance"
|
|
2478
|
+
});
|
|
2479
|
+
if (!adapter) {
|
|
2480
|
+
throw new Error("Unable to acquire a WebGPU adapter for wavefront path tracing.");
|
|
2481
|
+
}
|
|
2482
|
+
const device = await adapter.requestDevice();
|
|
2483
|
+
const context = canvas.getContext("webgpu");
|
|
2484
|
+
if (!context || typeof context.configure !== "function") {
|
|
2485
|
+
throw new Error("Canvas WebGPU context does not support configure().");
|
|
2486
|
+
}
|
|
2487
|
+
const format = options.format ?? (typeof navigatorRef.gpu.getPreferredCanvasFormat === "function" ? navigatorRef.gpu.getPreferredCanvasFormat() : "bgra8unorm");
|
|
2488
|
+
let config = initialConfig;
|
|
2489
|
+
const safeTileSize = clampTileSizeForDevice(config, device);
|
|
2490
|
+
if (safeTileSize !== config.tileSize) {
|
|
2491
|
+
config = createWavefrontPathTracingComputeConfig({
|
|
2492
|
+
...options,
|
|
2493
|
+
canvas,
|
|
2494
|
+
width: config.width,
|
|
2495
|
+
height: config.height,
|
|
2496
|
+
tileSize: safeTileSize
|
|
2497
|
+
});
|
|
2498
|
+
}
|
|
2499
|
+
canvas.width = config.width;
|
|
2500
|
+
canvas.height = config.height;
|
|
2501
|
+
context.configure({
|
|
2502
|
+
device,
|
|
2503
|
+
format,
|
|
2504
|
+
alphaMode: options.alpha === true ? "premultiplied" : "opaque"
|
|
2505
|
+
});
|
|
2506
|
+
const bufferUsage = constants.buffer.STORAGE | constants.buffer.COPY_DST;
|
|
2507
|
+
const rayQueueBytes = config.tilePixelCapacity * RAY_RECORD_BYTES;
|
|
2508
|
+
const hitBytes = config.tilePixelCapacity * HIT_RECORD_BYTES;
|
|
2509
|
+
const accumulationBytes = config.tilePixelCapacity * ACCUMULATION_RECORD_BYTES;
|
|
2510
|
+
const activeQueue = createBuffer(device, bufferUsage, rayQueueBytes, "plasius.wavefront.activeQueue");
|
|
2511
|
+
const nextQueue = createBuffer(device, bufferUsage, rayQueueBytes, "plasius.wavefront.nextQueue");
|
|
2512
|
+
const hitBuffer = createBuffer(device, bufferUsage, hitBytes, "plasius.wavefront.hitBuffer");
|
|
2513
|
+
const accumulationBuffer = createBuffer(
|
|
2514
|
+
device,
|
|
2515
|
+
bufferUsage,
|
|
2516
|
+
accumulationBytes,
|
|
2517
|
+
"plasius.wavefront.accumulation"
|
|
2518
|
+
);
|
|
2519
|
+
const sceneObjectBuffer = createBuffer(
|
|
2520
|
+
device,
|
|
2521
|
+
constants.buffer.STORAGE | constants.buffer.COPY_DST,
|
|
2522
|
+
config.sceneObjectCapacity * SCENE_OBJECT_RECORD_BYTES,
|
|
2523
|
+
"plasius.wavefront.sceneObjects"
|
|
2524
|
+
);
|
|
2525
|
+
const triangleBuffer = createBuffer(
|
|
2526
|
+
device,
|
|
2527
|
+
constants.buffer.STORAGE | constants.buffer.COPY_DST,
|
|
2528
|
+
Math.max(1, config.triangleCapacity) * TRIANGLE_RECORD_BYTES,
|
|
2529
|
+
"plasius.wavefront.triangles"
|
|
2530
|
+
);
|
|
2531
|
+
const bvhNodeBuffer = createBuffer(
|
|
2532
|
+
device,
|
|
2533
|
+
constants.buffer.STORAGE | constants.buffer.COPY_DST,
|
|
2534
|
+
Math.max(1, config.bvhNodeCapacity + config.emissiveTriangleCapacity) * BVH_NODE_RECORD_BYTES,
|
|
2535
|
+
"plasius.wavefront.bvhNodes"
|
|
2536
|
+
);
|
|
2537
|
+
const meshVertexBuffer = createBuffer(
|
|
2538
|
+
device,
|
|
2539
|
+
constants.buffer.STORAGE | constants.buffer.COPY_DST,
|
|
2540
|
+
Math.max(1, config.gpuMeshSource.vertices.count) * MESH_VERTEX_RECORD_BYTES,
|
|
2541
|
+
"plasius.wavefront.meshVertices"
|
|
2542
|
+
);
|
|
2543
|
+
const meshIndexBuffer = createBuffer(
|
|
2544
|
+
device,
|
|
2545
|
+
constants.buffer.STORAGE | constants.buffer.COPY_DST,
|
|
2546
|
+
Math.max(1, config.gpuMeshSource.indices.count) * 4,
|
|
2547
|
+
"plasius.wavefront.meshIndices"
|
|
2548
|
+
);
|
|
2549
|
+
const meshRangeBuffer = createBuffer(
|
|
2550
|
+
device,
|
|
2551
|
+
constants.buffer.STORAGE | constants.buffer.COPY_DST,
|
|
2552
|
+
Math.max(1, config.gpuMeshSource.meshes.count) * MESH_RANGE_RECORD_BYTES,
|
|
2553
|
+
"plasius.wavefront.meshRanges"
|
|
2554
|
+
);
|
|
2555
|
+
const bvhLeafRefBuffer = createBuffer(
|
|
2556
|
+
device,
|
|
2557
|
+
constants.buffer.STORAGE | constants.buffer.COPY_DST,
|
|
2558
|
+
Math.max(1, config.bvhLeafSortCapacity) * BVH_LEAF_REF_RECORD_BYTES,
|
|
2559
|
+
"plasius.wavefront.bvhLeafRefs"
|
|
2560
|
+
);
|
|
2561
|
+
const configBuffer = createBuffer(
|
|
2562
|
+
device,
|
|
2563
|
+
constants.buffer.UNIFORM | constants.buffer.COPY_DST,
|
|
2564
|
+
CONFIG_BUFFER_BYTES,
|
|
2565
|
+
"plasius.wavefront.frameConfig"
|
|
2566
|
+
);
|
|
2567
|
+
const uniformOffsetAlignment = Number(device?.limits?.minUniformBufferOffsetAlignment);
|
|
2568
|
+
const configBufferStride = alignTo(
|
|
2569
|
+
CONFIG_BUFFER_BYTES,
|
|
2570
|
+
Number.isFinite(uniformOffsetAlignment) && uniformOffsetAlignment > 0 ? uniformOffsetAlignment : CONFIG_BUFFER_BYTES
|
|
2571
|
+
);
|
|
2572
|
+
const bvhBuildConfigSlots = 1 + config.bvhSortStages.length + config.bvhBuildLevels.length;
|
|
2573
|
+
const bvhBuildConfigBuffer = createBuffer(
|
|
2574
|
+
device,
|
|
2575
|
+
constants.buffer.UNIFORM | constants.buffer.COPY_DST,
|
|
2576
|
+
Math.max(1, bvhBuildConfigSlots) * configBufferStride,
|
|
2577
|
+
"plasius.wavefront.bvhBuildConfig"
|
|
2578
|
+
);
|
|
2579
|
+
const counterBuffer = createBuffer(
|
|
2580
|
+
device,
|
|
2581
|
+
constants.buffer.STORAGE | constants.buffer.COPY_DST,
|
|
2582
|
+
COUNTER_BUFFER_BYTES,
|
|
2583
|
+
"plasius.wavefront.counters"
|
|
2584
|
+
);
|
|
2585
|
+
let packedScene = packWavefrontSceneObjects(config.sceneObjects, config.sceneObjectCapacity);
|
|
2586
|
+
device.queue.writeBuffer(sceneObjectBuffer, 0, packedScene.buffer);
|
|
2587
|
+
const packedTriangles = packWavefrontTriangles(
|
|
2588
|
+
config.meshAcceleration.triangles,
|
|
2589
|
+
Math.max(1, config.triangleCapacity)
|
|
2590
|
+
);
|
|
2591
|
+
const packedBvhNodes = packWavefrontBvhNodes(
|
|
2592
|
+
config.meshAcceleration.nodes,
|
|
2593
|
+
Math.max(1, config.bvhNodeCapacity + config.emissiveTriangleCapacity)
|
|
2594
|
+
);
|
|
2595
|
+
const packedBvhNodeUints = new Uint32Array(packedBvhNodes.buffer);
|
|
2596
|
+
config.emissiveTriangleIndices.indices.forEach((triangleIndex, index) => {
|
|
2597
|
+
const nodeOffset = (config.bvhNodeCapacity + index) * (BVH_NODE_RECORD_BYTES / 4);
|
|
2598
|
+
packedBvhNodeUints[nodeOffset + 8] = triangleIndex;
|
|
2599
|
+
});
|
|
2600
|
+
device.queue.writeBuffer(triangleBuffer, 0, packedTriangles.buffer);
|
|
2601
|
+
device.queue.writeBuffer(bvhNodeBuffer, 0, packedBvhNodes.buffer);
|
|
2602
|
+
device.queue.writeBuffer(meshVertexBuffer, 0, config.gpuMeshSource.vertices.buffer);
|
|
2603
|
+
device.queue.writeBuffer(meshIndexBuffer, 0, config.gpuMeshSource.indices.buffer);
|
|
2604
|
+
device.queue.writeBuffer(meshRangeBuffer, 0, config.gpuMeshSource.meshes.buffer);
|
|
2605
|
+
const radianceTexture = device.createTexture({
|
|
2606
|
+
label: "plasius.wavefront.radiance",
|
|
2607
|
+
size: { width: config.width, height: config.height },
|
|
2608
|
+
format: "rgba16float",
|
|
2609
|
+
usage: constants.texture.STORAGE_BINDING | constants.texture.TEXTURE_BINDING
|
|
2610
|
+
});
|
|
2611
|
+
const radianceView = radianceTexture.createView();
|
|
2612
|
+
const denoiseScratchTexture = device.createTexture({
|
|
2613
|
+
label: "plasius.wavefront.denoiseScratch",
|
|
2614
|
+
size: { width: config.width, height: config.height },
|
|
2615
|
+
format: "rgba16float",
|
|
2616
|
+
usage: constants.texture.STORAGE_BINDING | constants.texture.TEXTURE_BINDING
|
|
2617
|
+
});
|
|
2618
|
+
const denoiseScratchView = denoiseScratchTexture.createView();
|
|
2619
|
+
const outputTexture = device.createTexture({
|
|
2620
|
+
label: "plasius.wavefront.output",
|
|
2621
|
+
size: { width: config.width, height: config.height },
|
|
2622
|
+
format: "rgba8unorm",
|
|
2623
|
+
usage: constants.texture.STORAGE_BINDING | constants.texture.TEXTURE_BINDING | constants.texture.COPY_SRC
|
|
2624
|
+
});
|
|
2625
|
+
const outputView = outputTexture.createView();
|
|
2626
|
+
const sampler = device.createSampler({
|
|
2627
|
+
label: "plasius.wavefront.presentSampler",
|
|
2628
|
+
magFilter: "nearest",
|
|
2629
|
+
minFilter: "nearest"
|
|
2630
|
+
});
|
|
2631
|
+
const traceBindGroupLayout = device.createBindGroupLayout({
|
|
2632
|
+
label: "plasius.wavefront.traceBindGroupLayout",
|
|
2633
|
+
entries: [
|
|
2634
|
+
{ binding: 0, visibility: constants.shader.COMPUTE, buffer: { type: "storage" } },
|
|
2635
|
+
{ binding: 1, visibility: constants.shader.COMPUTE, buffer: { type: "storage" } },
|
|
2636
|
+
{ binding: 2, visibility: constants.shader.COMPUTE, buffer: { type: "storage" } },
|
|
2637
|
+
{ binding: 3, visibility: constants.shader.COMPUTE, buffer: { type: "storage" } },
|
|
2638
|
+
{ binding: 4, visibility: constants.shader.COMPUTE, buffer: { type: "read-only-storage" } },
|
|
2639
|
+
{
|
|
2640
|
+
binding: 5,
|
|
2641
|
+
visibility: constants.shader.COMPUTE,
|
|
2642
|
+
buffer: { type: "uniform", hasDynamicOffset: true, minBindingSize: CONFIG_BUFFER_BYTES }
|
|
2643
|
+
},
|
|
2644
|
+
{ binding: 6, visibility: constants.shader.COMPUTE, buffer: { type: "storage" } },
|
|
2645
|
+
{
|
|
2646
|
+
binding: 7,
|
|
2647
|
+
visibility: constants.shader.COMPUTE,
|
|
2648
|
+
storageTexture: { access: "write-only", format: "rgba8unorm" }
|
|
2649
|
+
},
|
|
2650
|
+
{ binding: 8, visibility: constants.shader.COMPUTE, buffer: { type: "storage" } },
|
|
2651
|
+
{ binding: 9, visibility: constants.shader.COMPUTE, buffer: { type: "storage" } },
|
|
2652
|
+
{
|
|
2653
|
+
binding: 16,
|
|
2654
|
+
visibility: constants.shader.COMPUTE,
|
|
2655
|
+
storageTexture: { access: "write-only", format: "rgba16float" }
|
|
2656
|
+
}
|
|
2657
|
+
]
|
|
2658
|
+
});
|
|
2659
|
+
const accelerationBindGroupLayout = device.createBindGroupLayout({
|
|
2660
|
+
label: "plasius.wavefront.accelerationBindGroupLayout",
|
|
2661
|
+
entries: [
|
|
2662
|
+
{
|
|
2663
|
+
binding: 5,
|
|
2664
|
+
visibility: constants.shader.COMPUTE,
|
|
2665
|
+
buffer: { type: "uniform", hasDynamicOffset: true, minBindingSize: CONFIG_BUFFER_BYTES }
|
|
2666
|
+
},
|
|
2667
|
+
{ binding: 8, visibility: constants.shader.COMPUTE, buffer: { type: "storage" } },
|
|
2668
|
+
{ binding: 9, visibility: constants.shader.COMPUTE, buffer: { type: "storage" } },
|
|
2669
|
+
{ binding: 10, visibility: constants.shader.COMPUTE, buffer: { type: "read-only-storage" } },
|
|
2670
|
+
{ binding: 11, visibility: constants.shader.COMPUTE, buffer: { type: "read-only-storage" } },
|
|
2671
|
+
{ binding: 12, visibility: constants.shader.COMPUTE, buffer: { type: "read-only-storage" } },
|
|
2672
|
+
{ binding: 13, visibility: constants.shader.COMPUTE, buffer: { type: "storage" } }
|
|
2673
|
+
]
|
|
2674
|
+
});
|
|
2675
|
+
const denoiseRadianceBindGroupLayout = device.createBindGroupLayout({
|
|
2676
|
+
label: "plasius.wavefront.denoiseRadianceBindGroupLayout",
|
|
2677
|
+
entries: [
|
|
2678
|
+
{
|
|
2679
|
+
binding: 5,
|
|
2680
|
+
visibility: constants.shader.COMPUTE,
|
|
2681
|
+
buffer: { type: "uniform", hasDynamicOffset: true, minBindingSize: CONFIG_BUFFER_BYTES }
|
|
2682
|
+
},
|
|
2683
|
+
{
|
|
2684
|
+
binding: 14,
|
|
2685
|
+
visibility: constants.shader.COMPUTE,
|
|
2686
|
+
texture: { sampleType: "float" }
|
|
2687
|
+
},
|
|
2688
|
+
{
|
|
2689
|
+
binding: 15,
|
|
2690
|
+
visibility: constants.shader.COMPUTE,
|
|
2691
|
+
storageTexture: { access: "write-only", format: "rgba16float" }
|
|
2692
|
+
}
|
|
2693
|
+
]
|
|
2694
|
+
});
|
|
2695
|
+
const denoiseResolveBindGroupLayout = device.createBindGroupLayout({
|
|
2696
|
+
label: "plasius.wavefront.denoiseResolveBindGroupLayout",
|
|
2697
|
+
entries: [
|
|
2698
|
+
{
|
|
2699
|
+
binding: 5,
|
|
2700
|
+
visibility: constants.shader.COMPUTE,
|
|
2701
|
+
buffer: { type: "uniform", hasDynamicOffset: true, minBindingSize: CONFIG_BUFFER_BYTES }
|
|
2702
|
+
},
|
|
2703
|
+
{
|
|
2704
|
+
binding: 17,
|
|
2705
|
+
visibility: constants.shader.COMPUTE,
|
|
2706
|
+
texture: { sampleType: "float" }
|
|
2707
|
+
},
|
|
2708
|
+
{
|
|
2709
|
+
binding: 18,
|
|
2710
|
+
visibility: constants.shader.COMPUTE,
|
|
2711
|
+
storageTexture: { access: "write-only", format: "rgba8unorm" }
|
|
2712
|
+
}
|
|
2713
|
+
]
|
|
2714
|
+
});
|
|
2715
|
+
const tracePipelineLayout = device.createPipelineLayout({
|
|
2716
|
+
label: "plasius.wavefront.tracePipelineLayout",
|
|
2717
|
+
bindGroupLayouts: [traceBindGroupLayout]
|
|
2718
|
+
});
|
|
2719
|
+
const accelerationPipelineLayout = device.createPipelineLayout({
|
|
2720
|
+
label: "plasius.wavefront.accelerationPipelineLayout",
|
|
2721
|
+
bindGroupLayouts: [accelerationBindGroupLayout]
|
|
2722
|
+
});
|
|
2723
|
+
const denoiseRadiancePipelineLayout = device.createPipelineLayout({
|
|
2724
|
+
label: "plasius.wavefront.denoiseRadiancePipelineLayout",
|
|
2725
|
+
bindGroupLayouts: [denoiseRadianceBindGroupLayout]
|
|
2726
|
+
});
|
|
2727
|
+
const denoiseResolvePipelineLayout = device.createPipelineLayout({
|
|
2728
|
+
label: "plasius.wavefront.denoiseResolvePipelineLayout",
|
|
2729
|
+
bindGroupLayouts: [denoiseResolveBindGroupLayout]
|
|
2730
|
+
});
|
|
2731
|
+
const computeShader = device.createShaderModule({
|
|
2732
|
+
label: "plasius.wavefront.computeShader",
|
|
2733
|
+
code: WAVEFRONT_COMPUTE_WGSL
|
|
2734
|
+
});
|
|
2735
|
+
const pipelines = {
|
|
2736
|
+
prepareMeshTrianglesAndLeaves: await createComputePipeline(
|
|
2737
|
+
device,
|
|
2738
|
+
computeShader,
|
|
2739
|
+
accelerationPipelineLayout,
|
|
2740
|
+
"prepareMeshTrianglesAndLeaves",
|
|
2741
|
+
"plasius.wavefront.prepareMeshTrianglesAndLeaves"
|
|
2742
|
+
),
|
|
2743
|
+
sortBvhLeafRefs: await createComputePipeline(
|
|
2744
|
+
device,
|
|
2745
|
+
computeShader,
|
|
2746
|
+
accelerationPipelineLayout,
|
|
2747
|
+
"sortBvhLeafRefs",
|
|
2748
|
+
"plasius.wavefront.sortBvhLeafRefs"
|
|
2749
|
+
),
|
|
2750
|
+
writeSortedBvhLeaves: await createComputePipeline(
|
|
2751
|
+
device,
|
|
2752
|
+
computeShader,
|
|
2753
|
+
accelerationPipelineLayout,
|
|
2754
|
+
"writeSortedBvhLeaves",
|
|
2755
|
+
"plasius.wavefront.writeSortedBvhLeaves"
|
|
2756
|
+
),
|
|
2757
|
+
buildBvhInternalLevel: await createComputePipeline(
|
|
2758
|
+
device,
|
|
2759
|
+
computeShader,
|
|
2760
|
+
accelerationPipelineLayout,
|
|
2761
|
+
"buildBvhInternalLevel",
|
|
2762
|
+
"plasius.wavefront.buildBvhInternalLevel"
|
|
2763
|
+
),
|
|
2764
|
+
generatePrimaryRays: await createComputePipeline(
|
|
2765
|
+
device,
|
|
2766
|
+
computeShader,
|
|
2767
|
+
tracePipelineLayout,
|
|
2768
|
+
"generatePrimaryRays",
|
|
2769
|
+
"plasius.wavefront.generatePrimaryRays"
|
|
2770
|
+
),
|
|
2771
|
+
intersectActiveQueue: await createComputePipeline(
|
|
2772
|
+
device,
|
|
2773
|
+
computeShader,
|
|
2774
|
+
tracePipelineLayout,
|
|
2775
|
+
"intersectActiveQueue",
|
|
2776
|
+
"plasius.wavefront.intersectActiveQueue"
|
|
2777
|
+
),
|
|
2778
|
+
resolveSurfaceRecords: await createComputePipeline(
|
|
2779
|
+
device,
|
|
2780
|
+
computeShader,
|
|
2781
|
+
tracePipelineLayout,
|
|
2782
|
+
"resolveSurfaceRecords",
|
|
2783
|
+
"plasius.wavefront.resolveSurfaceRecords"
|
|
2784
|
+
),
|
|
2785
|
+
compactAndSwapQueues: await createComputePipeline(
|
|
2786
|
+
device,
|
|
2787
|
+
computeShader,
|
|
2788
|
+
tracePipelineLayout,
|
|
2789
|
+
"compactAndSwapQueues",
|
|
2790
|
+
"plasius.wavefront.compactAndSwapQueues"
|
|
2791
|
+
),
|
|
2792
|
+
accumulateTerminalRadiance: await createComputePipeline(
|
|
2793
|
+
device,
|
|
2794
|
+
computeShader,
|
|
2795
|
+
tracePipelineLayout,
|
|
2796
|
+
"accumulateTerminalRadiance",
|
|
2797
|
+
"plasius.wavefront.accumulateTerminalRadiance"
|
|
2798
|
+
),
|
|
2799
|
+
denoiseLinearRadiance: await createComputePipeline(
|
|
2800
|
+
device,
|
|
2801
|
+
computeShader,
|
|
2802
|
+
denoiseRadiancePipelineLayout,
|
|
2803
|
+
"denoiseLinearRadiance",
|
|
2804
|
+
"plasius.wavefront.denoiseLinearRadiance"
|
|
2805
|
+
),
|
|
2806
|
+
resolveDenoisedOutputImage: await createComputePipeline(
|
|
2807
|
+
device,
|
|
2808
|
+
computeShader,
|
|
2809
|
+
denoiseResolvePipelineLayout,
|
|
2810
|
+
"resolveDenoisedOutputImage",
|
|
2811
|
+
"plasius.wavefront.resolveDenoisedOutputImage"
|
|
2812
|
+
)
|
|
2813
|
+
};
|
|
2814
|
+
function createTraceBindGroup(activeBuffer, nextBuffer, label, frameConfigBuffer = configBuffer) {
|
|
2815
|
+
return device.createBindGroup({
|
|
2816
|
+
label,
|
|
2817
|
+
layout: traceBindGroupLayout,
|
|
2818
|
+
entries: [
|
|
2819
|
+
{ binding: 0, resource: { buffer: activeBuffer } },
|
|
2820
|
+
{ binding: 1, resource: { buffer: nextBuffer } },
|
|
2821
|
+
{ binding: 2, resource: { buffer: hitBuffer } },
|
|
2822
|
+
{ binding: 3, resource: { buffer: accumulationBuffer } },
|
|
2823
|
+
{ binding: 4, resource: { buffer: sceneObjectBuffer } },
|
|
2824
|
+
{ binding: 5, resource: { buffer: frameConfigBuffer, size: CONFIG_BUFFER_BYTES } },
|
|
2825
|
+
{ binding: 6, resource: { buffer: counterBuffer } },
|
|
2826
|
+
{ binding: 7, resource: outputView },
|
|
2827
|
+
{ binding: 8, resource: { buffer: triangleBuffer } },
|
|
2828
|
+
{ binding: 9, resource: { buffer: bvhNodeBuffer } },
|
|
2829
|
+
{ binding: 16, resource: radianceView }
|
|
2830
|
+
]
|
|
2831
|
+
});
|
|
2832
|
+
}
|
|
2833
|
+
const bindGroups = [
|
|
2834
|
+
createTraceBindGroup(activeQueue, nextQueue, "plasius.wavefront.bind.activeNext"),
|
|
2835
|
+
createTraceBindGroup(nextQueue, activeQueue, "plasius.wavefront.bind.nextActive")
|
|
2836
|
+
];
|
|
2837
|
+
const bvhBuildBindGroup = device.createBindGroup({
|
|
2838
|
+
label: "plasius.wavefront.bind.bvhBuild",
|
|
2839
|
+
layout: accelerationBindGroupLayout,
|
|
2840
|
+
entries: [
|
|
2841
|
+
{ binding: 5, resource: { buffer: bvhBuildConfigBuffer, size: CONFIG_BUFFER_BYTES } },
|
|
2842
|
+
{ binding: 8, resource: { buffer: triangleBuffer } },
|
|
2843
|
+
{ binding: 9, resource: { buffer: bvhNodeBuffer } },
|
|
2844
|
+
{ binding: 10, resource: { buffer: meshVertexBuffer } },
|
|
2845
|
+
{ binding: 11, resource: { buffer: meshIndexBuffer } },
|
|
2846
|
+
{ binding: 12, resource: { buffer: meshRangeBuffer } },
|
|
2847
|
+
{ binding: 13, resource: { buffer: bvhLeafRefBuffer } }
|
|
2848
|
+
]
|
|
2849
|
+
});
|
|
2850
|
+
function createDenoiseRadianceBindGroup(inputView, targetView, label) {
|
|
2851
|
+
return device.createBindGroup({
|
|
2852
|
+
label,
|
|
2853
|
+
layout: denoiseRadianceBindGroupLayout,
|
|
2854
|
+
entries: [
|
|
2855
|
+
{ binding: 5, resource: { buffer: configBuffer, size: CONFIG_BUFFER_BYTES } },
|
|
2856
|
+
{ binding: 14, resource: inputView },
|
|
2857
|
+
{ binding: 15, resource: targetView }
|
|
2858
|
+
]
|
|
2859
|
+
});
|
|
2860
|
+
}
|
|
2861
|
+
function createDenoiseResolveBindGroup(inputView, targetView, label) {
|
|
2862
|
+
return device.createBindGroup({
|
|
2863
|
+
label,
|
|
2864
|
+
layout: denoiseResolveBindGroupLayout,
|
|
2865
|
+
entries: [
|
|
2866
|
+
{ binding: 5, resource: { buffer: configBuffer, size: CONFIG_BUFFER_BYTES } },
|
|
2867
|
+
{ binding: 17, resource: inputView },
|
|
2868
|
+
{ binding: 18, resource: targetView }
|
|
2869
|
+
]
|
|
2870
|
+
});
|
|
2871
|
+
}
|
|
2872
|
+
const denoiseRadianceBindGroup = createDenoiseRadianceBindGroup(
|
|
2873
|
+
radianceView,
|
|
2874
|
+
denoiseScratchView,
|
|
2875
|
+
"plasius.wavefront.bind.denoise.radianceToScratch"
|
|
2876
|
+
);
|
|
2877
|
+
const denoiseResolveBindGroup = createDenoiseResolveBindGroup(
|
|
2878
|
+
denoiseScratchView,
|
|
2879
|
+
outputView,
|
|
2880
|
+
"plasius.wavefront.bind.denoise.scratchToOutput"
|
|
2881
|
+
);
|
|
2882
|
+
const presentBindGroupLayout = device.createBindGroupLayout({
|
|
2883
|
+
label: "plasius.wavefront.presentBindGroupLayout",
|
|
2884
|
+
entries: [
|
|
2885
|
+
{ binding: 0, visibility: constants.shader.FRAGMENT, texture: { sampleType: "float" } },
|
|
2886
|
+
{ binding: 1, visibility: constants.shader.FRAGMENT, sampler: { type: "filtering" } }
|
|
2887
|
+
]
|
|
2888
|
+
});
|
|
2889
|
+
const presentShader = device.createShaderModule({
|
|
2890
|
+
label: "plasius.wavefront.presentShader",
|
|
2891
|
+
code: PRESENT_WGSL
|
|
2892
|
+
});
|
|
2893
|
+
const presentPipeline = await createRenderPipeline(device, {
|
|
2894
|
+
label: "plasius.wavefront.presentPipeline",
|
|
2895
|
+
layout: device.createPipelineLayout({
|
|
2896
|
+
label: "plasius.wavefront.presentPipelineLayout",
|
|
2897
|
+
bindGroupLayouts: [presentBindGroupLayout]
|
|
2898
|
+
}),
|
|
2899
|
+
vertex: { module: presentShader, entryPoint: "vertexMain" },
|
|
2900
|
+
fragment: {
|
|
2901
|
+
module: presentShader,
|
|
2902
|
+
entryPoint: "fragmentMain",
|
|
2903
|
+
targets: [{ format }]
|
|
2904
|
+
},
|
|
2905
|
+
primitive: { topology: "triangle-list" }
|
|
2906
|
+
});
|
|
2907
|
+
const presentBindGroup = device.createBindGroup({
|
|
2908
|
+
label: "plasius.wavefront.presentBindGroup",
|
|
2909
|
+
layout: presentBindGroupLayout,
|
|
2910
|
+
entries: [
|
|
2911
|
+
{ binding: 0, resource: outputView },
|
|
2912
|
+
{ binding: 1, resource: sampler }
|
|
2913
|
+
]
|
|
2914
|
+
});
|
|
2915
|
+
let frame = 0;
|
|
2916
|
+
const tiles = createTiles(config.width, config.height, config.tileSize);
|
|
2917
|
+
function dispatchGpuAccelerationBuild(frameIndex) {
|
|
2918
|
+
if (!config.gpuAccelerationBuildRequired) {
|
|
2919
|
+
return;
|
|
2920
|
+
}
|
|
2921
|
+
const buildTile = tiles[0] ?? { x: 0, y: 0, width: 1, height: 1 };
|
|
2922
|
+
const encoder = device.createCommandEncoder({
|
|
2923
|
+
label: `plasius.wavefront.buildAcceleration.${frameIndex}`
|
|
2924
|
+
});
|
|
2925
|
+
device.queue.writeBuffer(
|
|
2926
|
+
bvhBuildConfigBuffer,
|
|
2927
|
+
0,
|
|
2928
|
+
createConfigPayload(config, buildTile, frameIndex, {
|
|
2929
|
+
sortItemCount: config.bvhLeafSortCapacity
|
|
2930
|
+
})
|
|
2931
|
+
);
|
|
2932
|
+
config.bvhSortStages.forEach((sortStage, stageIndex) => {
|
|
2933
|
+
device.queue.writeBuffer(
|
|
2934
|
+
bvhBuildConfigBuffer,
|
|
2935
|
+
(stageIndex + 1) * configBufferStride,
|
|
2936
|
+
createConfigPayload(config, buildTile, frameIndex, {
|
|
2937
|
+
start: sortStage.compareDistance,
|
|
2938
|
+
count: sortStage.sequenceSize,
|
|
2939
|
+
sortItemCount: config.bvhLeafSortCapacity
|
|
2940
|
+
})
|
|
2941
|
+
);
|
|
2942
|
+
});
|
|
2943
|
+
const buildLevelConfigStart = 1 + config.bvhSortStages.length;
|
|
2944
|
+
config.bvhBuildLevels.forEach((buildLevel, levelIndex) => {
|
|
2945
|
+
device.queue.writeBuffer(
|
|
2946
|
+
bvhBuildConfigBuffer,
|
|
2947
|
+
(buildLevelConfigStart + levelIndex) * configBufferStride,
|
|
2948
|
+
createConfigPayload(config, buildTile, frameIndex, buildLevel)
|
|
2949
|
+
);
|
|
2950
|
+
});
|
|
2951
|
+
const passEncoder = encoder.beginComputePass({
|
|
2952
|
+
label: "plasius.wavefront.buildAccelerationPass"
|
|
2953
|
+
});
|
|
2954
|
+
passEncoder.setBindGroup(0, bvhBuildBindGroup, [0]);
|
|
2955
|
+
passEncoder.setPipeline(pipelines.prepareMeshTrianglesAndLeaves);
|
|
2956
|
+
passEncoder.dispatchWorkgroups(Math.ceil(config.bvhLeafSortCapacity / WORKGROUP_SIZE));
|
|
2957
|
+
passEncoder.setPipeline(pipelines.sortBvhLeafRefs);
|
|
2958
|
+
for (let stageIndex = 0; stageIndex < config.bvhSortStages.length; stageIndex += 1) {
|
|
2959
|
+
passEncoder.setBindGroup(0, bvhBuildBindGroup, [
|
|
2960
|
+
(stageIndex + 1) * configBufferStride
|
|
2961
|
+
]);
|
|
2962
|
+
passEncoder.dispatchWorkgroups(Math.ceil(config.bvhLeafSortCapacity / WORKGROUP_SIZE));
|
|
2963
|
+
}
|
|
2964
|
+
passEncoder.setBindGroup(0, bvhBuildBindGroup, [0]);
|
|
2965
|
+
passEncoder.setPipeline(pipelines.writeSortedBvhLeaves);
|
|
2966
|
+
passEncoder.dispatchWorkgroups(Math.ceil(config.triangleCount / WORKGROUP_SIZE));
|
|
2967
|
+
passEncoder.setPipeline(pipelines.buildBvhInternalLevel);
|
|
2968
|
+
for (let levelIndex = 0; levelIndex < config.bvhBuildLevels.length; levelIndex += 1) {
|
|
2969
|
+
const buildLevel = config.bvhBuildLevels[levelIndex];
|
|
2970
|
+
passEncoder.setBindGroup(0, bvhBuildBindGroup, [
|
|
2971
|
+
(buildLevelConfigStart + levelIndex) * configBufferStride
|
|
2972
|
+
]);
|
|
2973
|
+
passEncoder.dispatchWorkgroups(Math.ceil(buildLevel.count / WORKGROUP_SIZE));
|
|
2974
|
+
}
|
|
2975
|
+
passEncoder.end();
|
|
2976
|
+
device.queue.submit([encoder.finish()]);
|
|
2977
|
+
}
|
|
2978
|
+
function dispatchTileSample(tile, frameIndex, sampleIndex) {
|
|
2979
|
+
const sampleWeight = 1 / config.samplesPerPixel;
|
|
2980
|
+
const configPayload = createConfigPayload(config, tile, frameIndex, {
|
|
2981
|
+
sampleIndex,
|
|
2982
|
+
sampleWeight
|
|
2983
|
+
});
|
|
2984
|
+
device.queue.writeBuffer(configBuffer, 0, configPayload);
|
|
2985
|
+
const encoder = device.createCommandEncoder({
|
|
2986
|
+
label: `plasius.wavefront.frame.${frameIndex}.tile.${tile.x}.${tile.y}.sample.${sampleIndex}`
|
|
2987
|
+
});
|
|
2988
|
+
const passEncoder = encoder.beginComputePass({
|
|
2989
|
+
label: "plasius.wavefront.computePass"
|
|
2990
|
+
});
|
|
2991
|
+
const tileWorkgroups = Math.ceil(tile.width * tile.height / WORKGROUP_SIZE);
|
|
2992
|
+
const capacityWorkgroups = Math.ceil(config.tilePixelCapacity / WORKGROUP_SIZE);
|
|
2993
|
+
passEncoder.setBindGroup(0, bindGroups[0], [0]);
|
|
2994
|
+
passEncoder.setPipeline(pipelines.generatePrimaryRays);
|
|
2995
|
+
passEncoder.dispatchWorkgroups(tileWorkgroups);
|
|
2996
|
+
for (let bounceIndex = 0; bounceIndex < config.maxDepth; bounceIndex += 1) {
|
|
2997
|
+
passEncoder.setBindGroup(0, bindGroups[bounceIndex % 2], [0]);
|
|
2998
|
+
passEncoder.setPipeline(pipelines.intersectActiveQueue);
|
|
2999
|
+
passEncoder.dispatchWorkgroups(capacityWorkgroups);
|
|
3000
|
+
passEncoder.setPipeline(pipelines.resolveSurfaceRecords);
|
|
3001
|
+
passEncoder.dispatchWorkgroups(capacityWorkgroups);
|
|
3002
|
+
passEncoder.setPipeline(pipelines.compactAndSwapQueues);
|
|
3003
|
+
passEncoder.dispatchWorkgroups(1);
|
|
3004
|
+
}
|
|
3005
|
+
passEncoder.end();
|
|
3006
|
+
device.queue.submit([encoder.finish()]);
|
|
3007
|
+
}
|
|
3008
|
+
function dispatchTileOutput(tile, frameIndex) {
|
|
3009
|
+
const configPayload = createConfigPayload(config, tile, frameIndex, {
|
|
3010
|
+
sampleIndex: 0,
|
|
3011
|
+
sampleWeight: 1 / config.samplesPerPixel
|
|
3012
|
+
});
|
|
3013
|
+
device.queue.writeBuffer(configBuffer, 0, configPayload);
|
|
3014
|
+
const encoder = device.createCommandEncoder({
|
|
3015
|
+
label: `plasius.wavefront.frame.${frameIndex}.tile.${tile.x}.${tile.y}.output`
|
|
3016
|
+
});
|
|
3017
|
+
const passEncoder = encoder.beginComputePass({
|
|
3018
|
+
label: "plasius.wavefront.outputPass"
|
|
3019
|
+
});
|
|
3020
|
+
const tileWorkgroups = Math.ceil(tile.width * tile.height / WORKGROUP_SIZE);
|
|
3021
|
+
passEncoder.setBindGroup(0, bindGroups[0], [0]);
|
|
3022
|
+
passEncoder.setPipeline(pipelines.accumulateTerminalRadiance);
|
|
3023
|
+
passEncoder.dispatchWorkgroups(tileWorkgroups);
|
|
3024
|
+
passEncoder.end();
|
|
3025
|
+
device.queue.submit([encoder.finish()]);
|
|
3026
|
+
}
|
|
3027
|
+
function dispatchTile(tile, frameIndex) {
|
|
3028
|
+
for (let sampleIndex = 0; sampleIndex < config.samplesPerPixel; sampleIndex += 1) {
|
|
3029
|
+
dispatchTileSample(tile, frameIndex, sampleIndex);
|
|
3030
|
+
}
|
|
3031
|
+
dispatchTileOutput(tile, frameIndex);
|
|
3032
|
+
}
|
|
3033
|
+
function dispatchDenoise(frameIndex) {
|
|
3034
|
+
if (!config.denoise) {
|
|
3035
|
+
return;
|
|
3036
|
+
}
|
|
3037
|
+
device.queue.writeBuffer(
|
|
3038
|
+
configBuffer,
|
|
3039
|
+
0,
|
|
3040
|
+
createConfigPayload(
|
|
3041
|
+
config,
|
|
3042
|
+
{ x: 0, y: 0, width: config.width, height: config.height },
|
|
3043
|
+
frameIndex,
|
|
3044
|
+
{ sampleIndex: 0, sampleWeight: 1 / config.samplesPerPixel }
|
|
3045
|
+
)
|
|
3046
|
+
);
|
|
3047
|
+
const encoder = device.createCommandEncoder({
|
|
3048
|
+
label: `plasius.wavefront.frame.${frameIndex}.denoise`
|
|
3049
|
+
});
|
|
3050
|
+
const radiancePass = encoder.beginComputePass({
|
|
3051
|
+
label: "plasius.wavefront.denoiseRadiancePass"
|
|
3052
|
+
});
|
|
3053
|
+
radiancePass.setBindGroup(0, denoiseRadianceBindGroup, [0]);
|
|
3054
|
+
radiancePass.setPipeline(pipelines.denoiseLinearRadiance);
|
|
3055
|
+
radiancePass.dispatchWorkgroups(Math.ceil(config.width / 8), Math.ceil(config.height / 8));
|
|
3056
|
+
radiancePass.end();
|
|
3057
|
+
const resolvePass = encoder.beginComputePass({
|
|
3058
|
+
label: "plasius.wavefront.denoiseResolvePass"
|
|
3059
|
+
});
|
|
3060
|
+
resolvePass.setBindGroup(0, denoiseResolveBindGroup, [0]);
|
|
3061
|
+
resolvePass.setPipeline(pipelines.resolveDenoisedOutputImage);
|
|
3062
|
+
resolvePass.dispatchWorkgroups(Math.ceil(config.width / 8), Math.ceil(config.height / 8));
|
|
3063
|
+
resolvePass.end();
|
|
3064
|
+
device.queue.submit([encoder.finish()]);
|
|
3065
|
+
}
|
|
3066
|
+
function present() {
|
|
3067
|
+
const texture = context.getCurrentTexture();
|
|
3068
|
+
const encoder = device.createCommandEncoder({
|
|
3069
|
+
label: `plasius.wavefront.present.${frame}`
|
|
3070
|
+
});
|
|
3071
|
+
const passEncoder = encoder.beginRenderPass({
|
|
3072
|
+
label: "plasius.wavefront.presentPass",
|
|
3073
|
+
colorAttachments: [
|
|
3074
|
+
{
|
|
3075
|
+
view: texture.createView(),
|
|
3076
|
+
clearValue: { r: 0, g: 0, b: 0, a: 1 },
|
|
3077
|
+
loadOp: "clear",
|
|
3078
|
+
storeOp: "store"
|
|
3079
|
+
}
|
|
3080
|
+
]
|
|
3081
|
+
});
|
|
3082
|
+
passEncoder.setPipeline(presentPipeline);
|
|
3083
|
+
passEncoder.setBindGroup(0, presentBindGroup);
|
|
3084
|
+
passEncoder.draw(3);
|
|
3085
|
+
passEncoder.end();
|
|
3086
|
+
device.queue.submit([encoder.finish()]);
|
|
3087
|
+
}
|
|
3088
|
+
function renderOnce() {
|
|
3089
|
+
frame += 1;
|
|
3090
|
+
dispatchGpuAccelerationBuild(frame + config.frameIndex);
|
|
3091
|
+
for (const tile of tiles) {
|
|
3092
|
+
dispatchTile(tile, frame + config.frameIndex);
|
|
3093
|
+
}
|
|
3094
|
+
dispatchDenoise(frame + config.frameIndex);
|
|
3095
|
+
present();
|
|
3096
|
+
return Object.freeze({
|
|
3097
|
+
frame,
|
|
3098
|
+
width: config.width,
|
|
3099
|
+
height: config.height,
|
|
3100
|
+
maxDepth: config.maxDepth,
|
|
3101
|
+
tiles: tiles.length,
|
|
3102
|
+
tileSize: config.tileSize,
|
|
3103
|
+
samplesPerPixel: config.samplesPerPixel,
|
|
3104
|
+
screenRays: config.width * config.height,
|
|
3105
|
+
primaryRays: config.width * config.height * config.samplesPerPixel,
|
|
3106
|
+
sceneObjectCount: config.sceneObjectCount,
|
|
3107
|
+
triangleCount: config.triangleCount,
|
|
3108
|
+
emissiveTriangleCount: config.emissiveTriangleCount,
|
|
3109
|
+
bvhNodeCount: config.bvhNodeCount,
|
|
3110
|
+
displayQuality: config.displayQuality,
|
|
3111
|
+
accelerationBuildMode: config.accelerationBuildMode,
|
|
3112
|
+
gpuAccelerationBuildRequired: config.gpuAccelerationBuildRequired,
|
|
3113
|
+
memory: config.memory
|
|
3114
|
+
});
|
|
3115
|
+
}
|
|
3116
|
+
async function readOutputProbe(optionsForProbe = {}) {
|
|
3117
|
+
const mapMode = constants.map;
|
|
3118
|
+
if (!mapMode) {
|
|
3119
|
+
throw new Error("GPUMapMode.READ is unavailable in this environment.");
|
|
3120
|
+
}
|
|
3121
|
+
const x = clamp(readNonNegativeInteger("x", optionsForProbe.x, Math.floor(config.width / 2)), 0, config.width - 1);
|
|
3122
|
+
const y = clamp(readNonNegativeInteger("y", optionsForProbe.y, Math.floor(config.height / 2)), 0, config.height - 1);
|
|
3123
|
+
const readback = device.createBuffer({
|
|
3124
|
+
label: "plasius.wavefront.outputProbe",
|
|
3125
|
+
size: 256,
|
|
3126
|
+
usage: constants.buffer.COPY_DST | constants.buffer.MAP_READ
|
|
3127
|
+
});
|
|
3128
|
+
const encoder = device.createCommandEncoder({
|
|
3129
|
+
label: "plasius.wavefront.outputProbe.copy"
|
|
3130
|
+
});
|
|
3131
|
+
encoder.copyTextureToBuffer(
|
|
3132
|
+
{ texture: outputTexture, origin: { x, y } },
|
|
3133
|
+
{ buffer: readback, bytesPerRow: 256, rowsPerImage: 1 },
|
|
3134
|
+
{ width: 1, height: 1, depthOrArrayLayers: 1 }
|
|
3135
|
+
);
|
|
3136
|
+
device.queue.submit([encoder.finish()]);
|
|
3137
|
+
await readback.mapAsync(mapMode.READ);
|
|
3138
|
+
const bytes = new Uint8Array(readback.getMappedRange()).slice(0, 4);
|
|
3139
|
+
readback.unmap();
|
|
3140
|
+
readback.destroy?.();
|
|
3141
|
+
return Object.freeze({
|
|
3142
|
+
x,
|
|
3143
|
+
y,
|
|
3144
|
+
rgba: Object.freeze(Array.from(bytes)),
|
|
3145
|
+
luminance: (0.2126 * bytes[0] + 0.7152 * bytes[1] + 0.0722 * bytes[2]) / 255
|
|
3146
|
+
});
|
|
3147
|
+
}
|
|
3148
|
+
function updateSceneObjects(sceneObjects) {
|
|
3149
|
+
const nextPackedScene = packWavefrontSceneObjects(sceneObjects, config.sceneObjectCapacity);
|
|
3150
|
+
packedScene = nextPackedScene;
|
|
3151
|
+
config = createWavefrontPathTracingComputeConfig({
|
|
3152
|
+
...options,
|
|
3153
|
+
canvas,
|
|
3154
|
+
width: config.width,
|
|
3155
|
+
height: config.height,
|
|
3156
|
+
maxDepth: config.maxDepth,
|
|
3157
|
+
tileSize: config.tileSize,
|
|
3158
|
+
samplesPerPixel: config.samplesPerPixel,
|
|
3159
|
+
sceneObjectCapacity: config.sceneObjectCapacity,
|
|
3160
|
+
sceneObjects: packedScene.objects,
|
|
3161
|
+
frameIndex: config.frameIndex
|
|
3162
|
+
});
|
|
3163
|
+
device.queue.writeBuffer(sceneObjectBuffer, 0, packedScene.buffer);
|
|
3164
|
+
return config;
|
|
3165
|
+
}
|
|
3166
|
+
function getSnapshot() {
|
|
3167
|
+
return Object.freeze({
|
|
3168
|
+
frame,
|
|
3169
|
+
width: config.width,
|
|
3170
|
+
height: config.height,
|
|
3171
|
+
maxDepth: config.maxDepth,
|
|
3172
|
+
tiles: tiles.length,
|
|
3173
|
+
tileSize: config.tileSize,
|
|
3174
|
+
samplesPerPixel: config.samplesPerPixel,
|
|
3175
|
+
sceneObjectCount: config.sceneObjectCount,
|
|
3176
|
+
triangleCount: config.triangleCount,
|
|
3177
|
+
emissiveTriangleCount: config.emissiveTriangleCount,
|
|
3178
|
+
bvhNodeCount: config.bvhNodeCount,
|
|
3179
|
+
displayQuality: config.displayQuality,
|
|
3180
|
+
accelerationBuildMode: config.accelerationBuildMode,
|
|
3181
|
+
gpuAccelerationBuildRequired: config.gpuAccelerationBuildRequired,
|
|
3182
|
+
memory: config.memory
|
|
3183
|
+
});
|
|
3184
|
+
}
|
|
3185
|
+
function destroy() {
|
|
3186
|
+
activeQueue.destroy?.();
|
|
3187
|
+
nextQueue.destroy?.();
|
|
3188
|
+
hitBuffer.destroy?.();
|
|
3189
|
+
accumulationBuffer.destroy?.();
|
|
3190
|
+
sceneObjectBuffer.destroy?.();
|
|
3191
|
+
triangleBuffer.destroy?.();
|
|
3192
|
+
bvhNodeBuffer.destroy?.();
|
|
3193
|
+
meshVertexBuffer.destroy?.();
|
|
3194
|
+
meshIndexBuffer.destroy?.();
|
|
3195
|
+
meshRangeBuffer.destroy?.();
|
|
3196
|
+
bvhLeafRefBuffer.destroy?.();
|
|
3197
|
+
configBuffer.destroy?.();
|
|
3198
|
+
bvhBuildConfigBuffer.destroy?.();
|
|
3199
|
+
counterBuffer.destroy?.();
|
|
3200
|
+
radianceTexture.destroy?.();
|
|
3201
|
+
denoiseScratchTexture.destroy?.();
|
|
3202
|
+
outputTexture.destroy?.();
|
|
3203
|
+
context.unconfigure?.();
|
|
3204
|
+
}
|
|
3205
|
+
return Object.freeze({
|
|
3206
|
+
canvas,
|
|
3207
|
+
context,
|
|
3208
|
+
device,
|
|
3209
|
+
format,
|
|
3210
|
+
config,
|
|
3211
|
+
renderOnce,
|
|
3212
|
+
readOutputProbe,
|
|
3213
|
+
updateSceneObjects,
|
|
3214
|
+
getSnapshot,
|
|
3215
|
+
destroy
|
|
3216
|
+
});
|
|
3217
|
+
}
|
|
3218
|
+
|
|
1
3219
|
// src/index.js
|
|
2
3220
|
var DEFAULT_CLEAR_COLOR = Object.freeze([0.07, 0.11, 0.18, 1]);
|
|
3
3221
|
var DEFAULT_CANVAS_SELECTOR = "canvas[data-plasius-gpu-renderer]";
|
|
@@ -28,6 +3246,23 @@ var rendererRayTracingStageOrder = Object.freeze([
|
|
|
28
3246
|
"composition",
|
|
29
3247
|
"present"
|
|
30
3248
|
]);
|
|
3249
|
+
var rendererWavefrontBufferSchemaVersion = 1;
|
|
3250
|
+
var rendererWavefrontQueuePairStrategy = "ping-pong-active-next";
|
|
3251
|
+
var rendererWavefrontHitTypes = Object.freeze([
|
|
3252
|
+
"surface",
|
|
3253
|
+
"emissive",
|
|
3254
|
+
"environment",
|
|
3255
|
+
"transparent",
|
|
3256
|
+
"miss"
|
|
3257
|
+
]);
|
|
3258
|
+
var rendererWavefrontPassOrder = Object.freeze([
|
|
3259
|
+
"generatePrimaryRays",
|
|
3260
|
+
"intersectActiveQueue",
|
|
3261
|
+
"resolveSurfaceRecords",
|
|
3262
|
+
"accumulateTerminalRadiance",
|
|
3263
|
+
"scatterContinuations",
|
|
3264
|
+
"compactAndSwapQueues"
|
|
3265
|
+
]);
|
|
31
3266
|
var rendererRayTracingStageDefinitions = Object.freeze(
|
|
32
3267
|
rendererRayTracingStageOrder.map(
|
|
33
3268
|
(key, index) => Object.freeze({
|
|
@@ -96,6 +3331,153 @@ var rendererAccelerationStructurePolicies = Object.freeze(
|
|
|
96
3331
|
})
|
|
97
3332
|
)
|
|
98
3333
|
);
|
|
3334
|
+
function createWavefrontField(name, type, description) {
|
|
3335
|
+
return Object.freeze({
|
|
3336
|
+
name,
|
|
3337
|
+
type,
|
|
3338
|
+
description
|
|
3339
|
+
});
|
|
3340
|
+
}
|
|
3341
|
+
var rendererWavefrontBufferContracts = Object.freeze({
|
|
3342
|
+
ray: Object.freeze({
|
|
3343
|
+
schemaVersion: rendererWavefrontBufferSchemaVersion,
|
|
3344
|
+
recordName: "RayRecord",
|
|
3345
|
+
fields: Object.freeze([
|
|
3346
|
+
createWavefrontField("rayId", "u32", "Stable ray identifier for correlation and debugging."),
|
|
3347
|
+
createWavefrontField("parentRayId", "u32", "Parent ray identifier for continuation lineage."),
|
|
3348
|
+
createWavefrontField("sourcePixelId", "u32", "Screen pixel or texel that owns the sample."),
|
|
3349
|
+
createWavefrontField("sampleId", "u32", "Per-pixel sample slot for accumulation."),
|
|
3350
|
+
createWavefrontField("bounce", "u32", "Breadth-first bounce depth for the queue entry."),
|
|
3351
|
+
createWavefrontField("origin", "vec3<f32>", "Ray origin in renderer world space."),
|
|
3352
|
+
createWavefrontField("direction", "vec3<f32>", "Normalized ray direction in renderer world space."),
|
|
3353
|
+
createWavefrontField("throughput", "vec3<f32>", "Current path throughput before the next event."),
|
|
3354
|
+
createWavefrontField("mediumRefId", "u32", "Active medium reference identifier for the ray."),
|
|
3355
|
+
createWavefrontField("flags", "u32", "Bit flags for front-face state, debug, and quality toggles.")
|
|
3356
|
+
])
|
|
3357
|
+
}),
|
|
3358
|
+
hit: Object.freeze({
|
|
3359
|
+
schemaVersion: rendererWavefrontBufferSchemaVersion,
|
|
3360
|
+
recordName: "HitRecord",
|
|
3361
|
+
fields: Object.freeze([
|
|
3362
|
+
createWavefrontField("rayId", "u32", "Ray identifier copied from the active queue."),
|
|
3363
|
+
createWavefrontField("sourcePixelId", "u32", "Pixel/texel owner for the ray sample."),
|
|
3364
|
+
createWavefrontField("hitType", rendererWavefrontHitTypes.join(" | "), "Resolved hit classification for termination or continuation."),
|
|
3365
|
+
createWavefrontField("distance", "f32", "Nearest-hit distance or miss sentinel."),
|
|
3366
|
+
createWavefrontField("entityId", "u32", "Stable scene entity identifier."),
|
|
3367
|
+
createWavefrontField("instanceId", "u32", "Renderer instance identifier."),
|
|
3368
|
+
createWavefrontField("primitiveId", "u32", "Primitive or triangle identifier."),
|
|
3369
|
+
createWavefrontField("materialId", "u32", "Surface material identifier."),
|
|
3370
|
+
createWavefrontField("barycentrics", "vec3<f32>", "Triangle barycentric coordinates for interpolation."),
|
|
3371
|
+
createWavefrontField("uv", "vec2<f32>", "Resolved surface UV when available."),
|
|
3372
|
+
createWavefrontField("geometricNormal", "vec3<f32>", "True geometric face normal."),
|
|
3373
|
+
createWavefrontField("shadingNormal", "vec3<f32>", "Interpolated or repaired shading normal."),
|
|
3374
|
+
createWavefrontField("frontFace", "bool", "Front-face classification for shading and medium transitions.")
|
|
3375
|
+
])
|
|
3376
|
+
}),
|
|
3377
|
+
surface: Object.freeze({
|
|
3378
|
+
schemaVersion: rendererWavefrontBufferSchemaVersion,
|
|
3379
|
+
recordName: "SurfaceRecord",
|
|
3380
|
+
fields: Object.freeze([
|
|
3381
|
+
createWavefrontField("rayId", "u32", "Ray identifier matched to the resolved hit."),
|
|
3382
|
+
createWavefrontField("entityId", "u32", "Stable scene entity identifier."),
|
|
3383
|
+
createWavefrontField("materialRefId", "u32", "Material-reference indirection for shading lookup tables."),
|
|
3384
|
+
createWavefrontField("mediumRefId", "u32", "Resolved medium transition/reference identifier."),
|
|
3385
|
+
createWavefrontField("geometricNormal", "vec3<f32>", "Preserved geometric normal for hemisphere checks."),
|
|
3386
|
+
createWavefrontField("shadingNormal", "vec3<f32>", "Normal used for BSDF/BTDF evaluation."),
|
|
3387
|
+
createWavefrontField("uv", "vec2<f32>", "Resolved texture coordinate."),
|
|
3388
|
+
createWavefrontField("tangentFrame", "mat3x3<f32>", "Optional tangent basis for normal-map transforms.")
|
|
3389
|
+
])
|
|
3390
|
+
}),
|
|
3391
|
+
materialReference: Object.freeze({
|
|
3392
|
+
schemaVersion: rendererWavefrontBufferSchemaVersion,
|
|
3393
|
+
recordName: "MaterialReferenceRecord",
|
|
3394
|
+
fields: Object.freeze([
|
|
3395
|
+
createWavefrontField("materialRefId", "u32", "Stable material lookup identifier."),
|
|
3396
|
+
createWavefrontField("materialId", "u32", "Authoritative material id from scene submission."),
|
|
3397
|
+
createWavefrontField("shadingModel", "u32", "Renderer-owned shading model enum."),
|
|
3398
|
+
createWavefrontField("textureSetId", "u32", "Texture indirection set for the material."),
|
|
3399
|
+
createWavefrontField("flags", "u32", "Alpha, emissive, transmission, and debug flags.")
|
|
3400
|
+
])
|
|
3401
|
+
}),
|
|
3402
|
+
mediumReference: Object.freeze({
|
|
3403
|
+
schemaVersion: rendererWavefrontBufferSchemaVersion,
|
|
3404
|
+
recordName: "MediumReferenceRecord",
|
|
3405
|
+
fields: Object.freeze([
|
|
3406
|
+
createWavefrontField("mediumRefId", "u32", "Stable medium lookup identifier."),
|
|
3407
|
+
createWavefrontField("mediumId", "u32", "Authoritative medium or fluid descriptor id."),
|
|
3408
|
+
createWavefrontField("phaseModel", "u32", "Medium phase-function selector."),
|
|
3409
|
+
createWavefrontField("absorption", "vec3<f32>", "Absorption coefficients for the active medium."),
|
|
3410
|
+
createWavefrontField("scattering", "vec3<f32>", "Scattering coefficients for the active medium.")
|
|
3411
|
+
])
|
|
3412
|
+
}),
|
|
3413
|
+
accumulation: Object.freeze({
|
|
3414
|
+
schemaVersion: rendererWavefrontBufferSchemaVersion,
|
|
3415
|
+
recordName: "AccumulationRecord",
|
|
3416
|
+
fields: Object.freeze([
|
|
3417
|
+
createWavefrontField("sourcePixelId", "u32", "Screen pixel or texel accumulator owner."),
|
|
3418
|
+
createWavefrontField("sampleCount", "u32", "Committed sample count for the pixel."),
|
|
3419
|
+
createWavefrontField("radiance", "vec3<f32>", "Accumulated radiance before tone-map/output resolve."),
|
|
3420
|
+
createWavefrontField("throughput", "vec3<f32>", "Last surviving throughput for debug and variance tracking."),
|
|
3421
|
+
createWavefrontField("resetEpoch", "u32", "Accumulation reset generation for history invalidation.")
|
|
3422
|
+
])
|
|
3423
|
+
})
|
|
3424
|
+
});
|
|
3425
|
+
function buildWavefrontTerminationPolicy() {
|
|
3426
|
+
return Object.freeze({
|
|
3427
|
+
terminalHitTypes: Object.freeze(["emissive", "environment", "miss"]),
|
|
3428
|
+
continuationHitTypes: Object.freeze(["surface", "transparent"]),
|
|
3429
|
+
emissive: Object.freeze({
|
|
3430
|
+
action: "accumulate-and-stop",
|
|
3431
|
+
contributesRadiance: true
|
|
3432
|
+
}),
|
|
3433
|
+
environment: Object.freeze({
|
|
3434
|
+
action: "accumulate-and-stop",
|
|
3435
|
+
contributesRadiance: true
|
|
3436
|
+
}),
|
|
3437
|
+
miss: Object.freeze({
|
|
3438
|
+
action: "accumulate-environment-or-dark-stop",
|
|
3439
|
+
contributesRadiance: true
|
|
3440
|
+
})
|
|
3441
|
+
});
|
|
3442
|
+
}
|
|
3443
|
+
function buildWavefrontBounceSchedule(maxDepth) {
|
|
3444
|
+
return Object.freeze(
|
|
3445
|
+
Array.from(
|
|
3446
|
+
{ length: maxDepth },
|
|
3447
|
+
(_, index) => Object.freeze({
|
|
3448
|
+
bounce: index,
|
|
3449
|
+
readQueue: index % 2 === 0 ? "active" : "next",
|
|
3450
|
+
writeQueue: index % 2 === 0 ? "next" : "active",
|
|
3451
|
+
passOrder: rendererWavefrontPassOrder
|
|
3452
|
+
})
|
|
3453
|
+
)
|
|
3454
|
+
);
|
|
3455
|
+
}
|
|
3456
|
+
function createWavefrontPathTracingPlan(options = {}) {
|
|
3457
|
+
const maxDepth = options.maxDepth === void 0 ? 6 : readPositiveInteger2("maxDepth", options.maxDepth);
|
|
3458
|
+
const queueCapacity = options.queueCapacity === void 0 ? 8192 : readPositiveInteger2("queueCapacity", options.queueCapacity);
|
|
3459
|
+
const accumulationResetEpoch = options.accumulationResetEpoch === void 0 ? 0 : readNonNegativeInteger2("accumulationResetEpoch", options.accumulationResetEpoch);
|
|
3460
|
+
const explicitLightSampling = options.explicitLightSampling === true;
|
|
3461
|
+
return Object.freeze({
|
|
3462
|
+
schemaVersion: rendererWavefrontBufferSchemaVersion,
|
|
3463
|
+
owner: rendererDebugOwner,
|
|
3464
|
+
maxDepth,
|
|
3465
|
+
queueCapacity,
|
|
3466
|
+
explicitLightSampling,
|
|
3467
|
+
accumulationResetEpoch,
|
|
3468
|
+
queueLayout: Object.freeze({
|
|
3469
|
+
strategy: rendererWavefrontQueuePairStrategy,
|
|
3470
|
+
compactAfterScatter: true,
|
|
3471
|
+
queues: Object.freeze([
|
|
3472
|
+
Object.freeze({ name: "active", role: "current-bounce" }),
|
|
3473
|
+
Object.freeze({ name: "next", role: "next-bounce" })
|
|
3474
|
+
])
|
|
3475
|
+
}),
|
|
3476
|
+
bufferContracts: rendererWavefrontBufferContracts,
|
|
3477
|
+
bounceSchedule: buildWavefrontBounceSchedule(maxDepth),
|
|
3478
|
+
terminationPolicy: buildWavefrontTerminationPolicy()
|
|
3479
|
+
});
|
|
3480
|
+
}
|
|
99
3481
|
function buildRendererWorkerBudgetLevels(jobType, queueClass, levels) {
|
|
100
3482
|
return Object.freeze(
|
|
101
3483
|
levels.map(
|
|
@@ -633,6 +4015,7 @@ function createRayTracingRenderPlan(options = {}) {
|
|
|
633
4015
|
renderStages: workerManifest.renderStages,
|
|
634
4016
|
representationBands: representations,
|
|
635
4017
|
accelerationStructureUpdates: workerManifest.accelerationStructureUpdates,
|
|
4018
|
+
wavefront: createWavefrontPathTracingPlan(options.wavefront),
|
|
636
4019
|
workerManifest
|
|
637
4020
|
});
|
|
638
4021
|
}
|
|
@@ -680,6 +4063,18 @@ function readPositiveNumber(name, value) {
|
|
|
680
4063
|
}
|
|
681
4064
|
return value;
|
|
682
4065
|
}
|
|
4066
|
+
function readPositiveInteger2(name, value) {
|
|
4067
|
+
if (!Number.isInteger(value) || value <= 0) {
|
|
4068
|
+
throw new Error(`${name} must be a positive integer.`);
|
|
4069
|
+
}
|
|
4070
|
+
return value;
|
|
4071
|
+
}
|
|
4072
|
+
function readNonNegativeInteger2(name, value) {
|
|
4073
|
+
if (!Number.isInteger(value) || value < 0) {
|
|
4074
|
+
throw new Error(`${name} must be a non-negative integer.`);
|
|
4075
|
+
}
|
|
4076
|
+
return value;
|
|
4077
|
+
}
|
|
683
4078
|
function now() {
|
|
684
4079
|
if (typeof performance !== "undefined" && typeof performance.now === "function") {
|
|
685
4080
|
return performance.now();
|
|
@@ -790,7 +4185,7 @@ function readDocument(documentOverride) {
|
|
|
790
4185
|
}
|
|
791
4186
|
return doc;
|
|
792
4187
|
}
|
|
793
|
-
function
|
|
4188
|
+
function resolveCanvas2(canvasOrSelector, documentOverride) {
|
|
794
4189
|
if (canvasOrSelector && typeof canvasOrSelector === "object") {
|
|
795
4190
|
return canvasOrSelector;
|
|
796
4191
|
}
|
|
@@ -868,7 +4263,7 @@ async function createGpuRenderer(options = {}) {
|
|
|
868
4263
|
throw new Error("Unable to obtain GPU adapter.");
|
|
869
4264
|
}
|
|
870
4265
|
const device = await adapter.requestDevice();
|
|
871
|
-
const targetCanvas =
|
|
4266
|
+
const targetCanvas = resolveCanvas2(canvas, documentOverride);
|
|
872
4267
|
const context = targetCanvas.getContext?.("webgpu");
|
|
873
4268
|
if (!context) {
|
|
874
4269
|
throw new Error("Unable to obtain WebGPU canvas context.");
|
|
@@ -1108,21 +4503,44 @@ function bindRendererToXrManager(renderer, xrManager, options = {}) {
|
|
|
1108
4503
|
var defaultRendererClearColor = DEFAULT_CLEAR_COLOR;
|
|
1109
4504
|
export {
|
|
1110
4505
|
bindRendererToXrManager,
|
|
4506
|
+
createDefaultWavefrontSceneObjects,
|
|
1111
4507
|
createGpuRenderer,
|
|
1112
4508
|
createRayTracingRenderPlan,
|
|
1113
4509
|
createRendererDebugHooks,
|
|
4510
|
+
createWavefrontBvhBuildLevels,
|
|
4511
|
+
createWavefrontBvhSortStages,
|
|
4512
|
+
createWavefrontEmissiveTriangleIndexSource,
|
|
4513
|
+
createWavefrontGpuMeshSource,
|
|
4514
|
+
createWavefrontMeshAcceleration,
|
|
4515
|
+
createWavefrontPathTracingComputeConfig,
|
|
4516
|
+
createWavefrontPathTracingComputeRenderer,
|
|
4517
|
+
createWavefrontPathTracingPlan,
|
|
1114
4518
|
defaultRendererClearColor,
|
|
1115
4519
|
defaultRendererWorkerProfile,
|
|
4520
|
+
estimateWavefrontPathTracingMemory,
|
|
1116
4521
|
getRendererWorkerManifest,
|
|
1117
4522
|
getRendererWorkerProfile,
|
|
4523
|
+
normalizeWavefrontMesh,
|
|
4524
|
+
normalizeWavefrontSceneObject,
|
|
4525
|
+
packWavefrontBvhNodes,
|
|
4526
|
+
packWavefrontSceneObjects,
|
|
4527
|
+
packWavefrontTriangles,
|
|
1118
4528
|
rendererAccelerationStructureUpdateClasses,
|
|
1119
4529
|
rendererDebugOwner,
|
|
1120
4530
|
rendererRayTracingStageOrder,
|
|
1121
4531
|
rendererRepresentationBands,
|
|
4532
|
+
rendererWavefrontBufferSchemaVersion,
|
|
4533
|
+
rendererWavefrontHitTypes,
|
|
4534
|
+
rendererWavefrontPassOrder,
|
|
4535
|
+
rendererWavefrontQueuePairStrategy,
|
|
1122
4536
|
rendererWorkerManifests,
|
|
1123
4537
|
rendererWorkerProfileNames,
|
|
1124
4538
|
rendererWorkerProfiles,
|
|
1125
4539
|
rendererWorkerQueueClass,
|
|
1126
|
-
|
|
4540
|
+
supportsWavefrontPathTracingCompute,
|
|
4541
|
+
supportsWebGpu,
|
|
4542
|
+
wavefrontMaterialKinds,
|
|
4543
|
+
wavefrontPathTracingComputeLimits,
|
|
4544
|
+
wavefrontSceneObjectKinds
|
|
1127
4545
|
};
|
|
1128
4546
|
//# sourceMappingURL=index.js.map
|