-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsofren.c
More file actions
5451 lines (4588 loc) · 195 KB
/
sofren.c
File metadata and controls
5451 lines (4588 loc) · 195 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
#ifndef SFR_H
#define SFR_H
#ifdef __cplusplus
extern "C" {
#endif
//================================================
//: PUBLIC API
//================================================
#ifndef SFR_MAX_WIDTH
#define SFR_MAX_WIDTH 1280
#endif
#ifndef SFR_MAX_HEIGHT
#define SFR_MAX_HEIGHT 720
#endif
//: threading config
#ifdef SFR_THREAD_COUNT
#if SFR_THREAD_COUNT < 1 || SFR_THREAD_COUNT > 32
#error "SFR ERROR: SFR_THREAD_COUNT must be between 1 and 32 (32 arbitrary)"
#endif
#else
#define SFR_THREAD_COUNT 1
#endif
#if SFR_THREAD_COUNT > 1
#define SFR_MULTITHREADED
#ifndef SFR_TILE_WIDTH
#define SFR_TILE_WIDTH 64
#endif
#ifndef SFR_TILE_HEIGHT
#define SFR_TILE_HEIGHT 64
#endif
#define SFR_TILE_DIM (SFR_TILE_WIDTH * SFR_TILE_HEIGHT)
#ifndef SFR_GEOMETRY_JOB_SIZE
// number of triangles per geometry job
#define SFR_GEOMETRY_JOB_SIZE 64
#endif
#ifndef SFR_BIN_PAGE_SIZE
// number of triangles per page
#define SFR_BIN_PAGE_SIZE 4096
#endif
#endif
#ifdef SFR_MULTITHREADED
#ifdef _WIN32
#ifndef _WIN32_WINNT
// for CreateSemaphoreEx
#define _WIN32_WINNT 0x0600
#endif
#define NOGDI
#define NOUSER
#define NOMINMAX
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#ifdef near
#undef near
#endif
#ifdef far
#undef far
#endif
#include <process.h> // for _beginthreadex
typedef HANDLE SfrThread;
typedef HANDLE SfrSemaphore;
typedef CRITICAL_SECTION SfrMutex;
typedef volatile LONG SfrAtomic32;
typedef volatile LONG64 SfrAtomic64;
#else
#include <pthread.h>
#include <semaphore.h>
#include <sched.h> // for sched_yield
#include <errno.h>
typedef pthread_t SfrThread;
typedef sem_t SfrSemaphore;
typedef pthread_mutex_t SfrMutex;
typedef volatile int SfrAtomic32;
typedef volatile long long SfrAtomic64;
#endif
#ifndef SFR_THREAD_LOCAL
#if defined(_MSC_VER)
#define SFR_THREAD_LOCAL __declspec(thread)
#elif defined(__GNUC__) || defined(__clang__)
#define SFR_THREAD_LOCAL __thread
#else
#define SFR_THREAD_LOCAL _Thread_local
#endif
#endif
#else
#define SfrAtomic32 i32
#define SfrAtomic64 i64
#endif
//: types
#ifdef SFR_PREFIXED_TYPES
#define i8 sfri8_t
#define u8 sfru8_t
#define i16 sfri16_t
#define u16 sfru16_t
#define i32 sfri32_t
#define u32 sfru32_t
#define i64 sfri64_t
#define u64 sfru64_t
#define f32 sfrf32_t
#define f64 sfrf64_t
#endif
#ifndef SFR_NO_STDINT
#include <stdint.h>
typedef int8_t i8;
typedef uint8_t u8;
typedef int16_t i16;
typedef uint16_t u16;
typedef int32_t i32;
typedef uint32_t u32;
typedef int64_t i64;
typedef uint64_t u64;
#else
typedef signed char i8;
typedef unsigned char u8;
typedef signed short i16;
typedef unsigned short u16;
typedef signed int i32;
typedef unsigned int u32;
typedef signed long long i64;
typedef unsigned long long u64;
#endif
typedef float f32;
typedef double f64;
typedef union sfrvec sfrvec;
typedef union sfrmat sfrmat;
typedef struct sfrmesh SfrMesh;
typedef struct sfrtex SfrTexture;
typedef struct sfrfont SfrFont;
typedef struct sfrScene SfrScene;
typedef struct sfrSceneObject SfrSceneObject;
typedef struct sfrRayHit SfrRayHit;
typedef struct sfrParticle SfrParticle;
typedef struct sfrParticles SfrParticleSystem;
typedef struct sfrlight SfrLight;
#ifdef SFR_USE_CGLTF
typedef struct sfrModel SfrModel;
#endif
//: extern variables
extern i32 sfrWidth, sfrHeight;
extern u32* sfrPixelBuf;
extern f32* sfrDepthBuf;
extern SfrLight sfrLight;
// variables below can be managed by you, however
// there is probably a function that will do what you want
extern SfrAtomic32 sfrRasterCount; // how many triangles have been rasterized since the last call to clear
extern sfrmat sfrMatModel, sfrMatView, sfrMatProj;
extern sfrvec sfrCamPos, sfrCamUp, sfrCamTarget;
extern f32 sfrCamFov;
extern f32 sfrNearDist, sfrFarDist;
#if defined(SFR_FUNC) && defined(SFR_USE_INLINE) && !defined(SFR_NO_WARNINGS)
#warning "SFR WARNING: SFR_FUNC and SFR_USE_INLINE both being defined is contradictory, using SFR_FUNC"
#endif
#ifndef SFR_FUNC
#ifdef SFR_USE_INLINE
#define SFR_FUNC static inline
#else
#define SFR_FUNC static
#endif
#endif
#ifndef SFR_SQRT_ACCURACY
#define SFR_SQRT_ACCURACY 20
#endif
#ifndef SFR_TRIG_ACCURACY
#define SFR_TRIG_ACCURACY 10
#endif
#ifndef SFR_FONT_GLYPH_MAX
#define SFR_FONT_GLYPH_MAX 512
#endif
#ifndef SFR_FONT_VERT_MAX
// 72 verts max == 12 tris max
#define SFR_FONT_VERT_MAX 72
#endif
#define SFR_FONT_VERT_EMPTY 1234321
//: math functions
SFR_FUNC sfrvec sfr_vec_add(sfrvec a, sfrvec b);
SFR_FUNC sfrvec sfr_vec_sub(sfrvec a, sfrvec b);
SFR_FUNC sfrvec sfr_vec_mul(sfrvec a, f32 b);
SFR_FUNC sfrvec sfr_vec_div(sfrvec a, f32 b);
SFR_FUNC f32 sfr_vec_dot(sfrvec a, sfrvec b);
SFR_FUNC f32 sfr_vec_length(sfrvec v);
SFR_FUNC f32 sfr_vec_length2(sfrvec v);
SFR_FUNC sfrvec sfr_vec_cross(sfrvec a, sfrvec b);
SFR_FUNC sfrvec sfr_vec_norm(sfrvec v);
SFR_FUNC sfrvec sfr_vec_normf(f32 x, f32 y, f32 z);
SFR_FUNC sfrvec sfr_vec_face_normal(sfrvec a, sfrvec b, sfrvec c);
SFR_FUNC sfrvec sfr_vec_lerp(sfrvec a, sfrvec b, f32 t);
SFR_FUNC sfrmat sfr_mat_identity();
SFR_FUNC sfrmat sfr_mat_rot_x(f32 a);
SFR_FUNC sfrmat sfr_mat_rot_y(f32 a);
SFR_FUNC sfrmat sfr_mat_rot_z(f32 a);
SFR_FUNC sfrmat sfr_mat_translate(f32 x, f32 y, f32 z);
SFR_FUNC sfrmat sfr_mat_scale(f32 x, f32 y, f32 z);
SFR_FUNC sfrmat sfr_mat_proj(f32 fovDeg, f32 aspect, f32 near, f32 far);
SFR_FUNC sfrmat sfr_mat_mul(sfrmat a, sfrmat b);
SFR_FUNC sfrvec sfr_mat_mul_vec(sfrmat m, sfrvec v);
SFR_FUNC sfrmat sfr_mat_qinv(sfrmat m);
SFR_FUNC sfrmat sfr_mat_look_at(sfrvec pos, sfrvec target, sfrvec up);
SFR_FUNC void sfr_mat_decompose(sfrmat m, sfrvec* pos, sfrvec* rot, sfrvec* scale);
SFR_FUNC sfrmat sfr_mat_from_quat(sfrvec q);
SFR_FUNC sfrvec sfr_quat_mul(sfrvec a, sfrvec b);
SFR_FUNC sfrvec sfr_quat_slerp(sfrvec a, sfrvec b, f32 t);
//: core functions
SFR_FUNC void sfr_init(i32 w, i32 h, f32 fovDeg,
void* (*mallocFunc)(u64), void (*freeFunc)(void*), void* (*reallocFunc)(void*, u64));
SFR_FUNC void sfr_release(void);
// finish rendering triangles, must be called for any thread count
SFR_FUNC void sfr_flush_and_wait(void);
SFR_FUNC void sfr_resize(i32 width, i32 height); // resize internals to new dimensions
SFR_FUNC void sfr_reset(void); // reset model matrix to identity
SFR_FUNC void sfr_rotate_x(f32 theta); // rotate model matrix about x by theta radians
SFR_FUNC void sfr_rotate_y(f32 theta); // rotate model matrix about y by theta radians
SFR_FUNC void sfr_rotate_z(f32 theta); // rotate model matrix about z by theta radians
SFR_FUNC void sfr_translate(f32 x, f32 y, f32 z); // translate model matrix by x y z
SFR_FUNC void sfr_scale(f32 x, f32 y, f32 z); // scale model matrix by x y z
SFR_FUNC void sfr_look_at(f32 x, f32 y, f32 z); // set view matrix to look at x y z
// clear all buffers to default states
SFR_FUNC void sfr_clear(u32 clearCol);
SFR_FUNC void sfr_clear_depth(void);
// texture order: front, right, back, left, top, bottom
SFR_FUNC void sfr_skybox(const SfrTexture* faces[6]);
// triangle drawing functions
SFR_FUNC void sfr_triangle(
f32 ax, f32 ay, f32 az,
f32 bx, f32 by, f32 bz,
f32 cx, f32 cy, f32 cz,
u32 col);
SFR_FUNC void sfr_triangle_tex(
f32 ax, f32 ay, f32 az, f32 au, f32 av,
f32 bx, f32 by, f32 bz, f32 bu, f32 bv,
f32 cx, f32 cy, f32 cz, f32 cu, f32 cv,
u32 col, const SfrTexture* tex);
// other drawing functions, if tex is null sfrState.baseTex (white 1x1 texture) will be used
SFR_FUNC void sfr_point(f32 worldX, f32 worldY, f32 worldZ, i32 radius, u32 col);
SFR_FUNC void sfr_billboard(u32 col, const SfrTexture* tex);
SFR_FUNC void sfr_cube(u32 col, const SfrTexture* tex);
SFR_FUNC void sfr_cube_ex(u32 col[12]);
SFR_FUNC void sfr_mesh(const SfrMesh* mesh, u32 col, const SfrTexture* tex);
SFR_FUNC void sfr_string(const SfrFont* font, const char* s, i32 sLength, u32 col); // not yet implemented
SFR_FUNC void sfr_glyph(const SfrFont* font, u16 id, u32 col); // draw a single character
// static scene functions
SFR_FUNC SfrScene* sfr_scene_create(SfrSceneObject* objects, i32 count);
SFR_FUNC void sfr_scene_release(SfrScene** scene, u8 freeObjects);
SFR_FUNC void sfr_scene_draw(const SfrScene* scene);
SFR_FUNC SfrRayHit sfr_scene_raycast(const SfrScene* scene, f32 ox, f32 oy, f32 oz, f32 dx, f32 dy, f32 dz);
// project the world position specified to screen coordinates
SFR_FUNC u8 sfr_world_to_screen(f32 x, f32 y, f32 z, i32* screenX, i32* screenY);
// update the camera with the new position and view
SFR_FUNC void sfr_set_camera(f32 x, f32 y, f32 z, f32 yaw, f32 pitch, f32 roll);
SFR_FUNC void sfr_set_fov(f32 fovDeg); // update projection matrix with new fov
SFR_FUNC void sfr_set_lighting(u8 enabled);
#ifdef SFR_USE_CGLTF
SFR_FUNC void sfr_model_animate(SfrModel* model, i32 animInd, f32 time);
SFR_FUNC SfrModel* sfr_load_gltf(const char* filename, i32 uvChannel);
SFR_FUNC void sfr_model_draw(const SfrModel* model, sfrmat transform, const SfrTexture* overrideTex);
SFR_FUNC SfrScene* sfr_scene_from_model(const SfrModel* model);
SFR_FUNC void sfr_release_model(SfrModel** model);
#endif
// things requiring stdio
#ifndef SFR_NO_STD
SFR_FUNC SfrMesh* sfr_load_mesh(const char* filename); // load an obj file into a struct that sofren can use
SFR_FUNC void sfr_release_mesh(SfrMesh** mesh); // release loaded mesh's memory
SFR_FUNC SfrTexture* sfr_load_texture(const char* filename); // load a BMP texture
SFR_FUNC void sfr_release_texture(SfrTexture** texture); // release loaded texture's memory
SFR_FUNC SfrFont* sfr_load_font(const char* filename); // load a .srft (sofren font type) font, see 'sfr-fontmaker'
SFR_FUNC void sfr_release_font(SfrFont** font); // release loaded font's memory
#endif
// all particle related functions
SFR_FUNC SfrParticleSystem sfr_particles_create(SfrParticle* buffer, i32 count, const SfrTexture* tex);
SFR_FUNC void sfr_particles_update(SfrParticleSystem* sys, f32 frameTime);
SFR_FUNC void sfr_particles_draw(const SfrParticleSystem* sys);
SFR_FUNC void sfr_particles_emit(SfrParticleSystem* sys,
f32 px, f32 py, f32 pz,
f32 vx, f32 vy, f32 vz,
f32 ax, f32 ay, f32 az,
f32 startSize, f32 endSize,
u32 startCol, u32 endCol,
f32 lifetime);
SFR_FUNC void sfr_rand_seed(u32 seed); // seed random number generator
SFR_FUNC u32 sfr_rand_next(void); // Lehmer random number generator
SFR_FUNC i32 sfr_rand_int(i32 min, i32 max); // random int in range [min, max)
SFR_FUNC f32 sfr_rand_flt(f32 min, f32 max); // random f32 in range [min, max)
// threading related functions
#ifdef SFR_MULTITHREADED
#ifdef _WIN32
static unsigned __stdcall sfr__worker_thread_func(void* arg);
#else
static void* sfr__worker_thread_func(void* arg);
#endif
SFR_FUNC i32 sfr_atomic_add(SfrAtomic32* a, i32 val);
SFR_FUNC i32 sfr_atomic_get(SfrAtomic32* a);
SFR_FUNC void sfr_atomic_set(SfrAtomic32* a, i32 val);
SFR_FUNC i32 sfr_atomic_cas(SfrAtomic32* ptr, i32 oldVal, i32 newVal);
SFR_FUNC i64 sfr_atomic_add64(SfrAtomic64* a, i64 val);
SFR_FUNC i64 sfr_atomic_get64(SfrAtomic64* a);
SFR_FUNC void sfr_atomic_set64(SfrAtomic64* a, i64 val);
SFR_FUNC i64 sfr_atomic_cas64(SfrAtomic64* ptr, i64 oldVal, i64 newVal);
SFR_FUNC void sfr_mutex_init(SfrMutex* m);
SFR_FUNC void sfr_mutex_destroy(SfrMutex* m);
SFR_FUNC void sfr_mutex_lock(SfrMutex* m);
SFR_FUNC void sfr_mutex_unlock(SfrMutex* m);
SFR_FUNC i32 sfr_semaphore_init(SfrSemaphore* s, i32 initialCount);
SFR_FUNC void sfr_semaphore_destroy(SfrSemaphore* s);
SFR_FUNC void sfr_semaphore_wait(SfrSemaphore* s);
SFR_FUNC void sfr_semaphore_post(SfrSemaphore* s, i32 n);
#endif
//================================================
//: PUBLIC MACROS
//================================================
#define SFR_PI (3.14159265358979323846)
#define SFR_EPSILON (1e-10)
#define SFR_ARRLEN(_arr) (sizeof(_arr) / sizeof((_arr)[0]))
#define SFR_MIN(_a, _b) ((_a) < (_b) ? (_a) : (_b))
#define SFR_MAX(_a, _b) ((_a) > (_b) ? (_a) : (_b))
#define SFR_CLAMP(_x, _min, _max) ((_x) < (_min) ? (_min) : ((_x) > (_max) ? (_max) : (_x)))
//================================================
//: TYPES
//================================================
#ifdef _MSC_VER
#define SFR_ALIGNED(n) __declspec(align(n))
#else
#define SFR_ALIGNED(n) __attribute__((aligned(n)))
#endif
#ifndef SFR_NO_SIMD
#include <immintrin.h>
typedef union SFR_ALIGNED(16) sfrvec {
__m128 v;
struct { f32 x, y, z, w; };
} sfrvec;
typedef struct sfrvec8 {
__m256 x, y, z, w;
} sfrvec8;
#else
typedef union sfrvec { struct { f32 x, y, z, w; }; } sfrvec;
#endif
typedef union sfrmat {
struct { f32 m[4][4]; };
sfrvec rows[4];
} sfrmat;
typedef struct sfrmesh {
f32* tris; // vertex positions
f32* uvs; // uv coordinates
f32* normals; // vertex normals
i32 vertCount; // total number of floats (3 per vertex)
} SfrMesh;
typedef struct sfrtex {
u32* pixels;
i32 w, h;
u32* mipPixels[14]; // levels 1-14, up to 16k x 16k textures
i32 mipW[14];
i32 mipH[14];
i32 mipLevels; // total levels including base, i.e. 1 => no extra levels
} SfrTexture;
typedef struct sfrfont {
// xy pairs [x0, y0, x1, y1, x2, ...]
f32 verts[SFR_FONT_GLYPH_MAX][SFR_FONT_VERT_MAX];
} SfrFont;
struct sfrBounds {
f32 minX, minY, minZ;
f32 maxX, maxY, maxZ;
};
typedef struct sfrScene {
SfrSceneObject* objects;
i32 count;
} SfrScene;
struct sfrBvhNode {
f32 minX, minY, minZ;
f32 maxX, maxY, maxZ;
// if count == 0 this is an internal node and 'leftFirst' is the index of the left child
// the right child is always at 'leftFirst + 1'
// if count > 0 this is a leaf node and 'leftFirst' is the index of the first triangle
i32 leftFirst;
i32 count;
};
typedef struct sfrSceneObject {
// all provided when creating the list of objects
SfrMesh* mesh;
sfrvec pos, rot, scale;
SfrTexture* tex;
u32 col;
// calculated and set in sfr_scene_create
sfrmat _model, _invModel, _normal;
struct sfrBvhNode* _bvhNodes;
i32 _bvhRoot;
i32 _bvhNodeCount;
} SfrSceneObject;
typedef struct sfrRayHit {
u8 hit; // 1 if hit, 0 if not
f32 distance; // distance along the ray to the hit
sfrvec pos; // world space hit position
sfrvec normal; // geometric normal of the triangle hit
i32 objectInd; // index of the object in the scene->objects array
i32 triangleInd; // index of the triangle within that object's mesh
SfrSceneObject* obj; // pointer to the object hit
} SfrRayHit;
#ifdef SFR_USE_CGLTF
enum sfrAnimPathType {
SFR_ANIM_PATH_TRANSLATION,
SFR_ANIM_PATH_ROTATION,
SFR_ANIM_PATH_SCALE
};
struct sfrAnimSampler {
f32* inputs; // times
f32* outputs; // values
i32 count;
};
struct sfrAnimChannel {
i32 transformNodeInd; // into model->transforms
i32 samplerInd;
enum sfrAnimPathType path;
};
struct sfrAnimation {
char* name;
f32 duration;
struct sfrAnimSampler* samplers;
i32 samplerCount;
struct sfrAnimChannel* channels;
i32 channelCount;
};
struct sfrTransformNode {
// local transform components
sfrvec localPos;
sfrvec localRot; // quaternion
sfrvec localScale;
i32 parentInd;
// cached matrices
sfrmat localMatrix;
sfrmat worldMatrix;
};
struct sfrModelNode {
SfrMesh* mesh;
SfrTexture* tex;
i32 transformInd; // link to the scene graph hierarchy
};
typedef struct sfrModel {
struct sfrModelNode* nodes; // renderable parts
i32 nodeCount;
struct sfrTransformNode* transforms; // hierarchy logic (1:1 with gltf nodes)
i32 transformCount;
struct sfrAnimation* animations;
i32 animCount;
// resource tracking for cleanup
SfrMesh** _allMeshes;
i32 _meshCount;
SfrTexture** _allTextures;
i32 _texCount;
} SfrModel;
#endif // SFR_USE_CGLTF
typedef struct sfrParticle {
f32 px, py, pz; // position
f32 vx, vy, vz; // velocity
f32 ax, ay, az; // acceleration
f32 startSize, endSize;
u32 startCol, endCol;
f32 lifetime, age;
} SfrParticle;
typedef struct sfrParticles {
SfrParticle* particles;
i32 total, active;
const SfrTexture* tex;
} SfrParticleSystem;
typedef struct sfrlight {
f32 dirX, dirY, dirZ;
f32 ambient, intensity;
f32 r, g, b; // [0.0, 1.0]
} SfrLight;
struct sfrTriangleBin {
i32 binId;
f32 invDet;
f32 dzdx, dzdy, zBase;
f32 dudx, dudy, uBase;
f32 dvdx, dvdy, vBase;
f32 didx, didy, iBase;
f32 A0, B0, C0;
f32 A1, B1, C1;
f32 A2, B2, C2;
i32 minX, maxX;
i32 minY, maxY;
u32 col;
const SfrTexture* tex;
};
struct sfrTile {
i32 minX, minY, maxX, maxY;
f32 maxZ; // furthest visible depth in the tile
#ifdef SFR_MULTITHREADED
struct sfrTriangleBin** bins[SFR_THREAD_COUNT + 1];
i32 binsCapacity[SFR_THREAD_COUNT + 1];
i32 binCount[SFR_THREAD_COUNT + 1];
SfrAtomic32 hasWork;
SFR_ALIGNED(32) f32 localDepth[SFR_TILE_DIM];
SFR_ALIGNED(32) i32 localId[SFR_TILE_DIM];
#endif
};
#ifdef SFR_MULTITHREADED
struct sfrThreadData {
SfrThread handle;
i32 threadInd;
};
struct sfrMeshChunkJob {
const f32* tris;
const f32* uvs;
const f32* normals;
sfrmat matNormal;
sfrmat matMVP;
u32 col;
const SfrTexture* tex;
i32 startTriangle;
i32 triangleCount;
};
struct sfrThreadBuf {
// tiling system data
struct sfrTile tiles[
((SFR_MAX_HEIGHT + SFR_TILE_WIDTH - 1) / SFR_TILE_WIDTH) *
((SFR_MAX_WIDTH + SFR_TILE_WIDTH - 1) / SFR_TILE_WIDTH)];
i32 tileCols, tileRows, tileCount;
struct sfrTriangleBin** binPages; // dynamic array of pointers to fixed size pages
i32 binPagesCapacity; // how many pages pointers have been allocated for
SfrAtomic32 triangleBinAllocator; // total bins allocated across all pages
SfrMutex binPoolMutex; // protects the binPages array resizing
// rasterizer work dispatch data
i32 rasterWorkQueue[(SFR_MAX_WIDTH / SFR_TILE_WIDTH + 1) * (SFR_MAX_HEIGHT / SFR_TILE_HEIGHT + 1)];
SfrAtomic32 rasterWorkQueueCount;
SfrAtomic32 rasterWorkQueueHead;
// dynamic pool for mesh jobs
struct sfrMeshChunkJob* meshJobPool;
i32 meshJobPoolCapacity;
SfrAtomic32 meshJobAllocator;
// dynamic queue for geometry work
i32* geometryWorkQueue;
i32 geometryWorkQueueCapacity;
SfrAtomic32 geometryWorkQueueCount;
SfrAtomic32 geometryWorkQueueHead;
SfrMutex geometryMutex; // protects resizing of job pool and work queue
// thread management data
struct sfrThreadData threads[SFR_THREAD_COUNT];
SfrSemaphore geometryStartSem;
SfrSemaphore geometryDoneSem;
SfrSemaphore rasterStartSem;
SfrSemaphore rasterDoneSem;
};
#endif
struct sfrState {
u8 lightingEnabled;
i32 activeLightCount;
sfrmat matNormal;
u8 normalMatDirty;
u32 randState;
f32 halfWidth, halfHeight;
sfrvec clipPlanes[4][2];
u32 baseTexPixels[1];
SfrTexture baseTex;
#ifdef SFR_MULTITHREADED
u8 shutdown;
#else
struct sfrTriangleBin* globalBins;
i32 globalBinsCount, globalBinsCap;
i32* idBuf;
#endif
};
// helper to track vertex attributes during clipping of textured triangles
struct sfrTexVert {
sfrvec pos; // position in view space
f32 u, v; // texture coords
sfrvec normal; // world space normal for lighting
f32 viewZ; // z in view space for perspective correction
f32 intensity; // intensity for goraud shading
};
//================================================
//: IMPLEMENTATION
//================================================
#ifdef SFR_IMPL
i32 sfrWidth, sfrHeight;
u32* sfrPixelBuf;
f32* sfrDepthBuf;
#ifdef SFR_MULTITHREADED
static struct sfrThreadBuf* sfrThreadBuf;
#endif
SfrLight sfrLight;
SfrAtomic32 sfrRasterCount;
sfrmat sfrMatModel, sfrMatView, sfrMatProj;
sfrvec sfrCamPos, sfrCamUp, sfrCamTarget;
f32 sfrCamFov;
f32 sfrNearDist = 0.1f, sfrFarDist = 100.f;
static struct sfrState sfrState = {0};
static void* (*sfrMalloc)(u64);
static void (*sfrFree)(void*);
static void* (*sfrRealloc)(void*, u64);
#ifdef SFR_MULTITHREADED
// for bin batching to avoid atomic operation each time
static SFR_THREAD_LOCAL i32 sfrTlsBinStart = 0;
static SFR_THREAD_LOCAL i32 sfrTlsBinEnd = 0;
// track thread inds including main thread
static SFR_THREAD_LOCAL i32 sfrTlsThreadInd = SFR_THREAD_COUNT;
#endif
//================================================
//: OPTIONAL LIBS SETUP
//================================================
#ifndef SFR_CGLTF_PATH
#define SFR_CGLTF_PATH "optional/cgltf.h"
#endif
#ifndef SFR_STB_IMAGE_PATH
#define SFR_STB_IMAGE_PATH "optional/stb_image.h"
#endif
#ifdef SFR_USE_STB_IMAGE
#define STB_IMAGE_IMPLEMENTATION
#define STBI_MALLOC(sz) sfrMalloc(sz)
#define STBI_FREE(p) sfrFree(p)
#define STBI_REALLOC(p,sz) sfrRealloc(p,sz)
#define STBI_ASSERT(x)
#include SFR_STB_IMAGE_PATH
// STB RGBA to sofren ARGB
static void sfr__swizzle_stb(u32* pixels, i32 count) {
for (i32 i = 0; i < count; i += 1) {
const u32 c = pixels[i];
const u32 r = (c >> 0) & 0xFF;
const u32 g = (c >> 8) & 0xFF;
const u32 b = (c >> 16) & 0xFF;
const u32 a = (c >> 24) & 0xFF;
pixels[i] = (a << 24) | (r << 16) | (g << 8) | b;
}
}
#endif
#ifdef SFR_USE_CGLTF
#ifdef SFR_NO_MATH
#error "SFR ERROR: To use cgltf, math.h must be included (but SFR_NO_MATH is defined)"
#endif
#ifdef SFR_NO_STD
#error "SFR ERROR: To use cgltf, standard lib must be included (but SFR_NO_STD is defined)"
#endif
#define CGLTF_IMPLEMENTATION
#include SFR_CGLTF_PATH
#ifndef SFR_USE_STB_IMAGE
#warning "SFR WARNING: SFR_USE_CGLTF defined without SFR_USE_STB_IMAGE. Model textures won't be loaded."
#endif
static void* sfr__cgltf_alloc(void* user, cgltf_size size) {
(void)user;
return sfrMalloc((u64)size);
}
static void sfr__cgltf_free(void* user, void* ptr) {
(void)user;
sfrFree(ptr);
}
#endif
#ifndef SFR_NO_STRING
#include <string.h>
#define sfr_memset memset
#define sfr_memcpy memcpy
#else
SFR_FUNC void* sfr_memset(void* dest, char c, i32 count) {
char* p = (char*)dest;
while (count--) {
*p++ = c;
}
return dest;
}
SFR_FUNC void* sfr_memcpy(void* dest, const void* const src, u64 n) {
u8* d = (u8*)dest;
const u8* s = (const u8*)src;
// copy until dest is aligned to word size
while (n && ((u64)d & (sizeof(u64) - 1))) {
*d++ = *s++;
n--;
}
// copy word sized chunks
u64* dw = (u64*)d;
const u64* sw = (const u64*)s;
while (n >= sizeof(u64)) {
*dw++ = *sw++;
n -= sizeof(u64);
}
// copy remaining bytes
d = (u8*)dw;
s = (const u8*)sw;
while (n--) {
*d++ = *s++;
}
return dest;
}
#endif
//================================================
//: MISC HELPER MACROS
//================================================
#define SFR__SWAP(type, _a, _b) { const type _swapTemp = (_a); (_a) = (_b); (_b) = _swapTemp; }
#define SFR__LERPF(_a, _b, _t) ((_a) + (_t) * ((_b) - (_a)))
#define SFR__DIV255(_r, _a, _b) \
const u8 _r = (_a * _b * 0x8081) >> 23;
#define SFR__MAT_IDENTITY (sfrmat){ .m = {{1, 0, 0, 0}, {0, 1, 0, 0}, {0, 0, 1, 0}, {0, 0, 0, 1}} }
#define SFR__TRIS_PER_BOUNDS 32
#ifndef SFR_NO_STD
#include <stdio.h>
#include <stdlib.h>
#define SFR__ERR_EXIT(...) { \
fprintf(stderr, "SFR error (%s) at line %d:\n\t", __FILE__, __LINE__); \
fprintf(stderr, __VA_ARGS__); \
exit(1); \
}
#define SFR__ERR_RET(_r, ...) { \
fprintf(stderr, "SFR error (%s) at line %d:\n\t", __FILE__, __LINE__); \
fprintf(stderr, __VA_ARGS__); \
return _r; \
}
#else
#ifndef SFR_NO_WARNINGS
#warning "SFR WARNING: If there is an internal error it will not be reported (SFR_NO_STD defined)"
#endif
#define SFR__ERR_EXIT(...) { sfrPixelBuf[999999999] = 1; } // crash the program to exit, hopefully there arent 1 billion pixels
#define SFR__ERR_RET(_r, ...) return _r
#endif
//================================================
//: MATH
//================================================
SFR_FUNC f32 sfr_fmaxf(f32 a, f32 b) { return a > b ? a : b; }
SFR_FUNC f32 sfr_fminf(f32 a, f32 b) { return a < b ? a : b; }
#ifndef SFR_NO_MATH
#include <math.h>
#define sfr_floorf floorf
#define sfr_ceilf ceilf
#define sfr_fabsf fabsf
#define sfr_sqrtf sqrtf
#define sfr_cosf cosf
#define sfr_sinf sinf
#define sfr_tanf tanf
#define sfr_powf powf
#define sfr_fmodf fmodf
#else
SFR_FUNC f32 sfr_floorf(f32 x) {
const i32 ix = (i32)x;
return ix - 1 * (x < ix);
// return (x < ix) ? ix - 1 : ix;
}
SFR_FUNC f32 sfr_ceilf(f32 x) {
// works fine for normal inputs
return (i32)(x + 0.999f * (x >= 0.f));
// return (x < 0.f) ? (i32)x : (i32)(x + 0.999f);
}
SFR_FUNC f32 sfr_fabsf(f32 x) {
return x < 0.f ? -x : x;
}
SFR_FUNC f32 sfr_sqrtf(f32 x) { // newton-raphson method
if (x <= 0.f) {
return 0.f;
}
f32 g = x;
for (i32 i = 0; i < SFR_SQRT_ACCURACY; i += 1) {
g = 0.5f * (g + x / g);
}
return g;
}
SFR_FUNC f32 sfr_cosf(f32 x) { // taylor series approximation
x -= (2 * SFR_PI) * sfr_floorf((x + SFR_PI) / (2.f * SFR_PI));
const f32 x2 = x * x;
f32 term = 1.f, sum = 1.f;
for (i32 i = 1, n = 0; i < SFR_TRIG_ACCURACY; i += 1) {
n += 2;
term *= -x2 / (n * (n - 1));
sum += term;
}
return sum;
}
SFR_FUNC f32 sfr_sinf(f32 x) { // taylor series approximation
x -= (2 * SFR_PI) * sfr_floorf((x + SFR_PI) / (2.f * SFR_PI));
const f32 x2 = x * x;
f32 term = x, sum = x;
for (i32 i = 1, n = 1; i < SFR_TRIG_ACCURACY; i += 1) {
n += 2;
term *= -x2 / (n * (n - 1));
sum += term;
}
return sum;
}
SFR_FUNC f32 sfr_tanf(f32 x) {
const f32 c = sfr_cosf(x);
return (c < SFR_EPSILON && c > -SFR_EPSILON) ? 0.f : sfr_sinf(x) / c;
}
SFR_FUNC f32 sfr_powf(f32 base, f32 exp) {
if (base < 0 && sfr_floorf(exp) != exp) {
return 0.f;
}
if (0 == exp) return 1.f;
if (1 == exp) return base;
f32 res = 1.f;
if (exp < 0) {
base = 1.f / base;
exp = -exp;
}
// this sucks and is very inaccurate
i32 iexp = (i32)exp;
while (iexp > 0) {
if (1 == iexp % 2) {
res *= base;
}
base *= base;
iexp /= 2;
}
return res;
}
SFR_FUNC f32 sfr_fmodf(f32 x, f32 y) {
return x - (i32)(x / y) * y;
}
#endif
SFR_FUNC sfrvec sfr_vec_add(sfrvec a, sfrvec b) {
sfrvec r;
#ifndef SFR_NO_SIMD
r.v = _mm_add_ps(a.v, b.v);
#else
r.x = a.x + b.x;
r.y = a.y + b.y;
r.z = a.z + b.z;
r.w = a.w + b.w;
#endif
return r;
}
SFR_FUNC sfrvec sfr_vec_sub(sfrvec a, sfrvec b) {
sfrvec r;
#ifndef SFR_NO_SIMD
r.v = _mm_sub_ps(a.v, b.v);
#else
r.x = a.x - b.x;
r.y = a.y - b.y;
r.z = a.z - b.z;
r.w = a.w - b.w;
#endif
return r;
}
SFR_FUNC sfrvec sfr_vec_mul(sfrvec a, f32 b) {
sfrvec r;
#ifndef SFR_NO_SIMD
const __m128 t = _mm_set1_ps(b);
r.v = _mm_mul_ps(a.v, t);
#else
r.x = a.x * b;
r.y = a.y * b;
r.z = a.z * b;
r.w = a.w * b;
#endif
return r;
}