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

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

Make lasers deal damage to asteroids and eventually destroy them

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