forked from jbikker/tinybvh
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtiny_scene.h
More file actions
3293 lines (3153 loc) · 149 KB
/
tiny_scene.h
File metadata and controls
3293 lines (3153 loc) · 149 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
/*
The MIT License (MIT)
Copyright (c) 2024-2025, 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 TINYSCENE_IMPLEMENTATION
// #include "tiny_scene.h"
// tinyscene can use custom vector types by defining TINYSCENE_USE_CUSTOM_VECTOR_TYPES
// once before inclusion. To define custom vector types create a tinybvh namespace with
// the appropriate using directives, e.g.:
// namespace tinyscene
// {
// using bvhint2 = math::int2;
// using bvhint3 = math::int3;
// using bvhuint2 = math::uint2;
// using bvhvec2 = math::float2;
// using bvhvec3 = math::float3;
// using bvhvec4 = math::float4;
// }
//
// #define TINYSCENE_USE_CUSTOM_VECTOR_TYPES
// #include <tiny_scene.h>
// tiny_scene.h depends on tiny_obj_loader, tiny_gltf and stb_image.
// If you already implement these elsewhere, use the following defines
// to supress duplicate implementation in this header file.
// #define TINYSCENE_TINYOBJ_AREADY_IMPLEMENTED
// #define TINYSCENE_TINYGLTF_ALREADY_IMPLEMENTED
// #define TINYSCENE_STBIMAGE_ALREADY_IMPLEMENTED
#ifndef TINY_SCENE_H_
#define TINY_SCENE_H_
// LIGHTHOUSE 2 SCENE MANAGEMENT CODE - QUICK OVERVIEW
//
// This file defines the data structures for the Lighthouse 2 scene graph.
// It is designed to conveniently load and/or construct 3D scenes, using a
// combination of .gtlf / .obj files and extra triangles.
//
// The basis is a scenegraph: a hierarchy of nodes with 4x4 matrix transforms and
// (optionally) a triangle mesh. Meshes have materials and (optionally) data for
// animation.
//
// The data structure closely follows the gltf 2.0 format and supports all types
// of animation in pure CPU code: See Scene::SetPose for details.
//
// The triangle data is optimized for ray tracing rather than rasterization:
// - Triangle data is split in 'vertex only' and 'everything else' (see FatTri);
// - A mesh can have multiple materials. However: when loaded from a gltf file,
// each mesh will have only one material.
//
// Note about the use of pointers: This is intentionally minimal. Most objects are
// stored in vectors in class Scene; references to these are specified as indices
// in these vectors. E.g.: Mesh::ID stores the index of a mesh in Scene::meshPool.
//
// Architectural limitations: There is very little support for *deleting* anything
// in the scene. Adding this properly may require significant engineering.
// Scene::RemoveNode exists, but it only removes nodes themselves, not any
// linked materials or textures.
// access syoyo's tiny_obj and tiny_gltf implementations
#if defined TINYSCENE_IMPLEMENTATION && !defined TINYSCENE_TINYOBJ_AREADY_IMPLEMENTED
#define TINYOBJLOADER_IMPLEMENTATION
#endif
#include "tiny_obj_loader.h"
#if defined TINYSCENE_IMPLEMENTATION && !defined TINYSCENE_TINYGLTF_ALREADY_IMPLEMENTED
#define TINYGLTF_IMPLEMENTATION
#endif
#define TINYGLTF_NO_STB_IMAGE_WRITE
#include "tiny_gltf.h"
#if defined TINYSCENE_IMPLEMENTATION && !defined TINYSCENE_STBIMAGE_ALREADY_IMPLEMENTED
#define STB_IMAGE_IMPLEMENTATION
#endif
#include "stb_image.h"
#define MIPLEVELCOUNT 5
#define BINTEXFILEVERSION 0x10001001
#define CACHEIMAGES
namespace tinyscene
{
// 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/tinybvh, in a different namespace.
inline size_t make_multiple_of( size_t x, size_t alignment ) { return (x + (alignment - 1)) & ~(alignment - 1); }
#ifdef _MSC_VER // Visual Studio / C11
#define ALIGNED( x ) __declspec( align( x ) )
#define _ALIGNED_ALLOC(alignment,size) _aligned_malloc( make_multiple_of( size, alignment ), alignment );
#define _ALIGNED_FREE(ptr) _aligned_free( ptr );
#else // EMSCRIPTEN / gcc / clang
#define ALIGNED( x ) __attribute__( ( aligned( x ) ) )
#if !defined TINYBVH_NO_SIMD && (defined __x86_64__ || defined _M_X64 || defined __wasm_simd128__ || defined __wasm_relaxed_simd__)
#include <xmmintrin.h>
#define _ALIGNED_ALLOC(alignment,size) _mm_malloc( make_multiple_of( size, alignment ), alignment );
#define _ALIGNED_FREE(ptr) _mm_free( ptr );
#else
#if defined __APPLE__ || defined __aarch64__ || (defined __ANDROID_API__ && (__ANDROID_API__ >= 28))
#define _ALIGNED_ALLOC(alignment,size) aligned_alloc( alignment, make_multiple_of( size, alignment ) );
#elif defined __GNUC__
#ifdef __linux__
#define _ALIGNED_ALLOC(alignment,size) aligned_alloc( alignment, make_multiple_of( size, alignment ) );
#else
#define _ALIGNED_ALLOC(alignment,size) _aligned_malloc( alignment, make_multiple_of( size, alignment ) );
#endif
#endif
#define _ALIGNED_FREE(ptr) free( ptr );
#endif
#endif
inline void* malloc64( size_t size, void* = nullptr ) { return size == 0 ? 0 : _ALIGNED_ALLOC( 64, size ); }
inline void* malloc4k( size_t size, void* = nullptr ) { return size == 0 ? 0 : _ALIGNED_ALLOC( 4096, size ); }
inline void* malloc32k( size_t size, void* = nullptr ) { return size == 0 ? 0 : _ALIGNED_ALLOC( 32768, size ); }
inline void free64( void* ptr, void* = nullptr ) { _ALIGNED_FREE( ptr ); }
inline void free4k( void* ptr, void* = nullptr ) { _ALIGNED_FREE( ptr ); }
inline void free32k( void* ptr, void* = nullptr ) { _ALIGNED_FREE( ptr ); }
#ifndef TINYSCENE_USE_CUSTOM_VECTOR_TYPES
// tiny_scene.h sports its own vector types so it doesn't have a dependency on
// something external. TODO: 'bring your own vector type' as in tiny_bvh.h.
struct ts_vec3;
struct ALIGNED( 16 ) ts_vec4
{
// vector naming is designed to not cause any name clashes.
ts_vec4() = default;
ts_vec4( const float a, const float b, const float c, const float d ) : x( a ), y( b ), z( c ), w( d ) {}
ts_vec4( const float a ) : x( a ), y( a ), z( a ), w( a ) {}
ts_vec4( const ts_vec3 & a );
ts_vec4( const ts_vec3 & a, float b );
float& operator [] ( const int32_t i ) { return cell[i]; }
const float& operator [] ( const int32_t i ) const { return cell[i]; }
union { struct { float x, y, z, w; }; float cell[4]; };
};
struct ALIGNED( 8 ) ts_vec2
{
ts_vec2() = default;
ts_vec2( const float a, const float b ) : x( a ), y( b ) {}
ts_vec2( const float a ) : x( a ), y( a ) {}
ts_vec2( const ts_vec4 a ) : x( a.x ), y( a.y ) {}
float& operator [] ( const int32_t i ) { return cell[i]; }
const float& operator [] ( const int32_t i ) const { return cell[i]; }
union { struct { float x, y; }; float cell[2]; };
};
struct ts_vec3
{
ts_vec3() = default;
ts_vec3( const float a, const float b, const float c ) : x( a ), y( b ), z( c ) {}
ts_vec3( const float a ) : x( a ), y( a ), z( a ) {}
ts_vec3( const ts_vec4 a ) : x( a.x ), y( a.y ), z( a.z ) {}
float& operator [] ( const int32_t i ) { return cell[i]; }
const float& operator [] ( const int32_t i ) const { return cell[i]; }
union { struct { float x, y, z; }; float cell[3]; };
};
struct ts_int3
{
ts_int3() = default;
ts_int3( const int32_t a, const int32_t b, const int32_t c ) : x( a ), y( b ), z( c ) {}
ts_int3( const int32_t a ) : x( a ), y( a ), z( a ) {}
ts_int3( const ts_vec3& 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 ts_int2
{
ts_int2() = default;
ts_int2( const int32_t a, const int32_t b ) : x( a ), y( b ) {}
ts_int2( const int32_t a ) : x( a ), y( a ) {}
int32_t x, y;
};
struct ts_uint2
{
ts_uint2() = default;
ts_uint2( const uint32_t a, const uint32_t b ) : x( a ), y( b ) {}
ts_uint2( const uint32_t a ) : x( a ), y( a ) {}
uint32_t x, y;
};
struct ts_uint4
{
ts_uint4() = default;
ts_uint4( const uint32_t a, const uint32_t b, const uint32_t c, const uint32_t d ) : x( a ), y( b ), z( c ), w( d ) {}
ts_uint4( const uint32_t a ) : x( a ), y( a ), z( a ), w( a ) {}
uint32_t x, y, z, w;
};
inline ts_vec2 operator-( const ts_vec2& a ) { return ts_vec2( -a.x, -a.y ); }
inline ts_vec3 operator-( const ts_vec3& a ) { return ts_vec3( -a.x, -a.y, -a.z ); }
inline ts_vec4 operator-( const ts_vec4& a ) { return ts_vec4( -a.x, -a.y, -a.z, -a.w ); }
inline ts_vec2 operator+( const ts_vec2& a, const ts_vec2& b ) { return ts_vec2( a.x + b.x, a.y + b.y ); }
inline ts_vec3 operator+( const ts_vec3& a, const ts_vec3& b ) { return ts_vec3( a.x + b.x, a.y + b.y, a.z + b.z ); }
inline ts_vec4 operator+( const ts_vec4& a, const ts_vec4& b ) { return ts_vec4( a.x + b.x, a.y + b.y, a.z + b.z, a.w + b.w ); }
inline ts_vec4 operator+( const ts_vec4& a, const ts_vec3& b ) { return ts_vec4( a.x + b.x, a.y + b.y, a.z + b.z, a.w ); }
inline ts_vec2 operator-( const ts_vec2& a, const ts_vec2& b ) { return ts_vec2( a.x - b.x, a.y - b.y ); }
inline ts_vec3 operator-( const ts_vec3& a, const ts_vec3& b ) { return ts_vec3( a.x - b.x, a.y - b.y, a.z - b.z ); }
inline ts_vec4 operator-( const ts_vec4& a, const ts_vec4& b ) { return ts_vec4( a.x - b.x, a.y - b.y, a.z - b.z, a.w - b.w ); }
inline void operator+=( ts_vec2& a, const ts_vec2& b ) { a.x += b.x; a.y += b.y; }
inline void operator+=( ts_vec3& a, const ts_vec3& b ) { a.x += b.x; a.y += b.y; a.z += b.z; }
inline void operator+=( ts_vec4& a, const ts_vec4& b ) { a.x += b.x; a.y += b.y; a.z += b.z; a.w += b.w; }
inline ts_vec2 operator*( const ts_vec2& a, const ts_vec2& b ) { return ts_vec2( a.x * b.x, a.y * b.y ); }
inline ts_vec3 operator*( const ts_vec3& a, const ts_vec3& b ) { return ts_vec3( a.x * b.x, a.y * b.y, a.z * b.z ); }
inline ts_vec4 operator*( const ts_vec4& a, const ts_vec4& b ) { return ts_vec4( a.x * b.x, a.y * b.y, a.z * b.z, a.w * b.w ); }
inline ts_vec2 operator*( const ts_vec2& a, float b ) { return ts_vec2( a.x * b, a.y * b ); }
inline ts_vec3 operator*( const ts_vec3& a, float b ) { return ts_vec3( a.x * b, a.y * b, a.z * b ); }
inline ts_vec4 operator*( const ts_vec4& a, float b ) { return ts_vec4( a.x * b, a.y * b, a.z * b, a.w * b ); }
inline ts_vec2 operator*( float b, const ts_vec2& a ) { return ts_vec2( b * a.x, b * a.y ); }
inline ts_vec3 operator*( float b, const ts_vec3& a ) { return ts_vec3( b * a.x, b * a.y, b * a.z ); }
inline ts_vec4 operator*( float b, const ts_vec4& a ) { return ts_vec4( b * a.x, b * a.y, b * a.z, b * a.w ); }
inline ts_vec2 operator/( float b, const ts_vec2& a ) { return ts_vec2( b / a.x, b / a.y ); }
inline ts_vec3 operator/( float b, const ts_vec3& a ) { return ts_vec3( b / a.x, b / a.y, b / a.z ); }
inline ts_vec4 operator/( float b, const ts_vec4& a ) { return ts_vec4( b / a.x, b / a.y, b / a.z, b / a.w ); }
inline void operator*=( ts_vec3& a, const float b ) { a.x *= b; a.y *= b; a.z *= b; }
#endif // TINYSCENE_USE_CUSTOM_VECTOR_TYPES
struct ts_uchar4
{
ts_uchar4() = default;
ts_uchar4( const uint8_t a, const uint8_t b, const uint8_t c, const uint8_t d ) : x( a ), y( b ), z( c ), w( d ) {}
ts_uchar4( const uint8_t a ) : x( a ), y( a ), z( a ), w( a ) {}
uint8_t x, y, z, w;
};
struct ts_mat4
{
ts_mat4() = default;
static ts_mat4 scale( const float s ) { ts_mat4 r; r[0] = r[5] = r[10] = s; return r; }
static ts_mat4 scale( const ts_vec3 s ) { ts_mat4 r; r[0] = s.x, r[5] = s.y, r[10] = s.z; return r; }
static ts_mat4 translate( const ts_vec3 t ) { ts_mat4 r; r[3] = t.x, r[7] = t.y, r[11] = t.z; return r; }
float cell[16] = { 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 };
float& operator [] ( const int idx ) { return cell[idx]; }
const float& operator [] ( const int idx ) const { return cell[idx]; }
float operator()( const int i, const int j ) const { return cell[i * 4 + j]; }
float& operator()( const int i, const int j ) { return cell[i * 4 + j]; }
ts_mat4& operator += ( const ts_mat4& a )
{
for (int i = 0; i < 16; i++) cell[i] += a.cell[i];
return *this;
}
ts_mat4 inverted() const;
};
struct ts_aabb
{
ts_aabb() = default;
ts_vec3 bmin = ts_vec3( 1e30f );
ts_vec3 bmax = ts_vec3( -1e30f );
void grow( const ts_vec3& p );
};
class ts_quat // based on https://github.com/adafruit. Only what we actually need.
{
public:
ts_quat() = default;
ts_quat( float _w, float _x, float _y, float _z ) : w( _w ), x( _x ), y( _y ), z( _z ) {}
ts_quat( float _w, ts_vec3 v ) : w( _w ), x( v.x ), y( v.y ), z( v.z ) {}
float magnitude() const { return sqrtf( w * w + x * x + y * y + z * z ); }
void ts_normalize() { float m = magnitude(); *this = this->scale( 1 / m ); }
ts_mat4 toMatrix() const;
static ts_quat slerp( const ts_quat& a, const ts_quat& b, const float t );
ts_quat operator + ( const ts_quat& q ) const { return ts_quat( w + q.w, x + q.x, y + q.y, z + q.z ); }
ts_quat operator - ( const ts_quat& q ) const { return ts_quat( w - q.w, x - q.x, y - q.y, z - q.z ); }
ts_quat operator / ( float s ) const { return ts_quat( w / s, x / s, y / s, z / s ); }
ts_quat operator * ( float s ) const { return scale( s ); }
ts_quat scale( float s ) const { return ts_quat( w * s, x * s, y * s, z * s ); }
float w = 1, x = 0, y = 0, z = 0;
};
// +-----------------------------------------------------------------------------+
// | FatTri |
// | Full triangle data (for shading only), carefully layed out. LH2'24|
// +-----------------------------------------------------------------------------+
class FatTri
{
public:
FatTri() { ::memset( this, 0, sizeof( FatTri ) ); ltriIdx = -1; }
// 128 bytes of data needed for basic shading with texture and normal interpolation.
float u0, u1, u2; // 12 bytes for layer 0 texture coordinates
int ltriIdx; // 4, set only for emissive triangles, used for MIS
float v0, v1, v2; // 12 bytes for layer 0 texture coordinates
uint32_t material; // 4 bytes for triangle material index
ts_vec3 vN0; // 12 bytes for vertex0 normal
float Nx; // 4 bytes for x-component of geometric triangle normal
ts_vec3 vN1; // 12 bytes for vertex1 normal
float Ny; // 4 bytes for y-component of geometric triangle normal
ts_vec3 vN2; // 12 bytes for vertex2 normal
float Nz; // 4 bytes for z-component of geometric triangle normal
ts_vec3 vertex0; float u0_2; // vertex 0 position + second layer u0
ts_vec3 vertex1; float u1_2; // vertex 1 position + second layer u1
ts_vec3 vertex2; float u2_2; // vertex 2 position + second layer u2
// 64 bytes of data needed for normal mapping, anisotropic, multi-texture etc.
ts_vec3 T; // 12 bytes for tangent vector
float area; // 4 bytes for triangle area
ts_vec3 B; // 12 bytes for bitangent vector
float invArea; // 4 bytes for reciprocal triangle area
ts_vec3 alpha; // better spot than vertex0..2.w for reasons
float LOD; // for MIP mapping
float v0_2, v1_2, v2_2; // 12 bytes for second layer texture coordinates
float dummy4; // padding
// total FatTri size: 192 bytes.
void UpdateArea();
};
// +-----------------------------------------------------------------------------+
// | SkyDome |
// | Stores data for a HDR sky dome. LH2'24|
// +-----------------------------------------------------------------------------+
class SkyDome
{
public:
// constructor / destructor
SkyDome() = default;
SkyDome( const char* file ) { Load( file ); }
void Load( const char* filename, const ts_vec3 scale = { 1.f, 1.f, 1.f } );
// public data members
ts_vec3* pixels = nullptr; // HDR texture data for sky dome
int width = 0, height = 0; // width and height of the sky texture
ts_mat4 worldToLight; // for PBRT scenes; transform for skydome
};
// +-----------------------------------------------------------------------------+
// | Skin |
// | Skin data storage. LH2'24|
// +-----------------------------------------------------------------------------+
class Skin
{
public:
Skin( const ::tinygltf::Skin& gltfSkin, const ::tinygltf::Model& gltfModel, const int nodeBase );
void ConvertFromGLTFSkin( const ::tinygltf::Skin& gltfSkin, const ::tinygltf::Model& gltfModel, const int nodeBase );
::std::string name;
int skeletonRoot = 0;
::std::vector<ts_mat4> inverseBindMatrices, jointMat;
::std::vector<int> joints; // node indices of the joints
};
// +-----------------------------------------------------------------------------+
// | Mesh |
// | Mesh data storage. LH2'24|
// +-----------------------------------------------------------------------------+
class Mesh
{
public:
struct Pose { ::std::vector<ts_vec3> positions, normals, tangents; };
// constructor / destructor
Mesh() = default;
Mesh( const int triCount );
Mesh( const char* name, const char* dir, const float scale = 1.0f, const bool flatShaded = false );
Mesh( const ::tinygltf::Mesh& gltfMesh, const ::tinygltf::Model& gltfModel, const ::std::vector<int>& matIdx, const int materialOverride = -1 );
~Mesh() { /* TODO */ }
// methods
void LoadGeometry( const char* file, const char* dir, const float scale = 1.0f, const bool flatShaded = false );
void LoadGeometryFromOBJ( const ::std::string& fileName, const char* directory, const ts_mat4& transform, const bool flatShaded = false );
void ConvertFromGTLFMesh( const ::tinygltf::Mesh& gltfMesh, const ::tinygltf::Model& gltfModel, const ::std::vector<int>& matIdx, const int materialOverride );
void BuildFromIndexedData( const ::std::vector<int>& tmpIndices, const ::std::vector<ts_vec3>& tmpVertices,
const ::std::vector<ts_vec3>& tmpNormals, const ::std::vector<ts_vec2>& tmpUvs, const ::std::vector<ts_vec2>& tmpUv2s,
const ::std::vector<ts_vec4>& tmpTs, const ::std::vector<Pose>& tmpPoses,
const ::std::vector<ts_uint4>& tmpJoints, const ::std::vector<ts_vec4>& tmpWeights, const int materialIdx );
void BuildMaterialList();
void SetPose( const ::std::vector<float>& weights );
void SetPose( const Skin* skin );
// data members
::std::string name = "unnamed"; // name for the mesh
int ID = -1; // unique ID for the mesh: position in mesh array
::std::vector<ts_vec4> vertices; // model vertices, always 3 per triangle: vertices are *not* indexed.
::std::vector<ts_vec3> vertexNormals; // vertex normals, 1 per vertex
::std::vector<ts_vec4> original; // skinning: base pose; will be transformed into vector vertices
::std::vector<ts_vec3> origNormal; // skinning: base pose normals
::std::vector<FatTri> triangles; // full triangles, to be used for shading
::std::vector<int> materialList; // list of materials used by the mesh; used to efficiently track light changes
::std::vector<ts_uint4> joints; // skinning: joints
::std::vector<ts_vec4> weights; // skinning: joint weights
::std::vector<Pose> poses; // morph target data
bool isAnimated; // true when this mesh has animation data
bool excludeFromNavmesh = false; // prevents mesh from influencing navmesh generation (e.g. curtains)
ts_mat4 transform, invTransform; // copy of combined transform of parent node, for TLAS construction
ts_aabb worldBounds; // mesh bounds transformed by the transform of the parent node, for TLAS builds
};
// +-----------------------------------------------------------------------------+
// | Node |
// | Simple node for construction of a scene graph for the scene. LH2'24|
// +-----------------------------------------------------------------------------+
class Node
{
public:
// constructor / destructor
Node() = default;
Node( const int meshIdx, const ts_mat4& transform );
Node( const ::tinygltf::Node& gltfNode, const int nodeBase, const int meshBase, const int skinBase );
~Node();
// methods
void ConvertFromGLTFNode( const ::tinygltf::Node& gltfNode, const int nodeBase, const int meshBase, const int skinBase );
void Update( const ts_mat4& T ); // recursively update the transform of this node and its children
void UpdateTransformFromTRS(); // process T, R, S data to localTransform
void PrepareLights(); // create light trianslges from detected emissive triangles
void UpdateLights(); // fix light triangles when the transform changes
// data members
::std::string name; // node name as specified in the GLTF file
ts_vec3 translation = { 0 }; // T
ts_quat rotation; // R
ts_vec3 scale = ts_vec3( 1 ); // S
ts_mat4 matrix; // object transform
ts_mat4 localTransform; // = matrix * T * R * S, in case of animation
ts_mat4 combinedTransform; // transform combined with ancestor transforms
int ID = -1; // unique ID for the node: position in node array
int meshID = -1; // id of the mesh this node refers to (if any, -1 otherwise)
int skinID = -1; // id of the skin this node refers to (if any, -1 otherwise)
::std::vector<float> weights; // morph target weights
bool hasLights = false; // true if this instance uses an emissive material
bool morphed = false; // node mesh should update pose
bool transformed = false; // local transform of node should be updated
bool treeChanged = false; // this node or one of its children got updated
::std::vector<int> childIdx; // child nodes of this node
protected:
int instanceID = -1; // for mesh nodes: location in the instance array. For internal use only.
};
// +-----------------------------------------------------------------------------+
// | Material |
// | Full material definition, which contains everything that can be read from |
// | a gltf file. Will need to be digested to something more practical for |
// | rendering: For that there is 'Material'. LH2'24|
// +-----------------------------------------------------------------------------+
class Material
{
public:
enum { DISNEYBRDF = 1, LAMBERTBSDF, /* add extra here */ };
struct vec3Value
{
// ts_vec3Value / ScalarValue: all material parameters can be spatially variant or invariant.
// If a map is used, this map may have an offset and scale. The map values may also be
// scaled, to facilitate parameter map reuse.
vec3Value() = default;
vec3Value( const float f ) : value( ts_vec3( f ) ) {}
vec3Value( const ts_vec3 f ) : value( f ) {}
ts_vec3 value = ts_vec3( 1e-32f ); // default value if map is absent; 1e-32 means: not set
float dummy; // because ts_vec3 is 12 bytes.
int textureID = -1; // texture ID; 'value'field is used if -1
float scale = 1; // map values will be scaled by this
ts_vec2 uvscale = ts_vec2( 1 ); // uv coordinate scale
ts_vec2 uvoffset = ts_vec2( 0 ); // uv coordinate offset
ts_uint2 size = ts_uint2( 0 ); // texture dimensions
// a parameter that has not been specified has a -1 textureID and a 1e-32f value
bool Specified() { return value.x != 1e32f || value.y != 1e32f || value.z != 1e32f || textureID != -1; }
ts_vec3& operator()() { return value; }
};
struct ScalarValue
{
ScalarValue() = default;
ScalarValue( const float f ) : value( f ) {}
float value = 1e-32f; // default value if map is absent; 1e32 means: not set
int textureID = -1; // texture ID; -1 denotes empty slot
int component = 0; // 0 = x, 1 = y, 2 = z, 3 = w
float scale = 1; // map values will be scaled by this
ts_vec2 uvscale = ts_vec2( 1 ); // uv coordinate scale
ts_vec2 uvoffset = ts_vec2( 0 ); // uv coordinate offset
ts_uint2 size = ts_uint2( 0 ); // texture dimensions
bool Specified() { return value != 1e32f || textureID != -1; }
float& operator()() { return value; }
};
enum
{
SMOOTH = 1, // material uses normal interpolation
FROM_MTL = 4, // changes are persistent for these, not for others
SINGLE_COLOR_COPY = 8 // material was created for a tri that uses a single texel
};
// constructor / destructor
Material() = default;
// methods
void ConvertFrom( const ::tinyobj::material_t& );
void ConvertFrom( const ::tinygltf::Material&, const ::std::vector<int>& texIdx );
bool IsEmissive() { ts_vec3& c = color(); return c.x > 1 || c.y > 1 || c.z > 1; /* ignores vec3map */ }
// material properties
vec3Value color = vec3Value( 1 ); // universal material property: base color
vec3Value detailColor; // universal material property: detail texture
vec3Value normals; // universal material property: normal map
vec3Value detailNormals; // universal material property: detail normal map
uint32_t flags = SMOOTH; // material flags: default is SMOOTH
// Disney BRDF properties: data for the Disney Principled BRDF
vec3Value absorption;
ScalarValue metallic, subsurface, specular, roughness, specularTint, anisotropic;
ScalarValue sheen, sheenTint, clearcoat, clearcoatGloss, transmission, eta;
// Lambert BSDF properties, augmented with pure specular reflection and refraction
// FloatValue absorption; // shared with disney brdf
ScalarValue reflection, refraction, ior;
// identifier and name
::std::string name = "unnamed"; // material name, not for unique identification
::std::string origin; // origin: file from which the data was loaded, with full path
int ID = -1; // unique integer ID of this material
uint32_t refCount = 1; // the number of models that use this material
// field for the BuildMaterialList method of Mesh
bool visited = false; // last mesh that checked this material
// internal
private:
uint32_t prevFlags = SMOOTH; // initially identical to flags
};
// +-----------------------------------------------------------------------------+
// | Material |
// | Material definition. This is the version for actual rendering; it stores |
// | a subset of the full data of a Material. LH2'24|
// +-----------------------------------------------------------------------------+
class RenderMaterial
{
enum
{
HASDIFFUSEMAP = 1,
HASNORMALMAP = 2,
ISDIELECTRIC = 4,
HASSPECULARITYMAP = 8,
HASROUGHNESSMAP = 16,
HAS2NDNORMALMAP = 32,
HAS2NDDIFFUSEMAP = 64,
HASSMOOTHNORMALS = 128,
HASALPHA = 256,
DIFFUSEMAPISHDR = 512
};
struct Map { short width, height; uint16_t uscale, vscale, uoffs, voffs; uint32_t addr; };
public:
RenderMaterial( const Material* source, const ::std::vector<int>& offsets );
Map MakeMap( Material::vec3Value source, const ::std::vector<int>& offsets );
void SetDiffuse( ts_vec3 d );
void SetTransmittance( ts_vec3 t );
uint16_t diffuse_r, diffuse_g, diffuse_b, transmittance_r, transmittance_g, transmittance_b;
uint32_t flags;
ts_uint4 parameters; // 16 Disney principled BRDF parameters, 0.8 fixed point
Map tex0, tex1, nmap0, nmap1, smap, rmap; // total Material size: 128 bytes
};
// +-----------------------------------------------------------------------------+
// | Animation |
// | Animation definition. LH2'24|
// +-----------------------------------------------------------------------------+
class Animation
{
class Sampler
{
public:
enum { LINEAR = 0, SPLINE, STEP };
Sampler( const ::tinygltf::AnimationSampler& gltfSampler, const ::tinygltf::Model& gltfModel );
void ConvertFromGLTFSampler( const ::tinygltf::AnimationSampler& gltfSampler, const ::tinygltf::Model& gltfModel );
float SampleFloat( float t, int k, int i, int count ) const;
ts_vec3 SampleVec3( float t, int k ) const;
ts_quat SampleQuat( float t, int k ) const;
::std::vector<float> t; // key frame times
::std::vector<ts_vec3> vec3Key; // vec3 key frames (location or scale)
::std::vector<ts_quat> vec4Key; // vec4 key frames (rotation)
::std::vector<float> floatKey; // float key frames (weight)
int interpolation; // interpolation type: linear, spline, step
};
class Channel
{
public:
Channel( const ::tinygltf::AnimationChannel& gltfChannel, const int nodeBase );
int samplerIdx; // sampler used by this channel
int nodeIdx; // index of the node this channel affects
int target; // 0: translation, 1: rotation, 2: scale, 3: weights
void Reset() { t = 0, k = 0; }
void SetTime( const float v ) { t = v, k = 0; }
void Update( const float t, const Sampler* sampler ); // apply this channel to the target nde for time t
void ConvertFromGLTFChannel( const ::tinygltf::AnimationChannel& gltfChannel, const int nodeBase );
// data
float t = 0; // animation timer
int k = 0; // current keyframe
};
public:
Animation( ::tinygltf::Animation& gltfAnim, ::tinygltf::Model& gltfModel, const int nodeBase );
::std::vector<Sampler*> sampler; // animation samplers
::std::vector<Channel*> channel; // animation channels
void Reset(); // reset all channels
void SetTime( const float t );
void Update( const float dt ); // advance and apply all channels
void ConvertFromGLTFAnim( ::tinygltf::Animation& gltfAnim, ::tinygltf::Model& gltfModel, const int nodeBase );
};
// +-----------------------------------------------------------------------------+
// | Texture |
// | Stores a texture, with either integer or floating point data. |
// | Policy regarding texture reuse: |
// | - The owner of the textures is the scene. |
// | - Multiple materials may use a texture. A refCount keeps track of this. |
// | - A file name does not uniquely identify a texture: the file may be |
// | different between folders, and the texture may have been loaded with |
// | 'modFlags'. Instead, a texture is uniquely identified by its full file |
// | name, including path, as well as the mods field. LH2'24|
// +-----------------------------------------------------------------------------+
class Texture
{
public:
enum
{
NORMALMAP = 2, // this texture is a normal map
LDR = 4, // this texture stores integer pixels in Texture::idata
HDR = 8 // this texture stores float pixels in Texture::fdata
};
enum { LINEARIZED = 1, FLIPPED = 2 };
// constructor / destructor / conversion
Texture() = default;
Texture( const char* fileName, const uint32_t modFlags = 0 );
// methods
bool Equals( const ::std::string& o, const uint32_t m );
void Load( const char* fileName, const uint32_t modFlags, bool normalMap = false );
static void sRGBtoLinear( unsigned char* pixels, const uint32_t size, const uint32_t stride );
void BumpToNormalMap( float heightScale );
uint32_t* GetLDRPixels() { return (uint32_t*)idata; }
ts_vec4* GetHDRPixels() { return fdata; }
// internal methods
int PixelsNeeded( int w, int h, const int l ) const;
void ConstructMIPmaps();
// public properties
public:
uint32_t width = 0, height = 0; // width and height in pixels
uint32_t MIPlevels = 1; // number of MIPmaps
uint32_t ID = 0; // unique integer ID of this texture
::std::string name; // texture name, not for unique identification
::std::string origin; // origin: file from which the data was loaded, with full path
uint32_t flags = 0; // flags
uint32_t mods = 0; // modifications to original data
uint32_t refCount = 1; // the number of materials that use this texture
ts_uchar4* idata = nullptr; // pointer to a 32-bit ARGB bitmap
ts_vec4* fdata = nullptr; // pointer to a 128-bit ARGB bitmap
};
// +-----------------------------------------------------------------------------+
// | TriLight |
// | Light triangle. LH2'24|
// +-----------------------------------------------------------------------------+
class TriLight
{
public:
// constructor / destructor
TriLight() = default;
TriLight( FatTri* origTri, int origIdx, int origInstance );
// data members
int triIdx = 0; // the index of the triangle this ltri is based on
int instIdx = 0; // the instance to which this triangle belongs
ts_vec3 vertex0 = { 0 }; // vertex 0 position
ts_vec3 vertex1 = { 0 }; // vertex 1 position
ts_vec3 vertex2 = { 0 }; // vertex 2 position
ts_vec3 centre = { 0 }; // barycenter of the triangle
ts_vec3 radiance = { 0 }; // radiance per unit area
ts_vec3 N = ts_vec3( 0, -1, 0 ); // geometric triangle normal
float area = 0; // triangle area
float energy = 0; // total radiance
};
// +-----------------------------------------------------------------------------+
// | PointLight |
// | Point light definition. LH2'24|
// +-----------------------------------------------------------------------------+
class PointLight
{
public:
// constructor / destructor
PointLight() = default;
// data members
ts_vec3 position = { 0 }; // position of the point light
ts_vec3 radiance = { 0 }; // emitted radiance
int ID = 0; // position in Scene::pointLights
};
// +-----------------------------------------------------------------------------+
// | SpotLight |
// | Spot light definition. LH2'19|
// +-----------------------------------------------------------------------------+
class SpotLight
{
public:
// constructor / destructor
SpotLight() = default;
// data members
ts_vec3 position = { 0 }; // position of the spot light
float cosInner = 0; // cosine of the inner boundary
ts_vec3 radiance = { 0 }; // emitted radiance
float cosOuter = 0; // cosine of the outer boundary
ts_vec3 direction = ts_vec3( 0, -1, 0 ); // spot light direction
int ID = 0; // position in Scene::spotLights
};
// +-----------------------------------------------------------------------------+
// | DirectionalLight |
// | Directional light definition. LH2'24|
// +-----------------------------------------------------------------------------+
class DirectionalLight
{
public:
// constructor / destructor
DirectionalLight() = default;
// data members
ts_vec3 direction = ts_vec3( 0, -1, 0 );
ts_vec3 radiance = { 0 };
int ID = 0;
};
// +-----------------------------------------------------------------------------+
// | Scene |
// | Module for scene I/O and host-side management. |
// | This is a pure static class; we will not have more than one scene. LH2'24|
// +-----------------------------------------------------------------------------+
class Scene
{
public:
// constructor / destructor
Scene() = default;
~Scene();
// methods
static void Init() { /* nothing here for now */ }
static void SetSkyDome( SkyDome* skydome ) { sky = skydome; }
static int FindOrCreateTexture( const ::std::string& origin, const uint32_t modFlags = 0 );
static int FindTextureID( const char* name );
static int CreateTexture( const ::std::string& origin, const uint32_t modFlags = 0 );
static int FindOrCreateMaterial( const ::std::string& name );
static int FindOrCreateMaterialCopy( const int matID, const uint32_t color );
static int FindMaterialID( const char* name );
static int FindMaterialIDByOrigin( const char* name );
static int FindNextMaterialID( const char* name, const int matID );
static int FindNode( const char* name );
static void SetNodeTransform( const int nodeId, const ts_mat4& transform );
static const ts_mat4& GetNodeTransform( const int nodeId );
static void ResetAnimation( const int animId );
static void UpdateAnimation( const int animId, const float dt );
static int AnimationCount() { return (int)animations.size(); }
// scene construction / maintenance
static int AddMesh( Mesh* mesh );
static int AddMesh( const char* objFile, const char* dir, const float scale = 1.0f, const bool flatShaded = false );
static int AddMesh( const char* objFile, const float scale = 1.0f, const bool flatShaded = false );
static int AddScene( const char* sceneFile, const ts_mat4& transform = ts_mat4() );
static int AddScene( const char* sceneFile, const char* dir, const ts_mat4& transform );
static int AddMesh( const int triCount );
static void AddTriToMesh( const int meshId, const ts_vec3& v0, const ts_vec3& v1, const ts_vec3& v2, const int matId );
static int AddQuad( const ts_vec3 N, const ts_vec3 pos, const float width, const float height, const int matId, const int meshID = -1 );
static int AddNode( Node* node );
static int AddChildNode( const int parentNodeId, const int childNodeId );
static int GetChildId( const int parentId, const int childIdx );
static int AddInstance( const int nodeId );
static void RemoveNode( const int instId );
static int AddMaterial( Material* material );
static int AddMaterial( const ts_vec3 color, const char* name = 0 );
static int AddPointLight( const ts_vec3 pos, const ts_vec3 radiance );
static int AddSpotLight( const ts_vec3 pos, const ts_vec3 direction, const float inner, const float outer, const ts_vec3 radiance );
static int AddDirectionalLight( const ts_vec3 direction, const ts_vec3 radiance );
static void UpdateSceneGraph( const float deltaTime );
// data members
static inline ::std::vector<int> rootNodes; // root node indices of loaded (or instanced) objects
static inline ::std::vector<Node*> nodePool; // all scene nodes
static inline ::std::vector<Mesh*> meshPool; // all scene meshes
static inline ::std::vector<Skin*> skins; // all scene skins
static inline ::std::vector<Animation*> animations; // all scene animations
static inline ::std::vector<Material*> materials; // all scene materials
static inline ::std::vector<Texture*> textures; // all scene textures
static inline ::std::vector<TriLight*> triLights; // light emitting triangles
static inline ::std::vector<PointLight*> pointLights; // scene point lights
static inline ::std::vector<SpotLight*> spotLights; // scene spot lights
static inline ::std::vector<DirectionalLight*> directionalLights; // scene directional lights
static inline SkyDome* sky; // HDR skydome
};
} // namespace tinyscene
// ============================================================================
//
// I M P L E M E N T A T I O N
//
// ============================================================================
#ifdef TINYSCENE_IMPLEMENTATION
// error handling
#define SCENE_FATAL_ERROR(s) { SCENE_FATAL_ERROR_IF(1,(s)) }
#ifdef _WINDOWS_ // windows.h has been included
#define SCENE_FATAL_ERROR_IF(c,s) { if (c) { char t[512]; sprintf( t, \
"Fatal error in tiny_bvh.h, line %i:\n%s\n", __LINE__, s ); \
MessageBox( NULL, t, "Fatal error", MB_OK ); exit( 1 ); } }
#else
#define SCENE_FATAL_ERROR_IF(c,s) if (c) { fprintf( stderr, \
"Fatal error in tiny_bvh.h, line %i:\n%s\n", __LINE__, s ); exit( 1 ); }
#endif
namespace tinyscene {
// basic vector math operations
ts_mat4 operator*( const float s, const ts_mat4& a )
{
ts_mat4 r;
for (uint32_t i = 0; i < 16; i++) r.cell[i] = a.cell[i] * s;
return r;
}
ts_mat4 operator*( const ts_mat4& a, const ts_mat4& b )
{
ts_mat4 r;
for (uint32_t i = 0; i < 16; i += 4) for (uint32_t j = 0; j < 4; ++j)
r[i + j] = (a[i + 0] * b[j + 0]) + (a[i + 1] * b[j + 4]) +
(a[i + 2] * b[j + 8]) + (a[i + 3] * b[j + 12]);
return r;
}
inline float ts_dot( const ts_vec2& a, const ts_vec2& b ) { return a.x * b.x + a.y * b.y; }
inline float ts_dot( const ts_vec3& a, const ts_vec3& b ) { return a.x * b.x + a.y * b.y + a.z * b.z; }
inline float ts_dot( const ts_vec4& a, const ts_vec4& b ) { return a.x * b.x + a.y * b.y + a.z * b.z + a.w * b.w; }
inline ts_vec3 ts_cross( const ts_vec3& a, const ts_vec3& b ) { return ts_vec3( a.y * b.z - a.z * b.y, a.z * b.x - a.x * b.z, a.x * b.y - a.y * b.x ); }
inline float ts_length( const ts_vec3& a ) { return sqrtf( a.x * a.x + a.y * a.y + a.z * a.z ); }
inline ts_vec3 ts_normalize( const ts_vec3& a )
{
float l = ts_length( a ), rl = l == 0 ? 0 : (1.0f / l);
return a * rl;
}
inline ts_vec3 ts_transform_point( const ts_vec3& v, const ts_mat4& T )
{
const ts_vec3 res(
T[0] * v.x + T[1] * v.y + T[2] * v.z + T[3],
T[4] * v.x + T[5] * v.y + T[6] * v.z + T[7],
T[8] * v.x + T[9] * v.y + T[10] * v.z + T[11] );
const float w = T[12] * v.x + T[13] * v.y + T[14] * v.z + T[15];
if (w == 1) return res; else return res * (1.f / w);
}
inline ts_vec3 ts_transform_vector( const ts_vec3& v, const ts_mat4& T )
{
return ts_vec3( T[0] * v.x + T[1] * v.y + T[2] * v.z, T[4] * v.x +
T[5] * v.y + T[6] * v.z, T[8] * v.x + T[9] * v.y + T[10] * v.z );
}
inline float ts_min( const float a, const float b ) { return a < b ? a : b; }
inline float ts_max( const float a, const float b ) { return a > b ? a : b; }
inline ts_vec3 ts_min( const ts_vec3& a, const ts_vec3& b ) { return ts_vec3( ts_min( a.x, b.x ), ts_min( a.y, b.y ), ts_min( a.z, b.z ) ); }
inline ts_vec3 ts_max( const ts_vec3& a, const ts_vec3& b ) { return ts_vec3( ts_max( a.x, b.x ), ts_max( a.y, b.y ), ts_max( a.z, b.z ) ); }
// basic 16-bit float support
static uint32_t ts_as_uint( const float x ) { return *(uint32_t*)&x; }
float ts_as_float( const uint32_t x ) { return *(float*)&x; }
float ts_half_to_float( const uint16_t x ) {
const uint32_t e = (x & 0x7C00) >> 10, m = (x & 0x03FF) << 13, v = ts_as_uint( (float)m ) >> 23;
return ts_as_float( (x & 0x8000) << 16 | (e != 0) * ((e + 112) << 23 | m) | ((e == 0) & (m != 0)) *
((v - 37) << 23 | ((m << (150 - v)) & 0x007FE000)) );
}
uint16_t ts_float_to_half( const float x )
{
const uint32_t b = ts_as_uint( x ) + 0x00001000, e = (b & 0x7F800000) >> 23, m = b & 0x007FFFFF;
return (uint16_t)((b & 0x80000000) >> 16 | (e > 112) * ((((e - 112) << 10) & 0x7C00) | m >> 13) |
((e < 113) & (e > 101)) * ((((0x007FF000 + m) >> (125 - e)) + 1) >> 1) | (e > 143) * 0x7FFF);
}
// ts_vec4::ts_vec4( const ts_vec3& a ) { x = a.x, y = a.y, z = a.z, w = 0; }
// ts_vec4::ts_vec4( const ts_vec3& a, const float b ) { x = a.x, y = a.y, z = a.z, w = b; }
void ts_aabb::grow( const ts_vec3& p )
{
bmin = ts_min( bmin, p );
bmax = ts_max( bmin, p );
}
ts_mat4 ts_mat4::inverted() const
{
// from MESA, via http://stackoverflow.com/questions/1148309/inverting-a-4x4-matrix
const float inv[16] = {
cell[5] * cell[10] * cell[15] - cell[5] * cell[11] * cell[14] - cell[9] * cell[6] * cell[15] +
cell[9] * cell[7] * cell[14] + cell[13] * cell[6] * cell[11] - cell[13] * cell[7] * cell[10],
-cell[1] * cell[10] * cell[15] + cell[1] * cell[11] * cell[14] + cell[9] * cell[2] * cell[15] -
cell[9] * cell[3] * cell[14] - cell[13] * cell[2] * cell[11] + cell[13] * cell[3] * cell[10],
cell[1] * cell[6] * cell[15] - cell[1] * cell[7] * cell[14] - cell[5] * cell[2] * cell[15] +
cell[5] * cell[3] * cell[14] + cell[13] * cell[2] * cell[7] - cell[13] * cell[3] * cell[6],
-cell[1] * cell[6] * cell[11] + cell[1] * cell[7] * cell[10] + cell[5] * cell[2] * cell[11] -
cell[5] * cell[3] * cell[10] - cell[9] * cell[2] * cell[7] + cell[9] * cell[3] * cell[6],
-cell[4] * cell[10] * cell[15] + cell[4] * cell[11] * cell[14] + cell[8] * cell[6] * cell[15] -
cell[8] * cell[7] * cell[14] - cell[12] * cell[6] * cell[11] + cell[12] * cell[7] * cell[10],
cell[0] * cell[10] * cell[15] - cell[0] * cell[11] * cell[14] - cell[8] * cell[2] * cell[15] +
cell[8] * cell[3] * cell[14] + cell[12] * cell[2] * cell[11] - cell[12] * cell[3] * cell[10],
-cell[0] * cell[6] * cell[15] + cell[0] * cell[7] * cell[14] + cell[4] * cell[2] * cell[15] -
cell[4] * cell[3] * cell[14] - cell[12] * cell[2] * cell[7] + cell[12] * cell[3] * cell[6],
cell[0] * cell[6] * cell[11] - cell[0] * cell[7] * cell[10] - cell[4] * cell[2] * cell[11] +
cell[4] * cell[3] * cell[10] + cell[8] * cell[2] * cell[7] - cell[8] * cell[3] * cell[6],
cell[4] * cell[9] * cell[15] - cell[4] * cell[11] * cell[13] - cell[8] * cell[5] * cell[15] +
cell[8] * cell[7] * cell[13] + cell[12] * cell[5] * cell[11] - cell[12] * cell[7] * cell[9],
-cell[0] * cell[9] * cell[15] + cell[0] * cell[11] * cell[13] + cell[8] * cell[1] * cell[15] -
cell[8] * cell[3] * cell[13] - cell[12] * cell[1] * cell[11] + cell[12] * cell[3] * cell[9],
cell[0] * cell[5] * cell[15] - cell[0] * cell[7] * cell[13] - cell[4] * cell[1] * cell[15] +
cell[4] * cell[3] * cell[13] + cell[12] * cell[1] * cell[7] - cell[12] * cell[3] * cell[5],
-cell[0] * cell[5] * cell[11] + cell[0] * cell[7] * cell[9] + cell[4] * cell[1] * cell[11] -
cell[4] * cell[3] * cell[9] - cell[8] * cell[1] * cell[7] + cell[8] * cell[3] * cell[5],
-cell[4] * cell[9] * cell[14] + cell[4] * cell[10] * cell[13] + cell[8] * cell[5] * cell[14] -
cell[8] * cell[6] * cell[13] - cell[12] * cell[5] * cell[10] + cell[12] * cell[6] * cell[9],
cell[0] * cell[9] * cell[14] - cell[0] * cell[10] * cell[13] - cell[8] * cell[1] * cell[14] +
cell[8] * cell[2] * cell[13] + cell[12] * cell[1] * cell[10] - cell[12] * cell[2] * cell[9],
-cell[0] * cell[5] * cell[14] + cell[0] * cell[6] * cell[13] + cell[4] * cell[1] * cell[14] -
cell[4] * cell[2] * cell[13] - cell[12] * cell[1] * cell[6] + cell[12] * cell[2] * cell[5],
cell[0] * cell[5] * cell[10] - cell[0] * cell[6] * cell[9] - cell[4] * cell[1] * cell[10] +
cell[4] * cell[2] * cell[9] + cell[8] * cell[1] * cell[6] - cell[8] * cell[2] * cell[5]
};
const float det = cell[0] * inv[0] + cell[1] * inv[4] + cell[2] * inv[8] + cell[3] * inv[12];
ts_mat4 retVal;
if (det != 0)
{
const float invdet = 1.0f / det;
for (int i = 0; i < 16; i++) retVal.cell[i] = inv[i] * invdet;
}
return retVal;
}
ts_mat4 ts_quat::toMatrix() const
{
ts_mat4 ret;
ret.cell[0] = 1 - 2 * y * y - 2 * z * z;
ret.cell[1] = 2 * x * y - 2 * w * z, ret.cell[2] = 2 * x * z + 2 * w * y, ret.cell[4] = 2 * x * y + 2 * w * z;
ret.cell[5] = 1 - 2 * x * x - 2 * z * z;
ret.cell[6] = 2 * y * z - 2 * w * x, ret.cell[8] = 2 * x * z - 2 * w * y, ret.cell[9] = 2 * y * z + 2 * w * x;
ret.cell[10] = 1 - 2 * x * x - 2 * y * y;
return ret;
}
ts_quat ts_quat::slerp( const ts_quat& a, const ts_quat& b, const float t )
{
// from GLM, via blog.magnum.graphics/backstage/the-unnecessarily-short-ways-to-do-a-quaternion-slerp
ts_quat r = b;
float cosTheta = a.w * r.w + a.x * r.x + a.y * r.y + a.z * r.z;
if (cosTheta < 0) r = r * -1.0f, cosTheta = -cosTheta;
if (cosTheta > 0.99f)
{
// Linear interpolation
r.w = (1 - t) * a.w + t * r.w, r.x = (1 - t) * a.x + t * r.x;
r.y = (1 - t) * a.y + t * r.y, r.z = (1 - t) * a.z + t * r.z;
}
else
{
float angle = acosf( cosTheta );
float s1 = sinf( (1 - t) * angle ), s2 = sinf( t * angle ), rs3 = 1.0f / sinf( angle );
r.w = (s1 * a.w + s2 * r.w) * rs3, r.x = (s1 * a.x + s2 * r.x) * rs3;
r.y = (s1 * a.y + s2 * r.y) * rs3, r.z = (s1 * a.z + s2 * r.z) * rs3;
}
return r;
}
void FatTri::UpdateArea()
{
const float a = ts_length( vertex1 - vertex0 ), b = ts_length( vertex2 - vertex1 );
const float c = ts_length( vertex0 - vertex2 ), s = (a + b + c) * 0.5f;
area = sqrtf( s * (s - a) * (s - b) * (s - c) ); // Heron's formula
}
void RenderMaterial::SetDiffuse( ts_vec3 d )
{
diffuse_r = ts_float_to_half( d.x );
diffuse_g = ts_float_to_half( d.y );
diffuse_b = ts_float_to_half( d.z );
}
void RenderMaterial::SetTransmittance( ts_vec3 t )
{
transmittance_r = ts_float_to_half( t.x );
transmittance_g = ts_float_to_half( t.y );
transmittance_b = ts_float_to_half( t.z );
}
#ifdef _WIN32
#include <direct.h>
#define getcwd _getcwd // stupid MSFT "deprecation" warning
#define chdir _chdir
#elif
#include <unistd.h>
#endif
// 'declaration of x hides previous local declaration'
#pragma warning( disable: 4456)
// bring std
using namespace ::std;
// +-----------------------------------------------------------------------------+
// | SkyDome::Load |
// | Load a skydome. LH2'24|
// +-----------------------------------------------------------------------------+
void SkyDome::Load( const char* filename, const ts_vec3 scale )
{