Repository navigation
Expand file tree
/
Copy pathwebgpu.html
More file actions
474 lines (450 loc) · 23.1 KB
/
Copy pathwebgpu.html
File metadata and controls
474 lines (450 loc) · 23.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
<!doctype html>
<html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><link rel="icon" href="data:,">
<title>Fast SDF AO · Unified WebGPU Compute Backend</title>
<style>
*{box-sizing:border-box}body{margin:0;background:#121821;color:#f1f5f8;font:15px system-ui,sans-serif}
main{max-width:1180px;margin:auto;padding:22px}
.top{display:flex;justify-content:space-between;align-items:baseline;flex-wrap:wrap;gap:12px;margin-bottom:8px}
h1{margin:0;font-size:clamp(22px,3.6vw,34px)}
a.back{color:#7dd3fc;text-decoration:none;font-weight:600;border:1px solid #334155;padding:6px 12px;border-radius:6px;background:#1e293b}
a.back:hover{background:#283548}
p{color:#c4d0db;margin:0 0 12px}
nav{display:flex;gap:8px;margin-bottom:12px;flex-wrap:wrap;align-items:center}
button,select{font:inherit;padding:7px 12px;color:inherit;background:#252f3d;border:1px solid #718095;border-radius:6px;cursor:pointer}
button[aria-pressed=true]{background:#d4e9fb;color:#162433;font-weight:600}
nav label{display:flex;align-items:center;gap:5px;padding:4px 6px}
#view{position:relative;background:#17212e;border-radius:8px;overflow:hidden}
#view.dragover{outline:3px dashed #38bdf8;outline-offset:-3px}
#drop-hint{display:none;position:absolute;inset:0;background:rgba(15,23,42,.78);color:#e0f2fe;font-size:22px;font-weight:700;align-items:center;justify-content:center;pointer-events:none}
#view.dragover #drop-hint{display:flex}
canvas{display:block;width:100%;height:auto}
#hud{position:absolute;top:12px;left:12px;margin:0;padding:8px 12px;background:#121821ec;border-radius:6px;pointer-events:none;font-variant-numeric:tabular-nums}
#hud strong{font-size:19px}
#hud small{display:block;color:#94a3b8}
#status{display:block;margin-top:10px;color:#c4d0db;font-variant-numeric:tabular-nums}
#err{display:none;padding:18px;background:#2a171c;border:1px solid #f43f5e;border-radius:8px;margin-bottom:14px;color:#fecdd3}
</style>
<main>
<div class="top">
<h1>Fast SDF AO · Unified WebGPU Compute</h1>
<a class="back" href="./index.html">← WebGL2 Viewer</a>
</div>
<p>Native WGSL compute pipeline: Storage-buffer Dual-Child SAH Contact BVH2 · 2×2 Shared-Memory Occlusion-Point Reuse · SHaRC World-Space Spatial Hash Cache · Glossy SDF Reflections · Live GPU SDF Baker (drop any <code>.glb</code> / <code>.obj</code>)</p>
<div id="err"></div>
<nav aria-label="Scene and quality">
<button data-scene="gallery" aria-pressed="true">Gallery (Multi-Bounce GI)</button>
<button data-scene="atrium" aria-pressed="false">Atrium (Curved)</button>
<button data-scene="archive" aria-pressed="false">Archive (Boxes)</button>
<button id="load-btn" style="border-color:#38bdf8;color:#bae6fd">Load .glb / .obj</button>
<input id="file-in" type="file" accept=".glb,.gltf,.obj" style="display:none">
<select id="quality" aria-label="Quality">
<option value="very_low">Quality: Very Low (Mobile)</option>
<option value="low">Quality: Low (Performance)</option>
<option value="medium">Quality: Medium (Balanced)</option>
<option value="high" selected>Quality: High (Default)</option>
<option value="very_high">Quality: Very High</option>
<option value="ultra">Quality: Ultra (Reference)</option>
</select>
<select id="viewmode" aria-label="View mode">
<option value="0" selected>View: Shaded PBR + GI</option>
<option value="1">View: AO Mask</option>
<option value="2">View: GI Bounce Only</option>
<option value="3">View: SHaRC Hash Cache</option>
<option value="4">View: Glossy Reflections</option>
</select>
<label><input id="refl" type="checkbox" checked> Reflections</label>
<label><input id="hash" type="checkbox" checked> SHaRC Hash</label>
<label><input id="reuse" type="checkbox" checked> 2×2 Reuse</label>
<label><input id="emissive" type="checkbox"> Emissive Orb</label>
<label><input id="movers" type="checkbox"> Moving Objects</label>
<label>Sun <input id="sun" type="range" min="-65" max="65" value="22" step="1" style="width:90px"><span id="sun-val" style="min-width:32px">22°</span></label>
<button id="clear">Clear Cache</button>
</nav>
<div id="view">
<canvas id="c" width="1280" height="720"></canvas>
<div id="drop-hint">Drop .glb or .obj to bake exact SDF on GPU</div>
<output id="hud"><strong id="fps">— FPS</strong><small id="gpu-ms">GPU: — ms · Cache skip: —%</small></output>
</div>
<output id="status">Initializing WebGPU Compute…</output>
</main>
<script type="importmap">{"imports":{"three":"https://cdn.jsdelivr.net/npm/three@0.170.0/build/three.module.js","three/addons/":"https://cdn.jsdelivr.net/npm/three@0.170.0/examples/jsm/"}}</script>
<script type="module">
import * as T from 'three';
import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
import { OBJLoader } from 'three/addons/loaders/OBJLoader.js';
import { buildContactBVH } from './contact-bvh.js';
import { WebGPUFastSDFAO, WEBGPU_QUALITY_PRESETS } from './src/webgpu.js';
const statusEl = document.querySelector('#status');
const errEl = document.querySelector('#err');
const canvas = document.querySelector('#c');
const fpsEl = document.querySelector('#fps');
const gpuMsEl = document.querySelector('#gpu-ms');
async function fetchGzipHalf(url) {
const resp = await fetch(url);
if (!resp.ok) throw Error(`Failed to fetch ${url} (${resp.status})`);
const stream = resp.body.pipeThrough(new DecompressionStream('gzip'));
const buf = await new Response(stream).arrayBuffer();
return new Uint16Array(buf);
}
function buildArchiveMeshData(boxes) {
const pos = [], nor = [], col = [], idx = [];
const faces = [
[[ 1,0,0], [ [1,-1,-1],[1,1,-1],[1,1,1],[1,-1,1] ]],
[[-1,0,0], [ [-1,1,-1],[-1,-1,-1],[-1,-1,1],[-1,1,1] ]],
[[0, 1,0], [ [1,1,-1],[-1,1,-1],[-1,1,1],[1,1,1] ]],
[[0,-1,0], [ [-1,-1,-1],[1,-1,-1],[1,-1,1],[-1,-1,1] ]],
[[0,0, 1], [ [-1,-1,1],[1,-1,1],[1,1,1],[-1,1,1] ]],
[[0,0,-1], [ [-1,1,-1],[1,1,-1],[1,-1,-1],[-1,-1,-1] ]],
];
for (const [cx, cy, cz, hx, hy, hz] of boxes) {
for (const [n, corners] of faces) {
const base = pos.length / 3;
for (const [sx, sy, sz] of corners) {
const x = cx + sx * hx, y = cy + sy * hy, z = cz + sz * hz;
pos.push(x, y, z);
nor.push(n[0], n[1], n[2]);
if (z < 0.005) {
col.push(0.37, 0.41, 0.44);
} else {
const t = Math.max(0, Math.min(1, z / 4 + 0.14));
col.push(0.28 + 0.36 * t, 0.34 + 0.35 * t, 0.43 + 0.32 * t);
}
}
idx.push(base, base + 1, base + 2, base, base + 2, base + 3);
}
}
return {
positions: new Float32Array(pos),
normals: new Float32Array(nor),
colors: new Float32Array(col),
indices: new Uint32Array(idx),
};
}
function makeThreeMesh(data) {
const g = new T.BufferGeometry();
g.setAttribute('position', new T.BufferAttribute(data.positions, 3));
g.setAttribute('normal', new T.BufferAttribute(data.normals, 3));
g.setIndex(new T.BufferAttribute(data.indices, 1));
return new T.Mesh(g);
}
function sunDirFromDeg(deg) {
const rad = (deg * Math.PI) / 180;
const x = Math.sin(rad) * 0.92;
const y = -0.22;
const z = Math.cos(rad) * 0.96 + 0.32;
const l = Math.hypot(x, y, z) || 1;
return [x / l, y / l, z / l];
}
try {
const gpu = await WebGPUFastSDFAO.create(canvas);
const camera = new T.PerspectiveCamera(37, 1280 / 720, 0.1, 100);
camera.up.set(0, 0, 1);
const controls = new OrbitControls(camera, canvas);
controls.minDistance = 1.2;
controls.maxDistance = 45;
const sceneCache = {};
let activeScene = 'gallery';
let emissiveOn = false;
let moversOn = false;
let sunDeg = 22;
let simTime = 0, lastNow = 0;
function updateMovers(t) {
if (!moversOn) { gpu.dynObjects = []; return; }
const a1 = t * 1.05;
const a2 = a1 + Math.PI;
gpu.dynObjects = [
// Collision-free elevated orbit around the central pedestal: polished mirror-gold sphere + coral matte sphere
{ pos: [1.82 * Math.cos(a1), -0.15 + 1.38 * Math.sin(a1), 1.18 + 0.30 * Math.sin(a1 * 2.0)], radius: 0.33, color: [0.98, 0.80, 0.36], roughness: -0.04 },
{ pos: [1.78 * Math.cos(a2), -0.15 + 1.34 * Math.sin(a2), 1.02 + 0.24 * Math.cos(a2 * 2.0)], radius: 0.28, color: [0.95, 0.30, 0.18], roughness: 0.65 },
];
}
async function loadSceneData(name) {
if (sceneCache[name]) return sceneCache[name];
statusEl.value = `Loading ${name} mesh, FP16 SDF & SAH Contact BVH…`;
if (name === 'gallery') {
const [mod, sdfHalf] = await Promise.all([
import('./assets/gallery-scene.js'),
fetchGzipHalf('./assets/gallery.f16.gz'),
]);
const data = mod.buildGalleryGeometryData();
// Diffuse-bounce albedo stays the mesh's own albedo (the chrome override below only changes shading).
data.giColors = data.colors.slice();
// Make the central hero sphere at (0.36, -0.16, 1.08, r=0.40) half mirror-smooth chrome (left)
// and half brushed rough chrome (right) to showcase real-time SDF glossy + rough reflections.
const vCnt = data.positions.length / 3;
const rough = new Float32Array(vCnt);
for (let i = 0; i < vCnt; i++) {
const px = data.positions[i * 3], py = data.positions[i * 3 + 1], pz = data.positions[i * 3 + 2];
const nz = data.normals[i * 3 + 2];
const dHero = Math.hypot(px - 0.36, py + 0.16, pz - 1.08);
if (dHero < 0.415) {
const smoothHalf = px < 0.36;
data.colors[i * 3] = smoothHalf ? 0.95 : 0.90;
data.colors[i * 3 + 1] = smoothHalf ? 0.96 : 0.91;
data.colors[i * 3 + 2] = smoothHalf ? 0.98 : 0.93;
// Negative roughness encodes conductor (metal = 1.0) in WebGPUFastSDFAO
rough[i] = smoothHalf ? -0.03 : -0.34;
} else if (pz < 0.02 && nz > 0.85) {
rough[i] = 0.16;
} else if (Math.abs(nz) < 0.15 && (Math.abs(px) > 3.2 || Math.abs(py) > 3.2)) {
rough[i] = 0.80;
} else if (pz < 2.2) {
rough[i] = 0.24;
} else {
rough[i] = 0.55;
}
}
data.roughness = rough;
const mesh = makeThreeMesh(data);
const contactRange = Math.max(0.18, 0.12 + 0.5 * Math.hypot(mod.GALLERY_SDF_SPAN[0] / mod.GALLERY_SDF_DIMS[0], mod.GALLERY_SDF_SPAN[1] / mod.GALLERY_SDF_DIMS[1], mod.GALLERY_SDF_SPAN[2] / mod.GALLERY_SDF_DIMS[2]));
const bvh = buildContactBVH([mesh], T, { gridSize: 0, maxLeaf: 2 });
sceneCache[name] = { ...data, sdfHalf, sdfDims: mod.GALLERY_SDF_DIMS, sdfMin: mod.GALLERY_SDF_MIN, sdfSpan: mod.GALLERY_SDF_SPAN, bvh, contactRange, cam: mod.GALLERY_CAMERA, useGI: true };
} else if (name === 'atrium') {
const [mod, sdfHalf] = await Promise.all([
import('./assets/atrium-scene.js'),
fetchGzipHalf('./assets/atrium.f16.gz'),
]);
const data = mod.buildAtriumGeometryData();
const mesh = makeThreeMesh(data);
const contactRange = Math.max(0.18, 0.12 + 0.5 * Math.hypot(mod.ATRIUM_SDF_SPAN[0] / mod.ATRIUM_SDF_DIMS[0], mod.ATRIUM_SDF_SPAN[1] / mod.ATRIUM_SDF_DIMS[1], mod.ATRIUM_SDF_SPAN[2] / mod.ATRIUM_SDF_DIMS[2]));
const bvh = buildContactBVH([mesh], T, { gridSize: 0, maxLeaf: 2 });
sceneCache[name] = { ...data, sdfHalf, sdfDims: mod.ATRIUM_SDF_DIMS, sdfMin: mod.ATRIUM_SDF_MIN, sdfSpan: mod.ATRIUM_SDF_SPAN, bvh, contactRange, cam: mod.ATRIUM_CAMERA, useGI: true };
} else {
const [boxes, sdfHalf] = await Promise.all([
fetch('./benchmark/archive.json').then(r => r.json()),
fetchGzipHalf('./assets/archive.f16.gz'),
]);
const data = buildArchiveMeshData(boxes);
const mesh = makeThreeMesh(data);
const contactRange = 0.24;
const bvh = buildContactBVH([mesh], T, { gridSize: 0, maxLeaf: 2 });
sceneCache[name] = {
...data, sdfHalf, sdfDims: [256, 176, 80], sdfMin: [-1, -1, -1], sdfSpan: [26, 18, 8], bvh, contactRange,
cam: { position: [18, -4, 7.3], target: [10.8, 8.8, 1.4] }, useGI: false,
};
}
return sceneCache[name];
}
async function selectScene(name) {
activeScene = name;
document.querySelectorAll('button[data-scene]').forEach(b => b.setAttribute('aria-pressed', String(b.dataset.scene === name)));
const sc = await loadSceneData(name);
gpu.sunDir = name === 'archive' ? [-0.33, -0.45, 0.83] : sunDirFromDeg(sunDeg);
gpu.emissiveCol = (emissiveOn && name === 'gallery') ? [3.6, 2.0, 0.6] : [0, 0, 0];
gpu.loadScene(sc);
camera.position.set(...sc.cam.position);
controls.target.set(...sc.cam.target);
controls.update();
const info = gpu.adapterInfo;
const devLabel = info.description || info.architecture || info.vendor || 'WebGPU';
statusEl.value = `${name.toUpperCase()} · ${devLabel} · ${(sc.indices.length / 3).toLocaleString()} tris · ${sc.bvh.nodes.toLocaleString()} BVH nodes · 262k SHaRC hash slots`;
}
document.querySelectorAll('button[data-scene]').forEach(b => { b.onclick = () => selectScene(b.dataset.scene); });
document.querySelector('#quality').onchange = e => {
gpu.setQuality(e.target.value);
document.querySelector('#refl').checked = gpu.useReflections;
};
document.querySelector('#viewmode').onchange = e => { gpu.viewMode = Number(e.target.value); };
document.querySelector('#refl').onchange = e => { gpu.useReflections = e.target.checked; gpu.stillFrames = 0; };
document.querySelector('#hash').onchange = e => { gpu.useHash = e.target.checked; };
document.querySelector('#reuse').onchange = e => { gpu.reuseEnabled = e.target.checked; };
document.querySelector('#emissive').onchange = e => {
emissiveOn = e.target.checked;
gpu.emissiveCol = (emissiveOn && activeScene === 'gallery') ? [3.6, 2.0, 0.6] : [0, 0, 0];
gpu.relight(true);
};
document.querySelector('#movers').onchange = e => {
moversOn = e.target.checked;
updateMovers(simTime);
};
document.querySelector('#sun').oninput = e => {
sunDeg = Number(e.target.value);
document.querySelector('#sun-val').textContent = `${sunDeg}°`;
gpu.sunDir = sunDirFromDeg(sunDeg);
gpu.relight(true);
};
document.querySelector('#clear').onclick = () => gpu.clearHash();
// ---- Drag-and-Drop .glb / .obj + Live In-Browser WebGPU Compute SDF Baker ----
async function loadCustomThreeObject(rootObj, label) {
statusEl.value = `Normalizing ${label} & baking exact FP16 SDF on WebGPU…`;
rootObj.updateWorldMatrix(true, true);
const box = new T.Box3().setFromObject(rootObj);
const size = box.getSize(new T.Vector3());
const maxDim = Math.max(size.x, size.y, size.z, 1e-4);
const scale = 4.2 / maxDim;
const center = box.getCenter(new T.Vector3());
const pos = [], nor = [], col = [], rough = [], idx = [];
const v = new T.Vector3(), nrm = new T.Vector3(), nMat = new T.Matrix3();
let metalTris = 0, glossyTris = 0;
rootObj.traverse(obj => {
if (!obj.isMesh || !obj.geometry) return;
const g = obj.geometry;
if (!g.attributes.normal) g.computeVertexNormals();
const pAttr = g.attributes.position, nAttr = g.attributes.normal, cAttr = g.attributes.color, iAttr = g.index;
const mat = Array.isArray(obj.material) ? obj.material[0] : obj.material;
const mc = mat?.color ? [mat.color.r, mat.color.g, mat.color.b] : [0.76, 0.74, 0.70];
const em = mat?.emissive ? [mat.emissive.r * (mat.emissiveIntensity ?? 1), mat.emissive.g * (mat.emissiveIntensity ?? 1), mat.emissive.b * (mat.emissiveIntensity ?? 1)] : [0, 0, 0];
const metalness = (typeof mat?.metalness === 'number') ? mat.metalness : 0.0;
const rawRough = (typeof mat?.roughness === 'number') ? mat.roughness : 0.42;
const isMetal = metalness >= 0.5;
// Encode metallic conductors with negative roughness (-0.03..-0.95) for full-res mirror/GGX reflections
const encRough = isMetal ? -Math.max(0.03, Math.min(0.95, rawRough)) : Math.max(0.04, Math.min(0.98, rawRough));
const triCount = (iAttr ? iAttr.count : pAttr.count) / 3;
if (isMetal) metalTris += triCount;
else if (rawRough < 0.45) glossyTris += triCount;
nMat.getNormalMatrix(obj.matrixWorld);
const base = pos.length / 3;
for (let i = 0; i < pAttr.count; i++) {
v.fromBufferAttribute(pAttr, i).applyMatrix4(obj.matrixWorld);
// Convert Y-up (glTF/OBJ convention) to Z-up viewer convention, resting on z = 0
const wx = (v.x - center.x) * scale;
const wy = -(v.z - center.z) * scale;
const wz = (v.y - box.min.y) * scale;
pos.push(wx, wy, wz);
nrm.fromBufferAttribute(nAttr, i).applyMatrix3(nMat).normalize();
nor.push(nrm.x, -nrm.z, nrm.y);
const vr = cAttr ? cAttr.getX(i) : 1.0;
const vg = cAttr ? cAttr.getY(i) : 1.0;
const vb = cAttr ? cAttr.getZ(i) : 1.0;
col.push(Math.min(1, mc[0] * vr + em[0]), Math.min(1, mc[1] * vg + em[1]), Math.min(1, mc[2] * vb + em[2]));
rough.push(encRough);
}
if (iAttr) {
for (let i = 0; i < iAttr.count; i++) idx.push(base + iAttr.getX(i));
} else {
for (let i = 0; i < pAttr.count; i++) idx.push(base + i);
}
});
if (idx.length < 3) throw Error(`No triangles found in ${label}`);
// Add a subtle polished studio floor slab under the dropped model so it casts crisp contact shadows & reflections
const fBase = pos.length / 3;
const fS = 4.6, fH = 0.25;
const fVerts = [
[-fS,-fS,0, 0,0,1], [fS,-fS,0, 0,0,1], [fS,fS,0, 0,0,1], [-fS,fS,0, 0,0,1],
[-fS,fS,-fH, 0,0,-1], [fS,fS,-fH, 0,0,-1], [fS,-fS,-fH, 0,0,-1], [-fS,-fS,-fH, 0,0,-1],
];
for (const fv of fVerts) { pos.push(fv[0], fv[1], fv[2]); nor.push(fv[3], fv[4], fv[5]); col.push(0.56, 0.58, 0.62); rough.push(0.18); }
idx.push(fBase, fBase+1, fBase+2, fBase, fBase+2, fBase+3, fBase+4, fBase+5, fBase+6, fBase+4, fBase+6, fBase+7);
const data = {
positions: new Float32Array(pos),
normals: new Float32Array(nor),
colors: new Float32Array(col),
roughness: new Float32Array(rough),
indices: new Uint32Array(idx),
};
const mesh = makeThreeMesh(data);
const sdfMin = [-5.0, -5.0, -0.5];
const sdfSpan = [10.0, 10.0, 5.5];
const sdfDims = [96, 96, 56];
const contactRange = Math.max(0.18, 0.12 + 0.5 * Math.hypot(sdfSpan[0] / sdfDims[0], sdfSpan[1] / sdfDims[1], sdfSpan[2] / sdfDims[2]));
// Build one Global Quantized SAH BVH2 (used for both GPU SDF baking and exact runtime tracing)
const tBvh0 = performance.now();
const globalBvh = buildContactBVH([mesh], T, { gridSize: 0, maxLeaf: 2 });
const bvhMs = performance.now() - tBvh0;
const { sdfTex, bakeMs } = await gpu.bakeSDF(globalBvh, { sdfMin, sdfSpan, sdfDims, clip: 1.5 });
activeScene = 'custom';
document.querySelectorAll('button[data-scene]').forEach(b => b.setAttribute('aria-pressed', 'false'));
gpu.sunDir = sunDirFromDeg(sunDeg);
gpu.emissiveCol = [0, 0, 0];
gpu.loadScene({ ...data, sdfTex, sdfDims, sdfMin, sdfSpan, bvh: globalBvh, contactRange, useGI: true });
camera.position.set(0.8, -8.4, 3.2);
controls.target.set(0, 0, 1.5);
controls.update();
if (metalTris > 0 || glossyTris > 0) {
gpu.useReflections = true;
document.querySelector('#refl').checked = true;
}
const pbrTag = metalTris > 0 ? ` · PBR metal (${Math.round(metalTris)} tris)` : (glossyTris > 0 ? ` · PBR glossy` : '');
statusEl.value = `CUSTOM (${label}) · ${(idx.length / 3).toLocaleString()} tris${pbrTag} · GPU SDF baked (${sdfDims.join('×')} FP16) in ${bakeMs.toFixed(1)} ms · BVH ${bvhMs.toFixed(1)} ms`;
return { triangles: idx.length / 3, metalTris: Math.round(metalTris), glossyTris: Math.round(glossyTris), bakeMs, bvhMs };
}
async function handleFile(file) {
const ext = file.name.split('.').pop().toLowerCase();
try {
if (ext === 'obj') {
const text = await file.text();
const obj = new OBJLoader().parse(text);
await loadCustomThreeObject(obj, file.name);
} else if (ext === 'glb' || ext === 'gltf') {
const buf = await file.arrayBuffer();
const gltf = await new GLTFLoader().parseAsync(buf, '');
await loadCustomThreeObject(gltf.scene, file.name);
} else {
throw Error('Please drop a .glb, .gltf, or .obj file.');
}
} catch (e) {
statusEl.value = `Load failed: ${e.message}`;
throw e;
}
}
const fileIn = document.querySelector('#file-in');
document.querySelector('#load-btn').onclick = () => fileIn.click();
fileIn.onchange = () => { if (fileIn.files?.[0]) handleFile(fileIn.files[0]); fileIn.value = ''; };
const viewEl = document.querySelector('#view');
viewEl.addEventListener('dragover', e => { e.preventDefault(); viewEl.classList.add('dragover'); });
viewEl.addEventListener('dragleave', () => viewEl.classList.remove('dragover'));
viewEl.addEventListener('drop', e => { e.preventDefault(); viewEl.classList.remove('dragover'); if (e.dataTransfer?.files?.[0]) handleFile(e.dataTransfer.files[0]); });
await selectScene('gallery');
let running = true, fCount = 0, fStart = performance.now();
function renderOnce() {
controls.update();
gpu.render(camera.position.toArray(), controls.target.toArray());
}
function loop(now) {
if (!running) return;
if (lastNow) simTime += Math.min(now - lastNow, 100) / 1000;
lastNow = now;
if (emissiveOn && activeScene === 'gallery') {
const a = simTime * 0.9;
gpu.emissivePos = [1.45 * Math.cos(a), 0.75 + 1.15 * Math.sin(a), 1.65 + 0.35 * Math.sin(a * 1.7)];
const m = 0.5 + 0.5 * Math.sin(a * 0.5);
gpu.emissiveCol = [3.6 * (1 - m) + 0.7 * m, 1.9 * (1 - m) + 2.9 * m, 0.5 * (1 - m) + 3.6 * m];
gpu.relight(true);
}
if (moversOn) updateMovers(simTime);
renderOnce();
fCount++;
const dt = now - fStart;
if (dt >= 500) {
fpsEl.textContent = `${Math.round((1000 * fCount) / dt)} FPS`;
const msTxt = gpu.hasTimestamp ? `${gpu.lastGpuMs.toFixed(2)} ms` : 'n/a';
gpuMsEl.textContent = `GPU: ${msTxt} · Cache skip: ${gpu.lastSkipPct.toFixed(1)}%`;
fCount = 0; fStart = now;
}
requestAnimationFrame(loop);
}
requestAnimationFrame(loop);
window.wgpuDemo = {
gpu, camera, controls, selectScene, renderOnce, WEBGPU_QUALITY_PRESETS,
loadCustomOBJ: async (objText, name = 'custom.obj') => {
const obj = new OBJLoader().parse(objText);
return loadCustomThreeObject(obj, name);
},
loadCustomThreeObject,
setMovers: (on, t = 0.6) => {
moversOn = !!on;
document.querySelector('#movers').checked = moversOn;
updateMovers(t);
},
stopLoop: () => { running = false; },
setSun: (deg) => { sunDeg = deg; gpu.sunDir = sunDirFromDeg(deg); gpu.relight(true); },
setEmissive: (on, t = 0.7) => {
emissiveOn = !!on;
if (emissiveOn) {
gpu.emissivePos = [1.45 * Math.cos(t), 0.75 + 1.15 * Math.sin(t), 1.65 + 0.35 * Math.sin(t * 1.7)];
gpu.emissiveCol = [3.6, 2.0, 0.6];
} else {
gpu.emissiveCol = [0, 0, 0];
}
gpu.relight(true);
},
};
} catch (e) {
errEl.style.display = 'block';
errEl.innerHTML = `<strong>WebGPU unavailable:</strong> ${e.message} — <a href="./index.html" style="color:#7dd3fc">open the WebGL2 viewer instead</a>.`;
statusEl.value = e.message;
throw e;
}
</script>
</html>