-
Notifications
You must be signed in to change notification settings - Fork 35
/
tiny_bvh.h
5906 lines (5651 loc) · 249 KB
/
tiny_bvh.h
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
/*
The MIT License (MIT)
Copyright (c) 2024, Jacco Bikker / Breda University of Applied Sciences.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
// How to use:
//
// Use this in *one* .c or .cpp
// #define TINYBVH_IMPLEMENTATION
// #include "tiny_bvh.h"
// Instantiate a BVH and build it for a list of triangles:
// BVH bvh;
// bvh.Build( (bvhvec4*)myVerts, numTriangles );
// Ray ray( bvhvec3( 0, 0, 0 ), bvhvec3( 0, 0, 1 ), 1e30f );
// bvh.Intersect( ray );
// After this, intersection information is in ray.hit.
// tinybvh can use custom vector types by defining TINYBVH_USE_CUSTOM_VECTOR_TYPES once before inclusion.
// To define custom vector types create a tinybvh namespace with the appropriate using directives, e.g.:
// namespace tinybvh
// {
// using bvhint2 = math::int2;
// using bvhint3 = math::int3;
// using bvhuint2 = math::uint2;
// using bvhvec2 = math::float2;
// using bvhvec3 = math::float3;
// using bvhvec4 = math::float4;
// using bvhdbl3 = math::double3;
// }
//
// #define TINYBVH_USE_CUSTOM_VECTOR_TYPES
// #include <tiny_bvh.h>
// See tiny_bvh_test.cpp for basic usage. In short:
// instantiate a BVH: tinybvh::BVH bvh;
// build it: bvh.Build( (tinybvh::bvhvec4*)triangleData, TRIANGLE_COUNT );
// ..where triangleData is an array of four-component float vectors:
// - For a single triangle, provide 3 vertices,
// - For each vertex provide x, y and z.
// The fourth float in each vertex is a dummy value and exists purely for
// a more efficient layout of the data in memory.
// More information about the BVH data structure:
// https://jacco.ompf2.com/2022/04/13/how-to-build-a-bvh-part-1-basics
// Further references: See README.md
// Author and contributors:
// Jacco Bikker: BVH code and examples
// Eddy L O Jansson: g++ / clang support
// Aras Pranckevičius: non-Intel architecture support
// Jefferson Amstutz: CMake support
// Christian Oliveros: WASM / EMSCRIPTEN support
// Thierry Cantenot: user-defined alloc & free
// David Peicho: slices & Rust bindings, API advice
// Aytek Aman: C++11 threading implementation
#ifndef TINY_BVH_H_
#define TINY_BVH_H_
// Run-time checks; disabled by default.
// #define PARANOID
// Binned BVH building: bin count.
#define BVHBINS 8
#define HQBVHBINS 32
#define AVXBINS 8 // must stay at 8.
// SAH BVH building: Heuristic parameters
// CPU builds: C_INT = 1, C_TRAV = 1 seems optimal.
#define C_INT 1
#define C_TRAV 1
// SBVH: "Unsplitting"
#define SBVH_UNSPLITTING
// 'Infinity' values
#define BVH_FAR 1e30f // actual valid ieee range: 3.40282347E+38
#define BVH_DBL_FAR 1e300 // actual valid ieee range: 1.797693134862315E+308
// Features
#define DOUBLE_PRECISION_SUPPORT
//#define TINYBVH_USE_CUSTOM_VECTOR_TYPES
// CWBVH triangle format: doesn't seem to help on GPU?
// #define CWBVH_COMPRESSED_TRIS
// BVH4 triangle format
// #define BVH4_GPU_COMPRESSED_TRIS
// We'll use this whenever a layout has no specialized shadow ray query.
#define FALLBACK_SHADOW_QUERY( s ) { Ray r = s; float d = s.hit.t; Intersect( r ); return r.hit.t < d; }
// include fast AVX BVH builder
#if defined(__x86_64__) || defined(_M_X64) || defined(__wasm_simd128__) || defined(__wasm_relaxed_simd__)
#define BVH_USEAVX
#include "immintrin.h" // for __m128 and __m256
#elif defined(__aarch64__) || defined(_M_ARM64)
#define BVH_USENEON
#include "arm_neon.h"
#endif
// library version
#define TINY_BVH_VERSION_MAJOR 1
#define TINY_BVH_VERSION_MINOR 2
#define TINY_BVH_VERSION_SUB 1
// ============================================================================
//
// P R E L I M I N A R I E S
//
// ============================================================================
// needful includes
#ifdef _MSC_VER // Visual Studio / C11
#include <malloc.h> // for alloc/free
#include <stdio.h> // for fprintf
#include <math.h> // for sqrtf, fabs
#include <string.h> // for memset
#include <stdlib.h> // for exit(1)
#else // Emscripten / gcc / clang
#include <cstdlib>
#include <cstdio>
#include <cmath>
#include <cstring>
#endif
#include <cstdint>
// aligned memory allocation
// note: formally size needs to be a multiple of 'alignment'. See:
// https://en.cppreference.com/w/c/memory/aligned_alloc
// EMSCRIPTEN enforces this.
// Copy of the same construct in tinyocl, different namespace.
namespace tinybvh {
inline size_t make_multiple_64( size_t x ) { return (x + 63) & ~0x3f; }
}
#ifdef _MSC_VER // Visual Studio / C11
#define ALIGNED( x ) __declspec( align( x ) )
namespace tinybvh {
inline void* malloc64( size_t size, void* = nullptr )
{
return size == 0 ? 0 : _aligned_malloc( make_multiple_64( size ), 64 );
}
inline void free64( void* ptr, void* = nullptr ) { _aligned_free( ptr ); }
}
#else // EMSCRIPTEN / gcc / clang
#define ALIGNED( x ) __attribute__( ( aligned( x ) ) )
#if defined(__x86_64__) || defined(_M_X64) || defined(__wasm_simd128__) || defined(__wasm_relaxed_simd__)
#include <xmmintrin.h>
namespace tinybvh {
inline void* malloc64( size_t size, void* = nullptr )
{
return size == 0 ? 0 : _mm_malloc( make_multiple_64( size ), 64 );
}
inline void free64( void* ptr, void* = nullptr ) { _mm_free( ptr ); }
}
#else
namespace tinybvh {
inline void* malloc64( size_t size, void* = nullptr )
{
return size == 0 ? 0 : aligned_alloc( 64, make_multiple_64( size ) );
}
inline void free64( void* ptr, void* = nullptr ) { free( ptr ); }
}
#endif
#endif
#ifdef _MSC_VER
#define __FORCEINLINE __forceinline
#else
#define __FORCEINLINE __attribute__((always_inline)) inline
#endif
namespace tinybvh {
#ifdef _MSC_VER
// Suppress a warning caused by the union of x,y,.. and cell[..] in vectors.
// We need this union to address vector components either by name or by index.
// The warning is re-enabled right after the definition of the data types.
#pragma warning ( push )
#pragma warning ( disable: 4201 /* nameless struct / union */ )
#endif
#ifndef TINYBVH_USE_CUSTOM_VECTOR_TYPES
struct bvhvec3;
struct ALIGNED( 16 ) bvhvec4
{
// vector naming is designed to not cause any name clashes.
bvhvec4() = default;
bvhvec4( const float a, const float b, const float c, const float d ) : x( a ), y( b ), z( c ), w( d ) {}
bvhvec4( const float a ) : x( a ), y( a ), z( a ), w( a ) {}
bvhvec4( const bvhvec3 & a );
bvhvec4( const bvhvec3 & a, float b );
float& operator [] ( const int32_t i ) { return cell[i]; }
union { struct { float x, y, z, w; }; float cell[4]; };
};
struct ALIGNED( 8 ) bvhvec2
{
bvhvec2() = default;
bvhvec2( const float a, const float b ) : x( a ), y( b ) {}
bvhvec2( const float a ) : x( a ), y( a ) {}
bvhvec2( const bvhvec4 a ) : x( a.x ), y( a.y ) {}
float& operator [] ( const int32_t i ) { return cell[i]; }
union { struct { float x, y; }; float cell[2]; };
};
struct bvhvec3
{
bvhvec3() = default;
bvhvec3( const float a, const float b, const float c ) : x( a ), y( b ), z( c ) {}
bvhvec3( const float a ) : x( a ), y( a ), z( a ) {}
bvhvec3( const bvhvec4 a ) : x( a.x ), y( a.y ), z( a.z ) {}
float halfArea() { return x < -BVH_FAR ? 0 : (x * y + y * z + z * x); } // for SAH calculations
float& operator [] ( const int32_t i ) { return cell[i]; }
union { struct { float x, y, z; }; float cell[3]; };
};
struct bvhint3
{
bvhint3() = default;
bvhint3( const int32_t a, const int32_t b, const int32_t c ) : x( a ), y( b ), z( c ) {}
bvhint3( const int32_t a ) : x( a ), y( a ), z( a ) {}
bvhint3( const bvhvec3& a ) { x = (int32_t)a.x, y = (int32_t)a.y, z = (int32_t)a.z; }
int32_t& operator [] ( const int32_t i ) { return cell[i]; }
union { struct { int32_t x, y, z; }; int32_t cell[3]; };
};
struct bvhint2
{
bvhint2() = default;
bvhint2( const int32_t a, const int32_t b ) : x( a ), y( b ) {}
bvhint2( const int32_t a ) : x( a ), y( a ) {}
int32_t x, y;
};
struct bvhuint2
{
bvhuint2() = default;
bvhuint2( const uint32_t a, const uint32_t b ) : x( a ), y( b ) {}
bvhuint2( const uint32_t a ) : x( a ), y( a ) {}
uint32_t x, y;
};
#endif // TINYBVH_USE_CUSTOM_VECTOR_TYPES
struct ALIGNED( 32 ) bvhaabb
{
bvhvec3 minBounds; uint32_t dummy1;
bvhvec3 maxBounds; uint32_t dummy2;
};
struct bvhvec4slice
{
bvhvec4slice() = default;
bvhvec4slice( const bvhvec4* data, uint32_t count, uint32_t stride = sizeof( bvhvec4 ) );
operator bool() const { return !!data; }
const bvhvec4& operator [] ( size_t i ) const;
const int8_t* data = nullptr;
uint32_t count, stride;
};
#ifdef _MSC_VER
#pragma warning ( pop )
#endif
// Math operations.
// Note: Since this header file is expected to be included in a source file
// of a separate project, the static keyword doesn't provide sufficient
// isolation; hence the tinybvh_ prefix.
inline float tinybvh_safercp( const float x ) { return x > 1e-12f ? (1.0f / x) : (x < -1e-12f ? (1.0f / x) : BVH_FAR); }
inline bvhvec3 tinybvh_safercp( const bvhvec3 a ) { return bvhvec3( tinybvh_safercp( a.x ), tinybvh_safercp( a.y ), tinybvh_safercp( a.z ) ); }
static inline float tinybvh_min( const float a, const float b ) { return a < b ? a : b; }
static inline float tinybvh_max( const float a, const float b ) { return a > b ? a : b; }
static inline double tinybvh_min( const double a, const double b ) { return a < b ? a : b; }
static inline double tinybvh_max( const double a, const double b ) { return a > b ? a : b; }
static inline int32_t tinybvh_min( const int32_t a, const int32_t b ) { return a < b ? a : b; }
static inline int32_t tinybvh_max( const int32_t a, const int32_t b ) { return a > b ? a : b; }
static inline uint32_t tinybvh_min( const uint32_t a, const uint32_t b ) { return a < b ? a : b; }
static inline uint32_t tinybvh_max( const uint32_t a, const uint32_t b ) { return a > b ? a : b; }
static inline bvhvec3 tinybvh_min( const bvhvec3& a, const bvhvec3& b ) { return bvhvec3( tinybvh_min( a.x, b.x ), tinybvh_min( a.y, b.y ), tinybvh_min( a.z, b.z ) ); }
static inline bvhvec4 tinybvh_min( const bvhvec4& a, const bvhvec4& b ) { return bvhvec4( tinybvh_min( a.x, b.x ), tinybvh_min( a.y, b.y ), tinybvh_min( a.z, b.z ), tinybvh_min( a.w, b.w ) ); }
static inline bvhvec3 tinybvh_max( const bvhvec3& a, const bvhvec3& b ) { return bvhvec3( tinybvh_max( a.x, b.x ), tinybvh_max( a.y, b.y ), tinybvh_max( a.z, b.z ) ); }
static inline bvhvec4 tinybvh_max( const bvhvec4& a, const bvhvec4& b ) { return bvhvec4( tinybvh_max( a.x, b.x ), tinybvh_max( a.y, b.y ), tinybvh_max( a.z, b.z ), tinybvh_max( a.w, b.w ) ); }
static inline float tinybvh_clamp( const float x, const float a, const float b ) { return x < a ? a : (x > b ? b : x); }
static inline int32_t tinybvh_clamp( const int32_t x, const int32_t a, const int32_t b ) { return x < a ? a : (x > b ? b : x); }
template <class T> inline static void tinybvh_swap( T& a, T& b ) { T t = a; a = b; b = t; }
// Operator overloads.
// Only a minimal set is provided.
#ifndef TINYBVH_USE_CUSTOM_VECTOR_TYPES
inline bvhvec2 operator-( const bvhvec2& a ) { return bvhvec2( -a.x, -a.y ); }
inline bvhvec3 operator-( const bvhvec3& a ) { return bvhvec3( -a.x, -a.y, -a.z ); }
inline bvhvec4 operator-( const bvhvec4& a ) { return bvhvec4( -a.x, -a.y, -a.z, -a.w ); }
inline bvhvec2 operator+( const bvhvec2& a, const bvhvec2& b ) { return bvhvec2( a.x + b.x, a.y + b.y ); }
inline bvhvec3 operator+( const bvhvec3& a, const bvhvec3& b ) { return bvhvec3( a.x + b.x, a.y + b.y, a.z + b.z ); }
inline bvhvec4 operator+( const bvhvec4& a, const bvhvec4& b ) { return bvhvec4( a.x + b.x, a.y + b.y, a.z + b.z, a.w + b.w ); }
inline bvhvec4 operator+( const bvhvec4& a, const bvhvec3& b ) { return bvhvec4( a.x + b.x, a.y + b.y, a.z + b.z, a.w ); }
inline bvhvec2 operator-( const bvhvec2& a, const bvhvec2& b ) { return bvhvec2( a.x - b.x, a.y - b.y ); }
inline bvhvec3 operator-( const bvhvec3& a, const bvhvec3& b ) { return bvhvec3( a.x - b.x, a.y - b.y, a.z - b.z ); }
inline bvhvec4 operator-( const bvhvec4& a, const bvhvec4& b ) { return bvhvec4( a.x - b.x, a.y - b.y, a.z - b.z, a.w - b.w ); }
inline void operator+=( bvhvec2& a, const bvhvec2& b ) { a.x += b.x; a.y += b.y; }
inline void operator+=( bvhvec3& a, const bvhvec3& b ) { a.x += b.x; a.y += b.y; a.z += b.z; }
inline void operator+=( bvhvec4& a, const bvhvec4& b ) { a.x += b.x; a.y += b.y; a.z += b.z; a.w += b.w; }
inline bvhvec2 operator*( const bvhvec2& a, const bvhvec2& b ) { return bvhvec2( a.x * b.x, a.y * b.y ); }
inline bvhvec3 operator*( const bvhvec3& a, const bvhvec3& b ) { return bvhvec3( a.x * b.x, a.y * b.y, a.z * b.z ); }
inline bvhvec4 operator*( const bvhvec4& a, const bvhvec4& b ) { return bvhvec4( a.x * b.x, a.y * b.y, a.z * b.z, a.w * b.w ); }
inline bvhvec2 operator*( const bvhvec2& a, float b ) { return bvhvec2( a.x * b, a.y * b ); }
inline bvhvec3 operator*( const bvhvec3& a, float b ) { return bvhvec3( a.x * b, a.y * b, a.z * b ); }
inline bvhvec4 operator*( const bvhvec4& a, float b ) { return bvhvec4( a.x * b, a.y * b, a.z * b, a.w * b ); }
inline bvhvec2 operator*( float b, const bvhvec2& a ) { return bvhvec2( b * a.x, b * a.y ); }
inline bvhvec3 operator*( float b, const bvhvec3& a ) { return bvhvec3( b * a.x, b * a.y, b * a.z ); }
inline bvhvec4 operator*( float b, const bvhvec4& a ) { return bvhvec4( b * a.x, b * a.y, b * a.z, b * a.w ); }
inline bvhvec2 operator/( float b, const bvhvec2& a ) { return bvhvec2( b / a.x, b / a.y ); }
inline bvhvec3 operator/( float b, const bvhvec3& a ) { return bvhvec3( b / a.x, b / a.y, b / a.z ); }
inline bvhvec4 operator/( float b, const bvhvec4& a ) { return bvhvec4( b / a.x, b / a.y, b / a.z, b / a.w ); }
inline void operator*=( bvhvec3& a, const float b ) { a.x *= b; a.y *= b; a.z *= b; }
#endif // TINYBVH_USE_CUSTOM_VECTOR_TYPES
// Vector math: cross and dot.
static inline bvhvec3 cross( const bvhvec3& a, const bvhvec3& b )
{
return bvhvec3( a.y * b.z - a.z * b.y, a.z * b.x - a.x * b.z, a.x * b.y - a.y * b.x );
}
static inline float dot( const bvhvec2& a, const bvhvec2& b ) { return a.x * b.x + a.y * b.y; }
static inline float dot( const bvhvec3& a, const bvhvec3& b ) { return a.x * b.x + a.y * b.y + a.z * b.z; }
static inline float dot( const bvhvec4& a, const bvhvec4& b ) { return a.x * b.x + a.y * b.y + a.z * b.z + a.w * b.w; }
// Vector math: common operations.
static float length( const bvhvec3& a ) { return sqrtf( a.x * a.x + a.y * a.y + a.z * a.z ); }
static bvhvec3 normalize( const bvhvec3& a )
{
float l = length( a ), rl = l == 0 ? 0 : (1.0f / l);
return a * rl;
}
#ifdef DOUBLE_PRECISION_SUPPORT
// Double-precision math
#ifndef TINYBVH_USE_CUSTOM_VECTOR_TYPES
struct bvhdbl3
{
bvhdbl3() = default;
bvhdbl3( const double a, const double b, const double c ) : x( a ), y( b ), z( c ) {}
bvhdbl3( const double a ) : x( a ), y( a ), z( a ) {}
bvhdbl3( const bvhvec3 a ) : x( (double)a.x ), y( (double)a.y ), z( (double)a.z ) {}
double halfArea() { return x < -BVH_FAR ? 0 : (x * y + y * z + z * x); } // for SAH calculations
double& operator [] ( const int32_t i ) { return cell[i]; }
union { struct { double x, y, z; }; double cell[3]; };
};
#endif // TINYBVH_USE_CUSTOM_VECTOR_TYPES
static inline bvhdbl3 tinybvh_min( const bvhdbl3& a, const bvhdbl3& b ) { return bvhdbl3( tinybvh_min( a.x, b.x ), tinybvh_min( a.y, b.y ), tinybvh_min( a.z, b.z ) ); }
static inline bvhdbl3 tinybvh_max( const bvhdbl3& a, const bvhdbl3& b ) { return bvhdbl3( tinybvh_max( a.x, b.x ), tinybvh_max( a.y, b.y ), tinybvh_max( a.z, b.z ) ); }
#ifndef TINYBVH_USE_CUSTOM_VECTOR_TYPES
inline bvhdbl3 operator-( const bvhdbl3& a ) { return bvhdbl3( -a.x, -a.y, -a.z ); }
inline bvhdbl3 operator+( const bvhdbl3& a, const bvhdbl3& b ) { return bvhdbl3( a.x + b.x, a.y + b.y, a.z + b.z ); }
inline bvhdbl3 operator-( const bvhdbl3& a, const bvhdbl3& b ) { return bvhdbl3( a.x - b.x, a.y - b.y, a.z - b.z ); }
inline void operator+=( bvhdbl3& a, const bvhdbl3& b ) { a.x += b.x; a.y += b.y; a.z += b.z; }
inline bvhdbl3 operator*( const bvhdbl3& a, const bvhdbl3& b ) { return bvhdbl3( a.x * b.x, a.y * b.y, a.z * b.z ); }
inline bvhdbl3 operator*( const bvhdbl3& a, double b ) { return bvhdbl3( a.x * b, a.y * b, a.z * b ); }
inline bvhdbl3 operator*( double b, const bvhdbl3& a ) { return bvhdbl3( b * a.x, b * a.y, b * a.z ); }
inline bvhdbl3 operator/( double b, const bvhdbl3& a ) { return bvhdbl3( b / a.x, b / a.y, b / a.z ); }
inline bvhdbl3 operator*=( bvhdbl3& a, const double b ) { return bvhdbl3( a.x * b, a.y * b, a.z * b ); }
#endif // TINYBVH_USE_CUSTOM_VECTOR_TYPES
static inline bvhdbl3 cross( const bvhdbl3& a, const bvhdbl3& b )
{
return bvhdbl3( a.y * b.z - a.z * b.y, a.z * b.x - a.x * b.z, a.x * b.y - a.y * b.x );
}
static inline double dot( const bvhdbl3& a, const bvhdbl3& b ) { return a.x * b.x + a.y * b.y + a.z * b.z; }
#endif
// SIMD typedef, helps keeping the interface generic
#ifdef BVH_USEAVX
typedef __m128 SIMDVEC4;
typedef __m256 SIMDVEC8;
#define SIMD_SETVEC(a,b,c,d) _mm_set_ps( a, b, c, d )
#define SIMD_SETRVEC(a,b,c,d) _mm_set_ps( d, c, b, a )
#elif defined(BVH_USENEON)
typedef float32x4_t SIMDVEC4;
typedef float32x4x2_t SIMDVEC8;
inline float32x4_t SIMD_SETVEC( float w, float z, float y, float x )
{
ALIGNED( 64 ) float data[4] = { x, y, z, w };
return vld1q_f32( data );
}
inline float32x4_t SIMD_SETRVEC( float x, float y, float z, float w )
{
ALIGNED( 64 ) float data[4] = { x, y, z, w };
return vld1q_f32( data );
}
inline uint32x4_t SIMD_SETRVECU( uint32_t x, uint32_t y, uint32_t z, uint32_t w )
{
ALIGNED( 64 ) uint32_t data[4] = { x, y, z, w };
return vld1q_u32( data );
}
#else
typedef bvhvec4 SIMDVEC4;
#define SIMD_SETVEC(a,b,c,d) bvhvec4( d, c, b, a )
#define SIMD_SETRVEC(a,b,c,d) bvhvec4( a, b, c, d )
#endif
// error handling
#define FATAL_ERROR_IF(c,s) if (c) { fprintf( stderr, \
"Fatal error in tiny_bvh.h, line %i:\n%s\n", __LINE__, s ); exit( 1 ); }
// ============================================================================
//
// T I N Y _ B V H I N T E R F A C E
//
// ============================================================================
struct Intersection
{
// An intersection result is designed to fit in no more than
// four 32-bit values. This allows efficient storage of a result in
// GPU code. The obvious missing result is an instance id; consider
// squeezing this in the 'prim' field in some way.
// Using this data and the original triangle data, all other info for
// shading (such as normal, texture color etc.) can be reconstructed.
float t, u, v; // distance along ray & barycentric coordinates of the intersection
uint32_t prim; // primitive index
};
struct Ray
{
// Basic ray class. Note: For single blas traversal it is expected
// that Ray::rD is properly initialized. For tlas/blas traversal this
// field is typically updated for each blas.
Ray() = default;
Ray( bvhvec3 origin, bvhvec3 direction, float t = BVH_FAR )
{
memset( this, 0, sizeof( Ray ) );
O = origin, D = normalize( direction ), rD = tinybvh_safercp( D );
hit.t = t;
}
ALIGNED( 16 ) bvhvec3 O; uint32_t dummy1;
ALIGNED( 16 ) bvhvec3 D; uint32_t dummy2;
ALIGNED( 16 ) bvhvec3 rD; uint32_t dummy3;
ALIGNED( 16 ) Intersection hit;
};
#ifdef DOUBLE_PRECISION_SUPPORT
struct RayEx
{
// Double-precision ray definition.
RayEx() = default;
RayEx( bvhdbl3 origin, bvhdbl3 direction, double tmax = BVH_DBL_FAR )
{
memset( this, 0, sizeof( RayEx ) );
O = origin, D = direction;
double rl = 1.0 / sqrt( D.x * D.x + D.y * D.y + D.z * D.z );
D.x *= rl, D.y *= rl, D.z *= rl;
rD.x = 1.0 / D.x, rD.y = 1.0 / D.y, rD.z = 1.0 / D.z;
u = v = 0, t = tmax;
}
bvhdbl3 O, D, rD;
double t, u, v;
uint64_t primIdx;
};
#endif
struct BVHContext
{
void* (*malloc)(size_t size, void* userdata) = malloc64;
void (*free)(void* ptr, void* userdata) = free64;
void* userdata = nullptr;
};
enum TraceDevice : uint32_t { USE_CPU = 1, USE_GPU };
class BVHBase
{
public:
struct ALIGNED( 32 ) Fragment
{
// A fragment stores the bounds of an input primitive. The name 'Fragment' is from
// "Parallel Spatial Splits in Bounding Volume Hierarchies", 2016, Fuetterling et al.,
// and refers to the potential splitting of these boxes for SBVH construction.
bvhvec3 bmin; // AABB min x, y and z
uint32_t primIdx; // index of the original primitive
bvhvec3 bmax; // AABB max x, y and z
uint32_t clipped = 0; // Fragment is the result of clipping if > 0.
bool validBox() { return bmin.x < BVH_FAR; }
};
// BVH flags, maintainted by tiny_bvh.
bool rebuildable = true; // rebuilds are safe only if a tree has not been converted.
bool refittable = true; // refits are safe only if the tree has no spatial splits.
bool may_have_holes = false; // threaded builds and MergeLeafs produce BVHs with unused nodes.
bool bvh_over_aabbs = false; // a BVH over AABBs is useful for e.g. TLAS traversal.
bool bvh_over_indices = false; // a BVH over indices cannot translate primitive index to vertex index.
BVHContext context; // context used to provide user-defined allocation functions
// Keep track of allocated buffer size to avoid repeated allocation during layout conversion.
uint32_t allocatedNodes = 0; // number of nodes allocated for the BVH.
uint32_t usedNodes = 0; // number of nodes used for the BVH.
uint32_t triCount = 0; // number of primitives in the BVH.
uint32_t idxCount = 0; // number of primitive indices; can exceed triCount for SBVH.
// Custom memory allocation
void* AlignedAlloc( size_t size );
void AlignedFree( void* ptr );
// Common methods
void CopyBasePropertiesFrom( const BVHBase& original ); // copy flags from one BVH to another
protected:
__FORCEINLINE void IntersectTri( Ray& ray, const bvhvec4slice& verts, const uint32_t triIdx ) const;
__FORCEINLINE void IntersectTriIndexed( Ray& ray, const bvhvec4slice& verts, const uint32_t* indices, const uint32_t idx ) const;
__FORCEINLINE bool TriOccludes( const Ray& ray, const bvhvec4slice& verts, const uint32_t idx ) const;
__FORCEINLINE bool IndexedTriOccludes( const Ray& ray, const bvhvec4slice& verts, const uint32_t* indices, const uint32_t idx ) const;
static float IntersectAABB( const Ray& ray, const bvhvec3& aabbMin, const bvhvec3& aabbMax );
static void PrecomputeTriangle( const bvhvec4slice& vert, uint32_t triIndex, float* T );
static float SA( const bvhvec3& aabbMin, const bvhvec3& aabbMax );
};
class BLASInstance;
class BVH_Verbose;
class BVH : public BVHBase
{
public:
friend class BVH_GPU;
friend class BVH_SoA;
template <int M> friend class MBVH;
enum BuildFlags : uint32_t {
NONE = 0, // Default building behavior (binned, SAH-driven).
FULLSPLIT = 1 // Split as far as possible, even when SAH doesn't agree.
};
struct BVHNode
{
// 'Traditional' 32-byte BVH node layout, as proposed by Ingo Wald.
// When aligned to a cache line boundary, two of these fit together.
bvhvec3 aabbMin; uint32_t leftFirst; // 16 bytes
bvhvec3 aabbMax; uint32_t triCount; // 16 bytes, total: 32 bytes
bool isLeaf() const { return triCount > 0; /* empty BVH leaves do not exist */ }
float Intersect( const Ray& ray ) const { return BVH::IntersectAABB( ray, aabbMin, aabbMax ); }
float SurfaceArea() const { return BVH::SA( aabbMin, aabbMax ); }
};
BVH( BVHContext ctx = {} ) { context = ctx; }
BVH( const BVH_Verbose& original ) { ConvertFrom( original ); }
BVH( const bvhvec4* vertices, const uint32_t primCount ) { Build( vertices, primCount ); }
BVH( const bvhvec4slice& vertices ) { Build( vertices ); }
~BVH();
void ConvertFrom( const BVH_Verbose& original );
float SAHCost( const uint32_t nodeIdx = 0 ) const;
int32_t NodeCount() const;
int32_t PrimCount( const uint32_t nodeIdx = 0 ) const;
void Compact();
void BuildQuick( const bvhvec4* vertices, const uint32_t primCount );
void BuildQuick( const bvhvec4slice& vertices );
void Build( const bvhvec4* vertices, const uint32_t primCount );
void Build( const bvhvec4slice& vertices );
void Build( const bvhvec4* vertices, const uint32_t* indices, const uint32_t primCount );
void Build( const bvhvec4slice& vertices, const uint32_t* indices, const uint32_t primCount );
void BuildHQ( const bvhvec4* vertices, const uint32_t primCount );
void BuildHQ( const bvhvec4slice& vertices );
void BuildHQ( const bvhvec4* vertices, const uint32_t* indices, const uint32_t primCount );
void BuildHQ( const bvhvec4slice& vertices, const uint32_t* indices, const uint32_t primCount );
#ifdef BVH_USEAVX
void BuildAVX( const bvhvec4* vertices, const uint32_t primCount );
void BuildAVX( const bvhvec4slice& vertices );
void BuildAVX( const bvhvec4* vertices, const uint32_t* indices, const uint32_t primCount );
void BuildAVX( const bvhvec4slice& vertices, const uint32_t* indices, const uint32_t primCount );
#elif defined BVH_USENEON
void BuildNEON( const bvhvec4* vertices, const uint32_t primCount );
void BuildNEON( const bvhvec4slice& vertices );
#endif
void BuildTLAS( const bvhaabb* aabbs, const uint32_t aabbCount );
void BuildTLAS( const BLASInstance* bvhs, const uint32_t instCount );
void Refit( const uint32_t nodeIdx = 0 );
int32_t Intersect( Ray& ray ) const;
int32_t IntersectTLAS( Ray& ray ) const;
bool IsOccluded( const Ray& ray ) const;
void Intersect256Rays( Ray* first ) const;
void Intersect256RaysSSE( Ray* packet ) const; // requires BVH_USEAVX
private:
void PrepareBuild( const bvhvec4slice& vertices, const uint32_t* indices, const uint32_t primCount );
void Build();
void PrepareAVXBuild( const bvhvec4slice& vertices, const uint32_t* indices, const uint32_t primCount );
void BuildAVX();
void PrepareHQBuild( const bvhvec4slice& vertices, const uint32_t* indices, const uint32_t prims );
void BuildHQ();
bool ClipFrag( const Fragment& orig, Fragment& newFrag, bvhvec3 bmin, bvhvec3 bmax, bvhvec3 minDim, const uint32_t splitAxis );
void RefitUpVerbose( uint32_t nodeIdx );
uint32_t FindBestNewPosition( const uint32_t Lid );
void ReinsertNodeVerbose( const uint32_t Lid, const uint32_t Nid, const uint32_t origin );
uint32_t CountSubtreeTris( const uint32_t nodeIdx, uint32_t* counters );
void MergeSubtree( const uint32_t nodeIdx, uint32_t* newIdx, uint32_t& newIdxPtr );
protected:
void BuildDefault( const bvhvec4* vertices, const uint32_t primCount );
void BuildDefault( const bvhvec4slice& vertices );
void BuildDefault( const bvhvec4* vertices, const uint32_t* indices, const uint32_t primCount );
void BuildDefault( const bvhvec4slice& vertices, const uint32_t* indices, const uint32_t primCount );
public:
// Basic BVH data
bvhvec4slice verts = {}; // pointer to input primitive array: 3x16 bytes per tri.
uint32_t* vertIdx = 0; // vertex indices, only used in case the BVH is built over indexed prims.
uint32_t* triIdx = 0; // primitive index array.
BVHNode* bvhNode = 0; // BVH node pool, Wald 32-byte format. Root is always in node 0.
uint32_t newNodePtr = 0; // used during build to keep track of next free node in pool.
Fragment* fragment = 0; // input primitive bounding boxes.
};
#ifdef DOUBLE_PRECISION_SUPPORT
class BVH_Double : public BVHBase
{
public:
struct BVHNode
{
// Double precision 'traditional' BVH node layout.
// Compared to the default BVHNode, child node indices and triangle indices
// are also expanded to 64bit values to support massive scenes.
bvhdbl3 aabbMin, aabbMax; // 2x24 bytes
uint64_t leftFirst; // 8 bytes
uint64_t triCount; // 8 bytes, total: 64 bytes
bool isLeaf() const { return triCount > 0; /* empty BVH leaves do not exist */ }
double Intersect( const RayEx& ray ) const;
double SurfaceArea() const;
};
struct Fragment
{
// Double-precision version of the fragment sruct.
bvhdbl3 bmin, bmax; // AABB
uint64_t primIdx; // index of the original primitive
};
BVH_Double( BVHContext ctx = {} ) { context = ctx; }
~BVH_Double();
void Build( const bvhdbl3* vertices, const uint32_t primCount );
double SAHCost( const uint64_t nodeIdx = 0 ) const;
int32_t Intersect( RayEx& ray ) const;
bvhdbl3* verts = 0; // pointer to input primitive array, double-precision, 3x24 bytes per tri.
Fragment* fragment = 0; // input primitive bounding boxes, double-precision.
BVHNode* bvhNode = 0; // BVH node, double precision format.
uint64_t* triIdx = 0; // primitive index array for double-precision bvh.
};
#endif
class BVH_GPU : public BVHBase
{
public:
struct BVHNode
{
// Alternative 64-byte BVH node layout, which specifies the bounds of
// the children rather than the node itself. This layout is used by
// Aila and Laine in their seminal GPU ray tracing paper.
bvhvec3 lmin; uint32_t left;
bvhvec3 lmax; uint32_t right;
bvhvec3 rmin; uint32_t triCount;
bvhvec3 rmax; uint32_t firstTri; // total: 64 bytes
bool isLeaf() const { return triCount > 0; }
};
BVH_GPU( BVHContext ctx = {} ) { context = ctx; }
BVH_GPU( const BVH& original ) { /* DEPRICATED */ ConvertFrom( original ); }
~BVH_GPU();
void Build( const bvhvec4* vertices, const uint32_t primCount );
void Build( const bvhvec4slice& vertices );
void Build( const bvhvec4* vertices, const uint32_t* indices, const uint32_t primCount );
void Build( const bvhvec4slice& vertices, const uint32_t* indices, const uint32_t primCount );
void BuildHQ( const bvhvec4* vertices, const uint32_t primCount );
void BuildHQ( const bvhvec4slice& vertices );
void BuildHQ( const bvhvec4* vertices, const uint32_t* indices, const uint32_t primCount );
void BuildHQ( const bvhvec4slice& vertices, const uint32_t* indices, const uint32_t primCount );
void ConvertFrom( const BVH& original );
int32_t Intersect( Ray& ray ) const;
bool IsOccluded( const Ray& ray ) const { FALLBACK_SHADOW_QUERY( ray ); }
// BVH data
BVHNode* bvhNode = 0; // BVH node in Aila & Laine format.
BVH bvh; // BVH4 is created from BVH and uses its data.
bool ownBVH = true; // False when ConvertFrom receives an external bvh.
};
class BVH_SoA : public BVHBase
{
public:
struct BVHNode
{
// Second alternative 64-byte BVH node layout, same as BVHAilaLaine but
// with child AABBs stored in SoA order.
SIMDVEC4 xxxx, yyyy, zzzz;
uint32_t left, right, triCount, firstTri; // total: 64 bytes
bool isLeaf() const { return triCount > 0; }
};
BVH_SoA( BVHContext ctx = {} ) { context = ctx; }
BVH_SoA( const BVH& original ) { /* DEPRICATED */ ConvertFrom( original ); }
~BVH_SoA();
void Build( const bvhvec4* vertices, const uint32_t primCount );
void Build( const bvhvec4slice& vertices );
void Build( const bvhvec4* vertices, const uint32_t* indices, const uint32_t primCount );
void Build( const bvhvec4slice& vertices, const uint32_t* indices, const uint32_t primCount );
void BuildHQ( const bvhvec4* vertices, const uint32_t primCount );
void BuildHQ( const bvhvec4slice& vertices );
void BuildHQ( const bvhvec4* vertices, const uint32_t* indices, const uint32_t primCount );
void BuildHQ( const bvhvec4slice& vertices, const uint32_t* indices, const uint32_t primCount );
void ConvertFrom( const BVH& original );
int32_t Intersect( Ray& ray ) const;
bool IsOccluded( const Ray& ray ) const;
// BVH data
BVHNode* bvhNode = 0; // BVH node in 'structure of arrays' format.
BVH bvh; // BVH_SoA is created from BVH and uses its data.
bool ownBVH = true; // False when ConvertFrom receives an external bvh.
};
class BVH_Verbose : public BVHBase
{
public:
struct BVHNode
{
// This node layout has some extra data per node: It stores left and right
// child node indices explicitly, and stores the index of the parent node.
// This format exists primarily for the BVH optimizer.
bvhvec3 aabbMin; uint32_t left;
bvhvec3 aabbMax; uint32_t right;
uint32_t triCount, firstTri, parent, dummy;
bool isLeaf() const { return triCount > 0; }
};
BVH_Verbose( BVHContext ctx = {} ) { context = ctx; }
BVH_Verbose( const BVH& original ) { /* DEPRECATED */ ConvertFrom( original ); }
~BVH_Verbose() { AlignedFree( bvhNode ); }
void ConvertFrom( const BVH& original );
float SAHCost( const uint32_t nodeIdx = 0 ) const;
int32_t NodeCount() const;
int32_t PrimCount( const uint32_t nodeIdx = 0 ) const;
void Refit( const uint32_t nodeIdx );
void Compact();
void SplitLeafs( const uint32_t maxPrims = 1 );
void MergeLeafs();
void Optimize( const uint32_t iterations );
private:
void RefitUpVerbose( uint32_t nodeIdx );
uint32_t FindBestNewPosition( const uint32_t Lid );
void ReinsertNodeVerbose( const uint32_t Lid, const uint32_t Nid, const uint32_t origin );
uint32_t CountSubtreeTris( const uint32_t nodeIdx, uint32_t* counters );
void MergeSubtree( const uint32_t nodeIdx, uint32_t* newIdx, uint32_t& newIdxPtr );
public:
// BVH data
bvhvec4slice verts = {}; // pointer to input primitive array: 3x16 bytes per tri.
Fragment* fragment = 0; // input primitive bounding boxes, double-precision.
uint32_t* triIdx = 0; // primitive index array - pointer copied from original.
BVHNode* bvhNode = 0; // BVH node with additional info, for BVH optimizer.
};
template <int M> class MBVH : public BVHBase
{
public:
struct MBVHNode
{
// 4-wide (aka 'shallow') BVH layout.
bvhvec3 aabbMin; uint32_t firstTri;
bvhvec3 aabbMax; uint32_t triCount;
uint32_t child[M];
uint32_t childCount;
uint32_t dummy[((30 - M) & 3) + 1]; // dummies are for alignment.
bool isLeaf() const { return triCount > 0; }
};
MBVH( BVHContext ctx = {} ) { context = ctx; }
MBVH( const BVH& original ) { /* DEPRECATED */ ConvertFrom( original ); }
~MBVH();
void Build( const bvhvec4* vertices, const uint32_t primCount );
void Build( const bvhvec4slice& vertices );
void Build( const bvhvec4* vertices, const uint32_t* indices, const uint32_t primCount );
void Build( const bvhvec4slice& vertices, const uint32_t* indices, const uint32_t primCount );
void BuildHQ( const bvhvec4* vertices, const uint32_t primCount );
void BuildHQ( const bvhvec4slice& vertices );
void BuildHQ( const bvhvec4* vertices, const uint32_t* indices, const uint32_t primCount );
void BuildHQ( const bvhvec4slice& vertices, const uint32_t* indices, const uint32_t primCount );
void ConvertFrom( const BVH& original );
void SplitBVHLeaf( const uint32_t nodeIdx, const uint32_t maxPrims );
// BVH data
MBVHNode* mbvhNode = 0; // BVH node for M-wide BVH.
BVH bvh; // BVH4 is created from BVH and uses its data.
bool ownBVH = true; // False when ConvertFrom receives an external bvh.
};
class BVH4_GPU : public BVHBase
{
public:
struct BVHNode // actual struct is unused; left here to show structure of data in bvh4Data.
{
// 4-way BVH node, optimized for GPU rendering
struct aabb8 { uint8_t xmin, ymin, zmin, xmax, ymax, zmax; }; // quantized
bvhvec3 aabbMin; uint32_t c0Info; // 16
bvhvec3 aabbExt; uint32_t c1Info; // 16
aabb8 c0bounds, c1bounds; uint32_t c2Info; // 16
aabb8 c2bounds, c3bounds; uint32_t c3Info; // 16; total: 64 bytes
// childInfo, 32bit:
// msb: 0=interior, 1=leaf
// leaf: 16 bits: relative start of triangle data, 15 bits: triangle count.
// interior: 31 bits: child node address, in float4s from BVH data start.
// Triangle data: directly follows nodes with leaves. Per tri:
// - bvhvec4 vert0, vert1, vert2
// - uint vert0.w stores original triangle index.
// We can make the node smaller by storing child nodes sequentially, but
// there is no way we can shave off a full 16 bytes, unless aabbExt is stored
// as chars as well, as in CWBVH.
};
BVH4_GPU( BVHContext ctx = {} ) { context = ctx; }
BVH4_GPU( const MBVH<4>& original ) { /* DEPRECATED */ ConvertFrom( bvh4 ); }
~BVH4_GPU();
void Build( const bvhvec4* vertices, const uint32_t primCount );
void Build( const bvhvec4slice& vertices );
void Build( const bvhvec4* vertices, const uint32_t* indices, const uint32_t primCount );
void Build( const bvhvec4slice& vertices, const uint32_t* indices, const uint32_t primCount );
void BuildHQ( const bvhvec4* vertices, const uint32_t primCount );
void BuildHQ( const bvhvec4slice& vertices );
void BuildHQ( const bvhvec4* vertices, const uint32_t* indices, const uint32_t primCount );
void BuildHQ( const bvhvec4slice& vertices, const uint32_t* indices, const uint32_t primCount );
void ConvertFrom( const MBVH<4>& original );
int32_t Intersect( Ray& ray ) const;
bool IsOccluded( const Ray& ray ) const { FALLBACK_SHADOW_QUERY( ray ); }
// BVH data
bvhvec4* bvh4Data = 0; // 64-byte 4-wide BVH node for efficient GPU rendering.
uint32_t allocatedBlocks = 0; // node data and triangles are stored in 16-byte blocks.
uint32_t usedBlocks = 0; // actually used storage.
MBVH<4> bvh4; // BVH4_CPU is created from BVH4 and uses its data.
bool ownBVH4 = true; // False when ConvertFrom receives an external bvh.
};
class BVH4_CPU : public BVHBase
{
public:
struct BVHNode
{
// 4-way BVH node, optimized for CPU rendering.
// Based on: "Faster Incoherent Ray Traversal Using 8-Wide AVX Instructions",
// Áfra, 2013.
SIMDVEC4 xmin4, ymin4, zmin4;
SIMDVEC4 xmax4, ymax4, zmax4;
uint32_t childFirst[4];
uint32_t triCount[4];
};
BVH4_CPU( BVHContext ctx = {} ) { context = ctx; }
BVH4_CPU( const MBVH<4>& original ) { /* DEPRECATED */ ConvertFrom( bvh4 ); }
~BVH4_CPU();
void Build( const bvhvec4* vertices, const uint32_t primCount );
void Build( const bvhvec4slice& vertices );
void Build( const bvhvec4* vertices, const uint32_t* indices, const uint32_t primCount );
void Build( const bvhvec4slice& vertices, const uint32_t* indices, const uint32_t primCount );
void BuildHQ( const bvhvec4* vertices, const uint32_t primCount );
void BuildHQ( const bvhvec4slice& vertices );
void BuildHQ( const bvhvec4* vertices, const uint32_t* indices, const uint32_t primCount );
void BuildHQ( const bvhvec4slice& vertices, const uint32_t* indices, const uint32_t primCount );
void ConvertFrom( const MBVH<4>& original );
int32_t Intersect( Ray& ray ) const;
bool IsOccluded( const Ray& ray ) const;
// BVH data
BVHNode* bvh4Node = 0; // 128-byte 4-wide BVH node for efficient CPU rendering.
bvhvec4* bvh4Tris = 0; // triangle data for BVHNode4Alt2 nodes.
MBVH<4> bvh4; // BVH4_CPU is created from BVH4 and uses its data.
bool ownBVH4 = true; // False when ConvertFrom receives an external bvh4.
};
class BVH8_CWBVH : public BVHBase
{
public:
BVH8_CWBVH( BVHContext ctx = {} ) { context = ctx; }
BVH8_CWBVH( MBVH<8>& original ) { /* DEPRECATED */ ConvertFrom( bvh8 ); }
~BVH8_CWBVH();
void Save( const char* fileName );
bool Load( const char* fileName, const uint32_t expectedTris );
void Build( const bvhvec4* vertices, const uint32_t primCount );
void Build( const bvhvec4slice& vertices );
void Build( const bvhvec4* vertices, const uint32_t* indices, const uint32_t primCount );
void Build( const bvhvec4slice& vertices, const uint32_t* indices, const uint32_t primCount );
void BuildHQ( const bvhvec4* vertices, const uint32_t primCount );
void BuildHQ( const bvhvec4slice& vertices );
void BuildHQ( const bvhvec4* vertices, const uint32_t* indices, const uint32_t primCount );
void BuildHQ( const bvhvec4slice& vertices, const uint32_t* indices, const uint32_t primCount );
void ConvertFrom( MBVH<8>& original ); // NOTE: Not const; this may change some nodes in the original.
int32_t Intersect( Ray& ray ) const;
bool IsOccluded( const Ray& ray ) const { FALLBACK_SHADOW_QUERY( ray ); }
// BVH8 data
bvhvec4* bvh8Data = 0; // nodes in CWBVH format.
bvhvec4* bvh8Tris = 0; // triangle data for CWBVH nodes.
uint32_t allocatedBlocks = 0; // node data is stored in blocks of 16 byte.
uint32_t usedBlocks = 0; // actually used blocks.
MBVH<8> bvh8; // BVH8_CWBVH is created from BVH8 and uses its data.
bool ownBVH8 = true; // false when ConvertFrom receives an external bvh8.
};
// BLASInstance: A TLAS is built over BLAS instances, where a single BLAS can be
// used with multiple transforms, and multiple BLASses can be combined in a complex
// scene. The TLAS is built over the world-space AABBs of the BLAS root nodes.
class BLASInstance
{
public:
BLASInstance( BVH* bvh ) : blas( bvh ) {}
void Update(); // Update the world bounds based on the current transform.
bvhaabb worldBounds; // World-space AABB over the transformed blas root node.
float transform[16] = { 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 }; // identity
BVH* blas = 0; // Bottom-level acceleration structure.
bvhvec3 TransformPoint( const bvhvec3& v ) const;
bvhvec3 TransformVector( const bvhvec3& v ) const;
};
// Experimental & 'under construction' structs
class BVH4_WiVe : public BVHBase
{
public:
struct BVHNode
{
// 4-way BVH node, optimized for CPU rendering.
// Based on: "Accelerated Single Ray Tracing for Wide Vector Units",
// Fuetterling1 et al., 2017.
union { SIMDVEC4 xmin4; float xmin[4]; };
union { SIMDVEC4 xmax4; float xmax[4]; };
union { SIMDVEC4 ymin4; float ymin[4]; };
union { SIMDVEC4 ymax4; float ymax[4]; };
union { SIMDVEC4 zmin4; float zmin[4]; };
union { SIMDVEC4 zmax4; float zmax[4]; };
// ORSTRec rec[4];
};
BVH4_WiVe( BVHContext ctx = {} ) { context = ctx; }
~BVH4_WiVe() { AlignedFree( bvh4Node ); }
BVH4_WiVe( const bvhvec4* vertices, const uint32_t primCount );
BVH4_WiVe( const bvhvec4slice& vertices );
int32_t Intersect( Ray& ray ) const;
bool IsOccluded( const Ray& ray ) const;
// BVH4 data
bvhvec4slice verts = {}; // pointer to input primitive array: 3x16 bytes per tri.
uint32_t* triIdx = 0; // primitive index array - pointer copied from original.
BVHNode* bvh4Node = 0; // 128-byte 4-wide BVH node for efficient CPU rendering.
};
class QBVH6
{
public:
// based on https://github.com/RenderKit/embree/blob/master/kernels/rthwif/rtbuild/qnode.h
struct QBVH6BasicNode
{
// 16 bytes specify the quantization grid
bvhvec3 lower; // world space origin of quantization grid
int8_t exp_x; // 2^exp_x is the size of the grid in x dimension
int8_t exp_y; // 2^exp_y is the size of the grid in y dimension
int8_t exp_z; // 2^exp_z is the size of the grid in z dimension
uint8_t pad; // unused byte
// 12 bytes for...
uint32_t childPtr; // offset to consequtive list of child nodes, in 64-byte multiples
uint32_t primCount; // 6x4=24bit prim count (1..16) for each leaf node, 8 bits: offset of leaf 6.
uint32_t offset; // 4x8=32bit leaf 1, 2, 3, 4 offsets (leaf 0 offset = 0).
// 36 bytes of quantized child node bounds
uint8_t lower_x[6]; // the quantized lower bounds in x-dimension
uint8_t upper_x[6]; // the quantized upper bounds in x-dimension
uint8_t lower_y[6]; // the quantized lower bounds in y-dimension
uint8_t upper_y[6]; // the quantized upper bounds in y-dimension
uint8_t lower_z[6]; // the quantized lower bounds in z-dimension
uint8_t upper_z[6]; // the quantized upper bounds in z-dimension
};
};
} // namespace tinybvh
// ============================================================================
//
// I M P L E M E N T A T I O N
//
// ============================================================================
#ifdef TINYBVH_IMPLEMENTATION
#include <assert.h> // for assert
#ifdef _MSC_VER
#include <intrin.h> // for __lzcnt
#endif
#include <fstream> // fstream
// We need quite a bit of type reinterpretation, so we'll
// turn off the gcc warning here until the end of the file.
#ifdef __GNUC__
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wstrict-aliasing"
#endif
namespace tinybvh {