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

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

Make a laser stop when it hits an asteroid

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