-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRenderer.cpp
More file actions
1418 lines (1220 loc) · 74.2 KB
/
Renderer.cpp
File metadata and controls
1418 lines (1220 loc) · 74.2 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 "Renderer.hpp"
#include <map>
#include <cstring>
#include <algorithm>
#include "Queue.hpp"
#include "RenderPass.hpp"
#include "AssetManager.hpp"
#include "Window.hpp"
#include "Command.hpp"
#include "Swapchain.hpp"
#include "Framebuffers.hpp"
#include "PhysicalDevice.hpp"
namespace Lca{
namespace Core{
void Renderer::init(){
for(uint32_t i = 0; i < MAX_FRAMES_IN_FLIGHT; i++) {
objectInstancesGPU[i] = createDualBuffer(Lca::Core::MAX_OBJECTS, sizeof(ObjectInstance), VK_BUFFER_USAGE_STORAGE_BUFFER_BIT);
modelMatricesGPU[i] = createDualBuffer(Lca::Core::MAX_MODEL_MATRICES, sizeof(ModelMatrix), VK_BUFFER_USAGE_STORAGE_BUFFER_BIT);
lightsGPU[i] = createDualBuffer(Lca::Core::MAX_LIGHTS + 1, sizeof(Light), VK_BUFFER_USAGE_STORAGE_BUFFER_BIT);
cameraBuffer[i] = createDualBuffer(1, sizeof(Camera), VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT);
drawCounts[i] = createBuffer(Lca::Core::MAX_SHADERS, sizeof(uint32_t), VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_INDIRECT_BUFFER_BIT);
// Per-frame single-sample depth map used by compute light culling
depthMaps[i] = createDepthMap(vkExtent2D.width, vkExtent2D.height);
// Per-frame depth pre-pass indirect buffer and its count
depthPrePassBuffer[i] = createBuffer(Lca::Core::MAX_OBJECTS, sizeof(VkDrawIndexedIndirectCommand), VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_INDIRECT_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT);
depthPrePassCountBuffer[i] = createBuffer(1, sizeof(uint32_t), VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_INDIRECT_BUFFER_BIT);
// Create per-frame tile light index buffers for the light culling compute shader.
// Must match shader constants
const uint32_t tilesX = (vkExtent2D.width + TILE_WIDTH - 1u) / TILE_WIDTH;
const uint32_t tilesY = (vkExtent2D.height + TILE_HEIGHT - 1u) / TILE_HEIGHT;
const uint32_t entriesPerTile = MAX_LIGHTS_PER_TILE + 1u; // count + indices
const uint32_t totalElements = tilesX * tilesY * entriesPerTile;
lightIndicesBuffer[i] = createBuffer(totalElements, sizeof(uint32_t), VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT);
// ── Skeleton mesh rendering buffers ───────────────────
skeletonMeshInstancesGPU[i] = createDualBuffer(Lca::Core::MAX_OBJECTS, sizeof(SkeletonMeshInstance), VK_BUFFER_USAGE_STORAGE_BUFFER_BIT);
skeletonInstancesGPU[i] = createDualBuffer(Lca::Core::MAX_SKELETON_INSTANCES, sizeof(SkeletonInstance), VK_BUFFER_USAGE_STORAGE_BUFFER_BIT);
skeletonDrawCounts[i] = createBuffer(Lca::Core::MAX_SHADERS, sizeof(uint32_t), VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_INDIRECT_BUFFER_BIT);
skeletonDepthPrePassBuffer[i] = createBuffer(Lca::Core::MAX_OBJECTS, sizeof(VkDrawIndexedIndirectCommand), VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_INDIRECT_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT);
skeletonDepthPrePassCountBuffer[i] = createBuffer(1, sizeof(uint32_t), VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_INDIRECT_BUFFER_BIT);
// ── Particle system rendering buffers ─────────────────
particleSystemInstancesGPU[i] = createDualBuffer(Lca::Core::MAX_PARTICLE_SYSTEMS, sizeof(ParticleSystemInstance), VK_BUFFER_USAGE_STORAGE_BUFFER_BIT);
particleDeltaTimeBuffer[i] = createDualBuffer(1, sizeof(ParticleDeltaTimeUniform), VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT);
particleGfxDrawCounts[i] = createBuffer(Lca::Core::MAX_PARTICLE_GFX_PIPELINES, sizeof(uint32_t),
VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_INDIRECT_BUFFER_BIT);
}
// Per-pipeline device-local indirect buffers written every frame by ParticleCullPipeline.
// particleGfxIndirectBuffers[graphicsID][slot]: VkDrawIndexedIndirectCommand
// firstInstance = particleOffset, instanceCount = particleCount (0 when culled).
// Indexed by global particle system slot; buffers are created in addParticleSystemPipeline().
// One VkDispatchIndirectCommand per comp pipeline (not per system).
// y and z are always 1; only x (workgroup count) varies and is written by the cull shader.
// The CPU resets x to 0 each frame via vkCmdUpdateBuffer before the cull dispatch.
particleCompIndirectBuffer = createBuffer(
Lca::Core::MAX_PARTICLE_COMP_PIPELINES, sizeof(VkDispatchIndirectCommand),
VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_INDIRECT_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT);
// Dispatch table: maps global workgroup ID -> (particleBase, systemSlot).
// Written by the cull shader; read by the sim shader via gl_WorkGroupID.x.
particleDispatchTableBuffer = createBuffer(
Lca::Core::MAX_PARTICLE_DISPATCH_ENTRIES, sizeof(ParticleDispatchEntry),
VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT);
// One large device-local particle storage buffer shared by all systems.
particleStorageBuffer = createBuffer(Lca::Core::MAX_PARTICLES, sizeof(Particle),
VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT);
currentParticleTop = 0;
particleFreeRanges.clear();
// If comp pipelines were registered before init(), initialise their y=1, z=1 now.
shaderCapacities = createDualBuffer(Lca::Core::MAX_SHADERS, sizeof(uint32_t), VK_BUFFER_USAGE_STORAGE_BUFFER_BIT);
memset(shaderCapacities.interface.pMemory, 0, Lca::Core::MAX_SHADERS * sizeof(uint32_t));
dummyIndirectBuffer = createBuffer(Lca::Core::MAX_OBJECTS, sizeof(VkDrawIndexedIndirectCommand), VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_INDIRECT_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT);
skeletonShaderCapacities = createDualBuffer(Lca::Core::MAX_SHADERS, sizeof(uint32_t), VK_BUFFER_USAGE_STORAGE_BUFFER_BIT);
memset(skeletonShaderCapacities.interface.pMemory, 0, Lca::Core::MAX_SHADERS * sizeof(uint32_t));
skeletonDummyIndirectBuffer = createBuffer(Lca::Core::MAX_OBJECTS, sizeof(VkDrawIndexedIndirectCommand), VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_INDIRECT_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT);
// Fill GPU-side instance buffers with 0xFFFFFFFF so every
// uninitialised slot has transformID == UINT32_MAX and is
// rejected by the cull shaders' invalid-slot check.
// Without this, the 250 zero-filled slots in the last
// dispatch workgroup pass the check and generate ghost draw
// commands, destroying framerate.
beginSingleCommand(singleCommand);
for (uint32_t i = 0; i < MAX_FRAMES_IN_FLIGHT; i++) {
memset(objectInstancesGPU[i].interface.pMemory, 0xFF,
MAX_OBJECTS * sizeof(ObjectInstance));
vkCmdFillBuffer(singleCommand.vkCommandBuffer,
objectInstancesGPU[i].buffer.vkBuffer,
0, VK_WHOLE_SIZE, 0xFFFFFFFF);
memset(skeletonMeshInstancesGPU[i].interface.pMemory, 0xFF,
MAX_OBJECTS * sizeof(SkeletonMeshInstance));
vkCmdFillBuffer(singleCommand.vkCommandBuffer,
skeletonMeshInstancesGPU[i].buffer.vkBuffer,
0, VK_WHOLE_SIZE, 0xFFFFFFFF);
}
endSingleCommand(singleCommand);
submitSingleCommand(singleCommand);
uberCullPipeline = std::make_unique<UberCullPipeline>("shader/uber_cull.comp.spv");
uberCullPipeline->build();
GraphicsPipelineConfig depthPipelineConfig{};
depthPipelineConfig.vertexShader = "shader/depth.vert.spv";
depthPipelineConfig.depthBiasConstantFactor = 1.25f;
depthPipelineConfig.depthBiasClamp = 0.0f;
depthPipelineConfig.depthBiasSlopeFactor = 1.75f;
depthPipelineConfig.sampleCount = VK_SAMPLE_COUNT_1_BIT;
depthPipelineConfig.minSampleShading = 1.0f;
depthPipelineConfig.depthCompareOp = VK_COMPARE_OP_LESS_OR_EQUAL;
depthPipelineConfig.minDepthBounds = 0.0f;
depthPipelineConfig.maxDepthBounds = 1.0f;
depthPipelineConfig.hasColorAttachments = false;
depthPipeline = std::make_unique<DepthPipeline>(depthPipelineConfig);
depthPipeline->build();
// Skeleton depth pipeline: same config but with a skinning depth shader
GraphicsPipelineConfig skeletonDepthConfig = depthPipelineConfig;
skeletonDepthConfig.vertexShader = "shader/skeleton_depth.vert.spv";
skeletonDepthPipeline = std::make_unique<SkeletonDepthPipeline>(skeletonDepthConfig);
skeletonDepthPipeline->build();
skeletonCullPipeline = std::make_unique<SkeletonCullPipeline>("shader/skeleton_cull.comp.spv");
skeletonCullPipeline->build();
// Pre-reserve so that addParticleSystemPipeline() / addMeshPipeline() never
// trigger a reallocation. Pipeline has no user-defined move constructor, so a
// reallocation would copy the raw VkPipeline handle then destroy the old element,
// calling vkDestroyPipeline on a still-live handle (use-after-free / 0xee handle).
particlePipelines.reserve(Lca::Core::MAX_PARTICLE_GFX_PIPELINES);
meshPipelines.reserve(Lca::Core::MAX_SHADERS);
skeletonMeshPipelines.reserve(Lca::Core::MAX_SHADERS);
// Particle cull pipeline: built after all particle pipelines are registered
// (same pattern as uberCull). The shader path placeholder will be replaced
// once particle_cull.comp.spv is compiled.
particleCullPipeline = std::make_unique<ParticleCullPipeline>("shader/particle_cull.comp.spv");
particleCullPipeline->build();
lightCullPipeline = std::make_unique<LightCullPipeline>("shader/light_cull.comp.spv");
lightCullPipeline->build();
}
void Renderer::shutdown(){
particleCullPipeline.reset();
uberCullPipeline.reset();
skeletonCullPipeline.reset();
depthPipeline.reset();
skeletonDepthPipeline.reset();
lightCullPipeline.reset();
for(uint32_t i = 0; i < MAX_FRAMES_IN_FLIGHT; i++) {
destroyDualBuffer(objectInstancesGPU[i]);
destroyDualBuffer(modelMatricesGPU[i]);
destroyDualBuffer(lightsGPU[i]);
destroyDualBuffer(cameraBuffer[i]);
destroyBuffer(drawCounts[i]);
destroyTexture(depthMaps[i]);
destroyBuffer(lightIndicesBuffer[i]);
destroyBuffer(depthPrePassBuffer[i]);
destroyBuffer(depthPrePassCountBuffer[i]);
destroyDualBuffer(skeletonMeshInstancesGPU[i]);
destroyDualBuffer(skeletonInstancesGPU[i]);
destroyBuffer(skeletonDrawCounts[i]);
destroyBuffer(skeletonDepthPrePassBuffer[i]);
destroyBuffer(skeletonDepthPrePassCountBuffer[i]);
destroyDualBuffer(particleSystemInstancesGPU[i]);
destroyDualBuffer(particleDeltaTimeBuffer[i]);
destroyBuffer(particleGfxDrawCounts[i]);
}
destroyBuffer(particleStorageBuffer);
for (auto& buf : particleGfxIndirectBuffers) { destroyBuffer(buf); }
particleGfxIndirectBuffers.clear();
destroyBuffer(particleCompIndirectBuffer);
destroyBuffer(particleDispatchTableBuffer);
particlePipelines.clear();
particlePipelineMap.clear();
particleGfxSystems.clear();
particleCompPipelines.clear();
particleCompPipelineMap.clear();
particleCompSystems.clear();
destroyDualBuffer(shaderCapacities);
destroyBuffer(dummyIndirectBuffer);
destroyDualBuffer(skeletonShaderCapacities);
destroyBuffer(skeletonDummyIndirectBuffer);
for(auto& buffer : indirectBuffers) {
for(auto& buf : buffer) {
destroyBuffer(buf);
}
buffer.clear();
}
for(auto& buffer : skeletonIndirectBuffers) {
for(auto& buf : buffer) {
destroyBuffer(buf);
}
buffer.clear();
}
meshPipelineMap.clear();
meshPipelines.clear();
skeletonMeshPipelineMap.clear();
skeletonMeshPipelines.clear();
}
void Renderer::updatePipelineDescriptorSets(){
for (auto& meshPipeline : meshPipelines) {
meshPipeline.updateDescriptorSetWrites();
}
for (auto& skeletonPipeline : skeletonMeshPipelines) {
skeletonPipeline.updateDescriptorSetWrites();
}
}
void Renderer::recordFrame(uint32_t frameIndex){
getSwapchainImageIndex(frameIndex);
beginCommand(command[frameIndex]);
// --- Dynamic block: upload only the slots that changed this frame.
// copyModelMatricesToGPU / copyObjectInstancesToGPU (called by ECS
// systems before recordFrame) already wrote only dirty elements to
// the staging buffers and returned their indices. Static entities
// (Component::Static) stop producing dirty indices after their
// first MAX_FRAMES_IN_FLIGHT frames, so they never incur a GPU
// copy again. Dynamic entities are re-marked dirty every frame by
// the "Non Static Transform Update" system and always appear here.
objectInstancesGPU[frameIndex].recordSyncRanges(command[frameIndex], dirtyObjectInstanceIndices[frameIndex]);
modelMatricesGPU[frameIndex].recordSyncRanges(command[frameIndex], dirtyModelMatrixIndices[frameIndex]);
cameraBuffer[frameIndex].recordSync(command[frameIndex]);
lightsGPU[frameIndex].recordSync(command[frameIndex]);
GetAssetManager().recordSync(command[frameIndex]);
// Skeleton mesh instance and bone matrix uploads
skeletonMeshInstancesGPU[frameIndex].recordSyncRanges(command[frameIndex], dirtySkeletonMeshInstanceIndices[frameIndex]);
skeletonInstancesGPU[frameIndex].recordSyncRanges(command[frameIndex], dirtySkeletonInstanceIndices_[frameIndex]);
dirtySkeletonInstanceIndices_[frameIndex].clear();
// Particle system instance uploads and deltaTime uniform
particleSystemInstancesGPU[frameIndex].recordSyncRanges(command[frameIndex], dirtyParticleSystemIndices[frameIndex]);
particleDeltaTimeBuffer[frameIndex].recordSync(command[frameIndex]);
vkCmdFillBuffer(command[frameIndex].vkCommandBuffer, drawCounts[frameIndex].vkBuffer, 0, VK_WHOLE_SIZE, 0);
for (auto& indirectBuffer : indirectBuffers[frameIndex]) {
vkCmdFillBuffer(command[frameIndex].vkCommandBuffer, indirectBuffer.vkBuffer, 0, VK_WHOLE_SIZE, 0);
}
// Clear skeleton draw counts and indirect buffers
vkCmdFillBuffer(command[frameIndex].vkCommandBuffer, skeletonDrawCounts[frameIndex].vkBuffer, 0, VK_WHOLE_SIZE, 0);
for (auto& indirectBuffer : skeletonIndirectBuffers[frameIndex]) {
vkCmdFillBuffer(command[frameIndex].vkCommandBuffer, indirectBuffer.vkBuffer, 0, VK_WHOLE_SIZE, 0);
}
// Clear depth pre-pass buffers — only zero the portion that the
// uber cull shader can actually write to (objectInstances.getSize()
// commands at most) plus the count word, instead of the full
// MAX_OBJECTS * 20-byte buffer.
{
const VkDeviceSize usedBytes = static_cast<VkDeviceSize>(objectInstances.getSize()) * sizeof(VkDrawIndexedIndirectCommand);
const VkDeviceSize fillSize = usedBytes > 0 ? usedBytes : 4;
vkCmdFillBuffer(command[frameIndex].vkCommandBuffer, depthPrePassBuffer[frameIndex].vkBuffer, 0, fillSize, 0);
}
vkCmdFillBuffer(command[frameIndex].vkCommandBuffer, depthPrePassCountBuffer[frameIndex].vkBuffer, 0, VK_WHOLE_SIZE, 0);
// Clear skeleton depth pre-pass buffers
{
const VkDeviceSize usedBytes = static_cast<VkDeviceSize>(skeletonMeshInstances.getSize()) * sizeof(VkDrawIndexedIndirectCommand);
const VkDeviceSize fillSize = usedBytes > 0 ? usedBytes : 4;
vkCmdFillBuffer(command[frameIndex].vkCommandBuffer, skeletonDepthPrePassBuffer[frameIndex].vkBuffer, 0, fillSize, 0);
}
vkCmdFillBuffer(command[frameIndex].vkCommandBuffer, skeletonDepthPrePassCountBuffer[frameIndex].vkBuffer, 0, VK_WHOLE_SIZE, 0);
vkCmdFillBuffer(command[frameIndex].vkCommandBuffer, lightIndicesBuffer[frameIndex].vkBuffer, 0, VK_WHOLE_SIZE, 0);
// Reset per-pipeline particle graphics indirect buffers and draw counts.
// The cull shader packs visible draw commands from index 0 and writes the
// per-pipeline count into particleGfxDrawCounts so the GPU knows how many to draw.
if (!particleGfxIndirectBuffers.empty()) {
vkCmdFillBuffer(command[frameIndex].vkCommandBuffer,
particleGfxDrawCounts[frameIndex].vkBuffer, 0, VK_WHOLE_SIZE, 0);
for (auto& gfxBuf : particleGfxIndirectBuffers) {
vkCmdFillBuffer(command[frameIndex].vkCommandBuffer,
gfxBuf.vkBuffer, 0, VK_WHOLE_SIZE, 0);
}
}
VkMemoryBarrier transferToShaderBarrier{};
transferToShaderBarrier.sType = VK_STRUCTURE_TYPE_MEMORY_BARRIER;
transferToShaderBarrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
transferToShaderBarrier.dstAccessMask = VK_ACCESS_UNIFORM_READ_BIT |
VK_ACCESS_SHADER_READ_BIT |
VK_ACCESS_SHADER_WRITE_BIT;
vkCmdPipelineBarrier(
command[frameIndex].vkCommandBuffer,
VK_PIPELINE_STAGE_TRANSFER_BIT,
VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT |
VK_PIPELINE_STAGE_VERTEX_SHADER_BIT |
VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT,
0,
1,
&transferToShaderBarrier,
0,
nullptr,
0,
nullptr
);
{
VkDescriptorSet descriptorSet = uberCullPipeline->getVkDescriptorSet(frameIndex);
vkCmdBindPipeline(
command[frameIndex].vkCommandBuffer,
VK_PIPELINE_BIND_POINT_COMPUTE,
uberCullPipeline->getVkPipeline()
);
vkCmdBindDescriptorSets(
command[frameIndex].vkCommandBuffer,
VK_PIPELINE_BIND_POINT_COMPUTE,
uberCullPipeline->getVkPipelineLayout(),
0,
1,
&descriptorSet,
0,
nullptr
);
constexpr uint32_t WORKGROUP_SIZE_X = 256;
if (objectInstances.getSize() > 0) {
const uint32_t groupCountX = (objectInstances.getSize() + WORKGROUP_SIZE_X - 1) / WORKGROUP_SIZE_X;
vkCmdDispatch(command[frameIndex].vkCommandBuffer, groupCountX, 1, 1);
}
}
// --- Skeleton cull compute dispatch ---
{
VkDescriptorSet descriptorSet = skeletonCullPipeline->getVkDescriptorSet(frameIndex);
vkCmdBindPipeline(
command[frameIndex].vkCommandBuffer,
VK_PIPELINE_BIND_POINT_COMPUTE,
skeletonCullPipeline->getVkPipeline()
);
vkCmdBindDescriptorSets(
command[frameIndex].vkCommandBuffer,
VK_PIPELINE_BIND_POINT_COMPUTE,
skeletonCullPipeline->getVkPipelineLayout(),
0,
1,
&descriptorSet,
0,
nullptr
);
constexpr uint32_t WORKGROUP_SIZE_X = 256;
if (skeletonMeshInstances.getSize() > 0) {
const uint32_t groupCountX = (skeletonMeshInstances.getSize() + WORKGROUP_SIZE_X - 1) / WORKGROUP_SIZE_X;
vkCmdDispatch(command[frameIndex].vkCommandBuffer, groupCountX, 1, 1);
}
}
// --- Particle cull dispatch ---
// One invocation per registered particle system slot.
// Writes VkDrawIndexedIndirectCommand into particleGfxIndirectBuffer (per slot),
// atomically accumulates x into particleCompIndirectBuffer (per comp pipeline),
// and writes dispatchTable entries mapping global workgroup ID -> (particleBase, systemSlot).
if (particleSystemRegisteredCount > 0 && particleCullPipeline) {
// Reset x=0 for each active comp pipeline. y and z remain 1 (written at registration).
// vkCmdUpdateBuffer is a TRANSFER command, covered by the existing transferToShaderBarrier.
for (uint32_t k = 0; k < static_cast<uint32_t>(particleCompPipelines.size()); ++k) {
const VkDispatchIndirectCommand reset{0, 1, 1};
vkCmdUpdateBuffer(command[frameIndex].vkCommandBuffer,
particleCompIndirectBuffer.vkBuffer,
k * sizeof(VkDispatchIndirectCommand),
sizeof(VkDispatchIndirectCommand), &reset);
}
struct ParticleCullPC { uint32_t systemCount; uint32_t _pad; };
ParticleCullPC pc{ particleSystemRegisteredCount, 0u };
VkDescriptorSet descSet = particleCullPipeline->getVkDescriptorSet(frameIndex);
vkCmdBindPipeline(command[frameIndex].vkCommandBuffer,
VK_PIPELINE_BIND_POINT_COMPUTE,
particleCullPipeline->getVkPipeline());
vkCmdBindDescriptorSets(command[frameIndex].vkCommandBuffer,
VK_PIPELINE_BIND_POINT_COMPUTE,
particleCullPipeline->getVkPipelineLayout(),
0, 1, &descSet, 0, nullptr);
vkCmdPushConstants(command[frameIndex].vkCommandBuffer,
particleCullPipeline->getVkPipelineLayout(),
VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(ParticleCullPC), &pc);
constexpr uint32_t CULL_WORKGROUP = 64;
const uint32_t cullGroups = (particleSystemRegisteredCount + CULL_WORKGROUP - 1) / CULL_WORKGROUP;
vkCmdDispatch(command[frameIndex].vkCommandBuffer, cullGroups, 1, 1);
// Barrier: cull writes (comp indirect x, gfx indirect, dispatch table, active flags)
// must be visible before:
// - sim dispatches read comp indirect (INDIRECT_COMMAND_READ) and dispatch table (SHADER_READ)
// - draw-indirect stage reads gfx indirect (INDIRECT_COMMAND_READ, later in the frame)
VkMemoryBarrier particleCullBarrier{};
particleCullBarrier.sType = VK_STRUCTURE_TYPE_MEMORY_BARRIER;
particleCullBarrier.srcAccessMask = VK_ACCESS_SHADER_WRITE_BIT;
particleCullBarrier.dstAccessMask = VK_ACCESS_INDIRECT_COMMAND_READ_BIT | VK_ACCESS_SHADER_READ_BIT;
vkCmdPipelineBarrier(command[frameIndex].vkCommandBuffer,
VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT,
VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT | VK_PIPELINE_STAGE_DRAW_INDIRECT_BIT,
0, 1, &particleCullBarrier, 0, nullptr, 0, nullptr);
}
// --- Particle simulation: ONE vkCmdDispatchIndirect per comp pipeline ---
// The cull shader:
// - accumulated x = total workgroups into particleCompIndirectBuffer[K]
// - wrote dispatchTable[K * MAX_DISPATCH_PER_PIPELINE + (0..x-1)]
// = { particleBase, systemSlot } for every scheduled workgroup
// The sim shader reads dispatchTable[pipelineIndex * MAX_DISPATCH_PER_PIPELINE
// + gl_WorkGroupID.x] to find its work.
for (uint32_t compIdx = 0; compIdx < static_cast<uint32_t>(particleCompPipelines.size()); ++compIdx) {
if (particleCompSystems[compIdx].empty()) continue;
VkDescriptorSet descSet = particleCompPipelines[compIdx]->getVkDescriptorSet(frameIndex);
vkCmdBindPipeline(command[frameIndex].vkCommandBuffer,
VK_PIPELINE_BIND_POINT_COMPUTE,
particleCompPipelines[compIdx]->getVkPipeline());
vkCmdBindDescriptorSets(command[frameIndex].vkCommandBuffer,
VK_PIPELINE_BIND_POINT_COMPUTE,
particleCompPipelines[compIdx]->getVkPipelineLayout(),
0, 1, &descSet, 0, nullptr);
// Pass pipelineIndex so the shader can compute its dispatch table base:
// dispatchTable[pipelineIndex * MAX_DISPATCH_PER_PIPELINE + gl_WorkGroupID.x]
vkCmdPushConstants(command[frameIndex].vkCommandBuffer,
particleCompPipelines[compIdx]->getVkPipelineLayout(),
VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(uint32_t), &compIdx);
// x = total workgroups for all visible systems using this pipeline.
vkCmdDispatchIndirect(command[frameIndex].vkCommandBuffer,
particleCompIndirectBuffer.vkBuffer,
static_cast<VkDeviceSize>(compIdx) * sizeof(VkDispatchIndirectCommand));
}
{
// Ensure compute writes (cull + particle simulation) are visible
// to the subsequent depth pre-pass indirect draw and vertex reads.
VkMemoryBarrier uberToDepthBarrier{};
uberToDepthBarrier.sType = VK_STRUCTURE_TYPE_MEMORY_BARRIER;
uberToDepthBarrier.srcAccessMask = VK_ACCESS_SHADER_WRITE_BIT;
uberToDepthBarrier.dstAccessMask = VK_ACCESS_INDIRECT_COMMAND_READ_BIT |
VK_ACCESS_SHADER_READ_BIT;
vkCmdPipelineBarrier(
command[frameIndex].vkCommandBuffer,
VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT,
VK_PIPELINE_STAGE_DRAW_INDIRECT_BIT |
VK_PIPELINE_STAGE_VERTEX_SHADER_BIT |
VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT,
0,
1,
&uberToDepthBarrier,
0,
nullptr,
0,
nullptr
);
}
// --- Depth pre-pass: render into a single-sample depth map used by light culling ---
{
// Ensure depth map is transitioned to depth attachment optimal
VkImageMemoryBarrier depthBarrierInit{};
depthBarrierInit.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
depthBarrierInit.oldLayout = VK_IMAGE_LAYOUT_UNDEFINED;
depthBarrierInit.newLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
depthBarrierInit.srcAccessMask = 0;
depthBarrierInit.dstAccessMask = VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT;
depthBarrierInit.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
depthBarrierInit.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
depthBarrierInit.image = depthMaps[frameIndex].vkImage;
depthBarrierInit.subresourceRange.aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT;
depthBarrierInit.subresourceRange.baseMipLevel = 0;
depthBarrierInit.subresourceRange.levelCount = 1;
depthBarrierInit.subresourceRange.baseArrayLayer = 0;
depthBarrierInit.subresourceRange.layerCount = 1;
vkCmdPipelineBarrier(
command[frameIndex].vkCommandBuffer,
VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT,
VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT,
0,
0, nullptr,
0, nullptr,
1, &depthBarrierInit
);
// Begin rendering to the depth map only
VkRenderingAttachmentInfo depthAttachment{};
depthAttachment.sType = VK_STRUCTURE_TYPE_RENDERING_ATTACHMENT_INFO;
depthAttachment.imageView = depthMaps[frameIndex].vkImageView;
depthAttachment.imageLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
depthAttachment.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR;
depthAttachment.storeOp = VK_ATTACHMENT_STORE_OP_STORE;
depthAttachment.clearValue.depthStencil = {1.0f, 0};
VkRenderingInfo depthRenderingInfo{};
depthRenderingInfo.sType = VK_STRUCTURE_TYPE_RENDERING_INFO;
depthRenderingInfo.renderArea.offset = {0, 0};
depthRenderingInfo.renderArea.extent = vkExtent2D;
depthRenderingInfo.layerCount = 1;
depthRenderingInfo.viewMask = 0;
depthRenderingInfo.colorAttachmentCount = 0;
depthRenderingInfo.pColorAttachments = nullptr;
depthRenderingInfo.pDepthAttachment = &depthAttachment;
depthRenderingInfo.pStencilAttachment = nullptr;
vkCmdBeginRendering(command[frameIndex].vkCommandBuffer, &depthRenderingInfo);
// Bind depth pipeline and draw all meshes (indirect buffers per mesh)
vkCmdBindPipeline(
command[frameIndex].vkCommandBuffer,
VK_PIPELINE_BIND_POINT_GRAPHICS,
depthPipeline->getVkPipeline()
);
VkDescriptorSet depthDesc = depthPipeline->getVkDescriptorSet(frameIndex);
vkCmdBindDescriptorSets(
command[frameIndex].vkCommandBuffer,
VK_PIPELINE_BIND_POINT_GRAPHICS,
depthPipeline->getVkPipelineLayout(),
0,
1,
&depthDesc,
0,
nullptr
);
const Buffer vertexBuffer = GetAssetManager().getVertexBuffer();
const Buffer indexBuffer = GetAssetManager().getIndexBuffer();
VkBuffer vkVertexBuffer = vertexBuffer.vkBuffer;
VkDeviceSize offsets[] = {0};
vkCmdBindVertexBuffers(command[frameIndex].vkCommandBuffer, 0, 1, &vkVertexBuffer, offsets);
vkCmdBindIndexBuffer(command[frameIndex].vkCommandBuffer, indexBuffer.vkBuffer, 0, VK_INDEX_TYPE_UINT32);
const uint32_t meshPipelineCount = static_cast<uint32_t>(meshPipelines.size());
LCA_ASSERT(meshPipelineCount == static_cast<uint32_t>(indirectBuffers[frameIndex].size()), "Renderer", "recordFrame", "meshPipelines and indirectBuffers size mismatch.");
// Draw all visible objects using the single depth pre-pass indirect buffer
vkCmdDrawIndexedIndirectCount(
command[frameIndex].vkCommandBuffer,
depthPrePassBuffer[frameIndex].vkBuffer,
0,
depthPrePassCountBuffer[frameIndex].vkBuffer,
0,
depthPrePassBuffer[frameIndex].numberElements,
sizeof(VkDrawIndexedIndirectCommand)
);
// --- Skeleton depth pre-pass ---
vkCmdBindPipeline(
command[frameIndex].vkCommandBuffer,
VK_PIPELINE_BIND_POINT_GRAPHICS,
skeletonDepthPipeline->getVkPipeline()
);
VkDescriptorSet skelDepthDesc = skeletonDepthPipeline->getVkDescriptorSet(frameIndex);
vkCmdBindDescriptorSets(
command[frameIndex].vkCommandBuffer,
VK_PIPELINE_BIND_POINT_GRAPHICS,
skeletonDepthPipeline->getVkPipelineLayout(),
0,
1,
&skelDepthDesc,
0,
nullptr
);
{
const Buffer skelVertexBuffer = GetAssetManager().getSkeletonVertexBuffer();
const Buffer skelIndexBuffer = GetAssetManager().getSkeletonIndexBuffer();
VkBuffer vkSkelVertexBuffer = skelVertexBuffer.vkBuffer;
vkCmdBindVertexBuffers(command[frameIndex].vkCommandBuffer, 0, 1, &vkSkelVertexBuffer, offsets);
vkCmdBindIndexBuffer(command[frameIndex].vkCommandBuffer, skelIndexBuffer.vkBuffer, 0, VK_INDEX_TYPE_UINT32);
}
vkCmdDrawIndexedIndirectCount(
command[frameIndex].vkCommandBuffer,
skeletonDepthPrePassBuffer[frameIndex].vkBuffer,
0,
skeletonDepthPrePassCountBuffer[frameIndex].vkBuffer,
0,
skeletonDepthPrePassBuffer[frameIndex].numberElements,
sizeof(VkDrawIndexedIndirectCommand)
);
vkCmdEndRendering(command[frameIndex].vkCommandBuffer);
// Transition depth map to shader read for the light cull compute shader
VkImageMemoryBarrier depthBarrierToRead{};
depthBarrierToRead.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
depthBarrierToRead.srcAccessMask = VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT;
depthBarrierToRead.dstAccessMask = VK_ACCESS_SHADER_READ_BIT;
depthBarrierToRead.oldLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
depthBarrierToRead.newLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
depthBarrierToRead.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
depthBarrierToRead.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
depthBarrierToRead.image = depthMaps[frameIndex].vkImage;
depthBarrierToRead.subresourceRange.aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT;
depthBarrierToRead.subresourceRange.baseMipLevel = 0;
depthBarrierToRead.subresourceRange.levelCount = 1;
depthBarrierToRead.subresourceRange.baseArrayLayer = 0;
depthBarrierToRead.subresourceRange.layerCount = 1;
vkCmdPipelineBarrier(
command[frameIndex].vkCommandBuffer,
VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT |
VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT,
VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT,
0,
0, nullptr,
0, nullptr,
1, &depthBarrierToRead
);
}
// --- Light cull compute dispatch ---
{
VkDescriptorSet descriptorSet = lightCullPipeline->getVkDescriptorSet(frameIndex);
vkCmdBindPipeline(
command[frameIndex].vkCommandBuffer,
VK_PIPELINE_BIND_POINT_COMPUTE,
lightCullPipeline->getVkPipeline()
);
vkCmdBindDescriptorSets(
command[frameIndex].vkCommandBuffer,
VK_PIPELINE_BIND_POINT_COMPUTE,
lightCullPipeline->getVkPipelineLayout(),
0,
1,
&descriptorSet,
0,
nullptr
);
const uint32_t groupCountX = (vkExtent2D.width + TILE_WIDTH - 1u) / TILE_WIDTH;
const uint32_t groupCountY = (vkExtent2D.height + TILE_HEIGHT - 1u) / TILE_HEIGHT;
vkCmdDispatch(command[frameIndex].vkCommandBuffer, groupCountX, groupCountY, 1);
}
// Make light cull compute writes visible to fragment shader SSBO reads.
VkBufferMemoryBarrier lightIndicesBarrier{};
lightIndicesBarrier.sType = VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER;
lightIndicesBarrier.srcAccessMask = VK_ACCESS_SHADER_WRITE_BIT;
lightIndicesBarrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT;
lightIndicesBarrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
lightIndicesBarrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
lightIndicesBarrier.buffer = lightIndicesBuffer[frameIndex].vkBuffer;
lightIndicesBarrier.offset = 0;
lightIndicesBarrier.size = VK_WHOLE_SIZE;
vkCmdPipelineBarrier(
command[frameIndex].vkCommandBuffer,
VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT,
VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT,
0,
0,
nullptr,
1,
&lightIndicesBarrier,
0,
nullptr
);
// Use dynamic rendering (vkCmdBeginRendering / vkCmdEndRendering)
{
VkImage swapImage = swapchain.vkImages[swapchain.imageIndex];
// Transition swapchain image from UNDEFINED to COLOR_ATTACHMENT_OPTIMAL before rendering
VkImageMemoryBarrier swapBarrierInit{};
swapBarrierInit.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
swapBarrierInit.srcAccessMask = 0;
swapBarrierInit.dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;
swapBarrierInit.oldLayout = VK_IMAGE_LAYOUT_UNDEFINED;
swapBarrierInit.newLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
swapBarrierInit.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
swapBarrierInit.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
swapBarrierInit.image = swapImage;
swapBarrierInit.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
swapBarrierInit.subresourceRange.baseMipLevel = 0;
swapBarrierInit.subresourceRange.levelCount = 1;
swapBarrierInit.subresourceRange.baseArrayLayer = 0;
swapBarrierInit.subresourceRange.layerCount = 1;
vkCmdPipelineBarrier(
command[frameIndex].vkCommandBuffer,
VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT,
VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT,
0,
0, nullptr,
0, nullptr,
1, &swapBarrierInit
);
// Color attachment: use multisampled transient color image and resolve to swapchain view
VkRenderingAttachmentInfo colorAttachment{};
colorAttachment.sType = VK_STRUCTURE_TYPE_RENDERING_ATTACHMENT_INFO;
colorAttachment.imageView = framebuffers.colorImages[swapchain.imageIndex].vkImageView;
colorAttachment.imageLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
colorAttachment.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR;
colorAttachment.storeOp = VK_ATTACHMENT_STORE_OP_STORE;
colorAttachment.clearValue.color = {{0.0f, 0.0f, 0.0f, 1.0f}};
colorAttachment.resolveMode = VK_RESOLVE_MODE_AVERAGE_BIT;
colorAttachment.resolveImageView = swapchain.vkImageViews[swapchain.imageIndex];
colorAttachment.resolveImageLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
// Depth attachment: per-frame transient depth image (must match sample count of colorAttachment)
VkRenderingAttachmentInfo depthAttachment{};
depthAttachment.sType = VK_STRUCTURE_TYPE_RENDERING_ATTACHMENT_INFO;
depthAttachment.imageView = framebuffers.depthImages[swapchain.imageIndex].vkImageView;
depthAttachment.imageLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
depthAttachment.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR;
depthAttachment.storeOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
depthAttachment.clearValue.depthStencil = {1.0f, 0};
VkRenderingInfo renderingInfo{};
renderingInfo.sType = VK_STRUCTURE_TYPE_RENDERING_INFO;
renderingInfo.pNext = nullptr;
renderingInfo.flags = 0;
renderingInfo.renderArea.offset = {0, 0};
renderingInfo.renderArea.extent = vkExtent2D;
renderingInfo.layerCount = 1;
renderingInfo.viewMask = 0;
renderingInfo.colorAttachmentCount = 1;
renderingInfo.pColorAttachments = &colorAttachment;
renderingInfo.pDepthAttachment = &depthAttachment;
renderingInfo.pStencilAttachment = nullptr;
vkCmdBeginRendering(command[frameIndex].vkCommandBuffer, &renderingInfo);
const Buffer vertexBuffer = GetAssetManager().getVertexBuffer();
const Buffer indexBuffer = GetAssetManager().getIndexBuffer();
VkBuffer vkVertexBuffer = vertexBuffer.vkBuffer;
VkDeviceSize offsets[] = {0};
vkCmdBindVertexBuffers(command[frameIndex].vkCommandBuffer, 0, 1, &vkVertexBuffer, offsets);
vkCmdBindIndexBuffer(command[frameIndex].vkCommandBuffer, indexBuffer.vkBuffer, 0, VK_INDEX_TYPE_UINT32);
const uint32_t meshPipelineCount = static_cast<uint32_t>(meshPipelines.size());
LCA_ASSERT(meshPipelineCount == static_cast<uint32_t>(indirectBuffers[frameIndex].size()), "Renderer", "recordFrame", "meshPipelines and indirectBuffers size mismatch.");
for (uint32_t i = 0; i < meshPipelineCount; ++i) {
MeshPipeline& meshPipeline = meshPipelines[i];
VkDescriptorSet descriptorSet = meshPipeline.getVkDescriptorSet(frameIndex);
vkCmdBindPipeline(
command[frameIndex].vkCommandBuffer,
VK_PIPELINE_BIND_POINT_GRAPHICS,
meshPipeline.getVkPipeline()
);
vkCmdBindDescriptorSets(
command[frameIndex].vkCommandBuffer,
VK_PIPELINE_BIND_POINT_GRAPHICS,
meshPipeline.getVkPipelineLayout(),
0,
1,
&descriptorSet,
0,
nullptr
);
const Buffer& indirectBuffer = indirectBuffers[frameIndex][i];
const VkDeviceSize drawCountOffset = static_cast<VkDeviceSize>(i) * sizeof(uint32_t);
vkCmdDrawIndexedIndirectCount(
command[frameIndex].vkCommandBuffer,
indirectBuffer.vkBuffer,
0,
drawCounts[frameIndex].vkBuffer,
drawCountOffset,
indirectBuffer.numberElements,
sizeof(VkDrawIndexedIndirectCommand)
);
}
// --- Skeleton mesh rendering ---
{
const Buffer skelVertexBuffer = GetAssetManager().getSkeletonVertexBuffer();
const Buffer skelIndexBuffer = GetAssetManager().getSkeletonIndexBuffer();
VkBuffer vkSkelVertexBuffer = skelVertexBuffer.vkBuffer;
vkCmdBindVertexBuffers(command[frameIndex].vkCommandBuffer, 0, 1, &vkSkelVertexBuffer, offsets);
vkCmdBindIndexBuffer(command[frameIndex].vkCommandBuffer, skelIndexBuffer.vkBuffer, 0, VK_INDEX_TYPE_UINT32);
const uint32_t skelPipelineCount = static_cast<uint32_t>(skeletonMeshPipelines.size());
LCA_ASSERT(skelPipelineCount == static_cast<uint32_t>(skeletonIndirectBuffers[frameIndex].size()), "Renderer", "recordFrame", "skeletonMeshPipelines and skeletonIndirectBuffers size mismatch.");
for (uint32_t i = 0; i < skelPipelineCount; ++i) {
SkeletonMeshPipeline& skelPipeline = skeletonMeshPipelines[i];
VkDescriptorSet descriptorSet = skelPipeline.getVkDescriptorSet(frameIndex);
vkCmdBindPipeline(
command[frameIndex].vkCommandBuffer,
VK_PIPELINE_BIND_POINT_GRAPHICS,
skelPipeline.getVkPipeline()
);
vkCmdBindDescriptorSets(
command[frameIndex].vkCommandBuffer,
VK_PIPELINE_BIND_POINT_GRAPHICS,
skelPipeline.getVkPipelineLayout(),
0,
1,
&descriptorSet,
0,
nullptr
);
const Buffer& skelIndirectBuffer = skeletonIndirectBuffers[frameIndex][i];
const VkDeviceSize skelDrawCountOffset = static_cast<VkDeviceSize>(i) * sizeof(uint32_t);
vkCmdDrawIndexedIndirectCount(
command[frameIndex].vkCommandBuffer,
skelIndirectBuffer.vkBuffer,
0,
skeletonDrawCounts[frameIndex].vkBuffer,
skelDrawCountOffset,
skelIndirectBuffer.numberElements,
sizeof(VkDrawIndexedIndirectCommand)
);
}
}
// --- Particle system rendering ---
// Each particle system has one VkDrawIndexedIndirectCommand at
// particleGfxIndirectBuffer[slot]. The cull shader sets instanceCount=0
// for culled systems so the GPU skips them with zero GPU work.
if (!particlePipelines.empty()) {
const Buffer meshVertexBuffer = GetAssetManager().getVertexBuffer();
const Buffer meshIndexBuffer = GetAssetManager().getIndexBuffer();
VkBuffer vkMeshVB = meshVertexBuffer.vkBuffer;
vkCmdBindVertexBuffers(command[frameIndex].vkCommandBuffer, 0, 1, &vkMeshVB, offsets);
vkCmdBindIndexBuffer(command[frameIndex].vkCommandBuffer, meshIndexBuffer.vkBuffer, 0, VK_INDEX_TYPE_UINT32);
for (uint32_t gfxIdx = 0; gfxIdx < static_cast<uint32_t>(particlePipelines.size()); ++gfxIdx) {
const auto& slots = particleGfxSystems[gfxIdx];
if (slots.empty()) continue;
VkDescriptorSet descSet = particlePipelines[gfxIdx].getVkDescriptorSet(frameIndex);
vkCmdBindPipeline(command[frameIndex].vkCommandBuffer,
VK_PIPELINE_BIND_POINT_GRAPHICS,
particlePipelines[gfxIdx].getVkPipeline());
vkCmdBindDescriptorSets(command[frameIndex].vkCommandBuffer,
VK_PIPELINE_BIND_POINT_GRAPHICS,
particlePipelines[gfxIdx].getVkPipelineLayout(),
0, 1, &descSet, 0, nullptr);
// One batched draw call per gfx pipeline.
// The cull shader packed visible draw commands from index 0 and wrote
// the count into particleGfxDrawCounts[gfxIdx].
// firstInstance = particleOffset → gl_InstanceIndex = absolute particle index
// The vertex shader reads particle.params.y (floatBitsToUint) to get
// the system slot for transform and material lookup.
vkCmdDrawIndexedIndirectCount(
command[frameIndex].vkCommandBuffer,
particleGfxIndirectBuffers[gfxIdx].vkBuffer,
0,
particleGfxDrawCounts[frameIndex].vkBuffer,
static_cast<VkDeviceSize>(gfxIdx) * sizeof(uint32_t),
particleGfxIndirectBuffers[gfxIdx].numberElements,
sizeof(VkDrawIndexedIndirectCommand));
}
}
vkCmdEndRendering(command[frameIndex].vkCommandBuffer);
// Transition the swapchain image from COLOR_ATTACHMENT_OPTIMAL to PRESENT_SRC_KHR for presentation
VkImageMemoryBarrier swapBarrierPresent{};
swapBarrierPresent.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
swapBarrierPresent.srcAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;
swapBarrierPresent.dstAccessMask = 0;
swapBarrierPresent.oldLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
swapBarrierPresent.newLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR;
swapBarrierPresent.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
swapBarrierPresent.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
swapBarrierPresent.image = swapImage;
swapBarrierPresent.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
swapBarrierPresent.subresourceRange.baseMipLevel = 0;
swapBarrierPresent.subresourceRange.levelCount = 1;
swapBarrierPresent.subresourceRange.baseArrayLayer = 0;
swapBarrierPresent.subresourceRange.layerCount = 1;
vkCmdPipelineBarrier(
command[frameIndex].vkCommandBuffer,
VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT,
VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT,
0,
0, nullptr,
0, nullptr,
1, &swapBarrierPresent
);
}
endCommand(command[frameIndex]);
}
void Renderer::submitFrame(uint32_t frameIndex){
submitGraphicsCommand(command[frameIndex], frameIndex);
presentGraphics(command[frameIndex], frameIndex);
}
uint32_t Renderer::addModelMatrix(const ModelMatrix& matrix){
return modelMatrices.add(matrix);
}
void Renderer::removeModelMatrix(uint32_t id){
modelMatrices.remove(id);
}
uint32_t Renderer::addObjectInstance(const ObjectInstance& instance){
uint32_t id = objectInstances.add(instance);
return id;
}
void Renderer::updateObjectInstance(uint32_t id, const ObjectInstance& instance){
objectInstances.update(id, instance);
}
void Renderer::removeObjectInstance(uint32_t id){
objectInstances.remove(id);
}
uint32_t Renderer::addMeshPipeline(const std::string& name, MeshPipeline&& pipeline, uint32_t maxObjects){
LCA_ASSERT(meshPipelineMap.find(name) == meshPipelineMap.end(), "Renderer", "addMeshPipeline", "Mesh pipeline name already exists.")
LCA_ASSERT(meshPipelines.size() < MAX_SHADERS, "Renderer", "addMeshPipeline", "Exceeded MAX_SHADERS capacity.")
LCA_ASSERT(maxObjects > 0, "Renderer", "addMeshPipeline", "maxObjects must be greater than 0.")
meshPipelines.push_back(std::move(pipeline));
const uint32_t id = static_cast<uint32_t>(meshPipelines.size() - 1);
meshPipelines.back().build();
meshPipelineMap[name] = id;
for(uint32_t i = 0; i < MAX_FRAMES_IN_FLIGHT; i++) {
Buffer buffer = createBuffer(maxObjects, sizeof(VkDrawIndexedIndirectCommand), VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_INDIRECT_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT);
indirectBuffers[i].push_back(buffer);
}
auto* capacities = static_cast<uint32_t*>(shaderCapacities.interface.pMemory);
capacities[id] = maxObjects;
beginSingleCommand(singleCommand);
shaderCapacities.recordSync(singleCommand);
endSingleCommand(singleCommand);
submitSingleCommand(singleCommand);
uberCullPipeline->updateDescriptorSetWrites();
return id;
}
uint32_t Renderer::getMeshPipelineId(const std::string& name) const {
auto it = meshPipelineMap.find(name);
LCA_ASSERT(it != meshPipelineMap.end(), "Renderer", "getMeshPipelineId", "Mesh pipeline name not found.")
return it->second;
}
// ── Skeleton mesh instances ────────────────────────────
uint32_t Renderer::addSkeletonMeshInstance(const SkeletonMeshInstance& instance){
return skeletonMeshInstances.add(instance);
}
void Renderer::updateSkeletonMeshInstance(uint32_t id, const SkeletonMeshInstance& instance){
skeletonMeshInstances.update(id, instance);
}
void Renderer::removeSkeletonMeshInstance(uint32_t id){
skeletonMeshInstances.remove(id);
}
// ── Skeleton instances (bone matrices) ─────────────────
uint32_t Renderer::addSkeletonInstance(){
uint32_t id;
if(!freeSkeletonInstanceSlots.empty()){
id = freeSkeletonInstanceSlots.back();
freeSkeletonInstanceSlots.pop_back();