-
Notifications
You must be signed in to change notification settings - Fork 1.9k
/
testbed_nerf.cu
3689 lines (3095 loc) · 136 KB
/
testbed_nerf.cu
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
/*
* Copyright (c) 2020-2022, NVIDIA CORPORATION. All rights reserved.
*
* NVIDIA CORPORATION and its licensors retain all intellectual property
* and proprietary rights in and to this software, related documentation
* and any modifications thereto. Any use, reproduction, disclosure or
* distribution of this software and related documentation without an express
* license agreement from NVIDIA CORPORATION is strictly prohibited.
*/
/** @file testbed_nerf.cu
* @author Thomas Müller & Alex Evans, NVIDIA
*/
#include <neural-graphics-primitives/adam_optimizer.h>
#include <neural-graphics-primitives/common_device.cuh>
#include <neural-graphics-primitives/common.h>
#include <neural-graphics-primitives/envmap.cuh>
#include <neural-graphics-primitives/json_binding.h>
#include <neural-graphics-primitives/marching_cubes.h>
#include <neural-graphics-primitives/nerf_loader.h>
#include <neural-graphics-primitives/nerf_network.h>
#include <neural-graphics-primitives/render_buffer.h>
#include <neural-graphics-primitives/testbed.h>
#include <neural-graphics-primitives/trainable_buffer.cuh>
#include <neural-graphics-primitives/triangle_octree.cuh>
#include <tiny-cuda-nn/encodings/grid.h>
#include <tiny-cuda-nn/encodings/spherical_harmonics.h>
#include <tiny-cuda-nn/loss.h>
#include <tiny-cuda-nn/network_with_input_encoding.h>
#include <tiny-cuda-nn/network.h>
#include <tiny-cuda-nn/optimizer.h>
#include <tiny-cuda-nn/trainer.h>
#include <filesystem/directory.h>
#include <filesystem/path.h>
#ifdef copysign
#undef copysign
#endif
using namespace tcnn;
NGP_NAMESPACE_BEGIN
inline constexpr __device__ float NERF_RENDERING_NEAR_DISTANCE() { return 0.05f; }
inline constexpr __device__ uint32_t NERF_STEPS() { return 1024; } // finest number of steps per unit length
inline constexpr __device__ uint32_t NERF_CASCADES() { return 8; }
inline constexpr __device__ float SQRT3() { return 1.73205080757f; }
inline constexpr __device__ float STEPSIZE() { return (SQRT3() / NERF_STEPS()); } // for nerf raymarch
inline constexpr __device__ float MIN_CONE_STEPSIZE() { return STEPSIZE(); }
// Maximum step size is the width of the coarsest gridsize cell.
inline constexpr __device__ float MAX_CONE_STEPSIZE() { return STEPSIZE() * (1<<(NERF_CASCADES()-1)) * NERF_STEPS() / NERF_GRIDSIZE(); }
// Used to index into the PRNG stream. Must be larger than the number of
// samples consumed by any given training ray.
inline constexpr __device__ uint32_t N_MAX_RANDOM_SAMPLES_PER_RAY() { return 16; }
// Any alpha below this is considered "invisible" and is thus culled away.
inline constexpr __device__ float NERF_MIN_OPTICAL_THICKNESS() { return 0.01f; }
static constexpr uint32_t MARCH_ITER = 10000;
static constexpr uint32_t MIN_STEPS_INBETWEEN_COMPACTION = 1;
static constexpr uint32_t MAX_STEPS_INBETWEEN_COMPACTION = 8;
Testbed::NetworkDims Testbed::network_dims_nerf() const {
NetworkDims dims;
dims.n_input = sizeof(NerfCoordinate) / sizeof(float);
dims.n_output = 4;
dims.n_pos = sizeof(NerfPosition) / sizeof(float);
return dims;
}
inline __host__ __device__ uint32_t grid_mip_offset(uint32_t mip) {
return NERF_GRID_N_CELLS() * mip;
}
inline __host__ __device__ float calc_cone_angle(float cosine, const vec2& focal_length, float cone_angle_constant) {
// Pixel size. Doesn't always yield a good performance vs. quality
// trade off. Especially if training pixels have a much different
// size than rendering pixels.
// return cosine*cosine / focal_length.mean();
return cone_angle_constant;
}
inline __host__ __device__ float to_stepping_space(float t, float cone_angle) {
if (cone_angle <= 1e-5f) {
return t / MIN_CONE_STEPSIZE();
}
float log1p_c = logf(1.0f + cone_angle);
float a = (logf(MIN_CONE_STEPSIZE()) - logf(log1p_c)) / log1p_c;
float b = (logf(MAX_CONE_STEPSIZE()) - logf(log1p_c)) / log1p_c;
float at = expf(a * log1p_c);
float bt = expf(b * log1p_c);
if (t <= at) {
return (t - at) / MIN_CONE_STEPSIZE() + a;
} else if (t <= bt) {
return logf(t) / log1p_c;
} else {
return (t - bt) / MAX_CONE_STEPSIZE() + b;
}
}
inline __host__ __device__ float from_stepping_space(float n, float cone_angle) {
if (cone_angle <= 1e-5f) {
return n * MIN_CONE_STEPSIZE();
}
float log1p_c = logf(1.0f + cone_angle);
float a = (logf(MIN_CONE_STEPSIZE()) - logf(log1p_c)) / log1p_c;
float b = (logf(MAX_CONE_STEPSIZE()) - logf(log1p_c)) / log1p_c;
float at = expf(a * log1p_c);
float bt = expf(b * log1p_c);
if (n <= a) {
return (n - a) * MIN_CONE_STEPSIZE() + at;
} else if (n <= b) {
return expf(n * log1p_c);
} else {
return (n - b) * MAX_CONE_STEPSIZE() + bt;
}
}
inline __host__ __device__ float advance_n_steps(float t, float cone_angle, float n) {
return from_stepping_space(to_stepping_space(t, cone_angle) + n, cone_angle);
}
inline __host__ __device__ float calc_dt(float t, float cone_angle) {
return advance_n_steps(t, cone_angle, 1.0f) - t;
}
struct LossAndGradient {
vec3 loss;
vec3 gradient;
__host__ __device__ LossAndGradient operator*(float scalar) {
return {loss * scalar, gradient * scalar};
}
__host__ __device__ LossAndGradient operator/(float scalar) {
return {loss / scalar, gradient / scalar};
}
};
inline __device__ vec3 copysign(const vec3& a, const vec3& b) {
return {
copysignf(a.x, b.x),
copysignf(a.y, b.y),
copysignf(a.z, b.z),
};
}
inline __device__ LossAndGradient l2_loss(const vec3& target, const vec3& prediction) {
vec3 difference = prediction - target;
return {
difference * difference,
2.0f * difference
};
}
inline __device__ LossAndGradient relative_l2_loss(const vec3& target, const vec3& prediction) {
vec3 difference = prediction - target;
vec3 denom = prediction * prediction + vec3(1e-2f);
return {
difference * difference / denom,
2.0f * difference / denom
};
}
inline __device__ LossAndGradient l1_loss(const vec3& target, const vec3& prediction) {
vec3 difference = prediction - target;
return {
abs(difference),
copysign(vec3(1.0f), difference),
};
}
inline __device__ LossAndGradient huber_loss(const vec3& target, const vec3& prediction, float alpha = 1) {
vec3 difference = prediction - target;
vec3 abs_diff = abs(difference);
vec3 square = 0.5f/alpha * difference * difference;
return {
{
abs_diff.x > alpha ? (abs_diff.x - 0.5f * alpha) : square.x,
abs_diff.y > alpha ? (abs_diff.y - 0.5f * alpha) : square.y,
abs_diff.z > alpha ? (abs_diff.z - 0.5f * alpha) : square.z,
},
{
abs_diff.x > alpha ? (difference.x > 0 ? 1.0f : -1.0f) : (difference.x / alpha),
abs_diff.y > alpha ? (difference.y > 0 ? 1.0f : -1.0f) : (difference.y / alpha),
abs_diff.z > alpha ? (difference.z > 0 ? 1.0f : -1.0f) : (difference.z / alpha),
},
};
}
inline __device__ LossAndGradient log_l1_loss(const vec3& target, const vec3& prediction) {
vec3 difference = prediction - target;
vec3 divisor = abs(difference) + vec3(1.0f);
return {
log(divisor),
copysign(vec3(1.0f) / divisor, difference),
};
}
inline __device__ LossAndGradient smape_loss(const vec3& target, const vec3& prediction) {
vec3 difference = prediction - target;
vec3 denom = 0.5f * (abs(prediction) + abs(target)) + vec3(1e-2f);
return {
abs(difference) / denom,
copysign(vec3(1.0f) / denom, difference),
};
}
inline __device__ LossAndGradient mape_loss(const vec3& target, const vec3& prediction) {
vec3 difference = prediction - target;
vec3 denom = abs(prediction) + vec3(1e-2f);
return {
abs(difference) / denom,
copysign(vec3(1.0f) / denom, difference),
};
}
inline __device__ float distance_to_next_voxel(const vec3& pos, const vec3& dir, const vec3& idir, float res) { // dda like step
vec3 p = res * (pos - vec3(0.5f));
float tx = (floorf(p.x + 0.5f + 0.5f * sign(dir.x)) - p.x) * idir.x;
float ty = (floorf(p.y + 0.5f + 0.5f * sign(dir.y)) - p.y) * idir.y;
float tz = (floorf(p.z + 0.5f + 0.5f * sign(dir.z)) - p.z) * idir.z;
float t = min(min(tx, ty), tz);
return fmaxf(t / res, 0.0f);
}
inline __device__ float advance_to_next_voxel(float t, float cone_angle, const vec3& pos, const vec3& dir, const vec3& idir, uint32_t mip) {
float res = scalbnf(NERF_GRIDSIZE(), -(int)mip);
float t_target = t + distance_to_next_voxel(pos, dir, idir, res);
// Analytic stepping in multiples of 1 in the "log-space" of our exponential stepping routine
t = to_stepping_space(t, cone_angle);
t_target = to_stepping_space(t_target, cone_angle);
return from_stepping_space(t + ceilf(fmaxf(t_target - t, 0.5f)), cone_angle);
}
__device__ float network_to_rgb(float val, ENerfActivation activation) {
switch (activation) {
case ENerfActivation::None: return val;
case ENerfActivation::ReLU: return val > 0.0f ? val : 0.0f;
case ENerfActivation::Logistic: return tcnn::logistic(val);
case ENerfActivation::Exponential: return __expf(tcnn::clamp(val, -10.0f, 10.0f));
default: assert(false);
}
return 0.0f;
}
__device__ float network_to_rgb_derivative(float val, ENerfActivation activation) {
switch (activation) {
case ENerfActivation::None: return 1.0f;
case ENerfActivation::ReLU: return val > 0.0f ? 1.0f : 0.0f;
case ENerfActivation::Logistic: { float density = tcnn::logistic(val); return density * (1 - density); };
case ENerfActivation::Exponential: return __expf(tcnn::clamp(val, -10.0f, 10.0f));
default: assert(false);
}
return 0.0f;
}
template <typename T>
__device__ vec3 network_to_rgb_derivative_vec(const T& val, ENerfActivation activation) {
return {
network_to_rgb_derivative(float(val[0]), activation),
network_to_rgb_derivative(float(val[1]), activation),
network_to_rgb_derivative(float(val[2]), activation),
};
}
__device__ float network_to_density(float val, ENerfActivation activation) {
switch (activation) {
case ENerfActivation::None: return val;
case ENerfActivation::ReLU: return val > 0.0f ? val : 0.0f;
case ENerfActivation::Logistic: return tcnn::logistic(val);
case ENerfActivation::Exponential: return __expf(val);
default: assert(false);
}
return 0.0f;
}
__device__ float network_to_density_derivative(float val, ENerfActivation activation) {
switch (activation) {
case ENerfActivation::None: return 1.0f;
case ENerfActivation::ReLU: return val > 0.0f ? 1.0f : 0.0f;
case ENerfActivation::Logistic: { float density = tcnn::logistic(val); return density * (1 - density); };
case ENerfActivation::Exponential: return __expf(tcnn::clamp(val, -15.0f, 15.0f));
default: assert(false);
}
return 0.0f;
}
template <typename T>
__device__ vec3 network_to_rgb_vec(const T& val, ENerfActivation activation) {
return {
network_to_rgb(float(val[0]), activation),
network_to_rgb(float(val[1]), activation),
network_to_rgb(float(val[2]), activation),
};
}
__device__ vec3 warp_position(const vec3& pos, const BoundingBox& aabb) {
// return {tcnn::logistic(pos.x - 0.5f), tcnn::logistic(pos.y - 0.5f), tcnn::logistic(pos.z - 0.5f)};
// return pos;
return aabb.relative_pos(pos);
}
__device__ vec3 unwarp_position(const vec3& pos, const BoundingBox& aabb) {
// return {logit(pos.x) + 0.5f, logit(pos.y) + 0.5f, logit(pos.z) + 0.5f};
// return pos;
return aabb.min + pos * aabb.diag();
}
__device__ vec3 unwarp_position_derivative(const vec3& pos, const BoundingBox& aabb) {
// return {logit(pos.x) + 0.5f, logit(pos.y) + 0.5f, logit(pos.z) + 0.5f};
// return pos;
return aabb.diag();
}
__device__ vec3 warp_position_derivative(const vec3& pos, const BoundingBox& aabb) {
return vec3(1.0f) / unwarp_position_derivative(pos, aabb);
}
__host__ __device__ vec3 warp_direction(const vec3& dir) {
return (dir + vec3(1.0f)) * 0.5f;
}
__device__ vec3 unwarp_direction(const vec3& dir) {
return dir * 2.0f - vec3(1.0f);
}
__device__ vec3 warp_direction_derivative(const vec3& dir) {
return vec3(0.5f);
}
__device__ vec3 unwarp_direction_derivative(const vec3& dir) {
return vec3(2.0f);
}
__device__ float warp_dt(float dt) {
float max_stepsize = MIN_CONE_STEPSIZE() * (1<<(NERF_CASCADES()-1));
return (dt - MIN_CONE_STEPSIZE()) / (max_stepsize - MIN_CONE_STEPSIZE());
}
__device__ float unwarp_dt(float dt) {
float max_stepsize = MIN_CONE_STEPSIZE() * (1<<(NERF_CASCADES()-1));
return dt * (max_stepsize - MIN_CONE_STEPSIZE()) + MIN_CONE_STEPSIZE();
}
__device__ uint32_t cascaded_grid_idx_at(vec3 pos, uint32_t mip) {
float mip_scale = scalbnf(1.0f, -mip);
pos -= vec3(0.5f);
pos *= mip_scale;
pos += vec3(0.5f);
ivec3 i = pos * (float)NERF_GRIDSIZE();
if (i.x < 0 || i.x >= NERF_GRIDSIZE() || i.y < 0 || i.y >= NERF_GRIDSIZE() || i.z < 0 || i.z >= NERF_GRIDSIZE()) {
return 0xFFFFFFFF;
}
return tcnn::morton3D(i.x, i.y, i.z);
}
__device__ bool density_grid_occupied_at(const vec3& pos, const uint8_t* density_grid_bitfield, uint32_t mip) {
uint32_t idx = cascaded_grid_idx_at(pos, mip);
if (idx == 0xFFFFFFFF) {
return false;
}
return density_grid_bitfield[idx/8+grid_mip_offset(mip)/8] & (1<<(idx%8));
}
__device__ float cascaded_grid_at(vec3 pos, const float* cascaded_grid, uint32_t mip) {
uint32_t idx = cascaded_grid_idx_at(pos, mip);
if (idx == 0xFFFFFFFF) {
return 0.0f;
}
return cascaded_grid[idx+grid_mip_offset(mip)];
}
__device__ float& cascaded_grid_at(vec3 pos, float* cascaded_grid, uint32_t mip) {
uint32_t idx = cascaded_grid_idx_at(pos, mip);
if (idx == 0xFFFFFFFF) {
idx = 0;
printf("WARNING: invalid cascaded grid access.");
}
return cascaded_grid[idx+grid_mip_offset(mip)];
}
__global__ void extract_srgb_with_activation(const uint32_t n_elements, const uint32_t rgb_stride, const float* __restrict__ rgbd, float* __restrict__ rgb, ENerfActivation rgb_activation, bool from_linear) {
const uint32_t i = threadIdx.x + blockIdx.x * blockDim.x;
if (i >= n_elements) return;
const uint32_t elem_idx = i / 3;
const uint32_t dim_idx = i - elem_idx * 3;
float c = network_to_rgb(rgbd[elem_idx*4 + dim_idx], rgb_activation);
if (from_linear) {
c = linear_to_srgb(c);
}
rgb[elem_idx*rgb_stride + dim_idx] = c;
}
__global__ void mark_untrained_density_grid(const uint32_t n_elements, float* __restrict__ grid_out,
const uint32_t n_training_images,
const TrainingImageMetadata* __restrict__ metadata,
const TrainingXForm* training_xforms,
bool clear_visible_voxels
) {
const uint32_t i = threadIdx.x + blockIdx.x * blockDim.x;
if (i >= n_elements) return;
uint32_t level = i / NERF_GRID_N_CELLS();
uint32_t pos_idx = i % NERF_GRID_N_CELLS();
uint32_t x = tcnn::morton3D_invert(pos_idx>>0);
uint32_t y = tcnn::morton3D_invert(pos_idx>>1);
uint32_t z = tcnn::morton3D_invert(pos_idx>>2);
float voxel_size = scalbnf(1.0f / NERF_GRIDSIZE(), level);
vec3 pos = (vec3{(float)x, (float)y, (float)z} / (float)NERF_GRIDSIZE() - vec3(0.5f)) * scalbnf(1.0f, level) + vec3(0.5f);
vec3 corners[8] = {
pos + vec3{0.0f, 0.0f, 0.0f },
pos + vec3{voxel_size, 0.0f, 0.0f },
pos + vec3{0.0f, voxel_size, 0.0f },
pos + vec3{voxel_size, voxel_size, 0.0f },
pos + vec3{0.0f, 0.0f, voxel_size},
pos + vec3{voxel_size, 0.0f, voxel_size},
pos + vec3{0.0f, voxel_size, voxel_size},
pos + vec3{voxel_size, voxel_size, voxel_size},
};
// Number of training views that need to see a voxel cell
// at minimum for that cell to be marked trainable.
// Floaters can be reduced by increasing this value to 2,
// but at the cost of certain reconstruction artifacts.
const uint32_t min_count = 1;
uint32_t count = 0;
for (uint32_t j = 0; j < n_training_images && count < min_count; ++j) {
const auto& xform = training_xforms[j].start;
const auto& m = metadata[j];
if (m.lens.mode == ELensMode::FTheta || m.lens.mode == ELensMode::LatLong || m.lens.mode == ELensMode::Equirectangular) {
// FTheta lenses don't have a forward mapping, so are assumed seeing everything. Latlong and equirect lenses
// by definition see everything.
++count;
continue;
}
for (uint32_t k = 0; k < 8; ++k) {
// Only consider voxel corners in front of the camera
vec3 dir = normalize(corners[k] - xform[3]);
if (dot(dir, xform[2]) < 1e-4f) {
continue;
}
// Check if voxel corner projects onto the image plane, i.e. uv must be in (0, 1)^2
vec2 uv = pos_to_uv(corners[k], m.resolution, m.focal_length, xform, m.principal_point, vec3(0.0f), {}, m.lens);
// `pos_to_uv` is _not_ injective in the presence of lens distortion (which breaks down outside of the image plane).
// So we need to check whether the produced uv location generates a ray that matches the ray that we started with.
Ray ray = uv_to_ray(0.0f, uv, m.resolution, m.focal_length, xform, m.principal_point, vec3(0.0f), 0.0f, 1.0f, 0.0f, {}, {}, m.lens);
if (distance(normalize(ray.d), dir) < 1e-3f && uv.x > 0.0f && uv.y > 0.0f && uv.x < 1.0f && uv.y < 1.0f) {
++count;
break;
}
}
}
if (clear_visible_voxels || (grid_out[i] < 0) != (count < min_count)) {
grid_out[i] = (count >= min_count) ? 0.f : -1.f;
}
}
__global__ void generate_grid_samples_nerf_uniform(ivec3 res_3d, const uint32_t step, BoundingBox render_aabb, mat3 render_aabb_to_local, BoundingBox train_aabb, NerfPosition* __restrict__ out) {
// check grid_in for negative values -> must be negative on output
uint32_t x = threadIdx.x + blockIdx.x * blockDim.x;
uint32_t y = threadIdx.y + blockIdx.y * blockDim.y;
uint32_t z = threadIdx.z + blockIdx.z * blockDim.z;
if (x >= res_3d.x || y >= res_3d.y || z >= res_3d.z) {
return;
}
uint32_t i = x + y * res_3d.x + z * res_3d.x * res_3d.y;
vec3 pos = vec3{(float)x, (float)y, (float)z} / vec3(res_3d - ivec3(1));
pos = transpose(render_aabb_to_local) * (pos * (render_aabb.max - render_aabb.min) + render_aabb.min);
out[i] = { warp_position(pos, train_aabb), warp_dt(MIN_CONE_STEPSIZE()) };
}
// generate samples for uniform grid including constant ray direction
__global__ void generate_grid_samples_nerf_uniform_dir(ivec3 res_3d, const uint32_t step, BoundingBox render_aabb, mat3 render_aabb_to_local, BoundingBox train_aabb, vec3 ray_dir, PitchedPtr<NerfCoordinate> network_input, const float* extra_dims, bool voxel_centers) {
// check grid_in for negative values -> must be negative on output
uint32_t x = threadIdx.x + blockIdx.x * blockDim.x;
uint32_t y = threadIdx.y + blockIdx.y * blockDim.y;
uint32_t z = threadIdx.z + blockIdx.z * blockDim.z;
if (x >= res_3d.x || y >= res_3d.y || z >= res_3d.z) {
return;
}
uint32_t i = x+ y*res_3d.x + z*res_3d.x*res_3d.y;
vec3 pos;
if (voxel_centers) {
pos = vec3{(float)x + 0.5f, (float)y + 0.5f, (float)z + 0.5f} / vec3(res_3d);
} else {
pos = vec3{(float)x, (float)y, (float)z} / vec3(res_3d - ivec3(1));
}
pos = transpose(render_aabb_to_local) * (pos * (render_aabb.max - render_aabb.min) + render_aabb.min);
network_input(i)->set_with_optional_extra_dims(warp_position(pos, train_aabb), warp_direction(ray_dir), warp_dt(MIN_CONE_STEPSIZE()), extra_dims, network_input.stride_in_bytes);
}
inline __device__ uint32_t mip_from_pos(const vec3& pos, uint32_t max_cascade = NERF_CASCADES()-1) {
int exponent;
float maxval = compMax(abs(pos - vec3(0.5f)));
frexpf(maxval, &exponent);
return (uint32_t)tcnn::clamp(exponent+1, 0, (int)max_cascade);
}
inline __device__ uint32_t mip_from_dt(float dt, const vec3& pos, uint32_t max_cascade = NERF_CASCADES()-1) {
uint32_t mip = mip_from_pos(pos, max_cascade);
dt *= 2 * NERF_GRIDSIZE();
if (dt < 1.0f) {
return mip;
}
int exponent;
frexpf(dt, &exponent);
return (uint32_t)tcnn::clamp((int)mip, exponent, (int)max_cascade);
}
__global__ void generate_grid_samples_nerf_nonuniform(const uint32_t n_elements, default_rng_t rng, const uint32_t step, BoundingBox aabb, const float* __restrict__ grid_in, NerfPosition* __restrict__ out, uint32_t* __restrict__ indices, uint32_t n_cascades, float thresh) {
const uint32_t i = threadIdx.x + blockIdx.x * blockDim.x;
if (i >= n_elements) return;
// 1 random number to select the level, 3 to select the position.
rng.advance(i*4);
uint32_t level = (uint32_t)(random_val(rng) * n_cascades) % n_cascades;
// Select grid cell that has density
uint32_t idx;
for (uint32_t j = 0; j < 10; ++j) {
idx = ((i+step*n_elements) * 56924617 + j * 19349663 + 96925573) % NERF_GRID_N_CELLS();
idx += level * NERF_GRID_N_CELLS();
if (grid_in[idx] > thresh) {
break;
}
}
// Random position within that cellq
uint32_t pos_idx = idx % NERF_GRID_N_CELLS();
uint32_t x = tcnn::morton3D_invert(pos_idx>>0);
uint32_t y = tcnn::morton3D_invert(pos_idx>>1);
uint32_t z = tcnn::morton3D_invert(pos_idx>>2);
vec3 pos = ((vec3{(float)x, (float)y, (float)z} + random_val_3d(rng)) / (float)NERF_GRIDSIZE() - vec3(0.5f)) * scalbnf(1.0f, level) + vec3(0.5f);
out[i] = { warp_position(pos, aabb), warp_dt(MIN_CONE_STEPSIZE()) };
indices[i] = idx;
}
__global__ void splat_grid_samples_nerf_max_nearest_neighbor(const uint32_t n_elements, const uint32_t* __restrict__ indices, const tcnn::network_precision_t* network_output, float* __restrict__ grid_out, ENerfActivation rgb_activation, ENerfActivation density_activation) {
const uint32_t i = threadIdx.x + blockIdx.x * blockDim.x;
if (i >= n_elements) return;
uint32_t local_idx = indices[i];
// Current setting: optical thickness of the smallest possible stepsize.
// Uncomment for: optical thickness of the ~expected step size when the observer is in the middle of the scene
uint32_t level = 0;//local_idx / NERF_GRID_N_CELLS();
float mlp = network_to_density(float(network_output[i]), density_activation);
float optical_thickness = mlp * scalbnf(MIN_CONE_STEPSIZE(), level);
// Positive floats are monotonically ordered when their bit pattern is interpretes as uint.
// uint atomicMax is thus perfectly acceptable.
atomicMax((uint32_t*)&grid_out[local_idx], __float_as_uint(optical_thickness));
}
__global__ void grid_samples_half_to_float(const uint32_t n_elements, BoundingBox aabb, float* dst, const tcnn::network_precision_t* network_output, ENerfActivation density_activation, const NerfPosition* __restrict__ coords_in, const float* __restrict__ grid_in, uint32_t max_cascade) {
const uint32_t i = threadIdx.x + blockIdx.x * blockDim.x;
if (i >= n_elements) return;
// let's interpolate for marching cubes based on the raw MLP output, not the density (exponentiated) version
//float mlp = network_to_density(float(network_output[i * padded_output_width]), density_activation);
float mlp = float(network_output[i]);
if (grid_in) {
vec3 pos = unwarp_position(coords_in[i].p, aabb);
float grid_density = cascaded_grid_at(pos, grid_in, mip_from_pos(pos, max_cascade));
if (grid_density < NERF_MIN_OPTICAL_THICKNESS()) {
mlp = -10000.0f;
}
}
dst[i] = mlp;
}
__global__ void ema_grid_samples_nerf(const uint32_t n_elements,
float decay,
const uint32_t count,
float* __restrict__ grid_out,
const float* __restrict__ grid_in
) {
const uint32_t i = threadIdx.x + blockIdx.x * blockDim.x;
if (i >= n_elements) return;
float importance = grid_in[i];
// float ema_debias_old = 1 - (float)powf(decay, count);
// float ema_debias_new = 1 - (float)powf(decay, count+1);
// float filtered_val = ((grid_out[i] * decay * ema_debias_old + importance * (1 - decay)) / ema_debias_new);
// grid_out[i] = filtered_val;
// Maximum instead of EMA allows capture of very thin features.
// Basically, we want the grid cell turned on as soon as _ANYTHING_ visible is in there.
float prev_val = grid_out[i];
float val = (prev_val<0.f) ? prev_val : fmaxf(prev_val * decay, importance);
grid_out[i] = val;
}
__global__ void decay_sharpness_grid_nerf(const uint32_t n_elements, float decay, float* __restrict__ grid) {
const uint32_t i = threadIdx.x + blockIdx.x * blockDim.x;
if (i >= n_elements) return;
grid[i] *= decay;
}
__global__ void grid_to_bitfield(
const uint32_t n_elements,
const uint32_t n_nonzero_elements,
const float* __restrict__ grid,
uint8_t* __restrict__ grid_bitfield,
const float* __restrict__ mean_density_ptr
) {
const uint32_t i = threadIdx.x + blockIdx.x * blockDim.x;
if (i >= n_elements) return;
if (i >= n_nonzero_elements) {
grid_bitfield[i] = 0;
return;
}
uint8_t bits = 0;
float thresh = std::min(NERF_MIN_OPTICAL_THICKNESS(), *mean_density_ptr);
NGP_PRAGMA_UNROLL
for (uint8_t j = 0; j < 8; ++j) {
bits |= grid[i*8+j] > thresh ? ((uint8_t)1 << j) : 0;
}
grid_bitfield[i] = bits;
}
__global__ void bitfield_max_pool(const uint32_t n_elements,
const uint8_t* __restrict__ prev_level,
uint8_t* __restrict__ next_level
) {
const uint32_t i = threadIdx.x + blockIdx.x * blockDim.x;
if (i >= n_elements) return;
uint8_t bits = 0;
NGP_PRAGMA_UNROLL
for (uint8_t j = 0; j < 8; ++j) {
// If any bit is set in the previous level, set this
// level's bit. (Max pooling.)
bits |= prev_level[i*8+j] > 0 ? ((uint8_t)1 << j) : 0;
}
uint32_t x = tcnn::morton3D_invert(i>>0) + NERF_GRIDSIZE()/8;
uint32_t y = tcnn::morton3D_invert(i>>1) + NERF_GRIDSIZE()/8;
uint32_t z = tcnn::morton3D_invert(i>>2) + NERF_GRIDSIZE()/8;
next_level[tcnn::morton3D(x, y, z)] |= bits;
}
template <bool MIP_FROM_DT=false>
__device__ float if_unoccupied_advance_to_next_occupied_voxel(
float t,
float cone_angle,
const Ray& ray,
const vec3& idir,
const uint8_t* __restrict__ density_grid,
uint32_t min_mip,
uint32_t max_mip,
BoundingBox aabb,
mat3 aabb_to_local = mat3(1.0f)
) {
while (true) {
vec3 pos = ray(t);
if (t >= MAX_DEPTH() || !aabb.contains(aabb_to_local * pos)) {
return MAX_DEPTH();
}
uint32_t mip = tcnn::clamp(MIP_FROM_DT ? mip_from_dt(calc_dt(t, cone_angle), pos) : mip_from_pos(pos), min_mip, max_mip);
if (!density_grid || density_grid_occupied_at(pos, density_grid, mip)) {
return t;
}
// Find largest empty voxel surrounding us, such that we can advance as far as possible in the next step.
// Other places that do voxel stepping don't need this, because they don't rely on thread coherence as
// much as this one here.
while (mip < max_mip && !density_grid_occupied_at(pos, density_grid, mip+1)) {
++mip;
}
t = advance_to_next_voxel(t, cone_angle, pos, ray.d, idir, mip);
}
}
__device__ void advance_pos_nerf(
NerfPayload& payload,
const BoundingBox& render_aabb,
const mat3& render_aabb_to_local,
const vec3& camera_fwd,
const vec2& focal_length,
uint32_t sample_index,
const uint8_t* __restrict__ density_grid,
uint32_t min_mip,
uint32_t max_mip,
float cone_angle_constant
) {
if (!payload.alive) {
return;
}
vec3 origin = payload.origin;
vec3 dir = payload.dir;
vec3 idir = vec3(1.0f) / dir;
float cone_angle = calc_cone_angle(dot(dir, camera_fwd), focal_length, cone_angle_constant);
float t = advance_n_steps(payload.t, cone_angle, ld_random_val(sample_index, payload.idx * 786433));
t = if_unoccupied_advance_to_next_occupied_voxel(t, cone_angle, {origin, dir}, idir, density_grid, min_mip, max_mip, render_aabb, render_aabb_to_local);
if (t >= MAX_DEPTH()) {
payload.alive = false;
} else {
payload.t = t;
}
}
__global__ void advance_pos_nerf_kernel(
const uint32_t n_elements,
BoundingBox render_aabb,
mat3 render_aabb_to_local,
vec3 camera_fwd,
vec2 focal_length,
uint32_t sample_index,
NerfPayload* __restrict__ payloads,
const uint8_t* __restrict__ density_grid,
uint32_t min_mip,
uint32_t max_mip,
float cone_angle_constant
) {
const uint32_t i = threadIdx.x + blockIdx.x * blockDim.x;
if (i >= n_elements) return;
advance_pos_nerf(payloads[i], render_aabb, render_aabb_to_local, camera_fwd, focal_length, sample_index, density_grid, min_mip, max_mip, cone_angle_constant);
}
__global__ void generate_nerf_network_inputs_from_positions(const uint32_t n_elements, BoundingBox aabb, const vec3* __restrict__ pos, PitchedPtr<NerfCoordinate> network_input, const float* extra_dims) {
const uint32_t i = threadIdx.x + blockIdx.x * blockDim.x;
if (i >= n_elements) return;
vec3 dir = normalize(pos[i] - vec3(0.5f)); // choose outward pointing directions, for want of a better choice
network_input(i)->set_with_optional_extra_dims(warp_position(pos[i], aabb), warp_direction(dir), warp_dt(MIN_CONE_STEPSIZE()), extra_dims, network_input.stride_in_bytes);
}
__global__ void generate_nerf_network_inputs_at_current_position(const uint32_t n_elements, BoundingBox aabb, const NerfPayload* __restrict__ payloads, PitchedPtr<NerfCoordinate> network_input, const float* extra_dims) {
const uint32_t i = threadIdx.x + blockIdx.x * blockDim.x;
if (i >= n_elements) return;
vec3 dir = payloads[i].dir;
network_input(i)->set_with_optional_extra_dims(warp_position(payloads[i].origin + dir * payloads[i].t, aabb), warp_direction(dir), warp_dt(MIN_CONE_STEPSIZE()), extra_dims, network_input.stride_in_bytes);
}
__device__ vec4 compute_nerf_rgba(const vec4& network_output, ENerfActivation rgb_activation, ENerfActivation density_activation, float depth, bool density_as_alpha = false) {
vec4 rgba = network_output;
float density = network_to_density(rgba.a, density_activation);
float alpha = 1.f;
if (density_as_alpha) {
rgba.a = density;
} else {
rgba.a = alpha = tcnn::clamp(1.f - __expf(-density * depth), 0.0f, 1.0f);
}
rgba.rgb = network_to_rgb_vec(rgba.rgb, rgb_activation) * alpha;
return rgba;
}
__global__ void compute_nerf_rgba_kernel(const uint32_t n_elements, vec4* network_output, ENerfActivation rgb_activation, ENerfActivation density_activation, float depth, bool density_as_alpha = false) {
const uint32_t i = threadIdx.x + blockIdx.x * blockDim.x;
if (i >= n_elements) return;
network_output[i] = compute_nerf_rgba(network_output[i], rgb_activation, density_activation, depth, density_as_alpha);
}
__global__ void generate_next_nerf_network_inputs(
const uint32_t n_elements,
BoundingBox render_aabb,
mat3 render_aabb_to_local,
BoundingBox train_aabb,
vec2 focal_length,
vec3 camera_fwd,
NerfPayload* __restrict__ payloads,
PitchedPtr<NerfCoordinate> network_input,
uint32_t n_steps,
const uint8_t* __restrict__ density_grid,
uint32_t min_mip,
uint32_t max_mip,
float cone_angle_constant,
const float* extra_dims
) {
const uint32_t i = threadIdx.x + blockIdx.x * blockDim.x;
if (i >= n_elements) return;
NerfPayload& payload = payloads[i];
if (!payload.alive) {
return;
}
vec3 origin = payload.origin;
vec3 dir = payload.dir;
vec3 idir = vec3(1.0f) / dir;
float cone_angle = calc_cone_angle(dot(dir, camera_fwd), focal_length, cone_angle_constant);
float t = payload.t;
for (uint32_t j = 0; j < n_steps; ++j) {
t = if_unoccupied_advance_to_next_occupied_voxel(t, cone_angle, {origin, dir}, idir, density_grid, min_mip, max_mip, render_aabb, render_aabb_to_local);
if (t >= MAX_DEPTH()) {
payload.n_steps = j;
return;
}
float dt = calc_dt(t, cone_angle);
network_input(i + j * n_elements)->set_with_optional_extra_dims(warp_position(origin + dir * t, train_aabb), warp_direction(dir), warp_dt(dt), extra_dims, network_input.stride_in_bytes); // XXXCONE
t += dt;
}
payload.t = t;
payload.n_steps = n_steps;
}
__global__ void composite_kernel_nerf(
const uint32_t n_elements,
const uint32_t stride,
const uint32_t current_step,
BoundingBox aabb,
float glow_y_cutoff,
int glow_mode,
mat4x3 camera_matrix,
vec2 focal_length,
float depth_scale,
vec4* __restrict__ rgba,
float* __restrict__ depth,
NerfPayload* payloads,
PitchedPtr<NerfCoordinate> network_input,
const tcnn::network_precision_t* __restrict__ network_output,
uint32_t padded_output_width,
uint32_t n_steps,
ERenderMode render_mode,
const uint8_t* __restrict__ density_grid,
ENerfActivation rgb_activation,
ENerfActivation density_activation,
int show_accel,
float min_transmittance
) {
const uint32_t i = threadIdx.x + blockIdx.x * blockDim.x;
if (i >= n_elements) return;
NerfPayload& payload = payloads[i];
if (!payload.alive) {
return;
}
vec4 local_rgba = rgba[i];
float local_depth = depth[i];
vec3 origin = payload.origin;
vec3 cam_fwd = camera_matrix[2];
// Composite in the last n steps
uint32_t actual_n_steps = payload.n_steps;
uint32_t j = 0;
for (; j < actual_n_steps; ++j) {
tcnn::vector_t<tcnn::network_precision_t, 4> local_network_output;
local_network_output[0] = network_output[i + j * n_elements + 0 * stride];
local_network_output[1] = network_output[i + j * n_elements + 1 * stride];
local_network_output[2] = network_output[i + j * n_elements + 2 * stride];
local_network_output[3] = network_output[i + j * n_elements + 3 * stride];
const NerfCoordinate* input = network_input(i + j * n_elements);
vec3 warped_pos = input->pos.p;
vec3 pos = unwarp_position(warped_pos, aabb);
float T = 1.f - local_rgba.a;
float dt = unwarp_dt(input->dt);
float alpha = 1.f - __expf(-network_to_density(float(local_network_output[3]), density_activation) * dt);
if (show_accel >= 0) {
alpha = 1.f;
}
float weight = alpha * T;
vec3 rgb = network_to_rgb_vec(local_network_output, rgb_activation);
if (glow_mode) { // random grid visualizations ftw!
#if 0
if (0) { // extremely startrek edition
float glow_y = (pos.y - (glow_y_cutoff - 0.5f)) * 2.f;
if (glow_y>1.f) glow_y=max(0.f,21.f-glow_y*20.f);
if (glow_y>0.f) {
float line;
line =max(0.f,cosf(pos.y*2.f*3.141592653589793f * 16.f)-0.95f);
line+=max(0.f,cosf(pos.x*2.f*3.141592653589793f * 16.f)-0.95f);
line+=max(0.f,cosf(pos.z*2.f*3.141592653589793f * 16.f)-0.95f);
line+=max(0.f,cosf(pos.y*4.f*3.141592653589793f * 16.f)-0.975f);
line+=max(0.f,cosf(pos.x*4.f*3.141592653589793f * 16.f)-0.975f);
line+=max(0.f,cosf(pos.z*4.f*3.141592653589793f * 16.f)-0.975f);
glow_y=glow_y*glow_y*0.5f + glow_y*line*25.f;
rgb.y+=glow_y;
rgb.z+=glow_y*0.5f;
rgb.x+=glow_y*0.25f;
}
}
#endif
float glow = 0.f;
bool green_grid = glow_mode & 1;
bool green_cutline = glow_mode & 2;
bool mask_to_alpha = glow_mode & 4;
// less used?
bool radial_mode = glow_mode & 8;
bool grid_mode = glow_mode & 16; // makes object rgb go black!
{
float dist;
if (radial_mode) {
dist = distance(pos, camera_matrix[3]);
dist = min(dist, (4.5f - pos.y) * 0.333f);
} else {
dist = pos.y;
}
if (grid_mode) {
glow = 1.f / max(1.f, dist);
} else {
float y = glow_y_cutoff - dist; // - (ii*0.005f);
float mask = 0.f;
if (y > 0.f) {
y *= 80.f;
mask = min(1.f, y);
//if (mask_mode) {
// rgb.x=rgb.y=rgb.z=mask; // mask mode
//} else
{
if (green_cutline) {
glow += max(0.f, 1.f - abs(1.f -y)) * 4.f;
}
if (y>1.f) {
y = 1.f - (y - 1.f) * 0.05f;
}
if (green_grid) {
glow += max(0.f, y / max(1.f, dist));
}
}
}
if (mask_to_alpha) {
weight *= mask;
}