source: opengl-game/vulkan-game.hpp@ 187b0f5

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

Change VulkanGame and SDLGame to only use discrete GPUs and switch the timer class to steady_clock

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