source: opengl-game/vulkan-game.hpp@ 9d21aac

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

Remove the SSBOType template parameter from GraphicsPipeline_Vulkan

  • Property mode set to 100644
File size: 24.8 KB
RevLine 
[99d44b2]1#ifndef _VULKAN_GAME_H
2#define _VULKAN_GAME_H
[e8ebc76]3
[aa7707d]4#include <algorithm>
[0807aeb]5#include <chrono>
[e1f88a9]6#include <map>
[5192672]7#include <vector>
[0807aeb]8
[20e4c2b]9#include <vulkan/vulkan.h>
10
11#include <SDL2/SDL.h>
12#include <SDL2/SDL_ttf.h>
13
[60578ce]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
[a79be34]16#define GLM_FORCE_RIGHT_HANDED
[60578ce]17
[771b33a]18#include <glm/glm.hpp>
[15104a8]19#include <glm/gtc/matrix_transform.hpp>
[771b33a]20
[ea2b4dc]21#include "IMGUI/imgui_impl_vulkan.h"
22
[6bfd91c]23#include "consts.hpp"
[7d2b0b9]24#include "graphics-pipeline_vulkan.hpp"
[4e705d6]25#include "game-gui-sdl.hpp"
[b8efa56]26#include "utils.hpp"
27#include "vulkan-utils.hpp"
[b794178]28
[15104a8]29using namespace glm;
[0807aeb]30using namespace std::chrono;
[15104a8]31
[2e77b3f]32#ifdef NDEBUG
33 const bool ENABLE_VALIDATION_LAYERS = false;
34#else
35 const bool ENABLE_VALIDATION_LAYERS = true;
36#endif
37
[cefdf23]38// TODO: Consider if there is a better way of dealing with all the vertex types and ssbo types, maybe
39// by consolidating some and trying to keep new ones to a minimum
40
[5a1ace0]41struct OverlayVertex {
[15104a8]42 vec3 pos;
43 vec2 texCoord;
[771b33a]44};
45
[5a1ace0]46struct ModelVertex {
[15104a8]47 vec3 pos;
[5a1ace0]48 vec3 color;
[15104a8]49 vec2 texCoord;
[a00eb06]50 vec3 normal;
[5a1ace0]51 unsigned int objIndex;
[15104a8]52};
53
[237cbec]54struct LaserVertex {
55 vec3 pos;
56 vec2 texCoord;
57 unsigned int objIndex;
58};
59
[4a9416a]60struct ExplosionVertex {
61 vec3 particleStartVelocity;
62 float particleStartTime;
63 unsigned int objIndex;
64};
65
[2d87297]66struct SSBO_ModelObject {
[055750a]67 alignas(16) mat4 model;
68};
69
[2d87297]70struct SSBO_Asteroid {
[3e8cc8b]71 alignas(16) mat4 model;
72 alignas(4) float hp;
[4ece3bf]73 alignas(4) unsigned int deleted;
[3e8cc8b]74};
75
[237cbec]76struct SSBO_Laser {
77 alignas(16) mat4 model;
78 alignas(4) vec3 color;
79 alignas(4) unsigned int deleted;
80};
81
[4a9416a]82struct SSBO_Explosion {
83 alignas(16) mat4 model;
84 alignas(4) float explosionStartTime;
85 alignas(4) float explosionDuration;
86 alignas(4) unsigned int deleted;
87};
88
[52a02e6]89struct UBO_VP_mats {
90 alignas(16) mat4 view;
91 alignas(16) mat4 proj;
92};
93
[4a9416a]94struct UBO_Explosion {
95 alignas(16) mat4 view;
96 alignas(16) mat4 proj;
97 alignas(4) float cur_time;
98};
99
[4994692]100// TODO: Change the index type to uint32_t and check the Vulkan Tutorial loading model section as a reference
101// TODO: Create a typedef for index type so I can easily change uin16_t to something else later
102// TODO: Maybe create a typedef for each of the templated SceneObject types
103template<class VertexType, class SSBOType>
104struct SceneObject {
105 vector<VertexType> vertices;
106 vector<uint16_t> indices;
107 SSBOType ssbo;
108
109 mat4 model_base;
110 mat4 model_transform;
111
[5ba732a]112 bool modified;
113
[4994692]114 // TODO: Figure out if I should make child classes that have these fields instead of putting them in the
115 // parent class
116 vec3 center; // currently only matters for asteroids
117 float radius; // currently only matters for asteroids
[b8efa56]118 SceneObject<ModelVertex, SSBO_Asteroid>* targetAsteroid; // currently only used for lasers
[4994692]119};
120
121// TODO: Have to figure out how to include an optional ssbo parameter for each object
[2da64ef]122// Could probably use the same approach to make indices optional
[4994692]123// Figure out if there are sufficient use cases to make either of these optional or is it fine to make
124// them mamdatory
[2da64ef]125
[7297892]126
127// TODO: Look into using dynamic_cast to check types of SceneObject and EffectOverTime
128
129struct BaseEffectOverTime {
130 bool deleted;
131
[5192672]132 virtual void applyEffect(float curTime) = 0;
[7297892]133
134 BaseEffectOverTime() :
135 deleted(false) {
136 }
137
138 virtual ~BaseEffectOverTime() {
139 }
140};
141
142template<class VertexType, class SSBOType>
143struct EffectOverTime : public BaseEffectOverTime {
[9d21aac]144 GraphicsPipeline_Vulkan<VertexType>& pipeline;
[7297892]145 vector<SceneObject<VertexType, SSBOType>>& objects;
146 unsigned int objectIndex;
147 size_t effectedFieldOffset;
148 float startValue;
149 float startTime;
150 float changePerSecond;
151
[9d21aac]152 EffectOverTime(GraphicsPipeline_Vulkan<VertexType>& pipeline, vector<SceneObject<VertexType, SSBOType>>& objects,
153 unsigned int objectIndex, size_t effectedFieldOffset, float startTime, float changePerSecond)
154 : pipeline(pipeline)
155 , objects(objects)
156 , objectIndex(objectIndex)
157 , effectedFieldOffset(effectedFieldOffset)
158 , startTime(startTime)
159 , changePerSecond(changePerSecond) {
[7297892]160 size_t ssboOffset = offset_of(&SceneObject<VertexType, SSBOType>::ssbo);
161
162 unsigned char* effectedFieldPtr = reinterpret_cast<unsigned char*>(&objects[objectIndex]) +
163 ssboOffset + effectedFieldOffset;
164
165 startValue = *reinterpret_cast<float*>(effectedFieldPtr);
166 }
167
[5192672]168 void applyEffect(float curTime) {
[7297892]169 if (objects[objectIndex].ssbo.deleted) {
170 this->deleted = true;
171 return;
172 }
173
174 size_t ssboOffset = offset_of(&SceneObject<VertexType, SSBOType>::ssbo);
175
176 unsigned char* effectedFieldPtr = reinterpret_cast<unsigned char*>(&objects[objectIndex]) +
177 ssboOffset + effectedFieldOffset;
178
179 *reinterpret_cast<float*>(effectedFieldPtr) = startValue + (curTime - startTime) * changePerSecond;
180
181 objects[objectIndex].modified = true;
182 }
183};
184
[cefdf23]185// TODO: Maybe move this to a different header
186
[20e4c2b]187enum UIValueType {
188 UIVALUE_INT,
189 UIVALUE_DOUBLE,
190};
191
192struct UIValue {
193 UIValueType type;
194 string label;
195 void* value;
196
197 UIValue(UIValueType _type, string _label, void* _value) : type(_type), label(_label), value(_value) {}
198};
199
[e8445f0]200/* TODO: The following syntax (note the const keyword) means the function will not modify
201 * its params. I should use this where appropriate
202 *
203 * [return-type] [func-name](params...) const { ... }
204 */
205
[99d44b2]206class VulkanGame {
[914bb99]207
[e8ebc76]208 public:
[cefdf23]209
[3f32dfd]210 VulkanGame();
[99d44b2]211 ~VulkanGame();
[0df3c9a]212
[b6e60b4]213 void run(int width, int height, unsigned char guiFlags);
[0df3c9a]214
215 private:
[cefdf23]216
[c324d6a]217 static VKAPI_ATTR VkBool32 VKAPI_CALL debugCallback(
218 VkDebugUtilsMessageSeverityFlagBitsEXT messageSeverity,
219 VkDebugUtilsMessageTypeFlagsEXT messageType,
220 const VkDebugUtilsMessengerCallbackDataEXT* pCallbackData,
221 void* pUserData);
222
[cefdf23]223 // TODO: Maybe pass these in as parameters to some Camera class
[5ab1b20]224 const float NEAR_CLIP = 0.1f;
225 const float FAR_CLIP = 100.0f;
[cefdf23]226 const float FOV_ANGLE = 67.0f; // means the camera lens goes from -33 deg to 33 deg
[5ab1b20]227
[4a9416a]228 const int EXPLOSION_PARTICLE_COUNT = 300;
229 const vec3 LASER_COLOR = vec3(0.2f, 1.0f, 0.2f);
230
[c6f0793]231 bool done;
[e1f88a9]232
[15104a8]233 vec3 cam_pos;
234
[4e705d6]235 // TODO: Good place to start using smart pointers
[0df3c9a]236 GameGui* gui;
[c559904]237
238 SDL_version sdlVersion;
[b794178]239 SDL_Window* window = nullptr;
[c1d9b2a]240
[301c90a]241 int drawableWidth, drawableHeight;
242
[c1d9b2a]243 VkInstance instance;
244 VkDebugUtilsMessengerEXT debugMessenger;
[7865c5b]245 VkSurfaceKHR vulkanSurface;
[90a424f]246 VkPhysicalDevice physicalDevice = VK_NULL_HANDLE;
[c1c2021]247 VkDevice device;
248
249 VkQueue graphicsQueue;
250 VkQueue presentQueue;
[0df3c9a]251
[3f32dfd]252 // TODO: Maybe make a swapchain struct for convenience
253 VkSurfaceFormatKHR swapChainSurfaceFormat;
254 VkPresentModeKHR swapChainPresentMode;
255 VkExtent2D swapChainExtent;
256 uint32_t swapChainMinImageCount;
[c324d6a]257 uint32_t swapChainImageCount;
[502bd0b]258 VkSwapchainKHR swapChain;
259 vector<VkImage> swapChainImages;
[f94eea9]260 vector<VkImageView> swapChainImageViews;
[603b5bc]261 vector<VkFramebuffer> swapChainFramebuffers;
[fa9fa1c]262
[6fc24c7]263 VkRenderPass renderPass;
[3f32dfd]264
265 VkCommandPool resourceCommandPool;
266
[9c0a614]267 vector<VkCommandPool> commandPools;
[603b5bc]268 vector<VkCommandBuffer> commandBuffers;
[502bd0b]269
[603b5bc]270 VulkanImage depthImage;
[b794178]271
[3f32dfd]272 // These are per frame
273 vector<VkSemaphore> imageAcquiredSemaphores;
274 vector<VkSemaphore> renderCompleteSemaphores;
275
276 // These are per swap chain image
[4e705d6]277 vector<VkFence> inFlightFences;
278
[3f32dfd]279 uint32_t imageIndex;
280 uint32_t currentFrame;
[4e705d6]281
[28ea92f]282 bool shouldRecreateSwapChain;
[4e705d6]283
[b794178]284 VkSampler textureSampler;
285
[4994692]286 VulkanImage floorTextureImage;
287 VkDescriptorImageInfo floorTextureImageDescriptor;
288
[237cbec]289 VulkanImage laserTextureImage;
290 VkDescriptorImageInfo laserTextureImageDescriptor;
291
[22217d4]292 mat4 viewMat, projMat;
293
[cefdf23]294 // Maybe at some point create an imgui pipeline class, but I don't think it makes sense right now
295 VkDescriptorPool imguiDescriptorPool;
296
297 // TODO: Probably restructure the GraphicsPipeline_Vulkan class based on what I learned about descriptors and textures
298 // while working on graphics-library. Double-check exactly what this was and note it down here.
299 // Basically, I think the point was that if I have several modesl that all use the same shaders and, therefore,
300 // the same pipeline, but use different textures, the approach I took when initially creating GraphicsPipeline_Vulkan
301 // wouldn't work since the whole pipeline couldn't have a common set of descriptors for the textures
[9d21aac]302 GraphicsPipeline_Vulkan<ModelVertex> modelPipeline;
303 GraphicsPipeline_Vulkan<ModelVertex> shipPipeline;
304 GraphicsPipeline_Vulkan<ModelVertex> asteroidPipeline;
305 GraphicsPipeline_Vulkan<LaserVertex> laserPipeline;
306 GraphicsPipeline_Vulkan<ExplosionVertex> explosionPipeline;
[cefdf23]307
[860a0da]308 // TODO: Maybe make the ubo objects part of the pipeline class since there's only one ubo
309 // per pipeline.
310 // Or maybe create a higher level wrapper around GraphicsPipeline_Vulkan to hold things like
311 // the objects vector, the ubo, and the ssbo
312
[2ba5617]313 // TODO: Rename *_VP_mats to *_uniforms and possibly use different types for each one
314 // if there is a need to add other uniform variables to one or more of the shaders
315
[2d87297]316 vector<SceneObject<ModelVertex, SSBO_ModelObject>> modelObjects;
[0fe8433]317
[d25381b]318 vector<VkBuffer> uniformBuffers_modelPipeline;
319 vector<VkDeviceMemory> uniformBuffersMemory_modelPipeline;
320 vector<VkDescriptorBufferInfo> uniformBufferInfoList_modelPipeline;
[b794178]321
[0fe8433]322 UBO_VP_mats object_VP_mats;
323
[8d92284]324 vector<SceneObject<ModelVertex, SSBO_ModelObject>> shipObjects;
[0fe8433]325
[3782d66]326 vector<VkBuffer> uniformBuffers_shipPipeline;
327 vector<VkDeviceMemory> uniformBuffersMemory_shipPipeline;
328 vector<VkDescriptorBufferInfo> uniformBufferInfoList_shipPipeline;
329
[0fe8433]330 UBO_VP_mats ship_VP_mats;
[0e09340]331
[b8efa56]332 vector<SceneObject<ModelVertex, SSBO_Asteroid>> asteroidObjects;
[3e8cc8b]333
334 vector<VkBuffer> uniformBuffers_asteroidPipeline;
335 vector<VkDeviceMemory> uniformBuffersMemory_asteroidPipeline;
336 vector<VkDescriptorBufferInfo> uniformBufferInfoList_asteroidPipeline;
337
338 UBO_VP_mats asteroid_VP_mats;
339
[237cbec]340 vector<SceneObject<LaserVertex, SSBO_Laser>> laserObjects;
341
342 vector<VkBuffer> uniformBuffers_laserPipeline;
343 vector<VkDeviceMemory> uniformBuffersMemory_laserPipeline;
344 vector<VkDescriptorBufferInfo> uniformBufferInfoList_laserPipeline;
345
346 UBO_VP_mats laser_VP_mats;
347
[4a9416a]348 vector<SceneObject<ExplosionVertex, SSBO_Explosion>> explosionObjects;
349
350 vector<VkBuffer> uniformBuffers_explosionPipeline;
351 vector<VkDeviceMemory> uniformBuffersMemory_explosionPipeline;
352 vector<VkDescriptorBufferInfo> uniformBufferInfoList_explosionPipeline;
353
354 UBO_Explosion explosion_UBO;
355
[7297892]356 vector<BaseEffectOverTime*> effects;
357
[0807aeb]358 float shipSpeed = 0.5f;
359 float asteroidSpeed = 2.0f;
360
361 float spawnRate_asteroid = 0.5;
362 float lastSpawn_asteroid;
[4ece3bf]363
[1f81ecc]364 unsigned int leftLaserIdx = -1;
[b8efa56]365 EffectOverTime<ModelVertex, SSBO_Asteroid>* leftLaserEffect = nullptr;
[1f81ecc]366
367 unsigned int rightLaserIdx = -1;
[b8efa56]368 EffectOverTime<ModelVertex, SSBO_Asteroid>* rightLaserEffect = nullptr;
[1f81ecc]369
[20e4c2b]370 /*** High-level vars ***/
371
[301c90a]372 // TODO: Just typedef the type of this function to RenderScreenFn or something since it's used in a few places
373 void (VulkanGame::* currentRenderScreenFn)(int width, int height);
[20e4c2b]374
375 map<string, vector<UIValue>> valueLists;
376
377 int score;
378 float fps;
379
380 // TODO: Make a separate TImer class
381 time_point<steady_clock> startTime;
382 float fpsStartTime, curTime, prevTime, elapsedTime;
383
384 int frameCount;
385
386 /*** Functions ***/
387
[4e705d6]388 bool initUI(int width, int height, unsigned char guiFlags);
[0df3c9a]389 void initVulkan();
[f97c5e7]390 void initGraphicsPipelines();
[15104a8]391 void initMatrices();
[20e4c2b]392 void renderLoop();
[3f32dfd]393 void updateScene();
[0df3c9a]394 void cleanup();
[c1d9b2a]395
[c324d6a]396 void createVulkanInstance(const vector<const char*>& validationLayers);
[c1d9b2a]397 void setupDebugMessenger();
398 void populateDebugMessengerCreateInfo(VkDebugUtilsMessengerCreateInfoEXT& createInfo);
[90a424f]399 void createVulkanSurface();
[fe5c3ba]400 void pickPhysicalDevice(const vector<const char*>& deviceExtensions);
[fa9fa1c]401 bool isDeviceSuitable(VkPhysicalDevice physicalDevice, const vector<const char*>& deviceExtensions);
[c324d6a]402 void createLogicalDevice(const vector<const char*>& validationLayers,
[c1c2021]403 const vector<const char*>& deviceExtensions);
[3f32dfd]404 void chooseSwapChainProperties();
[502bd0b]405 void createSwapChain();
[f94eea9]406 void createImageViews();
[3f32dfd]407 void createResourceCommandPool();
[603b5bc]408 void createImageResources();
[cefdf23]409 VkFormat findDepthFormat(); // TODO: Declare/define (in the cpp file) this function in some util functions section
410 void createRenderPass();
411 void createCommandPools();
[603b5bc]412 void createFramebuffers();
413 void createCommandBuffers();
[34bdf3a]414 void createSyncObjects();
[f94eea9]415
[3f32dfd]416 void createTextureSampler();
417
[cefdf23]418 void initImGuiOverlay();
419 void cleanupImGuiOverlay();
420
[9d21aac]421 // TODO: Maybe move these to a different class, possibly VulkanBuffer or some new related class
422
423 void createBufferSet(VkDeviceSize bufferSize, VkBufferUsageFlags flags, VkMemoryPropertyFlags properties,
424 vector<VkBuffer>& buffers, vector<VkDeviceMemory>& buffersMemory,
425 vector<VkDescriptorBufferInfo>& bufferInfoList);
426
427 // TODO: See if it makes sense to rename this to resizeBufferSet() and use it to resize other types of buffers as well
428 // TODO: Remove the need for templating, which is only there so a GraphicsPupeline_Vulkan can be passed in
429 template<class VertexType, class SSBOType>
430 void resizeStorageBufferSet(StorageBufferSet& set, VkCommandPool commandPool, VkQueue graphicsQueue,
431 GraphicsPipeline_Vulkan<VertexType>& pipeline);
432
433 template<class SSBOType>
434 void updateStorageBuffer(StorageBufferSet& storageBufferSet, size_t objIndex, SSBOType& ssbo);
[3b7d497]435
[4994692]436 // TODO: Since addObject() returns a reference to the new object now,
437 // stop using objects.back() to access the object that was just created
[2d87297]438 template<class VertexType, class SSBOType>
[9d21aac]439 SceneObject<VertexType, SSBOType>& addObject(vector<SceneObject<VertexType, SSBOType>>& objects,
440 GraphicsPipeline_Vulkan<VertexType>& pipeline,
441 const vector<VertexType>& vertices, vector<uint16_t> indices,
442 SSBOType ssbo, bool pipelinesCreated);
[0fe8433]443
[cefdf23]444 template<class VertexType>
445 vector<VertexType> addObjectIndex(unsigned int objIndex, vector<VertexType> vertices);
446
447 template<class VertexType>
448 vector<VertexType> addVertexNormals(vector<VertexType> vertices);
449
450 template<class VertexType, class SSBOType>
451 void centerObject(SceneObject<VertexType, SSBOType>& object);
452
[2da64ef]453 template<class VertexType, class SSBOType>
454 void updateObject(vector<SceneObject<VertexType, SSBOType>>& objects,
[9d21aac]455 GraphicsPipeline_Vulkan<VertexType>& pipeline, size_t index);
[2da64ef]456
[1f81ecc]457 template<class VertexType, class SSBOType>
[9d21aac]458 void updateObjectVertices(GraphicsPipeline_Vulkan<VertexType>& pipeline,
[1f81ecc]459 SceneObject<VertexType, SSBOType>& obj, size_t index);
460
[52a02e6]461 void addLaser(vec3 start, vec3 end, vec3 color, float width);
462 void translateLaser(size_t index, const vec3& translation);
463 void updateLaserTarget(size_t index);
[b8efa56]464 bool getLaserAndAsteroidIntersection(SceneObject<ModelVertex, SSBO_Asteroid>& asteroid,
[52a02e6]465 vec3& start, vec3& end, vec3& intersection);
466
[4a9416a]467 void addExplosion(mat4 model_mat, float duration, float cur_time);
468
[ea2b4dc]469 void renderFrame(ImDrawData* draw_data);
[4e2c709]470 void presentFrame();
471
[d2d9286]472 void recreateSwapChain();
473
[c1c2021]474 void cleanupSwapChain();
[20e4c2b]475
476 /*** High-level functions ***/
477
[301c90a]478 void renderMainScreen(int width, int height);
479 void renderGameScreen(int width, int height);
[20e4c2b]480
481 void initGuiValueLists(map<string, vector<UIValue>>& valueLists);
482 void renderGuiValueList(vector<UIValue>& values);
483
[301c90a]484 void goToScreen(void (VulkanGame::* renderScreenFn)(int width, int height));
[20e4c2b]485 void quitGame();
[e8ebc76]486};
487
[4a9416a]488// Start of specialized no-op functions
489
490template<>
491inline void VulkanGame::centerObject(SceneObject<ExplosionVertex, SSBO_Explosion>& object) {
492}
493
494// End of specialized no-op functions
495
[9d21aac]496template<class VertexType, class SSBOType>
497void VulkanGame::resizeStorageBufferSet(StorageBufferSet& set, VkCommandPool commandPool, VkQueue graphicsQueue,
498 GraphicsPipeline_Vulkan<VertexType>& pipeline) {
499 pipeline.objectCapacity *= 2;
500 VkDeviceSize bufferSize = pipeline.objectCapacity * sizeof(SSBOType);
501
502 for (size_t i = 0; i < set.buffers.size(); i++) {
503 VkBuffer newStorageBuffer;
504 VkDeviceMemory newStorageBufferMemory;
505
506 VulkanUtils::createBuffer(device, physicalDevice, bufferSize,
507 VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT,
508 VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
509 newStorageBuffer, newStorageBufferMemory);
510
511 VulkanUtils::copyBuffer(device, commandPool, set.buffers[i], newStorageBuffer,
512 0, 0, pipeline.numObjects * sizeof(SSBOType), graphicsQueue);
513
514 vkDestroyBuffer(device, set.buffers[i], nullptr);
515 vkFreeMemory(device, set.memory[i], nullptr);
516
517 set.buffers[i] = newStorageBuffer;
518 set.memory[i] = newStorageBufferMemory;
519
520 set.infoSet[i].buffer = set.buffers[i];
521 set.infoSet[i].offset = 0; // This is the offset from the start of the buffer, so always 0 for now
522 set.infoSet[i].range = bufferSize; // Size of the update starting from offset, or VK_WHOLE_SIZE
523 }
524}
525
526// TODO: See if it makes sense to pass in the current swapchain index instead of updating all of them
527template<class SSBOType>
528void VulkanGame::updateStorageBuffer(StorageBufferSet& storageBufferSet, size_t objIndex, SSBOType& ssbo) {
529 for (size_t i = 0; i < storageBufferSet.memory.size(); i++) {
530 VulkanUtils::copyDataToMemory(device, ssbo, storageBufferSet.memory[i], objIndex * sizeof(SSBOType));
531 }
532}
533
[3b84bb6]534// TODO: Right now, it's basically necessary to pass the identity matrix in for ssbo.model
535// and to change the model matrix later by setting model_transform and then calling updateObject()
[9d21aac]536// Figure out a better way to allow the model matrix to be set during object creation
[2ba5617]537
538// TODO: Maybe return a reference to the object from this method if I decide that updating it
539// immediately after creation is a good idea (such as setting model_base)
540// Currently, model_base is set like this in a few places and the radius is set for asteroids
541// to account for scaling
[2d87297]542template<class VertexType, class SSBOType>
[9d21aac]543SceneObject<VertexType, SSBOType>& VulkanGame::addObject(vector<SceneObject<VertexType, SSBOType>>& objects,
544 GraphicsPipeline_Vulkan<VertexType>& pipeline,
545 const vector<VertexType>& vertices, vector<uint16_t> indices,
546 SSBOType ssbo, bool pipelinesCreated) {
[2ba5617]547 // TODO: Use the model field of ssbo to set the object's model_base
548 // currently, the passed in model is useless since it gets overridden in updateObject() anyway
[0fe8433]549 size_t numVertices = pipeline.getNumVertices();
550
551 for (uint16_t& idx : indices) {
552 idx += numVertices;
553 }
554
[5ba732a]555 objects.push_back({ vertices, indices, ssbo, mat4(1.0f), mat4(1.0f), false });
[3b84bb6]556
[2ba5617]557 SceneObject<VertexType, SSBOType>& obj = objects.back();
[1f81ecc]558
[cefdf23]559 // TODO: Specify whether to center the object outside of this function or, worst case, maybe
560 // with a boolean being passed in here, so that I don't have to rely on checking the specific object
561 // type
[4a9416a]562 if (!is_same_v<VertexType, LaserVertex> && !is_same_v<VertexType, ExplosionVertex>) {
[1f81ecc]563 centerObject(obj);
564 }
[2ba5617]565
[9d21aac]566 pipeline.addObject(obj.vertices, obj.indices, resourceCommandPool, graphicsQueue);
567
568 bool resizeStorageBuffer = pipeline.numObjects == pipeline.objectCapacity;
569
570 if (resizeStorageBuffer) {
571 resizeStorageBufferSet<VertexType, SSBOType>(pipeline.storageBufferSet, resourceCommandPool, graphicsQueue, pipeline);
572 pipeline.cleanup();
573
574 // Assume the SSBO is always the 2nd binding
575 pipeline.updateDescriptorInfo(1, &pipeline.storageBufferSet.infoSet);
576 }
577
578 pipeline.numObjects++;
579
580 updateStorageBuffer(pipeline.storageBufferSet, pipeline.numObjects - 1, obj.ssbo);
581
582 // TODO: Figure out why I am destroying and recreating the ubos when the swap chain is recreated,
583 // but am reusing the same ssbos. Maybe I don't need to recreate the ubos.
[0fe8433]584
[3b84bb6]585 if (pipelinesCreated) {
[44f23af]586 vkDeviceWaitIdle(device);
[9c0a614]587
588 for (uint32_t i = 0; i < swapChainImageCount; i++) {
589 vkFreeCommandBuffers(device, commandPools[i], 1, &commandBuffers[i]);
590 }
[44f23af]591
592 // TODO: The pipeline recreation only has to be done once per frame where at least
593 // one SSBO is resized.
594 // Refactor the logic to check for any resized SSBOs after all objects for the frame
595 // are created and then recreate each of the corresponding pipelines only once per frame
[9d21aac]596
597 // TODO: Also, verify if I actually need to recreate all of these, or maybe just the descriptor sets, for instance
598
599 if (resizeStorageBuffer) {
[44f23af]600 pipeline.createPipeline(pipeline.vertShaderFile, pipeline.fragShaderFile);
601 pipeline.createDescriptorPool(swapChainImages);
602 pipeline.createDescriptorSets(swapChainImages);
[3b84bb6]603 }
604
605 createCommandBuffers();
606 }
[4994692]607
608 return obj;
[0fe8433]609}
610
[cefdf23]611template<class VertexType>
612vector<VertexType> VulkanGame::addObjectIndex(unsigned int objIndex, vector<VertexType> vertices) {
613 for (VertexType& vertex : vertices) {
614 vertex.objIndex = objIndex;
615 }
[2da64ef]616
[cefdf23]617 return vertices;
[1f81ecc]618}
619
[914bb99]620// This function sets all the normals for a face to be parallel
621// This is good for models that should have distinct faces, but bad for models that should appear smooth
622// Maybe add an option to set all copies of a point to have the same normal and have the direction of
623// that normal be the weighted average of all the faces it is a part of, where the weight from each face
624// is its surface area.
625
626// TODO: Since the current approach to normal calculation basicaly makes indexed drawing useless, see if it's
627// feasible to automatically enable/disable indexed drawing based on which approach is used
[06d959f]628template<class VertexType>
629vector<VertexType> VulkanGame::addVertexNormals(vector<VertexType> vertices) {
630 for (unsigned int i = 0; i < vertices.size(); i += 3) {
631 vec3 p1 = vertices[i].pos;
[cefdf23]632 vec3 p2 = vertices[i + 1].pos;
633 vec3 p3 = vertices[i + 2].pos;
[06d959f]634
[a79be34]635 vec3 normal = normalize(cross(p2 - p1, p3 - p1));
[06d959f]636
637 // Add the same normal for all 3 vertices
638 vertices[i].normal = normal;
[cefdf23]639 vertices[i + 1].normal = normal;
640 vertices[i + 2].normal = normal;
[cf727ca]641 }
642
643 return vertices;
644}
645
[3b84bb6]646template<class VertexType, class SSBOType>
647void VulkanGame::centerObject(SceneObject<VertexType, SSBOType>& object) {
648 vector<VertexType>& vertices = object.vertices;
649
[a79be34]650 float min_x = vertices[0].pos.x;
651 float max_x = vertices[0].pos.x;
652 float min_y = vertices[0].pos.y;
653 float max_y = vertices[0].pos.y;
654 float min_z = vertices[0].pos.z;
655 float max_z = vertices[0].pos.z;
656
657 // start from the second point
658 for (unsigned int i = 1; i < vertices.size(); i++) {
[3b84bb6]659 vec3& pos = vertices[i].pos;
660
661 if (min_x > pos.x) {
662 min_x = pos.x;
663 } else if (max_x < pos.x) {
664 max_x = pos.x;
[a79be34]665 }
666
[3b84bb6]667 if (min_y > pos.y) {
668 min_y = pos.y;
669 } else if (max_y < pos.y) {
670 max_y = pos.y;
[a79be34]671 }
672
[3b84bb6]673 if (min_z > pos.z) {
674 min_z = pos.z;
675 } else if (max_z < pos.z) {
676 max_z = pos.z;
[a79be34]677 }
678 }
679
680 vec3 center = vec3(min_x + max_x, min_y + max_y, min_z + max_z) / 2.0f;
681
682 for (unsigned int i = 0; i < vertices.size(); i++) {
683 vertices[i].pos -= center;
684 }
685
[2ba5617]686 object.radius = std::max(max_x - center.x, max_y - center.y);
687 object.radius = std::max(object.radius, max_z - center.z);
688
[3b84bb6]689 object.center = vec3(0.0f, 0.0f, 0.0f);
[a79be34]690}
691
[cefdf23]692// TODO: Just pass in the single object instead of a list of all of them
693template<class VertexType, class SSBOType>
694void VulkanGame::updateObject(vector<SceneObject<VertexType, SSBOType>>& objects,
[9d21aac]695 GraphicsPipeline_Vulkan<VertexType>& pipeline, size_t index) {
[cefdf23]696 SceneObject<VertexType, SSBOType>& obj = objects[index];
697
698 obj.ssbo.model = obj.model_transform * obj.model_base;
699 obj.center = vec3(obj.ssbo.model * vec4(0.0f, 0.0f, 0.0f, 1.0f));
700
[9d21aac]701 updateStorageBuffer(pipeline.storageBufferSet, index, obj.ssbo);
[cefdf23]702
703 obj.modified = false;
704}
705
706template<class VertexType, class SSBOType>
[9d21aac]707void VulkanGame::updateObjectVertices(GraphicsPipeline_Vulkan<VertexType>& pipeline,
[cefdf23]708 SceneObject<VertexType, SSBOType>& obj, size_t index) {
709 pipeline.updateObjectVertices(index, obj.vertices, resourceCommandPool, graphicsQueue);
710}
711
[3b84bb6]712#endif // _VULKAN_GAME_H
Note: See TracBrowser for help on using the repository browser.