Crimson Engine 1.0.0
A high-performance C++20 game engine prototype showcasing a custom ECS, Vulkan renderer, and ImGui editor.
Loading...
Searching...
No Matches
RenderSystem.hpp
Go to the documentation of this file.
1#pragma once
2#include "../System.hpp"
3#include "../Registry.hpp"
11#include "glm/gtc/matrix_access.hpp"
12#include <glm/gtc/matrix_transform.hpp>
16#include <functional>
17#include <fstream>
18#include "core/JobSystem.hpp"
19
24class RenderSystem : public System {
25public:
32 : registry(reg), renderer(renderer) {
33 // Auto-track entities with Mesh + Transform + Material
34 registry.subscribeToAdded<Mesh>([this](Entity e) { checkAndAdd(e); });
35 registry.subscribeToAdded<Transform>([this](Entity e) { checkAndAdd(e); });
36 registry.subscribeToAdded<Material>([this](Entity e) { checkAndAdd(e); });
37 registry.subscribeToRemoved<Mesh>([this](Entity e) { removeEntity(e); });
38 registry.subscribeToRemoved<Transform>([this](Entity e) { removeEntity(e); });
39 registry.subscribeToRemoved<Material>([this](Entity e) { removeEntity(e); });
40
41 registry.subscribeToAdded<Grid>([this](Entity e) { checkAndAdd(e); });
42 registry.subscribeToRemoved<Grid>([this](Entity e) { removeEntity(e); });
43 }
44
49 void update(float dt) override {
51 renderer.updateInstanceBuffer(); // bulk upload to GPU
52 }
53
58 void drawFrame(const std::function<void(VkCommandBuffer)>& overlayPass = {}) {
60
61 VkCommandBuffer cmd = renderer.getCurrentCommandBuffer();
62
63 // --- Collect active light info ---
64 glm::vec4 ambientLight = glm::vec4(1.0f, 1.0f, 1.0f, 1.0f); // Renderer fallback sun as ambient fill
65 glm::vec4 lightDir = glm::vec4(0.0f, 1.0f, 0.0f, 0.0f); // Default key light direction, type 0 (directional)
66 glm::vec4 lightColor = glm::vec4(1.0f, 1.0f, 1.0f, 1.0f); // Default key light color/intensity
67
68 Entity lightEnt;
69 for (auto [e, light] : registry.view<Engine::LightComponent>()) {
70 lightEnt = e;
71 break;
72 }
73
74 if (lightEnt.getId() != Entity::INVALID_ENTITY && registry.isValid(lightEnt)) {
75 auto* light = registry.get<Engine::LightComponent>(lightEnt);
76 auto* transform = registry.get<Transform>(lightEnt);
77 if (light) {
78 glm::vec3 dir(0.0f, 1.0f, 0.0f);
79 if (transform) {
80 if (glm::dot(transform->position, transform->position) > 0.0001f) {
81 dir = glm::normalize(-transform->position);
82 } else {
83 dir = transform->forward();
84 }
85 }
86 lightDir = glm::vec4(dir.x, dir.y, dir.z, static_cast<float>(light->type));
87 lightColor = glm::vec4(light->color.x, light->color.y, light->color.z, light->intensity);
88 }
89 }
90
91 CameraUBO ubo{};
92 ubo.viewProj = renderer.getActiveCameraViewProj();
93 ubo.camPos = glm::vec4(renderer.getActiveCameraPosition(), 1.0f);
94 ubo.ambientLight = ambientLight;
95 ubo.lightDir = lightDir;
96 ubo.lightColor = lightColor;
97 renderer.updateCameraUBO(ubo);
98
99
100 std::vector<InstanceDataGPU> gpuData(renderer.instanceDataCPU.size());
101 for (size_t i = 0; i < renderer.instanceDataCPU.size(); i++) {
102 gpuData[i].model = renderer.instanceDataCPU.models[i];
103 gpuData[i].color = renderer.instanceDataCPU.colors[i];
104 }
105 renderer.instanceBuffer.uploadData(gpuData.data(), gpuData.size() * sizeof(InstanceDataGPU));
106
107
108 // --- Draw grids ---
109 drawGrids();
110
111 // --- Draw instances ---
112 drawBatches();
113
114 if (overlayPass) {
115 overlayPass(cmd);
116 }
117
118 renderer.endFrame();
119 }
120
121private:
127 std::vector<Entity> entities;
129 std::unordered_map<Entity, size_t> entityToInstanceIndex;
131 std::vector<Entity> renderableEntities;
132
138 if ((registry.get<Mesh>(e) && registry.get<Transform>(e) && registry.get<Material>(e))
139 || registry.get<Grid>(e)) {
140 if (std::find(entities.begin(), entities.end(), e) == entities.end())
141 entities.push_back(e);
142 }
143 }
144
150 entities.erase(std::remove(entities.begin(), entities.end(), e), entities.end());
151 }
152
156 glm::mat4 getWorldMatrix(Entity entity, int depth = 0) {
157 if (depth > 100) return glm::mat4(1.0f); // Safety depth limit to prevent infinite recursion
158 glm::mat4 model = glm::mat4(1.0f);
159 if (auto* transform = registry.get<Transform>(entity)) {
160 model = transform->matrix();
161 }
162 if (auto* hierarchy = registry.get<HierarchyComponent>(entity)) {
163 if (hierarchy->parent.getId() != Entity::INVALID_ENTITY && registry.isValid(hierarchy->parent)) {
164 // If this is a child mesh entity that is rigid/non-skinned, attach it to its parent bone if matching joint exists
165 if (auto* mesh = registry.get<Mesh>(entity)) {
166 if (!mesh->isSkinned) {
167 std::string targetBone = mesh->parentBoneName.empty() ? mesh->nodeName : mesh->parentBoneName;
168 if (!targetBone.empty()) {
169 if (auto* parentSkeleton = registry.get<SkeletonComponent>(hierarchy->parent)) {
170 int jointIdx = -1;
171
172 // 1. Exact match
173 for (size_t i = 0; i < parentSkeleton->joints.size(); ++i) {
174 if (parentSkeleton->joints[i].name == targetBone) {
175 jointIdx = static_cast<int>(i);
176 break;
177 }
178 }
179
180 // 2. Case-insensitive match fallback
181 if (jointIdx == -1) {
182 auto toLower = [](std::string s) {
183 for (char& c : s) c = static_cast<char>(std::tolower(c));
184 return s;
185 };
186 std::string lowerTarget = toLower(targetBone);
187 for (size_t i = 0; i < parentSkeleton->joints.size(); ++i) {
188 if (toLower(parentSkeleton->joints[i].name) == lowerTarget) {
189 jointIdx = static_cast<int>(i);
190 break;
191 }
192 }
193 }
194
195 // 3. Substring match fallback (handles prefixes/suffixes)
196 if (jointIdx == -1) {
197 for (size_t i = 0; i < parentSkeleton->joints.size(); ++i) {
198 if (parentSkeleton->joints[i].name.find(targetBone) != std::string::npos ||
199 targetBone.find(parentSkeleton->joints[i].name) != std::string::npos) {
200 jointIdx = static_cast<int>(i);
201 break;
202 }
203 }
204 }
205
206 if (jointIdx != -1 && jointIdx < static_cast<int>(parentSkeleton->jointMatrices.size())) {
207 return getWorldMatrix(hierarchy->parent, depth + 1) * parentSkeleton->jointMatrices[jointIdx];
208 }
209 }
210 }
211 }
212 }
213 model = getWorldMatrix(hierarchy->parent, depth + 1) * model;
214 }
215 }
216 return model;
217 }
218
223 renderer.instanceDataCPU.clear();
224 entityToInstanceIndex.clear();
225
226 renderableEntities.clear();
227 for (auto [entity, mesh, transform, material] :
228 registry.view<Mesh, Transform, Material>()) {
229 if (registry.get<Grid>(entity)) continue;
230 if (!mesh.visible) continue;
231 renderableEntities.push_back(entity);
232 }
233
234 std::vector<InstanceData> tempInstances(renderableEntities.size());
235
236 Engine::JobSystem::getInstance().parallelFor(static_cast<int>(renderableEntities.size()), [&](int idx) {
237 Entity entity = renderableEntities[idx];
238 auto* mesh = registry.get<Mesh>(entity);
239 auto* material = registry.get<Material>(entity);
240
241 InstanceData inst{};
242 inst.model = getWorldMatrix(entity);
243 inst.materialID = material ? material->id : 0;
244 inst.meshID = mesh ? mesh->id : 0;
245 inst.color = material ? material->color : glm::vec4(1.0f);
246
247 tempInstances[idx] = inst;
248 });
249
250 for (size_t i = 0; i < renderableEntities.size(); ++i) {
251 size_t instanceIdx = renderer.instanceDataCPU.push(tempInstances[i]);
253 }
254 }
255
260 glm::vec3 getCameraPosition() {
261 if (renderer.hasActiveCamera()) {
262 return renderer.getActiveCameraPosition();
263 }
264 return glm::vec3(0.0f);
265 }
266
270 void drawBatches() {
271 VkCommandBuffer cmd = renderer.getCurrentCommandBuffer();
272 VkDescriptorSet cameraSet = renderer.getCameraDescriptorSet();
273
274 // --- Group instances by Mesh + Material using the *existing* instance indices and track their Entities
275 std::unordered_map<std::pair<Mesh*, Material*>, std::vector<std::pair<Entity, size_t>>, pair_hash> batches;
276
277 for (Entity e : entities) {
278 auto* mesh = registry.get<Mesh>(e);
279 auto* mat = registry.get<Material>(e);
280 auto* transform = registry.get<Transform>(e);
281 if (!mesh || !mat || !transform) continue;
282
283 auto it = entityToInstanceIndex.find(e);
284 if (it == entityToInstanceIndex.end()) continue;
285 size_t idx = it->second;
286 batches[{mesh, mat}].push_back({e, idx});
287 }
288
289 for (auto& [key, batch] : batches) {
290 Mesh* mesh = key.first;
291 Material* mat = key.second;
292
293 if (!mesh || !mat || batch.empty() || mesh->vertexBuffer == VK_NULL_HANDLE || mesh->indexBuffer == VK_NULL_HANDLE || mat->pipeline == VK_NULL_HANDLE) continue;
294
295
296 // --- Bind pipeline
297 vkCmdBindPipeline(cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, mat->pipeline);
298
299 // --- Bind descriptor sets (camera at set 0, material sampler at set 1)
300 VkDescriptorSet descriptorSets[2] = {
301 cameraSet,
302 mat->descriptorSet != VK_NULL_HANDLE ? mat->descriptorSet : renderer.getDefaultTextureSet()
303 };
304
305 vkCmdBindDescriptorSets(cmd,
306 VK_PIPELINE_BIND_POINT_GRAPHICS,
307 mat->pipelineLayout,
308 0,
309 2,
310 descriptorSets,
311 0,
312 nullptr);
313
314 // --- Bind vertex buffers
315 VkBuffer vertexBuffers[] = { mesh->vertexBuffer };
316 VkDeviceSize vertexOffsets[] = { 0 };
317 vkCmdBindVertexBuffers(cmd, 0, 1, vertexBuffers, vertexOffsets);
318
319 // If you still have an instance buffer bound elsewhere, it's harmless,
320 // but we don't rely on it here because shader uses push.model.
321 // vkCmdBindVertexBuffers(cmd, 1, 1, &renderer.instanceBuffer.get(), offsets);
322
323 // --- Bind index buffer
324 vkCmdBindIndexBuffer(cmd, mesh->indexBuffer, 0, VK_INDEX_TYPE_UINT32);
325
326 // Draw each instance in this batch individually, pushing its model/color
327 for (auto& [e, instanceIdx] : batch) {
328 // Bind Joint Descriptor Set (Set 2) if entity (or parent) has a Skeleton component
329 SkeletonComponent* skeleton = registry.get<SkeletonComponent>(e);
330 if (!skeleton) {
331 if (auto* hierarchy = registry.get<HierarchyComponent>(e)) {
332 if (hierarchy->parent.getId() != Entity::INVALID_ENTITY && registry.isValid(hierarchy->parent)) {
333 skeleton = registry.get<SkeletonComponent>(hierarchy->parent);
334 }
335 }
336 }
337
338 if (skeleton && skeleton->descriptorSet != VK_NULL_HANDLE) {
339 vkCmdBindDescriptorSets(cmd,
340 VK_PIPELINE_BIND_POINT_GRAPHICS,
341 mat->pipelineLayout,
342 2, // Set 2
343 1,
344 &skeleton->descriptorSet,
345 0,
346 nullptr);
347 }
348
349 // read instance data from renderer.instanceDataCPU
350 const InstanceDataGPU& inst = renderer.instanceDataCPU.get(instanceIdx);
351
352 PushConstants pc{};
353 pc.model = inst.model;
354 pc.color = inst.color;
355 pc.camPos = glm::vec4(getCameraPosition(), 1.0f);
356 if (renderer.hasActiveCamera()) {
357 pc.viewProj = renderer.getActiveCameraViewProj();
358 } else {
359 pc.viewProj = glm::mat4(1.0f);
360 }
361 pc.scale = mat ? mat->roughness : 0.5f;
362 pc.fade = mat ? mat->metallic : 0.0f;
363
364 vkCmdPushConstants(cmd,
365 mat->pipelineLayout,
366 VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_FRAGMENT_BIT,
367 0,
368 sizeof(PushConstants),
369 &pc);
370
371 // Draw one instance
372 vkCmdDrawIndexed(cmd,
373 static_cast<uint32_t>(mesh->indices.size()),
374 1, // instance count = 1 because we handle instances manually
375 0, // firstIndex
376 0, // vertexOffset
377 0); // firstInstance
378 }
379 }
380 }
381
385 void drawGrids() {
386 VkCommandBuffer cmd = renderer.getCurrentCommandBuffer();
387 VkDescriptorSet cameraSet = renderer.getCameraDescriptorSet();
388
389 for (Entity e : entities) {
390 auto* grid = registry.get<Grid>(e);
391 auto* mat = registry.get<Material>(e);
392 if (!grid || !mat || mat->pipeline == VK_NULL_HANDLE) continue;
393
394
395 // Bind grid pipeline
396 vkCmdBindPipeline(cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, mat->pipeline);
397
398 // Bind grid quad vertex buffer to satisfy pipeline input requirements
399 if (auto* mesh = registry.get<Mesh>(e)) {
400 if (mesh->vertexBuffer != VK_NULL_HANDLE) {
401 VkBuffer vertexBuffers[] = { mesh->vertexBuffer };
402 VkDeviceSize vertexOffsets[] = { 0 };
403 vkCmdBindVertexBuffers(cmd, 0, 1, vertexBuffers, vertexOffsets);
404 }
405 }
406
407 // Bind descriptor sets (camera)
408 vkCmdBindDescriptorSets(cmd,
409 VK_PIPELINE_BIND_POINT_GRAPHICS,
410 mat->pipelineLayout,
411 0,
412 1,
413 &cameraSet,
414 0,
415 nullptr);
416
417 // Get camera position for grid positioning
418 glm::vec3 camPos = getCameraPosition();
419
420 // Push constants for grid shader
421 struct GridPushConstants {
422 glm::mat4 viewProj;
423 glm::vec4 color;
424 glm::vec4 camPos;
425 float scale;
426 float fade;
427 } pc;
428
429 // Use the camera's view-projection matrix
430 if (renderer.hasActiveCamera()) {
431 pc.viewProj = renderer.getActiveCameraViewProj();
432 } else {
433 pc.viewProj = glm::mat4(1.0f);
434 }
435
436 pc.color = grid->color;
437 pc.camPos = glm::vec4(camPos, 1.0f);
438 pc.scale = grid->spacing;
439 pc.fade = grid->size;
440
441 vkCmdPushConstants(cmd,
442 mat->pipelineLayout,
443 VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_FRAGMENT_BIT,
444 0,
445 sizeof(GridPushConstants),
446 &pc);
447
448 // Draw 6 vertices so the shader can emit a full-screen quad as two triangles.
449 vkCmdDraw(cmd, 6, 1, 0, 0);
450 }
451 }
452
457 struct pair_hash {
463 std::size_t operator()(const std::pair<Mesh*, Material*>& p) const {
464 return std::hash<Mesh*>()(p.first) ^ (std::hash<Material*>()(p.second) << 1);
465 }
466 };
467};
static JobSystem & getInstance()
Get the singleton instance.
Definition JobSystem.hpp:23
void parallelFor(int count, std::function< void(int)> func)
Splits a total loop count into chunks and evaluates them in parallel.
Definition JobSystem.cpp:143
Lightweight identifier representing a game object in the Entity Component System.
Definition Entity.hpp:11
static constexpr IdType INVALID_ENTITY
Constant representing a null or invalid entity.
Definition Entity.hpp:16
IdType getId() const
Retrieve the raw identifier of the entity.
Definition Entity.hpp:32
Coordinates entities and components, providing creation, removal, lookup, and views.
Definition Registry.hpp:30
auto view()
Generates a filtered view of entities containing the requested components.
Definition Registry.hpp:279
VulkanRenderer & renderer
Reference to the renderer.
Definition RenderSystem.hpp:125
void removeEntity(Entity e)
Removes an entity from tracking when components are removed.
Definition RenderSystem.hpp:149
glm::mat4 getWorldMatrix(Entity entity, int depth=0)
Computes the absolute world matrix of an entity by traversing the hierarchy.
Definition RenderSystem.hpp:156
void buildInstanceData()
Rebuilds instance data by iterating over entities.
Definition RenderSystem.hpp:222
void update(float dt) override
System update called each frame to rebuild instance data.
Definition RenderSystem.hpp:49
std::vector< Entity > entities
List of tracked entities that have renderable components.
Definition RenderSystem.hpp:127
glm::vec3 getCameraPosition()
Retrieves the active camera's world position.
Definition RenderSystem.hpp:260
void drawBatches()
Binds pipelines, descriptor sets, and draw buffers for geometry batches.
Definition RenderSystem.hpp:270
void drawFrame(const std::function< void(VkCommandBuffer)> &overlayPass={})
Executes the rendering pass, drawing geometry, grid, and optional GUI/overlay passes.
Definition RenderSystem.hpp:58
void drawGrids()
Draws all active grid overlays.
Definition RenderSystem.hpp:385
void checkAndAdd(Entity e)
Verifies if an entity meets requirements for rendering and adds it to the tracked list.
Definition RenderSystem.hpp:137
RenderSystem(Registry &reg, VulkanRenderer &renderer)
Construct a new Render System object and subscribes to component add/remove events.
Definition RenderSystem.hpp:31
std::unordered_map< Entity, size_t > entityToInstanceIndex
Mapping from entity to its instance index in CPU buffers.
Definition RenderSystem.hpp:129
Registry & registry
Reference to the entity registry.
Definition RenderSystem.hpp:123
std::vector< Entity > renderableEntities
Vector to track renderable entities to avoid allocation.
Definition RenderSystem.hpp:131
Base class for ECS systems that process sets of entities.
Definition System.hpp:12
Manages core Vulkan pipeline states, device interaction, frames, buffers, and command submissions.
Definition VulkanRenderer.hpp:127
void beginFrame()
Starts render pass recording for the current frame.
Definition VulkanRenderer.cpp:202
VkCommandBuffer getCurrentCommandBuffer()
Retrieves active Vulkan command buffer for current frame.
Definition VulkanRenderer.hpp:273
InstanceDataSoA instanceDataCPU
CPU-side instancing data in Structure-of-Arrays format.
Definition VulkanRenderer.hpp:374
glm::mat4 viewProj
View-projection matrix.
Definition VulkanRenderer.hpp:40
glm::vec4 camPos
Definition VulkanRenderer.hpp:41
glm::vec4 lightColor
Definition VulkanRenderer.hpp:44
glm::vec4 ambientLight
Definition VulkanRenderer.hpp:42
glm::vec4 lightDir
Definition VulkanRenderer.hpp:43
Component representing a light source in the scene.
Definition LightComponent.hpp:27
Represents a grid component used for rendering a grid overlay.
Definition Grid.hpp:9
Represents a parent-child relationship between ECS entities.
Definition Hierarchy.hpp:8
Layout of per-instance data uploaded to the GPU for instanced rendering.
Definition pushconstants.hpp:29
glm::vec4 color
Instance color.
Definition pushconstants.hpp:33
glm::mat4 model
Model transform matrix.
Definition pushconstants.hpp:31
size_t push(const InstanceData &inst)
Appends a new instance.
Definition VulkanRenderer.hpp:91
Represents a material component defining rendering properties.
Definition Material.hpp:17
VkPipelineLayout pipelineLayout
Optional per-material custom Vulkan pipeline layout.
Definition Material.hpp:31
float metallic
Definition Material.hpp:45
VkDescriptorSet descriptorSet
Vulkan descriptor set representing resource bindings.
Definition Material.hpp:27
float roughness
Definition Material.hpp:43
VkPipeline pipeline
Optional per-material custom Vulkan pipeline.
Definition Material.hpp:29
Represents a mesh component that holds geometry data and its Vulkan buffers.
Definition Mesh.hpp:95
VkBuffer vertexBuffer
Vulkan buffer holding the vertex data.
Definition Mesh.hpp:115
std::vector< uint32_t > indices
CPU-side index data.
Definition Mesh.hpp:112
VkBuffer indexBuffer
Vulkan buffer holding the index data.
Definition Mesh.hpp:119
Struct for passing constant data directly via Vulkan push constants to shaders.
Definition pushconstants.hpp:10
glm::vec4 camPos
Camera position in world space.
Definition pushconstants.hpp:18
float fade
Fade amount (e.g., for grids).
Definition pushconstants.hpp:22
glm::mat4 model
Model matrix of the object being rendered.
Definition pushconstants.hpp:12
glm::vec4 color
Base color multiplier.
Definition pushconstants.hpp:14
glm::mat4 viewProj
Precomputed view-projection matrix.
Definition pushconstants.hpp:16
float scale
Scale factor.
Definition pushconstants.hpp:20
Custom hash function for std::pair<Mesh*, Material*> used in batch rendering maps.
Definition RenderSystem.hpp:457
std::size_t operator()(const std::pair< Mesh *, Material * > &p) const
Computes hash for pair of Mesh and Material pointers.
Definition RenderSystem.hpp:463
Component managing the list of joints and generating the offset matrices palette.
Definition Skeleton.hpp:37
VkDescriptorSet descriptorSet
Definition Skeleton.hpp:45
Represents the position, rotation, and scale of an entity in 3D space.
Definition Transform.hpp:127
static ufbxi_noinline int depth
Definition ufbx.cpp:7467
double scale
Definition ufbx.cpp:26002
const ufbx_keyframe * key
Definition ufbx.cpp:25982