MayaFlux 0.3.0
Digital-First Multimedia Processing Framework
Loading...
Searching...
No Matches
RenderFlow.cpp
Go to the documentation of this file.
1#include "RenderFlow.hpp"
2
4
7
11
13
15
16bool RenderFlow::s_initialized = false;
17
18namespace {
19
20 /**
21 * @brief Translate semantic VertexLayout to Vulkan bindings/attributes
22 * @param layout Semantic vertex layout
23 * @return Tuple of (bindings, attributes)
24 */
25 static std::pair<
26 std::vector<Core::VertexBinding>,
27 std::vector<Core::VertexAttribute>>
28 translate_semantic_layout(const Kakshya::VertexLayout& layout)
29 {
30 using namespace MayaFlux::Portal::Graphics;
31
32 auto [vk_bindings, vk_attributes] = VertexLayoutTranslator::translate_layout(layout);
33
35 "Translated semantic vertex layout: {} bindings, {} attributes",
36 vk_bindings.size(), vk_attributes.size());
37
38 return { vk_bindings, vk_attributes };
39 }
40
41} // anonymous namespace
42
43//==============================================================================
44// Initialization
45//==============================================================================
46
48{
49 if (s_initialized) {
51 "RenderFlow already initialized (static flag)");
52 return true;
53 }
54
55 if (m_shader_foundry) {
57 "RenderFlow already initialized");
58 return true;
59 }
60
64 "ShaderFoundry must be initialized before RenderFlow");
65 return false;
66 }
67
70
71 if (!m_display_service) {
73 "DisplayService not found in BackendRegistry");
74 return false;
75 }
76
77 s_initialized = true;
78
80 "RenderFlow initialized");
81 return true;
82}
83
85{
86 if (!s_initialized) {
87 return;
88 }
89
91 "RenderFlow stopped");
92}
93
95{
96 if (!s_initialized) {
97 return;
98 }
99
101 "Shutting down RenderFlow...");
102
105 "Cannot shutdown RenderFlow: ShaderFoundry not initialized");
106 return;
107 }
108
109 auto device = m_shader_foundry->get_device();
110
111 if (!device) {
113 "Cannot shutdown RenderFlow: Vulkan device is null");
114 return;
115 }
116
118
119 m_window_associations.clear();
120
121 m_shader_foundry = nullptr;
122 m_display_service = nullptr;
123
124 s_initialized = false;
125
127 "RenderFlow shutdown complete");
128}
129
130//==============================================================================
131// Utility Conversions (Portal enums → Vulkan enums)
132//==============================================================================
133
134namespace {
135
136 vk::PrimitiveTopology to_vk_topology(PrimitiveTopology topology)
137 {
138 switch (topology) {
140 return vk::PrimitiveTopology::ePointList;
142 return vk::PrimitiveTopology::eLineList;
144 return vk::PrimitiveTopology::eLineStrip;
146 return vk::PrimitiveTopology::eTriangleList;
148 return vk::PrimitiveTopology::eTriangleStrip;
150 return vk::PrimitiveTopology::eTriangleFan;
151 default:
152 return vk::PrimitiveTopology::eTriangleList;
153 }
154 }
155
156 vk::PolygonMode to_vk_polygon_mode(PolygonMode mode)
157 {
158 switch (mode) {
160 return vk::PolygonMode::eFill;
162 return vk::PolygonMode::eLine;
164 return vk::PolygonMode::ePoint;
165 default:
166 return vk::PolygonMode::eFill;
167 }
168 }
169
170 vk::CullModeFlags to_vk_cull_mode(CullMode mode)
171 {
172 switch (mode) {
173 case CullMode::NONE:
174 return vk::CullModeFlagBits::eNone;
175 case CullMode::FRONT:
176 return vk::CullModeFlagBits::eFront;
177 case CullMode::BACK:
178 return vk::CullModeFlagBits::eBack;
180 return vk::CullModeFlagBits::eFrontAndBack;
181 default:
182 return vk::CullModeFlagBits::eBack;
183 }
184 }
185
186 vk::CompareOp to_vk_compare_op(CompareOp op)
187 {
188 switch (op) {
189 case CompareOp::NEVER:
190 return vk::CompareOp::eNever;
191 case CompareOp::LESS:
192 return vk::CompareOp::eLess;
193 case CompareOp::EQUAL:
194 return vk::CompareOp::eEqual;
196 return vk::CompareOp::eLessOrEqual;
198 return vk::CompareOp::eGreater;
200 return vk::CompareOp::eNotEqual;
202 return vk::CompareOp::eGreaterOrEqual;
204 return vk::CompareOp::eAlways;
205 default:
206 return vk::CompareOp::eLess;
207 }
208 }
209
210 vk::BlendFactor to_vk_blend_factor(BlendFactor factor)
211 {
212 switch (factor) {
214 return vk::BlendFactor::eZero;
215 case BlendFactor::ONE:
216 return vk::BlendFactor::eOne;
218 return vk::BlendFactor::eSrcColor;
220 return vk::BlendFactor::eOneMinusSrcColor;
222 return vk::BlendFactor::eDstColor;
224 return vk::BlendFactor::eOneMinusDstColor;
226 return vk::BlendFactor::eSrcAlpha;
228 return vk::BlendFactor::eOneMinusSrcAlpha;
230 return vk::BlendFactor::eDstAlpha;
232 return vk::BlendFactor::eOneMinusDstAlpha;
233 default:
234 return vk::BlendFactor::eOne;
235 }
236 }
237
238 vk::BlendOp to_vk_blend_op(BlendOp op)
239 {
240 switch (op) {
241 case BlendOp::ADD:
242 return vk::BlendOp::eAdd;
244 return vk::BlendOp::eSubtract;
246 return vk::BlendOp::eReverseSubtract;
247 case BlendOp::MIN:
248 return vk::BlendOp::eMin;
249 case BlendOp::MAX:
250 return vk::BlendOp::eMax;
251 default:
252 return vk::BlendOp::eAdd;
253 }
254 }
255} // anonymous namespace
256
257//==============================================================================
258// Pipeline Creation
259//==============================================================================
260
262 const RenderPipelineConfig& config,
263 const std::vector<vk::Format>& color_formats,
264 vk::Format depth_format)
265{
266 if (!is_initialized()) {
268 "RenderFlow not initialized");
270 }
271
272 if (config.mesh_shader == INVALID_SHADER && config.vertex_shader == INVALID_SHADER) {
274 "Pipeline requires either mesh shader or vertex shader");
276 }
277
278 if (color_formats.empty()) {
280 "At least one color format required for dynamic rendering pipeline");
282 }
283
285
287 if (config.fragment_shader != INVALID_SHADER) {
289 }
290 if (config.geometry_shader != INVALID_SHADER) {
292 }
293 if (config.tess_control_shader != INVALID_SHADER) {
295 }
296 if (config.tess_eval_shader != INVALID_SHADER) {
298 }
299
301 if (config.task_shader != INVALID_SHADER) {
303 }
304
305 if (config.fragment_shader != INVALID_SHADER) {
307 }
308
309 if (config.semantic_vertex_layout.has_value()) {
311 "Pipeline using semantic VertexLayout ({} vertices, {} attributes)",
312 config.semantic_vertex_layout->vertex_count,
313 config.semantic_vertex_layout->attributes.size());
314
315 auto [vk_bindings, vk_attributes] = translate_semantic_layout(
316 config.semantic_vertex_layout.value());
317
318 vk_config.vertex_bindings = vk_bindings;
319 vk_config.vertex_attributes = vk_attributes;
320 vk_config.use_vertex_shader_reflection = false;
321
322 } else if (!config.vertex_bindings.empty() || !config.vertex_attributes.empty()) {
324 "Pipeline using explicit vertex config ({} bindings, {} attributes)",
325 config.vertex_bindings.size(), config.vertex_attributes.size());
326
327 for (const auto& binding : config.vertex_bindings) {
328 Core::VertexBinding vk_binding {};
329 vk_binding.binding = binding.binding;
330 vk_binding.stride = binding.stride;
331 vk_binding.input_rate = binding.per_instance ? vk::VertexInputRate::eInstance : vk::VertexInputRate::eVertex;
332 vk_config.vertex_bindings.push_back(vk_binding);
333 }
334
335 for (const auto& attr : config.vertex_attributes) {
336 Core::VertexAttribute vk_attr {};
337 vk_attr.location = attr.location;
338 vk_attr.binding = attr.binding;
339 vk_attr.format = attr.format;
340 vk_attr.offset = attr.offset;
341 vk_config.vertex_attributes.push_back(vk_attr);
342 }
343
344 vk_config.use_vertex_shader_reflection = false;
345 } else {
347 "Pipeline will use shader reflection for vertex input");
349 }
350
351 vk_config.topology = to_vk_topology(config.topology);
352 vk_config.primitive_restart_enable = false;
353
354 vk_config.polygon_mode = to_vk_polygon_mode(config.rasterization.polygon_mode);
355 vk_config.cull_mode = to_vk_cull_mode(config.rasterization.cull_mode);
356 vk_config.front_face = config.rasterization.front_face_ccw ? vk::FrontFace::eCounterClockwise : vk::FrontFace::eClockwise;
357 vk_config.line_width = config.rasterization.line_width;
359 vk_config.depth_bias_enable = config.rasterization.depth_bias;
360
363 vk_config.depth_compare_op = to_vk_compare_op(config.depth_stencil.depth_compare_op);
365
366 for (const auto& blend : config.blend_attachments) {
368 vk_blend.blend_enable = blend.blend_enable;
369 vk_blend.src_color_blend_factor = to_vk_blend_factor(blend.src_color_factor);
370 vk_blend.dst_color_blend_factor = to_vk_blend_factor(blend.dst_color_factor);
371 vk_blend.color_blend_op = to_vk_blend_op(blend.color_blend_op);
372 vk_blend.src_alpha_blend_factor = to_vk_blend_factor(blend.src_alpha_factor);
373 vk_blend.dst_alpha_blend_factor = to_vk_blend_factor(blend.dst_alpha_factor);
374 vk_blend.alpha_blend_op = to_vk_blend_op(blend.alpha_blend_op);
375 vk_config.color_blend_attachments.push_back(vk_blend);
376 }
377
378 std::vector<vk::DescriptorSetLayout> layouts;
379 for (const auto& desc_set : config.descriptor_sets) {
380 std::vector<vk::DescriptorSetLayoutBinding> bindings;
381 for (const auto& binding : desc_set) {
382 vk::DescriptorSetLayoutBinding vk_binding;
383 vk_binding.binding = binding.binding;
384 vk_binding.descriptorType = binding.type;
385 vk_binding.descriptorCount = 1;
386 vk_binding.stageFlags = vk::ShaderStageFlagBits::eVertex | vk::ShaderStageFlagBits::eFragment;
387 bindings.push_back(vk_binding);
388 }
389
390 vk::DescriptorSetLayoutCreateInfo layout_info;
391 layout_info.bindingCount = static_cast<uint32_t>(bindings.size());
392 layout_info.pBindings = bindings.data();
393
394 auto layout = m_shader_foundry->get_device().createDescriptorSetLayout(layout_info);
395 layouts.push_back(layout);
396 }
397 vk_config.descriptor_set_layouts = layouts;
398
399 vk::ShaderStageFlags push_constant_stages;
400
401 if (config.mesh_shader != INVALID_SHADER) {
402 push_constant_stages = vk::ShaderStageFlagBits::eMeshEXT;
403 if (config.task_shader != INVALID_SHADER) {
404 push_constant_stages |= vk::ShaderStageFlagBits::eTaskEXT;
405 }
406 if (config.fragment_shader != INVALID_SHADER) {
407 push_constant_stages |= vk::ShaderStageFlagBits::eFragment;
408 }
409 } else {
410 push_constant_stages = vk::ShaderStageFlagBits::eVertex | vk::ShaderStageFlagBits::eFragment;
411 if (config.geometry_shader != INVALID_SHADER) {
412 push_constant_stages |= vk::ShaderStageFlagBits::eGeometry;
413 }
414 if (config.tess_control_shader != INVALID_SHADER) {
415 push_constant_stages |= vk::ShaderStageFlagBits::eTessellationControl;
416 }
417 if (config.tess_eval_shader != INVALID_SHADER) {
418 push_constant_stages |= vk::ShaderStageFlagBits::eTessellationEvaluation;
419 }
420 }
421
422 if (config.push_constant_size > 0) {
423 vk::PushConstantRange range;
424 range.stageFlags = push_constant_stages;
425 range.offset = 0;
426 range.size = static_cast<uint32_t>(config.push_constant_size);
427 vk_config.push_constant_ranges.push_back(range);
428 }
429
430 vk_config.color_attachment_formats = color_formats;
431 vk_config.depth_attachment_format = depth_format;
432
433 vk_config.dynamic_states = {
434 vk::DynamicState::eViewport,
435 vk::DynamicState::eScissor
436 };
437
438 auto pipeline = std::make_shared<Core::VKGraphicsPipeline>();
439 if (!pipeline->create(m_shader_foundry->get_device(), vk_config)) {
441 "Failed to create VKGraphicsPipeline for dynamic rendering");
442
443 for (auto layout : layouts) {
444 m_shader_foundry->get_device().destroyDescriptorSetLayout(layout);
445 }
447 }
448
449 auto pipeline_id = m_next_pipeline_id.fetch_add(1);
450 PipelineState state;
451 state.shader_ids = { config.vertex_shader, config.fragment_shader };
452 state.pipeline = pipeline;
453 state.layouts = layouts;
454 state.layout = pipeline->get_layout();
455 state.push_constant_stages = push_constant_stages;
456 m_pipelines[pipeline_id] = std::move(state);
457
459 "Dynamic rendering pipeline created (ID: {}, {} color attachments)",
460 pipeline_id, color_formats.size());
461
462 return pipeline_id;
463}
464
466{
467 auto it = m_pipelines.find(pipeline_id);
468 if (it == m_pipelines.end()) {
469 return;
470 }
471
472 auto device = m_shader_foundry->get_device();
473
474 if (it->second.pipeline) {
475 it->second.pipeline->cleanup(device);
476 }
477
478 if (it->second.layout) {
479 device.destroyPipelineLayout(it->second.layout);
480 }
481
482 for (auto layout : it->second.layouts) {
483 if (layout) {
484 device.destroyDescriptorSetLayout(layout);
485 }
486 }
487
488 m_pipelines.erase(it);
489
491 "Destroyed graphics pipeline (ID: {})", pipeline_id);
492}
493
495{
496 auto device = m_shader_foundry->get_device();
497
498 for (auto& [id, state] : m_pipelines) {
499 if (state.pipeline) {
500 state.pipeline->cleanup(device);
501 }
502
503 for (auto layout : state.layouts) {
504 if (layout) {
505 device.destroyDescriptorSetLayout(layout);
506 }
507 }
508 }
509 m_pipelines.clear();
510
512 "Cleaned up all graphics pipelines");
513}
514
515//==============================================================================
516// Dynamic Rendering
517//==============================================================================
518
520 CommandBufferID cmd_id,
521 const std::shared_ptr<Core::Window>& window,
522 vk::Image swapchain_image,
523 const std::array<float, 4>& clear_color,
524 vk::ImageView depth_image_view)
525{
526 auto cmd = m_shader_foundry->get_command_buffer(cmd_id);
527 if (!cmd) {
529 "Invalid command buffer ID: {}", cmd_id);
530 return;
531 }
532
533 if (!window) {
535 "Cannot begin rendering for null window");
536 return;
537 }
538
539 if (!swapchain_image) {
541 "Cannot begin rendering with null swapchain image");
542 return;
543 }
544
545 auto it = m_window_associations.find(window);
546 if (it == m_window_associations.end()) {
548 "Window '{}' not registered for rendering. "
549 "Call register_window_for_rendering() first.",
550 window->get_create_info().title);
551 m_window_associations.emplace(window, WindowRenderAssociation { .window = window, .swapchain_image = swapchain_image });
552 } else {
553 it->second.swapchain_image = swapchain_image;
554 }
555
556 uint32_t width = 0, height = 0;
557 m_display_service->get_swapchain_extent(window, width, height);
558
559 if (width == 0 || height == 0) {
561 "Invalid swapchain extent for window '{}': {}x{}",
562 window->get_create_info().title, width, height);
563 return;
564 }
565
566 vk::ImageView image_view = get_current_image_view(window);
567 if (!image_view) {
569 "Failed to get image view for window '{}'",
570 window->get_create_info().title);
571 return;
572 }
573
574 vk::ImageMemoryBarrier pre_barrier {};
575 pre_barrier.oldLayout = vk::ImageLayout::eUndefined;
576 pre_barrier.newLayout = vk::ImageLayout::eColorAttachmentOptimal;
577 pre_barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
578 pre_barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
579 pre_barrier.image = swapchain_image;
580 pre_barrier.subresourceRange.aspectMask = vk::ImageAspectFlagBits::eColor;
581 pre_barrier.subresourceRange.baseMipLevel = 0;
582 pre_barrier.subresourceRange.levelCount = 1;
583 pre_barrier.subresourceRange.baseArrayLayer = 0;
584 pre_barrier.subresourceRange.layerCount = 1;
585 pre_barrier.srcAccessMask = vk::AccessFlagBits::eNone;
586 pre_barrier.dstAccessMask = vk::AccessFlagBits::eColorAttachmentWrite;
587
588 cmd.pipelineBarrier(
589 vk::PipelineStageFlagBits::eTopOfPipe,
590 vk::PipelineStageFlagBits::eColorAttachmentOutput,
591 vk::DependencyFlags {},
592 0, nullptr,
593 0, nullptr,
594 1, &pre_barrier);
595
596 vk::RenderingAttachmentInfo color_attachment {};
597 color_attachment.sType = vk::StructureType::eRenderingAttachmentInfo;
598 color_attachment.pNext = nullptr;
599 color_attachment.imageView = image_view;
600 color_attachment.imageLayout = vk::ImageLayout::eColorAttachmentOptimal;
601 color_attachment.resolveMode = vk::ResolveModeFlagBits::eNone;
602 color_attachment.resolveImageView = nullptr;
603 color_attachment.resolveImageLayout = vk::ImageLayout::eUndefined;
604 color_attachment.loadOp = vk::AttachmentLoadOp::eClear;
605 color_attachment.storeOp = vk::AttachmentStoreOp::eStore;
606
607 if (clear_color != default_color) {
608 color_attachment.clearValue.color = vk::ClearColorValue(clear_color);
609 } else {
610 color_attachment.clearValue.color = vk::ClearColorValue(window->get_create_info().clear_color);
611 }
612
613 vk::RenderingAttachmentInfo depth_attachment {};
614 if (depth_image_view) {
615 depth_attachment.sType = vk::StructureType::eRenderingAttachmentInfo;
616 depth_attachment.pNext = nullptr;
617 depth_attachment.imageView = depth_image_view;
618 depth_attachment.imageLayout = vk::ImageLayout::eDepthStencilAttachmentOptimal;
619 depth_attachment.resolveMode = vk::ResolveModeFlagBits::eNone;
620 depth_attachment.resolveImageView = nullptr;
621 depth_attachment.resolveImageLayout = vk::ImageLayout::eUndefined;
622 depth_attachment.loadOp = vk::AttachmentLoadOp::eClear;
623 depth_attachment.storeOp = vk::AttachmentStoreOp::eDontCare;
624 depth_attachment.clearValue.depthStencil = vk::ClearDepthStencilValue { 1.0F, 0 };
625 }
626
627 vk::RenderingInfo rendering_info {};
628 rendering_info.sType = vk::StructureType::eRenderingInfo;
629 rendering_info.pNext = nullptr;
630 rendering_info.flags = vk::RenderingFlagBits::eContentsSecondaryCommandBuffers;
631 rendering_info.renderArea.offset = vk::Offset2D { 0, 0 };
632 rendering_info.renderArea.extent = vk::Extent2D { width, height };
633 rendering_info.layerCount = 1;
634 rendering_info.colorAttachmentCount = 1;
635 rendering_info.pColorAttachments = &color_attachment;
636 rendering_info.pDepthAttachment = depth_image_view ? &depth_attachment : nullptr;
637 rendering_info.pStencilAttachment = nullptr;
638
639 cmd.beginRendering(rendering_info);
640
642 "Began dynamic rendering for window '{}' ({}x{}, depth: {})",
643 window->get_create_info().title, width, height,
644 depth_image_view ? "yes" : "no");
645}
646
648 CommandBufferID cmd_id,
649 const std::shared_ptr<Core::Window>& window)
650{
651 auto cmd = m_shader_foundry->get_command_buffer(cmd_id);
652 if (!cmd) {
654 "Invalid command buffer ID: {}", cmd_id);
655 return;
656 }
657
658 cmd.endRendering();
659
660 auto it = m_window_associations.find(window);
661 if (it == m_window_associations.end() || !it->second.swapchain_image) {
663 "No swapchain image tracked for window '{}'",
664 window->get_create_info().title);
665 return;
666 }
667
668 vk::ImageMemoryBarrier post_barrier {};
669 post_barrier.oldLayout = vk::ImageLayout::eColorAttachmentOptimal;
670 post_barrier.newLayout = vk::ImageLayout::ePresentSrcKHR;
671 post_barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
672 post_barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
673 post_barrier.image = it->second.swapchain_image;
674 post_barrier.subresourceRange.aspectMask = vk::ImageAspectFlagBits::eColor;
675 post_barrier.subresourceRange.baseMipLevel = 0;
676 post_barrier.subresourceRange.levelCount = 1;
677 post_barrier.subresourceRange.baseArrayLayer = 0;
678 post_barrier.subresourceRange.layerCount = 1;
679 post_barrier.srcAccessMask = vk::AccessFlagBits::eColorAttachmentWrite;
680 post_barrier.dstAccessMask = vk::AccessFlagBits::eNone;
681
682 cmd.pipelineBarrier(
683 vk::PipelineStageFlagBits::eColorAttachmentOutput,
684 vk::PipelineStageFlagBits::eBottomOfPipe,
685 vk::DependencyFlags {},
686 0, nullptr,
687 0, nullptr,
688 1, &post_barrier);
689
690 it->second.swapchain_image = nullptr;
691
693 "Ended dynamic rendering for window '{}'",
694 window->get_create_info().title);
695}
696
697//==============================================================================
698// Command Recording
699//==============================================================================
700
702{
703 auto pipeline_it = m_pipelines.find(pipeline_id);
704 if (pipeline_it == m_pipelines.end()) {
706 "Invalid pipeline ID: {}", pipeline_id);
707 return;
708 }
709
710 auto cmd = m_shader_foundry->get_command_buffer(cmd_id);
711 if (!cmd) {
713 "Invalid command buffer ID: {}", cmd_id);
714 return;
715 }
716
717 pipeline_it->second.pipeline->bind(cmd);
718}
719
721 CommandBufferID cmd_id,
722 const std::vector<std::shared_ptr<Buffers::VKBuffer>>& buffers,
723 uint32_t first_binding)
724{
725 auto cmd = m_shader_foundry->get_command_buffer(cmd_id);
726 if (!cmd) {
728 "Invalid command buffer ID: {}", cmd_id);
729 return;
730 }
731
732 std::vector<vk::Buffer> vk_buffers;
733 std::vector<vk::DeviceSize> offsets(buffers.size(), 0);
734
735 vk_buffers.reserve(buffers.size());
736 for (const auto& buf : buffers) {
737 vk_buffers.push_back(buf->get_buffer());
738
739 /* void* mapped = buf->get_mapped_ptr();
740 if (mapped) {
741 float* data = reinterpret_cast<float*>(mapped);
742 MF_PRINT(Journal::Component::Portal, Journal::Context::Rendering,
743 "BIND_VERTEX: All vertex data:");
744 for (int v = 0; v < 3; ++v) {
745 int offset = v * 6; // 24 bytes / 4 bytes per float = 6 floats per vertex
746 MF_PRINT(Journal::Component::Portal, Journal::Context::Rendering,
747 " Vertex {}: pos=({}, {}, {}), color=({}, {}, {})",
748 v,
749 data[offset], data[offset + 1], data[offset + 2],
750 data[offset + 3], data[offset + 4], data[offset + 5]);
751 }
752 } else {
753 MF_RT_ERROR(Journal::Component::Portal, Journal::Context::Rendering,
754 "BIND_VERTEX: Buffer not host-mapped!");
755 } */
756 }
757
758 cmd.bindVertexBuffers(first_binding, vk_buffers, offsets);
759}
760
762 CommandBufferID cmd_id,
763 const std::shared_ptr<Buffers::VKBuffer>& buffer,
764 vk::IndexType index_type)
765{
766 auto cmd = m_shader_foundry->get_command_buffer(cmd_id);
767 if (!cmd) {
769 "Invalid command buffer ID: {}", cmd_id);
770 return;
771 }
772
773 cmd.bindIndexBuffer(buffer->get_buffer(), 0, index_type);
774}
775
777 CommandBufferID cmd_id,
778 RenderPipelineID pipeline_id,
779 const std::vector<DescriptorSetID>& descriptor_sets)
780{
781 auto pipeline_it = m_pipelines.find(pipeline_id);
782 if (pipeline_it == m_pipelines.end()) {
784 "Invalid pipeline ID: {}", pipeline_id);
785 return;
786 }
787
788 auto cmd = m_shader_foundry->get_command_buffer(cmd_id);
789 if (!cmd) {
791 "Invalid command buffer ID: {}", cmd_id);
792 return;
793 }
794
795 std::vector<vk::DescriptorSet> vk_sets;
796 vk_sets.reserve(descriptor_sets.size());
797 for (auto ds_id : descriptor_sets) {
798 vk_sets.push_back(m_shader_foundry->get_descriptor_set(ds_id));
799 }
800
801 cmd.bindDescriptorSets(
802 vk::PipelineBindPoint::eGraphics,
803 pipeline_it->second.layout,
804 0,
805 vk_sets,
806 nullptr);
807}
808
810 CommandBufferID cmd_id,
811 RenderPipelineID pipeline_id,
812 const void* data,
813 size_t size)
814{
815 auto pipeline_it = m_pipelines.find(pipeline_id);
816 if (pipeline_it == m_pipelines.end()) {
818 "Invalid pipeline ID: {}", pipeline_id);
819 return;
820 }
821
822 auto cmd = m_shader_foundry->get_command_buffer(cmd_id);
823 if (!cmd) {
825 "Invalid command buffer ID: {}", cmd_id);
826 return;
827 }
828
829 cmd.pushConstants(
830 pipeline_it->second.layout,
831 pipeline_it->second.push_constant_stages,
832 0,
833 static_cast<uint32_t>(size),
834 data);
835}
836
838 CommandBufferID cmd_id,
839 uint32_t vertex_count,
840 uint32_t instance_count,
841 uint32_t first_vertex,
842 uint32_t first_instance)
843{
844 auto cmd = m_shader_foundry->get_command_buffer(cmd_id);
845 if (!cmd) {
847 "Invalid command buffer ID: {}", cmd_id);
848 return;
849 }
850
851 cmd.draw(vertex_count, instance_count, first_vertex, first_instance);
852}
853
855 CommandBufferID cmd_id,
856 uint32_t index_count,
857 uint32_t instance_count,
858 uint32_t first_index,
859 int32_t vertex_offset,
860 uint32_t first_instance)
861{
862 auto cmd = m_shader_foundry->get_command_buffer(cmd_id);
863 if (!cmd) {
864 return;
865 }
866
867 cmd.drawIndexed(index_count, instance_count, first_index,
868 vertex_offset, first_instance);
869}
870
872 CommandBufferID cmd_id,
873 uint32_t group_count_x,
874 uint32_t group_count_y,
875 uint32_t group_count_z)
876{
877 auto cmd = m_shader_foundry->get_command_buffer(cmd_id);
878 if (!cmd) {
880 "Invalid command buffer ID: {}", cmd_id);
881 return;
882 }
883
884 cmd.drawMeshTasksEXT(group_count_x, group_count_y, group_count_z);
885}
886
888 CommandBufferID cmd_id,
889 const std::shared_ptr<Buffers::VKBuffer>& buffer,
890 vk::DeviceSize offset,
891 uint32_t draw_count,
892 uint32_t stride)
893{
894 auto cmd = m_shader_foundry->get_command_buffer(cmd_id);
895 if (!cmd || !buffer)
896 return;
897
898 cmd.drawMeshTasksIndirectEXT(buffer->get_buffer(), offset, draw_count, stride);
899}
900
901//==========================================================================
902// Window Rendering Registration
903//==========================================================================
904
905void RenderFlow::register_window_for_rendering(const std::shared_ptr<Core::Window>& window)
906{
907 if (!window) {
909 "Cannot register null window");
910 return;
911 }
912
913 if (!window->is_graphics_registered()) {
915 "Window '{}' not registered with graphics backend yet.",
916 window->get_create_info().title);
917 }
918
919 if (!m_window_associations.contains(window)) {
920 WindowRenderAssociation association;
921 association.window = window;
922 m_window_associations[window] = std::move(association);
923
925 "Registered window '{}' for dynamic rendering",
926 window->get_create_info().title);
927 }
928}
929
930void RenderFlow::unregister_window(const std::shared_ptr<Core::Window>& window)
931{
932 if (!window) {
933 return;
934 }
935
936 auto it = m_window_associations.find(window);
937
938 if (it != m_window_associations.end()) {
939 m_window_associations.erase(it);
940
942 "Unregistered window '{}' from rendering",
943 window->get_create_info().title);
944 }
945}
946
947bool RenderFlow::is_window_registered(const std::shared_ptr<Core::Window>& window) const
948{
949 return window && m_window_associations.contains(window);
950}
951
952std::vector<std::shared_ptr<Core::Window>> RenderFlow::get_registered_windows() const
953{
954 std::vector<std::shared_ptr<Core::Window>> windows;
955 windows.reserve(m_window_associations.size());
956
957 for (const auto& [key, association] : m_window_associations) {
958 if (auto window = association.window.lock()) {
959 windows.push_back(window);
960 }
961 }
962
963 return windows;
964}
965
966vk::ImageView RenderFlow::get_current_image_view(const std::shared_ptr<Core::Window>& window)
967{
968 auto view_ptr = m_display_service->get_current_image_view(window);
969 if (!view_ptr) {
970 return nullptr;
971 }
972 return *static_cast<vk::ImageView*>(view_ptr);
973}
974
975//==============================================================================
976// Convenience Methods
977//==============================================================================
978
979std::vector<DescriptorSetID> RenderFlow::allocate_pipeline_descriptors(
980 RenderPipelineID pipeline_id)
981{
982 auto pipeline_it = m_pipelines.find(pipeline_id);
983 if (pipeline_it == m_pipelines.end()) {
985 "Invalid pipeline ID: {}", pipeline_id);
986 return {};
987 }
988
989 std::vector<DescriptorSetID> descriptor_set_ids;
990 for (const auto& layout : pipeline_it->second.layouts) {
991 auto ds_id = m_shader_foundry->allocate_descriptor_set(layout);
992 if (ds_id == INVALID_DESCRIPTOR_SET) {
994 "Failed to allocate descriptor set for pipeline {}", pipeline_id);
995 return {};
996 }
997 descriptor_set_ids.push_back(ds_id);
998 }
999
1001 "Allocated {} descriptor sets for pipeline {}",
1002 descriptor_set_ids.size(), pipeline_id);
1003
1004 return descriptor_set_ids;
1005}
1006
1007} // namespace MayaFlux::Portal::Graphics
#define MF_INFO(comp, ctx,...)
#define MF_ERROR(comp, ctx,...)
#define MF_RT_ERROR(comp, ctx,...)
#define MF_TRACE(comp, ctx,...)
#define MF_WARN(comp, ctx,...)
#define MF_DEBUG(comp, ctx,...)
void bind_pipeline(CommandBufferID cmd_id, RenderPipelineID pipeline)
Bind graphics pipeline.
void register_window_for_rendering(const std::shared_ptr< Core::Window > &window)
Register a window for dynamic rendering.
void push_constants(CommandBufferID cmd_id, RenderPipelineID pipeline, const void *data, size_t size)
Push constants.
std::unordered_map< std::shared_ptr< Core::Window >, WindowRenderAssociation > m_window_associations
void begin_rendering(CommandBufferID cmd_id, const std::shared_ptr< Core::Window > &window, vk::Image swapchain_image, const std::array< float, 4 > &clear_color=default_color, vk::ImageView depth_image_view=nullptr)
Begin dynamic rendering to a window.
vk::ImageView get_current_image_view(const std::shared_ptr< Core::Window > &window)
Get current image view for window.
std::vector< DescriptorSetID > allocate_pipeline_descriptors(RenderPipelineID pipeline)
Allocate descriptor sets for pipeline.
void destroy_pipeline(RenderPipelineID pipeline_id)
Destroy a graphics pipeline.
void bind_vertex_buffers(CommandBufferID cmd_id, const std::vector< std::shared_ptr< Buffers::VKBuffer > > &buffers, uint32_t first_binding=0)
Bind vertex buffers.
std::vector< std::shared_ptr< Core::Window > > get_registered_windows() const
Get all registered windows.
void end_rendering(CommandBufferID cmd_id, const std::shared_ptr< Core::Window > &window)
End dynamic rendering.
void draw_indexed(CommandBufferID cmd_id, uint32_t index_count, uint32_t instance_count=1, uint32_t first_index=0, int32_t vertex_offset=0, uint32_t first_instance=0)
Indexed draw command.
std::unordered_map< RenderPipelineID, PipelineState > m_pipelines
void bind_index_buffer(CommandBufferID cmd_id, const std::shared_ptr< Buffers::VKBuffer > &buffer, vk::IndexType index_type=vk::IndexType::eUint32)
Bind index buffer.
void bind_descriptor_sets(CommandBufferID cmd_id, RenderPipelineID pipeline, const std::vector< DescriptorSetID > &descriptor_sets)
Bind descriptor sets.
void draw_mesh_tasks(CommandBufferID cmd_id, uint32_t group_count_x, uint32_t group_count_y=1, uint32_t group_count_z=1)
Draw mesh tasks (mesh shading pipeline only)
bool is_window_registered(const std::shared_ptr< Core::Window > &window) const
Check if a window is registered for rendering.
void draw(CommandBufferID cmd_id, uint32_t vertex_count, uint32_t instance_count=1, uint32_t first_vertex=0, uint32_t first_instance=0)
Draw command.
void draw_mesh_tasks_indirect(CommandBufferID cmd_id, const std::shared_ptr< Buffers::VKBuffer > &buffer, vk::DeviceSize offset=0, uint32_t draw_count=1, uint32_t stride=sizeof(VkDrawMeshTasksIndirectCommandEXT))
Draw mesh tasks indirect.
void unregister_window(const std::shared_ptr< Core::Window > &window)
Unregister a window from rendering.
Registry::Service::DisplayService * m_display_service
std::atomic< uint64_t > m_next_pipeline_id
RenderPipelineID create_pipeline(const RenderPipelineConfig &config, const std::vector< vk::Format > &color_formats, vk::Format depth_format=vk::Format::eUndefined)
Create graphics pipeline for dynamic rendering (no render pass object)
vk::DescriptorSet get_descriptor_set(DescriptorSetID descriptor_set_id)
Get Vulkan descriptor set handle from DescriptorSetID.
std::shared_ptr< Core::VKShaderModule > get_vk_shader_module(ShaderID shader_id)
bool is_initialized() const
Check if compiler is initialized.
vk::CommandBuffer get_command_buffer(CommandBufferID cmd_id)
Get Vulkan command buffer handle from CommandBufferID.
DescriptorSetID allocate_descriptor_set(vk::DescriptorSetLayout layout)
Allocate descriptor set for a pipeline.
static std::pair< std::vector< Core::VertexBinding >, std::vector< Core::VertexAttribute > > translate_layout(const Kakshya::VertexLayout &layout, uint32_t binding_index=0)
Translate a semantic vertex layout to Vulkan binding/attribute descriptions.
Interface * get_service()
Query for a backend service.
static BackendRegistry & instance()
Get the global registry instance.
@ Rendering
GPU rendering operations (graphics pipeline, frame rendering)
@ Portal
High-level user-facing API layer.
PolygonMode
Rasterization polygon mode.
constexpr RenderPipelineID INVALID_RENDER_PIPELINE
const std::array< float, 4 > default_color
constexpr ShaderID INVALID_SHADER
BlendOp
Blending operation.
PrimitiveTopology
Vertex assembly primitive topology.
CompareOp
Depth/stencil comparison operation.
constexpr DescriptorSetID INVALID_DESCRIPTOR_SET
std::vector< ColorBlendAttachment > color_blend_attachments
std::vector< vk::Format > color_attachment_formats
std::shared_ptr< VKShaderModule > task_shader
std::shared_ptr< VKShaderModule > fragment_shader
std::shared_ptr< VKShaderModule > mesh_shader
std::vector< vk::DynamicState > dynamic_states
std::vector< vk::PushConstantRange > push_constant_ranges
std::shared_ptr< VKShaderModule > vertex_shader
std::vector< vk::DescriptorSetLayout > descriptor_set_layouts
std::vector< VertexBinding > vertex_bindings
std::vector< VertexAttribute > vertex_attributes
std::shared_ptr< VKShaderModule > geometry_shader
std::shared_ptr< VKShaderModule > tess_evaluation_shader
std::shared_ptr< VKShaderModule > tess_control_shader
Configuration for creating a graphics pipeline.
std::vector< vk::DescriptorSetLayout > layouts
std::shared_ptr< Core::VKGraphicsPipeline > pipeline
std::vector< std::vector< DescriptorBindingInfo > > descriptor_sets
std::vector< Core::VertexAttribute > vertex_attributes
std::vector< Core::VertexBinding > vertex_bindings
std::optional< Kakshya::VertexLayout > semantic_vertex_layout
std::vector< BlendAttachmentConfig > blend_attachments
Complete render pipeline configuration.
std::function< void *(const std::shared_ptr< void > &)> get_current_image_view
Get current swapchain image view for rendering.
std::function< void(const std::shared_ptr< void > &, uint32_t &, uint32_t &)> get_swapchain_extent
Get swapchain extent for a window.
Backend display and presentation service interface.