@playcanvas/supersplat-viewer 1.26.4 → 1.27.1

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/public/index.js CHANGED
@@ -1,7 +1,7 @@
1
1
  const TRACEID_GPU_TIMINGS = "GpuTimings";
2
2
 
3
- const version$1 = "2.20.2";
4
- const revision = "4590e5f";
3
+ const version$1 = "2.20.6";
4
+ const revision = "9a2a8ef";
5
5
  function extend(target, ex) {
6
6
  for (const prop in ex) {
7
7
  const copy = ex[prop];
@@ -6209,13 +6209,13 @@ class GraphicsDevice extends EventHandler {
6209
6209
  this.updateClientRect();
6210
6210
  }
6211
6211
  updateClientRect() {
6212
- if (platform.worker) {
6213
- this.clientRect.width = this.canvas.width;
6214
- this.clientRect.height = this.canvas.height;
6215
- } else {
6212
+ if (typeof this.canvas.getBoundingClientRect === "function") {
6216
6213
  const rect = this.canvas.getBoundingClientRect();
6217
6214
  this.clientRect.width = rect.width;
6218
6215
  this.clientRect.height = rect.height;
6216
+ } else {
6217
+ this.clientRect.width = this.canvas.width ?? 0;
6218
+ this.clientRect.height = this.canvas.height ?? 0;
6219
6219
  }
6220
6220
  }
6221
6221
  get width() {
@@ -18406,8 +18406,8 @@ class Mesh extends RefCountedObject {
18406
18406
  this._geometryData.recreate = true;
18407
18407
  this._geometryData.maxVertices = maxVertices;
18408
18408
  this._geometryData.maxIndices = maxIndices;
18409
- this._geometryData.verticesUsage = verticesDynamic ? BUFFER_STATIC : BUFFER_DYNAMIC;
18410
- this._geometryData.indicesUsage = indicesDynamic ? BUFFER_STATIC : BUFFER_DYNAMIC;
18409
+ this._geometryData.verticesUsage = verticesDynamic ? BUFFER_DYNAMIC : BUFFER_STATIC;
18410
+ this._geometryData.indicesUsage = indicesDynamic ? BUFFER_DYNAMIC : BUFFER_STATIC;
18411
18411
  }
18412
18412
  setVertexStream(semantic, data, componentCount, numVertices, dataType = TYPE_FLOAT32, dataTypeNormalize = false, asInt = false) {
18413
18413
  this._initGeometryData();
@@ -37777,6 +37777,9 @@ class ResourceHandler {
37777
37777
  this._app = app;
37778
37778
  this.handlerType = handlerType;
37779
37779
  }
37780
+ get app() {
37781
+ return this._app;
37782
+ }
37780
37783
  set maxRetries(value) {
37781
37784
  this._maxRetries = value;
37782
37785
  }
@@ -42316,6 +42319,7 @@ float median(float r, float g, float b) {
42316
42319
  return max(min(r, g), min(max(r, g), b));
42317
42320
  }
42318
42321
  uniform float font_sdfIntensity;
42322
+ uniform float font_pxrange;
42319
42323
  #ifndef LIT_MSDF_TEXT_ATTRIBUTE
42320
42324
  uniform vec4 outline_color;
42321
42325
  uniform float outline_thickness;
@@ -42335,10 +42339,11 @@ vec4 applyMsdf(vec4 color) {
42335
42339
  float sigDist = median(tsample.r, tsample.g, tsample.b);
42336
42340
  float sigDistShdw = median(ssample.r, ssample.g, ssample.b);
42337
42341
  float edge = 0.5 - 0.5 * font_sdfIntensity;
42338
- float aa = max(fwidth(sigDist), 1e-4);
42339
- float inside = clamp((sigDist - edge) / aa + 0.5, 0.0, 1.0);
42340
- float outline = clamp((sigDist + outline_thickness - edge) / aa + 0.5, 0.0, 1.0);
42341
- float shadow = clamp((sigDistShdw + outline_thickness - edge) / aa + 0.5, 0.0, 1.0);
42342
+ vec2 unitRange = vec2(font_pxrange) / vec2(textureSize(texture_msdfMap, 0));
42343
+ float screenPxRange = max(0.5 * dot(unitRange, 1.0 / max(fwidth(vUv0), vec2(1e-6))), 1.0);
42344
+ float inside = clamp(screenPxRange * (sigDist - edge) + 0.5, 0.0, 1.0);
42345
+ float outline = clamp(screenPxRange * (sigDist + outline_thickness - edge) + 0.5, 0.0, 1.0);
42346
+ float shadow = clamp(screenPxRange * (sigDistShdw + outline_thickness - edge) + 0.5, 0.0, 1.0);
42342
42347
  vec4 tcolor = (outline > inside) ? outline * vec4(outline_color.a * outline_color.rgb, outline_color.a) : vec4(0.0);
42343
42348
  tcolor = mix(tcolor, color, inside);
42344
42349
  vec4 scolor = (shadow > outline) ? shadow * vec4(shadow_color.a * shadow_color.rgb, shadow_color.a) : tcolor;
@@ -47789,6 +47794,7 @@ fn median(r: f32, g: f32, b: f32) -> f32 {
47789
47794
  return max(min(r, g), min(max(r, g), b));
47790
47795
  }
47791
47796
  uniform font_sdfIntensity: f32;
47797
+ uniform font_pxrange: f32;
47792
47798
  #ifndef LIT_MSDF_TEXT_ATTRIBUTE
47793
47799
  uniform outline_color: vec4f;
47794
47800
  uniform outline_thickness: f32;
@@ -47819,10 +47825,12 @@ fn applyMsdf(color_in: vec4f) -> vec4f {
47819
47825
  let sigDist: f32 = median(tsample.r, tsample.g, tsample.b);
47820
47826
  let sigDistShdw: f32 = median(ssample.r, ssample.g, ssample.b);
47821
47827
  let edge: f32 = 0.5 - 0.5 * uniform.font_sdfIntensity;
47822
- let aa: f32 = max(abs(dpdx(sigDist)) + abs(dpdy(sigDist)), 1e-4);
47823
- let inside: f32 = clamp((sigDist - edge) / aa + 0.5, 0.0, 1.0);
47824
- let outline: f32 = clamp((sigDist + outline_thicknessValue - edge) / aa + 0.5, 0.0, 1.0);
47825
- let shadow: f32 = clamp((sigDistShdw + outline_thicknessValue - edge) / aa + 0.5, 0.0, 1.0);
47828
+ let unitRange: vec2f = vec2f(uniform.font_pxrange) / vec2f(textureDimensions(texture_msdfMap, 0));
47829
+ let uvDeriv: vec2f = max(abs(dpdx(vUv0)) + abs(dpdy(vUv0)), vec2f(1e-6));
47830
+ let screenPxRange: f32 = max(0.5 * dot(unitRange, vec2f(1.0) / uvDeriv), 1.0);
47831
+ let inside: f32 = clamp(screenPxRange * (sigDist - edge) + 0.5, 0.0, 1.0);
47832
+ let outline: f32 = clamp(screenPxRange * (sigDist + outline_thicknessValue - edge) + 0.5, 0.0, 1.0);
47833
+ let shadow: f32 = clamp(screenPxRange * (sigDistShdw + outline_thicknessValue - edge) + 0.5, 0.0, 1.0);
47826
47834
  let tcolor_outline: vec4f = outline * vec4f(outline_colorValue.a * outline_colorValue.rgb, outline_colorValue.a);
47827
47835
  var tcolor: vec4f = select(vec4f(0.0), tcolor_outline, outline > inside);
47828
47836
  tcolor = mix(tcolor, color, inside);
@@ -57964,6 +57972,9 @@ class GSplatOctree {
57964
57972
  }
57965
57973
  }
57966
57974
  ensureFileResource(fileIndex) {
57975
+ if (!this.assetLoader) {
57976
+ return;
57977
+ }
57967
57978
  if (this.fileResources.has(fileIndex)) {
57968
57979
  return;
57969
57980
  }
@@ -58561,6 +58572,14 @@ class GSplatWorld {
58561
58572
  result.newVersion = false;
58562
58573
  result.overdrawDirty = false;
58563
58574
  result.sortNeeded = false;
58575
+ for (const [placement, inst] of this._octreeInstances) {
58576
+ if (inst.octree.destroyed || !placement.resource) {
58577
+ this._octreeInstances.delete(placement);
58578
+ this._layerPlacementsDirty = true;
58579
+ this._placementSetChanged = true;
58580
+ this._octreeInstancesToDestroy.push(inst);
58581
+ }
58582
+ }
58564
58583
  if (--this._framesTillFullUpdate <= 0) {
58565
58584
  this._framesTillFullUpdate = 10;
58566
58585
  this._lodUpdateRequested = true;
@@ -61092,6 +61111,9 @@ class GSplatHybridRenderer extends GSplatRenderer {
61092
61111
  ic.sortElementCountBuffer,
61093
61112
  sortIndirectInfo
61094
61113
  );
61114
+ if (pickMode) {
61115
+ this.device.submit();
61116
+ }
61095
61117
  return gpuSorter.sortIndirect(
61096
61118
  projector.sortKeys,
61097
61119
  elementCount,
@@ -68921,11 +68943,16 @@ class SogParser {
68921
68943
  });
68922
68944
  const textureAssets = subs.map((sub) => textures[sub]).flat();
68923
68945
  let unloaded = false;
68946
+ let ownedByResource = false;
68924
68947
  asset.once("unload", () => {
68925
68948
  unloaded = true;
68926
68949
  textureAssets.forEach((t) => {
68927
68950
  assets.remove(t);
68928
- t.unload();
68951
+ if (!ownedByResource) {
68952
+ t.unload();
68953
+ } else {
68954
+ assets._loader.clearCache(t.getFileUrl(), t.type);
68955
+ }
68929
68956
  });
68930
68957
  });
68931
68958
  combineProgress(asset, textureAssets);
@@ -68970,6 +68997,7 @@ class SogParser {
68970
68997
  }
68971
68998
  const prepareCenters = gsplatCentersEnabledAtLoad;
68972
68999
  const resource = decompress ? new GSplatResource(this.app.graphicsDevice, await data.decompress(), { prepareCenters }) : new GSplatSogResource(this.app.graphicsDevice, data, { prepareCenters });
69000
+ ownedByResource = !decompress;
68973
69001
  if (this._shouldAbort(asset, unloaded)) {
68974
69002
  resource.destroy();
68975
69003
  callback(null, null);
@@ -69116,10 +69144,34 @@ class SogBundleParser {
69116
69144
  this.app = app;
69117
69145
  this.maxRetries = maxRetries;
69118
69146
  }
69147
+ _shouldAbort(asset, unloaded) {
69148
+ if (unloaded || !this.app.assets.get(asset.id)) return true;
69149
+ if (!this.app?.graphicsDevice || this.app.graphicsDevice._destroyed) return true;
69150
+ return false;
69151
+ }
69119
69152
  async load(url, callback, asset) {
69120
69153
  const gsplatCentersEnabledAtLoad = this.app.scene?.gsplatCentersEnabled !== false;
69121
69154
  try {
69155
+ const { assets } = this.app;
69156
+ let unloaded = false;
69157
+ let ownedByResource = false;
69158
+ const textures = {};
69159
+ asset.once("unload", () => {
69160
+ unloaded = true;
69161
+ Object.values(textures).forEach((t) => {
69162
+ assets.remove(t);
69163
+ if (!ownedByResource) {
69164
+ t.unload();
69165
+ } else {
69166
+ assets._loader.clearCache(t.getFileUrl(), t.type);
69167
+ }
69168
+ });
69169
+ });
69122
69170
  const arrayBuffer = await downloadArrayBuffer(url, asset);
69171
+ if (this._shouldAbort(asset, unloaded)) {
69172
+ callback(null, null);
69173
+ return;
69174
+ }
69123
69175
  const files = parseZipArchive(arrayBuffer);
69124
69176
  for (const file of files) {
69125
69177
  if (file.compression === "deflate") {
@@ -69139,7 +69191,6 @@ class SogBundleParser {
69139
69191
  return;
69140
69192
  }
69141
69193
  const filenames = ["means", "scales", "quats", "sh0", "shN"].map((key) => meta[key]?.files ?? []).flat();
69142
- const textures = {};
69143
69194
  const promises = [];
69144
69195
  for (const filename of filenames) {
69145
69196
  const file = files.find((f) => f.filename === filename);
@@ -69175,17 +69226,18 @@ class SogBundleParser {
69175
69226
  }
69176
69227
  Object.values(textures).forEach((t) => this.app.assets.load(t));
69177
69228
  await Promise.allSettled(promises);
69178
- Object.values(textures).forEach((t) => {
69179
- if (t.file) {
69180
- t.file.contents = null;
69181
- }
69182
- });
69183
- const { assets } = this.app;
69184
- asset.once("unload", () => {
69229
+ if (this._shouldAbort(asset, unloaded)) {
69185
69230
  Object.values(textures).forEach((t) => {
69186
69231
  assets.remove(t);
69187
69232
  t.unload();
69188
69233
  });
69234
+ callback(null, null);
69235
+ return;
69236
+ }
69237
+ Object.values(textures).forEach((t) => {
69238
+ if (t.file) {
69239
+ t.file.contents = null;
69240
+ }
69189
69241
  });
69190
69242
  const decompress = asset.data?.decompress;
69191
69243
  const data = new GSplatSogData();
@@ -69201,13 +69253,29 @@ class SogBundleParser {
69201
69253
  data.sh_labels = textures[meta.shN?.files[1]]?.resource;
69202
69254
  data.shBands = GSplatSogData.calcBands(data.sh_centroids?.width);
69203
69255
  if (!decompress) {
69256
+ if (this._shouldAbort(asset, unloaded)) {
69257
+ data.destroy();
69258
+ callback(null, null);
69259
+ return;
69260
+ }
69204
69261
  data.prepareCodebook();
69205
69262
  if (gsplatCentersEnabledAtLoad) {
69206
69263
  await data.prepareGpuData();
69207
69264
  }
69208
69265
  }
69266
+ if (this._shouldAbort(asset, unloaded)) {
69267
+ data.destroy();
69268
+ callback(null, null);
69269
+ return;
69270
+ }
69209
69271
  const prepareCenters = gsplatCentersEnabledAtLoad;
69210
69272
  const resource = decompress ? new GSplatResource(this.app.graphicsDevice, await data.decompress(), { prepareCenters }) : new GSplatSogResource(this.app.graphicsDevice, data, { prepareCenters });
69273
+ ownedByResource = !decompress;
69274
+ if (this._shouldAbort(asset, unloaded)) {
69275
+ resource.destroy();
69276
+ callback(null, null);
69277
+ return;
69278
+ }
69211
69279
  callback(null, resource);
69212
69280
  } catch (err) {
69213
69281
  callback(err);
@@ -69234,6 +69302,7 @@ class GSplatAssetLoader extends GSplatAssetLoaderBase {
69234
69302
  _currentlyLoading = /* @__PURE__ */ new Set();
69235
69303
  _loadQueue = [];
69236
69304
  _retryCount = /* @__PURE__ */ new Map();
69305
+ _failed = /* @__PURE__ */ new Set();
69237
69306
  _destroyed = false;
69238
69307
  constructor(registry) {
69239
69308
  super();
@@ -69252,12 +69321,16 @@ class GSplatAssetLoader extends GSplatAssetLoaderBase {
69252
69321
  this._loadQueue.length = 0;
69253
69322
  this._currentlyLoading.clear();
69254
69323
  this._retryCount.clear();
69324
+ this._failed.clear();
69255
69325
  }
69256
69326
  _canLoad() {
69257
69327
  return !!this._registry.loader?.getHandler("gsplat");
69258
69328
  }
69259
69329
  load(url) {
69260
69330
  const asset = this._urlToAsset.get(url);
69331
+ if (asset && asset.loaded && !asset.resource && !this._currentlyLoading.has(url) && !this._failed.has(url)) {
69332
+ asset.loaded = false;
69333
+ }
69261
69334
  if (asset?.loaded || this._currentlyLoading.has(url)) {
69262
69335
  return;
69263
69336
  }
@@ -69301,10 +69374,12 @@ class GSplatAssetLoader extends GSplatAssetLoaderBase {
69301
69374
  this._retryCount.set(url, retryCount + 1);
69302
69375
  asset.loaded = false;
69303
69376
  asset.loading = false;
69377
+ asset.once("error", (retryErr) => this._onAssetLoadError(url, asset, retryErr));
69304
69378
  this._registry.load(asset);
69305
69379
  } else {
69306
69380
  this._currentlyLoading.delete(url);
69307
69381
  this._retryCount.delete(url);
69382
+ this._failed.add(url);
69308
69383
  this._processQueue();
69309
69384
  }
69310
69385
  }
@@ -69326,6 +69401,7 @@ class GSplatAssetLoader extends GSplatAssetLoaderBase {
69326
69401
  this._loadQueue.splice(queueIndex, 1);
69327
69402
  }
69328
69403
  this._retryCount.delete(url);
69404
+ this._failed.delete(url);
69329
69405
  const asset = this._urlToAsset.get(url);
69330
69406
  if (asset) {
69331
69407
  asset.fire("unload", asset);
@@ -69341,6 +69417,9 @@ class GSplatAssetLoader extends GSplatAssetLoaderBase {
69341
69417
  const asset = this._urlToAsset.get(url);
69342
69418
  return asset?.resource;
69343
69419
  }
69420
+ hasFailed(url) {
69421
+ return this._failed.has(url);
69422
+ }
69344
69423
  }
69345
69424
 
69346
69425
  class GSplatOctreeParser {
@@ -81122,7 +81201,7 @@ const importSettings = (settings) => {
81122
81201
  return result;
81123
81202
  };
81124
81203
 
81125
- var version = "1.26.4";
81204
+ var version = "1.27.1";
81126
81205
 
81127
81206
  class Tooltip {
81128
81207
  register;
@@ -81542,10 +81621,11 @@ const initUI = (global) => {
81542
81621
  // AR/VR
81543
81622
  const arChanged = () => dom.arMode.classList[state.hasAR ? 'remove' : 'add']('hidden');
81544
81623
  const vrChanged = () => dom.vrMode.classList[state.hasVR ? 'remove' : 'add']('hidden');
81545
- // XR sessions require a WebGL device. Under WebGPU, prompt the user to reload
81546
- // the viewer with the WebGL renderer before starting AR/VR. Use replace() so
81547
- // the renderer-switch reload doesn't add a back-button entry — important
81548
- // because the viewer often runs inside an iframe (e.g. superspl.at /scene).
81624
+ // When a session can't start on the current (WebGPU) device but would work on
81625
+ // WebGL, prompt the user to reload the viewer with the WebGL renderer before
81626
+ // starting AR/VR. Use replace() so the renderer-switch reload doesn't add a
81627
+ // back-button entry — important because the viewer often runs inside an
81628
+ // iframe (e.g. superspl.at /scene).
81549
81629
  const reloadWithWebgl = () => {
81550
81630
  const reloadUrl = new URL(location.href);
81551
81631
  reloadUrl.searchParams.set('webgl', '');
@@ -81557,11 +81637,14 @@ const initUI = (global) => {
81557
81637
  dom.xrModalCancel.addEventListener('click', hideXrModal);
81558
81638
  dom.xrModal.addEventListener('pointerdown', hideXrModal);
81559
81639
  const handleXrClick = (type) => {
81560
- if (global.renderer !== 'webgl') {
81561
- showXrModal();
81640
+ // Availability is backend-aware: when the session can start on the current
81641
+ // device (WebGPU included), start it directly. Otherwise the button is only
81642
+ // visible because the session would work on WebGL, so offer the reload.
81643
+ if (global.app.xr.isAvailable(type === 'AR' ? 'immersive-ar' : 'immersive-vr')) {
81644
+ events.fire(type === 'AR' ? 'startAR' : 'startVR');
81562
81645
  }
81563
81646
  else {
81564
- events.fire(type === 'AR' ? 'startAR' : 'startVR');
81647
+ showXrModal();
81565
81648
  }
81566
81649
  };
81567
81650
  dom.arMode.addEventListener('click', () => handleXrClick('AR'));
@@ -84432,6 +84515,210 @@ class CameraManager {
84432
84515
  }
84433
84516
  }
84434
84517
 
84518
+ // Box-average downsample of a supersampled render. Each output texel averages the
84519
+ // `uRatio` x `uRatio` block of source texels it covers — true NxN supersampling, which
84520
+ // keeps thin high-frequency features (splat strings, edges) smooth, unlike a
84521
+ // bilinear/compositor downscale which aliases them. `uFlipY` flips vertically because
84522
+ // render targets and readback disagree on row order.
84523
+ const boxDownsampleGLSL = /* glsl */ `
84524
+ varying vec2 vUv0;
84525
+
84526
+ uniform sampler2D source;
84527
+ uniform vec2 uSrcSize;
84528
+ uniform float uRatio;
84529
+ uniform float uFlipY;
84530
+
84531
+ void main(void) {
84532
+ int r = int(uRatio);
84533
+ vec2 outSize = uSrcSize / uRatio;
84534
+ vec2 uv = vUv0;
84535
+ if (uFlipY > 0.5) {
84536
+ uv.y = 1.0 - uv.y;
84537
+ }
84538
+ vec2 base = floor(uv * outSize) * uRatio;
84539
+ vec4 sum = vec4(0.0);
84540
+ for (int y = 0; y < 8; y++) {
84541
+ if (y >= r) break;
84542
+ for (int x = 0; x < 8; x++) {
84543
+ if (x >= r) break;
84544
+ vec2 texel = base + vec2(float(x) + 0.5, float(y) + 0.5);
84545
+ sum += texture2D(source, texel / uSrcSize);
84546
+ }
84547
+ }
84548
+ gl_FragColor = sum / (uRatio * uRatio);
84549
+ }
84550
+ `;
84551
+ // WGSL twin of the box downsample (WebGPU can't compile GLSL, so a custom fullscreen
84552
+ // shader must supply WGSL too — the built-in fullscreenQuadVS chunk covers the vertex).
84553
+ const boxDownsampleWGSL = /* wgsl */ `
84554
+ varying vUv0: vec2f;
84555
+ var source: texture_2d<f32>;
84556
+ var sourceSampler: sampler;
84557
+ uniform uSrcSize: vec2f;
84558
+ uniform uRatio: f32;
84559
+ uniform uFlipY: f32;
84560
+
84561
+ @fragment
84562
+ fn fragmentMain(input: FragmentInput) -> FragmentOutput {
84563
+ var output: FragmentOutput;
84564
+ let r: i32 = i32(uniform.uRatio);
84565
+ let outSize: vec2f = uniform.uSrcSize / uniform.uRatio;
84566
+ var uv: vec2f = input.vUv0;
84567
+ if (uniform.uFlipY > 0.5) {
84568
+ uv.y = 1.0 - uv.y;
84569
+ }
84570
+ let base: vec2f = floor(uv * outSize) * uniform.uRatio;
84571
+ var sum: vec4f = vec4f(0.0);
84572
+ for (var y: i32 = 0; y < 8; y = y + 1) {
84573
+ if (y >= r) { break; }
84574
+ for (var x: i32 = 0; x < 8; x = x + 1) {
84575
+ if (x >= r) { break; }
84576
+ let texel: vec2f = base + vec2f(f32(x) + 0.5, f32(y) + 0.5);
84577
+ sum = sum + textureSample(source, sourceSampler, texel / uniform.uSrcSize);
84578
+ }
84579
+ }
84580
+ output.color = sum / (uniform.uRatio * uniform.uRatio);
84581
+ return output;
84582
+ }
84583
+ `;
84584
+ // Grabs downsampled snapshots of the viewer entirely on the GPU. The scene is rendered
84585
+ // (with post effects) into an app-owned render target at `supersample` x the requested
84586
+ // output size, box-downsampled to the output size, and only that small buffer is read
84587
+ // back. Rendering into our own target (rather than the backbuffer) means no
84588
+ // preserveDrawingBuffer, and it works on both WebGL and WebGPU.
84589
+ class Capture {
84590
+ app;
84591
+ device;
84592
+ camera;
84593
+ getCameraFrame;
84594
+ shader;
84595
+ srcRT = null;
84596
+ dstRT = null;
84597
+ constructor(app, camera, getCameraFrame) {
84598
+ this.app = app;
84599
+ this.device = app.graphicsDevice;
84600
+ this.camera = camera;
84601
+ this.getCameraFrame = getCameraFrame;
84602
+ this.shader = ShaderUtils.createShader(this.device, {
84603
+ uniqueName: 'captureBoxDownsample',
84604
+ attributes: { vertex_position: SEMANTIC_POSITION },
84605
+ vertexChunk: 'fullscreenQuadVS',
84606
+ fragmentGLSL: boxDownsampleGLSL,
84607
+ fragmentWGSL: boxDownsampleWGSL
84608
+ });
84609
+ }
84610
+ makeRT(name, width, height, depth) {
84611
+ // Plain RGBA8 (RGBA channel order, non-sRGB) so the box shader samples raw bytes
84612
+ // and the readback returns raw RGBA — no channel swap (WebGPU backbuffers are
84613
+ // often BGRA) and no sRGB decode/encode surprises; we average in the same gamma
84614
+ // space sharp did. We only mirror the backbuffer's sRGB *flag* (which the viewer
84615
+ // sets true only when post effects are active) — that drives the gamma the render
84616
+ // pipeline writes with, so our target receives identical bytes to the screen.
84617
+ const dev = this.device;
84618
+ const srgb = dev.backBuffer?.isColorBufferSrgb?.(0) ?? false;
84619
+ const colorBuffer = new Texture(this.device, {
84620
+ name,
84621
+ width,
84622
+ height,
84623
+ format: PIXELFORMAT_RGBA8,
84624
+ mipmaps: false,
84625
+ minFilter: FILTER_LINEAR,
84626
+ magFilter: FILTER_LINEAR,
84627
+ addressU: ADDRESS_CLAMP_TO_EDGE,
84628
+ addressV: ADDRESS_CLAMP_TO_EDGE
84629
+ });
84630
+ const rt = new RenderTarget({ name, colorBuffer, depth });
84631
+ rt.isColorBufferSrgb = () => srgb;
84632
+ return rt;
84633
+ }
84634
+ ensure(target, width, height, depth) {
84635
+ const existing = this[target];
84636
+ if (existing && existing.width === width && existing.height === height) {
84637
+ return existing;
84638
+ }
84639
+ existing?.colorBuffer.destroy();
84640
+ existing?.destroy();
84641
+ const rt = this.makeRT(target, width, height, depth);
84642
+ this[target] = rt;
84643
+ return rt;
84644
+ }
84645
+ // Point the camera at `renderTarget` and re-target CameraFrame's compose pass. Post
84646
+ // effects bind their output inside setupRenderPasses, which only re-runs on a reset,
84647
+ // so a plain renderTarget change doesn't take effect — force a reset via layersDirty,
84648
+ // otherwise the composited frame keeps going to the old target (reads back black).
84649
+ setCameraTarget(renderTarget) {
84650
+ this.camera.renderTarget = renderTarget;
84651
+ const cameraFrame = this.getCameraFrame();
84652
+ if (cameraFrame) {
84653
+ const rpc = cameraFrame.renderPassCamera;
84654
+ if (rpc) {
84655
+ rpc.layersDirty = true;
84656
+ }
84657
+ cameraFrame.update();
84658
+ }
84659
+ }
84660
+ async grab({ time, width, height, supersample = 2, scrub }) {
84661
+ const device = this.device;
84662
+ // clamp to the box shaders' 8x8 sample cap: a larger ratio would sum at most 64
84663
+ // texels yet still divide by ss*ss, producing an under-exposed (too dark) frame.
84664
+ const ss = Math.min(8, Math.max(1, Math.round(supersample)));
84665
+ // normalize the output size to positive integers so texture/RT creation and
84666
+ // readback don't fail confusingly on 0/negative/non-integer input
84667
+ const outW = Math.max(1, Math.round(width));
84668
+ const outH = Math.max(1, Math.round(height));
84669
+ const srcW = outW * ss;
84670
+ const srcH = outH * ss;
84671
+ // render the scene (incl. post effects) into our own supersampled target
84672
+ const srcRT = this.ensure('srcRT', srcW, srcH, true);
84673
+ // Redirect the camera into our offscreen target for the capture, then restore it.
84674
+ // window.captureFrame is a global API, so leaving the camera pointed at our target
84675
+ // would freeze on-screen rendering after the first call.
84676
+ const camera = this.camera;
84677
+ const saved = {
84678
+ renderTarget: camera.renderTarget,
84679
+ aspectRatioMode: camera.aspectRatioMode,
84680
+ aspectRatio: camera.aspectRatio,
84681
+ horizontalFov: camera.horizontalFov
84682
+ };
84683
+ try {
84684
+ camera.aspectRatioMode = ASPECT_AUTO; // aspect follows the target dims
84685
+ camera.horizontalFov = srcW >= srcH;
84686
+ this.setCameraTarget(srcRT);
84687
+ if (time !== undefined && scrub) {
84688
+ scrub(time);
84689
+ }
84690
+ this.app.renderNextFrame = true;
84691
+ await new Promise((resolve) => {
84692
+ this.app.once('frameend', () => resolve());
84693
+ });
84694
+ // box-downsample the supersampled render to the output size
84695
+ const dstRT = this.ensure('dstRT', outW, outH, false);
84696
+ const { scope } = device;
84697
+ scope.resolve('source').setValue(srcRT.colorBuffer);
84698
+ scope.resolve('uSrcSize').setValue([srcW, srcH]);
84699
+ scope.resolve('uRatio').setValue(ss);
84700
+ scope.resolve('uFlipY').setValue(srcRT.flipY ? 0 : 1);
84701
+ device.setBlendState(BlendState.NOBLEND);
84702
+ drawQuadWithShader(device, dstRT, this.shader);
84703
+ const pixels = await dstRT.colorBuffer.read(0, 0, outW, outH, { renderTarget: dstRT, immediate: true });
84704
+ const u8 = pixels instanceof Uint8Array ? pixels : new Uint8Array(pixels.buffer);
84705
+ const chunks = [];
84706
+ const chunk = 0x8000;
84707
+ for (let i = 0; i < u8.length; i += chunk) {
84708
+ chunks.push(String.fromCharCode.apply(null, u8.subarray(i, i + chunk)));
84709
+ }
84710
+ return { width: outW, height: outH, data: btoa(chunks.join('')) };
84711
+ }
84712
+ finally {
84713
+ camera.aspectRatioMode = saved.aspectRatioMode;
84714
+ camera.aspectRatio = saved.aspectRatio;
84715
+ camera.horizontalFov = saved.horizontalFov;
84716
+ this.setCameraTarget(saved.renderTarget);
84717
+ this.app.renderNextFrame = true;
84718
+ }
84719
+ }
84720
+ }
84721
+
84435
84722
  const captureCameraState = (cm, state) => ({
84436
84723
  position: [cm.camera.position.x, cm.camera.position.y, cm.camera.position.z],
84437
84724
  angles: [cm.camera.angles.x, cm.camera.angles.y, cm.camera.angles.z],
@@ -88086,6 +88373,37 @@ class Viewer {
88086
88373
  });
88087
88374
  };
88088
88375
  window.animationDuration = state.animationDuration;
88376
+ // Capture hook for the thumbnail pipeline. Renders the scene (with post
88377
+ // effects) into an offscreen supersampled target, GPU box-downsamples it to
88378
+ // the requested size and returns just that small buffer. Lazily created on
88379
+ // first use — no ?capture flag and no preserveDrawingBuffer needed, and it
88380
+ // works on both WebGL and WebGPU.
88381
+ let capture = null;
88382
+ let captureQueue = Promise.resolve();
88383
+ window.captureFrame = ({ time, width = 480, height = width, supersample } = {}) => {
88384
+ const run = () => {
88385
+ if (!capture) {
88386
+ capture = new Capture(app, camera.camera, () => this.cameraFrame ?? null);
88387
+ }
88388
+ return capture.grab({
88389
+ time,
88390
+ width,
88391
+ height,
88392
+ supersample,
88393
+ scrub: (t) => {
88394
+ if (state.hasAnimation) {
88395
+ state.animationPaused = true;
88396
+ events.fire('scrubAnim', t);
88397
+ }
88398
+ }
88399
+ });
88400
+ };
88401
+ // serialize calls: they share the viewer camera, so concurrent captures
88402
+ // would interleave the redirect/restore and could leave it mis-targeted
88403
+ const result = captureQueue.then(run, run);
88404
+ captureQueue = result.then(() => { }, () => { });
88405
+ return result;
88406
+ };
88089
88407
  });
88090
88408
  // wait for the model to load
88091
88409
  Promise.all([gsplatLoad, skyboxLoad, collisionLoad]).then((results) => {
@@ -89178,19 +89496,28 @@ class XrNavigation extends Script {
89178
89496
  // On entering/exiting AR, we need to set the camera clear color to transparent black
89179
89497
  const initXr = (global) => {
89180
89498
  const { app, events, state, camera, renderer } = global;
89181
- state.hasAR = app.xr.isAvailable('immersive-ar');
89182
- state.hasVR = app.xr.isAvailable('immersive-vr');
89183
- // initialize ar/vr
89184
- app.xr.on('available:immersive-ar', (available) => {
89185
- state.hasAR = available;
89186
- });
89187
- app.xr.on('available:immersive-vr', (available) => {
89188
- state.hasVR = available;
89189
- });
89190
- // XR sessions require a WebGL device; under WebGPU we only expose availability so
89191
- // the UI can offer to reload the viewer in WebGL mode.
89192
- if (renderer !== 'webgl') {
89193
- return;
89499
+ // Engine availability is backend-aware (2.20+): under WebGPU a session is only
89500
+ // reported available when it can start on the current device (browser exposes
89501
+ // XRGPUBinding, e.g. Safari on Apple Vision Pro). A session the WebGPU device
89502
+ // can't host may still run after reloading into WebGL, so keep the buttons
89503
+ // visible then — the UI offers that reload when the session can't start directly.
89504
+ let webglAR = false;
89505
+ let webglVR = false;
89506
+ const updateAvailable = () => {
89507
+ state.hasAR = app.xr.isAvailable('immersive-ar') || webglAR;
89508
+ state.hasVR = app.xr.isAvailable('immersive-vr') || webglVR;
89509
+ };
89510
+ updateAvailable();
89511
+ app.xr.on('available', updateAvailable);
89512
+ if (renderer === 'webgpu') {
89513
+ Promise.all([
89514
+ XrManager.isDeviceSupported(DEVICETYPE_WEBGL2, 'immersive-ar'),
89515
+ XrManager.isDeviceSupported(DEVICETYPE_WEBGL2, 'immersive-vr')
89516
+ ]).then(([ar, vr]) => {
89517
+ webglAR = ar;
89518
+ webglVR = vr;
89519
+ updateAvailable();
89520
+ });
89194
89521
  }
89195
89522
  const parent = camera.parent;
89196
89523
  const clearColor = new Color();
@@ -89307,8 +89634,8 @@ const loadSkybox = (app, url) => {
89307
89634
  const createApp = async (canvas, config) => {
89308
89635
  const useWebGPU = config.renderer === 'webgpu';
89309
89636
  // Create the graphics device. The engine auto-appends WebGL2/null fallbacks
89310
- // when WebGPU isn't supported, so request xrCompatible so the WebGL fallback
89311
- // is also usable for AR/VR.
89637
+ // when WebGPU isn't supported. Request xrCompatible so the device — WebGPU
89638
+ // (via XRGPUBinding) or the WebGL fallback — is usable for AR/VR.
89312
89639
  const device = await createGraphicsDevice(canvas, {
89313
89640
  deviceTypes: useWebGPU ? ['webgpu'] : [],
89314
89641
  antialias: false,
@@ -89445,8 +89772,8 @@ const main = async (canvas, settingsJson, config) => {
89445
89772
  initPoster(events);
89446
89773
  }
89447
89774
  camera.addComponent('camera');
89448
- // Initialize XR support (availability detection always runs so the UI can offer
89449
- // a reload into WebGL when the user requests AR/VR under WebGPU)
89775
+ // Initialize XR support (any backend; when the current device can't host a
89776
+ // session the UI can offer a reload into WebGL instead)
89450
89777
  initXr(global);
89451
89778
  // Initialize user interface
89452
89779
  initLocalization();