-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrenderer.c
More file actions
2726 lines (2360 loc) · 118 KB
/
Copy pathrenderer.c
File metadata and controls
2726 lines (2360 loc) · 118 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
#include <stdlib.h>
#include <string.h>
#include "renderer.h"
#include "context.h"
#include "common.h"
#include "scene.h"
#include "vulkan_setup.h"
#include "tinyexr_c.h"
#include "camera.h"
#define STB_IMAGE_IMPLEMENTATION
#include "stb_image.h"
#define STB_DXT_IMPLEMENTATION
#include "stb_dxt.h"
#define NANOSVG_IMPLEMENTATION
#include "nanosvg.h"
#define NANOSVGRAST_IMPLEMENTATION
#include "nanosvgrast.h"
#include <dirent.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <pthread.h>
#ifndef MIN
#define MIN(a,b) (((a)<(b))?(a):(b))
#endif
#define DDS_MAGIC 0x20534444
typedef struct {
uint32_t dwSize; uint32_t dwFlags; uint32_t dwHeight; uint32_t dwWidth;
uint32_t dwPitchOrLinearSize; uint32_t dwDepth; uint32_t dwMipMapCount;
uint32_t dwReserved1[11];
struct { uint32_t dwSize; uint32_t dwFlags; uint32_t dwFourCC; uint32_t dwRGBBitCount;
uint32_t dwRBitMask; uint32_t dwGBitMask; uint32_t dwBBitMask; uint32_t dwABitMask; } ddspf;
uint32_t dwCaps; uint32_t dwCaps2; uint32_t dwCaps3; uint32_t dwCaps4; uint32_t dwReserved2;
} DDS_HEADER;
typedef struct { uint32_t dxgiFormat; uint32_t resourceDimension; uint32_t miscFlag; uint32_t arraySize; uint32_t miscFlags2; } DDS_HEADER_DXT10;
// --- OBSIDIAN MEMORY MANAGER & ASYNC QUEUE ---
#define MAX_TEXTURE_PAGES 64 // 16GB max pool
typedef struct { VkDeviceMemory memory; VkDeviceSize size; VkDeviceSize offset; uint32_t active_allocations; } TexturePage;
static TexturePage texture_pages[MAX_TEXTURE_PAGES];
static uint32_t texture_page_count = 0;
static bool alloc_texture_vram(VulkanContext* ctx, VkMemoryRequirements req, VkDeviceMemory* out_mem, VkDeviceSize* out_offset) {
VkDeviceSize alignment = req.alignment; // Trust driver alignment entirely
for (uint32_t i = 0; i < texture_page_count; i++) {
VkDeviceSize aligned_offset = (texture_pages[i].offset + alignment - 1) & ~(alignment - 1);
if (aligned_offset + req.size <= texture_pages[i].size) {
*out_mem = texture_pages[i].memory; *out_offset = aligned_offset;
texture_pages[i].offset = aligned_offset + req.size;
texture_pages[i].active_allocations++;
return true;
}
}
if (texture_page_count >= MAX_TEXTURE_PAGES) {
fprintf(stderr, "\033[31m[OMM] CRITICAL: Max texture pages reached!\033[0m\n");
return false;
}
VkDeviceSize page_size = 256 * 1024 * 1024;
if (req.size > page_size) page_size = (req.size + alignment - 1) & ~(alignment - 1);
uint32_t memType = findMemoryType(ctx->physicalDevice, req.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT);
VkMemoryAllocateInfo allocInfo = { .sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO, .allocationSize = page_size, .memoryTypeIndex = memType };
VkDeviceMemory new_mem;
if (vkAllocateMemory(ctx->device, &allocInfo, NULL, &new_mem) != VK_SUCCESS) return false;
texture_pages[texture_page_count] = (TexturePage){ .memory = new_mem, .size = page_size, .offset = req.size, .active_allocations = 1 };
*out_mem = new_mem; *out_offset = 0;
texture_page_count++;
fprintf(stdout, "\033[35m[OMM] Allocated %llu MB VRAM Texture Block (Page %u)\033[0m\n", page_size / (1024*1024), texture_page_count);
return true;
}
static void free_texture_vram(VkDeviceMemory mem) {
for (uint32_t i = 0; i < texture_page_count; i++) {
if (texture_pages[i].memory == mem) {
if (texture_pages[i].active_allocations > 0) {
texture_pages[i].active_allocations--;
if (texture_pages[i].active_allocations == 0) {
texture_pages[i].offset = 0; // Compacting reset!
fprintf(stdout, "\033[35m[OMM] Page %u compacted (0 active allocations).\033[0m\n", i);
}
}
return;
}
}
}
typedef struct { VkBuffer buffer; VkDeviceMemory memory; VkFence fence; VkCommandBuffer cmd; bool* loaded_flag; } AsyncUpload;
static AsyncUpload* async_uploads = NULL;
static uint32_t async_upload_count = 0;
static uint32_t async_upload_capacity = 0;
static VkCommandPool async_cmd_pool = VK_NULL_HANDLE;
typedef struct { VkBuffer buffer; VkDeviceMemory memory; VkCommandBuffer cmd; bool* loaded_flag; } PendingUpload;
static PendingUpload pending_uploads[8192];
static uint32_t pending_upload_count = 0;
static pthread_mutex_t upload_mutex = PTHREAD_MUTEX_INITIALIZER;
static VkCommandBuffer begin_async_cmd(VulkanContext* ctx) {
pthread_mutex_lock(&upload_mutex);
if (async_cmd_pool == VK_NULL_HANDLE) {
VkCommandPoolCreateInfo poolInfo = {
.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO,
.flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT | VK_COMMAND_POOL_CREATE_TRANSIENT_BIT,
.queueFamilyIndex = ctx->graphicsQueueFamily
};
vkCreateCommandPool(ctx->device, &poolInfo, NULL, &async_cmd_pool);
}
VkCommandBufferAllocateInfo allocInfo = {
.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO,
.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY,
.commandPool = async_cmd_pool,
.commandBufferCount = 1
};
VkCommandBuffer cmd;
vkAllocateCommandBuffers(ctx->device, &allocInfo, &cmd);
VkCommandBufferBeginInfo beginInfo = {
.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO,
.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT
};
vkBeginCommandBuffer(cmd, &beginInfo);
return cmd;
}
static void end_async_cmd(VkCommandBuffer cmd) {
vkEndCommandBuffer(cmd);
pthread_mutex_unlock(&upload_mutex);
}
static void submit_async_upload(VulkanContext* ctx, VkBuffer buf, VkDeviceMemory mem, VkCommandBuffer cmd, bool* loaded_flag) {
pthread_mutex_lock(&upload_mutex);
if (pending_upload_count < 8192) {
pending_uploads[pending_upload_count++] = (PendingUpload){ buf, mem, cmd, loaded_flag };
} else {
fprintf(stderr, "\033[31m[CRITICAL] Pending uploads overflow! Skipping upload.\033[0m\n");
}
pthread_mutex_unlock(&upload_mutex);
}
void pump_async_uploads(VulkanContext* ctx) {
for (uint32_t i = 0; i < async_upload_count; i++) {
if (vkGetFenceStatus(ctx->device, async_uploads[i].fence) == VK_SUCCESS) {
vkDestroyBuffer(ctx->device, async_uploads[i].buffer, NULL);
vkFreeMemory(ctx->device, async_uploads[i].memory, NULL);
pthread_mutex_lock(&upload_mutex);
vkFreeCommandBuffers(ctx->device, async_cmd_pool, 1, &async_uploads[i].cmd);
pthread_mutex_unlock(&upload_mutex);
vkDestroyFence(ctx->device, async_uploads[i].fence, NULL);
if (async_uploads[i].loaded_flag) *async_uploads[i].loaded_flag = true;
async_uploads[i] = async_uploads[--async_upload_count]; i--;
}
}
pthread_mutex_lock(&upload_mutex);
for (uint32_t i = 0; i < pending_upload_count; i++) {
VkSubmitInfo submitInfo = { .sType = VK_STRUCTURE_TYPE_SUBMIT_INFO, .commandBufferCount = 1, .pCommandBuffers = &pending_uploads[i].cmd };
VkFenceCreateInfo fenceInfo = { .sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO };
VkFence fence; vkCreateFence(ctx->device, &fenceInfo, NULL, &fence);
vkQueueSubmit(ctx->graphicsQueue, 1, &submitInfo, fence);
if (async_upload_count == async_upload_capacity) {
uint32_t new_cap = async_upload_capacity == 0 ? 128 : async_upload_capacity * 2;
AsyncUpload* new_arr = realloc(async_uploads, new_cap * sizeof(AsyncUpload));
if (new_arr) {
async_uploads = new_arr;
async_upload_capacity = new_cap;
} else {
fprintf(stderr, "\033[31m[CRITICAL] Failed to allocate memory for async uploads!\033[0m\n");
continue;
}
}
async_uploads[async_upload_count++] = (AsyncUpload){ pending_uploads[i].buffer, pending_uploads[i].memory, fence, pending_uploads[i].cmd, pending_uploads[i].loaded_flag };
}
pending_upload_count = 0;
pthread_mutex_unlock(&upload_mutex);
}
// --- BACKGROUND TEXTURE COOKER ---
typedef struct {
char filepath[512];
int32_t pool_index;
bool is_roughness;
} CookerJob;
#define MAX_COOKER_JOBS 8192
static CookerJob cooker_queue[MAX_COOKER_JOBS];
static volatile uint32_t cooker_head = 0;
static volatile uint32_t cooker_tail = 0;
static pthread_mutex_t cooker_mutex = PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t cooker_cond = PTHREAD_COND_INITIALIZER;
static pthread_t cooker_threads[8];
static bool cooker_running = true;
// Forward declarations for cooker thread
static float* load_exr_as_float(const char* path, int* out_w, int* out_h, bool is_normal, bool is_roughness);
static const char* get_texture_cache_path(const char* original_path, bool is_roughness);
static bool load_texture_dds(VulkanContext* ctx, const char* filepath, Texture2D* texture);
typedef struct {
uint32_t magic; // 0x5845544F 'OTEX'
uint32_t width;
uint32_t height;
uint32_t format;
uint32_t data_size;
} OtexHeader;
// --- Texture Pool Management ---
static Texture2D texturePool[MAX_TEXTURES];
static char texturePoolPaths[MAX_TEXTURES][512];
static bool texturePoolIsRoughness[MAX_TEXTURES];
static uint32_t textureCount = 0;
static Texture2D dummyWhiteTexture;
static void* cooker_worker_thread(void* arg) {
(void)arg;
while (cooker_running) {
pthread_mutex_lock(&cooker_mutex);
while (cooker_head == cooker_tail && cooker_running) {
pthread_cond_wait(&cooker_cond, &cooker_mutex);
}
if (!cooker_running) { pthread_mutex_unlock(&cooker_mutex); break; }
CookerJob job = cooker_queue[cooker_head];
cooker_head = (cooker_head + 1) % MAX_COOKER_JOBS;
pthread_mutex_unlock(&cooker_mutex);
Texture2D* tex = &texturePool[job.pool_index];
tex->status = TEXTURE_STATUS_COOKING;
fprintf(stdout, "\033[35m[BACKGROUND COOKER] Compiling %s...\033[0m\n", job.filepath);
const char* cache_path = get_texture_cache_path(job.filepath, job.is_roughness);
int w, h, ch;
if (job.is_roughness) {
if (strstr(job.filepath, ".exr")) {
float* floatPixels = load_exr_as_float(job.filepath, &w, &h, false, true);
if (floatPixels) {
FILE* fout = fopen(cache_path, "wb");
if (fout) {
OtexHeader header = { 0x5845544F, (uint32_t)w, (uint32_t)h, VK_FORMAT_R32G32B32A32_SFLOAT, (uint32_t)(w * h * 16) };
fwrite(&header, sizeof(OtexHeader), 1, fout);
fwrite(floatPixels, 1, header.data_size, fout);
fclose(fout);
}
free(floatPixels);
tex->status = TEXTURE_STATUS_READY_FOR_UPLOAD;
} else { tex->status = TEXTURE_STATUS_FAILED; }
} else {
stbi_uc* roughPixels = stbi_load(job.filepath, &w, &h, &ch, 1);
if (roughPixels) {
size_t size = (size_t)w * h * 4;
stbi_uc* packed = malloc(size);
for (int i = 0; i < w * h; i++) {
packed[i*4 + 0] = 255; // AO default
packed[i*4 + 1] = roughPixels[i]; // Roughness correctly packed in G!
packed[i*4 + 2] = 0; // Metallic default
packed[i*4 + 3] = 255;
}
free(roughPixels);
FILE* fout = fopen(cache_path, "wb");
if (fout) {
OtexHeader header = { 0x5845544F, (uint32_t)w, (uint32_t)h, VK_FORMAT_R8G8B8A8_UNORM, (uint32_t)(size) };
fwrite(&header, sizeof(OtexHeader), 1, fout);
fwrite(packed, 1, header.data_size, fout);
fclose(fout);
}
free(packed);
tex->status = TEXTURE_STATUS_READY_FOR_UPLOAD;
} else { tex->status = TEXTURE_STATUS_FAILED; }
}
} else {
// Standard Albedo/Normal/etc JIT to DDS
if (strstr(job.filepath, ".exr")) {
bool is_normal = (strstr(job.filepath, "nor") != NULL);
float* float_pixels = load_exr_as_float(job.filepath, &w, &h, is_normal, false);
if (float_pixels) {
FILE* fout = fopen(cache_path, "wb");
if (fout) {
OtexHeader header = { 0x5845544F, (uint32_t)w, (uint32_t)h, VK_FORMAT_R32G32B32A32_SFLOAT, (uint32_t)(w * h * 16) };
fwrite(&header, sizeof(OtexHeader), 1, fout);
fwrite(float_pixels, 1, header.data_size, fout);
fclose(fout);
}
free(float_pixels);
tex->status = TEXTURE_STATUS_READY_FOR_UPLOAD;
} else { tex->status = TEXTURE_STATUS_FAILED; }
} else {
unsigned char* pixels = stbi_load(job.filepath, &w, &h, &ch, STBI_rgb_alpha);
if (pixels) {
uint32_t num_blocks_x = (w + 3) / 4;
uint32_t num_blocks_y = (h + 3) / 4;
uint32_t dxt_size = num_blocks_x * num_blocks_y * 16;
unsigned char* dxt_data = malloc(dxt_size);
for (uint32_t by = 0; by < num_blocks_y; by++) {
for (uint32_t bx = 0; bx < num_blocks_x; bx++) {
unsigned char block[64];
for (uint32_t y = 0; y < 4; y++) {
for (uint32_t x = 0; x < 4; x++) {
uint32_t px = (bx * 4) + x;
uint32_t py = (by * 4) + y;
uint32_t idx = ((py < (uint32_t)h ? py : (uint32_t)h - 1) * w + (px < (uint32_t)w ? px : (uint32_t)w - 1)) * 4;
memcpy(&block[(y * 4 + x) * 4], &pixels[idx], 4);
}
}
stb_compress_dxt_block(&dxt_data[(by * num_blocks_x + bx) * 16], block, 1, STB_DXT_NORMAL);
}
}
char out_dds_path[512];
strncpy(out_dds_path, job.filepath, sizeof(out_dds_path) - 1);
char* out_ext = strrchr(out_dds_path, '.');
if (out_ext) strcpy(out_ext, ".dds");
const char* out_dds_cache = get_texture_cache_path(out_dds_path, false);
FILE* fdds = fopen(out_dds_cache, "wb");
if (fdds) {
uint32_t magic = DDS_MAGIC;
DDS_HEADER header = {0};
header.dwSize = 124;
header.dwFlags = 0x1007 | 0x80000;
header.dwHeight = h;
header.dwWidth = w;
header.dwPitchOrLinearSize = dxt_size;
header.dwMipMapCount = 1;
header.ddspf.dwSize = 32;
header.ddspf.dwFlags = 0x4;
header.ddspf.dwFourCC = 0x35545844;
header.dwCaps = 0x1000;
fwrite(&magic, 4, 1, fdds);
fwrite(&header, sizeof(DDS_HEADER), 1, fdds);
fwrite(dxt_data, 1, dxt_size, fdds);
fclose(fdds);
}
free(dxt_data);
stbi_image_free(pixels);
tex->status = TEXTURE_STATUS_READY_FOR_UPLOAD;
} else { tex->status = TEXTURE_STATUS_FAILED; }
}
}
}
return NULL;
}
void texture_pool_init() {
textureCount = 0;
memset(texturePool, 0, sizeof(texturePool));
// Generate Dummy 1x1 White Texture Fallback
unsigned char white_pixel[4] = {255, 255, 255, 255};
dummyWhiteTexture.loaded = false;
load_texture_from_rgba(&context, white_pixel, 1, 1, &dummyWhiteTexture);
dummyWhiteTexture.status = TEXTURE_STATUS_READY;
// Launch 8 Background Cooker Threads
cooker_running = true;
for(int i = 0; i < 8; i++) {
pthread_create(&cooker_threads[i], NULL, cooker_worker_thread, NULL);
}
}
void texture_pool_cleanup(VulkanContext* context) {
cooker_running = false;
pthread_cond_broadcast(&cooker_cond);
for(int i = 0; i < 8; i++) {
if (cooker_threads[i] != 0) {
pthread_join(cooker_threads[i], NULL);
cooker_threads[i] = 0;
}
}
pump_async_uploads(context);
for (uint32_t i = 0; i < async_upload_count; i++) {
vkWaitForFences(context->device, 1, &async_uploads[i].fence, VK_TRUE, UINT64_MAX);
}
pump_async_uploads(context);
destroy_texture(context, &dummyWhiteTexture);
for (uint32_t i = 0; i < textureCount; i++) {
destroy_texture(context, &texturePool[i]);
}
textureCount = 0;
for (uint32_t i = 0; i < texture_page_count; i++) {
if (texture_pages[i].memory) {
vkFreeMemory(context->device, texture_pages[i].memory, NULL);
texture_pages[i].memory = VK_NULL_HANDLE;
}
}
texture_page_count = 0;
if (async_uploads) { free(async_uploads); async_uploads = NULL; }
async_upload_capacity = 0;
async_upload_count = 0;
if (async_cmd_pool) {
vkDestroyCommandPool(context->device, async_cmd_pool, NULL);
async_cmd_pool = VK_NULL_HANDLE;
}
}
int32_t texture_pool_add(VulkanContext* context, const char* filename) {
if (textureCount >= MAX_TEXTURES) {
fprintf(stderr, "Texture pool full! Cannot load %s\n", filename);
return -1;
}
printf("Loading texture %u: %s\n", textureCount, filename);
if (load_texture(context, filename, &texturePool[textureCount])) {
printf(" -> Successfully queued texture #%u\n", textureCount);
return textureCount++;
}
printf(" -> Failed to load\n");
return -1;
}
Texture2D* texture_pool_get(int32_t index) {
if (index < 0 || index >= (int32_t)textureCount) {
return NULL;
}
return &texturePool[index];
}
// --- 3D Renderer ---
static uint32_t vertex_count = 0;
static uint32_t dynamic_draw_count = 0;
static uint32_t frame_index = 0;
bool scene_topology_dirty = true;
static bool indirect_buffer_dirty[MAX_FRAMES_IN_FLIGHT] = {true, true};
static vec3 last_camera_pos = { -1e7f, -1e7f, -1e7f };
static float* mesh_distances = NULL;
static size_t mesh_distances_capacity = 0;
uint32_t opaqueMeshCount = 0;
uint32_t transparentMeshCount = 0;
uint32_t active_sdf_count = 0;
extern uint64_t megaVertexBufferAddr;
extern uint64_t dynamicVertexBufferAddr;
uint32_t append_vertices(const Vertex* verts, uint32_t count) {
if (vertex_count + count > MAX_DYNAMIC_VERTICES) return UINT32_MAX;
uint32_t first = vertex_count;
Vertex* dynVerts = (Vertex*)context.dynamicStagingMapped;
uint32_t offset = (frame_index * MAX_DYNAMIC_VERTICES) + first;
memcpy(&dynVerts[offset], verts, count * sizeof(Vertex));
vertex_count += count;
return first;
}
static VkDevice device;
static VkPhysicalDevice physicalDevice;
static VkCommandPool commandPool;
static VkQueue graphicsQueue;
PushConstants pushConstants;
static Material currentMaterial = {
.baseColorFactor = {1.0f, 1.0f, 1.0f, 1.0f},
.metallicFactor = 0.0f,
.roughnessFactor = 0.5f,
.emissiveStrength = 1.0f,
.isUnlit = 0,
.alphaMode = 2,
.emissiveFactor = {0.0f, 0.0f, 0.0f},
.albedoIndex = -1,
.normalMapIndex = -1,
.metallicRoughIndex = -1,
.aoIndex = -1,
.emissiveIndex = -1,
};
void set_material(const Material* mat) { currentMaterial = *mat; }
void reset_material(void) {
currentMaterial = (Material){
.baseColorFactor = {1.0f, 1.0f, 1.0f, 1.0f},
.metallicFactor = 0.0f,
.roughnessFactor = 0.5f,
.emissiveStrength = 1.0f,
.isUnlit = 0,
.alphaMode = 2,
.emissiveFactor = {0.0f, 0.0f, 0.0f},
.albedoIndex = -1,
.normalMapIndex = -1,
.metallicRoughIndex = -1,
.aoIndex = -1,
.emissiveIndex = -1,
.displacementIndex = -1,
.displacementScale = 0.1f, // Default 10cm displacement
.transmissionFactor = 0.0f,
.ior = 1.5f,
.thicknessFactor = 0.0f,
.transmissionIndex = -1,
.thicknessIndex = -1,
.attenuationColor = {1.0f, 1.0f, 1.0f},
.attenuationDistance = 100000.0f,
.dispersion = 0.0f,
.isWireframe = 0,
};
}
static bool load_texture_from_pixels(VulkanContext* ctx, stbi_uc* pixels, int w, int h, Texture2D* texture);
static float* load_exr_as_float(const char* path, int* out_w, int* out_h, bool is_normal, bool is_roughness) {
printf("\n[EXR] Decoding %s (HDR 32-bit float)...\n", path);
FILE* f = fopen(path, "rb");
if (!f) return NULL;
fseek(f, 0, SEEK_END);
size_t file_size = ftell(f);
fseek(f, 0, SEEK_SET);
unsigned char* file_data = malloc(file_size);
fread(file_data, 1, file_size, f);
fclose(f);
ExrContextCreateInfo ctx_info = { .api_version = TINYEXR_C_API_VERSION };
ExrContext exr_ctx;
if (exr_context_create(&ctx_info, &exr_ctx) != EXR_SUCCESS) {
free(file_data); return NULL;
}
ExrDataSource src;
exr_data_source_from_memory(file_data, file_size, &src);
ExrDecoderCreateInfo dec_info = { .source = src };
ExrDecoder decoder;
if (exr_decoder_create(exr_ctx, &dec_info, &decoder) != EXR_SUCCESS) {
exr_context_destroy(exr_ctx); free(file_data); return NULL;
}
ExrImage image;
if (exr_decoder_parse_header(decoder, &image) != EXR_SUCCESS) {
exr_decoder_destroy(decoder); exr_context_destroy(exr_ctx); free(file_data); return NULL;
}
ExrImageInfo img_info;
exr_image_get_info(image, &img_info);
*out_w = img_info.width;
*out_h = img_info.height;
uint32_t c = img_info.num_channels;
ExrPart part;
exr_image_get_part(image, 0, &part);
size_t num_pixels = (size_t)img_info.width * img_info.height;
float* float_data = malloc(num_pixels * c * sizeof(float));
ExrCommandBufferCreateInfo cmd_info = { .decoder = decoder };
ExrCommandBuffer cmd;
exr_command_buffer_create(exr_ctx, &cmd_info, &cmd);
exr_command_buffer_begin(cmd);
ExrFullImageRequest req = {
.part = part,
.output = { .data = float_data, .size = num_pixels * c * sizeof(float) },
.channels_mask = 0,
.output_pixel_type = EXR_PIXEL_FLOAT,
.output_layout = EXR_LAYOUT_INTERLEAVED
};
exr_cmd_request_full_image(cmd, &req);
exr_command_buffer_end(cmd);
ExrSubmitInfo submit = { .command_buffer_count = 1, .command_buffers = &cmd };
exr_submit(decoder, &submit);
exr_decoder_wait_idle(decoder);
exr_command_buffer_destroy(cmd);
exr_image_destroy(image);
exr_decoder_destroy(decoder);
exr_context_destroy(exr_ctx);
free(file_data);
// Pack into pristine 32-bit RGBA float
float* rgba_float = malloc(num_pixels * 4 * sizeof(float));
for (size_t i = 0; i < num_pixels; i++) {
float r = float_data[i * c + 0];
float g = (c > 1) ? float_data[i * c + 1] : r;
float b = (c > 2) ? float_data[i * c + 2] : r;
float a = (c > 3) ? float_data[i * c + 3] : 1.0f;
if (is_normal) {
// Polyhaven EXR normals are already encoded in [0.0, 1.0] space.
// We pass the pristine 32-bit floats directly to the GPU without mangling them!
}
if (is_roughness) {
// EXR roughness is usually in R. glTF expects Roughness in G.
float rough = r;
r = 1.0f; // AO default
g = rough; // Roughness
b = 0.0f; // Metallic default
a = 1.0f;
}
rgba_float[i * 4 + 0] = r;
rgba_float[i * 4 + 1] = g;
rgba_float[i * 4 + 2] = b;
rgba_float[i * 4 + 3] = a;
}
free(float_data);
printf("[EXR] -> Successfully unpacked and formatted HDR float data.\n");
return rgba_float;
}
// Forward declarations for texture utilities
static bool alloc_texture_image(VulkanContext* ctx, uint32_t w, uint32_t h, VkFormat fmt, VkImage* image, VkDeviceMemory* memory);
static bool upload_pixels_to_image(VulkanContext* ctx, unsigned char* pixels, VkDeviceSize imageSize, VkImage image, uint32_t w, uint32_t h, VkFormat fmt, VkImageLayout srcLayout, bool* loaded_flag);
static bool finalize_texture(VulkanContext* ctx, Texture2D* texture, VkFormat fmt, VkSamplerAddressMode addrMode);
static bool load_texture_from_float_pixels(VulkanContext* ctx, float* pixels, int w, int h, Texture2D* texture) {
if (!pixels) return false;
VkFormat fmt = VK_FORMAT_R32G32B32A32_SFLOAT;
bool ok = alloc_texture_image(ctx, w, h, fmt, &texture->image, &texture->memory) &&
upload_pixels_to_image(ctx, (unsigned char*)pixels, (VkDeviceSize)w*h*16, texture->image, w, h, fmt, VK_IMAGE_LAYOUT_UNDEFINED, &texture->loaded) &&
finalize_texture(ctx, texture, fmt, VK_SAMPLER_ADDRESS_MODE_REPEAT);
if (ok) { texture->width = w; texture->height = h; }
return ok;
}
static const char* get_texture_cache_path(const char* original_path, bool is_roughness) {
static char cache_path[512];
const char* home = getenv("HOME");
if (!home) home = ".";
char dir_path[512];
snprintf(dir_path, sizeof(dir_path), "%s/.cache", home); mkdir(dir_path, 0777);
snprintf(dir_path, sizeof(dir_path), "%s/.cache/obsidian", home); mkdir(dir_path, 0777);
snprintf(dir_path, sizeof(dir_path), "%s/.cache/obsidian/textures", home); mkdir(dir_path, 0777);
char safe_name[256];
strncpy(safe_name, original_path, sizeof(safe_name) - 1);
safe_name[sizeof(safe_name) - 1] = '\0';
for (int i = 0; safe_name[i]; i++) {
if (safe_name[i] == '/' || safe_name[i] == '\\' || safe_name[i] == '.') safe_name[i] = '_';
}
snprintf(cache_path, sizeof(cache_path), "%s/%s%s.otex", dir_path, safe_name, is_roughness ? "_rough" : "");
return cache_path;
}
// Forward declaration
static bool upload_file_to_image_direct(VulkanContext *ctx, const char *filepath,
VkDeviceSize imageSize, VkImage image,
uint32_t w, uint32_t h, VkFormat fmt,
size_t file_offset, bool* loaded_flag);
static int32_t texture_pool_load_roughness_to_gltf(VulkanContext* ctx, const char* roughPath) {
if (!roughPath) return -1;
const char* cache_path = get_texture_cache_path(roughPath, true);
FILE* f = fopen(cache_path, "rb");
if (f) {
OtexHeader header;
if (fread(&header, sizeof(OtexHeader), 1, f) == 1 && header.magic == 0x5845544F) {
fclose(f);
fprintf(stdout, "\033[32m[TEXTURE] Cache Hit Roughness (ZERO-COPY): %s\033[0m\n", cache_path);
if (textureCount >= MAX_TEXTURES) return -1;
Texture2D* texture = &texturePool[textureCount];
if (alloc_texture_image(ctx, header.width, header.height, header.format, &texture->image, &texture->memory)) {
if (upload_file_to_image_direct(ctx, cache_path, header.data_size, texture->image, header.width, header.height, header.format, sizeof(OtexHeader), &texture->loaded)) {
if (finalize_texture(ctx, texture, header.format, VK_SAMPLER_ADDRESS_MODE_REPEAT)) {
texture->width = header.width; texture->height = header.height;
texture->status = TEXTURE_STATUS_READY;
return textureCount++;
}
}
}
} else {
fclose(f);
}
}
fprintf(stdout, "\033[33m[TEXTURE] Cache Miss Roughness. Queueing Background Cook: %s\033[0m\n", roughPath);
if (textureCount >= MAX_TEXTURES) return -1;
int32_t tIdx = textureCount++;
Texture2D* texture = &texturePool[tIdx];
// AAA Instant metadata parsing for Editor UI sizing
int w = 1, h = 1, ch;
if (stbi_info(roughPath, &w, &h, &ch)) {
texture->width = w;
texture->height = h;
} else {
texture->width = 1;
texture->height = 1;
}
texture->status = TEXTURE_STATUS_QUEUED_FOR_COOKING;
// Pre-allocate bindless slot to eliminate gray flickering
if (texture->bindlessSlot == 0) {
texture->bindlessSlot = ctx->bindlessTextureCount++;
bindlessRegisterTexture(ctx, texture->bindlessSlot, dummyWhiteTexture.view, dummyWhiteTexture.sampler);
}
strncpy(texturePoolPaths[tIdx], roughPath, 511);
texturePoolIsRoughness[tIdx] = true;
pthread_mutex_lock(&cooker_mutex);
uint32_t next = (cooker_tail + 1) % MAX_COOKER_JOBS;
if (next != cooker_head) {
strncpy(cooker_queue[cooker_tail].filepath, roughPath, 511);
cooker_queue[cooker_tail].pool_index = tIdx;
cooker_queue[cooker_tail].is_roughness = true;
cooker_tail = next;
pthread_cond_signal(&cooker_cond);
}
pthread_mutex_unlock(&cooker_mutex);
return tIdx;
}
Material load_pbr_material(const char* albedoPath, const char* normalPath, const char* roughnessPath) {
Material mat;
reset_material();
mat = currentMaterial;
int32_t pIdx;
if (albedoPath) {
pIdx = texture_pool_add(&context, albedoPath);
if (pIdx >= 0) mat.albedoIndex = texture_pool_get(pIdx)->bindlessSlot;
printf("[PBR] Loaded Albedo: %s (Slot: %d)\n", albedoPath, mat.albedoIndex);
}
if (normalPath) {
pIdx = texture_pool_add(&context, normalPath);
if (pIdx >= 0) mat.normalMapIndex = texture_pool_get(pIdx)->bindlessSlot;
printf("[PBR] Loaded Normal: %s (Slot: %d)\n", normalPath, mat.normalMapIndex);
}
if (roughnessPath) {
pIdx = texture_pool_load_roughness_to_gltf(&context, roughnessPath);
if (pIdx >= 0) mat.metallicRoughIndex = texture_pool_get(pIdx)->bindlessSlot;
printf("[PBR] Loaded Roughness: %s (Slot: %d)\n", roughnessPath, mat.metallicRoughIndex);
}
// Clear default factors since we are using textures
if (albedoPath) glm_vec4_copy((vec4){1.0f, 1.0f, 1.0f, 1.0f}, mat.baseColorFactor);
if (roughnessPath) mat.roughnessFactor = 1.0f;
if (roughnessPath) mat.metallicFactor = 1.0f;
return mat;
}
typedef struct {
uint32_t magic; // 0x54414D4F 'OMAT'
char albedoPath[512];
char normalPath[512];
char roughPath[512];
char aoPath[512];
char dispPath[512];
float displacementScale;
} OmatCache;
static const char* get_material_cache_path(const char* dirPath) {
static char cache_path[512];
const char* home = getenv("HOME");
if (!home) home = ".";
char dir_path[512];
snprintf(dir_path, sizeof(dir_path), "%s/.cache", home); mkdir(dir_path, 0777);
snprintf(dir_path, sizeof(dir_path), "%s/.cache/obsidian", home); mkdir(dir_path, 0777);
snprintf(dir_path, sizeof(dir_path), "%s/.cache/obsidian/materials", home); mkdir(dir_path, 0777);
char safe_name[256];
strncpy(safe_name, dirPath, sizeof(safe_name) - 1);
safe_name[sizeof(safe_name) - 1] = '\0';
for (int i = 0; safe_name[i]; i++) {
if (safe_name[i] == '/' || safe_name[i] == '\\' || safe_name[i] == '.') safe_name[i] = '_';
}
snprintf(cache_path, sizeof(cache_path), "%s/%s.omat", dir_path, safe_name);
return cache_path;
}
Material load_pbr_material_dir(const char* dirPath) {
printf("\n[PBR SCAN] ==========================================\n");
const char* cache_path = get_material_cache_path(dirPath);
FILE* f = fopen(cache_path, "rb");
OmatCache cache = {0};
bool cache_hit = false;
if (f) {
if (fread(&cache, sizeof(OmatCache), 1, f) == 1 && cache.magic == 0x54414D4F) {
fprintf(stdout, "\033[32m[MATERIAL] Cache Hit (OMAT Manifest): %s\033[0m\n", cache_path);
cache_hit = true;
}
fclose(f);
}
if (!cache_hit) {
fprintf(stdout, "\033[33m[MATERIAL] Cache Miss. Scanning directory (OS Syscalls): %s\033[0m\n", dirPath);
cache.magic = 0x54414D4F;
cache.displacementScale = 0.5f;
DIR *dir;
struct dirent *ent;
if ((dir = opendir(dirPath)) != NULL) {
while ((ent = readdir(dir)) != NULL) {
if (strstr(ent->d_name, "diff") || strstr(ent->d_name, "albedo") || strstr(ent->d_name, "basecolor")) {
snprintf(cache.albedoPath, sizeof(cache.albedoPath), "%s/%s", dirPath, ent->d_name);
} else if (strstr(ent->d_name, "nor")) {
snprintf(cache.normalPath, sizeof(cache.normalPath), "%s/%s", dirPath, ent->d_name);
} else if (strstr(ent->d_name, "rough")) {
snprintf(cache.roughPath, sizeof(cache.roughPath), "%s/%s", dirPath, ent->d_name);
} else if (strstr(ent->d_name, "ao") || strstr(ent->d_name, "ambient")) {
snprintf(cache.aoPath, sizeof(cache.aoPath), "%s/%s", dirPath, ent->d_name);
} else if (strstr(ent->d_name, "disp") || strstr(ent->d_name, "height")) {
snprintf(cache.dispPath, sizeof(cache.dispPath), "%s/%s", dirPath, ent->d_name);
}
}
closedir(dir);
} else {
fprintf(stderr, "[WARNING] Could not open material directory: %s\n", dirPath);
}
FILE* fout = fopen(cache_path, "wb");
if (fout) {
fwrite(&cache, sizeof(OmatCache), 1, fout);
fclose(fout);
}
}
Material mat;
reset_material();
mat = currentMaterial;
int32_t pIdx;
if (cache.albedoPath[0]) {
pIdx = texture_pool_add(&context, cache.albedoPath);
if (pIdx >= 0) mat.albedoIndex = texture_pool_get(pIdx)->bindlessSlot;
printf("[PBR SCAN] -> Albedo mapped to Bindless Slot: %d\n", mat.albedoIndex);
}
if (cache.normalPath[0]) {
pIdx = texture_pool_add(&context, cache.normalPath);
if (pIdx >= 0) mat.normalMapIndex = texture_pool_get(pIdx)->bindlessSlot;
printf("[PBR SCAN] -> Normal mapped to Bindless Slot: %d\n", mat.normalMapIndex);
}
if (cache.roughPath[0]) {
pIdx = texture_pool_load_roughness_to_gltf(&context, cache.roughPath);
if (pIdx >= 0) mat.metallicRoughIndex = texture_pool_get(pIdx)->bindlessSlot;
printf("[PBR SCAN] -> Roughness mapped to Bindless Slot: %d\n", mat.metallicRoughIndex);
}
if (cache.aoPath[0]) {
pIdx = texture_pool_add(&context, cache.aoPath);
if (pIdx >= 0) mat.aoIndex = texture_pool_get(pIdx)->bindlessSlot;
printf("[PBR SCAN] -> AO mapped to Bindless Slot: %d\n", mat.aoIndex);
}
if (cache.dispPath[0]) {
pIdx = texture_pool_add(&context, cache.dispPath);
if (pIdx >= 0) mat.displacementIndex = texture_pool_get(pIdx)->bindlessSlot;
printf("[PBR SCAN] -> Displacement mapped to Bindless Slot: %d\n", mat.displacementIndex);
mat.displacementScale = cache.displacementScale;
}
printf("[PBR SCAN] ==========================================\n\n");
if (cache.albedoPath[0]) glm_vec4_copy((vec4){1.0f, 1.0f, 1.0f, 1.0f}, mat.baseColorFactor);
if (cache.roughPath[0]) mat.roughnessFactor = 1.0f;
if (cache.roughPath[0]) mat.metallicFactor = 1.0f;
return mat;
}
int alloc_slot(mat4 model) {
if (dynamic_draw_count >= MAX_DYNAMIC_MESHES) return 0;
uint32_t staticCount = (uint32_t)scene.meshes.count;
int slot = staticCount + dynamic_draw_count;
MeshGPUData* d = &((MeshGPUData*)context.meshSSBOMapped[frame_index])[slot];
glm_mat4_copy(model, d->model);
glm_vec4_copy(currentMaterial.baseColorFactor, d->baseColorFactor);
d->metallicFactor = currentMaterial.metallicFactor;
d->roughnessFactor = currentMaterial.roughnessFactor;
d->emissiveStrength = currentMaterial.emissiveStrength;
d->isUnlit = currentMaterial.isUnlit;
d->alphaMode = currentMaterial.alphaMode;
d->alphaCutoff = 0.5f;
glm_vec3_copy(currentMaterial.emissiveFactor, d->emissiveFactor);
d->albedoIndex = currentMaterial.albedoIndex;
d->normalMapIndex = currentMaterial.normalMapIndex;
d->metallicRoughIndex = currentMaterial.metallicRoughIndex;
d->aoIndex = currentMaterial.aoIndex;
d->emissiveIndex = currentMaterial.emissiveIndex;
d->displacementIndex = currentMaterial.displacementIndex;
d->displacementScale = currentMaterial.displacementScale;
d->transmissionFactor = currentMaterial.transmissionFactor;
d->ior = currentMaterial.ior;
d->thicknessFactor = currentMaterial.thicknessFactor;
d->transmissionIndex = currentMaterial.transmissionIndex;
d->thicknessIndex = currentMaterial.thicknessIndex;
d->attenuationColorR = currentMaterial.attenuationColor[0];
d->attenuationColorG = currentMaterial.attenuationColor[1];
d->attenuationColorB = currentMaterial.attenuationColor[2];
d->attenuationDistance = currentMaterial.attenuationDistance;
d->dispersion = currentMaterial.dispersion;
d->isVisible = 1; // Dynamic immediate-mode meshes/lines are always visible
d->isWireframe = currentMaterial.isWireframe;
d->thicknessFactor = currentMaterial.thicknessFactor;
glm_vec3_copy((vec3){-1e5f, -1e5f, -1e5f}, d->aabbMin);
glm_vec3_copy((vec3){ 1e5f, 1e5f, 1e5f}, d->aabbMax);
d->jointOffset = -1;
d->morphCount = 0;
d->morphDeltaOffset = 0;
d->morphWeightOffset = 0;
return slot;
}
void begin_frame(void) {
pump_async_uploads(&context); // Garbage collect finished staging buffers asynchronously
// Async GPU Upload Pipeline: Pump compiled cache files back to VRAM
for (uint32_t i = 0; i < textureCount; i++) {
if (texturePool[i].status == TEXTURE_STATUS_READY_FOR_UPLOAD) {
texturePool[i].status = TEXTURE_STATUS_UPLOADING;
texturePool[i].loaded = false; // Arm the DMA fence flag
if (texturePoolIsRoughness[i]) {
const char* cache_path = get_texture_cache_path(texturePoolPaths[i], true);
FILE* f = fopen(cache_path, "rb");
if (f) {
OtexHeader header;
if (fread(&header, sizeof(OtexHeader), 1, f) == 1) {
alloc_texture_image(&context, header.width, header.height, header.format, &texturePool[i].image, &texturePool[i].memory);
upload_file_to_image_direct(&context, cache_path, header.data_size, texturePool[i].image, header.width, header.height, header.format, sizeof(OtexHeader), &texturePool[i].loaded);
finalize_texture(&context, &texturePool[i], header.format, VK_SAMPLER_ADDRESS_MODE_REPEAT);
texturePool[i].width = header.width; texturePool[i].height = header.height;
}
fclose(f);
}
} else {
char dds_path[512];
strncpy(dds_path, texturePoolPaths[i], sizeof(dds_path) - 1);
char* ext = strrchr(dds_path, '.');
if (ext) strcpy(ext, ".dds");
const char* dds_cache = get_texture_cache_path(dds_path, false);
if (ext && load_texture_dds(&context, dds_cache, &texturePool[i])) {
// load_texture_dds handles async flag setting
} else {
const char* cache_path = get_texture_cache_path(texturePoolPaths[i], false);
FILE* f = fopen(cache_path, "rb");
if (f) {
OtexHeader header;
if (fread(&header, sizeof(OtexHeader), 1, f) == 1) {
alloc_texture_image(&context, header.width, header.height, header.format, &texturePool[i].image, &texturePool[i].memory);
upload_file_to_image_direct(&context, cache_path, header.data_size, texturePool[i].image, header.width, header.height, header.format, sizeof(OtexHeader), &texturePool[i].loaded);
finalize_texture(&context, &texturePool[i], header.format, VK_SAMPLER_ADDRESS_MODE_REPEAT);
texturePool[i].width = header.width; texturePool[i].height = header.height;
}
fclose(f);
}
}
}
}
// Zero-flicker DMA validation
// Only swap the global bindless slot ONCE the GPU fence signals the DMA transfer is fully complete
if (texturePool[i].status == TEXTURE_STATUS_UPLOADING && texturePool[i].loaded == true) {
bindlessRegisterTexture(&context, texturePool[i].bindlessSlot, texturePool[i].view, texturePool[i].sampler);
texturePool[i].status = TEXTURE_STATUS_READY;
markMeshesSSBODirty(&context); // Force SSBO to drop the -1 fallback and use the real texture slot
fprintf(stdout, "\033[36m[GPU PUMP] Swap complete! Texture %d is live.\033[0m\n", i);
}
}
frame_index = context.currentFrame;
dynamic_draw_count = 0;
vertex_count = 0;
line_renderer_clear();
context.indirectDrawCount = (uint32_t)scene.meshes.count;
extern void animate_scene(Scene* scene, float time);
animate_scene(&scene, 0.0f);
vec3 camPos = { camera.position[0], camera.position[1], camera.position[2] };
float cam_delta = glm_vec3_distance2(camPos, last_camera_pos);
// AAA Zero-Tick Architecture: Only sort and write to PCIe if the observer or topology changes
if (scene_topology_dirty || cam_delta > 0.01f) {
sort_meshes_by_alpha(&scene.meshes, camPos);
glm_vec3_copy(camPos, last_camera_pos);
for (uint32_t i = 0; i < MAX_FRAMES_IN_FLIGHT; i++) {
indirect_buffer_dirty[i] = true;
}
scene_topology_dirty = false;
}
if (indirect_buffer_dirty[frame_index]) {
updateMeshSSBOAndIndirect(&context, &scene.meshes);
indirect_buffer_dirty[frame_index] = false;
}
// flushMeshSSBO is extremely cheap (O(1) bitmask scan) so it safely runs every frame