source: opengl-game/vulkan-game.hpp@ 5192672

feature/imgui-sdl
Last change on this file since 5192672 was 5192672, checked in by Dmitry Portnoy <dportnoy@…>, 4 years ago

Add ui-value\.hpp to the VulkanGame project and make curTime an instance variable of VulkanGame instead of a global

  • Property mode set to 100644
File size: 19.3 KB
Line 
1#ifndef _VULKAN_GAME_H
2#define _VULKAN_GAME_H
3
4#include <algorithm>
5#include <chrono>
6#include <map>
7#include <vector>
8
9#define GLM_FORCE_RADIANS
10#define GLM_FORCE_DEPTH_ZERO_TO_ONE // Since, in Vulkan, the depth range is 0 to 1 instead of -1 to 1
11#define GLM_FORCE_RIGHT_HANDED
12
13#include <glm/glm.hpp>
14#include <glm/gtc/matrix_transform.hpp>
15
16#include <vulkan/vulkan.h>
17
18#include <SDL2/SDL.h>
19#include <SDL2/SDL_ttf.h>
20
21#include "IMGUI/imgui_impl_vulkan.h"
22
23#include "consts.hpp"
24#include "vulkan-utils.hpp"
25#include "graphics-pipeline_vulkan.hpp"
26
27#include "game-gui-sdl.hpp"
28
29#include "gui/screen.hpp"
30
31using namespace glm;
32using namespace std::chrono;
33
34#ifdef NDEBUG
35 const bool ENABLE_VALIDATION_LAYERS = false;
36#else
37 const bool ENABLE_VALIDATION_LAYERS = true;
38#endif
39
40struct OverlayVertex {
41 vec3 pos;
42 vec2 texCoord;
43};
44
45struct ModelVertex {
46 vec3 pos;
47 vec3 color;
48 vec2 texCoord;
49 unsigned int objIndex;
50};
51
52struct ShipVertex {
53 vec3 pos;
54 vec3 color;
55 vec3 normal;
56 unsigned int objIndex;
57};
58
59struct AsteroidVertex {
60 vec3 pos;
61 vec3 color;
62 vec3 normal;
63 unsigned int objIndex;
64};
65
66struct LaserVertex {
67 vec3 pos;
68 vec2 texCoord;
69 unsigned int objIndex;
70};
71
72struct ExplosionVertex {
73 vec3 particleStartVelocity;
74 float particleStartTime;
75 unsigned int objIndex;
76};
77
78struct SSBO_ModelObject {
79 alignas(16) mat4 model;
80};
81
82struct SSBO_Asteroid {
83 alignas(16) mat4 model;
84 alignas(4) float hp;
85 alignas(4) unsigned int deleted;
86};
87
88struct SSBO_Laser {
89 alignas(16) mat4 model;
90 alignas(4) vec3 color;
91 alignas(4) unsigned int deleted;
92};
93
94struct SSBO_Explosion {
95 alignas(16) mat4 model;
96 alignas(4) float explosionStartTime;
97 alignas(4) float explosionDuration;
98 alignas(4) unsigned int deleted;
99};
100
101struct UBO_VP_mats {
102 alignas(16) mat4 view;
103 alignas(16) mat4 proj;
104};
105
106struct UBO_Explosion {
107 alignas(16) mat4 view;
108 alignas(16) mat4 proj;
109 alignas(4) float cur_time;
110};
111
112// TODO: Change the index type to uint32_t and check the Vulkan Tutorial loading model section as a reference
113// TODO: Create a typedef for index type so I can easily change uin16_t to something else later
114// TODO: Maybe create a typedef for each of the templated SceneObject types
115template<class VertexType, class SSBOType>
116struct SceneObject {
117 vector<VertexType> vertices;
118 vector<uint16_t> indices;
119 SSBOType ssbo;
120
121 mat4 model_base;
122 mat4 model_transform;
123
124 bool modified;
125
126 // TODO: Figure out if I should make child classes that have these fields instead of putting them in the
127 // parent class
128 vec3 center; // currently only matters for asteroids
129 float radius; // currently only matters for asteroids
130 SceneObject<AsteroidVertex, SSBO_Asteroid>* targetAsteroid; // currently only used for lasers
131};
132
133// TODO: Have to figure out how to include an optional ssbo parameter for each object
134// Could probably use the same approach to make indices optional
135// Figure out if there are sufficient use cases to make either of these optional or is it fine to make
136// them mamdatory
137
138
139// TODO: Look into using dynamic_cast to check types of SceneObject and EffectOverTime
140
141struct BaseEffectOverTime {
142 bool deleted;
143
144 virtual void applyEffect(float curTime) = 0;
145
146 BaseEffectOverTime() :
147 deleted(false) {
148 }
149
150 virtual ~BaseEffectOverTime() {
151 }
152};
153
154template<class VertexType, class SSBOType>
155struct EffectOverTime : public BaseEffectOverTime {
156 GraphicsPipeline_Vulkan<VertexType, SSBOType>& pipeline;
157 vector<SceneObject<VertexType, SSBOType>>& objects;
158 unsigned int objectIndex;
159 size_t effectedFieldOffset;
160 float startValue;
161 float startTime;
162 float changePerSecond;
163
164 EffectOverTime(GraphicsPipeline_Vulkan<VertexType, SSBOType>& pipeline,
165 vector<SceneObject<VertexType, SSBOType>>& objects, unsigned int objectIndex,
166 size_t effectedFieldOffset, float startTime, float changePerSecond) :
167 pipeline(pipeline),
168 objects(objects),
169 objectIndex(objectIndex),
170 effectedFieldOffset(effectedFieldOffset),
171 startTime(startTime),
172 changePerSecond(changePerSecond) {
173 size_t ssboOffset = offset_of(&SceneObject<VertexType, SSBOType>::ssbo);
174
175 unsigned char* effectedFieldPtr = reinterpret_cast<unsigned char*>(&objects[objectIndex]) +
176 ssboOffset + effectedFieldOffset;
177
178 startValue = *reinterpret_cast<float*>(effectedFieldPtr);
179 }
180
181 void applyEffect(float curTime) {
182 if (objects[objectIndex].ssbo.deleted) {
183 this->deleted = true;
184 return;
185 }
186
187 size_t ssboOffset = offset_of(&SceneObject<VertexType, SSBOType>::ssbo);
188
189 unsigned char* effectedFieldPtr = reinterpret_cast<unsigned char*>(&objects[objectIndex]) +
190 ssboOffset + effectedFieldOffset;
191
192 *reinterpret_cast<float*>(effectedFieldPtr) = startValue + (curTime - startTime) * changePerSecond;
193
194 objects[objectIndex].modified = true;
195 }
196};
197
198class VulkanGame {
199 public:
200 VulkanGame();
201 ~VulkanGame();
202
203 void run(int width, int height, unsigned char guiFlags);
204
205 void goToScreen(Screen* screen);
206 void quitGame();
207
208 map<ScreenType, Screen*> screens;
209 Screen* currentScreen;
210
211 TTF_Font* lazyFont;
212 TTF_Font* proggyFont;
213
214 int score;
215 float fps;
216
217 GraphicsPipeline_Vulkan<OverlayVertex, void*> overlayPipeline;
218
219 GraphicsPipeline_Vulkan<ModelVertex, SSBO_ModelObject> modelPipeline;
220
221 GraphicsPipeline_Vulkan<ShipVertex, SSBO_ModelObject> shipPipeline;
222
223 GraphicsPipeline_Vulkan<AsteroidVertex, SSBO_Asteroid> asteroidPipeline;
224
225 GraphicsPipeline_Vulkan<LaserVertex, SSBO_Laser> laserPipeline;
226
227 GraphicsPipeline_Vulkan<ExplosionVertex, SSBO_Explosion> explosionPipeline;
228
229 private:
230 static VKAPI_ATTR VkBool32 VKAPI_CALL debugCallback(
231 VkDebugUtilsMessageSeverityFlagBitsEXT messageSeverity,
232 VkDebugUtilsMessageTypeFlagsEXT messageType,
233 const VkDebugUtilsMessengerCallbackDataEXT* pCallbackData,
234 void* pUserData);
235
236 const float NEAR_CLIP = 0.1f;
237 const float FAR_CLIP = 100.0f;
238 const float FOV_ANGLE = 67.0f; // means the camera lens goes from -33 deg to 33 def
239
240 const int EXPLOSION_PARTICLE_COUNT = 300;
241 const vec3 LASER_COLOR = vec3(0.2f, 1.0f, 0.2f);
242
243 bool done;
244
245 vec3 cam_pos;
246
247 // TODO: Good place to start using smart pointers
248 GameGui* gui;
249
250 SDL_version sdlVersion;
251 SDL_Window* window = nullptr;
252 SDL_Renderer* renderer = nullptr;
253
254 SDL_Texture* uiOverlay = nullptr;
255
256 VkInstance instance;
257 VkDebugUtilsMessengerEXT debugMessenger;
258 VkSurfaceKHR surface; // TODO: Change the variable name to vulkanSurface
259 VkPhysicalDevice physicalDevice = VK_NULL_HANDLE;
260 VkDevice device;
261
262 VkQueue graphicsQueue;
263 VkQueue presentQueue;
264
265 // TODO: Maybe make a swapchain struct for convenience
266 VkSurfaceFormatKHR swapChainSurfaceFormat;
267 VkPresentModeKHR swapChainPresentMode;
268 VkExtent2D swapChainExtent;
269 uint32_t swapChainMinImageCount;
270 uint32_t swapChainImageCount;
271 VkSwapchainKHR swapChain;
272 vector<VkImage> swapChainImages;
273 vector<VkImageView> swapChainImageViews;
274 vector<VkFramebuffer> swapChainFramebuffers;
275
276 VkRenderPass renderPass;
277
278 VkCommandPool resourceCommandPool;
279
280 vector<VkCommandPool> commandPools;
281 vector<VkCommandBuffer> commandBuffers;
282
283 VulkanImage depthImage;
284
285 // These are per frame
286 vector<VkSemaphore> imageAcquiredSemaphores;
287 vector<VkSemaphore> renderCompleteSemaphores;
288
289 // These are per swap chain image
290 vector<VkFence> inFlightFences;
291
292 uint32_t imageIndex;
293 uint32_t currentFrame;
294
295 bool shouldRecreateSwapChain;
296
297 VkDescriptorPool imguiDescriptorPool;
298
299 VkSampler textureSampler;
300
301 VulkanImage sdlOverlayImage;
302 VkDescriptorImageInfo sdlOverlayImageDescriptor;
303
304 VulkanImage floorTextureImage;
305 VkDescriptorImageInfo floorTextureImageDescriptor;
306
307 VulkanImage laserTextureImage;
308 VkDescriptorImageInfo laserTextureImageDescriptor;
309
310 mat4 viewMat, projMat;
311
312 // TODO: Maybe make the ubo objects part of the pipeline class since there's only one ubo
313 // per pipeline.
314 // Or maybe create a higher level wrapper around GraphicsPipeline_Vulkan to hold things like
315 // the objects vector, the ubo, and the ssbo
316
317 // TODO: Rename *_VP_mats to *_uniforms and possibly use different types for each one
318 // if there is a need to add other uniform variables to one or more of the shaders
319
320 vector<SceneObject<OverlayVertex, void*>> overlayObjects;
321
322 vector<SceneObject<ModelVertex, SSBO_ModelObject>> modelObjects;
323
324 vector<VkBuffer> uniformBuffers_modelPipeline;
325 vector<VkDeviceMemory> uniformBuffersMemory_modelPipeline;
326 vector<VkDescriptorBufferInfo> uniformBufferInfoList_modelPipeline;
327
328 UBO_VP_mats object_VP_mats;
329
330 vector<SceneObject<ShipVertex, SSBO_ModelObject>> shipObjects;
331
332 vector<VkBuffer> uniformBuffers_shipPipeline;
333 vector<VkDeviceMemory> uniformBuffersMemory_shipPipeline;
334 vector<VkDescriptorBufferInfo> uniformBufferInfoList_shipPipeline;
335
336 UBO_VP_mats ship_VP_mats;
337
338 vector<SceneObject<AsteroidVertex, SSBO_Asteroid>> asteroidObjects;
339
340 vector<VkBuffer> uniformBuffers_asteroidPipeline;
341 vector<VkDeviceMemory> uniformBuffersMemory_asteroidPipeline;
342 vector<VkDescriptorBufferInfo> uniformBufferInfoList_asteroidPipeline;
343
344 UBO_VP_mats asteroid_VP_mats;
345
346 vector<SceneObject<LaserVertex, SSBO_Laser>> laserObjects;
347
348 vector<VkBuffer> uniformBuffers_laserPipeline;
349 vector<VkDeviceMemory> uniformBuffersMemory_laserPipeline;
350 vector<VkDescriptorBufferInfo> uniformBufferInfoList_laserPipeline;
351
352 UBO_VP_mats laser_VP_mats;
353
354 vector<SceneObject<ExplosionVertex, SSBO_Explosion>> explosionObjects;
355
356 vector<VkBuffer> uniformBuffers_explosionPipeline;
357 vector<VkDeviceMemory> uniformBuffersMemory_explosionPipeline;
358 vector<VkDescriptorBufferInfo> uniformBufferInfoList_explosionPipeline;
359
360 UBO_Explosion explosion_UBO;
361
362 vector<BaseEffectOverTime*> effects;
363
364 // TODO: Make a separate TImer class
365 // It could also deal with the steady_clock vs high_resolution_clock issue
366 time_point<steady_clock> startTime;
367 float fpsStartTime, curTime, prevTime, elapsedTime;
368
369 int frameCount;
370
371 float shipSpeed = 0.5f;
372 float asteroidSpeed = 2.0f;
373
374 float spawnRate_asteroid = 0.5;
375 float lastSpawn_asteroid;
376
377 unsigned int leftLaserIdx = -1;
378 EffectOverTime<AsteroidVertex, SSBO_Asteroid>* leftLaserEffect = nullptr;
379
380 unsigned int rightLaserIdx = -1;
381 EffectOverTime<AsteroidVertex, SSBO_Asteroid>* rightLaserEffect = nullptr;
382
383 bool initUI(int width, int height, unsigned char guiFlags);
384 void initVulkan();
385 void initGraphicsPipelines();
386 void initMatrices();
387 void mainLoop();
388 void updateScene();
389 void cleanup();
390
391 void createVulkanInstance(const vector<const char*>& validationLayers);
392 void setupDebugMessenger();
393 void populateDebugMessengerCreateInfo(VkDebugUtilsMessengerCreateInfoEXT& createInfo);
394 void createVulkanSurface();
395 void pickPhysicalDevice(const vector<const char*>& deviceExtensions);
396 bool isDeviceSuitable(VkPhysicalDevice physicalDevice, const vector<const char*>& deviceExtensions);
397 void createLogicalDevice(const vector<const char*>& validationLayers,
398 const vector<const char*>& deviceExtensions);
399 void chooseSwapChainProperties();
400 void createSwapChain();
401 void createImageViews();
402 void createRenderPass();
403 VkFormat findDepthFormat(); // TODO: Declare/define (in the cpp file) this function in some util functions section
404 void createResourceCommandPool();
405 void createCommandPools();
406 void createImageResources();
407 void createFramebuffers();
408 void createCommandBuffers();
409 void createSyncObjects();
410
411 void createTextureSampler();
412
413 void createImguiDescriptorPool();
414 void destroyImguiDescriptorPool();
415
416 // TODO: Since addObject() returns a reference to the new object now,
417 // stop using objects.back() to access the object that was just created
418 template<class VertexType, class SSBOType>
419 SceneObject<VertexType, SSBOType>& addObject(
420 vector<SceneObject<VertexType, SSBOType>>& objects,
421 GraphicsPipeline_Vulkan<VertexType, SSBOType>& pipeline,
422 const vector<VertexType>& vertices, vector<uint16_t> indices, SSBOType ssbo,
423 bool pipelinesCreated);
424
425 template<class VertexType, class SSBOType>
426 void updateObject(vector<SceneObject<VertexType, SSBOType>>& objects,
427 GraphicsPipeline_Vulkan<VertexType, SSBOType>& pipeline, size_t index);
428
429 template<class VertexType, class SSBOType>
430 void updateObjectVertices(GraphicsPipeline_Vulkan<VertexType, SSBOType>& pipeline,
431 SceneObject<VertexType, SSBOType>& obj, size_t index);
432
433 template<class VertexType>
434 vector<VertexType> addVertexNormals(vector<VertexType> vertices);
435
436 template<class VertexType>
437 vector<VertexType> addObjectIndex(unsigned int objIndex, vector<VertexType> vertices);
438
439 template<class VertexType, class SSBOType>
440 void centerObject(SceneObject<VertexType, SSBOType>& object);
441
442 void addLaser(vec3 start, vec3 end, vec3 color, float width);
443 void translateLaser(size_t index, const vec3& translation);
444 void updateLaserTarget(size_t index);
445 bool getLaserAndAsteroidIntersection(SceneObject<AsteroidVertex, SSBO_Asteroid>& asteroid,
446 vec3& start, vec3& end, vec3& intersection);
447
448 void addExplosion(mat4 model_mat, float duration, float cur_time);
449
450 void createBufferSet(VkDeviceSize bufferSize, VkBufferUsageFlags flags,
451 vector<VkBuffer>& buffers, vector<VkDeviceMemory>& buffersMemory,
452 vector<VkDescriptorBufferInfo>& bufferInfoList);
453
454 void renderFrame(ImDrawData* draw_data);
455 void presentFrame();
456
457 void recreateSwapChain();
458
459 void cleanupSwapChain();
460};
461
462// Start of specialized no-op functions
463
464template<>
465inline void VulkanGame::centerObject(SceneObject<ExplosionVertex, SSBO_Explosion>& object) {
466}
467
468// End of specialized no-op functions
469
470// TODO: Right now, it's basically necessary to pass the identity matrix in for ssbo.model
471// and to change the model matrix later by setting model_transform and then calling updateObject()
472// Figure out a better way to allow the model matrix to be set during objecting creation
473
474// TODO: Maybe return a reference to the object from this method if I decide that updating it
475// immediately after creation is a good idea (such as setting model_base)
476// Currently, model_base is set like this in a few places and the radius is set for asteroids
477// to account for scaling
478template<class VertexType, class SSBOType>
479SceneObject<VertexType, SSBOType>& VulkanGame::addObject(
480 vector<SceneObject<VertexType, SSBOType>>& objects,
481 GraphicsPipeline_Vulkan<VertexType, SSBOType>& pipeline,
482 const vector<VertexType>& vertices, vector<uint16_t> indices, SSBOType ssbo,
483 bool pipelinesCreated) {
484 // TODO: Use the model field of ssbo to set the object's model_base
485 // currently, the passed in model is useless since it gets overridden in updateObject() anyway
486 size_t numVertices = pipeline.getNumVertices();
487
488 for (uint16_t& idx : indices) {
489 idx += numVertices;
490 }
491
492 objects.push_back({ vertices, indices, ssbo, mat4(1.0f), mat4(1.0f), false });
493
494 SceneObject<VertexType, SSBOType>& obj = objects.back();
495
496 if (!is_same_v<VertexType, LaserVertex> && !is_same_v<VertexType, ExplosionVertex>) {
497 centerObject(obj);
498 }
499
500 bool storageBufferResized = pipeline.addObject(obj.vertices, obj.indices, obj.ssbo,
501 resourceCommandPool, graphicsQueue);
502
503 if (pipelinesCreated) {
504 vkDeviceWaitIdle(device);
505
506 for (uint32_t i = 0; i < swapChainImageCount; i++) {
507 vkFreeCommandBuffers(device, commandPools[i], 1, &commandBuffers[i]);
508 }
509
510 // TODO: The pipeline recreation only has to be done once per frame where at least
511 // one SSBO is resized.
512 // Refactor the logic to check for any resized SSBOs after all objects for the frame
513 // are created and then recreate each of the corresponding pipelines only once per frame
514 if (storageBufferResized) {
515 pipeline.createPipeline(pipeline.vertShaderFile, pipeline.fragShaderFile);
516 pipeline.createDescriptorPool(swapChainImages);
517 pipeline.createDescriptorSets(swapChainImages);
518 }
519
520 createCommandBuffers();
521 }
522
523 return obj;
524}
525
526// TODO: Just pass in the single object instead of a list of all of them
527template<class VertexType, class SSBOType>
528void VulkanGame::updateObject(vector<SceneObject<VertexType, SSBOType>>& objects,
529 GraphicsPipeline_Vulkan<VertexType, SSBOType>& pipeline, size_t index) {
530 SceneObject<VertexType, SSBOType>& obj = objects[index];
531
532 obj.ssbo.model = obj.model_transform * obj.model_base;
533 obj.center = vec3(obj.ssbo.model * vec4(0.0f, 0.0f, 0.0f, 1.0f));
534
535 pipeline.updateObject(index, obj.ssbo);
536
537 obj.modified = false;
538}
539
540template<class VertexType, class SSBOType>
541void VulkanGame::updateObjectVertices(GraphicsPipeline_Vulkan<VertexType, SSBOType>& pipeline,
542 SceneObject<VertexType, SSBOType>& obj, size_t index) {
543 pipeline.updateObjectVertices(index, obj.vertices, resourceCommandPool, graphicsQueue);
544}
545
546template<class VertexType>
547vector<VertexType> VulkanGame::addVertexNormals(vector<VertexType> vertices) {
548 for (unsigned int i = 0; i < vertices.size(); i += 3) {
549 vec3 p1 = vertices[i].pos;
550 vec3 p2 = vertices[i+1].pos;
551 vec3 p3 = vertices[i+2].pos;
552
553 vec3 normal = normalize(cross(p2 - p1, p3 - p1));
554
555 // Add the same normal for all 3 vertices
556 vertices[i].normal = normal;
557 vertices[i+1].normal = normal;
558 vertices[i+2].normal = normal;
559 }
560
561 return vertices;
562}
563
564template<class VertexType>
565vector<VertexType> VulkanGame::addObjectIndex(unsigned int objIndex, vector<VertexType> vertices) {
566 for (VertexType& vertex : vertices) {
567 vertex.objIndex = objIndex;
568 }
569
570 return vertices;
571}
572
573template<class VertexType, class SSBOType>
574void VulkanGame::centerObject(SceneObject<VertexType, SSBOType>& object) {
575 vector<VertexType>& vertices = object.vertices;
576
577 float min_x = vertices[0].pos.x;
578 float max_x = vertices[0].pos.x;
579 float min_y = vertices[0].pos.y;
580 float max_y = vertices[0].pos.y;
581 float min_z = vertices[0].pos.z;
582 float max_z = vertices[0].pos.z;
583
584 // start from the second point
585 for (unsigned int i = 1; i < vertices.size(); i++) {
586 vec3& pos = vertices[i].pos;
587
588 if (min_x > pos.x) {
589 min_x = pos.x;
590 } else if (max_x < pos.x) {
591 max_x = pos.x;
592 }
593
594 if (min_y > pos.y) {
595 min_y = pos.y;
596 } else if (max_y < pos.y) {
597 max_y = pos.y;
598 }
599
600 if (min_z > pos.z) {
601 min_z = pos.z;
602 } else if (max_z < pos.z) {
603 max_z = pos.z;
604 }
605 }
606
607 vec3 center = vec3(min_x + max_x, min_y + max_y, min_z + max_z) / 2.0f;
608
609 for (unsigned int i = 0; i < vertices.size(); i++) {
610 vertices[i].pos -= center;
611 }
612
613 object.radius = std::max(max_x - center.x, max_y - center.y);
614 object.radius = std::max(object.radius, max_z - center.z);
615
616 object.center = vec3(0.0f, 0.0f, 0.0f);
617}
618
619#endif // _VULKAN_GAME_H
Note: See TracBrowser for help on using the repository browser.