-
Notifications
You must be signed in to change notification settings - Fork 216
Expand file tree
/
Copy pathrad.cpp
More file actions
2287 lines (1978 loc) · 81 KB
/
Copy pathrad.cpp
File metadata and controls
2287 lines (1978 loc) · 81 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
// Writer for Spark's .RAD LoD gaussian splat format.
//
// C++ port of the Rust build-lod tool (https://github.com/sparkjsdev/spark/tree/main/rust/build-lod)
//
// Splat attributes are stored as IEEE 754 half-precision values during
// processing; this quantization is part of the format design and shapes the
// LoD construction.
#include "rad.hpp"
#include <algorithm>
#include <array>
#include <cassert>
#include <chrono>
#include <cmath>
#include <cstdint>
#include <cstring>
#include <fstream>
#include <iostream>
#include <limits>
#include <stdexcept>
#include <unordered_map>
#include <vector>
#include <miniz.h>
#include <nlohmann/json.hpp>
namespace rad {
namespace {
// insertion-ordered to control metadata key order
using json = nlohmann::ordered_json;
// IEEE 754 half-precision conversions (round-to-nearest-even)
inline uint32_t f32Bits(float f){
uint32_t x;
std::memcpy(&x, &f, 4);
return x;
}
inline float f32FromBits(uint32_t x){
float f;
std::memcpy(&f, &x, 4);
return f;
}
// half-2.6.0 f32_to_f16_fallback
uint16_t f16FromF32(float value){
uint32_t x = f32Bits(value);
uint32_t sign = x & 0x80000000u;
uint32_t exp = x & 0x7F800000u;
uint32_t man = x & 0x007FFFFFu;
if (exp == 0x7F800000u){
uint32_t nanBit = (man == 0) ? 0 : 0x0200u;
return static_cast<uint16_t>((sign >> 16) | 0x7C00u | nanBit | (man >> 13));
}
uint32_t halfSign = sign >> 16;
int32_t unbiasedExp = static_cast<int32_t>(exp >> 23) - 127;
int32_t halfExp = unbiasedExp + 15;
if (halfExp >= 0x1F){
return static_cast<uint16_t>(halfSign | 0x7C00u);
}
if (halfExp <= 0){
if (14 - halfExp > 24){
return static_cast<uint16_t>(halfSign);
}
uint32_t man2 = man | 0x00800000u;
uint32_t halfMan = man2 >> (14 - halfExp);
uint32_t roundBit = 1u << (13 - halfExp);
if ((man2 & roundBit) != 0 && (man2 & (3 * roundBit - 1)) != 0){
halfMan += 1;
}
return static_cast<uint16_t>(halfSign | halfMan);
}
uint32_t halfExpBits = static_cast<uint32_t>(halfExp) << 10;
uint32_t halfMan = man >> 13;
uint32_t roundBit = 0x00001000u;
if ((man & roundBit) != 0 && (man & (3 * roundBit - 1)) != 0){
return static_cast<uint16_t>((halfSign | halfExpBits | halfMan) + 1);
}else{
return static_cast<uint16_t>(halfSign | halfExpBits | halfMan);
}
}
// half-2.6.0 f16_to_f32_fallback
float f16ToF32(uint16_t i){
if ((i & 0x7FFFu) == 0){
return f32FromBits(static_cast<uint32_t>(i) << 16);
}
uint32_t halfSign = i & 0x8000u;
uint32_t halfExp = i & 0x7C00u;
uint32_t halfMan = i & 0x03FFu;
if (halfExp == 0x7C00u){
if (halfMan == 0){
return f32FromBits((halfSign << 16) | 0x7F800000u);
}else{
return f32FromBits((halfSign << 16) | 0x7FC00000u | (halfMan << 13));
}
}
uint32_t sign = halfSign << 16;
int32_t unbiasedExp = (static_cast<int32_t>(halfExp) >> 10) - 15;
if (halfExp == 0){
// leading_zeros_u16(halfMan) - 6; halfMan != 0 here
int32_t lz = 0;
uint16_t m = static_cast<uint16_t>(halfMan);
while (!(m & 0x8000u)){ lz++; m <<= 1; }
int32_t e = lz - 6;
uint32_t exp = static_cast<uint32_t>(127 - 15 - e) << 23;
uint32_t man = (halfMan << (14 + e)) & 0x7FFFFFu;
return f32FromBits(sign | exp | man);
}
uint32_t exp = static_cast<uint32_t>(unbiasedExp + 127) << 23;
uint32_t man = (halfMan & 0x03FFu) << 13;
return f32FromBits(sign | exp | man);
}
// A stored f16 value (bit pattern). Mirrors half::f16.
struct F16 {
uint16_t bits = 0;
F16() = default;
static F16 fromF32(float v){ F16 h; h.bits = f16FromF32(v); return h; }
float toF32() const { return f16ToF32(bits); }
bool isNan() const { return (bits & 0x7C00u) == 0x7C00u && (bits & 0x03FFu) != 0; }
};
// half-2.6.0 f16::max: if other > self && !other.is_nan() { other } else { self }
// (non-NaN f16 ordering matches f32 ordering of the converted values, incl. -0 == 0)
inline F16 f16Max(F16 self, F16 other){
if (!self.isNan() && !other.isNan() && other.toF32() > self.toF32()) return other;
return self;
}
// Rust semantics helpers
// Rust `as` cast f32 -> integer: truncate toward zero, saturate, NaN -> 0.
inline int64_t rustCastI64(float v){
if (std::isnan(v)) return 0;
if (v <= -9223372036854775808.0f) return INT64_MIN;
if (v >= 9223372036854775807.0f) return INT64_MAX;
return static_cast<int64_t>(v);
}
inline int16_t rustCastI16(float v){
if (std::isnan(v)) return 0;
if (v <= -32768.0f) return INT16_MIN;
if (v >= 32767.0f) return INT16_MAX;
return static_cast<int16_t>(v);
}
inline uint8_t rustCastU8(float v){
if (std::isnan(v)) return 0;
if (v <= 0.0f) return 0;
if (v >= 255.0f) return 255;
return static_cast<uint8_t>(v);
}
inline int8_t rustCastI8(float v){
if (std::isnan(v)) return 0;
if (v <= -128.0f) return INT8_MIN;
if (v >= 127.0f) return INT8_MAX;
return static_cast<int8_t>(v);
}
inline uint32_t rustCastU32(uint64_t v){ return static_cast<uint32_t>(v); }
// Vector / quaternion / matrix math (scalar port of glam)
struct Vec3 {
float x = 0.0f, y = 0.0f, z = 0.0f;
Vec3() = default;
Vec3(float x_, float y_, float z_) : x(x_), y(y_), z(z_) {}
static Vec3 splat(float v){ return Vec3(v, v, v); }
float operator[](int i) const { return i == 0 ? x : (i == 1 ? y : z); }
float &operator[](int i){ return i == 0 ? x : (i == 1 ? y : z); }
Vec3 operator+(const Vec3 &o) const { return Vec3(x + o.x, y + o.y, z + o.z); }
Vec3 operator-(const Vec3 &o) const { return Vec3(x - o.x, y - o.y, z - o.z); }
Vec3 operator*(const Vec3 &o) const { return Vec3(x * o.x, y * o.y, z * o.z); }
Vec3 operator*(float s) const { return Vec3(x * s, y * s, z * s); }
Vec3 operator/(float s) const { return Vec3(x / s, y / s, z / s); }
// glam mul_add without the fma target feature calls f32::mul_add, which is
// a correctly-rounded fused multiply-add (fmaf), NOT mul-then-add.
Vec3 mulAdd(const Vec3 &a, const Vec3 &b) const {
return Vec3(std::fmaf(x, a.x, b.x), std::fmaf(y, a.y, b.y), std::fmaf(z, a.z, b.z));
}
// glam sse2 max/min use _mm_max_ps/_mm_min_ps: a > b ? a : b per element
Vec3 max(const Vec3 &o) const {
return Vec3(x > o.x ? x : o.x, y > o.y ? y : o.y, z > o.z ? z : o.z);
}
Vec3 floorv() const { return Vec3(std::floor(x), std::floor(y), std::floor(z)); }
float maxElement() const {
// glam sse2 max_element: max(max(x, y), z) via _mm_max_ss (a > b ? a : b)
float m = x > y ? x : y;
return m > z ? m : z;
}
// glam sse2 dot3: (x*x' + y*y') + z*z'
float dot(const Vec3 &o) const { return (x * o.x + y * o.y) + z * o.z; }
float lengthSquared() const { return dot(*this); }
float length() const { return std::sqrt(dot(*this)); }
bool isFinite() const { return std::isfinite(x) && std::isfinite(y) && std::isfinite(z); }
};
struct I64Vec3 {
int64_t x = 0, y = 0, z = 0;
I64Vec3() = default;
I64Vec3(int64_t x_, int64_t y_, int64_t z_) : x(x_), y(y_), z(z_) {}
int64_t operator[](int i) const { return i == 0 ? x : (i == 1 ? y : z); }
bool operator==(const I64Vec3 &o) const { return x == o.x && y == o.y && z == o.z; }
};
struct I64Vec3Hash {
size_t operator()(const I64Vec3 &v) const {
// Iteration order of the cell map is never observed, so any hash works.
uint64_t h = 0x9E3779B97F4A7C15ull;
for (uint64_t c : {static_cast<uint64_t>(v.x), static_cast<uint64_t>(v.y), static_cast<uint64_t>(v.z)}){
h ^= c + 0x9E3779B97F4A7C15ull + (h << 6) + (h >> 2);
}
return static_cast<size_t>(h);
}
};
struct Quat {
float x = 0.0f, y = 0.0f, z = 0.0f, w = 1.0f;
Quat() = default;
Quat(float x_, float y_, float z_, float w_) : x(x_), y(y_), z(z_), w(w_) {}
// glam sse2 dot4: (x*x' + z*z') + (y*y' + w*w')
float dot(const Quat &o) const { return (x * o.x + z * o.z) + (y * o.y + w * o.w); }
float length() const { return std::sqrt(dot(*this)); }
bool isFinite() const {
return std::isfinite(x) && std::isfinite(y) && std::isfinite(z) && std::isfinite(w);
}
};
// Column-major 3x3 matrix: m[c] is column c. col(c)[r] = m[c][r].
struct Mat3 {
float m[3][3];
static Mat3 identity(){
Mat3 r{};
r.m[0][0] = 1.0f; r.m[1][1] = 1.0f; r.m[2][2] = 1.0f;
return r;
}
static Mat3 fromCols(const Vec3 &c0, const Vec3 &c1, const Vec3 &c2){
Mat3 r;
for (int i = 0; i < 3; i++){ r.m[0][i] = c0[i]; r.m[1][i] = c1[i]; r.m[2][i] = c2[i]; }
return r;
}
Vec3 col(int c) const { return Vec3(m[c][0], m[c][1], m[c][2]); }
// glam Mat3A::from_quat
static Mat3 fromQuat(const Quat &q){
float x2 = q.x + q.x;
float y2 = q.y + q.y;
float z2 = q.z + q.z;
float xx = q.x * x2;
float xy = q.x * y2;
float xz = q.x * z2;
float yy = q.y * y2;
float yz = q.y * z2;
float zz = q.z * z2;
float wx = q.w * x2;
float wy = q.w * y2;
float wz = q.w * z2;
return fromCols(
Vec3(1.0f - (yy + zz), xy + wz, xz - wy),
Vec3(xy - wz, 1.0f - (xx + zz), yz + wx),
Vec3(xz + wy, yz - wx, 1.0f - (xx + yy)));
}
};
// glam Quat::from_rotation_axes (Quat::from_mat3a passes the matrix columns)
Quat quatFromMat3(const Mat3 &mat){
float m00 = mat.m[0][0], m01 = mat.m[0][1], m02 = mat.m[0][2];
float m10 = mat.m[1][0], m11 = mat.m[1][1], m12 = mat.m[1][2];
float m20 = mat.m[2][0], m21 = mat.m[2][1], m22 = mat.m[2][2];
if (m22 <= 0.0f){
float dif10 = m11 - m00;
float omm22 = 1.0f - m22;
if (dif10 <= 0.0f){
float fourXsq = omm22 - dif10;
float inv4x = 0.5f / std::sqrt(fourXsq);
return Quat(fourXsq * inv4x, (m01 + m10) * inv4x, (m02 + m20) * inv4x, (m12 - m21) * inv4x);
}else{
float fourYsq = omm22 + dif10;
float inv4y = 0.5f / std::sqrt(fourYsq);
return Quat((m01 + m10) * inv4y, fourYsq * inv4y, (m12 + m21) * inv4y, (m20 - m02) * inv4y);
}
}else{
float sum10 = m11 + m00;
float opm22 = 1.0f + m22;
if (sum10 <= 0.0f){
float fourZsq = opm22 - sum10;
float inv4z = 0.5f / std::sqrt(fourZsq);
return Quat((m02 + m20) * inv4z, (m12 + m21) * inv4z, fourZsq * inv4z, (m01 - m10) * inv4z);
}else{
float fourWsq = opm22 + sum10;
float inv4w = 0.5f / std::sqrt(fourWsq);
return Quat((m12 - m21) * inv4w, (m20 - m02) * inv4w, (m01 - m10) * inv4w, fourWsq * inv4w);
}
}
}
// SymMat3 (port of spark-lib/src/symmat3.rs)
// Storage [xx, yy, zz, xy] + [xz, yz]
struct SymMat3 {
float v0[4] = {0, 0, 0, 0}; // xx, yy, zz, xy
float v1[2] = {0, 0}; // xz, yz
static SymMat3 make(float xx, float yy, float zz, float xy, float xz, float yz){
SymMat3 r;
r.v0[0] = xx; r.v0[1] = yy; r.v0[2] = zz; r.v0[3] = xy;
r.v1[0] = xz; r.v1[1] = yz;
return r;
}
float xx() const { return v0[0]; }
float yy() const { return v0[1]; }
float zz() const { return v0[2]; }
float xy() const { return v0[3]; }
float xz() const { return v1[0]; }
float yz() const { return v1[1]; }
static SymMat3 newScaleQuaternion(const Vec3 &scale, const Quat &quat){
Mat3 rot = Mat3::fromQuat(quat);
Vec3 sx = rot.col(0) * scale.x;
Vec3 sy = rot.col(1) * scale.y;
Vec3 sz = rot.col(2) * scale.z;
float xx = sx.x * sx.x + sy.x * sy.x + sz.x * sz.x;
float yy = sx.y * sx.y + sy.y * sy.y + sz.y * sz.y;
float zz = sx.z * sx.z + sy.z * sy.z + sz.z * sz.z;
float xy = sx.x * sx.y + sy.x * sy.y + sz.x * sz.y;
float xz = sx.x * sx.z + sy.x * sy.z + sz.x * sz.z;
float yz = sx.y * sx.z + sy.y * sy.z + sz.y * sz.z;
return make(xx, yy, zz, xy, xz, yz);
}
// Vec4/Vec2 mul_add = correctly-rounded fused multiply-add (see Vec3::mulAdd)
void addWeighted(const SymMat3 &other, float weight){
for (int i = 0; i < 4; i++) v0[i] = std::fmaf(other.v0[i], weight, v0[i]);
for (int i = 0; i < 2; i++) v1[i] = std::fmaf(other.v1[i], weight, v1[i]);
}
static SymMat3 newAverage(const SymMat3 &a, const SymMat3 &b){
SymMat3 r;
for (int i = 0; i < 4; i++) r.v0[i] = std::fmaf(a.v0[i], 0.5f, b.v0[i] * 0.5f);
for (int i = 0; i < 2; i++) r.v1[i] = std::fmaf(a.v1[i], 0.5f, b.v1[i] * 0.5f);
return r;
}
float determinant() const {
float m00 = v0[0], m11 = v0[1], m22 = v0[2];
float m01 = v0[3], m02 = v1[0], m12 = v1[1];
return m00 * (m11 * m22 - m12 * m12) -
m01 * (m01 * m22 - m12 * m02) +
m02 * (m01 * m12 - m11 * m02);
}
bool inverse(SymMat3 &out) const {
float m00 = v0[0], m11 = v0[1], m22 = v0[2];
float m01 = v0[3], m02 = v1[0], m12 = v1[1];
float det = determinant();
float diagMax = std::fmaxf(std::fmaxf(std::fabs(v0[0]), std::fabs(v0[1])), std::fabs(v0[2]));
float relTol = 1e-9f * std::fmaxf(diagMax * diagMax * diagMax, 1e-30f);
if (std::fabs(det) < relTol){
return false;
}
float invDet = 1.0f / det;
out = make((m11 * m22 - m12 * m12) * invDet,
(m00 * m22 - m02 * m02) * invDet,
(m00 * m11 - m01 * m01) * invDet,
(m02 * m12 - m01 * m22) * invDet,
(m01 * m12 - m02 * m11) * invDet,
(m01 * m02 - m00 * m12) * invDet);
return true;
}
void eigens(float vals[3], Vec3 vecs[3]) const {
const int MAX_ITERS = 32;
float eps;
{
float s = std::fabs(v0[0]) + std::fabs(v0[1]) + std::fabs(v0[2]);
eps = 1e-6f * std::fmaxf(s, 1.0f);
}
Mat3 current = Mat3::fromCols(
Vec3(v0[0], v0[3], v1[0]),
Vec3(v0[3], v0[1], v1[1]),
Vec3(v1[0], v1[1], v0[2]));
Mat3 eigs = Mat3::identity();
auto offDiagNorm2 = [](const Mat3 &a) -> float {
float a01 = a.m[0][1];
float a02 = a.m[0][2];
float a12 = a.m[1][2];
return a01 * a01 + a02 * a02 + a12 * a12;
};
int k = 0;
while (k < MAX_ITERS && offDiagNorm2(current) > (eps * eps)){
int p = 0, q = 1;
float maxVal = std::fabs(current.m[0][1]);
const struct { int i, j; } cand[2] = {{0, 2}, {1, 2}};
const float candVal[2] = {std::fabs(current.m[0][2]), std::fabs(current.m[1][2])};
for (int c = 0; c < 2; c++){
if (candVal[c] > maxVal){
maxVal = candVal[c];
p = cand[c].i;
q = cand[c].j;
}
}
float apq = current.m[p][q];
if (std::fabs(apq) > eps){
float app = current.m[p][p];
float aqq = current.m[q][q];
float tau = aqq - app;
float phi = 0.5f * std::atan2(2.0f * apq, tau);
float c = std::cos(phi);
float s = std::sin(phi);
for (int r = 0; r < 3; r++){
float arp = current.m[r][p];
float arq = current.m[r][q];
current.m[r][p] = c * arp - s * arq;
current.m[r][q] = s * arp + c * arq;
}
for (int r = 0; r < 3; r++){
float apr = current.m[p][r];
float aqr = current.m[q][r];
current.m[p][r] = c * apr - s * aqr;
current.m[q][r] = s * apr + c * aqr;
}
current.m[p][q] = 0.0f;
current.m[q][p] = 0.0f;
for (int r = 0; r < 3; r++){
float vrp = eigs.m[r][p];
float vrq = eigs.m[r][q];
eigs.m[r][p] = c * vrp - s * vrq;
eigs.m[r][q] = s * vrp + c * vrq;
}
}
k += 1;
}
float rawVals[3] = {current.m[0][0], current.m[1][1], current.m[2][2]};
Vec3 rawVecs[3] = {
Vec3(eigs.m[0][0], eigs.m[1][0], eigs.m[2][0]),
Vec3(eigs.m[0][1], eigs.m[1][1], eigs.m[2][1]),
Vec3(eigs.m[0][2], eigs.m[1][2], eigs.m[2][2]),
};
for (int j = 0; j < 3; j++){
float n = std::sqrt(rawVecs[j].x * rawVecs[j].x + rawVecs[j].y * rawVecs[j].y + rawVecs[j].z * rawVecs[j].z);
if (n > 0.0f){
rawVecs[j].x /= n;
rawVecs[j].y /= n;
rawVecs[j].z /= n;
}
}
// Stable sort of [0,1,2] by descending eigenvalue
int idx[3] = {0, 1, 2};
std::stable_sort(idx, idx + 3, [&](int a, int b){
return rawVals[b] < rawVals[a];
});
for (int j = 0; j < 3; j++){
vals[j] = rawVals[idx[j]];
vecs[j] = rawVecs[idx[j]];
}
}
void positiveEigens(float vals[3], Vec3 vecs[3]) const {
eigens(vals, vecs);
float det =
vecs[0][0] * (vecs[1][1] * vecs[2][2] - vecs[1][2] * vecs[2][1]) -
vecs[0][1] * (vecs[1][0] * vecs[2][2] - vecs[1][2] * vecs[2][0]) +
vecs[0][2] * (vecs[1][0] * vecs[2][1] - vecs[1][1] * vecs[2][0]);
if (det < 0.0f){
vecs[2] = Vec3(-vecs[2][0], -vecs[2][1], -vecs[2][2]);
}
}
};
// Max-heap keyed by (float, index), compared lexicographically. Keys are
// unique, so pop order is fully deterministic; the internal array order only
// affects tie-breaking in neighbor scans.
struct HeapKey {
float key;
size_t index;
bool operator<(const HeapKey &o) const {
if (key != o.key) return key < o.key;
return index < o.index;
}
};
struct MaxHeap {
std::vector<HeapKey> data;
size_t len() const { return data.size(); }
bool isEmpty() const { return data.empty(); }
void push(const HeapKey &item){
data.push_back(item);
std::push_heap(data.begin(), data.end());
}
bool pop(HeapKey &out){
if (data.empty()) return false;
std::pop_heap(data.begin(), data.end());
out = data.back();
data.pop_back();
return true;
}
void extend(const std::vector<HeapKey> &items){
data.insert(data.end(), items.begin(), items.end());
std::make_heap(data.begin(), data.end());
}
};
// Gsplat / GsplatArray (port of spark-lib/src/gsplat.rs + tsplat.rs)
// tsplat.rs ellipsoid_area (Knud Thomsen approximation)
float ellipsoidArea(const Vec3 &scales){
const float P = 1.6075f;
float numerator = std::pow(scales.x * scales.y, P) + std::pow(scales.x * scales.z, P) +
std::pow(scales.y * scales.z, P);
return 4.0f * 3.14159265358979323846264338327950288f * std::pow(numerator / 3.0f, 1.0f / P);
}
struct Gsplat {
Vec3 center;
F16 opacity;
F16 rgb[3];
F16 lnScales[3];
F16 quaternion[4]; // x, y, z, w
static Gsplat make(const Vec3 ¢er, float opacity, const Vec3 &rgb, const Vec3 &scales,
const Quat &quaternion){
Gsplat s;
s.center = center;
s.opacity = F16::fromF32(opacity);
s.rgb[0] = F16::fromF32(rgb.x);
s.rgb[1] = F16::fromF32(rgb.y);
s.rgb[2] = F16::fromF32(rgb.z);
s.lnScales[0] = F16::fromF32(std::log(scales.x));
s.lnScales[1] = F16::fromF32(std::log(scales.y));
s.lnScales[2] = F16::fromF32(std::log(scales.z));
s.quaternion[0] = F16::fromF32(quaternion.x);
s.quaternion[1] = F16::fromF32(quaternion.y);
s.quaternion[2] = F16::fromF32(quaternion.z);
s.quaternion[3] = F16::fromF32(quaternion.w);
return s;
}
Vec3 getCenter() const { return center; }
float getOpacity() const { return opacity.toF32(); }
Vec3 getRgb() const { return Vec3(rgb[0].toF32(), rgb[1].toF32(), rgb[2].toF32()); }
Vec3 getScales() const {
return Vec3(std::exp(lnScales[0].toF32()), std::exp(lnScales[1].toF32()),
std::exp(lnScales[2].toF32()));
}
Quat getQuaternion() const {
return Quat(quaternion[0].toF32(), quaternion[1].toF32(), quaternion[2].toF32(),
quaternion[3].toF32());
}
// gsplat.rs: max over f16 ln_scales, then exp
float maxScale() const {
return std::exp(f16Max(f16Max(lnScales[0], lnScales[1]), lnScales[2]).toF32());
}
void setCenter(const Vec3 &c){ center = c; }
void setOpacity(float v){ opacity = F16::fromF32(v); }
void setRgb(const Vec3 &v){
rgb[0] = F16::fromF32(v.x);
rgb[1] = F16::fromF32(v.y);
rgb[2] = F16::fromF32(v.z);
}
void setScales(const Vec3 &scales){
lnScales[0] = F16::fromF32(std::log(scales.x));
lnScales[1] = F16::fromF32(std::log(scales.y));
lnScales[2] = F16::fromF32(std::log(scales.z));
}
void setQuaternion(const Quat &q){
quaternion[0] = F16::fromF32(q.x);
quaternion[1] = F16::fromF32(q.y);
quaternion[2] = F16::fromF32(q.z);
quaternion[3] = F16::fromF32(q.w);
}
float area() const { return ellipsoidArea(getScales()); }
// tsplat.rs lod_opacity
float lodOpacity() const {
float op = getOpacity();
if (op > 1.0f){
return std::sqrt(1.0f + 2.71828182845904523536028747135266250f * std::log(op));
}
return 1.0f;
}
float featureSize() const { return 2.0f * maxScale() * lodOpacity(); }
// tsplat.rs grid: (center / step).floor().as_i64vec3()
I64Vec3 grid(float stepSize) const {
Vec3 g = (center / stepSize).floorv();
return I64Vec3(rustCastI64(g.x), rustCastI64(g.y), rustCastI64(g.z));
}
};
// tsplat.rs bhattacharyya_distance
float bhattacharyyaDistance(const Gsplat &a, const Gsplat &b){
SymMat3 covA = SymMat3::newScaleQuaternion(a.getScales(), a.getQuaternion());
SymMat3 covB = SymMat3::newScaleQuaternion(b.getScales(), b.getQuaternion());
SymMat3 sigma = SymMat3::newAverage(covA, covB);
SymMat3 inv;
if (!sigma.inverse(inv)){
return 0.0f;
}
Vec3 delta = b.getCenter() - a.getCenter();
float quad = inv.xx() * delta.x * delta.x
+ inv.yy() * delta.y * delta.y
+ inv.zz() * delta.z * delta.z
+ 2.0f * inv.xy() * delta.x * delta.y
+ 2.0f * inv.xz() * delta.x * delta.z
+ 2.0f * inv.yz() * delta.y * delta.z;
float term1 = 0.125f * quad;
float detSigma = sigma.determinant();
float detA = covA.determinant();
float detB = covB.determinant();
float term2 = 0.5f * std::log(detSigma / std::sqrt(detA * detB));
return term1 + term2;
}
// tsplat.rs similarity_metric
float similarityMetric(const Gsplat &a, const Gsplat &b){
float spatial = std::exp(-bhattacharyyaDistance(a, b));
Vec3 colorDelta = a.getRgb() - b.getRgb();
float colorDelta2 = colorDelta.lengthSquared();
float metric = spatial * std::exp(-colorDelta2);
if (std::isnan(metric)){
return 0.0f;
}
return metric;
}
// tsplat.rs compute_swaps
std::vector<std::pair<size_t, size_t>> computeSwaps(const std::vector<size_t> &indexMap){
size_t n = indexMap.size();
std::vector<size_t> destOfSrc(n, 0);
for (size_t newI = 0; newI < n; newI++){
destOfSrc[indexMap[newI]] = newI;
}
std::vector<std::pair<size_t, size_t>> swaps;
for (size_t i = 0; i < n; i++){
while (destOfSrc[i] != i){
size_t j = destOfSrc[i];
swaps.push_back({i, j});
std::swap(destOfSrc[i], destOfSrc[j]);
}
}
return swaps;
}
template <typename T>
void applySwaps(std::vector<T> &data, const std::vector<std::pair<size_t, size_t>> &swaps){
for (const auto &s : swaps){
std::swap(data[s.first], data[s.second]);
}
}
typedef std::array<F16, 9> GsplatSH1; // 3 coeffs x rgb
typedef std::array<F16, 15> GsplatSH2; // 5 coeffs x rgb
typedef std::array<F16, 21> GsplatSH3; // 7 coeffs x rgb
struct GsplatArray {
size_t maxShDegree = 0;
std::vector<Gsplat> splats;
std::vector<std::vector<size_t>> children;
std::vector<GsplatSH1> sh1;
std::vector<GsplatSH2> sh2;
std::vector<GsplatSH3> sh3;
size_t len() const { return splats.size(); }
void prepareChildren(){ children.resize(len()); }
bool hasLodTree() const { return !children.empty(); }
// gsplat.rs new_merged (step is always 0.0 from bhatt_lod)
size_t newMerged(const size_t *indices, size_t numIndices, float step){
size_t newIndex = splats.size();
std::vector<float> weights(numIndices);
for (size_t i = 0; i < numIndices; i++){
const Gsplat &splat = splats[indices[i]];
weights[i] = splat.area() * splat.getOpacity();
}
float sum = 0.0f;
for (size_t i = 0; i < numIndices; i++) sum += weights[i];
float totalWeight = std::fmaxf(sum, 1.0e-30f);
for (size_t i = 0; i < numIndices; i++) weights[i] /= totalWeight;
Vec3 center = Vec3(0, 0, 0);
Vec3 rgb = Vec3(0, 0, 0);
for (size_t i = 0; i < numIndices; i++){
const Gsplat &splat = splats[indices[i]];
float weight = weights[i];
center = splat.getCenter().mulAdd(Vec3::splat(weight), center);
rgb = splat.getRgb().mulAdd(Vec3::splat(weight), rgb);
}
SymMat3 totalCov;
float filter2 = (0.5f * step) * (0.5f * step); // powi(2)
for (size_t i = 0; i < numIndices; i++){
const Gsplat &splat = splats[indices[i]];
float weight = weights[i];
Vec3 delta = splat.getCenter() - center;
SymMat3 cov = SymMat3::newScaleQuaternion(splat.getScales(), splat.getQuaternion());
float xx = delta.x * delta.x + cov.xx() + filter2;
float yy = delta.y * delta.y + cov.yy() + filter2;
float zz = delta.z * delta.z + cov.zz() + filter2;
float xy = delta.x * delta.y + cov.xy();
float xz = delta.x * delta.z + cov.xz();
float yz = delta.y * delta.z + cov.yz();
totalCov.addWeighted(SymMat3::make(xx, yy, zz, xy, xz, yz), weight);
}
float vals[3];
Vec3 vecs[3];
totalCov.positiveEigens(vals, vecs);
Vec3 scales = Vec3(std::sqrt(std::fmaxf(vals[0], 0.0f)), std::sqrt(std::fmaxf(vals[1], 0.0f)),
std::sqrt(std::fmaxf(vals[2], 0.0f)));
scales = scales.max(Vec3::splat(1.0e-30f));
Mat3 basis = Mat3::fromCols(vecs[0], vecs[1], vecs[2]);
Quat quaternion = quatFromMat3(basis);
float opacity = totalWeight / ellipsoidArea(scales);
opacity = std::clamp(opacity, 0.000001f, 1000.0f);
splats.push_back(Gsplat::make(center, opacity, rgb, scales, quaternion));
children.push_back(std::vector<size_t>(indices, indices + numIndices));
if (maxShDegree >= 1){
Vec3 total[3] = {Vec3(0, 0, 0), Vec3(0, 0, 0), Vec3(0, 0, 0)};
for (size_t i = 0; i < numIndices; i++){
float weight = weights[i];
const GsplatSH1 &s = sh1[indices[i]];
for (int c = 0; c < 3; c++){
Vec3 v(s[c * 3 + 0].toF32(), s[c * 3 + 1].toF32(), s[c * 3 + 2].toF32());
total[c] = v.mulAdd(Vec3::splat(weight), total[c]);
}
}
GsplatSH1 out;
for (int c = 0; c < 3; c++){
out[c * 3 + 0] = F16::fromF32(total[c].x);
out[c * 3 + 1] = F16::fromF32(total[c].y);
out[c * 3 + 2] = F16::fromF32(total[c].z);
}
sh1.push_back(out);
}
if (maxShDegree >= 2){
Vec3 total[5] = {Vec3(0, 0, 0), Vec3(0, 0, 0), Vec3(0, 0, 0), Vec3(0, 0, 0), Vec3(0, 0, 0)};
for (size_t i = 0; i < numIndices; i++){
float weight = weights[i];
const GsplatSH2 &s = sh2[indices[i]];
for (int c = 0; c < 5; c++){
Vec3 v(s[c * 3 + 0].toF32(), s[c * 3 + 1].toF32(), s[c * 3 + 2].toF32());
total[c] = v.mulAdd(Vec3::splat(weight), total[c]);
}
}
GsplatSH2 out;
for (int c = 0; c < 5; c++){
out[c * 3 + 0] = F16::fromF32(total[c].x);
out[c * 3 + 1] = F16::fromF32(total[c].y);
out[c * 3 + 2] = F16::fromF32(total[c].z);
}
sh2.push_back(out);
}
if (maxShDegree >= 3){
Vec3 total[7];
for (size_t i = 0; i < numIndices; i++){
float weight = weights[i];
const GsplatSH3 &s = sh3[indices[i]];
for (int c = 0; c < 7; c++){
Vec3 v(s[c * 3 + 0].toF32(), s[c * 3 + 1].toF32(), s[c * 3 + 2].toF32());
total[c] = v.mulAdd(Vec3::splat(weight), total[c]);
}
}
GsplatSH3 out;
for (int c = 0; c < 7; c++){
out[c * 3 + 0] = F16::fromF32(total[c].x);
out[c * 3 + 1] = F16::fromF32(total[c].y);
out[c * 3 + 2] = F16::fromF32(total[c].z);
}
sh3.push_back(out);
}
return newIndex;
}
void setChildren(size_t parent, const std::vector<size_t> &c){ children[parent] = c; }
std::vector<size_t> getChildren(size_t parent) const { return children[parent]; }
float similarity(size_t a, size_t b) const { return similarityMetric(splats[a], splats[b]); }
template <typename F>
void retain(F f){
std::vector<bool> keep(splats.size());
for (size_t i = 0; i < splats.size(); i++){
keep[i] = f(splats[i]);
}
retainByMask(splats, keep);
if (!children.empty()) retainByMask(children, keep);
if (!sh1.empty()) retainByMask(sh1, keep);
if (!sh2.empty()) retainByMask(sh2, keep);
if (!sh3.empty()) retainByMask(sh3, keep);
}
void permute(const std::vector<size_t> &indexMap){
assert(indexMap.size() == splats.size());
auto swaps = computeSwaps(indexMap);
applySwaps(splats, swaps);
if (!children.empty()) applySwaps(children, swaps);
if (!sh1.empty()) applySwaps(sh1, swaps);
if (!sh2.empty()) applySwaps(sh2, swaps);
if (!sh3.empty()) applySwaps(sh3, swaps);
}
void truncate(size_t count){
if (splats.size() > count) splats.resize(count);
if (!children.empty() && children.size() > count) children.resize(count);
if (!sh1.empty() && sh1.size() > count) sh1.resize(count);
if (!sh2.empty() && sh2.size() > count) sh2.resize(count);
if (!sh3.empty() && sh3.size() > count) sh3.resize(count);
}
// tsplat.rs sort_by: stable sort of the index map by key, then permute
void sortByFeatureSize(){
std::vector<size_t> indexMap(len());
for (size_t i = 0; i < indexMap.size(); i++) indexMap[i] = i;
std::vector<float> keys(len());
for (size_t i = 0; i < keys.size(); i++) keys[i] = splats[i].featureSize();
// OrderedFloat<f32> ordering; keys are finite here so plain < works,
// and stable_sort preserves equal-key order like Rust's stable sort.
std::stable_sort(indexMap.begin(), indexMap.end(),
[&](size_t a, size_t b){ return keys[a] < keys[b]; });
permute(indexMap);
}
// tsplat.rs encode_lod_opacity
void encodeLodOpacity(){
for (size_t i = 0; i < len(); i++){
Gsplat &splat = splats[i];
if (splat.getOpacity() > 1.0f){
float d = splat.lodOpacity();
splat.setOpacity(std::clamp(0.25f * (d - 1.0f) + 1.0f, 1.0f, 2.0f));
}
}
}
private:
template <typename T>
static void retainByMask(std::vector<T> &v, const std::vector<bool> &keep){
size_t out = 0;
for (size_t i = 0; i < v.size(); i++){
if (keep[i]){
if (out != i) v[out] = std::move(v[i]);
out++;
}
}
v.resize(out);
}
};
// bhatt_lod (port of spark-lib/src/bhatt_lod.rs)
const float MERGE_BASE = 2.0f;
void bhattRecurseToOutput(GsplatArray &splats, size_t index, std::vector<bool> &toOutput,
float lodBase, float &featureSizeOut, std::vector<size_t> &childrenOut){
float featureSize;
{
const Gsplat &splat = splats.splats[index];
featureSize = splat.area() * splat.getOpacity();
}
std::vector<size_t> children = splats.getChildren(index);
if (children.empty()){
featureSizeOut = featureSize;
childrenOut.assign(1, index);
return;
}
std::vector<size_t> newChildren;
float maxChildFeatureSize = -std::numeric_limits<float>::infinity();
for (size_t child : children){
float childFeatureSize;
std::vector<size_t> childChildren;
bhattRecurseToOutput(splats, child, toOutput, lodBase, childFeatureSize, childChildren);
maxChildFeatureSize = std::fmaxf(maxChildFeatureSize, childFeatureSize);
newChildren.insert(newChildren.end(), childChildren.begin(), childChildren.end());
}
if (featureSize >= (maxChildFeatureSize * lodBase)){
toOutput[index] = true;
}
if (toOutput[index]){
assert(newChildren.size() <= 65535);
splats.setChildren(index, newChildren);
featureSizeOut = featureSize;
childrenOut.assign(1, index);
}else{
splats.setChildren(index, std::vector<size_t>());
featureSizeOut = maxChildFeatureSize;
childrenOut = std::move(newChildren);
}
}
void bhattRecurseIndices(GsplatArray &splats, size_t index, std::vector<size_t> &indices,
float limitSize, std::vector<size_t> &frontier){
if (splats.splats[index].featureSize() < limitSize){
frontier.push_back(index);
return;
}
std::vector<size_t> children = splats.getChildren(index);
if (children.empty()){
return;
}
std::vector<size_t> newChildren(children.size());
for (size_t i = 0; i < children.size(); i++) newChildren[i] = indices.size() + i;
splats.setChildren(index, newChildren);
std::sort(children.begin(), children.end());
for (size_t child : children){
indices.push_back(child);
}
for (size_t child : children){
bhattRecurseIndices(splats, child, indices, limitSize, frontier);
}
}
void bhattComputeLodTree(GsplatArray &splats, float lodBase){
size_t initialLen = splats.len();
if (initialLen == 0){
return;
}
splats.sortByFeatureSize();
splats.prepareChildren();
std::vector<bool> isActive(splats.len(), true);