-
Notifications
You must be signed in to change notification settings - Fork 304
Expand file tree
/
Copy pathNewSparkRenderer.ts
More file actions
1665 lines (1508 loc) · 50.9 KB
/
NewSparkRenderer.ts
File metadata and controls
1665 lines (1508 loc) · 50.9 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
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import * as THREE from "three";
import {
ExtSplats,
PackedSplats,
PagedSplats,
Readback,
type SplatGenerator,
SplatMesh,
SplatPager,
dyno,
} from ".";
import { NewSplatAccumulator } from "./NewSplatAccumulator";
import { NewSplatGeometry } from "./NewSplatGeometry";
import { NewSplatWorker, workerPool } from "./NewSplatWorker";
import { SPLAT_TEX_HEIGHT, SPLAT_TEX_WIDTH } from "./defines";
import { getShaders } from "./shaders";
import { cloneClock, isAndroid, isIos, isOculus, isVisionPro } from "./utils";
export interface NewSparkRendererOptions {
/**
* Pass in your THREE.WebGLRenderer instance so Spark can perform work
* outside the usual render loop. Should be created with antialias: false
* (default setting) as WebGL anti-aliasing doesn't improve Gaussian Splatting
* rendering and significantly reduces performance.
*/
renderer: THREE.WebGLRenderer;
/**
* Whether to use premultiplied alpha when accumulating splat RGB
* @default true
*/
premultipliedAlpha?: boolean;
/**
* Whether to encode Gsplat with linear RGB (for environment mapping)
* @default false
*/
encodeLinear?: boolean;
/**
* Pass in a THREE.Clock to synchronize time-based effects across different
* systems. Alternatively, you can set the property time directly.
* (default: new THREE.Clock)
*/
clock?: THREE.Clock;
/**
* Controls whether to check and automatically update Gsplat collection after
* each frame render.
* @default true
*/
autoUpdate?: boolean;
/**
* Controls whether to update the Gsplats before or after rendering. For WebXR
* this must be false in order to complete rendering as soon as possible.
* @default true
*/
preUpdate?: boolean;
/**
* Maximum standard deviations from the center to render Gaussians. Values
* Math.sqrt(5)..Math.sqrt(8) produce good results and can be tweaked for
* performance.
* @default Math.sqrt(8)
*/
maxStdDev?: number;
/*
**
* Minimum pixel radius for splat rendering.
* @default 0.0
*/
minPixelRadius?: number;
/**
* Maximum pixel radius for splat rendering.
* @default 512.0
*/
maxPixelRadius?: number;
/**
* Whether to use extended Gsplat encoding for intermediary splats.
* @default false
*/
extSplats?: boolean;
/**
* Minimum alpha value for splat rendering.
* @default 0.5 * (1.0 / 255.0)
*/
minAlpha?: number;
/**
* Enable 2D Gaussian splatting rendering ability. When this mode is enabled,
* any scale x/y/z component that is exactly 0 (minimum quantized value) results
* in the other two non-0 axis being interpreted as an oriented 2D Gaussian Splat,
* rather instead of the usual projected 3DGS Z-slice. When reading PLY files,
* scale values less than e^-30 will be interpreted as 0.
* @default false
*/
enable2DGS?: boolean;
/**
* Scalar value to add to 2D splat covariance diagonal, effectively blurring +
* enlarging splats. In scenes trained without the Gsplat anti-aliasing tweak
* this value was typically 0.3, but with anti-aliasing it is 0.0
* @default 0.0
*/
preBlurAmount?: number;
/**
* Scalar value to add to 2D splat covarianve diagonal, with opacity adjustment
* to correctly account for "blurring" when anti-aliasing. Typically 0.3
* (equivalent to approx 0.5 pixel radius) in scenes trained with anti-aliasing.
*/
blurAmount?: number;
/**
* Depth-of-field distance to focal plane
*/
focalDistance?: number;
/**
* Full-width angle of aperture opening (in radians), 0.0 to disable
* @default 0.0
*/
apertureAngle?: number;
/**
* Modulate Gaussian kernel falloff. 0 means "no falloff, flat shading",
* while 1 is the normal Gaussian kernel.
* @default 1.0
*/
falloff?: number;
/**
* X/Y clipping boundary factor for Gsplat centers against view frustum.
* 1.0 clips any centers that are exactly out of bounds, while 1.4 clips
* centers that are 40% beyond the bounds.
* @default 1.4
*/
clipXY?: number;
/**
* Parameter to adjust projected splat scale calculation to match other renderers,
* similar to the same parameter in the MKellogg 3DGS renderer. Higher values will
* tend to sharpen the splats. A value 2.0 can be used to match the behavior of
* the PlayCanvas renderer.
* @default 1.0
*/
focalAdjustment?: number;
/**
* Whether to sort splats radially (geometric distance) from the viewpoint (true)
* or by Z-depth (false). Most scenes are trained with the Z-depth `sort `metric
* and will render more accurately at certain viewpoints. However, radial sorting
* is more stable under viewpoint rotations.
* @default true
*/
sortRadial?: boolean;
/**
* Minimum interval between sort calls in milliseconds.
* @default 1
*/
minSortIntervalMs?: number;
/**
* Minimum interval between LOD calls in milliseconds.
* @default 1
*/
minLodIntervalMs?: number;
/*
* Flag to control whether LoD is enabled. @default true
*/
enableLod?: boolean;
/**
* Whether to drive LOD updates (compute lodInstances, update pager, etc.).
* Set to false to use LOD instances from another renderer without driving updates.
* Only has effect if enableLod is true.
* @default true (if enableLod is true)
*/
enableDriveLod?: boolean;
/**
* Set the target # splats for LoD. Recommended # splats is 500K for mobile and 1.5M for desktop,
* which is set automatically if this isn't set.
*/
lodSplatCount?: number;
/**
* Scale factor for target # splats for LoD. 2.0 means 2x the recommended # splats.
* Recommended # splats is 500K for mobile and 1.5M for desktop.
* @default 1.0
*/
lodSplatScale?: number;
/* Global LoD scale to apply @default 1.0
*/
globalLodScale?: number;
/**
* Allocation size of paged splats
* @default 16777216
*/
maxPagedSplats?: number;
/* Foveation scale to apply outside the view frustum (but not behind viewer)
* @default 1.0
*/
outsideFoveate?: number;
/* Foveation scale to apply behind viewer
* @default 1.0
*/
behindFoveate?: number;
/* Full-width angle in degrees of fixed foveation cone along the view direction
* with perfection foveation=1.0
* @default 0.0 (disables perfect foveation zone)
*/
coneFov0?: number;
/* Full-width angle in degrees of fixed foveation cone along the view direction
* @default 0.0 (disables cone foveation)
*/
coneFov?: number;
/* Foveation scale to apply at the edge of the cone
* @default 1.0
*/
coneFoveate?: number;
numLodFetchers?: number;
target?: {
/**
* Width of the render target in pixels.
*/
width: number;
/**
* Height of the render target in pixels.
*/
height: number;
/**
* If you want to be able to render a scene that depends on this target's
* output (for example, a recursive viewport), set this to true to enable
* double buffering.
* @default false
*/
doubleBuffer?: boolean;
/**
* Super-sampling factor for the render target. Values 1-4 are supported.
* Note that re-sampling back down to .width x .height is done on the CPU
* with simple averaging only when calling readTarget().
* @default 1
*/
superXY?: number;
};
extraUniforms?: Record<string, unknown>;
vertexShader?: string;
fragmentShader?: string;
transparent?: boolean;
depthTest?: boolean;
depthWrite?: boolean;
}
export class NewSparkRenderer extends THREE.Mesh {
renderer: THREE.WebGLRenderer;
premultipliedAlpha: boolean;
material: THREE.ShaderMaterial;
uniforms: ReturnType<typeof NewSparkRenderer.makeUniforms>;
autoUpdate: boolean;
preUpdate: boolean;
static sparkOverride?: NewSparkRenderer;
renderSize = new THREE.Vector2();
maxStdDev: number;
minPixelRadius: number;
maxPixelRadius: number;
extSplats: boolean;
minAlpha: number;
enable2DGS: boolean;
preBlurAmount: number;
blurAmount: number;
focalDistance: number;
apertureAngle: number;
falloff: number;
clipXY: number;
focalAdjustment: number;
encodeLinear: boolean;
sortRadial: boolean;
clock: THREE.Clock;
time?: number;
lastFrame = -1;
updateTimeoutId = -1;
orderingTexture: THREE.DataTexture | null = null;
maxSplats = 0;
activeSplats = 0;
display: NewSplatAccumulator;
current: NewSplatAccumulator;
accumulators: NewSplatAccumulator[] = [];
sorting = false;
sortDirty = false;
lastSortTime = 0;
sortWorker: NewSplatWorker | null = null;
sortTimeoutId = -1;
sortedCenter = new THREE.Vector3().setScalar(Number.NEGATIVE_INFINITY);
sortedDir = new THREE.Vector3().setScalar(0);
readback32 = new Uint32Array(0);
minSortIntervalMs: number;
minLodIntervalMs: number;
enableLod: boolean;
enableDriveLod: boolean;
lodSplatCount?: number;
lodSplatScale: number;
globalLodScale: number;
maxPagedSplats: number;
outsideFoveate: number;
behindFoveate: number;
coneFov0: number;
coneFov: number;
coneFoveate: number;
numLodFetchers: number;
lodWorker: NewSplatWorker | null = null;
lodMeshes: { mesh: SplatMesh; version: number }[] = [];
lodDirty = false;
lodIds: Map<
PackedSplats | ExtSplats | PagedSplats,
{ lodId: number; lastTouched: number; rootPage?: number }
> = new Map();
lodIdToSplats: Map<number, PackedSplats | ExtSplats | PagedSplats> =
new Map();
lodInitQueue: (PackedSplats | ExtSplats | PagedSplats)[] = [];
lodPos = new THREE.Vector3().setScalar(Number.NEGATIVE_INFINITY);
lodQuat = new THREE.Quaternion().set(0, 0, 0, 0);
lodInstances: Map<
SplatMesh,
{
lodId: number;
numSplats: number;
indices: Uint32Array;
texture: THREE.DataTexture;
}
> = new Map();
lodFetchers: Promise<void>[] = [];
chunksToFetch: { lodId: number; chunk: number }[] = [];
lodUpdates: {
lodId: number;
pageBase: number;
chunkBase: number;
count: number;
lodTreeData?: Uint32Array;
}[] = [];
pager?: SplatPager;
pagerId = 0;
target?: THREE.WebGLRenderTarget;
backTarget?: THREE.WebGLRenderTarget;
superPixels?: Uint8Array;
targetPixels?: Uint8Array;
superXY = 1;
flushAfterGenerate = false;
flushAfterRead = false;
readPause = 1;
sortPause = 0;
sortDelay = 0;
constructor(options: NewSparkRendererOptions) {
const uniforms = NewSparkRenderer.makeUniforms();
Object.assign(uniforms, options.extraUniforms ?? {});
const shaders = getShaders();
const premultipliedAlpha = options.premultipliedAlpha ?? true;
const geometry = new NewSplatGeometry();
const material = new THREE.ShaderMaterial({
glslVersion: THREE.GLSL3,
vertexShader: options.vertexShader ?? shaders.newSplatVertex,
fragmentShader: options.fragmentShader ?? shaders.newSplatFragment,
uniforms,
premultipliedAlpha,
transparent: options.transparent ?? true,
depthTest: options.depthTest ?? true,
depthWrite: options.depthWrite ?? false,
side: THREE.DoubleSide,
});
super(geometry, material);
this.material = material;
this.uniforms = uniforms;
// Disable frustum culling because we want to always draw them all
// and cull Gsplats individually in the shader
this.frustumCulled = false;
// sparkRendererInstance = this;
this.renderer = options.renderer;
this.premultipliedAlpha = premultipliedAlpha;
this.autoUpdate = options.autoUpdate ?? true;
this.preUpdate = options.preUpdate ?? true;
this.maxStdDev = options.maxStdDev ?? Math.sqrt(8.0);
this.minPixelRadius = options.minPixelRadius ?? 0.0; //1.6;
this.maxPixelRadius = options.maxPixelRadius ?? 512.0;
this.extSplats = options.extSplats ?? false;
this.minAlpha = options.minAlpha ?? 0.5 * (1.0 / 255.0);
this.enable2DGS = options.enable2DGS ?? false;
this.preBlurAmount = options.preBlurAmount ?? 0.0;
this.blurAmount = options.blurAmount ?? 0.3;
this.focalDistance = options.focalDistance ?? 0.0;
this.apertureAngle = options.apertureAngle ?? 0.0;
this.falloff = options.falloff ?? 1.0;
this.clipXY = options.clipXY ?? 1.4;
this.focalAdjustment = options.focalAdjustment ?? 1.0;
this.encodeLinear = options.encodeLinear ?? false;
this.sortRadial = options.sortRadial ?? true;
this.minSortIntervalMs = options.minSortIntervalMs ?? 0;
this.minLodIntervalMs = options.minLodIntervalMs ?? 0;
this.enableLod = options.enableLod ?? true;
// enableDriveLod defaults to true if enableLod is true, false otherwise
this.enableDriveLod = options.enableDriveLod ?? this.enableLod;
this.lodSplatCount = options.lodSplatCount;
this.lodSplatScale = options.lodSplatScale ?? 1.0;
this.globalLodScale = options.globalLodScale ?? 1.0;
this.maxPagedSplats = options.maxPagedSplats ?? 16777216;
this.outsideFoveate = options.outsideFoveate ?? 1.0;
this.behindFoveate = options.behindFoveate ?? 1.0;
this.coneFov0 = options.coneFov0 ?? 0.0;
this.coneFov = options.coneFov ?? 0.0;
this.coneFoveate = options.coneFoveate ?? 1.0;
this.numLodFetchers = options.numLodFetchers ?? 3;
this.clock = options.clock ? cloneClock(options.clock) : new THREE.Clock();
const accumulatorOptions = { extSplats: this.extSplats };
this.display = new NewSplatAccumulator(accumulatorOptions);
this.current = this.display;
this.accumulators.push(new NewSplatAccumulator(accumulatorOptions));
this.accumulators.push(new NewSplatAccumulator(accumulatorOptions));
if (options.target) {
const { width, height, doubleBuffer } = options.target;
const superXY = Math.max(1, Math.min(4, options.target.superXY ?? 1));
if (width * superXY > 8192 || height * superXY > 8192) {
throw new Error("Target size too large");
}
this.superXY = superXY;
const superWidth = width * superXY;
const superHeight = height * superXY;
this.target = new THREE.WebGLRenderTarget(superWidth, superHeight, {
format: THREE.RGBAFormat,
type: THREE.UnsignedByteType,
colorSpace: THREE.SRGBColorSpace,
});
if (doubleBuffer) {
this.backTarget = new THREE.WebGLRenderTarget(superWidth, superHeight, {
format: THREE.RGBAFormat,
type: THREE.UnsignedByteType,
colorSpace: THREE.SRGBColorSpace,
});
}
this.encodeLinear = options.encodeLinear ?? true;
}
}
static makeUniforms() {
const uniforms = {
// // number of active splats to render
// numSplats: { value: 0 },
// Size of render viewport in pixels
renderSize: { value: new THREE.Vector2() },
// Near and far plane distances
near: { value: 0.1 },
far: { value: 1000.0 },
// SplatAccumulator to view transformation quaternion
renderToViewQuat: { value: new THREE.Quaternion() },
// SplatAccumulator to view transformation translation
renderToViewPos: { value: new THREE.Vector3() },
// Maximum distance (in stddevs) from Gsplat center to render
maxStdDev: { value: 1.0 },
// Minimum pixel radius for splat rendering
minPixelRadius: { value: 0.0 },
// Maximum pixel radius for splat rendering
maxPixelRadius: { value: 512.0 },
// Minimum alpha value for splat rendering
minAlpha: { value: 0.5 * (1.0 / 255.0) },
// Enable interpreting 0-thickness Gsplats as 2DGS
enable2DGS: { value: false },
// Add to projected 2D splat covariance diagonal (thickens and brightens)
preBlurAmount: { value: 0.0 },
// Add to 2D splat covariance diagonal and adjust opacity (anti-aliasing)
blurAmount: { value: 0.3 },
// Depth-of-field distance to focal plane
focalDistance: { value: 0.0 },
// Full-width angle of aperture opening (in radians)
apertureAngle: { value: 0.0 },
// Modulate Gaussian kernal falloff. 0 means "no falloff, flat shading",
// 1 is normal e^-x^2 falloff.
falloff: { value: 1.0 },
// Clip Gsplats that are clipXY times beyond the +-1 frustum bounds
clipXY: { value: 1.4 },
// Debug renderSize scale factor
focalAdjustment: { value: 1.0 },
// Whether to encode Gsplat with linear RGB (for environment mapping)
encodeLinear: { value: false },
// Back-to-front sort ordering of splat indices
ordering: { type: "t", value: NewSparkRenderer.emptyOrdering },
enableExtSplats: { value: true },
// Gsplat collection to render
extSplats: { type: "t", value: NewSplatAccumulator.emptyTexture },
extSplats2: { type: "t", value: NewSplatAccumulator.emptyTexture },
// Time in seconds for time-based effects
time: { value: 0 },
// Delta time in seconds since last frame
deltaTime: { value: 0 },
// Debug flag that alternates each frame
debugFlag: { value: false },
};
return uniforms;
}
dispose() {
if (this.target) {
this.target.dispose();
this.target = undefined;
}
if (this.backTarget) {
this.backTarget.dispose();
this.backTarget = undefined;
}
if (this.orderingTexture) {
this.orderingTexture.dispose();
this.orderingTexture = null;
}
const accumulators = new Set<NewSplatAccumulator>();
accumulators.add(this.display);
accumulators.add(this.current);
for (const accumulator of this.accumulators) {
accumulators.add(accumulator);
}
for (const accumulator of accumulators) {
accumulator.dispose();
}
const instances = this.lodInstances.values();
this.lodInstances.clear();
for (const instance of instances) {
instance.texture.dispose();
}
if (this.sortWorker) {
this.sortWorker.dispose();
this.sortWorker = null;
}
if (this.lodWorker) {
this.lodWorker.dispose();
this.lodWorker = null;
}
if (this.pager) {
this.pager.dispose();
this.pager = undefined;
}
}
onBeforeRender(
renderer: THREE.WebGLRenderer,
scene: THREE.Scene,
camera: THREE.Camera,
) {
const spark = NewSparkRenderer.sparkOverride ?? this;
const frame = renderer.info.render.frame;
const isNewFrame = frame !== spark.lastFrame;
spark.lastFrame = frame;
if (spark.target) {
spark.renderSize.set(spark.target.width, spark.target.height);
} else {
const renderSize = renderer.getDrawingBufferSize(spark.renderSize);
if (renderer.xr.isPresenting) {
if (renderSize.x === 1 && renderSize.y === 1) {
// WebXR mode on Apple Vision Pro returns 1x1 when presenting.
// Use a different means to figure out the render size.
const baseLayer = renderer.xr.getSession()?.renderState.baseLayer;
if (baseLayer) {
renderSize.x = baseLayer.framebufferWidth;
renderSize.y = baseLayer.framebufferHeight;
}
}
}
}
this.uniforms.renderSize.value.copy(spark.renderSize);
const typedCamera = camera as
| THREE.PerspectiveCamera
| THREE.OrthographicCamera;
this.uniforms.near.value = typedCamera.near;
this.uniforms.far.value = typedCamera.far;
const geometry = this.geometry as NewSplatGeometry;
geometry.instanceCount = spark.activeSplats;
const accumToWorld = new THREE.Matrix4();
if (!this.display.extSplats) {
accumToWorld.makeTranslation(spark.display.viewOrigin);
}
const cameraToWorld = camera.matrixWorld.clone();
const worldToCamera = cameraToWorld.invert();
const accumToCamera = worldToCamera.multiply(accumToWorld);
accumToCamera.decompose(
this.uniforms.renderToViewPos.value,
this.uniforms.renderToViewQuat.value,
new THREE.Vector3(),
);
this.uniforms.maxStdDev.value = spark.maxStdDev;
this.uniforms.minPixelRadius.value = spark.minPixelRadius;
this.uniforms.maxPixelRadius.value = spark.maxPixelRadius;
this.uniforms.minAlpha.value = spark.minAlpha;
this.uniforms.enable2DGS.value = spark.enable2DGS;
this.uniforms.preBlurAmount.value = spark.preBlurAmount;
this.uniforms.blurAmount.value = spark.blurAmount;
this.uniforms.focalDistance.value = spark.focalDistance;
this.uniforms.apertureAngle.value = spark.apertureAngle;
this.uniforms.falloff.value = spark.falloff;
this.uniforms.clipXY.value = spark.clipXY;
this.uniforms.focalAdjustment.value = spark.focalAdjustment;
this.uniforms.encodeLinear.value = spark.encodeLinear;
this.uniforms.ordering.value =
spark.orderingTexture ?? NewSparkRenderer.emptyOrdering;
if (this.display.extSplats) {
this.uniforms.enableExtSplats.value = true;
const extSplats = spark.display.getTextures();
this.uniforms.extSplats.value = extSplats[0];
this.uniforms.extSplats2.value = extSplats[1];
} else {
this.uniforms.enableExtSplats.value = false;
const packedSplats = spark.display.getTextures();
this.uniforms.extSplats.value = packedSplats[0];
this.uniforms.extSplats2.value = packedSplats[0];
}
this.uniforms.time.value = spark.display.time;
this.uniforms.deltaTime.value = spark.display.deltaTime;
// Alternating debug flag that can aid in visual debugging
this.uniforms.debugFlag.value = (performance.now() / 1000.0) % 2.0 < 1.0;
if (spark.autoUpdate && isNewFrame) {
const preUpdate = spark.preUpdate && !renderer.xr.isPresenting;
const useCamera = renderer.xr.isPresenting
? renderer.xr.getCamera()
: camera;
if (preUpdate) {
spark.updateInternal({
scene,
camera: useCamera,
autoUpdate: true,
});
} else {
if (spark.updateTimeoutId === -1) {
spark.updateTimeoutId = setTimeout(() => {
spark.updateTimeoutId = -1;
spark.updateInternal({
scene,
camera: useCamera,
autoUpdate: true,
});
}, 1);
}
}
}
}
async update({
scene,
camera,
}: {
scene: THREE.Scene;
camera: THREE.Camera;
}) {
await this.updateInternal({ scene, camera, autoUpdate: false });
}
private async updateInternal({
scene,
camera,
autoUpdate,
}: {
scene: THREE.Scene;
camera: THREE.Camera;
autoUpdate: boolean;
}) {
const renderer = this.renderer;
const time = this.time ?? this.clock.getElapsedTime();
const center = camera.getWorldPosition(new THREE.Vector3());
const dir = camera.getWorldDirection(new THREE.Vector3());
const viewChanged =
center.distanceTo(this.sortedCenter) > 0.001 ||
dir.dot(this.sortedDir) < 0.999;
const next = this.accumulators.pop();
if (!next) {
// Should never happen
throw new Error("No next accumulator");
}
const { version, visibleGenerators, generate } = next.prepareGenerate({
renderer,
scene,
time,
camera,
sortRadial: this.sortRadial ?? true,
renderSize: this.renderSize,
previous: this.current,
lodInstances: this.enableLod ? this.lodInstances : undefined,
});
if (this.enableDriveLod) {
this.driveLod({ visibleGenerators, camera });
}
this.driveSort();
const needsUpdate = viewChanged || version !== this.current.version;
if (autoUpdate && !needsUpdate) {
// Triggered by auto-update but no change, so exit early
this.accumulators.push(next);
return null;
}
if (needsUpdate && this.sorting) {
this.accumulators.push(next);
return null;
}
generate();
if (this.flushAfterGenerate) {
const gl = renderer.getContext() as WebGL2RenderingContext;
gl.flush();
}
if (this.display.mappingVersion === next.mappingVersion) {
this.accumulators.push(this.display);
this.display = next;
} else {
if (this.display !== this.current) {
this.accumulators.push(this.current);
}
}
this.current = next;
this.sortDirty = true;
await this.driveSort();
}
private async driveSort() {
if (this.sorting || !this.sortDirty) {
return;
}
if (this.sortTimeoutId !== -1) {
clearTimeout(this.sortTimeoutId);
this.sortTimeoutId = -1;
}
const now = performance.now();
const nextSortTime = this.lastSortTime
? this.lastSortTime + this.minSortIntervalMs
: now;
if (now < nextSortTime) {
this.sortTimeoutId = setTimeout(() => {
this.sortTimeoutId = -1;
this.driveSort();
}, nextSortTime - now);
return;
}
this.sorting = true;
this.sortDirty = false;
this.lastSortTime = now;
if (this.readPause > 0) {
await new Promise((resolve) => setTimeout(resolve, this.readPause));
}
const current = this.current;
this.sortedCenter.copy(current.viewOrigin);
this.sortedDir.copy(current.viewDirection);
const { numSplats, maxSplats } = current;
const rows = Math.max(1, Math.ceil(maxSplats / 16384));
const orderingMaxSplats = rows * 16384;
this.maxSplats = Math.max(this.maxSplats, orderingMaxSplats);
const ordering = new Uint32Array(this.maxSplats);
const readback = Readback.ensureBuffer(maxSplats, this.readback32);
this.readback32 = readback;
await this.readbackDepth({
current,
renderer: this.renderer,
numSplats,
readback,
});
if (this.sortPause > 0) {
await new Promise((resolve) => setTimeout(resolve, this.sortPause));
}
if (!this.sortWorker) {
this.sortWorker = new NewSplatWorker();
}
const result = (await this.sortWorker.call("sortSplats32", {
numSplats,
readback,
ordering,
})) as {
readback: Uint16Array | Uint32Array;
ordering: Uint32Array;
activeSplats: number;
};
if (this.sortDelay > 0) {
await new Promise((resolve) => setTimeout(resolve, this.sortDelay));
}
this.readback32 = result.readback as Uint32Array<ArrayBuffer>;
this.activeSplats = result.activeSplats;
if (this.orderingTexture) {
if (rows > this.orderingTexture.image.height) {
this.orderingTexture.dispose();
this.orderingTexture = null;
}
}
if (!this.orderingTexture) {
// console.log(`Allocating orderingTexture: ${4096}x${rows}`);
const orderingTexture = new THREE.DataTexture(
result.ordering,
4096,
rows,
THREE.RGBAIntegerFormat,
THREE.UnsignedIntType,
);
orderingTexture.internalFormat = "RGBA32UI";
orderingTexture.needsUpdate = true;
this.orderingTexture = orderingTexture;
} else {
const renderer = this.renderer;
const gl = renderer.getContext() as WebGL2RenderingContext;
if (!renderer.properties.has(this.orderingTexture)) {
this.orderingTexture.needsUpdate = true;
} else {
const props = renderer.properties.get(this.orderingTexture) as {
__webglTexture: WebGLTexture;
};
const glTexture = props.__webglTexture;
if (!glTexture) {
throw new Error("ordering texture not found");
}
renderer.state.activeTexture(gl.TEXTURE0);
renderer.state.bindTexture(gl.TEXTURE_2D, glTexture);
gl.bindBuffer(gl.PIXEL_UNPACK_BUFFER, null);
gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false);
gl.texSubImage2D(
gl.TEXTURE_2D,
0,
0,
0,
4096,
rows,
gl.RGBA_INTEGER,
gl.UNSIGNED_INT,
// data,
result.ordering,
);
renderer.state.bindTexture(gl.TEXTURE_2D, null);
}
}
// console.log(`Sorted (${this.minSortIntervalMs}) ${numSplats} splats in ${(performance.now() - now).toFixed(0)} ms`);
if (this.display.mappingVersion !== current.mappingVersion) {
this.accumulators.push(this.display);
this.display = this.current;
}
this.sorting = false;
this.driveSort();
}
private ensureLodWorker() {
if (!this.lodWorker) {
this.lodWorker = new NewSplatWorker();
}
return this.lodWorker;
}
private async driveLod({
visibleGenerators,
camera: inputCamera,
}: { visibleGenerators: SplatGenerator[]; camera: THREE.Camera }) {
const lodMeshes = !this.enableLod
? []
: (visibleGenerators.filter((generator) => {
return (
generator instanceof SplatMesh &&
(generator.packedSplats?.lodSplats ||
generator.extSplats?.lodSplats ||
generator.paged) &&
generator.enableLod !== false
);
}) as SplatMesh[]);
const hasPaged = lodMeshes.some((mesh) => mesh.paged);
let forceUpdate = this.lodMeshes.length !== lodMeshes.length;
if (
!forceUpdate &&
lodMeshes.some(
(m, i) =>
m !== this.lodMeshes[i].mesh || m.version > this.lodMeshes[i].version,
)
) {
forceUpdate = true;
}
this.lodMeshes = lodMeshes.map((mesh) => ({
mesh,
version: mesh.version + 1,
}));
// console.log(`lodMeshes versions: ${JSON.stringify(this.lodMeshes.map(m => m.version))}`);
if (forceUpdate) {
this.lodDirty = true;
}
if (!this.lodDirty && lodMeshes.length === 0 && this.lodIds.size === 0) {
return;
}
const camera = inputCamera.clone();
this.lodInitQueue = [];
const now = performance.now();
for (const mesh of lodMeshes) {
const splats =
mesh.packedSplats?.lodSplats ?? mesh.extSplats?.lodSplats ?? mesh.paged;
if (splats) {
const record = this.lodIds.get(splats);
if (record) {
record.lastTouched = now;
} else {
this.lodInitQueue.push(splats);
}
}
}
this.ensureLodWorker().tryExclusive(async (worker) => {
if (hasPaged && !this.pager) {
this.pager = new SplatPager({
renderer: this.renderer,
maxSplats: this.maxPagedSplats,
});
const { lodId } = (await worker.call("newLodTree", {
capacity: this.pager.maxSplats,
})) as { lodId: number };
this.pagerId = lodId;
// console.log("*** Set pagerId to", lodId);
}
// Assign pager to any new meshes that don't have one yet
// (must run every frame, not just when pager is first created)
if (this.pager) {
for (const { mesh } of this.lodMeshes) {
if (mesh.paged && !mesh.paged.pager) {
mesh.paged.pager = this.pager;
}
}
}
if (this.lodInitQueue.length > 0) {
const lodInitQueue = this.lodInitQueue;
this.lodInitQueue = [];
while (lodInitQueue.length > 0) {
const splats = lodInitQueue.shift();
if (splats) {
await this.initLodTree(worker, splats);
this.lodDirty = true;
}
}
}
if (this.pager) {
const updates = this.pager.consumeLodTreeUpdates();
for (const { splats, page, chunk, numSplats, lodTree } of updates) {
const record = this.lodIds.get(splats);
if (record) {
if (lodTree && chunk === 0) {
record.rootPage = page;
}
this.lodUpdates.push({
lodId: record.lodId,
pageBase: page * this.pager.pageSplats,
chunkBase: chunk * this.pager.pageSplats,
count: numSplats,
lodTreeData: lodTree,
});