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

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

Modify the VulkanBuffer class to take a range and to align data based on that rather than the size of an individual data item. Also, reorganize the code in VulkanGae::updateScene() in a more logical fashion, and remove VulkanGame::updateObject() and inline its functionality.

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