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
Line 
1#ifndef _VULKAN_GAME_H
2#define _VULKAN_GAME_H
3
4#include <algorithm>
5#include <chrono>
6#include <map>
7#include <vector>
8
9#include <vulkan/vulkan.h>
10
11#include <SDL2/SDL.h>
12#include <SDL2/SDL_ttf.h>
13
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
16#define GLM_FORCE_RIGHT_HANDED
17
18#include <glm/glm.hpp>
19#include <glm/gtc/matrix_transform.hpp>
20
21#include "IMGUI/imgui_impl_vulkan.h"
22
23#include "consts.hpp"
24#include "graphics-pipeline_vulkan.hpp"
25#include "game-gui-sdl.hpp"
26#include "utils.hpp"
27#include "vulkan-utils.hpp"
28
29using namespace glm;
30using namespace std::chrono;
31
32#ifdef NDEBUG
33 const bool ENABLE_VALIDATION_LAYERS = false;
34#else
35 const bool ENABLE_VALIDATION_LAYERS = true;
36#endif
37
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
41struct OverlayVertex {
42 vec3 pos;
43 vec2 texCoord;
44};
45
46struct ModelVertex {
47 vec3 pos;
48 vec3 color;
49 vec2 texCoord;
50 vec3 normal;
51 unsigned int objIndex;
52};
53
54struct LaserVertex {
55 vec3 pos;
56 vec2 texCoord;
57 unsigned int objIndex;
58};
59
60struct ExplosionVertex {
61 vec3 particleStartVelocity;
62 float particleStartTime;
63 unsigned int objIndex;
64};
65
66struct SSBO_ModelObject {
67 alignas(16) mat4 model;
68};
69
70struct SSBO_Asteroid {
71 alignas(16) mat4 model;
72 alignas(4) float hp;
73 alignas(4) unsigned int deleted;
74};
75
76struct SSBO_Laser {
77 alignas(16) mat4 model;
78 alignas(4) vec3 color;
79 alignas(4) unsigned int deleted;
80};
81
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
89struct UBO_VP_mats {
90 alignas(16) mat4 view;
91 alignas(16) mat4 proj;
92};
93
94struct UBO_Explosion {
95 alignas(16) mat4 view;
96 alignas(16) mat4 proj;
97 alignas(4) float cur_time;
98};
99
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
112 bool modified;
113
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
118 SceneObject<ModelVertex, SSBO_Asteroid>* targetAsteroid; // currently only used for lasers
119};
120
121// TODO: Have to figure out how to include an optional ssbo parameter for each object
122// Could probably use the same approach to make indices optional
123// Figure out if there are sufficient use cases to make either of these optional or is it fine to make
124// them mamdatory
125
126
127// TODO: Look into using dynamic_cast to check types of SceneObject and EffectOverTime
128
129struct BaseEffectOverTime {
130 bool deleted;
131
132 virtual void applyEffect(float curTime) = 0;
133
134 BaseEffectOverTime() :
135 deleted(false) {
136 }
137
138 virtual ~BaseEffectOverTime() {
139 }
140};
141
142template<class VertexType, class SSBOType>
143struct EffectOverTime : public BaseEffectOverTime {
144 GraphicsPipeline_Vulkan<VertexType>& pipeline;
145 vector<SceneObject<VertexType, SSBOType>>& objects;
146 unsigned int objectIndex;
147 size_t effectedFieldOffset;
148 float startValue;
149 float startTime;
150 float changePerSecond;
151
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) {
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
168 void applyEffect(float curTime) {
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
185// TODO: Maybe move this to a different header
186
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
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
206class VulkanGame {
207
208 public:
209
210 VulkanGame();
211 ~VulkanGame();
212
213 void run(int width, int height, unsigned char guiFlags);
214
215 private:
216
217 static VKAPI_ATTR VkBool32 VKAPI_CALL debugCallback(
218 VkDebugUtilsMessageSeverityFlagBitsEXT messageSeverity,
219 VkDebugUtilsMessageTypeFlagsEXT messageType,
220 const VkDebugUtilsMessengerCallbackDataEXT* pCallbackData,
221 void* pUserData);
222
223 // TODO: Maybe pass these in as parameters to some Camera class
224 const float NEAR_CLIP = 0.1f;
225 const float FAR_CLIP = 100.0f;
226 const float FOV_ANGLE = 67.0f; // means the camera lens goes from -33 deg to 33 deg
227
228 const int EXPLOSION_PARTICLE_COUNT = 300;
229 const vec3 LASER_COLOR = vec3(0.2f, 1.0f, 0.2f);
230
231 bool done;
232
233 vec3 cam_pos;
234
235 // TODO: Good place to start using smart pointers
236 GameGui* gui;
237
238 SDL_version sdlVersion;
239 SDL_Window* window = nullptr;
240
241 int drawableWidth, drawableHeight;
242
243 VkInstance instance;
244 VkDebugUtilsMessengerEXT debugMessenger;
245 VkSurfaceKHR vulkanSurface;
246 VkPhysicalDevice physicalDevice = VK_NULL_HANDLE;
247 VkDevice device;
248
249 VkQueue graphicsQueue;
250 VkQueue presentQueue;
251
252 // TODO: Maybe make a swapchain struct for convenience
253 VkSurfaceFormatKHR swapChainSurfaceFormat;
254 VkPresentModeKHR swapChainPresentMode;
255 VkExtent2D swapChainExtent;
256 uint32_t swapChainMinImageCount;
257 uint32_t swapChainImageCount;
258 VkSwapchainKHR swapChain;
259 vector<VkImage> swapChainImages;
260 vector<VkImageView> swapChainImageViews;
261 vector<VkFramebuffer> swapChainFramebuffers;
262
263 VkRenderPass renderPass;
264
265 VkCommandPool resourceCommandPool;
266
267 vector<VkCommandPool> commandPools;
268 vector<VkCommandBuffer> commandBuffers;
269
270 VulkanImage depthImage;
271
272 // These are per frame
273 vector<VkSemaphore> imageAcquiredSemaphores;
274 vector<VkSemaphore> renderCompleteSemaphores;
275
276 // These are per swap chain image
277 vector<VkFence> inFlightFences;
278
279 uint32_t imageIndex;
280 uint32_t currentFrame;
281
282 bool shouldRecreateSwapChain;
283
284 VkSampler textureSampler;
285
286 VulkanImage floorTextureImage;
287 VkDescriptorImageInfo floorTextureImageDescriptor;
288
289 VulkanImage laserTextureImage;
290 VkDescriptorImageInfo laserTextureImageDescriptor;
291
292 mat4 viewMat, projMat;
293
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
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;
307
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
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
316 vector<SceneObject<ModelVertex, SSBO_ModelObject>> modelObjects;
317
318 vector<VkBuffer> uniformBuffers_modelPipeline;
319 vector<VkDeviceMemory> uniformBuffersMemory_modelPipeline;
320 vector<VkDescriptorBufferInfo> uniformBufferInfoList_modelPipeline;
321
322 UBO_VP_mats object_VP_mats;
323
324 vector<SceneObject<ModelVertex, SSBO_ModelObject>> shipObjects;
325
326 vector<VkBuffer> uniformBuffers_shipPipeline;
327 vector<VkDeviceMemory> uniformBuffersMemory_shipPipeline;
328 vector<VkDescriptorBufferInfo> uniformBufferInfoList_shipPipeline;
329
330 UBO_VP_mats ship_VP_mats;
331
332 vector<SceneObject<ModelVertex, SSBO_Asteroid>> asteroidObjects;
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
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
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
356 vector<BaseEffectOverTime*> effects;
357
358 float shipSpeed = 0.5f;
359 float asteroidSpeed = 2.0f;
360
361 float spawnRate_asteroid = 0.5;
362 float lastSpawn_asteroid;
363
364 unsigned int leftLaserIdx = -1;
365 EffectOverTime<ModelVertex, SSBO_Asteroid>* leftLaserEffect = nullptr;
366
367 unsigned int rightLaserIdx = -1;
368 EffectOverTime<ModelVertex, SSBO_Asteroid>* rightLaserEffect = nullptr;
369
370 /*** High-level vars ***/
371
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);
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
388 bool initUI(int width, int height, unsigned char guiFlags);
389 void initVulkan();
390 void initGraphicsPipelines();
391 void initMatrices();
392 void renderLoop();
393 void updateScene();
394 void cleanup();
395
396 void createVulkanInstance(const vector<const char*>& validationLayers);
397 void setupDebugMessenger();
398 void populateDebugMessengerCreateInfo(VkDebugUtilsMessengerCreateInfoEXT& createInfo);
399 void createVulkanSurface();
400 void pickPhysicalDevice(const vector<const char*>& deviceExtensions);
401 bool isDeviceSuitable(VkPhysicalDevice physicalDevice, const vector<const char*>& deviceExtensions);
402 void createLogicalDevice(const vector<const char*>& validationLayers,
403 const vector<const char*>& deviceExtensions);
404 void chooseSwapChainProperties();
405 void createSwapChain();
406 void createImageViews();
407 void createResourceCommandPool();
408 void createImageResources();
409 VkFormat findDepthFormat(); // TODO: Declare/define (in the cpp file) this function in some util functions section
410 void createRenderPass();
411 void createCommandPools();
412 void createFramebuffers();
413 void createCommandBuffers();
414 void createSyncObjects();
415
416 void createTextureSampler();
417
418 void initImGuiOverlay();
419 void cleanupImGuiOverlay();
420
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);
435
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
438 template<class VertexType, class SSBOType>
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);
443
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
453 template<class VertexType, class SSBOType>
454 void updateObject(vector<SceneObject<VertexType, SSBOType>>& objects,
455 GraphicsPipeline_Vulkan<VertexType>& pipeline, size_t index);
456
457 template<class VertexType, class SSBOType>
458 void updateObjectVertices(GraphicsPipeline_Vulkan<VertexType>& pipeline,
459 SceneObject<VertexType, SSBOType>& obj, size_t index);
460
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);
464 bool getLaserAndAsteroidIntersection(SceneObject<ModelVertex, SSBO_Asteroid>& asteroid,
465 vec3& start, vec3& end, vec3& intersection);
466
467 void addExplosion(mat4 model_mat, float duration, float cur_time);
468
469 void renderFrame(ImDrawData* draw_data);
470 void presentFrame();
471
472 void recreateSwapChain();
473
474 void cleanupSwapChain();
475
476 /*** High-level functions ***/
477
478 void renderMainScreen(int width, int height);
479 void renderGameScreen(int width, int height);
480
481 void initGuiValueLists(map<string, vector<UIValue>>& valueLists);
482 void renderGuiValueList(vector<UIValue>& values);
483
484 void goToScreen(void (VulkanGame::* renderScreenFn)(int width, int height));
485 void quitGame();
486};
487
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
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
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()
536// Figure out a better way to allow the model matrix to be set during object creation
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
542template<class VertexType, class SSBOType>
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) {
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
549 size_t numVertices = pipeline.getNumVertices();
550
551 for (uint16_t& idx : indices) {
552 idx += numVertices;
553 }
554
555 objects.push_back({ vertices, indices, ssbo, mat4(1.0f), mat4(1.0f), false });
556
557 SceneObject<VertexType, SSBOType>& obj = objects.back();
558
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
562 if (!is_same_v<VertexType, LaserVertex> && !is_same_v<VertexType, ExplosionVertex>) {
563 centerObject(obj);
564 }
565
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.
584
585 if (pipelinesCreated) {
586 vkDeviceWaitIdle(device);
587
588 for (uint32_t i = 0; i < swapChainImageCount; i++) {
589 vkFreeCommandBuffers(device, commandPools[i], 1, &commandBuffers[i]);
590 }
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
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) {
600 pipeline.createPipeline(pipeline.vertShaderFile, pipeline.fragShaderFile);
601 pipeline.createDescriptorPool(swapChainImages);
602 pipeline.createDescriptorSets(swapChainImages);
603 }
604
605 createCommandBuffers();
606 }
607
608 return obj;
609}
610
611template<class VertexType>
612vector<VertexType> VulkanGame::addObjectIndex(unsigned int objIndex, vector<VertexType> vertices) {
613 for (VertexType& vertex : vertices) {
614 vertex.objIndex = objIndex;
615 }
616
617 return vertices;
618}
619
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
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;
632 vec3 p2 = vertices[i + 1].pos;
633 vec3 p3 = vertices[i + 2].pos;
634
635 vec3 normal = normalize(cross(p2 - p1, p3 - p1));
636
637 // Add the same normal for all 3 vertices
638 vertices[i].normal = normal;
639 vertices[i + 1].normal = normal;
640 vertices[i + 2].normal = normal;
641 }
642
643 return vertices;
644}
645
646template<class VertexType, class SSBOType>
647void VulkanGame::centerObject(SceneObject<VertexType, SSBOType>& object) {
648 vector<VertexType>& vertices = object.vertices;
649
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++) {
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;
665 }
666
667 if (min_y > pos.y) {
668 min_y = pos.y;
669 } else if (max_y < pos.y) {
670 max_y = pos.y;
671 }
672
673 if (min_z > pos.z) {
674 min_z = pos.z;
675 } else if (max_z < pos.z) {
676 max_z = pos.z;
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
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
689 object.center = vec3(0.0f, 0.0f, 0.0f);
690}
691
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,
695 GraphicsPipeline_Vulkan<VertexType>& pipeline, size_t index) {
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
701 updateStorageBuffer(pipeline.storageBufferSet, index, obj.ssbo);
702
703 obj.modified = false;
704}
705
706template<class VertexType, class SSBOType>
707void VulkanGame::updateObjectVertices(GraphicsPipeline_Vulkan<VertexType>& pipeline,
708 SceneObject<VertexType, SSBOType>& obj, size_t index) {
709 pipeline.updateObjectVertices(index, obj.vertices, resourceCommandPool, graphicsQueue);
710}
711
712#endif // _VULKAN_GAME_H
Note: See TracBrowser for help on using the repository browser.