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

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

Change VulkanUtils::copyDataToMemory() to always require a size and to optionally flush the memory. Also add a VulkanUtils::copyDataToMappedMemory function that does the same thing, but assumes the data is already mapped.

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