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

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

Make curTime a static global variable so it can be used by classes outside of VulkanGame

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