-
Notifications
You must be signed in to change notification settings - Fork 308
Expand file tree
/
Copy pathSwapChain.java
More file actions
366 lines (279 loc) · 14 KB
/
SwapChain.java
File metadata and controls
366 lines (279 loc) · 14 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
package net.vulkanmod.vulkan.framebuffer;
import it.unimi.dsi.fastutil.longs.Long2ReferenceOpenHashMap;
import net.vulkanmod.Initializer;
import net.vulkanmod.gl.GlTexture;
import net.vulkanmod.render.util.MathUtil;
import net.vulkanmod.vulkan.Renderer;
import net.vulkanmod.vulkan.Vulkan;
import net.vulkanmod.vulkan.device.DeviceManager;
import net.vulkanmod.vulkan.queue.Queue;
import net.vulkanmod.vulkan.texture.VulkanImage;
import org.lwjgl.system.MemoryStack;
import org.lwjgl.vulkan.*;
import java.nio.IntBuffer;
import java.nio.LongBuffer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import static net.vulkanmod.vulkan.Vulkan.*;
import static net.vulkanmod.vulkan.device.DeviceManager.vkDevice;
import static net.vulkanmod.vulkan.util.VUtil.UINT32_MAX;
import static org.lwjgl.glfw.GLFW.glfwGetFramebufferSize;
import static org.lwjgl.system.MemoryStack.stackGet;
import static org.lwjgl.system.MemoryStack.stackPush;
import static org.lwjgl.vulkan.KHRSurface.*;
import static org.lwjgl.vulkan.KHRSwapchain.*;
import static org.lwjgl.vulkan.VK10.*;
public class SwapChain extends Framebuffer {
// Necessary until tearing-control-unstable-v1 is fully implemented on all GPU Drivers for Wayland
// (As Immediate Mode (and by extension Screen tearing) doesn't exist on some Wayland installations currently)
private static final int defUncappedMode = checkPresentMode(VK_PRESENT_MODE_IMMEDIATE_KHR, VK_PRESENT_MODE_MAILBOX_KHR);
private final Long2ReferenceOpenHashMap<long[]> FBO_map = new Long2ReferenceOpenHashMap<>();
private long swapChainId = VK_NULL_HANDLE;
private List<VulkanImage> swapChainImages;
private VkExtent2D extent2D;
public boolean isBGRAformat;
private boolean vsync = false;
private int[] glIds;
public SwapChain() {
this.attachmentCount = 2;
this.depthFormat = Vulkan.getDefaultDepthFormat();
this.hasColorAttachment = true;
this.hasDepthAttachment = true;
recreate();
}
public void recreate() {
if (this.depthAttachment != null) {
this.depthAttachment.free();
this.depthAttachment = null;
}
if (!DYNAMIC_RENDERING) {
this.FBO_map.forEach((pass, framebuffers) -> Arrays.stream(framebuffers).forEach(id -> vkDestroyFramebuffer(getVkDevice(), id, null)));
this.FBO_map.clear();
}
createSwapChain();
}
private void createSwapChain() {
try (MemoryStack stack = stackPush()) {
VkDevice device = Vulkan.getVkDevice();
DeviceManager.SurfaceProperties surfaceProperties = DeviceManager.querySurfaceProperties(device.getPhysicalDevice(), stack);
VkSurfaceFormatKHR surfaceFormat = getFormat(surfaceProperties.formats);
int presentMode = getPresentMode(surfaceProperties.presentModes);
VkExtent2D extent = getExtent(surfaceProperties.capabilities);
if (extent.width() == 0 && extent.height() == 0) {
if (this.swapChainId != VK_NULL_HANDLE) {
this.swapChainImages.forEach(image -> vkDestroyImageView(device, image.getImageView(), null));
vkDestroySwapchainKHR(device, this.swapChainId, null);
this.swapChainId = VK_NULL_HANDLE;
}
this.width = 0;
this.height = 0;
return;
}
int requestedImages = surfaceProperties.capabilities.minImageCount() + 1;
if (surfaceProperties.capabilities.maxImageCount() > 0 && requestedImages > surfaceProperties.capabilities.maxImageCount()) {
requestedImages = surfaceProperties.capabilities.maxImageCount();
}
IntBuffer imageCount = stack.ints(requestedImages);
VkSwapchainCreateInfoKHR createInfo = VkSwapchainCreateInfoKHR.calloc(stack);
createInfo.sType(VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR);
createInfo.surface(Vulkan.getSurface());
// Image settings
this.format = surfaceFormat.format();
this.extent2D = VkExtent2D.create().set(extent);
createInfo.minImageCount(requestedImages);
createInfo.imageFormat(this.format);
createInfo.imageColorSpace(surfaceFormat.colorSpace());
createInfo.imageExtent(extent);
createInfo.imageArrayLayers(1);
createInfo.imageUsage(VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_SAMPLED_BIT);
Queue.QueueFamilyIndices indices = Queue.getQueueFamilies();
if (indices.graphicsFamily != indices.presentFamily) {
createInfo.imageSharingMode(VK_SHARING_MODE_CONCURRENT);
createInfo.pQueueFamilyIndices(stack.ints(indices.graphicsFamily, indices.presentFamily));
} else {
createInfo.imageSharingMode(VK_SHARING_MODE_EXCLUSIVE);
}
createInfo.preTransform(surfaceProperties.capabilities.currentTransform());
int supportedCompositeAlpha = surfaceProperties.capabilities.supportedCompositeAlpha();
if((supportedCompositeAlpha & VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR) != 0) {
createInfo.compositeAlpha(VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR);
}else if((supportedCompositeAlpha & VK_COMPOSITE_ALPHA_INHERIT_BIT_KHR) != 0){
// PowerVR GE8320 Vulkan drivers don't support the alpha composite opaque bit.
// In that case, use the inherit mode if supported.
createInfo.compositeAlpha(VK_COMPOSITE_ALPHA_INHERIT_BIT_KHR);
} else {
// Not sure how to handle the other cases, to be honest...
throw new RuntimeException("Neither opaque, nor inherited alpha compositing modes are supported.");
}
createInfo.presentMode(presentMode);
createInfo.clipped(true);
createInfo.oldSwapchain(this.swapChainId);
LongBuffer pSwapChain = stack.longs(VK_NULL_HANDLE);
int result = vkCreateSwapchainKHR(device, createInfo, null, pSwapChain);
Vulkan.checkResult(result, "Failed to create swap chain");
if (this.swapChainId != VK_NULL_HANDLE) {
this.swapChainImages.forEach(image -> vkDestroyImageView(device, image.getImageView(), null));
vkDestroySwapchainKHR(device, this.swapChainId, null);
}
this.swapChainId = pSwapChain.get(0);
vkGetSwapchainImagesKHR(device, this.swapChainId, imageCount, null);
LongBuffer pSwapchainImages = stack.mallocLong(imageCount.get(0));
vkGetSwapchainImagesKHR(device, this.swapChainId, imageCount, pSwapchainImages);
this.swapChainImages = new ArrayList<>(imageCount.get(0));
this.width = extent2D.width();
this.height = extent2D.height();
for (int i = 0; i < pSwapchainImages.capacity(); i++) {
long imageId = pSwapchainImages.get(i);
long imageView = VulkanImage.createImageView(imageId, this.format, VK_IMAGE_ASPECT_COLOR_BIT, 1);
VulkanImage image = new VulkanImage(imageId, this.format, 1, this.width, this.height, 4, 0, imageView);
image.updateTextureSampler(true, true, false);
this.swapChainImages.add(image);
}
}
createGlIds();
createDepthResources();
}
private void createGlIds() {
this.glIds = new int[this.swapChainImages.size()];
for (int i = 0; i < this.swapChainImages.size(); i++) {
int id = GlTexture.genTextureId();
this.glIds[i] = id;
GlTexture.bindIdToImage(id, this.swapChainImages.get(i));
}
}
public int getColorAttachmentGlId() {
return this.glIds[Renderer.getCurrentImage()];
}
private long[] createFramebuffers(RenderPass renderPass) {
try (MemoryStack stack = MemoryStack.stackPush()) {
long[] framebuffers = new long[this.swapChainImages.size()];
for (int i = 0; i < this.swapChainImages.size(); ++i) {
LongBuffer attachments = stack.longs(this.swapChainImages.get(i).getImageView(), this.depthAttachment.getImageView());
LongBuffer pFramebuffer = stack.mallocLong(1);
VkFramebufferCreateInfo framebufferInfo = VkFramebufferCreateInfo.calloc(stack);
framebufferInfo.sType(VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO);
framebufferInfo.renderPass(renderPass.getId());
framebufferInfo.width(this.width);
framebufferInfo.height(this.height);
framebufferInfo.layers(1);
framebufferInfo.pAttachments(attachments);
if (vkCreateFramebuffer(Vulkan.getVkDevice(), framebufferInfo, null, pFramebuffer) != VK_SUCCESS) {
throw new RuntimeException("Failed to create framebuffer");
}
framebuffers[i] = pFramebuffer.get(0);
}
return framebuffers;
}
}
private void createDepthResources() {
this.depthAttachment = VulkanImage.createDepthImage(depthFormat, this.width, this.height,
VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT | VK_IMAGE_USAGE_SAMPLED_BIT,
false, false);
}
@Override
protected long getFramebufferId(RenderPass renderPass) {
long[] framebuffers = this.FBO_map.computeIfAbsent(renderPass.id, renderPass1 -> createFramebuffers(renderPass));
return framebuffers[Renderer.getCurrentImage()];
}
public void cleanUp() {
VkDevice device = Vulkan.getVkDevice();
if (!DYNAMIC_RENDERING) {
this.FBO_map.forEach((pass, framebuffers) -> Arrays.stream(framebuffers).forEach(id -> vkDestroyFramebuffer(getVkDevice(), id, null)));
this.FBO_map.clear();
}
vkDestroySwapchainKHR(device, this.swapChainId, null);
this.swapChainImages.forEach(image -> vkDestroyImageView(device, image.getImageView(), null));
this.depthAttachment.free();
}
public long getId() {
return this.swapChainId;
}
public List<VulkanImage> getImages() {
return this.swapChainImages;
}
public long getImageId(int i) {
return this.swapChainImages.get(i).getId();
}
public VkExtent2D getExtent() {
return this.extent2D;
}
public VulkanImage getColorAttachment() {
return this.swapChainImages.get(Renderer.getCurrentImage());
}
public long getImageView(int i) {
return this.swapChainImages.get(i).getImageView();
}
private VkSurfaceFormatKHR getFormat(VkSurfaceFormatKHR.Buffer availableFormats) {
List<VkSurfaceFormatKHR> list = availableFormats.stream().toList();
VkSurfaceFormatKHR format = list.get(0);
for (VkSurfaceFormatKHR availableFormat : list) {
if (availableFormat.format() == VK_FORMAT_R8G8B8A8_UNORM && availableFormat.colorSpace() == VK_COLOR_SPACE_SRGB_NONLINEAR_KHR)
return availableFormat;
if (availableFormat.format() == VK_FORMAT_B8G8R8A8_UNORM && availableFormat.colorSpace() == VK_COLOR_SPACE_SRGB_NONLINEAR_KHR) {
format = availableFormat;
}
}
if (format.format() == VK_FORMAT_B8G8R8A8_UNORM)
isBGRAformat = true;
return format;
}
private int getPresentMode(IntBuffer availablePresentModes) {
int requestedMode = vsync ? VK_PRESENT_MODE_FIFO_KHR : defUncappedMode;
// FIFO mode is the only mode that has to be supported
if (requestedMode == VK_PRESENT_MODE_FIFO_KHR)
return VK_PRESENT_MODE_FIFO_KHR;
for (int i = 0; i < availablePresentModes.capacity(); i++) {
if (availablePresentModes.get(i) == requestedMode) {
return requestedMode;
}
}
Initializer.LOGGER.warn("Requested mode not supported: " + getDisplayModeString(requestedMode) + ": using FIFO present mode");
return VK_PRESENT_MODE_FIFO_KHR;
}
private String getDisplayModeString(int requestedMode) {
return switch (requestedMode) {
case VK_PRESENT_MODE_IMMEDIATE_KHR -> "Immediate";
case VK_PRESENT_MODE_MAILBOX_KHR -> "Mailbox (FastSync)";
case VK_PRESENT_MODE_FIFO_RELAXED_KHR -> "FIFO Relaxed (Adaptive VSync)";
default -> "FIFO (VSync)";
};
}
private static VkExtent2D getExtent(VkSurfaceCapabilitiesKHR capabilities) {
if (capabilities.currentExtent().width() != UINT32_MAX) {
return capabilities.currentExtent();
}
//Fallback
IntBuffer width = stackGet().ints(0);
IntBuffer height = stackGet().ints(0);
glfwGetFramebufferSize(window, width, height);
VkExtent2D actualExtent = VkExtent2D.mallocStack().set(width.get(0), height.get(0));
VkExtent2D minExtent = capabilities.minImageExtent();
VkExtent2D maxExtent = capabilities.maxImageExtent();
actualExtent.width(MathUtil.clamp(minExtent.width(), maxExtent.width(), actualExtent.width()));
actualExtent.height(MathUtil.clamp(minExtent.height(), maxExtent.height(), actualExtent.height()));
return actualExtent;
}
private static int checkPresentMode(int... requestedModes) {
try (MemoryStack stack = MemoryStack.stackPush()) {
var a = DeviceManager.querySurfaceProperties(vkDevice.getPhysicalDevice(), stack).presentModes;
for (int dMode : requestedModes) {
for (int i = 0; i < a.capacity(); i++) {
if (a.get(i) == dMode) {
return dMode;
}
}
}
return VK_PRESENT_MODE_FIFO_KHR; //If None of the request modes exist/are supported by Driver
}
}
public boolean isVsync() {
return this.vsync;
}
public void setVsync(boolean vsync) {
this.vsync = vsync;
}
public int getImagesNum() {
return this.swapChainImages.size();
}
}