source: opengl-game/vulkan-game.hpp@ 1f81ecc

feature/imgui-sdl points-test
Last change on this file since 1f81ecc was 1f81ecc, checked in by Dmitry Portnoy <dmitry.portnoy@…>, 4 years ago

Add the ability for the ship to fire a laser from either of its wings

  • Property mode set to 100644
File size: 14.7 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
53struct LaserVertex {
54 vec3 pos;
55 vec2 texCoord;
56 unsigned int objIndex;
57};
58
59struct UBO_VP_mats {
60 alignas(16) mat4 view;
61 alignas(16) mat4 proj;
62};
63
64struct SSBO_ModelObject {
65 alignas(16) mat4 model;
66};
67
68struct SSBO_Asteroid {
69 alignas(16) mat4 model;
70 alignas(4) float hp;
71 alignas(4) unsigned int deleted;
72};
73
74struct SSBO_Laser {
75 alignas(16) mat4 model;
76 alignas(4) vec3 color;
77 alignas(4) unsigned int deleted;
78};
79
80// TODO: Change the index type to uint32_t and check the Vulkan Tutorial loading model section as a reference
81// TODO: Create a typedef for index type so I can easily change uin16_t to something else later
82// TODO: Maybe create a typedef for each of the templated SceneObject types
83template<class VertexType, class SSBOType>
84struct SceneObject {
85 vector<VertexType> vertices;
86 vector<uint16_t> indices;
87 SSBOType ssbo;
88
89 mat4 model_base;
90 mat4 model_transform;
91
92 bool modified;
93
94 // TODO: Figure out if I should make child classes that have these fields instead of putting them in the
95 // parent class
96 vec3 center; // currently only matters for asteroids
97 float radius; // currently only matters for asteroids
98};
99
100// TODO: Have to figure out how to include an optional ssbo parameter for each object
101// Could probably use the same approach to make indices optional
102// Figure out if there are sufficient use cases to make either of these optional or is it fine to make
103// them mamdatory
104
105// TODO: Make a singleton timer class instead
106static float curTime;
107
108class VulkanGame {
109 public:
110 VulkanGame(int maxFramesInFlight);
111 ~VulkanGame();
112
113 void run(int width, int height, unsigned char guiFlags);
114
115 private:
116 const int MAX_FRAMES_IN_FLIGHT;
117
118 const float NEAR_CLIP = 0.1f;
119 const float FAR_CLIP = 100.0f;
120 const float FOV_ANGLE = 67.0f; // means the camera lens goes from -33 deg to 33 def
121
122 vec3 cam_pos;
123
124 GameGui* gui;
125
126 SDL_version sdlVersion;
127 SDL_Window* window = nullptr;
128 SDL_Renderer* renderer = nullptr;
129
130 SDL_Texture* uiOverlay = nullptr;
131
132 VkInstance instance;
133 VkDebugUtilsMessengerEXT debugMessenger;
134 VkSurfaceKHR surface; // TODO: Change the variable name to vulkanSurface
135 VkPhysicalDevice physicalDevice = VK_NULL_HANDLE;
136 VkDevice device;
137
138 VkQueue graphicsQueue;
139 VkQueue presentQueue;
140
141 VkSwapchainKHR swapChain;
142 vector<VkImage> swapChainImages;
143 VkFormat swapChainImageFormat;
144 VkExtent2D swapChainExtent;
145 vector<VkImageView> swapChainImageViews;
146 vector<VkFramebuffer> swapChainFramebuffers;
147
148 VkRenderPass renderPass;
149 VkCommandPool commandPool;
150 vector<VkCommandBuffer> commandBuffers;
151
152 VulkanImage depthImage;
153
154 VkSampler textureSampler;
155
156 VulkanImage sdlOverlayImage;
157 VkDescriptorImageInfo sdlOverlayImageDescriptor;
158
159 VulkanImage floorTextureImage;
160 VkDescriptorImageInfo floorTextureImageDescriptor;
161
162 VulkanImage laserTextureImage;
163 VkDescriptorImageInfo laserTextureImageDescriptor;
164
165 TTF_Font* font;
166 SDL_Texture* fontSDLTexture;
167
168 SDL_Texture* imageSDLTexture;
169
170 vector<VkSemaphore> imageAvailableSemaphores;
171 vector<VkSemaphore> renderFinishedSemaphores;
172 vector<VkFence> inFlightFences;
173
174 size_t currentFrame;
175
176 bool framebufferResized;
177
178 mat4 viewMat, projMat;
179
180 GraphicsPipeline_Vulkan<OverlayVertex, void*> overlayPipeline;
181 vector<SceneObject<OverlayVertex, void*>> overlayObjects;
182
183 // TODO: Maybe make the ubo objects part of the pipeline class since there's only one ubo
184 // per pipeline.
185 // Or maybe create a higher level wrapper around GraphicsPipeline_Vulkan to hold things like
186 // the objects vector, the ubo, and the ssbo
187
188 // TODO: Rename *_VP_mats to *_uniforms and possibly use different types for each one
189 // if there is a need to add other uniform variables to one or more of the shaders
190
191 GraphicsPipeline_Vulkan<ModelVertex, SSBO_ModelObject> modelPipeline;
192 vector<SceneObject<ModelVertex, SSBO_ModelObject>> modelObjects;
193
194 vector<VkBuffer> uniformBuffers_modelPipeline;
195 vector<VkDeviceMemory> uniformBuffersMemory_modelPipeline;
196 vector<VkDescriptorBufferInfo> uniformBufferInfoList_modelPipeline;
197
198 UBO_VP_mats object_VP_mats;
199
200 GraphicsPipeline_Vulkan<ShipVertex, SSBO_ModelObject> shipPipeline;
201 vector<SceneObject<ShipVertex, SSBO_ModelObject>> shipObjects;
202
203 vector<VkBuffer> uniformBuffers_shipPipeline;
204 vector<VkDeviceMemory> uniformBuffersMemory_shipPipeline;
205 vector<VkDescriptorBufferInfo> uniformBufferInfoList_shipPipeline;
206
207 UBO_VP_mats ship_VP_mats;
208
209 GraphicsPipeline_Vulkan<AsteroidVertex, SSBO_Asteroid> asteroidPipeline;
210 vector<SceneObject<AsteroidVertex, SSBO_Asteroid>> asteroidObjects;
211
212 vector<VkBuffer> uniformBuffers_asteroidPipeline;
213 vector<VkDeviceMemory> uniformBuffersMemory_asteroidPipeline;
214 vector<VkDescriptorBufferInfo> uniformBufferInfoList_asteroidPipeline;
215
216 UBO_VP_mats asteroid_VP_mats;
217
218 GraphicsPipeline_Vulkan<LaserVertex, SSBO_Laser> laserPipeline;
219 vector<SceneObject<LaserVertex, SSBO_Laser>> laserObjects;
220
221 vector<VkBuffer> uniformBuffers_laserPipeline;
222 vector<VkDeviceMemory> uniformBuffersMemory_laserPipeline;
223 vector<VkDescriptorBufferInfo> uniformBufferInfoList_laserPipeline;
224
225 UBO_VP_mats laser_VP_mats;
226
227 time_point<steady_clock> startTime;
228 float prevTime, elapsedTime;
229
230 float shipSpeed = 0.5f;
231 float asteroidSpeed = 2.0f;
232
233 float spawnRate_asteroid = 0.5;
234 float lastSpawn_asteroid;
235
236 unsigned int leftLaserIdx = -1;
237
238 unsigned int rightLaserIdx = -1;
239
240 bool initWindow(int width, int height, unsigned char guiFlags);
241 void initVulkan();
242 void initGraphicsPipelines();
243 void initMatrices();
244 void mainLoop();
245 void updateScene(uint32_t currentImage);
246 void renderUI();
247 void renderScene();
248 void cleanup();
249
250 void createVulkanInstance(const vector<const char*> &validationLayers);
251 void setupDebugMessenger();
252 void populateDebugMessengerCreateInfo(VkDebugUtilsMessengerCreateInfoEXT& createInfo);
253 void createVulkanSurface();
254 void pickPhysicalDevice(const vector<const char*>& deviceExtensions);
255 bool isDeviceSuitable(VkPhysicalDevice physicalDevice, const vector<const char*>& deviceExtensions);
256 void createLogicalDevice(
257 const vector<const char*> validationLayers,
258 const vector<const char*>& deviceExtensions);
259 void createSwapChain();
260 void createImageViews();
261 void createRenderPass();
262 VkFormat findDepthFormat();
263 void createCommandPool();
264 void createImageResources();
265
266 void createTextureSampler();
267 void createFramebuffers();
268 void createCommandBuffers();
269 void createSyncObjects();
270
271 void addLaser(vec3 start, vec3 end, vec3 color, float width);
272 void translateLaser(size_t index, const vec3& translation);
273
274 // TODO: Since addObject() returns a reference to the new object now,
275 // stop using objects.back() to access the object that was just created
276 template<class VertexType, class SSBOType>
277 SceneObject<VertexType, SSBOType>& addObject(
278 vector<SceneObject<VertexType, SSBOType>>& objects,
279 GraphicsPipeline_Vulkan<VertexType, SSBOType>& pipeline,
280 const vector<VertexType>& vertices, vector<uint16_t> indices, SSBOType ssbo,
281 bool pipelinesCreated);
282
283 template<class VertexType, class SSBOType>
284 void updateObject(vector<SceneObject<VertexType, SSBOType>>& objects,
285 GraphicsPipeline_Vulkan<VertexType, SSBOType>& pipeline, size_t index);
286
287 template<class VertexType, class SSBOType>
288 void updateObjectVertices(GraphicsPipeline_Vulkan<VertexType, SSBOType>& pipeline,
289 SceneObject<VertexType, SSBOType>& obj, size_t index);
290
291 template<class VertexType>
292 vector<VertexType> addVertexNormals(vector<VertexType> vertices);
293
294 template<class VertexType>
295 vector<VertexType> addObjectIndex(unsigned int objIndex, vector<VertexType> vertices);
296
297 template<class VertexType, class SSBOType>
298 void centerObject(SceneObject<VertexType, SSBOType>& object);
299
300 void createBufferSet(VkDeviceSize bufferSize, VkBufferUsageFlags flags,
301 vector<VkBuffer>& buffers, vector<VkDeviceMemory>& buffersMemory,
302 vector<VkDescriptorBufferInfo>& bufferInfoList);
303
304 void recreateSwapChain();
305
306 void cleanupSwapChain();
307
308 static VKAPI_ATTR VkBool32 VKAPI_CALL debugCallback(
309 VkDebugUtilsMessageSeverityFlagBitsEXT messageSeverity,
310 VkDebugUtilsMessageTypeFlagsEXT messageType,
311 const VkDebugUtilsMessengerCallbackDataEXT* pCallbackData,
312 void* pUserData);
313};
314
315// TODO: Right now, it's basically necessary to pass the identity matrix in for ssbo.model
316// and to change the model matrix later by setting model_transform and then calling updateObject()
317// Figure out a better way to allow the model matrix to be set during objecting creation
318
319// TODO: Maybe return a reference to the object from this method if I decide that updating it
320// immediately after creation is a good idea (such as setting model_base)
321// Currently, model_base is set like this in a few places and the radius is set for asteroids
322// to account for scaling
323template<class VertexType, class SSBOType>
324SceneObject<VertexType, SSBOType>& VulkanGame::addObject(
325 vector<SceneObject<VertexType, SSBOType>>& objects,
326 GraphicsPipeline_Vulkan<VertexType, SSBOType>& pipeline,
327 const vector<VertexType>& vertices, vector<uint16_t> indices, SSBOType ssbo,
328 bool pipelinesCreated) {
329 // TODO: Use the model field of ssbo to set the object's model_base
330 // currently, the passed in model is useless since it gets overridden in updateObject() anyway
331 size_t numVertices = pipeline.getNumVertices();
332
333 for (uint16_t& idx : indices) {
334 idx += numVertices;
335 }
336
337 objects.push_back({ vertices, indices, ssbo, mat4(1.0f), mat4(1.0f), false });
338
339 SceneObject<VertexType, SSBOType>& obj = objects.back();
340
341 if (!is_same_v<VertexType, LaserVertex>) {
342 centerObject(obj);
343 }
344
345 bool storageBufferResized = pipeline.addObject(obj.vertices, obj.indices, obj.ssbo,
346 this->commandPool, this->graphicsQueue);
347
348 if (pipelinesCreated) {
349 vkDeviceWaitIdle(device);
350 vkFreeCommandBuffers(device, commandPool, static_cast<uint32_t>(commandBuffers.size()), commandBuffers.data());
351
352 // TODO: The pipeline recreation only has to be done once per frame where at least
353 // one SSBO is resized.
354 // Refactor the logic to check for any resized SSBOs after all objects for the frame
355 // are created and then recreate each of the corresponding pipelines only once per frame
356 if (storageBufferResized) {
357 pipeline.createPipeline(pipeline.vertShaderFile, pipeline.fragShaderFile);
358 pipeline.createDescriptorPool(swapChainImages);
359 pipeline.createDescriptorSets(swapChainImages);
360 }
361
362 createCommandBuffers();
363 }
364
365 return obj;
366}
367
368// TODO: Just pass in the single object instead of a list of all of them
369template<class VertexType, class SSBOType>
370void VulkanGame::updateObject(vector<SceneObject<VertexType, SSBOType>>& objects,
371 GraphicsPipeline_Vulkan<VertexType, SSBOType>& pipeline, size_t index) {
372 SceneObject<VertexType, SSBOType>& obj = objects[index];
373
374 obj.ssbo.model = obj.model_transform * obj.model_base;
375 obj.center = vec3(obj.ssbo.model * vec4(0.0f, 0.0f, 0.0f, 1.0f));
376
377 pipeline.updateObject(index, obj.ssbo);
378
379 obj.modified = false;
380}
381
382template<class VertexType, class SSBOType>
383void VulkanGame::updateObjectVertices(GraphicsPipeline_Vulkan<VertexType, SSBOType>& pipeline,
384 SceneObject<VertexType, SSBOType>& obj, size_t index) {
385 pipeline.updateObjectVertices(index, obj.vertices, this->commandPool, this->graphicsQueue);
386}
387
388template<class VertexType>
389vector<VertexType> VulkanGame::addVertexNormals(vector<VertexType> vertices) {
390 for (unsigned int i = 0; i < vertices.size(); i += 3) {
391 vec3 p1 = vertices[i].pos;
392 vec3 p2 = vertices[i+1].pos;
393 vec3 p3 = vertices[i+2].pos;
394
395 vec3 normal = normalize(cross(p2 - p1, p3 - p1));
396
397 // Add the same normal for all 3 vertices
398 vertices[i].normal = normal;
399 vertices[i+1].normal = normal;
400 vertices[i+2].normal = normal;
401 }
402
403 return vertices;
404}
405
406template<class VertexType>
407vector<VertexType> VulkanGame::addObjectIndex(unsigned int objIndex, vector<VertexType> vertices) {
408 for (VertexType& vertex : vertices) {
409 vertex.objIndex = objIndex;
410 }
411
412 return vertices;
413}
414
415template<class VertexType, class SSBOType>
416void VulkanGame::centerObject(SceneObject<VertexType, SSBOType>& object) {
417 vector<VertexType>& vertices = object.vertices;
418
419 float min_x = vertices[0].pos.x;
420 float max_x = vertices[0].pos.x;
421 float min_y = vertices[0].pos.y;
422 float max_y = vertices[0].pos.y;
423 float min_z = vertices[0].pos.z;
424 float max_z = vertices[0].pos.z;
425
426 // start from the second point
427 for (unsigned int i = 1; i < vertices.size(); i++) {
428 vec3& pos = vertices[i].pos;
429
430 if (min_x > pos.x) {
431 min_x = pos.x;
432 } else if (max_x < pos.x) {
433 max_x = pos.x;
434 }
435
436 if (min_y > pos.y) {
437 min_y = pos.y;
438 } else if (max_y < pos.y) {
439 max_y = pos.y;
440 }
441
442 if (min_z > pos.z) {
443 min_z = pos.z;
444 } else if (max_z < pos.z) {
445 max_z = pos.z;
446 }
447 }
448
449 vec3 center = vec3(min_x + max_x, min_y + max_y, min_z + max_z) / 2.0f;
450
451 for (unsigned int i = 0; i < vertices.size(); i++) {
452 vertices[i].pos -= center;
453 }
454
455 object.radius = std::max(max_x - center.x, max_y - center.y);
456 object.radius = std::max(object.radius, max_z - center.z);
457
458 object.center = vec3(0.0f, 0.0f, 0.0f);
459}
460
461#endif // _VULKAN_GAME_H
Note: See TracBrowser for help on using the repository browser.