source: opengl-game/vulkan-game.hpp@ 0807aeb

feature/imgui-sdl points-test
Last change on this file since 0807aeb was 0807aeb, checked in by Dmitry Portnoy <dmp1488@…>, 5 years ago

Spawn asteroids at a regular interval and make them move in the player's direction, change the movement of all game objects to depend on elapsed time and be framerate-independent, and switch from SDL2 timers to the C++ chrono library

  • Property mode set to 100644
File size: 11.9 KB
Line 
1#ifndef _VULKAN_GAME_H
2#define _VULKAN_GAME_H
3
4#include <chrono>
5
6#define GLM_FORCE_RADIANS
7#define GLM_FORCE_DEPTH_ZERO_TO_ONE // Since, in Vulkan, the depth range is 0 to 1 instead of -1 to 1
8#define GLM_FORCE_RIGHT_HANDED
9
10#include <glm/glm.hpp>
11#include <glm/gtc/matrix_transform.hpp>
12
13#include "game-gui-sdl.hpp"
14#include "graphics-pipeline_vulkan.hpp"
15
16#include "vulkan-utils.hpp"
17
18using namespace glm;
19using namespace std::chrono;
20
21#ifdef NDEBUG
22 const bool ENABLE_VALIDATION_LAYERS = false;
23#else
24 const bool ENABLE_VALIDATION_LAYERS = true;
25#endif
26
27struct OverlayVertex {
28 vec3 pos;
29 vec2 texCoord;
30};
31
32struct ModelVertex {
33 vec3 pos;
34 vec3 color;
35 vec2 texCoord;
36 unsigned int objIndex;
37};
38
39struct ShipVertex {
40 vec3 pos;
41 vec3 color;
42 vec3 normal;
43 unsigned int objIndex;
44};
45
46struct AsteroidVertex {
47 vec3 pos;
48 vec3 color;
49 vec3 normal;
50 unsigned int objIndex;
51};
52
53// TODO: Change the index type to uint32_t and check the Vulkan Tutorial loading model section as a reference
54// TODO: Create a typedef for index type so I can easily change uin16_t to something else later
55template<class VertexType, class SSBOType>
56struct SceneObject {
57 vector<VertexType> vertices;
58 vector<uint16_t> indices;
59 SSBOType ssbo;
60
61 mat4 model_base;
62 mat4 model_transform;
63 vec3 center;
64 float radius;
65};
66
67struct UBO_VP_mats {
68 alignas(16) mat4 view;
69 alignas(16) mat4 proj;
70};
71
72struct SSBO_ModelObject {
73 alignas(16) mat4 model;
74};
75
76struct SSBO_Asteroid {
77 alignas(16) mat4 model;
78 alignas(4) float hp;
79 alignas(4) unsigned int deleted;
80};
81
82// Have to figure out how to include an optional ssbo parameter for each object
83// Could probably use the same approach to make indices optional
84
85class VulkanGame {
86 public:
87 VulkanGame(int maxFramesInFlight);
88 ~VulkanGame();
89
90 void run(int width, int height, unsigned char guiFlags);
91
92 private:
93 const int MAX_FRAMES_IN_FLIGHT;
94
95 const float NEAR_CLIP = 0.1f;
96 const float FAR_CLIP = 100.0f;
97 const float FOV_ANGLE = 67.0f; // means the camera lens goes from -33 deg to 33 def
98
99 vec3 cam_pos;
100
101 GameGui* gui;
102
103 SDL_version sdlVersion;
104 SDL_Window* window = nullptr;
105 SDL_Renderer* renderer = nullptr;
106
107 SDL_Texture* uiOverlay = nullptr;
108
109 VkInstance instance;
110 VkDebugUtilsMessengerEXT debugMessenger;
111 VkSurfaceKHR surface; // TODO: Change the variable name to vulkanSurface
112 VkPhysicalDevice physicalDevice = VK_NULL_HANDLE;
113 VkDevice device;
114
115 VkQueue graphicsQueue;
116 VkQueue presentQueue;
117
118 VkSwapchainKHR swapChain;
119 vector<VkImage> swapChainImages;
120 VkFormat swapChainImageFormat;
121 VkExtent2D swapChainExtent;
122 vector<VkImageView> swapChainImageViews;
123 vector<VkFramebuffer> swapChainFramebuffers;
124
125 VkRenderPass renderPass;
126 VkCommandPool commandPool;
127 vector<VkCommandBuffer> commandBuffers;
128
129 VulkanImage depthImage;
130
131 VkSampler textureSampler;
132
133 VulkanImage floorTextureImage;
134 VkDescriptorImageInfo floorTextureImageDescriptor;
135
136 VulkanImage sdlOverlayImage;
137 VkDescriptorImageInfo sdlOverlayImageDescriptor;
138
139 TTF_Font* font;
140 SDL_Texture* fontSDLTexture;
141
142 SDL_Texture* imageSDLTexture;
143
144 vector<VkSemaphore> imageAvailableSemaphores;
145 vector<VkSemaphore> renderFinishedSemaphores;
146 vector<VkFence> inFlightFences;
147
148 size_t currentFrame;
149
150 bool framebufferResized;
151
152 GraphicsPipeline_Vulkan<OverlayVertex, void*> overlayPipeline;
153 vector<SceneObject<OverlayVertex, void*>> overlayObjects;
154
155 // TODO: Maybe make the ubo objects part of the pipeline class since there's only one ubo
156 // per pipeline.
157 // Or maybe create a higher level wrapper around GraphicsPipeline_Vulkan to hold things like
158 // the objects vector, the ubo, and the ssbo
159
160 GraphicsPipeline_Vulkan<ModelVertex, SSBO_ModelObject> modelPipeline;
161 vector<SceneObject<ModelVertex, SSBO_ModelObject>> modelObjects;
162
163 vector<VkBuffer> uniformBuffers_modelPipeline;
164 vector<VkDeviceMemory> uniformBuffersMemory_modelPipeline;
165 vector<VkDescriptorBufferInfo> uniformBufferInfoList_modelPipeline;
166
167 UBO_VP_mats object_VP_mats;
168
169 GraphicsPipeline_Vulkan<ShipVertex, SSBO_ModelObject> shipPipeline;
170 vector<SceneObject<ShipVertex, SSBO_ModelObject>> shipObjects;
171
172 vector<VkBuffer> uniformBuffers_shipPipeline;
173 vector<VkDeviceMemory> uniformBuffersMemory_shipPipeline;
174 vector<VkDescriptorBufferInfo> uniformBufferInfoList_shipPipeline;
175
176 UBO_VP_mats ship_VP_mats;
177
178 GraphicsPipeline_Vulkan<AsteroidVertex, SSBO_Asteroid> asteroidPipeline;
179 vector<SceneObject<AsteroidVertex, SSBO_Asteroid>> asteroidObjects;
180
181 vector<VkBuffer> uniformBuffers_asteroidPipeline;
182 vector<VkDeviceMemory> uniformBuffersMemory_asteroidPipeline;
183 vector<VkDescriptorBufferInfo> uniformBufferInfoList_asteroidPipeline;
184
185 UBO_VP_mats asteroid_VP_mats;
186
187 time_point<steady_clock> startTime;
188 float curTime, prevTime, elapsedTime;
189
190 float shipSpeed = 0.5f;
191 float asteroidSpeed = 2.0f;
192
193 float spawnRate_asteroid = 0.5;
194 float lastSpawn_asteroid;
195
196 bool initWindow(int width, int height, unsigned char guiFlags);
197 void initVulkan();
198 void initGraphicsPipelines();
199 void initMatrices();
200 void mainLoop();
201 void updateScene(uint32_t currentImage);
202 void renderUI();
203 void renderScene();
204 void cleanup();
205
206 void createVulkanInstance(const vector<const char*> &validationLayers);
207 void setupDebugMessenger();
208 void populateDebugMessengerCreateInfo(VkDebugUtilsMessengerCreateInfoEXT& createInfo);
209 void createVulkanSurface();
210 void pickPhysicalDevice(const vector<const char*>& deviceExtensions);
211 bool isDeviceSuitable(VkPhysicalDevice physicalDevice, const vector<const char*>& deviceExtensions);
212 void createLogicalDevice(
213 const vector<const char*> validationLayers,
214 const vector<const char*>& deviceExtensions);
215 void createSwapChain();
216 void createImageViews();
217 void createRenderPass();
218 VkFormat findDepthFormat();
219 void createCommandPool();
220 void createImageResources();
221
222 void createTextureSampler();
223 void createFramebuffers();
224 void createCommandBuffers();
225 void createSyncObjects();
226
227 template<class VertexType, class SSBOType>
228 void addObject(vector<SceneObject<VertexType, SSBOType>>& objects,
229 GraphicsPipeline_Vulkan<VertexType, SSBOType>& pipeline,
230 const vector<VertexType>& vertices, vector<uint16_t> indices, SSBOType ssbo,
231 bool pipelinesCreated);
232
233 template<class VertexType, class SSBOType>
234 void updateObject(vector<SceneObject<VertexType, SSBOType>>& objects,
235 GraphicsPipeline_Vulkan<VertexType, SSBOType>& pipeline, size_t index);
236
237 template<class VertexType>
238 vector<VertexType> addVertexNormals(vector<VertexType> vertices);
239
240 template<class VertexType>
241 vector<VertexType> addObjectIndex(unsigned int objIndex, vector<VertexType> vertices);
242
243 template<class VertexType, class SSBOType>
244 void centerObject(SceneObject<VertexType, SSBOType>& object);
245
246 void createBufferSet(VkDeviceSize bufferSize, VkBufferUsageFlags flags,
247 vector<VkBuffer>& buffers, vector<VkDeviceMemory>& buffersMemory, vector<VkDescriptorBufferInfo>& bufferInfoList);
248
249 void recreateSwapChain();
250
251 void cleanupSwapChain();
252
253 static VKAPI_ATTR VkBool32 VKAPI_CALL debugCallback(
254 VkDebugUtilsMessageSeverityFlagBitsEXT messageSeverity,
255 VkDebugUtilsMessageTypeFlagsEXT messageType,
256 const VkDebugUtilsMessengerCallbackDataEXT* pCallbackData,
257 void* pUserData);
258};
259
260// TODO: Right now, it's basically necessary to pass the identity matrix in for ssbo.model
261// and to change the model matrix later by setting model_transform and then calling updateObject()
262// Figure out a better way to allow the model matrix to be set during objecting creation
263template<class VertexType, class SSBOType>
264void VulkanGame::addObject(vector<SceneObject<VertexType, SSBOType>>& objects,
265 GraphicsPipeline_Vulkan<VertexType, SSBOType>& pipeline,
266 const vector<VertexType>& vertices, vector<uint16_t> indices, SSBOType ssbo,
267 bool pipelinesCreated) {
268 size_t numVertices = pipeline.getNumVertices();
269
270 for (uint16_t& idx : indices) {
271 idx += numVertices;
272 }
273
274 objects.push_back({ vertices, indices, ssbo, mat4(1.0f), mat4(1.0f) });
275 centerObject(objects.back());
276
277 bool storageBufferResized = pipeline.addObject(vertices, indices, ssbo, commandPool, graphicsQueue);
278
279 if (pipelinesCreated) {
280 vkDeviceWaitIdle(device);
281 vkFreeCommandBuffers(device, commandPool, static_cast<uint32_t>(commandBuffers.size()), commandBuffers.data());
282
283 // TODO: The pipeline recreation only has to be done once per frame where at least
284 // one SSBO is resized.
285 // Refactor the logic to check for any resized SSBOs after all objects for the frame
286 // are created and then recreate each of the corresponding pipelines only once per frame
287 if (storageBufferResized) {
288 pipeline.createPipeline(pipeline.vertShaderFile, pipeline.fragShaderFile);
289 pipeline.createDescriptorPool(swapChainImages);
290 pipeline.createDescriptorSets(swapChainImages);
291 }
292
293 createCommandBuffers();
294 }
295}
296
297// TODO: Just pass in the single object instead of a list of all of them
298template<class VertexType, class SSBOType>
299void VulkanGame::updateObject(vector<SceneObject<VertexType, SSBOType>>& objects,
300 GraphicsPipeline_Vulkan<VertexType, SSBOType>& pipeline, size_t index) {
301 SceneObject<VertexType, SSBOType>& obj = objects[index];
302
303 obj.ssbo.model = obj.model_transform * obj.model_base;
304
305 // could probably re-calculate the object center here based on model
306 // I think the center should be calculated by using model * vec3(0, 0, 0)
307 // model_base is currently only used to set the original location of the ship and asteroids
308
309 pipeline.updateObject(index, obj.ssbo);
310}
311
312template<class VertexType>
313vector<VertexType> VulkanGame::addVertexNormals(vector<VertexType> vertices) {
314 for (unsigned int i = 0; i < vertices.size(); i += 3) {
315 vec3 p1 = vertices[i].pos;
316 vec3 p2 = vertices[i+1].pos;
317 vec3 p3 = vertices[i+2].pos;
318
319 vec3 normal = normalize(cross(p2 - p1, p3 - p1));
320
321 // Add the same normal for all 3 vertices
322 vertices[i].normal = normal;
323 vertices[i+1].normal = normal;
324 vertices[i+2].normal = normal;
325 }
326
327 return vertices;
328}
329
330template<class VertexType>
331vector<VertexType> VulkanGame::addObjectIndex(unsigned int objIndex, vector<VertexType> vertices) {
332 for (VertexType& vertex : vertices) {
333 vertex.objIndex = objIndex;
334 }
335
336 return vertices;
337}
338
339template<class VertexType, class SSBOType>
340void VulkanGame::centerObject(SceneObject<VertexType, SSBOType>& object) {
341 vector<VertexType>& vertices = object.vertices;
342
343 float min_x = vertices[0].pos.x;
344 float max_x = vertices[0].pos.x;
345 float min_y = vertices[0].pos.y;
346 float max_y = vertices[0].pos.y;
347 float min_z = vertices[0].pos.z;
348 float max_z = vertices[0].pos.z;
349
350 // start from the second point
351 for (unsigned int i = 1; i < vertices.size(); i++) {
352 vec3& pos = vertices[i].pos;
353
354 if (min_x > pos.x) {
355 min_x = pos.x;
356 } else if (max_x < pos.x) {
357 max_x = pos.x;
358 }
359
360 if (min_y > pos.y) {
361 min_y = pos.y;
362 } else if (max_y < pos.y) {
363 max_y = pos.y;
364 }
365
366 if (min_z > pos.z) {
367 min_z = pos.z;
368 } else if (max_z < pos.z) {
369 max_z = pos.z;
370 }
371 }
372
373 vec3 center = vec3(min_x + max_x, min_y + max_y, min_z + max_z) / 2.0f;
374
375 for (unsigned int i = 0; i < vertices.size(); i++) {
376 vertices[i].pos -= center;
377 }
378
379 object.radius = std::max(center.x, center.y);
380 object.radius = std::max(object.radius, center.z);
381 object.center = vec3(0.0f, 0.0f, 0.0f);
382}
383
384#endif // _VULKAN_GAME_H
Note: See TracBrowser for help on using the repository browser.