-
Notifications
You must be signed in to change notification settings - Fork 297
Expand file tree
/
Copy pathRenderer.java
More file actions
821 lines (618 loc) · 28.2 KB
/
Renderer.java
File metadata and controls
821 lines (618 loc) · 28.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
package net.vulkanmod.vulkan;
import com.mojang.blaze3d.platform.GlStateManager;
import it.unimi.dsi.fastutil.objects.ObjectArrayList;
import it.unimi.dsi.fastutil.objects.ObjectOpenHashSet;
import net.minecraft.client.Minecraft;
import net.vulkanmod.Initializer;
import net.vulkanmod.gl.GlFramebuffer;
import net.vulkanmod.mixin.window.WindowAccessor;
import net.vulkanmod.render.PipelineManager;
import net.vulkanmod.render.chunk.WorldRenderer;
import net.vulkanmod.render.chunk.buffer.UploadManager;
import net.vulkanmod.render.profiling.Profiler;
import net.vulkanmod.render.texture.ImageUploadHelper;
import net.vulkanmod.vulkan.device.DeviceManager;
import net.vulkanmod.vulkan.framebuffer.Framebuffer;
import net.vulkanmod.vulkan.framebuffer.RenderPass;
import net.vulkanmod.vulkan.framebuffer.SwapChain;
import net.vulkanmod.vulkan.memory.MemoryManager;
import net.vulkanmod.vulkan.pass.DefaultMainPass;
import net.vulkanmod.vulkan.pass.MainPass;
import net.vulkanmod.vulkan.queue.Queue;
import net.vulkanmod.vulkan.shader.GraphicsPipeline;
import net.vulkanmod.vulkan.shader.Pipeline;
import net.vulkanmod.vulkan.shader.PipelineState;
import net.vulkanmod.vulkan.shader.Uniforms;
import net.vulkanmod.vulkan.shader.layout.PushConstants;
import net.vulkanmod.vulkan.texture.VTextureSelector;
import net.vulkanmod.vulkan.util.VUtil;
import net.vulkanmod.vulkan.util.VkResult;
import org.lwjgl.PointerBuffer;
import org.lwjgl.system.MemoryStack;
import org.lwjgl.system.MemoryUtil;
import org.lwjgl.vulkan.*;
import java.nio.ByteBuffer;
import java.nio.IntBuffer;
import java.nio.LongBuffer;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import static com.mojang.blaze3d.platform.GlConst.GL_COLOR_BUFFER_BIT;
import static com.mojang.blaze3d.platform.GlConst.GL_DEPTH_BUFFER_BIT;
import static net.vulkanmod.vulkan.Vulkan.*;
import static org.lwjgl.system.MemoryStack.stackPush;
import static org.lwjgl.vulkan.EXTDebugUtils.*;
import static org.lwjgl.vulkan.KHRSwapchain.*;
import static org.lwjgl.vulkan.VK10.*;
public class Renderer {
private static Renderer INSTANCE;
private static VkDevice device;
private static boolean swapChainUpdate = false;
public static boolean skipRendering = false;
private static final boolean sync2 = DeviceManager.checkExt(KHRSynchronization2.VK_KHR_SYNCHRONIZATION_2_EXTENSION_NAME);
public static void initRenderer() {
INSTANCE = new Renderer();
INSTANCE.init();
}
public static Renderer getInstance() {
return INSTANCE;
}
public static Drawer getDrawer() {
return INSTANCE.drawer;
}
public static int getCurrentFrame() {
return currentFrame;
}
public static int getCurrentImage() {
return imageIndex;
}
private final Set<Pipeline> usedPipelines = new ObjectOpenHashSet<>();
private Pipeline boundPipeline;
private long boundPipelineHandle;
private Drawer drawer;
private SwapChain swapChain;
private int framesNum;
private List<VkCommandBuffer> commandBuffers;
private ArrayList<Long> imageAvailableSemaphores;
private ArrayList<Long> renderFinishedSemaphores;
private long inFlightSubmits;
private Framebuffer boundFramebuffer;
private RenderPass boundRenderPass;
private static int currentFrame = 0;
private static int imageIndex;
private static int lastReset = -1;
private VkCommandBuffer currentCmdBuffer;
private boolean recordingCmds = false;
MainPass mainPass;
private final List<Runnable> onResizeCallbacks = new ObjectArrayList<>();
public Renderer() {
device = Vulkan.getVkDevice();
framesNum = Initializer.CONFIG.frameQueueSize;
}
public static void setLineWidth(float width) {
if (INSTANCE.boundFramebuffer == null) {
return;
}
vkCmdSetLineWidth(INSTANCE.currentCmdBuffer, width);
}
private void init() {
MemoryManager.createInstance(Renderer.getFramesNum());
Vulkan.createStagingBuffers();
swapChain = new SwapChain();
mainPass = DefaultMainPass.create();
drawer = new Drawer();
drawer.createResources(framesNum);
Uniforms.setupDefaultUniforms();
PipelineManager.init();
UploadManager.createInstance();
allocateCommandBuffers();
createSyncObjects();
}
private void allocateCommandBuffers() {
if (commandBuffers != null) {
commandBuffers.forEach(commandBuffer -> vkFreeCommandBuffers(device, Vulkan.getCommandPool(), commandBuffer));
}
commandBuffers = new ArrayList<>(framesNum);
try (MemoryStack stack = stackPush()) {
VkCommandBufferAllocateInfo allocInfo = VkCommandBufferAllocateInfo.calloc(stack);
allocInfo.sType(VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO);
allocInfo.commandPool(getCommandPool());
allocInfo.level(VK_COMMAND_BUFFER_LEVEL_PRIMARY);
allocInfo.commandBufferCount(framesNum);
PointerBuffer pCommandBuffers = stack.mallocPointer(framesNum);
int vkResult = vkAllocateCommandBuffers(device, allocInfo, pCommandBuffers);
if (vkResult != VK_SUCCESS) {
throw new RuntimeException("Failed to allocate command buffers: %s".formatted(VkResult.decode(vkResult)));
}
for (int i = 0; i < framesNum; i++) {
commandBuffers.add(new VkCommandBuffer(pCommandBuffers.get(i), device));
}
}
}
private void createSyncObjects() {
imageAvailableSemaphores = new ArrayList<>(framesNum);
renderFinishedSemaphores = new ArrayList<>(framesNum);
try (MemoryStack stack = stackPush()) {
VkSemaphoreCreateInfo semaphoreInfo = VkSemaphoreCreateInfo.calloc(stack);
semaphoreInfo.sType(VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO);
LongBuffer pImageAvailableSemaphore = stack.mallocLong(1);
LongBuffer pRenderFinishedSemaphore = stack.mallocLong(1);
for (int i = 0; i < framesNum; i++) {
if (vkCreateSemaphore(device, semaphoreInfo, null, pImageAvailableSemaphore) != VK_SUCCESS
|| vkCreateSemaphore(device, semaphoreInfo, null, pRenderFinishedSemaphore) != VK_SUCCESS) {
throw new RuntimeException("Failed to create synchronization objects for the frame: " + i);
}
imageAvailableSemaphores.add(pImageAvailableSemaphore.get(0));
renderFinishedSemaphores.add(pRenderFinishedSemaphore.get(0));
}
}
}
public void preInitFrame() {
Profiler p = Profiler.getMainProfiler();
p.pop();
p.round();
p.push("Frame_ops");
// runTick might be called recursively,
// this check forces sync to avoid upload corruption
if (lastReset == currentFrame) {
submitPending();
}
lastReset = currentFrame;
drawer.resetBuffers(currentFrame);
WorldRenderer.getInstance().uploadSections();
UploadManager.INSTANCE.submitUploads();
}
public void beginFrame() {
Profiler p = Profiler.getMainProfiler();
p.pop();
p.push("Frame_fence");
if (swapChainUpdate) {
recreateSwapChain();
swapChainUpdate = false;
if (getSwapChain().getWidth() == 0 && getSwapChain().getHeight() == 0) {
skipRendering = true;
Minecraft.getInstance().noRender = true;
} else {
skipRendering = false;
Minecraft.getInstance().noRender = false;
}
}
if (skipRendering || recordingCmds)
return;
try (MemoryStack stack = stackPush()) {
//Wait on previous frame's submit: (framesNum - 1) is equal to Max Frames in Flight
// Mimics Array and Current Frame index by "Stepping Back" in the timeline
//TODO: Possible Nvidia VSync bug: stutter when submitting > 1 Submits in Flight (when in FIFO mode)
final int maxFiF = swapChain.isVsync() ? 1 : framesNum - 1;
DeviceManager.getGraphicsQueue().waitSubmits(stack, Math.max(0L, inFlightSubmits - maxFiF));
//Testing using Graphics Timeline as a substitute for inFlightFences
//Aggregate frame fences and Graphics Queue fences together as one
p.pop();
p.push("Begin_rendering");
MemoryManager.getInstance().initFrame(currentFrame);
drawer.setCurrentFrame(currentFrame);
resetDescriptors();
currentCmdBuffer = commandBuffers.get(currentFrame);
IntBuffer pImageIndex = stack.mallocInt(1);
int vkResult = vkAcquireNextImageKHR(device, swapChain.getId(), VUtil.UINT64_MAX,
imageAvailableSemaphores.get(currentFrame), VK_NULL_HANDLE, pImageIndex);
if (vkResult == VK_SUBOPTIMAL_KHR || vkResult == VK_ERROR_OUT_OF_DATE_KHR || swapChainUpdate) {
swapChainUpdate = true;
skipRendering = true;
beginFrame();
return;
} else if (vkResult != VK_SUCCESS) {
throw new RuntimeException("Cannot acquire next swap chain image: %s".formatted(VkResult.decode(vkResult)));
}
imageIndex = pImageIndex.get(0);
this.beginRenderPass(stack);
}
p.pop();
}
private void beginRenderPass(MemoryStack stack) {
VkCommandBufferBeginInfo beginInfo = VkCommandBufferBeginInfo.calloc(stack);
beginInfo.sType(VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO);
beginInfo.flags(VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT);
VkCommandBuffer commandBuffer = currentCmdBuffer;
int vkResult = vkBeginCommandBuffer(commandBuffer, beginInfo);
if (vkResult != VK_SUCCESS) {
throw new RuntimeException("Failed to begin recording command buffer: %s".formatted(VkResult.decode(vkResult)));
}
recordingCmds = true;
mainPass.begin(commandBuffer, stack);
resetDynamicState(commandBuffer);
}
public void endFrame() {
if (skipRendering || !recordingCmds)
return;
Profiler p = Profiler.getMainProfiler();
p.push("End_rendering");
mainPass.end(currentCmdBuffer);
submitPending();
submitFrame();
recordingCmds = false;
p.pop();
p.push("Post_rendering");
}
private void submitFrame() {
if (swapChainUpdate)
return;
try (MemoryStack stack = stackPush()) {
//Wait Async Transfers on host to avoid invalid frees (Destroy Buffer during use)
DeviceManager.getTransferQueue().waitSubmits(stack);
final long submitId = sync2 ? getSubmitId2(stack) : getSubmitId(stack);
VkPresentInfoKHR presentInfo = VkPresentInfoKHR.calloc(stack);
presentInfo.sType(VK_STRUCTURE_TYPE_PRESENT_INFO_KHR);
presentInfo.pWaitSemaphores(stack.longs(renderFinishedSemaphores.get(currentFrame)));
presentInfo.swapchainCount(1);
presentInfo.pSwapchains(stack.longs(swapChain.getId()));
presentInfo.pImageIndices(stack.ints(imageIndex));
final int vkResult = vkQueuePresentKHR(DeviceManager.getPresentQueue().queue(), presentInfo);
if (vkResult == VK_ERROR_OUT_OF_DATE_KHR || vkResult == VK_SUBOPTIMAL_KHR || swapChainUpdate) {
swapChainUpdate = true;
return;
} else if (vkResult != VK_SUCCESS) {
throw new RuntimeException("Failed to present rendered frame: %s".formatted(VkResult.decode(vkResult)));
}
currentFrame = (currentFrame + 1) % framesNum;
inFlightSubmits = submitId;
}
}
// Workaround used to fix macOS compatibility:
// LWJGL 3.3.3 uses an outdated MVK version, which doesn't support Sync2: (LWJGL 3.3.4 required for Sync2 on MoltenVK)
// Cannot be used on Nvidia due to using Host sync, which destabilizes VSync
//
// Remove when Mojang Updates to LWJGL 3.3.4+: (Allowing Sync2 Support on macOS)
private long getSubmitId(MemoryStack stack) {
Queue graphicsQueue = DeviceManager.getGraphicsQueue();
final int vkResult;
//Can't sync the GPU fully w/o Sync2, must use Host sync instead (Breaks Nvidia VSync)
graphicsQueue.waitSubmits(stack);
VkTimelineSemaphoreSubmitInfo mainSemaphoreSubmitInfo = VkTimelineSemaphoreSubmitInfo.calloc(stack)
.sType$Default()
.pSignalSemaphoreValues(stack.longs(0, graphicsQueue.submitCountAdd()));
VkSubmitInfo submitInfo = VkSubmitInfo.calloc(stack);
submitInfo.sType(VK_STRUCTURE_TYPE_SUBMIT_INFO);
submitInfo.pNext(mainSemaphoreSubmitInfo);
submitInfo.waitSemaphoreCount(1);
submitInfo.pWaitSemaphores(stack.longs(imageAvailableSemaphores.get(currentFrame)));
submitInfo.pWaitDstStageMask(stack.ints(VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT));
submitInfo.pSignalSemaphores(stack.longs(renderFinishedSemaphores.get(currentFrame), graphicsQueue.getTmSemaphore()));
submitInfo.pCommandBuffers(stack.pointers(currentCmdBuffer));
if ((vkResult = vkQueueSubmit(graphicsQueue.queue(), submitInfo, 0)) != VK_SUCCESS) {
throw new RuntimeException("Failed to submit draw command buffer: %s".formatted(VkResult.decode(vkResult)));
}
return graphicsQueue.submitCount();
}
//Used to Fix VSync stability on Nvidia: Used when Sync2 is supported (Most Vk1.2 Systems)
private long getSubmitId2(MemoryStack stack) {
Queue graphicsQueue = DeviceManager.getGraphicsQueue();
final int vkResult;
VkCommandBufferSubmitInfo.Buffer commandBufferSubmitInfo = VkCommandBufferSubmitInfo.calloc(1, stack)
.sType$Default()
.commandBuffer(currentCmdBuffer);
//Nvidia; Replace fence waits with a submit barrier: restoring VSync stability on Nvidia
VkSemaphoreSubmitInfo.Buffer waitSemaphoreSubmitInfo = VkSemaphoreSubmitInfo.calloc(2, stack);
waitSemaphoreSubmitInfo.get(0).sType$Default()
.semaphore(imageAvailableSemaphores.get(currentFrame))
.stageMask(VK13.VK_PIPELINE_STAGE_2_CLEAR_BIT) //Attachment Clears
.value(0);
waitSemaphoreSubmitInfo.get(1).sType$Default()
.semaphore(graphicsQueue.getTmSemaphore())
.stageMask(VK13.VK_PIPELINE_STAGE_2_VERTEX_SHADER_BIT) //LightMap Sampler Transitions
.value(graphicsQueue.submitCount());
VkSemaphoreSubmitInfo.Buffer mainSemaphoreSubmitInfo = VkSemaphoreSubmitInfo.calloc(2, stack);
mainSemaphoreSubmitInfo.get(0).sType$Default()
.semaphore(renderFinishedSemaphores.get(currentFrame))
.stageMask(VK13.VK_PIPELINE_STAGE_2_ALL_GRAPHICS_BIT)
.value(0);
mainSemaphoreSubmitInfo.get(1).sType$Default()
.semaphore(graphicsQueue.getTmSemaphore())
.stageMask(VK13.VK_PIPELINE_STAGE_2_ALL_GRAPHICS_BIT)
.value(graphicsQueue.submitCountAdd());
VkSubmitInfo2.Buffer submitInfo = VkSubmitInfo2.calloc(1, stack)
.sType$Default()
.pWaitSemaphoreInfos(waitSemaphoreSubmitInfo)
.pSignalSemaphoreInfos(mainSemaphoreSubmitInfo)
.pCommandBufferInfos(commandBufferSubmitInfo);
if ((vkResult = KHRSynchronization2.vkQueueSubmit2KHR(graphicsQueue.queue(), submitInfo, 0)) != VK_SUCCESS) {
throw new RuntimeException("Failed to submit draw command buffer: %s".formatted(VkResult.decode(vkResult)));
}
return graphicsQueue.submitCount();
}
/**
* Called in case draw results are needed before the of the frame
*/
public void flushCmds() {
if (!this.recordingCmds)
return;
try (MemoryStack stack = stackPush()) {
this.endRenderPass(currentCmdBuffer);
vkEndCommandBuffer(currentCmdBuffer);
submitPending();
final long submitId = sync2 ? getSubmitId2(stack) : getSubmitId(stack);
DeviceManager.getGraphicsQueue().waitSubmits(stack, submitId);
this.beginRenderPass(stack);
}
}
public void endRenderPass() {
endRenderPass(currentCmdBuffer);
}
public void endRenderPass(VkCommandBuffer commandBuffer) {
if (skipRendering || !recordingCmds || this.boundFramebuffer == null)
return;
if (!DYNAMIC_RENDERING)
this.boundRenderPass.endRenderPass(currentCmdBuffer);
else
KHRDynamicRendering.vkCmdEndRenderingKHR(commandBuffer);
this.boundRenderPass = null;
this.boundFramebuffer = null;
GlFramebuffer.resetBoundFramebuffer();
}
public boolean beginRendering(RenderPass renderPass, Framebuffer framebuffer) {
if (skipRendering || !recordingCmds)
return false;
if (this.boundFramebuffer != framebuffer) {
this.endRenderPass(currentCmdBuffer);
try (MemoryStack stack = stackPush()) {
framebuffer.beginRenderPass(currentCmdBuffer, renderPass, stack);
}
this.boundFramebuffer = framebuffer;
}
return true;
}
public void addUsedPipeline(Pipeline pipeline) {
usedPipelines.add(pipeline);
}
public void removeUsedPipeline(Pipeline pipeline) {
usedPipelines.remove(pipeline);
}
//Synchronization fences are merged into vkQueueSubmit2 submit Barrier, reducing sync overhead and improving frametime
private void submitPending() {
ImageUploadHelper.INSTANCE.submitCommands();
Synchronization.INSTANCE.recycleCmdBuffers();
Vulkan.getStagingBuffer().reset();
}
private void resetDescriptors() {
for (Pipeline pipeline : usedPipelines) {
pipeline.resetDescriptorPool(currentFrame);
}
usedPipelines.clear();
boundPipeline = null;
boundPipelineHandle = 0;
}
@SuppressWarnings("UnreachableCode")
private void recreateSwapChain() {
submitPending();
Vulkan.waitIdle();
commandBuffers.forEach(commandBuffer -> vkResetCommandBuffer(commandBuffer, 0));
recordingCmds = false;
swapChain.recreate();
//Semaphores need to be recreated in order to make them unsignaled
destroySyncObjects();
int newFramesNum = Initializer.CONFIG.frameQueueSize;
if (framesNum != newFramesNum) {
UploadManager.INSTANCE.submitUploads();
framesNum = newFramesNum;
MemoryManager.getInstance().freeAllBuffers();
MemoryManager.createInstance(newFramesNum);
createStagingBuffers();
allocateCommandBuffers();
Pipeline.recreateDescriptorSets(framesNum);
drawer.createResources(framesNum);
}
createSyncObjects();
this.onResizeCallbacks.forEach(Runnable::run);
((WindowAccessor) (Object) Minecraft.getInstance().getWindow()).getEventHandler().resizeDisplay();
currentFrame = 0;
}
public void cleanUpResources() {
WorldRenderer.getInstance().cleanUp();
destroySyncObjects();
drawer.cleanUpResources();
mainPass.cleanUp();
swapChain.cleanUp();
PipelineManager.destroyPipelines();
VTextureSelector.getWhiteTexture().free();
}
private void destroySyncObjects() {
for (int i = 0; i < framesNum; ++i) {
vkDestroySemaphore(device, imageAvailableSemaphores.get(i), null);
vkDestroySemaphore(device, renderFinishedSemaphores.get(i), null);
}
}
public void addOnResizeCallback(Runnable runnable) {
this.onResizeCallbacks.add(runnable);
}
public void bindGraphicsPipeline(GraphicsPipeline pipeline) {
VkCommandBuffer commandBuffer = currentCmdBuffer;
PipelineState currentState = PipelineState.getCurrentPipelineState(boundRenderPass);
final long handle = pipeline.getHandle(currentState);
if (boundPipelineHandle == handle) {
return;
}
vkCmdBindPipeline(commandBuffer, VK_PIPELINE_BIND_POINT_GRAPHICS, handle);
boundPipelineHandle = handle;
boundPipeline = pipeline;
addUsedPipeline(pipeline);
}
public void uploadAndBindUBOs(Pipeline pipeline) {
VkCommandBuffer commandBuffer = currentCmdBuffer;
pipeline.bindDescriptorSets(commandBuffer, currentFrame);
}
public void pushConstants(Pipeline pipeline) {
VkCommandBuffer commandBuffer = currentCmdBuffer;
PushConstants pushConstants = pipeline.getPushConstants();
try (MemoryStack stack = stackPush()) {
ByteBuffer buffer = stack.malloc(pushConstants.getSize());
long ptr = MemoryUtil.memAddress0(buffer);
pushConstants.update(ptr);
nvkCmdPushConstants(commandBuffer, pipeline.getLayout(), VK_SHADER_STAGE_VERTEX_BIT, 0, pushConstants.getSize(), ptr);
}
}
public Pipeline getBoundPipeline() {
return boundPipeline;
}
public void setBoundFramebuffer(Framebuffer framebuffer) {
this.boundFramebuffer = framebuffer;
}
public void setBoundRenderPass(RenderPass boundRenderPass) {
this.boundRenderPass = boundRenderPass;
}
public RenderPass getBoundRenderPass() {
return boundRenderPass;
}
public void setMainPass(MainPass mainPass) {
this.mainPass = mainPass;
}
public MainPass getMainPass() {
return this.mainPass;
}
public SwapChain getSwapChain() {
return swapChain;
}
private static void resetDynamicState(VkCommandBuffer commandBuffer) {
vkCmdSetDepthBias(commandBuffer, 0.0F, 0.0F, 0.0F);
vkCmdSetLineWidth(commandBuffer, 1.0F);
}
public static void setDepthBias(float units, float factor) {
VkCommandBuffer commandBuffer = INSTANCE.currentCmdBuffer;
vkCmdSetDepthBias(commandBuffer, units, 0.0f, factor);
}
public static void clearAttachments(int v) {
Framebuffer framebuffer = Renderer.getInstance().boundFramebuffer;
if (framebuffer == null)
return;
clearAttachments(v, framebuffer.getWidth(), framebuffer.getHeight());
}
public static void clearAttachments(int v, int width, int height) {
if (skipRendering)
return;
try (MemoryStack stack = stackPush()) {
//ClearValues have to be different for each attachment to clear,
//it seems it uses the same buffer: color and depth values override themselves
VkClearValue colorValue = VkClearValue.calloc(stack);
colorValue.color().float32(VRenderSystem.clearColor);
VkClearValue depthValue = VkClearValue.calloc(stack);
depthValue.depthStencil().set(VRenderSystem.clearDepthValue, 0); //Use fast depth clears if possible
int attachmentsCount = v == (GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT) ? 2 : 1;
final VkClearAttachment.Buffer pAttachments = VkClearAttachment.malloc(attachmentsCount, stack);
switch (v) {
case GL_DEPTH_BUFFER_BIT -> {
VkClearAttachment clearDepth = pAttachments.get(0);
clearDepth.aspectMask(VK_IMAGE_ASPECT_DEPTH_BIT);
clearDepth.colorAttachment(0);
clearDepth.clearValue(depthValue);
}
case GL_COLOR_BUFFER_BIT -> {
VkClearAttachment clearColor = pAttachments.get(0);
clearColor.aspectMask(VK_IMAGE_ASPECT_COLOR_BIT);
clearColor.colorAttachment(0);
clearColor.clearValue(colorValue);
}
case GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT -> {
VkClearAttachment clearColor = pAttachments.get(0);
clearColor.aspectMask(VK_IMAGE_ASPECT_COLOR_BIT);
clearColor.colorAttachment(0);
clearColor.clearValue(colorValue);
VkClearAttachment clearDepth = pAttachments.get(1);
clearDepth.aspectMask(VK_IMAGE_ASPECT_DEPTH_BIT);
clearDepth.colorAttachment(0);
clearDepth.clearValue(depthValue);
}
default -> throw new RuntimeException("unexpected value");
}
//Rect to clear
VkRect2D renderArea = VkRect2D.malloc(stack);
renderArea.offset().set(0, 0);
renderArea.extent().set(width, height);
VkClearRect.Buffer pRect = VkClearRect.malloc(1, stack);
pRect.rect(renderArea);
pRect.baseArrayLayer(0);
pRect.layerCount(1);
vkCmdClearAttachments(INSTANCE.currentCmdBuffer, pAttachments, pRect);
}
}
public static void setInvertedViewport(int x, int y, int width, int height) {
setViewportState(x, y + height, width, -height);
}
public static void resetViewport() {
int width = INSTANCE.getSwapChain().getWidth();
int height = INSTANCE.getSwapChain().getHeight();
setViewportState(0, 0, width, height);
}
public static void setViewportState(int x, int y, int width, int height) {
GlStateManager._viewport(x, y, width, height);
}
public static void setViewport(int x, int y, int width, int height) {
try (MemoryStack stack = stackPush()) {
setViewport(x, y, width, height, stack);
}
}
public static void setViewport(int x, int y, int width, int height, MemoryStack stack) {
if (!INSTANCE.recordingCmds)
return;
VkViewport.Buffer viewport = VkViewport.malloc(1, stack);
viewport.x(x);
viewport.y(height + y);
viewport.width(width);
viewport.height(-height);
viewport.minDepth(0.0f);
viewport.maxDepth(1.0f);
vkCmdSetViewport(INSTANCE.currentCmdBuffer, 0, viewport);
}
public static void setScissor(int x, int y, int width, int height) {
if (INSTANCE.boundFramebuffer == null)
return;
try (MemoryStack stack = stackPush()) {
int framebufferHeight = INSTANCE.boundFramebuffer.getHeight();
x = Math.max(0, x);
VkRect2D.Buffer scissor = VkRect2D.malloc(1, stack);
scissor.offset().set(x, framebufferHeight - (y + height));
scissor.extent().set(width, height);
vkCmdSetScissor(INSTANCE.currentCmdBuffer, 0, scissor);
}
}
public static void resetScissor() {
if (INSTANCE.boundFramebuffer == null)
return;
try (MemoryStack stack = stackPush()) {
VkRect2D.Buffer scissor = INSTANCE.boundFramebuffer.scissor(stack);
vkCmdSetScissor(INSTANCE.currentCmdBuffer, 0, scissor);
}
}
public static void pushDebugSection(String s) {
if (Vulkan.ENABLE_VALIDATION_LAYERS) {
VkCommandBuffer commandBuffer = INSTANCE.currentCmdBuffer;
try (MemoryStack stack = stackPush()) {
VkDebugUtilsLabelEXT markerInfo = VkDebugUtilsLabelEXT.calloc(stack);
markerInfo.sType(VK_STRUCTURE_TYPE_DEBUG_UTILS_LABEL_EXT);
ByteBuffer string = stack.UTF8(s);
markerInfo.pLabelName(string);
vkCmdBeginDebugUtilsLabelEXT(commandBuffer, markerInfo);
}
}
}
public static void popDebugSection() {
if (Vulkan.ENABLE_VALIDATION_LAYERS) {
VkCommandBuffer commandBuffer = INSTANCE.currentCmdBuffer;
vkCmdEndDebugUtilsLabelEXT(commandBuffer);
}
}
public static void popPushDebugSection(String s) {
popDebugSection();
pushDebugSection(s);
}
public static int getFramesNum() {
return INSTANCE.framesNum;
}
public static VkCommandBuffer getCommandBuffer() {
return INSTANCE.currentCmdBuffer;
}
public static boolean isRecording() {
return INSTANCE.recordingCmds;
}
public static void scheduleSwapChainUpdate() {
swapChainUpdate = true;
}
}