source: opengl-game/sdl-game.hpp@ bb76950

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

Change VulkanGame::resizeBufferSet() to take a buffer size instead of an entire
VulkanBuffer object, and to not update descriptor sets, which obviates the need
to pass in a GraphicsPipeline_Vulkan object. Descriptor set updates must
now be handled separetly.

  • Property mode set to 100644
File size: 15.7 KB
Line 
1#ifndef _SDL_GAME_H
2#define _SDL_GAME_H
3
4#include <chrono>
5#include <map>
6#include <vector>
7
8#include <vulkan/vulkan.h>
9
10#include <SDL2/SDL.h>
11
12#define GLM_FORCE_RADIANS
13#define GLM_FORCE_DEPTH_ZERO_TO_ONE // Since, in Vulkan, the depth range is 0 to 1 instead of -1 to 1
14#define GLM_FORCE_RIGHT_HANDED
15
16#include <glm/glm.hpp>
17#include <glm/gtc/matrix_transform.hpp>
18
19#include "IMGUI/imgui_impl_vulkan.h"
20
21#include "consts.hpp"
22#include "game-gui-sdl.hpp"
23#include "vulkan-utils.hpp"
24#include "graphics-pipeline_vulkan.hpp"
25#include "vulkan-buffer.hpp"
26
27using namespace glm;
28using namespace std;
29using namespace std::chrono;
30
31#define VulkanGame NewVulkanGame
32
33#ifdef NDEBUG
34 const bool ENABLE_VALIDATION_LAYERS = false;
35#else
36 const bool ENABLE_VALIDATION_LAYERS = true;
37#endif
38
39// TODO: Consider if there is a better way of dealing with all the vertex types and ssbo types, maybe
40// by consolidating some and trying to keep new ones to a minimum
41
42struct ModelVertex {
43 vec3 pos;
44 vec3 color;
45 vec2 texCoord;
46 vec3 normal;
47 unsigned int objIndex;
48};
49
50struct LaserVertex {
51 vec3 pos;
52 vec2 texCoord;
53 unsigned int objIndex;
54};
55
56struct ExplosionVertex {
57 vec3 particleStartVelocity;
58 float particleStartTime;
59 unsigned int objIndex;
60};
61
62// Currently using these as the dynamic UBO types as well
63// TODO: Rename them to something more general
64
65struct SSBO_ModelObject {
66 alignas(16) mat4 model;
67};
68
69struct SSBO_Asteroid {
70 alignas(16) mat4 model;
71 alignas(4) float hp;
72 alignas(4) unsigned int deleted;
73};
74
75struct UBO_VP_mats {
76 alignas(16) mat4 view;
77 alignas(16) mat4 proj;
78};
79
80// TODO: Use this struct for uniform buffers as well and probably combine it with the VulkanBuffer class
81// Also, probably better to make this a vector of structs where each struct
82// has a VkBuffer, VkDeviceMemory, and VkDescriptorBufferInfo
83// TODO: Maybe change the structure here since VkDescriptorBufferInfo already stores a reference to the VkBuffer
84struct BufferSet {
85 vector<VkBuffer> buffers;
86 vector<VkDeviceMemory> memory;
87 vector<VkDescriptorBufferInfo> infoSet;
88 VkBufferUsageFlags usages;
89 VkMemoryPropertyFlags properties;
90};
91
92// TODO: Change the index type to uint32_t and check the Vulkan Tutorial loading model section as a reference
93// TODO: Create a typedef for index type so I can easily change uin16_t to something else later
94// TODO: Maybe create a typedef for each of the templated SceneObject types
95template<class VertexType, class SSBOType>
96struct SceneObject {
97 vector<VertexType> vertices;
98 vector<uint16_t> indices;
99 SSBOType ssbo;
100
101 mat4 model_base;
102 mat4 model_transform;
103
104 bool modified;
105
106 // TODO: Figure out if I should make child classes that have these fields instead of putting them in the
107 // parent class
108 vec3 center; // currently only matters for asteroids
109 float radius; // currently only matters for asteroids
110
111 // Move the targetAsteroid stuff out of this class since it is very specific to lasers
112 // and makes moving SceneObject into its own header file more problematic
113 SceneObject<ModelVertex, SSBO_Asteroid>* targetAsteroid; // currently only used for lasers
114};
115
116// TODO: Have to figure out how to include an optional ssbo parameter for each object
117// Could probably use the same approach to make indices optional
118// Figure out if there are sufficient use cases to make either of these optional or is it fine to make
119// them mamdatory
120
121
122// TODO: Look into using dynamic_cast to check types of SceneObject and EffectOverTime
123
124// TODO: Maybe move this to a different header
125
126enum UIValueType {
127 UIVALUE_INT,
128 UIVALUE_DOUBLE,
129};
130
131struct UIValue {
132 UIValueType type;
133 string label;
134 void* value;
135
136 UIValue(UIValueType _type, string _label, void* _value) : type(_type), label(_label), value(_value) {}
137};
138
139class VulkanGame {
140
141 public:
142
143 VulkanGame();
144 ~VulkanGame();
145
146 void run(int width, int height, unsigned char guiFlags);
147
148 private:
149
150 static VKAPI_ATTR VkBool32 VKAPI_CALL debugCallback(
151 VkDebugUtilsMessageSeverityFlagBitsEXT messageSeverity,
152 VkDebugUtilsMessageTypeFlagsEXT messageType,
153 const VkDebugUtilsMessengerCallbackDataEXT* pCallbackData,
154 void* pUserData);
155
156 // TODO: Maybe pass these in as parameters to some Camera class
157 const float NEAR_CLIP = 0.1f;
158 const float FAR_CLIP = 100.0f;
159 const float FOV_ANGLE = 67.0f; // means the camera lens goes from -33 deg to 33 deg
160
161 bool done;
162
163 vec3 cam_pos;
164
165 // TODO: Good place to start using smart pointers
166 GameGui* gui;
167
168 SDL_version sdlVersion;
169 SDL_Window* window;
170
171 VkInstance instance;
172 VkDebugUtilsMessengerEXT debugMessenger;
173 VkSurfaceKHR vulkanSurface;
174 VkPhysicalDevice physicalDevice;
175 VkDevice device;
176
177 VkQueue graphicsQueue;
178 VkQueue presentQueue;
179
180 // TODO: Maybe make a swapchain struct for convenience
181 VkSurfaceFormatKHR swapChainSurfaceFormat;
182 VkPresentModeKHR swapChainPresentMode;
183 VkExtent2D swapChainExtent;
184 uint32_t swapChainMinImageCount;
185 uint32_t swapChainImageCount;
186
187 VkSwapchainKHR swapChain;
188 vector<VkImage> swapChainImages;
189 vector<VkImageView> swapChainImageViews;
190 vector<VkFramebuffer> swapChainFramebuffers;
191
192 VkRenderPass renderPass;
193
194 VkCommandPool resourceCommandPool;
195
196 vector<VkCommandPool> commandPools;
197 vector<VkCommandBuffer> commandBuffers;
198
199 VulkanImage depthImage;
200
201 // These are per frame
202 vector<VkSemaphore> imageAcquiredSemaphores;
203 vector<VkSemaphore> renderCompleteSemaphores;
204
205 // These are per swap chain image
206 vector<VkFence> inFlightFences;
207
208 uint32_t imageIndex;
209 uint32_t currentFrame;
210
211 bool shouldRecreateSwapChain;
212
213 VkSampler textureSampler;
214
215 VulkanImage floorTextureImage;
216 VkDescriptorImageInfo floorTextureImageDescriptor;
217
218 mat4 viewMat, projMat;
219
220 // Maybe at some point create an imgui pipeline class, but I don't think it makes sense right now
221 VkDescriptorPool imguiDescriptorPool;
222
223 // TODO: Probably restructure the GraphicsPipeline_Vulkan class based on what I learned about descriptors and textures
224 // while working on graphics-library. Double-check exactly what this was and note it down here.
225 // Basically, I think the point was that if I have several models that all use the same shaders and, therefore,
226 // the same pipeline, but use different textures, the approach I took when initially creating GraphicsPipeline_Vulkan
227 // wouldn't work since the whole pipeline couldn't have a common set of descriptors for the textures
228 GraphicsPipeline_Vulkan<ModelVertex> modelPipeline;
229
230 BufferSet storageBuffers_modelPipeline;
231 VulkanBuffer<SSBO_ModelObject> objects_modelPipeline;
232 BufferSet uniformBuffers_modelPipeline;
233
234 // TODO: Maybe make the ubo objects part of the pipeline class since there's only one ubo
235 // per pipeline.
236 // Or maybe create a higher level wrapper around GraphicsPipeline_Vulkan to hold things like
237 // the objects vector, the ubo, and the ssbo
238
239 // TODO: Rename *_VP_mats to *_uniforms and possibly use different types for each one
240 // if there is a need to add other uniform variables to one or more of the shaders
241
242 vector<SceneObject<ModelVertex, SSBO_ModelObject>> modelObjects;
243
244 UBO_VP_mats object_VP_mats;
245
246 /*** High-level vars ***/
247
248 // TODO: Just typedef the type of this function to RenderScreenFn or something since it's used in a few places
249 void (VulkanGame::* currentRenderScreenFn)(int width, int height);
250
251 map<string, vector<UIValue>> valueLists;
252
253 int score;
254 float fps;
255
256 // TODO: Make a separate singleton Timer class
257 time_point<steady_clock> startTime;
258 float fpsStartTime, curTime, prevTime, elapsedTime;
259
260 int frameCount;
261
262 /*** Functions ***/
263
264 bool initUI(int width, int height, unsigned char guiFlags);
265 void initVulkan();
266 void initGraphicsPipelines();
267 void initMatrices();
268 void renderLoop();
269 void updateScene();
270 void cleanup();
271
272 void createVulkanInstance(const vector<const char*>& validationLayers);
273 void setupDebugMessenger();
274 void populateDebugMessengerCreateInfo(VkDebugUtilsMessengerCreateInfoEXT& createInfo);
275 void createVulkanSurface();
276 void pickPhysicalDevice(const vector<const char*>& deviceExtensions);
277 bool isDeviceSuitable(VkPhysicalDevice physicalDevice, const vector<const char*>& deviceExtensions);
278 void createLogicalDevice(const vector<const char*>& validationLayers,
279 const vector<const char*>& deviceExtensions);
280 void chooseSwapChainProperties();
281 void createSwapChain();
282 void createImageViews();
283 void createResourceCommandPool();
284 void createImageResources();
285 VkFormat findDepthFormat(); // TODO: Declare/define (in the cpp file) this function in some util functions section
286 void createRenderPass();
287 void createCommandPools();
288 void createFramebuffers();
289 void createCommandBuffers();
290 void createSyncObjects();
291
292 void createTextureSampler();
293
294 void initImGuiOverlay();
295 void cleanupImGuiOverlay();
296
297 // TODO: Maybe move these to a different class, possibly VulkanBuffer or some new related class
298
299 void createBufferSet(VkDeviceSize bufferSize, VkBufferUsageFlags usages, VkMemoryPropertyFlags properties,
300 BufferSet& set);
301
302 void resizeBufferSet(BufferSet& set, VkDeviceSize newSize, VkCommandPool commandPool, VkQueue graphicsQueue,
303 bool copyData);
304
305 template<class SSBOType>
306 void updateBufferSet(BufferSet& set, size_t objIndex, SSBOType& ssbo);
307
308 // TODO: Since addObject() returns a reference to the new object now,
309 // stop using objects.back() to access the object that was just created
310 template<class VertexType, class SSBOType>
311 SceneObject<VertexType, SSBOType>& addObject(vector<SceneObject<VertexType, SSBOType>>& objects,
312 GraphicsPipeline_Vulkan<VertexType>& pipeline,
313 const vector<VertexType>& vertices, vector<uint16_t> indices,
314 VulkanBuffer<SSBOType>& objectBuffer, SSBOType ssbo);
315
316 template<class VertexType>
317 vector<VertexType> addObjectIndex(unsigned int objIndex, vector<VertexType> vertices);
318
319 template<class VertexType>
320 vector<VertexType> addVertexNormals(vector<VertexType> vertices);
321
322 template<class VertexType, class SSBOType>
323 void centerObject(SceneObject<VertexType, SSBOType>& object);
324
325 template<class VertexType, class SSBOType>
326 void updateObject(SceneObject<VertexType, SSBOType>& obj);
327
328 void renderFrame(ImDrawData* draw_data);
329 void presentFrame();
330
331 void recreateSwapChain();
332
333 void cleanupSwapChain();
334
335 /*** High-level functions ***/
336
337 void renderMainScreen(int width, int height);
338 void renderGameScreen(int width, int height);
339
340 void initGuiValueLists(map<string, vector<UIValue>>& valueLists);
341 void renderGuiValueList(vector<UIValue>& values);
342
343 void goToScreen(void (VulkanGame::* renderScreenFn)(int width, int height));
344 void quitGame();
345};
346
347// TODO: See if it makes sense to pass in the current swapchain index instead of updating all of them
348template<class SSBOType>
349void VulkanGame::updateBufferSet(BufferSet& set, size_t objIndex, SSBOType& ssbo) {
350 for (size_t i = 0; i < set.memory.size(); i++) {
351 VulkanUtils::copyDataToMemory(device, &ssbo, set.memory[i], objIndex * sizeof(SSBOType), sizeof(ssbo), false);
352 }
353}
354
355// TODO: Right now, it's basically necessary to pass the identity matrix in for ssbo.model
356// and to change the model matrix later by setting model_transform and then calling updateObject()
357// Figure out a better way to allow the model matrix to be set during object creation
358template<class VertexType, class SSBOType>
359SceneObject<VertexType, SSBOType>& VulkanGame::addObject(vector<SceneObject<VertexType, SSBOType>>& objects,
360 GraphicsPipeline_Vulkan<VertexType>& pipeline,
361 const vector<VertexType>& vertices, vector<uint16_t> indices,
362 VulkanBuffer<SSBOType>& objectBuffer, SSBOType ssbo) {
363 // TODO: Use the model field of ssbo to set the object's model_base
364 // currently, the passed in model is useless since it gets overridden in updateObject() anyway
365 size_t numVertices = pipeline.getNumVertices();
366
367 for (uint16_t& idx : indices) {
368 idx += numVertices;
369 }
370
371 objects.push_back({ vertices, indices, ssbo, mat4(1.0f), mat4(1.0f), false });
372 objectBuffer.add(ssbo);
373
374 SceneObject<VertexType, SSBOType>& obj = objects.back();
375
376 // TODO: Specify whether to center the object outside of this function or, worst case, maybe
377 // with a boolean being passed in here, so that I don't have to rely on checking the specific object
378 // type
379 // TODO: Actually, I've already defined a no-op centerObject method for explosions
380 // Maybe I should do the same for lasers and remove this conditional altogether
381 if (!is_same_v<VertexType, LaserVertex> && !is_same_v<VertexType, ExplosionVertex>) {
382 centerObject(obj);
383 }
384
385 pipeline.addObject(obj.vertices, obj.indices, resourceCommandPool, graphicsQueue);
386
387 return obj;
388}
389
390template<class VertexType>
391vector<VertexType> VulkanGame::addObjectIndex(unsigned int objIndex, vector<VertexType> vertices) {
392 for (VertexType& vertex : vertices) {
393 vertex.objIndex = objIndex;
394 }
395
396 return vertices;
397}
398
399template<class VertexType>
400vector<VertexType> VulkanGame::addVertexNormals(vector<VertexType> vertices) {
401 for (unsigned int i = 0; i < vertices.size(); i += 3) {
402 vec3 p1 = vertices[i].pos;
403 vec3 p2 = vertices[i + 1].pos;
404 vec3 p3 = vertices[i + 2].pos;
405
406 vec3 normal = normalize(cross(p2 - p1, p3 - p1));
407
408 // Add the same normal for all 3 vertices
409 vertices[i].normal = normal;
410 vertices[i + 1].normal = normal;
411 vertices[i + 2].normal = normal;
412 }
413
414 return vertices;
415}
416
417template<class VertexType, class SSBOType>
418void VulkanGame::centerObject(SceneObject<VertexType, SSBOType>& object) {
419 vector<VertexType>& vertices = object.vertices;
420
421 float min_x = vertices[0].pos.x;
422 float max_x = vertices[0].pos.x;
423 float min_y = vertices[0].pos.y;
424 float max_y = vertices[0].pos.y;
425 float min_z = vertices[0].pos.z;
426 float max_z = vertices[0].pos.z;
427
428 // start from the second point
429 for (unsigned int i = 1; i < vertices.size(); i++) {
430 vec3& pos = vertices[i].pos;
431
432 if (min_x > pos.x) {
433 min_x = pos.x;
434 }
435 else if (max_x < pos.x) {
436 max_x = pos.x;
437 }
438
439 if (min_y > pos.y) {
440 min_y = pos.y;
441 }
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 }
449 else if (max_z < pos.z) {
450 max_z = pos.z;
451 }
452 }
453
454 vec3 center = vec3(min_x + max_x, min_y + max_y, min_z + max_z) / 2.0f;
455
456 for (unsigned int i = 0; i < vertices.size(); i++) {
457 vertices[i].pos -= center;
458 }
459
460 object.radius = std::max(max_x - center.x, max_y - center.y);
461 object.radius = std::max(object.radius, max_z - center.z);
462
463 object.center = vec3(0.0f, 0.0f, 0.0f);
464}
465
466// TODO: Just pass in the single object instead of a list of all of them
467template<class VertexType, class SSBOType>
468void VulkanGame::updateObject(SceneObject<VertexType, SSBOType>& obj) {
469 obj.ssbo.model = obj.model_transform * obj.model_base;
470 obj.center = vec3(obj.ssbo.model * vec4(0.0f, 0.0f, 0.0f, 1.0f));
471
472 obj.modified = false;
473}
474
475#endif // _SDL_GAME_H
Note: See TracBrowser for help on using the repository browser.