From 3b2347093ad664873cd0df7c18953b6f66b305a5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dar=C3=ADo=20Rodr=C3=ADguez=20Mart=C3=ADnez?= Date: Fri, 6 Nov 2026 11:33:51 +0100 Subject: [PATCH 01/11] reflected audio --- .../src/toast/audio/nodes/audio_emitter.hpp | 14 ++++++-- .../toast/audio/nodes/audio_emitter_3d.hpp | 1 + .../toast/audio/nodes/audio_emitter_base.hpp | 19 +++++++++-- engine/src/toast/renderer/vulkan_renderer.hpp | 29 +++++++++------- .../toast/renderer/vulkan_renderer_detail.hpp | 8 +++++ .../toast/renderer/vulkan_renderer_record.cpp | 5 ++- .../toast/renderer/vulkan_renderer_scene.cpp | 12 +++---- .../toast/renderer/vulkan_renderer_thread.cpp | 34 +++++++++---------- 8 files changed, 77 insertions(+), 45 deletions(-) diff --git a/engine/src/toast/audio/nodes/audio_emitter.hpp b/engine/src/toast/audio/nodes/audio_emitter.hpp index 4e878a225..91e837b11 100644 --- a/engine/src/toast/audio/nodes/audio_emitter.hpp +++ b/engine/src/toast/audio/nodes/audio_emitter.hpp @@ -16,22 +16,30 @@ namespace toast { class TOAST_API [[ToastNode, Color("Beige"), Icon("AudioStreamPlayer")]] AudioEmitter : public Node { public: - [[Button]] + [[Reflect, Button]] void play(); ///< Fires the event - [[Button]] + [[Reflect, Button]] void stop(); ///< Stops the event using the @c allowFadeout() - + [[Reflect]] void pause(bool value); ///< Pauses and resumes in a location + [[Reflect]] void setParameter(std::string_view name, float value); ///< Changes a parameter by name + [[Reflect]] void setParameter(std::string_view, bool value); ///< Changes a parameter by name + [[Reflect]] auto isPlaying() -> bool; ///< @returns true if it's currently playing void event(std::string_view path); ///< Sets the event by URI + [[Reflect]] void event(toast::UID uid); ///< Sets the event by UID + [[Reflect]] void playOnEnable(bool value); ///< If true, will play every time the node is enabled + [[Reflect]] void volume(float value); ///< @param value 0.0 - 1.0 + [[Reflect]] void pitch(float value); ///< @param value 0.5 - 2.0 + [[Reflect]] void allowFadeout(bool value); ///< False forces the event to bypass envelope settings /// signals::Signal audio_started; diff --git a/engine/src/toast/audio/nodes/audio_emitter_3d.hpp b/engine/src/toast/audio/nodes/audio_emitter_3d.hpp index a2343ba20..e512077f3 100644 --- a/engine/src/toast/audio/nodes/audio_emitter_3d.hpp +++ b/engine/src/toast/audio/nodes/audio_emitter_3d.hpp @@ -17,6 +17,7 @@ namespace toast { */ class TOAST_API [[ToastNode]] AudioEmitter3D : public AudioEmitterBase { protected: + [[Reflect]] auto emitterPosition(const glm::vec3& listener) -> glm::vec3 override; }; diff --git a/engine/src/toast/audio/nodes/audio_emitter_base.hpp b/engine/src/toast/audio/nodes/audio_emitter_base.hpp index 8942fade6..53dfafbc2 100644 --- a/engine/src/toast/audio/nodes/audio_emitter_base.hpp +++ b/engine/src/toast/audio/nodes/audio_emitter_base.hpp @@ -22,29 +22,42 @@ namespace toast { */ class TOAST_API [[ToastNode, Hidden, Color("Beige"), Icon("AudioStreamPlayer")]] AudioEmitterBase : public Node3D { public: - [[Button]] + [[Reflect, Button]] void play(); - [[Button]] + [[Reflect, Button]] void stop(); + [[Reflect]] void pause(bool value); + [[Reflect]] void setParameter(std::string_view name, float value) const; + [[Reflect]] void setParameter(std::string_view name, bool value) const; - [[nodiscard]] + [[nodiscard, Reflect]] auto isPlaying() const -> bool; void event(std::string_view path); + [[Reflect]] void event(toast::UID uid); + [[Reflect]] void playOnEnable(bool value); + [[Reflect]] void volume(float value); + [[Reflect]] void pitch(float value); + [[Reflect]] void allowFadeout(bool value); + [[Reflect]] void dopplerScale(float value); + [[Reflect]] void calculateVelocity(bool value); + [[Reflect]] void overrideAttenuation(bool value); + [[Reflect]] void minDistance(float value); + [[Reflect]] void maxDistance(float value); signals::Signal audio_started; diff --git a/engine/src/toast/renderer/vulkan_renderer.hpp b/engine/src/toast/renderer/vulkan_renderer.hpp index 9f31dc39b..a4c358dba 100644 --- a/engine/src/toast/renderer/vulkan_renderer.hpp +++ b/engine/src/toast/renderer/vulkan_renderer.hpp @@ -1029,7 +1029,6 @@ class VulkanRenderer { return m_reflection_probe_pass; } - [[nodiscard]] void setActiveCamera(toast::Camera* camera); void forgetCamera(const toast::Camera* camera); @@ -1249,7 +1248,8 @@ class VulkanRenderer { std::thread m_render_thread; std::array m_render_frames; - std::atomic m_write_index = 0; + /// Main thread only + uint32_t m_write_index = 0; std::mutex m_queue_mutex; @@ -1500,7 +1500,7 @@ class VulkanRenderer { SceneColorResources m_voxel_noisy_specular; /// The voxel lighting writes the parity one and reads the other std::array m_voxel_reservoirs; - /// The lighting scope's reservoirs when the spatial pass then writes m_voxel_reservoirs + /// The lighting scope reservoirs when the spatial pass then writes m_voxel_reservoirs SceneColorResources m_voxel_candidate_reservoirs; uint32_t m_voxel_reservoir_parity = 0; bool m_voxel_reservoir_written = false; @@ -1803,19 +1803,23 @@ class VulkanRenderer { std::unique_ptr m_skinned_blas_pool; - std::atomic m_last_drawn_sequence {0}; - std::atomic m_out_of_order_frames {0}; - std::atomic m_dropped_frames {0}; + /// Render thread only + uint64_t m_last_drawn_sequence = 0; - std::atomic m_skipped_builds {0}; + /// Stats grouped by writer thread on separate cache lines to avoid false sharing + /// Main thread writes + alignas(64) std::atomic m_skipped_builds {0}; + std::atomic m_perf_ticks {0}; + std::atomic m_perf_frames_built {0}; + std::atomic m_perf_slot_wait_ns {0}; + std::atomic m_perf_build_ns {0}; + /// Render thread writes + alignas(64) std::atomic m_out_of_order_frames {0}; + std::atomic m_dropped_frames {0}; std::atomic m_frame_time_avg_ms {0.0f}; std::atomic m_frame_time_min_ms {0.0f}; std::atomic m_frame_time_max_ms {0.0f}; - - std::atomic m_perf_ticks {0}; - std::atomic m_perf_frames_built {0}; - std::atomic m_perf_slot_wait_ns {0}; std::atomic m_perf_draws {0}; std::atomic m_perf_repeated_draws {0}; std::atomic m_perf_draw_work_ns {0}; @@ -1827,9 +1831,8 @@ class VulkanRenderer { std::atomic m_perf_present_ns {0}; std::atomic m_perf_frame_wait_ns {0}; std::atomic m_perf_pacing_ns {0}; - std::atomic m_perf_build_ns {0}; - std::atomic_bool m_cull_debug_draw {false}; + alignas(64) std::atomic_bool m_cull_debug_draw {false}; std::atomic_bool m_cull_freeze {false}; glm::mat4 m_frozen_cull_view_projection {1.0f}; diff --git a/engine/src/toast/renderer/vulkan_renderer_detail.hpp b/engine/src/toast/renderer/vulkan_renderer_detail.hpp index 8e6d55411..f4a519fff 100644 --- a/engine/src/toast/renderer/vulkan_renderer_detail.hpp +++ b/engine/src/toast/renderer/vulkan_renderer_detail.hpp @@ -7,11 +7,19 @@ #include "toast/renderer/render_frame.hpp" #include "toast/renderer/resources/vulkan_mesh.hpp" +#include #include +#include #include namespace renderer::detail { +/// Single writer thread only so the add skips the locked read modify write +template +inline void addSingleWriter(std::atomic& counter, std::type_identity_t value) noexcept { + counter.store(counter.load(std::memory_order_relaxed) + value, std::memory_order_relaxed); +} + inline auto packExtent(vk::Extent2D extent) -> uint64_t { return (static_cast(extent.width) << 32u) | static_cast(extent.height); } diff --git a/engine/src/toast/renderer/vulkan_renderer_record.cpp b/engine/src/toast/renderer/vulkan_renderer_record.cpp index 97593bce4..5f81b5e4d 100644 --- a/engine/src/toast/renderer/vulkan_renderer_record.cpp +++ b/engine/src/toast/renderer/vulkan_renderer_record.cpp @@ -1424,9 +1424,8 @@ auto VulkanRenderer::drawFrame(RenderFrame& frame_data) -> bool { auto phase_start = clock::now(); auto end_phase = [&phase_start](std::atomic& counter) { const auto now = clock::now(); - counter.fetch_add( - static_cast(std::chrono::duration_cast(now - phase_start).count()), - std::memory_order_relaxed + detail::addSingleWriter( + counter, static_cast(std::chrono::duration_cast(now - phase_start).count()) ); phase_start = now; }; diff --git a/engine/src/toast/renderer/vulkan_renderer_scene.cpp b/engine/src/toast/renderer/vulkan_renderer_scene.cpp index d1a8f7bb8..d9bce3645 100644 --- a/engine/src/toast/renderer/vulkan_renderer_scene.cpp +++ b/engine/src/toast/renderer/vulkan_renderer_scene.cpp @@ -366,21 +366,21 @@ void VulkanRenderer::tick(float time) noexcept { acquireFrameSlot(); } const bool got_slot = std::exchange(m_frame_slot, FrameSlot::none) == FrameSlot::held; - m_perf_ticks.fetch_add(1, std::memory_order_relaxed); + detail::addSingleWriter(m_perf_ticks, 1); if (!got_slot) { - m_skipped_builds.fetch_add(1, std::memory_order_relaxed); + detail::addSingleWriter(m_skipped_builds, 1); return; } - m_perf_frames_built.fetch_add(1, std::memory_order_relaxed); + detail::addSingleWriter(m_perf_frames_built, 1); const auto build_start = std::chrono::steady_clock::now(); const auto count_build = [this, build_start] { - m_perf_build_ns.fetch_add( + detail::addSingleWriter( + m_perf_build_ns, static_cast( std::chrono::duration_cast(std::chrono::steady_clock::now() - build_start).count() - ), - std::memory_order_relaxed + ) ); }; diff --git a/engine/src/toast/renderer/vulkan_renderer_thread.cpp b/engine/src/toast/renderer/vulkan_renderer_thread.cpp index 28312a4bd..4c10943df 100644 --- a/engine/src/toast/renderer/vulkan_renderer_thread.cpp +++ b/engine/src/toast/renderer/vulkan_renderer_thread.cpp @@ -165,9 +165,9 @@ void VulkanRenderer::mainRenderThread() try { } } } - m_perf_frame_wait_ns.fetch_add( - static_cast(std::chrono::duration_cast(clock::now() - frame_wait_start).count()), - std::memory_order_relaxed + detail::addSingleWriter( + m_perf_frame_wait_ns, + static_cast(std::chrono::duration_cast(clock::now() - frame_wait_start).count()) ); if (!m_running) { @@ -182,9 +182,9 @@ void VulkanRenderer::mainRenderThread() try { has_frame = true; consumed_queued_frame = true; - const uint64_t previous = m_last_drawn_sequence.exchange(frame_to_draw.sequence, std::memory_order_relaxed); + const uint64_t previous = std::exchange(m_last_drawn_sequence, frame_to_draw.sequence); if (frame_to_draw.sequence < previous) { - m_out_of_order_frames.fetch_add(1, std::memory_order_relaxed); + detail::addSingleWriter(m_out_of_order_frames, 1); TOAST_WARN( "VulkanRenderer", "Frame {} drawn after frame {} - render frames arrived out of order", @@ -192,7 +192,7 @@ void VulkanRenderer::mainRenderThread() try { previous ); } else if (previous != 0 && frame_to_draw.sequence > previous + 1) { - m_dropped_frames.fetch_add(static_cast(frame_to_draw.sequence - previous - 1), std::memory_order_relaxed); + detail::addSingleWriter(m_dropped_frames, static_cast(frame_to_draw.sequence - previous - 1)); } } else if (!has_frame) { continue; @@ -203,9 +203,9 @@ void VulkanRenderer::mainRenderThread() try { if (limit_hz > 0.0 && !clamp_to_simulation) { const auto pacing_start = clock::now(); std::this_thread::sleep_until(next_frame_deadline); - m_perf_pacing_ns.fetch_add( - static_cast(std::chrono::duration_cast(clock::now() - pacing_start).count()), - std::memory_order_relaxed + detail::addSingleWriter( + m_perf_pacing_ns, + static_cast(std::chrono::duration_cast(clock::now() - pacing_start).count()) ); const auto interval = std::chrono::duration_cast(std::chrono::duration(1.0 / limit_hz)); const auto now = clock::now(); @@ -245,13 +245,13 @@ void VulkanRenderer::mainRenderThread() try { const auto draw_start = clock::now(); // A pass with no free output image rendered nothing if (drawFrame(frame_to_draw)) { - m_perf_draw_work_ns.fetch_add( - static_cast(std::chrono::duration_cast(clock::now() - draw_start).count()), - std::memory_order_relaxed + detail::addSingleWriter( + m_perf_draw_work_ns, + static_cast(std::chrono::duration_cast(clock::now() - draw_start).count()) ); - m_perf_draws.fetch_add(1, std::memory_order_relaxed); + detail::addSingleWriter(m_perf_draws, 1); if (!consumed_queued_frame) { - m_perf_repeated_draws.fetch_add(1, std::memory_order_relaxed); + detail::addSingleWriter(m_perf_repeated_draws, 1); } { @@ -333,11 +333,11 @@ void VulkanRenderer::acquireFrameSlot() noexcept { using namespace std::chrono_literals; const auto slot_wait_start = std::chrono::steady_clock::now(); m_frame_slot = m_free_frames.try_acquire_for(50ms) ? FrameSlot::held : FrameSlot::missed; - m_perf_slot_wait_ns.fetch_add( + detail::addSingleWriter( + m_perf_slot_wait_ns, static_cast( std::chrono::duration_cast(std::chrono::steady_clock::now() - slot_wait_start).count() - ), - std::memory_order_relaxed + ) ); } From eeda31ea4cca98523bded6a04ac7df7822f55251 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dar=C3=ADo=20Rodr=C3=ADguez=20Mart=C3=ADnez?= Date: Fri, 6 Nov 2026 11:33:51 +0100 Subject: [PATCH 02/11] reflected audio --- .../src/toast/audio/nodes/audio_emitter.hpp | 14 ++++++-- .../toast/audio/nodes/audio_emitter_3d.hpp | 1 + .../toast/audio/nodes/audio_emitter_base.hpp | 19 +++++++++-- engine/src/toast/renderer/vulkan_renderer.hpp | 29 +++++++++------- .../toast/renderer/vulkan_renderer_detail.hpp | 8 +++++ .../toast/renderer/vulkan_renderer_record.cpp | 5 ++- .../toast/renderer/vulkan_renderer_scene.cpp | 12 +++---- .../toast/renderer/vulkan_renderer_thread.cpp | 34 +++++++++---------- 8 files changed, 77 insertions(+), 45 deletions(-) diff --git a/engine/src/toast/audio/nodes/audio_emitter.hpp b/engine/src/toast/audio/nodes/audio_emitter.hpp index 4e878a225..91e837b11 100644 --- a/engine/src/toast/audio/nodes/audio_emitter.hpp +++ b/engine/src/toast/audio/nodes/audio_emitter.hpp @@ -16,22 +16,30 @@ namespace toast { class TOAST_API [[ToastNode, Color("Beige"), Icon("AudioStreamPlayer")]] AudioEmitter : public Node { public: - [[Button]] + [[Reflect, Button]] void play(); ///< Fires the event - [[Button]] + [[Reflect, Button]] void stop(); ///< Stops the event using the @c allowFadeout() - + [[Reflect]] void pause(bool value); ///< Pauses and resumes in a location + [[Reflect]] void setParameter(std::string_view name, float value); ///< Changes a parameter by name + [[Reflect]] void setParameter(std::string_view, bool value); ///< Changes a parameter by name + [[Reflect]] auto isPlaying() -> bool; ///< @returns true if it's currently playing void event(std::string_view path); ///< Sets the event by URI + [[Reflect]] void event(toast::UID uid); ///< Sets the event by UID + [[Reflect]] void playOnEnable(bool value); ///< If true, will play every time the node is enabled + [[Reflect]] void volume(float value); ///< @param value 0.0 - 1.0 + [[Reflect]] void pitch(float value); ///< @param value 0.5 - 2.0 + [[Reflect]] void allowFadeout(bool value); ///< False forces the event to bypass envelope settings /// signals::Signal audio_started; diff --git a/engine/src/toast/audio/nodes/audio_emitter_3d.hpp b/engine/src/toast/audio/nodes/audio_emitter_3d.hpp index a2343ba20..e512077f3 100644 --- a/engine/src/toast/audio/nodes/audio_emitter_3d.hpp +++ b/engine/src/toast/audio/nodes/audio_emitter_3d.hpp @@ -17,6 +17,7 @@ namespace toast { */ class TOAST_API [[ToastNode]] AudioEmitter3D : public AudioEmitterBase { protected: + [[Reflect]] auto emitterPosition(const glm::vec3& listener) -> glm::vec3 override; }; diff --git a/engine/src/toast/audio/nodes/audio_emitter_base.hpp b/engine/src/toast/audio/nodes/audio_emitter_base.hpp index 8942fade6..53dfafbc2 100644 --- a/engine/src/toast/audio/nodes/audio_emitter_base.hpp +++ b/engine/src/toast/audio/nodes/audio_emitter_base.hpp @@ -22,29 +22,42 @@ namespace toast { */ class TOAST_API [[ToastNode, Hidden, Color("Beige"), Icon("AudioStreamPlayer")]] AudioEmitterBase : public Node3D { public: - [[Button]] + [[Reflect, Button]] void play(); - [[Button]] + [[Reflect, Button]] void stop(); + [[Reflect]] void pause(bool value); + [[Reflect]] void setParameter(std::string_view name, float value) const; + [[Reflect]] void setParameter(std::string_view name, bool value) const; - [[nodiscard]] + [[nodiscard, Reflect]] auto isPlaying() const -> bool; void event(std::string_view path); + [[Reflect]] void event(toast::UID uid); + [[Reflect]] void playOnEnable(bool value); + [[Reflect]] void volume(float value); + [[Reflect]] void pitch(float value); + [[Reflect]] void allowFadeout(bool value); + [[Reflect]] void dopplerScale(float value); + [[Reflect]] void calculateVelocity(bool value); + [[Reflect]] void overrideAttenuation(bool value); + [[Reflect]] void minDistance(float value); + [[Reflect]] void maxDistance(float value); signals::Signal audio_started; diff --git a/engine/src/toast/renderer/vulkan_renderer.hpp b/engine/src/toast/renderer/vulkan_renderer.hpp index 9f31dc39b..a4c358dba 100644 --- a/engine/src/toast/renderer/vulkan_renderer.hpp +++ b/engine/src/toast/renderer/vulkan_renderer.hpp @@ -1029,7 +1029,6 @@ class VulkanRenderer { return m_reflection_probe_pass; } - [[nodiscard]] void setActiveCamera(toast::Camera* camera); void forgetCamera(const toast::Camera* camera); @@ -1249,7 +1248,8 @@ class VulkanRenderer { std::thread m_render_thread; std::array m_render_frames; - std::atomic m_write_index = 0; + /// Main thread only + uint32_t m_write_index = 0; std::mutex m_queue_mutex; @@ -1500,7 +1500,7 @@ class VulkanRenderer { SceneColorResources m_voxel_noisy_specular; /// The voxel lighting writes the parity one and reads the other std::array m_voxel_reservoirs; - /// The lighting scope's reservoirs when the spatial pass then writes m_voxel_reservoirs + /// The lighting scope reservoirs when the spatial pass then writes m_voxel_reservoirs SceneColorResources m_voxel_candidate_reservoirs; uint32_t m_voxel_reservoir_parity = 0; bool m_voxel_reservoir_written = false; @@ -1803,19 +1803,23 @@ class VulkanRenderer { std::unique_ptr m_skinned_blas_pool; - std::atomic m_last_drawn_sequence {0}; - std::atomic m_out_of_order_frames {0}; - std::atomic m_dropped_frames {0}; + /// Render thread only + uint64_t m_last_drawn_sequence = 0; - std::atomic m_skipped_builds {0}; + /// Stats grouped by writer thread on separate cache lines to avoid false sharing + /// Main thread writes + alignas(64) std::atomic m_skipped_builds {0}; + std::atomic m_perf_ticks {0}; + std::atomic m_perf_frames_built {0}; + std::atomic m_perf_slot_wait_ns {0}; + std::atomic m_perf_build_ns {0}; + /// Render thread writes + alignas(64) std::atomic m_out_of_order_frames {0}; + std::atomic m_dropped_frames {0}; std::atomic m_frame_time_avg_ms {0.0f}; std::atomic m_frame_time_min_ms {0.0f}; std::atomic m_frame_time_max_ms {0.0f}; - - std::atomic m_perf_ticks {0}; - std::atomic m_perf_frames_built {0}; - std::atomic m_perf_slot_wait_ns {0}; std::atomic m_perf_draws {0}; std::atomic m_perf_repeated_draws {0}; std::atomic m_perf_draw_work_ns {0}; @@ -1827,9 +1831,8 @@ class VulkanRenderer { std::atomic m_perf_present_ns {0}; std::atomic m_perf_frame_wait_ns {0}; std::atomic m_perf_pacing_ns {0}; - std::atomic m_perf_build_ns {0}; - std::atomic_bool m_cull_debug_draw {false}; + alignas(64) std::atomic_bool m_cull_debug_draw {false}; std::atomic_bool m_cull_freeze {false}; glm::mat4 m_frozen_cull_view_projection {1.0f}; diff --git a/engine/src/toast/renderer/vulkan_renderer_detail.hpp b/engine/src/toast/renderer/vulkan_renderer_detail.hpp index 8e6d55411..f4a519fff 100644 --- a/engine/src/toast/renderer/vulkan_renderer_detail.hpp +++ b/engine/src/toast/renderer/vulkan_renderer_detail.hpp @@ -7,11 +7,19 @@ #include "toast/renderer/render_frame.hpp" #include "toast/renderer/resources/vulkan_mesh.hpp" +#include #include +#include #include namespace renderer::detail { +/// Single writer thread only so the add skips the locked read modify write +template +inline void addSingleWriter(std::atomic& counter, std::type_identity_t value) noexcept { + counter.store(counter.load(std::memory_order_relaxed) + value, std::memory_order_relaxed); +} + inline auto packExtent(vk::Extent2D extent) -> uint64_t { return (static_cast(extent.width) << 32u) | static_cast(extent.height); } diff --git a/engine/src/toast/renderer/vulkan_renderer_record.cpp b/engine/src/toast/renderer/vulkan_renderer_record.cpp index 97593bce4..5f81b5e4d 100644 --- a/engine/src/toast/renderer/vulkan_renderer_record.cpp +++ b/engine/src/toast/renderer/vulkan_renderer_record.cpp @@ -1424,9 +1424,8 @@ auto VulkanRenderer::drawFrame(RenderFrame& frame_data) -> bool { auto phase_start = clock::now(); auto end_phase = [&phase_start](std::atomic& counter) { const auto now = clock::now(); - counter.fetch_add( - static_cast(std::chrono::duration_cast(now - phase_start).count()), - std::memory_order_relaxed + detail::addSingleWriter( + counter, static_cast(std::chrono::duration_cast(now - phase_start).count()) ); phase_start = now; }; diff --git a/engine/src/toast/renderer/vulkan_renderer_scene.cpp b/engine/src/toast/renderer/vulkan_renderer_scene.cpp index d1a8f7bb8..d9bce3645 100644 --- a/engine/src/toast/renderer/vulkan_renderer_scene.cpp +++ b/engine/src/toast/renderer/vulkan_renderer_scene.cpp @@ -366,21 +366,21 @@ void VulkanRenderer::tick(float time) noexcept { acquireFrameSlot(); } const bool got_slot = std::exchange(m_frame_slot, FrameSlot::none) == FrameSlot::held; - m_perf_ticks.fetch_add(1, std::memory_order_relaxed); + detail::addSingleWriter(m_perf_ticks, 1); if (!got_slot) { - m_skipped_builds.fetch_add(1, std::memory_order_relaxed); + detail::addSingleWriter(m_skipped_builds, 1); return; } - m_perf_frames_built.fetch_add(1, std::memory_order_relaxed); + detail::addSingleWriter(m_perf_frames_built, 1); const auto build_start = std::chrono::steady_clock::now(); const auto count_build = [this, build_start] { - m_perf_build_ns.fetch_add( + detail::addSingleWriter( + m_perf_build_ns, static_cast( std::chrono::duration_cast(std::chrono::steady_clock::now() - build_start).count() - ), - std::memory_order_relaxed + ) ); }; diff --git a/engine/src/toast/renderer/vulkan_renderer_thread.cpp b/engine/src/toast/renderer/vulkan_renderer_thread.cpp index 28312a4bd..4c10943df 100644 --- a/engine/src/toast/renderer/vulkan_renderer_thread.cpp +++ b/engine/src/toast/renderer/vulkan_renderer_thread.cpp @@ -165,9 +165,9 @@ void VulkanRenderer::mainRenderThread() try { } } } - m_perf_frame_wait_ns.fetch_add( - static_cast(std::chrono::duration_cast(clock::now() - frame_wait_start).count()), - std::memory_order_relaxed + detail::addSingleWriter( + m_perf_frame_wait_ns, + static_cast(std::chrono::duration_cast(clock::now() - frame_wait_start).count()) ); if (!m_running) { @@ -182,9 +182,9 @@ void VulkanRenderer::mainRenderThread() try { has_frame = true; consumed_queued_frame = true; - const uint64_t previous = m_last_drawn_sequence.exchange(frame_to_draw.sequence, std::memory_order_relaxed); + const uint64_t previous = std::exchange(m_last_drawn_sequence, frame_to_draw.sequence); if (frame_to_draw.sequence < previous) { - m_out_of_order_frames.fetch_add(1, std::memory_order_relaxed); + detail::addSingleWriter(m_out_of_order_frames, 1); TOAST_WARN( "VulkanRenderer", "Frame {} drawn after frame {} - render frames arrived out of order", @@ -192,7 +192,7 @@ void VulkanRenderer::mainRenderThread() try { previous ); } else if (previous != 0 && frame_to_draw.sequence > previous + 1) { - m_dropped_frames.fetch_add(static_cast(frame_to_draw.sequence - previous - 1), std::memory_order_relaxed); + detail::addSingleWriter(m_dropped_frames, static_cast(frame_to_draw.sequence - previous - 1)); } } else if (!has_frame) { continue; @@ -203,9 +203,9 @@ void VulkanRenderer::mainRenderThread() try { if (limit_hz > 0.0 && !clamp_to_simulation) { const auto pacing_start = clock::now(); std::this_thread::sleep_until(next_frame_deadline); - m_perf_pacing_ns.fetch_add( - static_cast(std::chrono::duration_cast(clock::now() - pacing_start).count()), - std::memory_order_relaxed + detail::addSingleWriter( + m_perf_pacing_ns, + static_cast(std::chrono::duration_cast(clock::now() - pacing_start).count()) ); const auto interval = std::chrono::duration_cast(std::chrono::duration(1.0 / limit_hz)); const auto now = clock::now(); @@ -245,13 +245,13 @@ void VulkanRenderer::mainRenderThread() try { const auto draw_start = clock::now(); // A pass with no free output image rendered nothing if (drawFrame(frame_to_draw)) { - m_perf_draw_work_ns.fetch_add( - static_cast(std::chrono::duration_cast(clock::now() - draw_start).count()), - std::memory_order_relaxed + detail::addSingleWriter( + m_perf_draw_work_ns, + static_cast(std::chrono::duration_cast(clock::now() - draw_start).count()) ); - m_perf_draws.fetch_add(1, std::memory_order_relaxed); + detail::addSingleWriter(m_perf_draws, 1); if (!consumed_queued_frame) { - m_perf_repeated_draws.fetch_add(1, std::memory_order_relaxed); + detail::addSingleWriter(m_perf_repeated_draws, 1); } { @@ -333,11 +333,11 @@ void VulkanRenderer::acquireFrameSlot() noexcept { using namespace std::chrono_literals; const auto slot_wait_start = std::chrono::steady_clock::now(); m_frame_slot = m_free_frames.try_acquire_for(50ms) ? FrameSlot::held : FrameSlot::missed; - m_perf_slot_wait_ns.fetch_add( + detail::addSingleWriter( + m_perf_slot_wait_ns, static_cast( std::chrono::duration_cast(std::chrono::steady_clock::now() - slot_wait_start).count() - ), - std::memory_order_relaxed + ) ); } From fbd128eed59f921b886c09e460587a445fb56a4d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dar=C3=ADo=20Rodr=C3=ADguez=20Mart=C3=ADnez?= Date: Sun, 8 Nov 2026 16:30:39 +0100 Subject: [PATCH 03/11] Tracy mutexes impl, gated some dev only stuff and fixed glass bloom --- engine/CMakeLists.txt | 11 + engine/assets/shaders/bloom.slang | 79 +++++-- engine/assets/shaders/voxel_glass.slang | 12 ++ engine/src/toast/engine.cpp | 204 +++++++----------- engine/src/toast/events/event.cpp | 6 +- engine/src/toast/events/event.hpp | 7 +- engine/src/toast/lock_profiling.hpp | 35 +++ engine/src/toast/physics/broad_phase.hpp | 2 +- .../src/toast/physics/debris_simulation.hpp | 3 +- engine/src/toast/physics/query_snapshot.hpp | 15 +- engine/src/toast/physics/simulator.cpp | 73 +++++-- engine/src/toast/physics/simulator.hpp | 11 +- engine/src/toast/physics/voxel_data_lock.cpp | 2 +- engine/src/toast/physics/voxel_data_lock.hpp | 3 +- .../toast/renderer/core/descriptor_cache.hpp | 86 ++++++++ .../src/toast/renderer/core/vulkan_core.cpp | 149 ++++++++----- .../src/toast/renderer/core/vulkan_core.hpp | 1 + .../output/shared_texture_output_target.hpp | 7 +- .../passes/debug/selection_outline.cpp | 17 +- .../passes/debug/selection_outline.hpp | 7 +- .../renderer/passes/geometry/debris_pass.cpp | 5 +- .../renderer/passes/geometry/debris_pass.hpp | 3 +- .../renderer/passes/geometry/voxel_pass.cpp | 41 ++-- .../renderer/passes/geometry/voxel_pass.hpp | 12 +- .../renderer/passes/lighting/gi_pass.cpp | 26 +-- .../renderer/passes/lighting/gi_pass.hpp | 9 +- .../renderer/passes/lighting/shadow_pass.cpp | 5 +- .../renderer/passes/lighting/shadow_pass.hpp | 3 +- .../renderer/passes/lighting/ssao_pass.cpp | 7 +- .../renderer/passes/lighting/ssao_pass.hpp | 3 +- .../renderer/passes/lighting/ssr_pass.cpp | 7 +- .../renderer/passes/lighting/ssr_pass.hpp | 3 +- .../passes/lighting/traced_shadow_pass.cpp | 10 +- .../passes/lighting/traced_shadow_pass.hpp | 6 +- .../passes/lighting/traced_specular_pass.cpp | 12 +- .../passes/lighting/traced_specular_pass.hpp | 5 +- .../passes/lighting/volumetric_pass.cpp | 12 +- .../passes/lighting/volumetric_pass.hpp | 5 +- .../toast/renderer/passes/post/bloom_pass.cpp | 46 ++-- .../toast/renderer/passes/post/bloom_pass.hpp | 11 +- .../toast/renderer/passes/post/fxaa_pass.cpp | 7 +- .../toast/renderer/passes/post/fxaa_pass.hpp | 3 +- .../renderer/passes/post/motion_blur_pass.cpp | 7 +- .../renderer/passes/post/motion_blur_pass.hpp | 3 +- .../toast/renderer/passes/post/taa_pass.cpp | 7 +- .../toast/renderer/passes/post/taa_pass.hpp | 3 +- .../renderer/passes/post/tonemap_pass.cpp | 14 +- .../renderer/passes/post/tonemap_pass.hpp | 5 +- .../passes/post_process_pass_base.hpp | 3 + .../resources/scene_descriptor_set.cpp | 12 +- .../resources/scene_descriptor_set.hpp | 5 +- .../renderer/shaders/shader_compiler.cpp | 5 +- engine/src/toast/renderer/vulkan_renderer.cpp | 2 +- engine/src/toast/renderer/vulkan_renderer.hpp | 34 +-- .../toast/renderer/vulkan_renderer_record.cpp | 83 ++++++- .../renderer/vulkan_renderer_resources.cpp | 16 +- .../toast/renderer/vulkan_renderer_scene.cpp | 11 +- .../toast/renderer/vulkan_renderer_thread.cpp | 31 ++- engine/src/toast/scripting/lua_state.hpp | 3 +- engine/src/toast/settings/settings.hpp | 3 +- engine/src/toast/thread_pool.cpp | 12 +- engine/src/toast/thread_pool.hpp | 19 +- engine/src/toast/voxel/runtime_pool.cpp | 10 +- engine/src/toast/voxel/runtime_pool.hpp | 3 +- engine/src/toast/world/node_owner.hpp | 5 +- 65 files changed, 813 insertions(+), 454 deletions(-) create mode 100644 engine/src/toast/lock_profiling.hpp create mode 100644 engine/src/toast/renderer/core/descriptor_cache.hpp diff --git a/engine/CMakeLists.txt b/engine/CMakeLists.txt index 6b336d73c..8f03d4174 100644 --- a/engine/CMakeLists.txt +++ b/engine/CMakeLists.txt @@ -158,6 +158,15 @@ target_compile_definitions(toast_engine PUBLIC GLM_FORCE_INTRINSICS ) +option(TOAST_PROFILE_LOCKS "Show contended mutexes in Tracy, every lock sends events while a profiler is connected" ON) +# A header and not a define since it changes engine type layouts and game projects never see engine defines +set(_toast_build_config_dir "${CMAKE_CURRENT_BINARY_DIR}/build_config/$") +file(GENERATE + OUTPUT "${_toast_build_config_dir}/toast/build_config.hpp" + CONTENT "#pragma once\n$<$,$>:#define TOAST_PROFILE_LOCKS\n>" +) +target_include_directories(toast_engine PUBLIC "${_toast_build_config_dir}") + # Replaces global operator new and delete so Tracy lists every heap allocation, only active where Tracy is option(TOAST_TRACK_HEAP "Report C++ heap allocations to Tracy" ON) # 0 records no callstack, around 8 to 16 shows who allocates but slows allocation heavy code down a lot @@ -247,6 +256,7 @@ list(GET _tinyspline_include_list 0 _tinyspline_include) add_custom_command(TARGET toast_engine POST_BUILD COMMAND ${CMAKE_COMMAND} -E rm -rf "${TOAST_ENGINE_OUTPUT_ROOT}/include" "${TOAST_ENGINE_OUTPUT_ROOT}/ffi" COMMAND ${CMAKE_COMMAND} -E copy_directory "${CMAKE_CURRENT_SOURCE_DIR}/include" "${TOAST_ENGINE_OUTPUT_ROOT}/include" + COMMAND ${CMAKE_COMMAND} -E copy_if_different "${_toast_build_config_dir}/toast/build_config.hpp" "${TOAST_ENGINE_OUTPUT_ROOT}/include/toast/build_config.hpp" COMMAND ${CMAKE_COMMAND} -E copy_directory "${CMAKE_CURRENT_SOURCE_DIR}/ffi" "${TOAST_ENGINE_OUTPUT_ROOT}/ffi" COMMAND ${CMAKE_COMMAND} -E copy_if_different "${CMAKE_SOURCE_DIR}/.clang-format" "${TOAST_ENGINE_OUTPUT_ROOT}/.clang-format" # Generated reflection headers @@ -281,6 +291,7 @@ if (EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/assets") ) endif () + if (WIN32) add_custom_command(TARGET toast_engine POST_BUILD COMMAND ${CMAKE_COMMAND} -E copy_if_different $ "${TOAST_ENGINE_BIN_DIR}" diff --git a/engine/assets/shaders/bloom.slang b/engine/assets/shaders/bloom.slang index 2684a791e..c14f6a2e2 100644 --- a/engine/assets/shaders/bloom.slang +++ b/engine/assets/shaders/bloom.slang @@ -24,6 +24,18 @@ Sampler2D gSource; [[vk::binding(1,0)]] Sampler2D gSceneColor; +[[vk::binding(2,0)]] +Sampler2D gGlassBackdrop; + +[[vk::binding(3,0)]] +Sampler2D gGlassMask; + +float3 bloomSource(float2 uv) +{ + float m = gGlassMask.Sample(uv).r; + return lerp(gSource.Sample(uv).rgb, gGlassBackdrop.Sample(uv).rgb, m); +} + typedef FullscreenVSOutput VSOutput; [shader("vertex")] @@ -48,7 +60,7 @@ float3 applyThreshold(float3 color) } // Not an entry point or Slang would promote the uniform parameter into a second push block -float4 fragmentDownsample(VSOutput input, uniform bool applyKaris) : SV_Target0 +float4 fragmentDownsampleLoop(VSOutput input) : SV_Target0 { float2 texel = gParams.inverseSourceSize; float2 uv = input.uv; @@ -78,22 +90,51 @@ float4 fragmentDownsample(VSOutput input, uniform bool applyKaris) : SV_Target0 float3 group4 = (e + f + h + i) * 0.25; float3 result; - if (applyKaris) - { - float w0 = 1.0 / (1.0 + luminance(group0)); - float w1 = 1.0 / (1.0 + luminance(group1)); - float w2 = 1.0 / (1.0 + luminance(group2)); - float w3 = 1.0 / (1.0 + luminance(group3)); - float w4 = 1.0 / (1.0 + luminance(group4)); - float total = w0 * 0.5 + (w1 + w2 + w3 + w4) * 0.125; - result = (group0 * w0 * 0.5 + (group1 * w1 + group2 * w2 + group3 * w3 + group4 * w4) * 0.125) / max(total, 1e-4); - - result = applyThreshold(result); - } - else - { - result = group0 * 0.5 + (group1 + group2 + group3 + group4) * 0.125; - } + result = group0 * 0.5 + (group1 + group2 + group3 + group4) * 0.125; + + return float4(result, 1.0); +} + +float4 fragmentDownsampleStart(VSOutput input) : SV_Target0 +{ + float2 texel = gParams.inverseSourceSize; + float2 uv = input.uv; + + // Interleaved so the texture queue never throttles and live registers stay low + float3 j = bloomSource(uv + float2(-1.0, 1.0) * texel).rgb; + float3 k = bloomSource(uv + float2( 1.0, 1.0) * texel).rgb; + float3 l = bloomSource(uv + float2(-1.0,-1.0) * texel).rgb; + float3 m = bloomSource(uv + float2( 1.0,-1.0) * texel).rgb; + float3 group0 = (j + k + l + m) * 0.25; + + float3 e = bloomSource(uv).rgb; + float3 b = bloomSource(uv + float2( 0.0, 2.0) * texel).rgb; + float3 d = bloomSource(uv + float2(-2.0, 0.0) * texel).rgb; + float3 a = bloomSource(uv + float2(-2.0, 2.0) * texel).rgb; + float3 group1 = (a + b + d + e) * 0.25; + + float3 c = bloomSource(uv + float2( 2.0, 2.0) * texel).rgb; + float3 f = bloomSource(uv + float2( 2.0, 0.0) * texel).rgb; + float3 group2 = (b + c + e + f) * 0.25; + + float3 g = bloomSource(uv + float2(-2.0,-2.0) * texel).rgb; + float3 h = bloomSource(uv + float2( 0.0,-2.0) * texel).rgb; + float3 group3 = (d + e + g + h) * 0.25; + + float3 i = bloomSource(uv + float2( 2.0,-2.0) * texel).rgb; + float3 group4 = (e + f + h + i) * 0.25; + + float3 result; + + float w0 = 1.0 / (1.0 + luminance(group0)); + float w1 = 1.0 / (1.0 + luminance(group1)); + float w2 = 1.0 / (1.0 + luminance(group2)); + float w3 = 1.0 / (1.0 + luminance(group3)); + float w4 = 1.0 / (1.0 + luminance(group4)); + float total = w0 * 0.5 + (w1 + w2 + w3 + w4) * 0.125; + result = (group0 * w0 * 0.5 + (group1 * w1 + group2 * w2 + group3 * w3 + group4 * w4) * 0.125) / max(total, 1e-4); + + result = applyThreshold(result); return float4(result, 1.0); } @@ -101,13 +142,13 @@ float4 fragmentDownsample(VSOutput input, uniform bool applyKaris) : SV_Target0 [shader("fragment")] float4 fragmentDownsampleFirst(VSOutput input) : SV_Target0 { - return fragmentDownsample(input, true); + return fragmentDownsampleStart(input); } [shader("fragment")] float4 fragmentDownsampleNext(VSOutput input) : SV_Target0 { - return fragmentDownsample(input, false); + return fragmentDownsampleLoop(input); } [shader("fragment")] diff --git a/engine/assets/shaders/voxel_glass.slang b/engine/assets/shaders/voxel_glass.slang index 5d1dd5c39..ddf649f98 100644 --- a/engine/assets/shaders/voxel_glass.slang +++ b/engine/assets/shaders/voxel_glass.slang @@ -635,3 +635,15 @@ SurfaceOutput fragmentSurface(VSOutput input, out float depth : SV_Depth) } return output; } + +[shader("fragment")] +float4 fragmentMask(VSOutput input, out float depth : SV_Depth) : SV_Target0 +{ + GlassComposite glass; + if (!compositeGlass(input, true, glass)) + { + discard; + } + depth = glass.depth; + return float4(1.0, 1.0, 1.0, 1.0); +} diff --git a/engine/src/toast/engine.cpp b/engine/src/toast/engine.cpp index f76af7f14..474fdaa7f 100644 --- a/engine/src/toast/engine.cpp +++ b/engine/src/toast/engine.cpp @@ -91,6 +91,78 @@ void addDebrisPass( renderer.setDebrisPass(debris_pass.get()); renderer.addRenderPass(std::move(debris_pass)); } + +/// Everything up to the display space overlays which differ between the game window and the editor viewport +auto addScenePasses( + const renderer::VulkanCore& core, renderer::VulkanRenderer& renderer, vk::Format color_format, vk::Format depth_format, + vk::Extent2D extent +) -> const renderer::ClusterLightingPass& { + // Constructed before any material pass so materials can bind the culled light buffers straight away + auto cluster_lighting_pass = std::make_unique(core); + const auto& cluster_lighting_pass_ref = *cluster_lighting_pass; + renderer.setClusterLightingPass(&cluster_lighting_pass_ref); + renderer.addComputePass(std::move(cluster_lighting_pass)); + + // Same ordering requirement as the lighting pass + auto shadow_pass = std::make_unique(core); + renderer.setShadowPass(shadow_pass.get()); + renderer.addRenderPass(std::move(shadow_pass)); + + // Environment cubemaps + auto environment_pass = std::make_unique(core, renderer.getSceneColorFormat(), depth_format); + renderer.setEnvironmentPass(environment_pass.get()); + renderer.addRenderPass(std::move(environment_pass)); + + // Probe cubemaps + auto reflection_probe_pass = + std::make_unique(core, renderer.getSceneColorFormat(), depth_format); + renderer.setReflectionProbePass(reflection_probe_pass.get()); + renderer.addRenderPass(std::move(reflection_probe_pass)); + + // Mesh rendering runs through per-material passes + + // World-stage passes render into the HDR scene target + const auto scene_format = renderer.getSceneColorFormat(); + + // Before the passes whose scene sets bind its cascades + auto gi_pass = std::make_unique(core, scene_format, extent); + renderer.setGiPass(gi_pass.get()); + + // Recorded in its own scopes so registration order here does not matter + auto voxel_pass = std::make_unique(core, scene_format, depth_format, extent); + renderer.setVoxelPass(voxel_pass.get()); + renderer.addRenderPass(std::move(voxel_pass)); + addDebrisPass(core, renderer, depth_format, extent); + + // World-space UI panels are scene content and get exposed with it, the screen-space UI does not + renderer.addRenderPass(std::make_unique(core, scene_format, depth_format, extent)); + + // First in the chain so the probes read depth before any post pass + renderer.addPostProcessPass(std::move(gi_pass)); + + if (core.isRayTracingSupported()) { + renderer.addPostProcessPass(std::make_unique(core, scene_format, extent)); + } + + // SSAO first + renderer.addPostProcessPass(std::make_unique(core, scene_format, extent)); + // Before SSR so the scene colour it reads already holds the traced voxel reflections + auto traced_specular = std::make_unique(core, scene_format, extent); + renderer.setTracedSpecularPass(traced_specular.get()); + renderer.addPostProcessPass(std::move(traced_specular)); + renderer.addPostProcessPass(std::make_unique(core, scene_format, extent)); + renderer.addPostProcessPass(std::make_unique(core, scene_format, extent)); + auto taa = std::make_unique(core, scene_format, extent); + renderer.setTaaPass(taa.get()); + renderer.addPostProcessPass(std::move(taa)); + renderer.addPostProcessPass(std::make_unique(core, scene_format, extent)); + renderer.addPostProcessPass(std::make_unique(core, scene_format, extent)); + renderer.addPostProcessPass(std::make_unique(core, scene_format, extent)); + renderer.addPostProcessPass(std::make_unique(core, color_format, extent)); + renderer.addPostProcessPass(std::make_unique(core, color_format, extent)); + + return cluster_lighting_pass_ref; +} } Engine* Engine::instance = nullptr; @@ -655,70 +727,8 @@ void Engine::createSDLWindow(const char* w_name) { m->renderer = std::make_unique(*m->vulkan_core, std::move(output_target)); m->renderer->setDisplayHdr(display_hdr.sdr_white, display_hdr.headroom); - // Constructed before any material pass so materials can bind the culled light buffers straight away - auto cluster_lighting_pass = std::make_unique(*m->vulkan_core); - const auto& cluster_lighting_pass_ref = *cluster_lighting_pass; - m->renderer->setClusterLightingPass(&cluster_lighting_pass_ref); - m->renderer->addComputePass(std::move(cluster_lighting_pass)); - - // Same ordering requirement as the lighting pass - auto shadow_pass = std::make_unique(*m->vulkan_core); - m->renderer->setShadowPass(shadow_pass.get()); - m->renderer->addRenderPass(std::move(shadow_pass)); - - // Environment cubemaps - auto environment_pass = - std::make_unique(*m->vulkan_core, m->renderer->getSceneColorFormat(), depth_format); - m->renderer->setEnvironmentPass(environment_pass.get()); - m->renderer->addRenderPass(std::move(environment_pass)); - - // Probe cubemaps - auto reflection_probe_pass = - std::make_unique(*m->vulkan_core, m->renderer->getSceneColorFormat(), depth_format); - m->renderer->setReflectionProbePass(reflection_probe_pass.get()); - m->renderer->addRenderPass(std::move(reflection_probe_pass)); - - // Mesh rendering runs through per-material passes - - // World-stage passes render into the HDR scene target - const auto scene_format = m->renderer->getSceneColorFormat(); - - // Before the passes whose scene sets bind its cascades - auto gi_pass = std::make_unique(*m->vulkan_core, scene_format, extent); - m->renderer->setGiPass(gi_pass.get()); - - // Recorded in its own scopes so registration order here does not matter - auto voxel_pass = std::make_unique(*m->vulkan_core, scene_format, depth_format, extent); - m->renderer->setVoxelPass(voxel_pass.get()); - m->renderer->addRenderPass(std::move(voxel_pass)); - addDebrisPass(*m->vulkan_core, *m->renderer, depth_format, extent); - - // World-space UI panels are scene content and get exposed with it, the screen-space UI does not - m->renderer->addRenderPass(std::make_unique(*m->vulkan_core, scene_format, depth_format, extent)); - - // First in the chain so the probes read depth before any post pass - m->renderer->addPostProcessPass(std::move(gi_pass)); - - if (m->vulkan_core->isRayTracingSupported()) { - m->renderer->addPostProcessPass(std::make_unique(*m->vulkan_core, scene_format, extent)); - } - - // SSAO first - m->renderer->addPostProcessPass(std::make_unique(*m->vulkan_core, scene_format, extent)); - // Before SSR so the scene colour it reads already holds the traced voxel reflections - auto traced_specular = std::make_unique(*m->vulkan_core, scene_format, extent); - m->renderer->setTracedSpecularPass(traced_specular.get()); - m->renderer->addPostProcessPass(std::move(traced_specular)); - m->renderer->addPostProcessPass(std::make_unique(*m->vulkan_core, scene_format, extent)); - m->renderer->addPostProcessPass(std::make_unique(*m->vulkan_core, scene_format, extent)); - auto taa = std::make_unique(*m->vulkan_core, scene_format, extent); - m->renderer->setTaaPass(taa.get()); - m->renderer->addPostProcessPass(std::move(taa)); - m->renderer->addPostProcessPass(std::make_unique(*m->vulkan_core, scene_format, extent)); - m->renderer->addPostProcessPass(std::make_unique(*m->vulkan_core, scene_format, extent)); - m->renderer->addPostProcessPass(std::make_unique(*m->vulkan_core, scene_format, extent)); - m->renderer->addPostProcessPass(std::make_unique(*m->vulkan_core, color_format, extent)); - m->renderer->addPostProcessPass(std::make_unique(*m->vulkan_core, color_format, extent)); + [[maybe_unused]] + const auto& cluster_lighting_pass_ref = addScenePasses(*m->vulkan_core, *m->renderer, color_format, depth_format, extent); // always_on_top world panels, after the tonemap and under the screen-space UI m->renderer->addRenderPass( @@ -763,70 +773,8 @@ void Engine::createAvaloniaWindow() { m->renderer = std::make_unique(*m->vulkan_core, std::move(output_target)); - // Constructed before any material pass so materials can bind the culled light buffers straight away - auto cluster_lighting_pass = std::make_unique(*m->vulkan_core); - const auto& cluster_lighting_pass_ref = *cluster_lighting_pass; - m->renderer->setClusterLightingPass(&cluster_lighting_pass_ref); - m->renderer->addComputePass(std::move(cluster_lighting_pass)); - - // Same ordering requirement as the lighting pass - auto shadow_pass = std::make_unique(*m->vulkan_core); - m->renderer->setShadowPass(shadow_pass.get()); - m->renderer->addRenderPass(std::move(shadow_pass)); - - // Environment cubemaps - auto environment_pass = - std::make_unique(*m->vulkan_core, m->renderer->getSceneColorFormat(), depth_format); - m->renderer->setEnvironmentPass(environment_pass.get()); - m->renderer->addRenderPass(std::move(environment_pass)); - - // Probe cubemaps - auto reflection_probe_pass = - std::make_unique(*m->vulkan_core, m->renderer->getSceneColorFormat(), depth_format); - m->renderer->setReflectionProbePass(reflection_probe_pass.get()); - m->renderer->addRenderPass(std::move(reflection_probe_pass)); - - // Mesh rendering runs through per-material passes - - // World-stage passes render into the HDR scene target - const auto scene_format = m->renderer->getSceneColorFormat(); - - // Before the passes whose scene sets bind its cascades - auto gi_pass = std::make_unique(*m->vulkan_core, scene_format, extent); - m->renderer->setGiPass(gi_pass.get()); - - // Recorded in its own scopes so registration order here does not matter - auto voxel_pass = std::make_unique(*m->vulkan_core, scene_format, depth_format, extent); - m->renderer->setVoxelPass(voxel_pass.get()); - m->renderer->addRenderPass(std::move(voxel_pass)); - addDebrisPass(*m->vulkan_core, *m->renderer, depth_format, extent); - - // World-space UI panels are scene content - m->renderer->addRenderPass(std::make_unique(*m->vulkan_core, scene_format, depth_format, extent)); - - // First in the chain so the probes read depth before any post pass - m->renderer->addPostProcessPass(std::move(gi_pass)); - - if (m->vulkan_core->isRayTracingSupported()) { - m->renderer->addPostProcessPass(std::make_unique(*m->vulkan_core, scene_format, extent)); - } - - // SSAO first - m->renderer->addPostProcessPass(std::make_unique(*m->vulkan_core, scene_format, extent)); - // Before SSR so the scene colour it reads already holds the traced voxel reflections - auto traced_specular = std::make_unique(*m->vulkan_core, scene_format, extent); - m->renderer->setTracedSpecularPass(traced_specular.get()); - m->renderer->addPostProcessPass(std::move(traced_specular)); - m->renderer->addPostProcessPass(std::make_unique(*m->vulkan_core, scene_format, extent)); - m->renderer->addPostProcessPass(std::make_unique(*m->vulkan_core, scene_format, extent)); - auto taa = std::make_unique(*m->vulkan_core, scene_format, extent); - m->renderer->setTaaPass(taa.get()); - m->renderer->addPostProcessPass(std::move(taa)); - m->renderer->addPostProcessPass(std::make_unique(*m->vulkan_core, scene_format, extent)); - m->renderer->addPostProcessPass(std::make_unique(*m->vulkan_core, scene_format, extent)); - m->renderer->addPostProcessPass(std::make_unique(*m->vulkan_core, scene_format, extent)); - m->renderer->addPostProcessPass(std::make_unique(*m->vulkan_core, color_format, extent)); - m->renderer->addPostProcessPass(std::make_unique(*m->vulkan_core, color_format, extent)); + [[maybe_unused]] + const auto& cluster_lighting_pass_ref = addScenePasses(*m->vulkan_core, *m->renderer, color_format, depth_format, extent); // Editor overlays, drawn after the tonemap in display space (see DebugPass::stage() / GridPass::stage()) m->renderer->addRenderPass(std::make_unique(*m->vulkan_core, color_format, depth_format, extent)); diff --git a/engine/src/toast/events/event.cpp b/engine/src/toast/events/event.cpp index bee5e7353..f983c8d9c 100644 --- a/engine/src/toast/events/event.cpp +++ b/engine/src/toast/events/event.cpp @@ -8,11 +8,11 @@ namespace event { std::unordered_map EventSystem::event_data; -std::shared_mutex EventSystem::registration_mutex; -std::mutex EventSystem::pool_mutex; +TOAST_SHARED_LOCKABLE(std::shared_mutex, EventSystem::registration_mutex, "Event registration"); +TOAST_LOCKABLE(std::mutex, EventSystem::pool_mutex, "Event pool"); std::unordered_map> EventSystem::unsubscribe_map; std::vector> EventSystem::deletion_queue; -std::mutex EventSystem::deletion_mutex; +TOAST_LOCKABLE(std::mutex, EventSystem::deletion_mutex, "Event deletion"); namespace { struct Pool { diff --git a/engine/src/toast/events/event.hpp b/engine/src/toast/events/event.hpp index 9e9d49e5e..d4ad753fc 100644 --- a/engine/src/toast/events/event.hpp +++ b/engine/src/toast/events/event.hpp @@ -15,6 +15,7 @@ #include #include #include +#include #include #include #include @@ -128,7 +129,7 @@ struct TOAST_API EventSystem { static std::unordered_map event_data; /// Guards event_data and unsubscribe_map - static std::shared_mutex registration_mutex; + static TOAST_SHARED_LOCKABLE_BASE(std::shared_mutex) registration_mutex; /// Unsubscribes a callback of the given type static void unsubscribeAny(std::type_index type, const std::any& iterator); @@ -137,7 +138,7 @@ struct TOAST_API EventSystem { static auto info() noexcept -> EventInfo&; /// Protects the event queue memory pool during concurrent sends - static std::mutex pool_mutex; + static TOAST_LOCKABLE_BASE(std::mutex) pool_mutex; /// Type-erased unsubscribe functions keyed by event type; used by Listener to erase iterators without the concrete type static std::unordered_map> unsubscribe_map; @@ -147,7 +148,7 @@ struct TOAST_API EventSystem { static std::vector> deletion_queue; /// Protects the event queue memory pool during concurrent sends - static std::mutex deletion_mutex; + static TOAST_LOCKABLE_BASE(std::mutex) deletion_mutex; template static void registerEvent() { diff --git a/engine/src/toast/lock_profiling.hpp b/engine/src/toast/lock_profiling.hpp new file mode 100644 index 000000000..3891da30a --- /dev/null +++ b/engine/src/toast/lock_profiling.hpp @@ -0,0 +1,35 @@ +/** + * @file lock_profiling.hpp + * @author dario + * @date 07/11/2026 + */ + +#pragma once + +#include +#include +#include +#include + +#if defined(TRACY_ENABLE) && defined(TOAST_PROFILE_LOCKS) +#include + +#define TOAST_LOCKABLE(type, name, desc) TracyLockableN(type, name, desc) +#define TOAST_SHARED_LOCKABLE(type, name, desc) TracySharedLockableN(type, name, desc) +#define TOAST_LOCKABLE_BASE(type) LockableBase(type) +#define TOAST_SHARED_LOCKABLE_BASE(type) SharedLockableBase(type) + +namespace toast { +/// Tracy lockables are not std::mutex so waits need the generic condition variable +using ConditionVariable = std::condition_variable_any; +} +#else +#define TOAST_LOCKABLE(type, name, desc) type name +#define TOAST_SHARED_LOCKABLE(type, name, desc) type name +#define TOAST_LOCKABLE_BASE(type) type +#define TOAST_SHARED_LOCKABLE_BASE(type) type + +namespace toast { +using ConditionVariable = std::condition_variable; +} +#endif diff --git a/engine/src/toast/physics/broad_phase.hpp b/engine/src/toast/physics/broad_phase.hpp index 9b0a6429f..efdea0e55 100644 --- a/engine/src/toast/physics/broad_phase.hpp +++ b/engine/src/toast/physics/broad_phase.hpp @@ -70,7 +70,7 @@ class BroadPhase { auto stats() const -> const BroadPhaseStats&; [[nodiscard]] - auto snapshotTree() const -> AABBTree { + auto tree() const -> const AABBTree& { return m_tree; } diff --git a/engine/src/toast/physics/debris_simulation.hpp b/engine/src/toast/physics/debris_simulation.hpp index fc7864667..01282b956 100644 --- a/engine/src/toast/physics/debris_simulation.hpp +++ b/engine/src/toast/physics/debris_simulation.hpp @@ -17,6 +17,7 @@ #include #include #include +#include #include #include #include @@ -186,7 +187,7 @@ class TOAST_API DebrisSimulation : public renderer::AsyncComputeTask { std::shared_ptr m_world; - mutable std::mutex m_time_mutex; + mutable TOAST_LOCKABLE(std::mutex, m_time_mutex, "Debris time"); double m_sim_time = 0.0; double m_display_time = 0.0; double m_frame_delta = 0.0; diff --git a/engine/src/toast/physics/query_snapshot.hpp b/engine/src/toast/physics/query_snapshot.hpp index 4c2bd6c5b..a45fbf459 100644 --- a/engine/src/toast/physics/query_snapshot.hpp +++ b/engine/src/toast/physics/query_snapshot.hpp @@ -13,12 +13,21 @@ namespace physics { +/// Immutable copy shared by every snapshot until the key below changes +struct QueryVoxel { + std::shared_ptr data; + uint32_t generation = 0; + uint64_t volume_id = 0; + uint32_t volume_revision = 0; + uint32_t surface_revision = 0; +}; + /// All data used by gameplay collision queries from one completed physics tick. struct QuerySnapshot { AABBTree tree; std::vector bodies; std::vector shapes; - std::vector voxels; + std::vector voxels; std::vector> collider_nodes; std::vector> body_nodes; float fat_margin = 0.0f; @@ -52,8 +61,8 @@ struct QuerySnapshot { if (id.slot >= voxels.size()) { return nullptr; } - const VoxelShapeSlot& slot = voxels[id.slot]; - return slot.data && slot.generation == id.generation ? &*slot.data : nullptr; + const QueryVoxel& slot = voxels[id.slot]; + return slot.data && slot.generation == id.generation ? slot.data.get() : nullptr; } [[nodiscard]] diff --git a/engine/src/toast/physics/simulator.cpp b/engine/src/toast/physics/simulator.cpp index 19419f790..7fd3e985d 100644 --- a/engine/src/toast/physics/simulator.cpp +++ b/engine/src/toast/physics/simulator.cpp @@ -199,7 +199,7 @@ namespace { std::atomic g_simulator_thread {}; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables) struct Requests { - std::mutex mutex; + TOAST_LOCKABLE(std::mutex, mutex, "Physics requests"); std::deque> queue; std::atomic pending {0}; ///< queued, plus the one being carried out bool running = false; ///< only the simulator thread touches it @@ -281,36 +281,65 @@ Simulator::~Simulator() { } auto Simulator::querySnapshot() -> std::shared_ptr { + // A physics tick between steps reads the step before it, only the tick thread is serial with the simulation + if (instance != nullptr && instance->m_query_snapshot_dirty.load(std::memory_order_acquire) && onSimulatorThread() && + instance->m_phase.load(std::memory_order_relaxed) == SimulationPhase::idle) { + instance->publishQuerySnapshot(); + } return published_query_snapshot.load(std::memory_order_acquire); } void Simulator::publishQuerySnapshot() { ZoneScopedN("physics::PublishQuerySnapshot"); - auto snapshot = std::make_shared(); - snapshot->tree = m_broad_phase.snapshotTree(); + m_query_snapshot_dirty.store(false, std::memory_order_relaxed); + std::shared_ptr previous = published_query_snapshot.load(std::memory_order_acquire); + std::shared_ptr snapshot = std::exchange(m_spare_query_snapshot, nullptr); + if (not snapshot) { + snapshot = std::make_shared(); + } + // Copy assignment keeps the spare capacity + snapshot->tree = m_broad_phase.tree(); snapshot->bodies = m_bodies; snapshot->shapes = m_shapes; snapshot->fat_margin = tunables().broadphase_fat_margin; snapshot->tick = m_tick_index; - snapshot->collider_nodes.resize(m_shapes.size()); - snapshot->body_nodes.resize(m_bodies.size()); + snapshot->collider_nodes.assign(m_shapes.size(), {}); + snapshot->body_nodes.assign(m_bodies.size(), {}); { std::scoped_lock voxel_lock {voxelDataMutex()}; - snapshot->voxels.reserve(m_voxel_shapes.size()); - for (const VoxelShapeSlot& source : m_voxel_shapes) { - VoxelShapeSlot copy; - copy.generation = source.generation; + const std::vector* cached = previous && not m_query_voxels_stale ? &previous->voxels : nullptr; + m_query_voxels_stale = false; + snapshot->voxels.resize(m_voxel_shapes.size()); + for (size_t index = 0; index < m_voxel_shapes.size(); ++index) { + const VoxelShapeSlot& source = m_voxel_shapes[index]; + const voxel::Volume* volume = source.data ? source.data->volume : nullptr; + QueryVoxel key { + .generation = source.generation, + .volume_id = volume ? volume->id() : 0, + .volume_revision = volume ? volume->revision() : 0, + .surface_revision = source.data ? source.data->surface_revision : 0, + }; + if (cached != nullptr && index < cached->size()) { + const QueryVoxel& hit = (*cached)[index]; + if ((hit.data != nullptr) == source.data.has_value() && hit.generation == key.generation && + hit.volume_id == key.volume_id && hit.volume_revision == key.volume_revision && + hit.surface_revision == key.surface_revision) { + snapshot->voxels[index] = hit; + continue; + } + } if (source.data) { - VoxelShapeData& data = copy.data.emplace(); - data.surface = source.data->surface; - data.palette = source.data->palette; - data.materials = source.data->materials; - if (source.data->volume) { - data.owned_volume = std::make_unique(voxel::Volume::instanceOf(*source.data->volume)); - data.volume = data.owned_volume.get(); + auto data = std::make_shared(); + data->surface = source.data->surface; + data->palette = source.data->palette; + data->materials = source.data->materials; + if (volume) { + data->owned_volume = std::make_unique(voxel::Volume::instanceOf(*volume)); + data->volume = data->owned_volume.get(); } + key.data = std::move(data); } - snapshot->voxels.push_back(std::move(copy)); + snapshot->voxels[index] = std::move(key); } } for (const NodeBinding& binding : m_node_bindings) { @@ -332,6 +361,10 @@ void Simulator::publishQuerySnapshot() { } } published_query_snapshot.store(std::move(snapshot), std::memory_order_release); + // Readers only reach it through the published pointer so one owner left means nobody reads it + if (previous.use_count() == 1) { + m_spare_query_snapshot = std::const_pointer_cast(std::move(previous)); + } } void Simulator::registerRigidbody(Rigidbody& node) { @@ -822,7 +855,7 @@ void Simulator::tick() { publishTransforms(); publishJoints(); publishVoxelRenderRecords(); - publishQuerySnapshot(); + m_query_snapshot_dirty.store(true, std::memory_order_release); m_profile.tick_ms = elapsed_ms(tick_start, std::chrono::steady_clock::now()); publishProfile(islands); FrameMarkNamed("PhysicsStep"); @@ -1195,6 +1228,7 @@ void Simulator::refreshPalette(uint64_t palette_uid) { data->palette = palette; data->materials = materials; data->moments = accumulateMassMoments(*data->volume, palette, materials); + m_query_voxels_stale = true; const Body* body = tryGetBody(slot.shape.owner); if (body != nullptr && body->type == BodyType::dynamic_body) { @@ -2542,6 +2576,9 @@ void Simulator::syncRenderPoses() { if (instance != nullptr) { runPendingRequests(); instance->rebuildRenderPoseLookup(); + if (instance->m_query_snapshot_dirty.load(std::memory_order_relaxed)) { + instance->publishQuerySnapshot(); + } } } diff --git a/engine/src/toast/physics/simulator.hpp b/engine/src/toast/physics/simulator.hpp index 566b10dfd..384e6f520 100644 --- a/engine/src/toast/physics/simulator.hpp +++ b/engine/src/toast/physics/simulator.hpp @@ -36,6 +36,7 @@ #include #include #include +#include #include #include #include @@ -720,7 +721,7 @@ class TOAST_API Simulator { inline static Simulator* instance = nullptr; inline static std::atomic> published_query_snapshot; - std::mutex m_wind_mutex; + TOAST_LOCKABLE(std::mutex, m_wind_mutex, "Physics wind"); std::optional m_level_wind; mutable std::thread::id m_owner_thread; @@ -802,13 +803,19 @@ class TOAST_API Simulator { std::vector m_voxel_render_records; std::vector m_debris_spawns; - std::mutex m_damage_mutex; + TOAST_LOCKABLE(std::mutex, m_damage_mutex, "Physics damage"); std::vector m_damage_commands; std::vector m_debug_dirty_bricks; uint64_t m_next_fragment_sequence = 1; uint64_t m_tick_index = 0; void publishQuerySnapshot(); + /// Unpublished snapshot nobody reads anymore so its buffers get refilled instead of reallocated + std::shared_ptr m_spare_query_snapshot; + /// Steps only mark it so a burst of fixed steps copies once per frame + std::atomic m_query_snapshot_dirty = false; + /// Palette reloads change voxel copies without bumping any revision + bool m_query_voxels_stale = false; std::vector m_fragments; std::unordered_map m_fragment_index; std::vector m_pending_fragments; diff --git a/engine/src/toast/physics/voxel_data_lock.cpp b/engine/src/toast/physics/voxel_data_lock.cpp index 6a659a884..5bc89a6a2 100644 --- a/engine/src/toast/physics/voxel_data_lock.cpp +++ b/engine/src/toast/physics/voxel_data_lock.cpp @@ -4,7 +4,7 @@ namespace physics { -auto voxelDataMutex() -> std::recursive_mutex& { +auto voxelDataMutex() -> TOAST_LOCKABLE_BASE(std::recursive_mutex) & { return voxel::runtimePoolMutex(); } diff --git a/engine/src/toast/physics/voxel_data_lock.hpp b/engine/src/toast/physics/voxel_data_lock.hpp index 0fed92bce..0d944523f 100644 --- a/engine/src/toast/physics/voxel_data_lock.hpp +++ b/engine/src/toast/physics/voxel_data_lock.hpp @@ -9,10 +9,11 @@ #include #include +#include namespace physics { [[nodiscard]] -TOAST_API auto voxelDataMutex() -> std::recursive_mutex&; +TOAST_API auto voxelDataMutex() -> TOAST_LOCKABLE_BASE(std::recursive_mutex) &; } diff --git a/engine/src/toast/renderer/core/descriptor_cache.hpp b/engine/src/toast/renderer/core/descriptor_cache.hpp new file mode 100644 index 000000000..7feb68d68 --- /dev/null +++ b/engine/src/toast/renderer/core/descriptor_cache.hpp @@ -0,0 +1,86 @@ +/** + * @file descriptor_cache.hpp + * @author dario + * @date 06/11/2026 + */ + +#pragma once + +#include +#include +#include +#include + +namespace renderer { + +namespace descriptor_cache_detail { +inline std::atomic target_generation {1}; +} + +[[nodiscard]] +inline auto targetGeneration() noexcept -> uint64_t { + return descriptor_cache_detail::target_generation.load(std::memory_order_acquire); +} + +/// Call whenever renderer owned targets are recreated since a new view can reuse a destroyed handle value +inline void bumpTargetGeneration() noexcept { + descriptor_cache_detail::target_generation.fetch_add(1, std::memory_order_acq_rel); +} + +/// What each descriptor set slot was last written with +template +class DescriptorCache { +public: + DescriptorCache() = default; + + explicit DescriptorCache(size_t slots) : m_entries(slots) { } + + void resize(size_t slots) { m_entries.assign(slots, Entry {}); } + + [[nodiscard]] + auto size() const noexcept -> size_t { + return m_entries.size(); + } + + /// True when the slot must be rewritten and from then on counts it as written with key + [[nodiscard]] + auto update(size_t slot, const Key& key) -> bool { + Entry& entry = m_entries[slot]; + const uint64_t generation = targetGeneration(); + if (entry.generation == generation && entry.key == key) { + return false; + } + entry.key = key; + entry.generation = generation; + return true; + } + + /// True when every slot was written since the last invalidation or target recreation + [[nodiscard]] + auto allCurrent() const noexcept -> bool { + const uint64_t generation = targetGeneration(); + for (const Entry& entry : m_entries) { + if (entry.generation != generation) { + return false; + } + } + return true; + } + + void invalidate() noexcept { + for (Entry& entry : m_entries) { + entry.generation = 0; + } + } + +private: + struct Entry { + Key key {}; + /// Zero is never a live generation so a fresh entry always writes + uint64_t generation = 0; + }; + + std::vector m_entries; +}; + +} diff --git a/engine/src/toast/renderer/core/vulkan_core.cpp b/engine/src/toast/renderer/core/vulkan_core.cpp index 3672fa54d..e63cf48cd 100644 --- a/engine/src/toast/renderer/core/vulkan_core.cpp +++ b/engine/src/toast/renderer/core/vulkan_core.cpp @@ -11,10 +11,6 @@ #include #include -#if defined(__linux__) -#include -#endif - #if defined(_WIN32) && defined(TOAST_DEV_TOOLS) #include #include @@ -51,11 +47,6 @@ auto vulkanCoreAttachedGraphicsDebugger() -> std::optional { GetModuleHandleW(NGFX_GPU_TRACE_INJECTION_LIB_NAME) != nullptr) { return "Nsight Graphics"; } -#elif defined(__linux__) -#elif defined(__linux__) && defined(TOAST_DEV_TOOLS) - dlclose(mod); - return "RenderDoc"; -} #endif return std::nullopt; } @@ -141,7 +132,7 @@ auto queueFamilyFlagsToString(vk::QueueFlags flags) -> std::string { return result; } -auto debugCallback( +VKAPI_ATTR auto VKAPI_CALL debugCallback( VkDebugUtilsMessageSeverityFlagBitsEXT message_severity, VkDebugUtilsMessageTypeFlagsEXT message_type, const VkDebugUtilsMessengerCallbackDataEXT* p_callback_data, void* p_user_data ) -> VkBool32 { @@ -339,6 +330,45 @@ auto judgeHardwareRayTracing(const vk::PhysicalDeviceProperties& props, bool mes } return {true, "unknown vendor, trusting the driver"}; } + +struct RayQueryProbe { + bool extensions_present = false; + bool features_present = false; + RayTracingVerdict verdict; + + [[nodiscard]] + auto used() const noexcept -> bool { + return extensions_present && features_present && verdict.hardware; + } +}; + +/// Logs nothing so it can run before the device is final +auto probeRayQuery(const vk::raii::PhysicalDevice& physical) -> RayQueryProbe { + const auto available = physical.enumerateDeviceExtensionProperties(); + const auto has_extension = [&available](std::string_view name) { + return std::ranges::any_of(available, [name](const vk::ExtensionProperties& ext) { + return std::string_view(ext.extensionName.data()) == name; + }); + }; + + RayQueryProbe probe {}; + probe.extensions_present = has_extension(VK_KHR_ACCELERATION_STRUCTURE_EXTENSION_NAME) && + has_extension(VK_KHR_RAY_QUERY_EXTENSION_NAME) && + has_extension(VK_KHR_DEFERRED_HOST_OPERATIONS_EXTENSION_NAME); + if (probe.extensions_present) { + vk::PhysicalDeviceFeatures2 features {}; + vk::PhysicalDeviceAccelerationStructureFeaturesKHR as_features {}; + vk::PhysicalDeviceRayQueryFeaturesKHR rq_features {}; + as_features.pNext = &rq_features; + features.pNext = &as_features; + (*physical).getFeatures2(&features); + probe.features_present = as_features.accelerationStructure == VK_TRUE && rq_features.rayQuery == VK_TRUE; + } + if (probe.extensions_present && probe.features_present) { + probe.verdict = judgeHardwareRayTracing(physical.getProperties(), has_extension(VK_EXT_MESH_SHADER_EXTENSION_NAME)); + } + return probe; +} } // namespace auto DeviceScore::toString() const noexcept -> std::string { @@ -378,6 +408,31 @@ VulkanCore::VulkanCore( TOAST_TRACE("Render", "Required instance extensions: {}", joinRequiredExtensions(required_instance_extensions)); TOAST_TRACE("Render", "Required device extensions: {}", joinRequiredExtensions(required_device_extensions)); + createInstance(required_instance_extensions, false); + pickPhysicalDevice(required_device_extensions); + // Layer settings are fixed at instance creation but ray query use is only known once a device is picked + if (m_validation_enabled && probeRayQuery(m_physical_device).used()) { + m_physical_device = nullptr; + m_instance = nullptr; + createInstance(required_instance_extensions, true); + pickPhysicalDevice(required_device_extensions); + } + createLogicalDeviceAndAllocator(required_device_extensions); + m_pipeline_cache = vk::raii::PipelineCache(m_device, vk::PipelineCacheCreateInfo {}); + +#if defined(TOAST_DEV_TOOLS) && defined(_WIN32) + if (HMODULE mod = GetModuleHandleA("renderdoc.dll")) { + pRENDERDOC_GetAPI renderdoc_get_api = reinterpret_cast(GetProcAddress(mod, "RENDERDOC_GetAPI")); + renderdoc_get_api(eRENDERDOC_API_Version_1_6_0, reinterpret_cast(&rdoc_api)); + TOAST_INFO("Render", "RenderDoc API detected"); + } +#endif + + // Not activating Nsight GPU trace here since it blocks until the host attaches +} + +void VulkanCore::createInstance(std::span required_instance_extensions, bool validate_ray_query) { + ZoneScoped; vk::ApplicationInfo app_info("SUPER DUPER TOASTY GAME", 1, "TOAST ENGINE", 1, VK_API_VERSION_1_4); std::vector layers; @@ -411,6 +466,32 @@ VulkanCore::VulkanCore( TOAST_INFO("Render", "Synchronization validation: {}", m_validation_enabled ? "enabled" : "disabled"); #endif + // GPU assisted validation with only the ray query checks on since the rest instruments every shader + constexpr VkBool32 k_on = VK_TRUE; + constexpr VkBool32 k_off = VK_FALSE; + const auto setting = [](const char* name, const VkBool32& value) { + return vk::LayerSettingEXT("VK_LAYER_KHRONOS_validation", name, vk::LayerSettingTypeEXT::eBool32, 1, &value); + }; + const std::array gpuav_settings { + setting("gpuav_enable", k_on), + setting("gpuav_shader_instrumentation", k_on), + setting("gpuav_validate_ray_query", k_on), + setting("gpuav_descriptor_checks", k_on), + setting("gpuav_post_process_descriptor_indexing", k_off), + setting("gpuav_buffer_address_oob", k_off), + setting("gpuav_mesh_shading", k_on), + setting("gpuav_validate_trace_ray", k_on), + setting("gpuav_vertex_attribute_fetch_oob", k_off), + setting("gpuav_shader_sanitizer", k_off), + setting("gpuav_shared_memory_data_race", k_off), + setting("gpuav_buffers_validation", k_off), + }; + vk::LayerSettingsCreateInfoEXT layer_settings(gpuav_settings); + if (m_validation_enabled && validate_ray_query) { + layer_settings.pNext = instance_ci.pNext; + instance_ci.pNext = &layer_settings; + } + m_instance = vk::raii::Instance(m_context, instance_ci); if (m_validation_enabled && m_debug_utils_enabled) { @@ -424,29 +505,6 @@ VulkanCore::VulkanCore( m_debug_messenger = vk::raii::DebugUtilsMessengerEXT(m_instance, debug_ci); #endif } - - pickPhysicalDevice(required_device_extensions); - createLogicalDeviceAndAllocator(required_device_extensions); - m_pipeline_cache = vk::raii::PipelineCache(m_device, vk::PipelineCacheCreateInfo {}); - -#if defined(TOAST_DEV_TOOLS) && defined(_WIN32) - if (HMODULE mod = GetModuleHandleA("renderdoc.dll")) { - pRENDERDOC_GetAPI renderdoc_get_api = reinterpret_cast(GetProcAddress(mod, "RENDERDOC_GetAPI")); - renderdoc_get_api(eRENDERDOC_API_Version_1_6_0, reinterpret_cast(&rdoc_api)); - TOAST_INFO("Render", "RenderDoc API detected"); - } -#elif defined(__linux__) -#elif defined(TOAST_DEV_TOOLS) && defined(__linux__) - auto* renderdoc_get_api = reinterpret_cast(dlsym(mod, "RENDERDOC_GetAPI")); - if (renderdoc_get_api) { - renderdoc_get_api(eRENDERDOC_API_Version_1_6_0, reinterpret_cast(&rdoc_api)); - TOAST_INFO("Render", "RenderDoc API detected"); - } - dlclose(mod); -} -#endif - - // Not activating Nsight GPU trace here since it blocks until the host attaches } #if defined(_WIN32) && defined(TOAST_DEV_TOOLS) @@ -791,32 +849,9 @@ void VulkanCore::createLogicalDeviceAndAllocator(std::span re } { - const auto available = m_physical_device.enumerateDeviceExtensionProperties(); - const auto has_extension = [&available](std::string_view name) { - return std::ranges::any_of(available, [name](const vk::ExtensionProperties& ext) { - return std::string_view(ext.extensionName.data()) == name; - }); - }; - - const bool extensions_present = has_extension(VK_KHR_ACCELERATION_STRUCTURE_EXTENSION_NAME) && - has_extension(VK_KHR_RAY_QUERY_EXTENSION_NAME) && - has_extension(VK_KHR_DEFERRED_HOST_OPERATIONS_EXTENSION_NAME); - - bool features_present = false; - if (extensions_present) { - vk::PhysicalDeviceFeatures2 probe {}; - vk::PhysicalDeviceAccelerationStructureFeaturesKHR as_probe {}; - vk::PhysicalDeviceRayQueryFeaturesKHR rq_probe {}; - as_probe.pNext = &rq_probe; - probe.pNext = &as_probe; - (*m_physical_device).getFeatures2(&probe); - features_present = as_probe.accelerationStructure == VK_TRUE && rq_probe.rayQuery == VK_TRUE; - } - + const auto [extensions_present, features_present, verdict] = probeRayQuery(m_physical_device); const bool driver_exposes_ray_query = extensions_present && features_present; - RayTracingVerdict verdict {}; if (driver_exposes_ray_query) { - verdict = judgeHardwareRayTracing(m_physical_device.getProperties(), has_extension(VK_EXT_MESH_SHADER_EXTENSION_NAME)); if (!verdict.hardware) { TOAST_WARN( "Render", diff --git a/engine/src/toast/renderer/core/vulkan_core.hpp b/engine/src/toast/renderer/core/vulkan_core.hpp index eea992bd1..068da849f 100644 --- a/engine/src/toast/renderer/core/vulkan_core.hpp +++ b/engine/src/toast/renderer/core/vulkan_core.hpp @@ -247,6 +247,7 @@ class VulkanCore { } private: + void createInstance(std::span required_instance_extensions, bool validate_ray_query); void pickPhysicalDevice(std::span required_device_extensions); void createLogicalDeviceAndAllocator(std::span required_device_extensions); diff --git a/engine/src/toast/renderer/output/shared_texture_output_target.hpp b/engine/src/toast/renderer/output/shared_texture_output_target.hpp index 12da55c4f..6829f9064 100644 --- a/engine/src/toast/renderer/output/shared_texture_output_target.hpp +++ b/engine/src/toast/renderer/output/shared_texture_output_target.hpp @@ -12,6 +12,7 @@ #include #include #include +#include #include namespace renderer { @@ -156,16 +157,16 @@ class SharedTextureOutputTarget final : public IOutputTarget { std::atomic m_sharing {SharingState::off}; std::atomic m_readback_requested {false}; - std::mutex m_frame_mutex; + TOAST_LOCKABLE(std::mutex, m_frame_mutex, "Viewport frames"); std::vector m_images; uint32_t m_next_acquire_index = 0; std::atomic m_latest_ready {-1}; std::atomic m_latest_readback {-1}; int32_t m_reading = -1; - std::condition_variable m_reading_done; + toast::ConditionVariable m_reading_done; /// Woken when the editor gives a slot back - std::condition_variable m_slot_freed; + toast::ConditionVariable m_slot_freed; std::atomic m_frame_counter {0}; std::unique_ptr m_interop; }; diff --git a/engine/src/toast/renderer/passes/debug/selection_outline.cpp b/engine/src/toast/renderer/passes/debug/selection_outline.cpp index 0f2f43d6a..f2fa7bd4b 100644 --- a/engine/src/toast/renderer/passes/debug/selection_outline.cpp +++ b/engine/src/toast/renderer/passes/debug/selection_outline.cpp @@ -137,7 +137,7 @@ void SelectionOutline::createTargets(vk::Extent2D extent) { m_extent = extent; m_drawn = false; m_history_valid = false; - std::ranges::fill(m_bound_outline, std::array {}); + m_bound_outline.invalidate(); if (extent.width == 0 || extent.height == 0) { return; } @@ -231,8 +231,8 @@ void SelectionOutline::createMaskPipelines(vk::Extent2D extent) { m_mask_sets.clear(); m_voxel_sets.clear(); m_volume_buffers.clear(); - m_bound_depth.assign(VulkanRenderer::k_frames_in_flight, vk::ImageView {}); - m_bound_storage.assign(VulkanRenderer::k_frames_in_flight, nullptr); + m_bound_depth.resize(VulkanRenderer::k_frames_in_flight); + m_bound_storage.resize(VulkanRenderer::k_frames_in_flight); DescriptorWriter writer; for (uint32_t i = 0; i < VulkanRenderer::k_frames_in_flight; ++i) { @@ -325,7 +325,7 @@ void SelectionOutline::createOutlinePipelines(vk::Format output_format, vk::Form const vk::DescriptorPool pool = VulkanRenderer::instance->getDescriptorPoolHandle(); const vk::DescriptorSetLayout set_layout = *layouts[0]; m_outline_sets.clear(); - m_bound_outline.assign(VulkanRenderer::k_frames_in_flight, {}); + m_bound_outline.resize(VulkanRenderer::k_frames_in_flight); for (uint32_t i = 0; i < VulkanRenderer::k_frames_in_flight; ++i) { auto allocated = device.allocateDescriptorSets(vk::DescriptorSetAllocateInfo(pool, 1, &set_layout)); m_outline_sets.push_back(std::move(allocated[0])); @@ -364,10 +364,9 @@ auto SelectionOutline::prepareVolumes(uint32_t frame_index) -> uint32_t { } m_volume_buffers[frame_index].getAllocation().flush(0, sizeof(VoxelInstanceGpu) * count); - if (m_bound_storage[frame_index] != storage) { + if (m_bound_storage.update(frame_index, storage)) { // Safe since the fence of this slot was waited on writeVoxelStorageDescriptors(m_core->getDevice(), *m_voxel_sets[frame_index], *storage); - m_bound_storage[frame_index] = storage; } return count; } @@ -422,7 +421,7 @@ void SelectionOutline::recordMask(vk::CommandBuffer cmd, uint32_t frame_index, v m_history_view_projection = frame->frame_data.view_projection; m_history_models = std::move(models); - if (m_bound_depth[frame_index] != scene_depth) { + if (m_bound_depth.update(frame_index, scene_depth)) { DescriptorWriter writer; writer.image( *m_mask_sets[frame_index], @@ -433,7 +432,6 @@ void SelectionOutline::recordMask(vk::CommandBuffer cmd, uint32_t frame_index, v vk::ImageLayout::eDepthReadOnlyOptimal ); writer.flush(m_core->getDevice()); - m_bound_depth[frame_index] = scene_depth; } sync::transition(cmd, m_mask_state, sync::Usage::stencil_attachment); @@ -521,7 +519,7 @@ void SelectionOutline::recordResolve(vk::CommandBuffer cmd, uint32_t frame_index } const std::array wanted {**m_mask_sampled, history.view(), target.view()}; - if (m_bound_outline[frame_index] != wanted) { + if (m_bound_outline.update(frame_index, wanted)) { DescriptorWriter writer; const vk::DescriptorSet set = *m_outline_sets[frame_index]; const auto type = vk::DescriptorType::eCombinedImageSampler; @@ -529,7 +527,6 @@ void SelectionOutline::recordResolve(vk::CommandBuffer cmd, uint32_t frame_index writer.image(set, 1, type, *m_sampler, wanted[1], vk::ImageLayout::eShaderReadOnlyOptimal); writer.image(set, 2, type, *m_sampler, wanted[2], vk::ImageLayout::eShaderReadOnlyOptimal); writer.flush(m_core->getDevice()); - m_bound_outline[frame_index] = wanted; } const OutlinePush push { diff --git a/engine/src/toast/renderer/passes/debug/selection_outline.hpp b/engine/src/toast/renderer/passes/debug/selection_outline.hpp index 3167c3b2a..dba7b0629 100644 --- a/engine/src/toast/renderer/passes/debug/selection_outline.hpp +++ b/engine/src/toast/renderer/passes/debug/selection_outline.hpp @@ -6,6 +6,7 @@ #pragma once +#include "toast/renderer/core/descriptor_cache.hpp" #include "toast/renderer/core/gpu_sync.hpp" #include "toast/renderer/core/vulkan_common.hpp" #include "toast/renderer/resources/post_process_target.hpp" @@ -82,15 +83,15 @@ class SelectionOutline { std::vector m_mask_sets; std::vector m_voxel_sets; std::vector m_volume_buffers; - std::vector m_bound_depth; - std::vector> m_bound_storage; + DescriptorCache m_bound_depth; + DescriptorCache> m_bound_storage; ShaderLayout m_outline_layout; VulkanPipeline m_resolve_pipeline; VulkanPipeline m_composite_pipeline; std::vector m_outline_sets; /// Mask history and outline views each set was written with - std::vector> m_bound_outline; + DescriptorCache> m_bound_outline; /// Ping pong where m_write is the one this frame resolves into std::array m_coverage; diff --git a/engine/src/toast/renderer/passes/geometry/debris_pass.cpp b/engine/src/toast/renderer/passes/geometry/debris_pass.cpp index 37170c7b5..62a4de02e 100644 --- a/engine/src/toast/renderer/passes/geometry/debris_pass.cpp +++ b/engine/src/toast/renderer/passes/geometry/debris_pass.cpp @@ -84,7 +84,7 @@ DebrisPass::DebrisPass( m_sets.push_back(std::move(sets[0])); setDebugName(core, *m_sets.back(), std::format("DebrisPass Set[{}]", i)); } - m_bound.assign(VulkanRenderer::k_frames_in_flight, {}); + m_bound.resize(VulkanRenderer::k_frames_in_flight); } auto DebrisPass::prepare(vk::CommandBuffer cmd, uint32_t frame_index) -> bool { @@ -107,7 +107,7 @@ auto DebrisPass::prepare(vk::CommandBuffer cmd, uint32_t frame_index) -> bool { return false; } - if (m_bound[frame_index] != std::array {particles, list}) { + if (m_bound.update(frame_index, std::array {particles, list})) { const vk::DescriptorBufferInfo particle_info(particles, 0, VK_WHOLE_SIZE); const vk::DescriptorBufferInfo list_info(list, 0, VK_WHOLE_SIZE); const std::array writes { @@ -119,7 +119,6 @@ auto DebrisPass::prepare(vk::CommandBuffer cmd, uint32_t frame_index) -> bool { ), }; m_core->getDevice().updateDescriptorSets(writes, {}); - m_bound[frame_index] = {particles, list}; } m_scene_sets.updateTlas(frame_index); diff --git a/engine/src/toast/renderer/passes/geometry/debris_pass.hpp b/engine/src/toast/renderer/passes/geometry/debris_pass.hpp index a9fb08061..316b947a4 100644 --- a/engine/src/toast/renderer/passes/geometry/debris_pass.hpp +++ b/engine/src/toast/renderer/passes/geometry/debris_pass.hpp @@ -6,6 +6,7 @@ #pragma once +#include "toast/renderer/core/descriptor_cache.hpp" #include "toast/renderer/passes/render_pass_base.hpp" #include "toast/renderer/resources/scene_descriptor_set.hpp" #include "toast/renderer/shaders/shader_layout.hpp" @@ -64,7 +65,7 @@ class DebrisPass : public IRenderPass { VulkanPipeline m_glass_pipeline; SceneDescriptorSets m_scene_sets; std::vector m_sets; - std::vector> m_bound; + DescriptorCache> m_bound; vk::Buffer m_args = nullptr; PushConstants m_push; }; diff --git a/engine/src/toast/renderer/passes/geometry/voxel_pass.cpp b/engine/src/toast/renderer/passes/geometry/voxel_pass.cpp index 6ac3d9ded..44d83c321 100644 --- a/engine/src/toast/renderer/passes/geometry/voxel_pass.cpp +++ b/engine/src/toast/renderer/passes/geometry/voxel_pass.cpp @@ -566,7 +566,7 @@ void VoxelPass::createLighting(const VulkanCore& core, vk::Format scene_format, const vk::DescriptorPool pool = VulkanRenderer::instance->getDescriptorPoolHandle(); const vk::DescriptorSetLayout gbuffer_layout = *layouts[k_gbuffer_set]; m_gbuffer_sets.clear(); - m_bound_gbuffer.assign(VulkanRenderer::k_frames_in_flight, {}); + m_bound_gbuffer.resize(VulkanRenderer::k_frames_in_flight); for (uint32_t i = 0; i < VulkanRenderer::k_frames_in_flight; ++i) { auto allocated = core.getDevice().allocateDescriptorSets(vk::DescriptorSetAllocateInfo(pool, 1, &gbuffer_layout)); m_gbuffer_sets.push_back(std::move(allocated[0])); @@ -626,6 +626,18 @@ void VoxelPass::createGlass(const VulkanCore& core, vk::Format scene_format, vk: config.depth_write = true; m_glass_surface_pipeline.rebuild(core, config); + config.debug_name = "VoxelGlass Mask"; + config.fragment_entry = "fragmentMask"; + config.color_format = vk::Format::eR8Unorm; + config.extra_color_formats.clear(); + config.write_color = true; + config.write_extra_color = false; + config.depth_test = true; + config.depth_write = false; + config.depth_compare = depth::k_closer_or_equal; + config.blend_preset = VulkanPipeline::BlendPreset::none; + m_glass_mask_pipeline.rebuild(core, config); + if (!dual_source) { TOAST_WARN("Render", "dualSrcBlend unsupported so voxel glass fades the background without tinting it"); } @@ -636,7 +648,7 @@ void VoxelPass::createGlass(const VulkanCore& core, vk::Format scene_format, vk: const vk::DescriptorSetLayout glass_layout = *layouts[k_storage_set]; m_glass_sets.clear(); m_glass_buffers.clear(); - m_bound_backdrop.assign(VulkanRenderer::k_frames_in_flight, {}); + m_bound_backdrop.resize(VulkanRenderer::k_frames_in_flight); for (uint32_t i = 0; i < VulkanRenderer::k_frames_in_flight; ++i) { vk::BufferCreateInfo buffer_ci {}; buffer_ci.size = sizeof(glm::uvec2) * k_max_glass_bricks; @@ -698,7 +710,7 @@ void VoxelPass::createDescriptors(const VulkanCore& core, const ShaderReflection const auto& device = core.getDevice(); m_storage_sets.clear(); - m_bound_storage.assign(VulkanRenderer::k_frames_in_flight, nullptr); + m_bound_storage.resize(VulkanRenderer::k_frames_in_flight); for (uint32_t i = 0; i < VulkanRenderer::k_frames_in_flight; ++i) { const vk::DescriptorSetLayout storage_layout = *layouts[k_storage_set]; @@ -747,7 +759,6 @@ void VoxelPass::bindStorage(uint32_t frame_index, const std::shared_ptrgetDevice(), *m_lighting_storage_sets[frame_index], *storage); } - m_bound_storage[frame_index] = storage; } void VoxelPass::writeAmbientGrid(uint32_t frame_index, std::span bounds) { @@ -847,7 +858,7 @@ auto VoxelPass::prepare(uint32_t frame_index) -> bool { return false; } - if (m_bound_storage[frame_index] != frame->voxel_storage) { + if (m_bound_storage.update(frame_index, frame->voxel_storage)) { bindStorage(frame_index, frame->voxel_storage); } @@ -966,7 +977,7 @@ auto VoxelPass::prepare(uint32_t frame_index) -> bool { VulkanRenderer::instance->getGlassBackdropView(), VulkanRenderer::instance->getGlassBackdropDepthView() }; if (frame_index < m_glass_sets.size() && frame_index < m_bound_backdrop.size() && backdrop[0] && backdrop[1] && - m_bound_backdrop[frame_index] != backdrop) { + m_bound_backdrop.update(frame_index, backdrop)) { DescriptorWriter writer; writer.image( *m_glass_sets[frame_index], @@ -985,7 +996,6 @@ auto VoxelPass::prepare(uint32_t frame_index) -> bool { vk::ImageLayout::eDepthReadOnlyOptimal ); writer.flush(m_core->getDevice()); - m_bound_backdrop[frame_index] = backdrop; } // Before any scope of this frame binds the set since updating a bound set invalidates the command buffer @@ -1423,7 +1433,7 @@ void VoxelPass::recordLighting(vk::CommandBuffer cmd, uint32_t frame_index, vk:: } // Safe since the fence of this slot was waited on - if (m_bound_gbuffer[frame_index] != views) { + if (m_bound_gbuffer.update(frame_index, views)) { DescriptorWriter writer; for (uint32_t binding = 0; binding < views.size(); ++binding) { writer.image( @@ -1436,7 +1446,6 @@ void VoxelPass::recordLighting(vk::CommandBuffer cmd, uint32_t frame_index, vk:: ); } writer.flush(m_core->getDevice()); - m_bound_gbuffer[frame_index] = views; } m_lighting_scene_sets.updateTlas(frame_index); @@ -1566,6 +1575,11 @@ void VoxelPass::recordGlassSurfaces(vk::CommandBuffer cmd, uint32_t frame_index) recordGlassBricks(cmd, frame_index, m_glass_surface_pipeline, 0, m_glass_count); } +void VoxelPass::recordGlassMask(vk::CommandBuffer cmd, uint32_t frame_index) { + ZoneScoped; + recordGlassBricks(cmd, frame_index, m_glass_mask_pipeline, 0, m_glass_count); +} + void VoxelPass::recordGlassBricks( vk::CommandBuffer cmd, uint32_t frame_index, const VulkanPipeline& pipeline, uint32_t first, uint32_t count ) { @@ -1598,8 +1612,7 @@ void VoxelPass::recordGlassBricks( auto VoxelPass::refractsGlass() const -> bool { const auto* renderer = VulkanRenderer::instance; - if (m_glass_count == 0 || !m_glass_dual_source || renderer->voxelGlassRefraction() <= 0.0f || - !std::ranges::all_of(m_bound_backdrop, [](const auto& views) { return views[0] && views[1]; })) { + if (m_glass_count == 0 || !m_glass_dual_source || renderer->voxelGlassRefraction() <= 0.0f || !m_bound_backdrop.allCurrent()) { return false; } // Draws are far to near and a brick centre sits up to a diagonal past its voxels @@ -1707,7 +1720,7 @@ void VoxelPass::createDenoiseTargets(vk::Extent2D extent) { ); } } - m_denoise_bound.assign(m_denoise_sets.size(), {}); + m_denoise_bound.resize(m_denoise_sets.size()); m_denoise_valid = false; } @@ -1732,7 +1745,7 @@ void VoxelPass::bindDenoise(vk::CommandBuffer cmd, uint32_t frame_index, const V }; // Safe since the fence of this slot was waited on - if (m_denoise_bound[set_index] != views) { + if (m_denoise_bound.update(set_index, views)) { DescriptorWriter writer; for (uint32_t binding = 0; binding < views.size(); ++binding) { const bool history = binding == 6 || binding == 7; @@ -1746,7 +1759,6 @@ void VoxelPass::bindDenoise(vk::CommandBuffer cmd, uint32_t frame_index, const V ); } writer.flush(m_core->getDevice()); - m_denoise_bound[set_index] = views; } const vk::Extent2D extent = m_denoise_history[0][0].extent(); @@ -1872,7 +1884,6 @@ void VoxelPass::recordMarchedComposite(vk::CommandBuffer cmd, uint32_t frame_ind } void VoxelPass::onTargetsRecreated() { - std::ranges::fill(m_bound_gbuffer, std::array {}); if (!m_denoise_sets.empty()) { createDenoiseTargets(VulkanRenderer::instance->renderExtent()); } diff --git a/engine/src/toast/renderer/passes/geometry/voxel_pass.hpp b/engine/src/toast/renderer/passes/geometry/voxel_pass.hpp index e34a6db54..ab0455767 100644 --- a/engine/src/toast/renderer/passes/geometry/voxel_pass.hpp +++ b/engine/src/toast/renderer/passes/geometry/voxel_pass.hpp @@ -6,6 +6,7 @@ #pragma once +#include "toast/renderer/core/descriptor_cache.hpp" #include "toast/renderer/passes/render_pass_base.hpp" #include "toast/renderer/resources/hiz_pyramid.hpp" #include "toast/renderer/resources/post_process_target.hpp" @@ -102,6 +103,8 @@ class VoxelPass : public IRenderPass { /// After every blended draw void recordGlassSurfaces(vk::CommandBuffer cmd, uint32_t frame_index); + void recordGlassMask(vk::CommandBuffer cmd, uint32_t frame_index); + /// Whether the backdrop must be copied before glass draws [[nodiscard]] auto refractsGlass() const -> bool; @@ -305,7 +308,7 @@ class VoxelPass : public IRenderPass { std::vector m_instance_buffers; - std::vector> m_bound_storage; + DescriptorCache> m_bound_storage; std::vector m_draws; @@ -367,7 +370,7 @@ class VoxelPass : public IRenderPass { uint32_t m_shadow_instance_count = 0; /// Albedo face normal material and depth last written into each set - std::vector> m_bound_gbuffer; + DescriptorCache> m_bound_gbuffer; VulkanPipeline m_spatial_pipeline; VulkanPipeline m_spatial_opaque_pipeline; VulkanPipeline m_marched_pipeline; @@ -380,7 +383,7 @@ class VoxelPass : public IRenderPass { vk::raii::Sampler m_backdrop_sampler = nullptr; vk::raii::Sampler m_backdrop_depth_sampler = nullptr; /// Backdrop colour and depth each glass set was written with - std::vector> m_bound_backdrop; + DescriptorCache> m_bound_backdrop; /// The push the lighting draw used so the spatial draw matches it LightingPushConstants m_lighting_push; @@ -416,7 +419,7 @@ class VoxelPass : public IRenderPass { vk::raii::Sampler m_linear_sampler = nullptr; /// Per frame in flight then per history parity std::vector m_denoise_sets; - std::vector> m_denoise_bound; + DescriptorCache> m_denoise_bound; /// [term][parity] where the temporal pass writes the parity and reads the other std::array, 2> m_denoise_history; uint32_t m_denoise_parity = 0; @@ -443,6 +446,7 @@ class VoxelPass : public IRenderPass { ShaderLayout m_glass_layout; VulkanPipeline m_glass_pipeline; VulkanPipeline m_glass_surface_pipeline; + VulkanPipeline m_glass_mask_pipeline; SceneDescriptorSets m_glass_scene_sets; std::vector m_glass_sets; /// Instance index and brick grid index per drawn glass brick diff --git a/engine/src/toast/renderer/passes/lighting/gi_pass.cpp b/engine/src/toast/renderer/passes/lighting/gi_pass.cpp index 53d57d33c..6d31a330e 100644 --- a/engine/src/toast/renderer/passes/lighting/gi_pass.cpp +++ b/engine/src/toast/renderer/passes/lighting/gi_pass.cpp @@ -667,11 +667,11 @@ auto GiPass::createPipelines(const VulkanCore& core) -> bool { writer.buffer(merge_set, k_merge_dirty_binding, storage, *m_dirty[i]); writer.flush(core.getDevice()); } - m_probe_bound.assign(VulkanRenderer::k_frames_in_flight, {}); - m_debug_bound.assign(VulkanRenderer::k_frames_in_flight, {}); - m_ray_bound.assign(VulkanRenderer::k_frames_in_flight, {}); + m_probe_bound.resize(VulkanRenderer::k_frames_in_flight); + m_debug_bound.resize(VulkanRenderer::k_frames_in_flight); + m_ray_bound.resize(VulkanRenderer::k_frames_in_flight); createChange(core); - m_ray_storage_bound.assign(VulkanRenderer::k_frames_in_flight, nullptr); + m_ray_storage_bound.resize(VulkanRenderer::k_frames_in_flight); if (trace == nullptr) { TOAST_WARN("Render", "GiPass found no voxel trace scene so probes get no rays"); } @@ -687,9 +687,9 @@ void GiPass::onResize(vk::Extent2D extent) { m_extent = extent; if (m_core != nullptr) { m_debug_target.create(*m_core, extent, m_scene_format, "GiPass Debug"); - std::ranges::fill(m_probe_bound, std::array {}); - std::ranges::fill(m_debug_bound, std::array {}); - std::ranges::fill(m_ray_bound, std::array {}); + m_probe_bound.invalidate(); + m_debug_bound.invalidate(); + m_ray_bound.invalidate(); createChange(*m_core); } } @@ -917,7 +917,7 @@ void GiPass::bindProbeSet(uint32_t frame_index) { const vk::ImageView depth_view = VulkanRenderer::instance->getOpaqueDepthView(); const vk::ImageView normal_view = VulkanRenderer::instance->getOpaqueNormalView(); const std::array wanted {depth_view, normal_view}; - if (m_probe_bound[frame_index] == wanted) { + if (!m_probe_bound.update(frame_index, wanted)) { return; } DescriptorWriter writer; @@ -938,7 +938,6 @@ void GiPass::bindProbeSet(uint32_t frame_index) { vk::ImageLayout::eShaderReadOnlyOptimal ); writer.flush(m_core->getDevice()); - m_probe_bound[frame_index] = wanted; } auto GiPass::bindRaySets(uint32_t frame_index, vk::ImageView scene_view) -> bool { @@ -948,15 +947,14 @@ auto GiPass::bindRaySets(uint32_t frame_index, vk::ImageView scene_view) -> bool return false; } // Safe since the fence of this slot was waited on - if (m_ray_storage_bound[frame_index] != frame->voxel_storage) { + if (m_ray_storage_bound.update(frame_index, frame->voxel_storage)) { writeVoxelStorageDescriptors(m_core->getDevice(), *m_ray_storage_sets[frame_index], *frame->voxel_storage); - m_ray_storage_bound[frame_index] = frame->voxel_storage; } const vk::ImageView depth_view = VulkanRenderer::instance->getOpaqueDepthView(); const vk::ImageView normal_view = VulkanRenderer::instance->getOpaqueNormalView(); const std::array wanted {depth_view, normal_view, scene_view}; - if (m_ray_bound[frame_index] != wanted) { + if (m_ray_bound.update(frame_index, wanted)) { DescriptorWriter writer; writer.image( *m_ray_sets[frame_index], @@ -983,7 +981,6 @@ auto GiPass::bindRaySets(uint32_t frame_index, vk::ImageView scene_view) -> bool vk::ImageLayout::eShaderReadOnlyOptimal ); writer.flush(m_core->getDevice()); - m_ray_bound[frame_index] = wanted; } m_ray_scene_sets.updateTlas(frame_index); return true; @@ -1287,7 +1284,7 @@ auto GiPass::recordDebug(vk::CommandBuffer cmd, uint32_t frame_index, vk::ImageV const vk::ImageView depth_view = VulkanRenderer::instance->getOpaqueDepthView(); const vk::ImageView normal_view = VulkanRenderer::instance->getOpaqueNormalView(); const std::array wanted {source_view, depth_view, normal_view}; - if (m_debug_bound[frame_index] != wanted) { + if (m_debug_bound.update(frame_index, wanted)) { DescriptorWriter writer; writer.image( *m_debug_sets[frame_index], @@ -1314,7 +1311,6 @@ auto GiPass::recordDebug(vk::CommandBuffer cmd, uint32_t frame_index, vk::ImageV vk::ImageLayout::eShaderReadOnlyOptimal ); writer.flush(m_core->getDevice()); - m_debug_bound[frame_index] = wanted; } const vk::PipelineLayout layout = *m_debug_layout.getPipelineLayout(); diff --git a/engine/src/toast/renderer/passes/lighting/gi_pass.hpp b/engine/src/toast/renderer/passes/lighting/gi_pass.hpp index 7bb94322e..720e2694f 100644 --- a/engine/src/toast/renderer/passes/lighting/gi_pass.hpp +++ b/engine/src/toast/renderer/passes/lighting/gi_pass.hpp @@ -4,6 +4,7 @@ #pragma once +#include "toast/renderer/core/descriptor_cache.hpp" #include "toast/renderer/core/gpu_sync.hpp" #include "toast/renderer/core/vulkan_common.hpp" #include "toast/renderer/passes/post_process_pass_base.hpp" @@ -227,9 +228,9 @@ class GiPass : public IPostProcessPass { VulkanPipeline m_change_pipeline; SceneDescriptorSets m_ray_scene_sets; std::vector m_ray_storage_sets; - std::vector> m_ray_storage_bound; + DescriptorCache> m_ray_storage_bound; std::vector m_ray_sets; - std::vector> m_ray_bound; + DescriptorCache> m_ray_bound; /// Reflection keeps gVoxelInstances only when the trace code reads it bool m_ray_instances_bound = false; @@ -304,9 +305,9 @@ class GiPass : public IPostProcessPass { float m_point_share = 0.5f; std::vector m_probe_sets; - std::vector> m_probe_bound; + DescriptorCache> m_probe_bound; std::vector m_debug_sets; - std::vector> m_debug_bound; + DescriptorCache> m_debug_bound; bool m_published_valid = false; uint32_t m_frame = 0; diff --git a/engine/src/toast/renderer/passes/lighting/shadow_pass.cpp b/engine/src/toast/renderer/passes/lighting/shadow_pass.cpp index 29d72c3d2..9f2e086f2 100644 --- a/engine/src/toast/renderer/passes/lighting/shadow_pass.cpp +++ b/engine/src/toast/renderer/passes/lighting/shadow_pass.cpp @@ -425,7 +425,7 @@ void ShadowPass::createVoxelResources(const VulkanCore& core) { m_voxel_shadow_sets.clear(); m_voxel_storage_sets.clear(); m_voxel_instance_buffers.clear(); - m_voxel_bound_storage.assign(VulkanRenderer::k_frames_in_flight, nullptr); + m_voxel_bound_storage.resize(VulkanRenderer::k_frames_in_flight); for (uint32_t i = 0; i < VulkanRenderer::k_frames_in_flight; ++i) { vk::BufferCreateInfo buffer_ci {}; @@ -573,10 +573,9 @@ auto ShadowPass::prepareVoxels(uint32_t frame_index) -> uint32_t { return 0; } - if (m_voxel_bound_storage[frame_index] != storage) { + if (m_voxel_bound_storage.update(frame_index, storage)) { // Safe since the fence of this slot was waited on writeVoxelStorageDescriptors(m_core->getDevice(), *m_voxel_storage_sets[frame_index], *storage); - m_voxel_bound_storage[frame_index] = storage; } const auto& allocation = m_voxel_instance_buffers[frame_index].getAllocation(); diff --git a/engine/src/toast/renderer/passes/lighting/shadow_pass.hpp b/engine/src/toast/renderer/passes/lighting/shadow_pass.hpp index c7a13e06c..b425be1a1 100644 --- a/engine/src/toast/renderer/passes/lighting/shadow_pass.hpp +++ b/engine/src/toast/renderer/passes/lighting/shadow_pass.hpp @@ -6,6 +6,7 @@ #pragma once +#include "toast/renderer/core/descriptor_cache.hpp" #include "toast/renderer/core/vulkan_common.hpp" #include "toast/renderer/lighting/shadow_constants.hpp" #include "toast/renderer/passes/render_pass_base.hpp" @@ -223,7 +224,7 @@ class ShadowPass : public IRenderPass { std::vector m_voxel_shadow_sets; std::vector m_voxel_storage_sets; std::vector m_voxel_instance_buffers; - std::vector> m_voxel_bound_storage; + DescriptorCache> m_voxel_bound_storage; bool m_voxels_ready = false; /// Depth units of the rasterizer constant bias since SV_Depth skips it diff --git a/engine/src/toast/renderer/passes/lighting/ssao_pass.cpp b/engine/src/toast/renderer/passes/lighting/ssao_pass.cpp index b3ed0db0d..8ed916fe9 100644 --- a/engine/src/toast/renderer/passes/lighting/ssao_pass.cpp +++ b/engine/src/toast/renderer/passes/lighting/ssao_pass.cpp @@ -83,7 +83,7 @@ void SsaoPass::createResources(const VulkanCore& core) { const vk::DescriptorPool pool = VulkanRenderer::instance->getDescriptorPoolHandle(); m_descriptor_sets.clear(); - m_bound_views.assign(VulkanRenderer::k_frames_in_flight, vk::ImageView {}); + m_bound_views.resize(VulkanRenderer::k_frames_in_flight); for (uint32_t i = 0; i < VulkanRenderer::k_frames_in_flight; ++i) { const vk::DescriptorSetAllocateInfo alloc_info(pool, 1, &set_layout); auto allocated = device.allocateDescriptorSets(alloc_info); @@ -95,7 +95,7 @@ void SsaoPass::createResources(const VulkanCore& core) { void SsaoPass::createTargets(const VulkanCore& core, vk::Extent2D extent) { m_target.create(core, extent, m_scene_format, "SsaoPass"); m_occlusion_target.create(core, PostProcessTarget::halfExtent(extent), k_occlusion_format, "SsaoPass Occlusion"); - std::ranges::fill(m_bound_views, vk::ImageView {}); + m_bound_views.invalidate(); } void SsaoPass::onResize(vk::Extent2D extent) { @@ -118,7 +118,7 @@ auto SsaoPass::record(vk::CommandBuffer cmd, uint32_t frame_index, vk::ImageView return source_view; } - if (m_bound_views[frame_index] != source_view) { + if (m_bound_views.update(frame_index, source_view)) { const std::array image_infos { vk::DescriptorImageInfo(*m_sampler, source_view, vk::ImageLayout::eShaderReadOnlyOptimal), vk::DescriptorImageInfo(*m_point_sampler, depth_view, vk::ImageLayout::eDepthReadOnlyOptimal), @@ -135,7 +135,6 @@ auto SsaoPass::record(vk::CommandBuffer cmd, uint32_t frame_index, vk::ImageView ); } m_core->getDevice().updateDescriptorSets(writes, {}); - m_bound_views[frame_index] = source_view; } const auto* frame = VulkanRenderer::instance->renderingFrame(); diff --git a/engine/src/toast/renderer/passes/lighting/ssao_pass.hpp b/engine/src/toast/renderer/passes/lighting/ssao_pass.hpp index d3db983a5..5b8533e94 100644 --- a/engine/src/toast/renderer/passes/lighting/ssao_pass.hpp +++ b/engine/src/toast/renderer/passes/lighting/ssao_pass.hpp @@ -6,6 +6,7 @@ #pragma once +#include "toast/renderer/core/descriptor_cache.hpp" #include "toast/renderer/core/vulkan_common.hpp" #include "toast/renderer/passes/post_process_pass_base.hpp" #include "toast/renderer/resources/post_process_target.hpp" @@ -62,7 +63,7 @@ class SsaoPass : public IPostProcessPass { vk::raii::Sampler m_point_sampler = nullptr; std::vector m_descriptor_sets; - std::vector m_bound_views; + DescriptorCache m_bound_views; PostProcessTarget m_occlusion_target; PostProcessTarget m_target; diff --git a/engine/src/toast/renderer/passes/lighting/ssr_pass.cpp b/engine/src/toast/renderer/passes/lighting/ssr_pass.cpp index c2a7215c7..951eeb882 100644 --- a/engine/src/toast/renderer/passes/lighting/ssr_pass.cpp +++ b/engine/src/toast/renderer/passes/lighting/ssr_pass.cpp @@ -92,7 +92,7 @@ void SsrPass::createResources(const VulkanCore& core) { const vk::DescriptorPool pool = VulkanRenderer::instance->getDescriptorPoolHandle(); m_descriptor_sets.clear(); - m_bound_views.assign(VulkanRenderer::k_frames_in_flight * 2, {}); + m_bound_views.resize(VulkanRenderer::k_frames_in_flight * 2); for (uint32_t i = 0; i < VulkanRenderer::k_frames_in_flight * 2; ++i) { const vk::DescriptorSetAllocateInfo alloc_info(pool, 1, &set_layout); auto allocated = device.allocateDescriptorSets(alloc_info); @@ -108,7 +108,7 @@ void SsrPass::createTargets(const VulkanCore& core, vk::Extent2D extent) { m_resolve_target.create(core, half, k_reflection_format, "SsrPass Resolve"); m_history[0].create(core, half, k_reflection_format, "SsrPass History0"); m_history[1].create(core, half, k_reflection_format, "SsrPass History1"); - std::ranges::fill(m_bound_views, std::array {}); + m_bound_views.invalidate(); m_history_valid = false; } @@ -149,7 +149,7 @@ auto SsrPass::record(vk::CommandBuffer cmd, uint32_t frame_index, vk::ImageView const vk::ImageView previous_view = VulkanRenderer::instance->previousResolvedColour(); const std::array wanted {source_view, previous_view ? previous_view : source_view, depth_view, normal_view}; - if (m_bound_views[set_index] != wanted) { + if (m_bound_views.update(set_index, wanted)) { // Point sampled except the colours since interpolated depth or normals invent surfaces const std::array image_infos { vk::DescriptorImageInfo(*m_sampler, source_view, vk::ImageLayout::eShaderReadOnlyOptimal), @@ -171,7 +171,6 @@ auto SsrPass::record(vk::CommandBuffer cmd, uint32_t frame_index, vk::ImageView vk::WriteDescriptorSet(set, binding, 0, 1, vk::DescriptorType::eCombinedImageSampler, &image_infos[binding]); } m_core->getDevice().updateDescriptorSets(writes, {}); - m_bound_views[set_index] = wanted; } const bool history_valid = m_history_valid && sequence == m_last_sequence + 1; diff --git a/engine/src/toast/renderer/passes/lighting/ssr_pass.hpp b/engine/src/toast/renderer/passes/lighting/ssr_pass.hpp index b05db3e79..44375a6d7 100644 --- a/engine/src/toast/renderer/passes/lighting/ssr_pass.hpp +++ b/engine/src/toast/renderer/passes/lighting/ssr_pass.hpp @@ -6,6 +6,7 @@ #pragma once +#include "toast/renderer/core/descriptor_cache.hpp" #include "toast/renderer/core/vulkan_common.hpp" #include "toast/renderer/passes/post_process_pass_base.hpp" #include "toast/renderer/resources/post_process_target.hpp" @@ -72,7 +73,7 @@ class SsrPass : public IPostProcessPass { /// Per frame in flight then per history parity std::vector m_descriptor_sets; /// Source then previous resolve last written into each set - std::vector> m_bound_views; + DescriptorCache> m_bound_views; PostProcessTarget m_hit_target; PostProcessTarget m_resolve_target; diff --git a/engine/src/toast/renderer/passes/lighting/traced_shadow_pass.cpp b/engine/src/toast/renderer/passes/lighting/traced_shadow_pass.cpp index 6e5d16d2a..211883a9d 100644 --- a/engine/src/toast/renderer/passes/lighting/traced_shadow_pass.cpp +++ b/engine/src/toast/renderer/passes/lighting/traced_shadow_pass.cpp @@ -76,8 +76,7 @@ void TracedShadowPass::createResources(const VulkanCore& core) { const vk::DescriptorPool pool = VulkanRenderer::instance->getDescriptorPoolHandle(); m_descriptor_sets.clear(); - m_bound_views.assign(VulkanRenderer::k_frames_in_flight, vk::ImageView {}); - m_bound_acceleration_structures.assign(VulkanRenderer::k_frames_in_flight, {}); + m_bound.resize(VulkanRenderer::k_frames_in_flight); for (uint32_t i = 0; i < VulkanRenderer::k_frames_in_flight; ++i) { const vk::DescriptorSetAllocateInfo alloc_info(pool, 1, &set_layout); auto allocated = device.allocateDescriptorSets(alloc_info); @@ -88,7 +87,7 @@ void TracedShadowPass::createResources(const VulkanCore& core) { void TracedShadowPass::createTarget(const VulkanCore& core, vk::Extent2D extent) { m_target.create(core, extent, m_scene_format, "TracedShadowPass"); - std::ranges::fill(m_bound_views, vk::ImageView {}); + m_bound.invalidate(); } void TracedShadowPass::onResize(vk::Extent2D extent) { @@ -122,8 +121,7 @@ auto TracedShadowPass::record(vk::CommandBuffer cmd, uint32_t frame_index, vk::I return source_view; } - const std::pair bound_tlas {tlas, scene->getAccelerationStructureGeneration(frame_index)}; - if (m_bound_views[frame_index] != source_view || m_bound_acceleration_structures[frame_index] != bound_tlas) { + if (m_bound.update(frame_index, {source_view, tlas, scene->getAccelerationStructureGeneration(frame_index)})) { constexpr auto k_sampler = vk::DescriptorType::eCombinedImageSampler; const vk::DescriptorSet set = *m_descriptor_sets[frame_index]; @@ -133,8 +131,6 @@ auto TracedShadowPass::record(vk::CommandBuffer cmd, uint32_t frame_index, vk::I .image(set, 2, k_sampler, *m_point_sampler, normal_view, vk::ImageLayout::eShaderReadOnlyOptimal) .accelerationStructure(set, 3, tlas); writer.flush(m_core->getDevice()); - m_bound_views[frame_index] = source_view; - m_bound_acceleration_structures[frame_index] = bound_tlas; } m_target.beginScope(cmd); diff --git a/engine/src/toast/renderer/passes/lighting/traced_shadow_pass.hpp b/engine/src/toast/renderer/passes/lighting/traced_shadow_pass.hpp index 6d5c8c9fb..0a1fff153 100644 --- a/engine/src/toast/renderer/passes/lighting/traced_shadow_pass.hpp +++ b/engine/src/toast/renderer/passes/lighting/traced_shadow_pass.hpp @@ -6,6 +6,7 @@ #pragma once +#include "toast/renderer/core/descriptor_cache.hpp" #include "toast/renderer/core/vulkan_common.hpp" #include "toast/renderer/passes/post_process_pass_base.hpp" #include "toast/renderer/resources/post_process_target.hpp" @@ -14,6 +15,7 @@ #include #include +#include #include #include @@ -55,9 +57,7 @@ class TracedShadowPass : public IPostProcessPass { vk::raii::Sampler m_point_sampler = nullptr; std::vector m_descriptor_sets; - std::vector m_bound_views; - /// Handle plus generation since a recreated structure can reuse a destroyed handle value - std::vector> m_bound_acceleration_structures; + DescriptorCache> m_bound; PostProcessTarget m_target; }; diff --git a/engine/src/toast/renderer/passes/lighting/traced_specular_pass.cpp b/engine/src/toast/renderer/passes/lighting/traced_specular_pass.cpp index d59f6468c..5df717f19 100644 --- a/engine/src/toast/renderer/passes/lighting/traced_specular_pass.cpp +++ b/engine/src/toast/renderer/passes/lighting/traced_specular_pass.cpp @@ -145,8 +145,8 @@ void TracedSpecularPass::createSets(const VulkanCore& core) { } } writer.flush(device); - m_storage_bound.assign(m_storage_sets.size(), nullptr); - m_image_bound.assign(m_image_sets.size(), {}); + m_storage_bound.resize(m_storage_sets.size()); + m_image_bound.resize(m_image_sets.size()); } void TracedSpecularPass::createTargets(const VulkanCore& core, vk::Extent2D extent) { @@ -157,7 +157,7 @@ void TracedSpecularPass::createTargets(const VulkanCore& core, vk::Extent2D exte m_resolved.create(core, half, k_trace_format, "TracedSpecular Resolved"); m_history[0].create(core, half, k_trace_format, "TracedSpecular History0"); m_history[1].create(core, half, k_trace_format, "TracedSpecular History1"); - std::ranges::fill(m_image_bound, std::array {}); + m_image_bound.invalidate(); m_history_valid = false; } @@ -182,9 +182,8 @@ auto TracedSpecularPass::record(vk::CommandBuffer cmd, uint32_t frame_index, vk: } // Safe since the fence of this slot was waited on - if (m_storage_bound[frame_index] != frame->voxel_storage) { + if (m_storage_bound.update(frame_index, frame->voxel_storage)) { writeVoxelStorageDescriptors(m_core->getDevice(), *m_storage_sets[frame_index], *frame->voxel_storage); - m_storage_bound[frame_index] = frame->voxel_storage; } const PostProcessTarget& history_write = m_history[m_parity]; @@ -210,7 +209,7 @@ auto TracedSpecularPass::record(vk::CommandBuffer cmd, uint32_t frame_index, vk: if (std::ranges::any_of(views, [](vk::ImageView view) { return !view; })) { return source_view; } - if (m_image_bound[set_index] != views) { + if (m_image_bound.update(set_index, views)) { DescriptorWriter writer; for (uint32_t binding = 0; binding < k_image_bindings; ++binding) { writer.image( @@ -223,7 +222,6 @@ auto TracedSpecularPass::record(vk::CommandBuffer cmd, uint32_t frame_index, vk: ); } writer.flush(m_core->getDevice()); - m_image_bound[set_index] = views; } m_scene_sets.updateTlas(frame_index); diff --git a/engine/src/toast/renderer/passes/lighting/traced_specular_pass.hpp b/engine/src/toast/renderer/passes/lighting/traced_specular_pass.hpp index be4cefa5d..e74f165c0 100644 --- a/engine/src/toast/renderer/passes/lighting/traced_specular_pass.hpp +++ b/engine/src/toast/renderer/passes/lighting/traced_specular_pass.hpp @@ -6,6 +6,7 @@ #pragma once +#include "toast/renderer/core/descriptor_cache.hpp" #include "toast/renderer/core/vulkan_common.hpp" #include "toast/renderer/passes/post_process_pass_base.hpp" #include "toast/renderer/resources/post_process_target.hpp" @@ -78,10 +79,10 @@ class TracedSpecularPass : public IPostProcessPass { /// Per frame in flight std::vector m_storage_sets; - std::vector> m_storage_bound; + DescriptorCache> m_storage_bound; /// Per frame in flight then per history parity std::vector m_image_sets; - std::vector> m_image_bound; + DescriptorCache> m_image_bound; PostProcessTarget m_surface; PostProcessTarget m_trace; diff --git a/engine/src/toast/renderer/passes/lighting/volumetric_pass.cpp b/engine/src/toast/renderer/passes/lighting/volumetric_pass.cpp index d28764507..5fb34999f 100644 --- a/engine/src/toast/renderer/passes/lighting/volumetric_pass.cpp +++ b/engine/src/toast/renderer/passes/lighting/volumetric_pass.cpp @@ -173,8 +173,8 @@ VolumetricPass::VolumetricPass(const VulkanCore& core, vk::Format scene_format, } } writer.flush(device); - m_storage_bound.assign(m_storage_sets.size(), nullptr); - m_image_bound.assign(m_image_sets.size(), {}); + m_storage_bound.resize(m_storage_sets.size()); + m_image_bound.resize(m_image_sets.size()); createTargets(core, extent, resolveQuality().divisor); m_ready = m_ambient_pipeline.isReady() && m_scatter_pipeline.isReady() && m_temporal_pipeline.isReady() && @@ -208,7 +208,7 @@ void VolumetricPass::createTargets(const VulkanCore& core, vk::Extent2D extent, m_scatter.create(core, reduced, k_scatter_format, "Volumetrics Scatter"); m_history[0].create(core, reduced, k_scatter_format, "Volumetrics History0"); m_history[1].create(core, reduced, k_scatter_format, "Volumetrics History1"); - std::ranges::fill(m_image_bound, std::array {}); + m_image_bound.invalidate(); m_history_valid = false; } @@ -241,9 +241,8 @@ auto VolumetricPass::record(vk::CommandBuffer cmd, uint32_t frame_index, vk::Ima } // Safe since the fence of this slot was waited on - if (m_storage_bound[frame_index] != frame->voxel_storage) { + if (m_storage_bound.update(frame_index, frame->voxel_storage)) { writeVoxelStorageDescriptors(m_core->getDevice(), *m_storage_sets[frame_index], *frame->voxel_storage); - m_storage_bound[frame_index] = frame->voxel_storage; } const PostProcessTarget& history_write = m_history[m_parity]; @@ -261,7 +260,7 @@ auto VolumetricPass::record(vk::CommandBuffer cmd, uint32_t frame_index, vk::Ima if (std::ranges::any_of(views, [](vk::ImageView view) { return !view; })) { return source_view; } - if (m_image_bound[set_index] != views) { + if (m_image_bound.update(set_index, views)) { DescriptorWriter writer; for (uint32_t binding = 0; binding < k_image_bindings; ++binding) { writer.image( @@ -274,7 +273,6 @@ auto VolumetricPass::record(vk::CommandBuffer cmd, uint32_t frame_index, vk::Ima ); } writer.flush(m_core->getDevice()); - m_image_bound[set_index] = views; } m_scene_sets.updateTlas(frame_index); diff --git a/engine/src/toast/renderer/passes/lighting/volumetric_pass.hpp b/engine/src/toast/renderer/passes/lighting/volumetric_pass.hpp index 698099488..5e38d03ac 100644 --- a/engine/src/toast/renderer/passes/lighting/volumetric_pass.hpp +++ b/engine/src/toast/renderer/passes/lighting/volumetric_pass.hpp @@ -6,6 +6,7 @@ #pragma once +#include "toast/renderer/core/descriptor_cache.hpp" #include "toast/renderer/core/vulkan_common.hpp" #include "toast/renderer/passes/post_process_pass_base.hpp" #include "toast/renderer/resources/post_process_target.hpp" @@ -86,11 +87,11 @@ class VolumetricPass : public IPostProcessPass { std::vector m_storage_sets; /// volumetrics.slang gFogAmbient per frame in flight std::vector m_ambient; - std::vector> m_storage_bound; + DescriptorCache> m_storage_bound; /// Per frame in flight then per history parity std::vector m_image_sets; - std::vector> m_image_bound; + DescriptorCache> m_image_bound; PostProcessTarget m_scatter; /// The temporal pass reads one and writes the other diff --git a/engine/src/toast/renderer/passes/post/bloom_pass.cpp b/engine/src/toast/renderer/passes/post/bloom_pass.cpp index 1d6e2b716..2ed4b3262 100644 --- a/engine/src/toast/renderer/passes/post/bloom_pass.cpp +++ b/engine/src/toast/renderer/passes/post/bloom_pass.cpp @@ -152,20 +152,19 @@ void BloomPass::createTargets(const VulkanCore& core, vk::Extent2D extent) { TOAST_TRACE("Render", "BloomPass targets created: {} mips from {}x{}", m_mips.size(), extent.width, extent.height); } -void BloomPass::writeDescriptor(vk::DescriptorSet set, vk::ImageView source, vk::ImageView scene) { - std::array image_infos {}; - image_infos[0].imageLayout = vk::ImageLayout::eShaderReadOnlyOptimal; - image_infos[0].imageView = source; - image_infos[0].sampler = *m_sampler; - - image_infos[1].imageLayout = vk::ImageLayout::eShaderReadOnlyOptimal; - image_infos[1].imageView = scene ? scene : source; - image_infos[1].sampler = *m_sampler; - - const std::array writes { - vk::WriteDescriptorSet(set, 0, 0, 1, vk::DescriptorType::eCombinedImageSampler, image_infos.data()), - vk::WriteDescriptorSet(set, 1, 0, 1, vk::DescriptorType::eCombinedImageSampler, &image_infos[1]), - }; +void BloomPass::writeDescriptor( + vk::DescriptorSet set, vk::ImageView source, vk::ImageView scene, vk::ImageView backdrop, vk::ImageView mask +) { + const std::array views {source, scene ? scene : source, backdrop ? backdrop : source, mask}; + + std::array image_infos {}; + std::array writes {}; + for (uint32_t i = 0; i < 4; ++i) { + image_infos[i].imageLayout = vk::ImageLayout::eShaderReadOnlyOptimal; + image_infos[i].imageView = views[i]; + image_infos[i].sampler = *m_sampler; + writes[i] = vk::WriteDescriptorSet(set, i, 0, 1, vk::DescriptorType::eCombinedImageSampler, &image_infos[i]); + } m_core->getDevice().updateDescriptorSets(writes, {}); } @@ -206,23 +205,25 @@ void BloomPass::drawInto( auto BloomPass::record(vk::CommandBuffer cmd, uint32_t frame_index, vk::ImageView source_view) -> vk::ImageView { ZoneScoped; if (m_mips.empty() || !m_composite.view.has_value() || !m_composite_pipeline.isReady() || !source_view || - frame_index >= m_frame_sets.size()) { + frame_index >= m_frame_sets.size() || !m_glass_mask) { return source_view; } // Safe since the fence of this slot was waited on FrameSets& sets = m_frame_sets[frame_index]; - if (sets.bound_source != source_view) { - writeDescriptor(*sets.downsample[0], source_view, source_view); + if (sets.bound_source != source_view || sets.bound_backdrop != m_glass_backdrop || sets.bound_mask != m_glass_mask) { + writeDescriptor(*sets.downsample[0], source_view, source_view, m_glass_backdrop, m_glass_mask); for (size_t i = 1; i < m_mips.size(); ++i) { - writeDescriptor(*sets.downsample[i], **m_mips[i - 1].view, source_view); + writeDescriptor(*sets.downsample[i], **m_mips[i - 1].view, source_view, m_glass_backdrop, m_glass_mask); } for (size_t i = 0; i + 1 < m_mips.size(); ++i) { const size_t from = m_mips.size() - 1 - i; - writeDescriptor(*sets.upsample[i], **m_mips[from].view, source_view); + writeDescriptor(*sets.upsample[i], **m_mips[from].view, source_view, m_glass_backdrop, m_glass_mask); } - writeDescriptor(*sets.composite, **m_mips[0].view, source_view); + writeDescriptor(*sets.composite, **m_mips[0].view, source_view, m_glass_backdrop, m_glass_mask); sets.bound_source = source_view; + sets.bound_backdrop = m_glass_backdrop; + sets.bound_mask = m_glass_mask; } const auto* frame = VulkanRenderer::instance->renderingFrame(); @@ -275,4 +276,9 @@ void BloomPass::onResize(vk::Extent2D extent) { createTargets(*m_core, extent); } +void BloomPass::setGlassSources(vk::ImageView backdrop, vk::ImageView mask) { + m_glass_backdrop = backdrop; + m_glass_mask = mask; +} + } diff --git a/engine/src/toast/renderer/passes/post/bloom_pass.hpp b/engine/src/toast/renderer/passes/post/bloom_pass.hpp index 9cbd7b35b..4d8854987 100644 --- a/engine/src/toast/renderer/passes/post/bloom_pass.hpp +++ b/engine/src/toast/renderer/passes/post/bloom_pass.hpp @@ -36,6 +36,8 @@ class BloomPass : public IPostProcessPass { void onResize(vk::Extent2D extent) override; + void setGlassSources(vk::ImageView backdrop, vk::ImageView mask) override; + private: /// Mirrors bloom.slang BloomParams struct Params { @@ -57,7 +59,12 @@ class BloomPass : public IPostProcessPass { void createTargets(const VulkanCore& core, vk::Extent2D extent); void createPipelines(const VulkanCore& core); - void writeDescriptor(vk::DescriptorSet set, vk::ImageView source, vk::ImageView scene); + void writeDescriptor( + vk::DescriptorSet set, vk::ImageView source, vk::ImageView scene, vk::ImageView backdrop, vk::ImageView mask + ); + + vk::ImageView m_glass_backdrop = nullptr; + vk::ImageView m_glass_mask = nullptr; void drawInto( vk::CommandBuffer cmd, const VulkanPipeline& pipeline, vk::DescriptorSet set, const Mip& target, const Params& params, @@ -85,6 +92,8 @@ class BloomPass : public IPostProcessPass { std::vector upsample; vk::raii::DescriptorSet composite = nullptr; vk::ImageView bound_source = nullptr; + vk::ImageView bound_backdrop = nullptr; + vk::ImageView bound_mask = nullptr; }; std::vector m_frame_sets; diff --git a/engine/src/toast/renderer/passes/post/fxaa_pass.cpp b/engine/src/toast/renderer/passes/post/fxaa_pass.cpp index 3c4284898..9c31f0f25 100644 --- a/engine/src/toast/renderer/passes/post/fxaa_pass.cpp +++ b/engine/src/toast/renderer/passes/post/fxaa_pass.cpp @@ -59,7 +59,7 @@ void FxaaPass::createResources(const VulkanCore& core) { const vk::DescriptorPool pool = VulkanRenderer::instance->getDescriptorPoolHandle(); m_descriptor_sets.clear(); - m_bound_views.assign(VulkanRenderer::k_frames_in_flight, vk::ImageView {}); + m_bound_views.resize(VulkanRenderer::k_frames_in_flight); for (uint32_t i = 0; i < VulkanRenderer::k_frames_in_flight; ++i) { const vk::DescriptorSetAllocateInfo alloc_info(pool, 1, &set_layout); auto allocated = device.allocateDescriptorSets(alloc_info); @@ -70,7 +70,7 @@ void FxaaPass::createResources(const VulkanCore& core) { void FxaaPass::createTarget(const VulkanCore& core, vk::Extent2D extent) { m_target.create(core, extent, m_ldr_format, "FxaaPass"); - std::ranges::fill(m_bound_views, vk::ImageView {}); + m_bound_views.invalidate(); } void FxaaPass::onResize(vk::Extent2D extent) { @@ -95,7 +95,7 @@ auto FxaaPass::record(vk::CommandBuffer cmd, uint32_t frame_index, vk::ImageView return source_view; } - if (m_bound_views[frame_index] != source_view) { + if (m_bound_views.update(frame_index, source_view)) { vk::DescriptorImageInfo image_info {}; image_info.imageLayout = vk::ImageLayout::eShaderReadOnlyOptimal; image_info.imageView = source_view; @@ -105,7 +105,6 @@ auto FxaaPass::record(vk::CommandBuffer cmd, uint32_t frame_index, vk::ImageView *m_descriptor_sets[frame_index], 0, 0, 1, vk::DescriptorType::eCombinedImageSampler, &image_info ); m_core->getDevice().updateDescriptorSets(write, {}); - m_bound_views[frame_index] = source_view; } m_target.beginScope(cmd); diff --git a/engine/src/toast/renderer/passes/post/fxaa_pass.hpp b/engine/src/toast/renderer/passes/post/fxaa_pass.hpp index 4f7446108..5d89e2646 100644 --- a/engine/src/toast/renderer/passes/post/fxaa_pass.hpp +++ b/engine/src/toast/renderer/passes/post/fxaa_pass.hpp @@ -6,6 +6,7 @@ #pragma once +#include "toast/renderer/core/descriptor_cache.hpp" #include "toast/renderer/core/vulkan_common.hpp" #include "toast/renderer/passes/post_process_pass_base.hpp" #include "toast/renderer/resources/post_process_target.hpp" @@ -58,7 +59,7 @@ class FxaaPass : public IPostProcessPass { vk::raii::Sampler m_sampler = nullptr; std::vector m_descriptor_sets; - std::vector m_bound_views; + DescriptorCache m_bound_views; PostProcessTarget m_target; }; diff --git a/engine/src/toast/renderer/passes/post/motion_blur_pass.cpp b/engine/src/toast/renderer/passes/post/motion_blur_pass.cpp index e17423fda..54e37f105 100644 --- a/engine/src/toast/renderer/passes/post/motion_blur_pass.cpp +++ b/engine/src/toast/renderer/passes/post/motion_blur_pass.cpp @@ -65,7 +65,7 @@ void MotionBlurPass::createResources(const VulkanCore& core) { const vk::DescriptorPool pool = VulkanRenderer::instance->getDescriptorPoolHandle(); m_descriptor_sets.clear(); - m_bound_views.assign(VulkanRenderer::k_frames_in_flight, {}); + m_bound_views.resize(VulkanRenderer::k_frames_in_flight); for (uint32_t i = 0; i < VulkanRenderer::k_frames_in_flight; ++i) { const vk::DescriptorSetAllocateInfo alloc_info(pool, 1, &set_layout); auto allocated = device.allocateDescriptorSets(alloc_info); @@ -77,7 +77,7 @@ void MotionBlurPass::createResources(const VulkanCore& core) { void MotionBlurPass::onResize(vk::Extent2D extent) { if (m_core != nullptr) { m_target.create(*m_core, extent, m_scene_format, "MotionBlurPass"); - std::ranges::fill(m_bound_views, vk::ImageView {}); + m_bound_views.invalidate(); } } @@ -110,7 +110,7 @@ auto MotionBlurPass::record(vk::CommandBuffer cmd, uint32_t frame_index, vk::Ima m_sequence = frame->sequence; } - if (m_bound_views[frame_index] != source_view) { + if (m_bound_views.update(frame_index, source_view)) { const std::array image_infos { vk::DescriptorImageInfo(*m_linear_sampler, source_view, vk::ImageLayout::eShaderReadOnlyOptimal), // Depth stays eDepthReadOnlyOptimal for the overlay stage @@ -125,7 +125,6 @@ auto MotionBlurPass::record(vk::CommandBuffer cmd, uint32_t frame_index, vk::Ima ); } m_core->getDevice().updateDescriptorSets(writes, {}); - m_bound_views[frame_index] = source_view; } const auto width = static_cast(m_target.extent().width); diff --git a/engine/src/toast/renderer/passes/post/motion_blur_pass.hpp b/engine/src/toast/renderer/passes/post/motion_blur_pass.hpp index 5945e3d63..d3cd22c5b 100644 --- a/engine/src/toast/renderer/passes/post/motion_blur_pass.hpp +++ b/engine/src/toast/renderer/passes/post/motion_blur_pass.hpp @@ -6,6 +6,7 @@ #pragma once +#include "toast/renderer/core/descriptor_cache.hpp" #include "toast/renderer/core/vulkan_common.hpp" #include "toast/renderer/passes/post_process_pass_base.hpp" #include "toast/renderer/resources/post_process_target.hpp" @@ -58,7 +59,7 @@ class MotionBlurPass : public IPostProcessPass { vk::raii::Sampler m_point_sampler = nullptr; std::vector m_descriptor_sets; - std::vector m_bound_views; + DescriptorCache m_bound_views; PostProcessTarget m_target; diff --git a/engine/src/toast/renderer/passes/post/taa_pass.cpp b/engine/src/toast/renderer/passes/post/taa_pass.cpp index 7c3bdbbc5..6187cfb1a 100644 --- a/engine/src/toast/renderer/passes/post/taa_pass.cpp +++ b/engine/src/toast/renderer/passes/post/taa_pass.cpp @@ -66,7 +66,7 @@ void TaaPass::createResources(const VulkanCore& core) { const vk::DescriptorPool pool = VulkanRenderer::instance->getDescriptorPoolHandle(); m_descriptor_sets.clear(); - m_bound_views.assign(VulkanRenderer::k_frames_in_flight, {}); + m_bound_views.resize(VulkanRenderer::k_frames_in_flight); for (uint32_t i = 0; i < VulkanRenderer::k_frames_in_flight; ++i) { const vk::DescriptorSetAllocateInfo alloc_info(pool, 1, &set_layout); auto allocated = device.allocateDescriptorSets(alloc_info); @@ -78,7 +78,7 @@ void TaaPass::createResources(const VulkanCore& core) { void TaaPass::createTargets(const VulkanCore& core, vk::Extent2D extent) { m_targets[0].create(core, extent, m_scene_format, "TaaPass History A"); m_targets[1].create(core, extent, m_scene_format, "TaaPass History B"); - std::ranges::fill(m_bound_views, std::array {}); + m_bound_views.invalidate(); m_history_valid = false; } @@ -124,7 +124,7 @@ auto TaaPass::record(vk::CommandBuffer cmd, uint32_t frame_index, vk::ImageView } const std::array wanted {source_view, history.view()}; - if (m_bound_views[frame_index] != wanted) { + if (m_bound_views.update(frame_index, wanted)) { const std::array image_infos { vk::DescriptorImageInfo(*m_point_sampler, source_view, vk::ImageLayout::eShaderReadOnlyOptimal), vk::DescriptorImageInfo(*m_linear_sampler, history.view(), vk::ImageLayout::eShaderReadOnlyOptimal), @@ -140,7 +140,6 @@ auto TaaPass::record(vk::CommandBuffer cmd, uint32_t frame_index, vk::ImageView ); } m_core->getDevice().updateDescriptorSets(writes, {}); - m_bound_views[frame_index] = wanted; } const glm::mat4 current_view_projection = frame->frame_data.view_projection; diff --git a/engine/src/toast/renderer/passes/post/taa_pass.hpp b/engine/src/toast/renderer/passes/post/taa_pass.hpp index 31318a20f..f9b9cff2b 100644 --- a/engine/src/toast/renderer/passes/post/taa_pass.hpp +++ b/engine/src/toast/renderer/passes/post/taa_pass.hpp @@ -6,6 +6,7 @@ #pragma once +#include "toast/renderer/core/descriptor_cache.hpp" #include "toast/renderer/core/vulkan_common.hpp" #include "toast/renderer/passes/post_process_pass_base.hpp" #include "toast/renderer/resources/post_process_target.hpp" @@ -72,7 +73,7 @@ class TaaPass : public IPostProcessPass { std::vector m_descriptor_sets; /// Source then history last written into each set - std::vector> m_bound_views; + DescriptorCache> m_bound_views; /// Last frame output is this frame history std::array m_targets; diff --git a/engine/src/toast/renderer/passes/post/tonemap_pass.cpp b/engine/src/toast/renderer/passes/post/tonemap_pass.cpp index 900b688e0..dcc596670 100644 --- a/engine/src/toast/renderer/passes/post/tonemap_pass.cpp +++ b/engine/src/toast/renderer/passes/post/tonemap_pass.cpp @@ -117,7 +117,7 @@ void TonemapPass::createExposureResources(const VulkanCore& core) { const vk::DescriptorPool pool = VulkanRenderer::instance->getDescriptorPoolHandle(); m_exposure_sets.clear(); - m_exposure_bound_views.assign(VulkanRenderer::k_frames_in_flight, vk::ImageView {}); + m_exposure_bound_views.resize(VulkanRenderer::k_frames_in_flight); DescriptorWriter writer; for (uint32_t i = 0; i < VulkanRenderer::k_frames_in_flight; ++i) { const vk::DescriptorSetAllocateInfo alloc_info(pool, 1, &set_layout); @@ -151,7 +151,7 @@ void TonemapPass::createResources(const VulkanCore& core) { m_descriptor_sets.clear(); m_params_buffers.resize(VulkanRenderer::k_frames_in_flight); - m_bound_views.assign(VulkanRenderer::k_frames_in_flight, vk::ImageView {}); + m_bound_views.resize(VulkanRenderer::k_frames_in_flight); for (uint32_t i = 0; i < VulkanRenderer::k_frames_in_flight; ++i) { vk::BufferCreateInfo buffer_ci {}; @@ -187,15 +187,15 @@ void TonemapPass::createResources(const VulkanCore& core) { void TonemapPass::createTarget(const VulkanCore& core, vk::Extent2D extent) { m_target.create(core, extent, m_ldr_format, "TonemapPass"); // A new view can reuse the handle value of a destroyed view - std::ranges::fill(m_bound_views, vk::ImageView {}); - std::ranges::fill(m_exposure_bound_views, vk::ImageView {}); + m_bound_views.invalidate(); + m_exposure_bound_views.invalidate(); } void TonemapPass::recordExposure( vk::CommandBuffer cmd, uint32_t frame_index, vk::ImageView source_view, const PostProcessSettings::Tonemap& settings ) { ZoneScoped; - if (m_exposure_bound_views[frame_index] != source_view) { + if (m_exposure_bound_views.update(frame_index, source_view)) { DescriptorWriter writer; writer.image( *m_exposure_sets[frame_index], @@ -206,7 +206,6 @@ void TonemapPass::recordExposure( vk::ImageLayout::eShaderReadOnlyOptimal ); writer.flush(m_core->getDevice()); - m_exposure_bound_views[frame_index] = source_view; } const auto now = std::chrono::steady_clock::now(); @@ -321,7 +320,7 @@ auto TonemapPass::record(vk::CommandBuffer cmd, uint32_t frame_index, vk::ImageV } } - if (m_bound_views[frame_index] != source_view) { + if (m_bound_views.update(frame_index, source_view)) { vk::DescriptorImageInfo image_info {}; image_info.imageLayout = vk::ImageLayout::eShaderReadOnlyOptimal; image_info.imageView = source_view; @@ -331,7 +330,6 @@ auto TonemapPass::record(vk::CommandBuffer cmd, uint32_t frame_index, vk::ImageV *m_descriptor_sets[frame_index], 1, 0, 1, vk::DescriptorType::eCombinedImageSampler, &image_info ); m_core->getDevice().updateDescriptorSets(write, {}); - m_bound_views[frame_index] = source_view; } m_target.beginScope(cmd); diff --git a/engine/src/toast/renderer/passes/post/tonemap_pass.hpp b/engine/src/toast/renderer/passes/post/tonemap_pass.hpp index 4b93cbbdf..0432e3efc 100644 --- a/engine/src/toast/renderer/passes/post/tonemap_pass.hpp +++ b/engine/src/toast/renderer/passes/post/tonemap_pass.hpp @@ -6,6 +6,7 @@ #pragma once +#include "toast/renderer/core/descriptor_cache.hpp" #include "toast/renderer/core/vulkan_common.hpp" #include "toast/renderer/passes/post_process_pass_base.hpp" #include "toast/renderer/resources/post_process_target.hpp" @@ -101,7 +102,7 @@ class TonemapPass : public IPostProcessPass { std::vector m_descriptor_sets; std::vector m_params_buffers; - std::vector m_bound_views; + DescriptorCache m_bound_views; ShaderLayout m_exposure_layout; VulkanPipeline m_histogram_pipeline; @@ -113,7 +114,7 @@ class TonemapPass : public IPostProcessPass { std::optional m_exposure; std::vector m_exposure_sets; - std::vector m_exposure_bound_views; + DescriptorCache m_exposure_bound_views; bool m_exposure_ready = false; bool m_was_metering = false; diff --git a/engine/src/toast/renderer/passes/post_process_pass_base.hpp b/engine/src/toast/renderer/passes/post_process_pass_base.hpp index 115ed6d11..192666790 100644 --- a/engine/src/toast/renderer/passes/post_process_pass_base.hpp +++ b/engine/src/toast/renderer/passes/post_process_pass_base.hpp @@ -20,6 +20,9 @@ class IPostProcessPass { virtual void onResize(vk::Extent2D extent) { } + /// Glass views read where glass covers a pixel + virtual void setGlassSources(vk::ImageView backdrop, vk::ImageView mask) { } + [[nodiscard]] virtual auto atOutputResolution() const -> bool { return false; diff --git a/engine/src/toast/renderer/resources/scene_descriptor_set.cpp b/engine/src/toast/renderer/resources/scene_descriptor_set.cpp index 04423ca3e..fe86e68a7 100644 --- a/engine/src/toast/renderer/resources/scene_descriptor_set.cpp +++ b/engine/src/toast/renderer/resources/scene_descriptor_set.cpp @@ -25,9 +25,9 @@ void SceneDescriptorSets::create( m_sets.clear(); m_sets.reserve(VulkanRenderer::k_frames_in_flight); m_scene_binding.reset(); - m_bound_tlas.assign(VulkanRenderer::k_frames_in_flight, {}); + m_bound_tlas.resize(VulkanRenderer::k_frames_in_flight); m_detail_binding.reset(); - m_bound_detail.assign(VulkanRenderer::k_frames_in_flight, {}); + m_bound_detail.resize(VulkanRenderer::k_frames_in_flight); for (uint32_t i = 0; i < VulkanRenderer::k_frames_in_flight; ++i) { const vk::DescriptorSetAllocateInfo alloc_info(pool, 1, &layout); @@ -84,7 +84,6 @@ void SceneDescriptorSets::create( vk::ImageLayout::eShaderReadOnlyOptimal ); m_detail_binding = binding.binding; - m_bound_detail[i] = detail; continue; } @@ -229,7 +228,7 @@ void SceneDescriptorSets::updateTlas(uint32_t frame_index) { ZoneScoped; if (m_core != nullptr && m_detail_binding.has_value() && frame_index < m_bound_detail.size()) { const vk::ImageView detail = VulkanRenderer::instance->voxelDetailView(); - if (detail != m_bound_detail[frame_index]) { + if (m_bound_detail.update(frame_index, detail)) { DescriptorWriter writer; writer.image( *m_sets[frame_index], @@ -240,7 +239,6 @@ void SceneDescriptorSets::updateTlas(uint32_t frame_index) { vk::ImageLayout::eShaderReadOnlyOptimal ); writer.flush(m_core->getDevice()); - m_bound_detail[frame_index] = detail; } } if (m_core == nullptr || !m_scene_binding.has_value() || frame_index >= m_bound_tlas.size()) { @@ -252,15 +250,13 @@ void SceneDescriptorSets::updateTlas(uint32_t frame_index) { const std::pair bound {tlas, scene != nullptr ? scene->getAccelerationStructureGeneration(frame_index) : 0}; // A descriptor cannot be written with a null structure - if (!tlas || bound == m_bound_tlas[frame_index]) { + if (!tlas || !m_bound_tlas.update(frame_index, bound)) { return; } DescriptorWriter writer; writer.accelerationStructure(*m_sets[frame_index], *m_scene_binding, tlas); writer.flush(m_core->getDevice()); - - m_bound_tlas[frame_index] = bound; } } diff --git a/engine/src/toast/renderer/resources/scene_descriptor_set.hpp b/engine/src/toast/renderer/resources/scene_descriptor_set.hpp index e7b4652fe..bf1f20a30 100644 --- a/engine/src/toast/renderer/resources/scene_descriptor_set.hpp +++ b/engine/src/toast/renderer/resources/scene_descriptor_set.hpp @@ -6,6 +6,7 @@ #pragma once +#include "toast/renderer/core/descriptor_cache.hpp" #include "toast/renderer/core/vulkan_common.hpp" #include "toast/renderer/shaders/shader_reflection.hpp" @@ -48,10 +49,10 @@ class SceneDescriptorSets { std::optional m_scene_binding; std::optional m_detail_binding; - std::vector m_bound_detail; + DescriptorCache m_bound_detail; /// Handle plus generation since a recreated structure can reuse a destroyed handle value - std::vector> m_bound_tlas; + DescriptorCache> m_bound_tlas; }; } diff --git a/engine/src/toast/renderer/shaders/shader_compiler.cpp b/engine/src/toast/renderer/shaders/shader_compiler.cpp index 3293ea8b2..8249b05c1 100644 --- a/engine/src/toast/renderer/shaders/shader_compiler.cpp +++ b/engine/src/toast/renderer/shaders/shader_compiler.cpp @@ -12,6 +12,7 @@ #include #include #include +#include namespace renderer { @@ -84,8 +85,8 @@ class SlangGlobalSessionPool { private: SlangGlobalSessionPool() : m_limit(std::clamp(std::thread::hardware_concurrency() / 2, 1, 4)) { } - std::mutex m_mutex; - std::condition_variable m_available; + TOAST_LOCKABLE(std::mutex, m_mutex, "Slang session pool"); + toast::ConditionVariable m_available; std::vector> m_free; size_t m_created = 0; size_t m_limit; diff --git a/engine/src/toast/renderer/vulkan_renderer.cpp b/engine/src/toast/renderer/vulkan_renderer.cpp index 87422c043..094540437 100644 --- a/engine/src/toast/renderer/vulkan_renderer.cpp +++ b/engine/src/toast/renderer/vulkan_renderer.cpp @@ -656,7 +656,7 @@ auto VulkanRenderer::applyResizeInternal(vk::Extent2D extent) -> void { if (m_voxel_pass != nullptr) { m_voxel_pass->onTargetsRecreated(); } - std::ranges::fill(m_present_bound_views, vk::ImageView {}); + bumpTargetGeneration(); m_current_frame = 0; } catch (const std::exception& e) { TOAST_CRITICAL("Render", "Failed to recreate output target on resize: {}", e.what()); } } diff --git a/engine/src/toast/renderer/vulkan_renderer.hpp b/engine/src/toast/renderer/vulkan_renderer.hpp index a4c358dba..5e97177ab 100644 --- a/engine/src/toast/renderer/vulkan_renderer.hpp +++ b/engine/src/toast/renderer/vulkan_renderer.hpp @@ -5,6 +5,7 @@ #pragma once #include "toast/renderer/core/depth_convention.hpp" +#include "toast/renderer/core/descriptor_cache.hpp" #include "toast/renderer/core/gpu_sync.hpp" #include "toast/renderer/core/gpu_timer.hpp" #include "toast/renderer/core/vulkan_core.hpp" @@ -51,6 +52,7 @@ #include #include #include +#include #include #include #include @@ -689,6 +691,11 @@ class VulkanRenderer { return m_glass_backdrop.view ? **m_glass_backdrop.view : vk::ImageView {}; } + [[nodiscard]] + auto getGlassMaskView() const noexcept -> vk::ImageView { + return m_glass_mask.view ? **m_glass_mask.view : vk::ImageView {}; + } + [[nodiscard]] auto getGlassBackdropDepthView() const noexcept -> vk::ImageView { return m_glass_backdrop_depth.view ? **m_glass_backdrop_depth.view : vk::ImageView {}; @@ -936,17 +943,12 @@ class VulkanRenderer { return m_irradiance_stale_count.load(std::memory_order_relaxed); } +#if defined(TOAST_DEV_TOOLS) [[nodiscard]] auto getOutOfOrderFrameCount() const noexcept -> uint32_t { return m_out_of_order_frames.load(std::memory_order_relaxed); } - void getFrameTimeStats(float& avg_ms, float& min_ms, float& max_ms) const noexcept { - avg_ms = m_frame_time_avg_ms.load(std::memory_order_relaxed); - min_ms = m_frame_time_min_ms.load(std::memory_order_relaxed); - max_ms = m_frame_time_max_ms.load(std::memory_order_relaxed); - } - [[nodiscard]] auto getSkippedBuildCount() const noexcept -> uint32_t { return m_skipped_builds.load(std::memory_order_relaxed); @@ -956,6 +958,7 @@ class VulkanRenderer { auto getDroppedFrameCount() const noexcept -> uint32_t { return m_dropped_frames.load(std::memory_order_relaxed); } +#endif [[nodiscard]] auto getVisibleInstanceCount() const noexcept -> uint32_t { @@ -1058,6 +1061,7 @@ class VulkanRenderer { return m_debug_draw_enabled.load(std::memory_order_relaxed); } +#if defined(TOAST_DEV_TOOLS) struct PerfCounters { uint64_t ticks = 0; uint64_t frames_built = 0; @@ -1097,6 +1101,7 @@ class VulkanRenderer { .build_ns = m_perf_build_ns.load(std::memory_order_relaxed), }; } +#endif struct UploadStats { uint32_t slots_in_flight = 0; @@ -1251,9 +1256,9 @@ class VulkanRenderer { /// Main thread only uint32_t m_write_index = 0; - std::mutex m_queue_mutex; + TOAST_LOCKABLE(std::mutex, m_queue_mutex, "Render frame queue"); - std::condition_variable m_frame_cv; + toast::ConditionVariable m_frame_cv; std::queue m_ready_frames; const RenderFrame* m_rendering_frame = nullptr; @@ -1407,7 +1412,7 @@ class VulkanRenderer { /// Main thread only void buildVoxelProxies(RenderFrame& frame); - std::mutex m_upload_mutex; + TOAST_LOCKABLE(std::mutex, m_upload_mutex, "Render uploads"); std::atomic m_pending_upload_builds {0}; @@ -1420,7 +1425,7 @@ class VulkanRenderer { std::unordered_map> m_material_passes; /// Guards m_material_passes and m_render_passes - mutable std::mutex m_pass_mutex; + mutable TOAST_LOCKABLE(std::mutex, m_pass_mutex, "Render passes"); std::atomic_bool m_pending_material_pass_clear {false}; event::Listener m_asset_listener; @@ -1481,6 +1486,7 @@ class VulkanRenderer { static constexpr vk::Format m_scene_color_format = vk::Format::eR16G16B16A16Sfloat; SceneColorResources m_scene_color; SceneColorResources m_glass_backdrop; + SceneColorResources m_glass_mask; SceneColorResources m_glass_backdrop_normal; static constexpr vk::Format m_scene_normal_format = renderer::k_scene_normal_format; @@ -1555,11 +1561,11 @@ class VulkanRenderer { VulkanPipeline m_present_pipeline; vk::raii::Sampler m_present_sampler = nullptr; std::vector m_present_sets; - std::vector m_present_bound_views; + DescriptorCache m_present_bound; VulkanPipeline m_depth_upscale_pipeline; vk::raii::Sampler m_depth_upscale_sampler = nullptr; std::vector m_depth_upscale_sets; - std::vector m_depth_upscale_bound; + DescriptorCache m_depth_upscale_bound; TracyVkCtx m_tracy_vk_ctx = nullptr; std::unique_ptr m_gpu_timer; @@ -1668,7 +1674,7 @@ class VulkanRenderer { UIFrameBuilder m_ui_frame_builder; - std::mutex m_mesh_proxy_mutex; + TOAST_LOCKABLE(std::mutex, m_mesh_proxy_mutex, "Render mesh proxies"); std::vector m_mesh_proxy_nodes; std::vector> m_debug_nodes; @@ -1806,6 +1812,7 @@ class VulkanRenderer { /// Render thread only uint64_t m_last_drawn_sequence = 0; +#if defined(TOAST_DEV_TOOLS) /// Stats grouped by writer thread on separate cache lines to avoid false sharing /// Main thread writes alignas(64) std::atomic m_skipped_builds {0}; @@ -1831,6 +1838,7 @@ class VulkanRenderer { std::atomic m_perf_present_ns {0}; std::atomic m_perf_frame_wait_ns {0}; std::atomic m_perf_pacing_ns {0}; +#endif alignas(64) std::atomic_bool m_cull_debug_draw {false}; diff --git a/engine/src/toast/renderer/vulkan_renderer_record.cpp b/engine/src/toast/renderer/vulkan_renderer_record.cpp index 5f81b5e4d..ae0f3329f 100644 --- a/engine/src/toast/renderer/vulkan_renderer_record.cpp +++ b/engine/src/toast/renderer/vulkan_renderer_record.cpp @@ -189,13 +189,12 @@ void plotGpuTimings(const GpuTimer& timer) { void VulkanRenderer::recordDepthUpscale(vk::CommandBuffer cmd, const vk::Rect2D& area) { ZoneScoped; const vk::ImageView scene_depth = **m_depth_resources.view; - if (m_depth_upscale_bound[m_current_frame] != scene_depth) { + if (m_depth_upscale_bound.update(m_current_frame, scene_depth)) { const vk::DescriptorImageInfo image_info(*m_depth_upscale_sampler, scene_depth, vk::ImageLayout::eDepthReadOnlyOptimal); const vk::WriteDescriptorSet write( *m_depth_upscale_sets[m_current_frame], 0, 0, 1, vk::DescriptorType::eCombinedImageSampler, &image_info ); m_core->getDevice().updateDescriptorSets(write, {}); - m_depth_upscale_bound[m_current_frame] = scene_depth; } sync::transition(cmd, m_output_depth.state, sync::Usage::depth_attachment); @@ -849,7 +848,7 @@ auto VulkanRenderer::recordVoxelScopes( auto VulkanRenderer::recordFrame(FrameContext& frame, uint32_t image_index) noexcept -> void { ZoneScoped; frame.command_buffer.reset(); - const vk::CommandBufferBeginInfo begin_info(vk::CommandBufferUsageFlagBits::eOneTimeSubmit); + constexpr vk::CommandBufferBeginInfo begin_info(vk::CommandBufferUsageFlagBits::eOneTimeSubmit); frame.command_buffer.begin(begin_info); if (m_gpu_timer != nullptr) { m_gpu_timer->beginGraphics(m_current_frame, *frame.command_buffer); @@ -1115,6 +1114,44 @@ auto VulkanRenderer::recordFrame(FrameContext& frame, uint32_t image_index) noex frame.command_buffer.endRendering(); + // Glass mask + sync::BarrierBatch to_mask; + to_mask.image(m_glass_mask.state, sync::Usage::color_attachment); + to_mask.image(m_depth_resources.state, sync::Usage::depth_attachment); + to_mask.flush(*frame.command_buffer); + + vk::RenderingAttachmentInfo mask_color {}; + mask_color.imageView = **m_glass_mask.view; + mask_color.imageLayout = vk::ImageLayout::eColorAttachmentOptimal; + mask_color.loadOp = vk::AttachmentLoadOp::eClear; + mask_color.storeOp = vk::AttachmentStoreOp::eStore; + mask_color.clearValue = vk::ClearValue(vk::ClearColorValue(std::array {0.0f, 0.0f, 0.0f, 0.0f})); + + vk::RenderingAttachmentInfo mask_depth {}; + mask_depth.imageView = **m_depth_resources.view; + mask_depth.imageLayout = vk::ImageLayout::eDepthAttachmentOptimal; + mask_depth.loadOp = vk::AttachmentLoadOp::eLoad; // keep the glass depth from the scene + mask_depth.storeOp = vk::AttachmentStoreOp::eStore; // must be store + + vk::RenderingInfo mask_info {}; + mask_info.renderArea = scene_scissor; + mask_info.layerCount = 1; + mask_info.colorAttachmentCount = 1; + mask_info.pColorAttachments = &mask_color; + mask_info.pDepthAttachment = &mask_depth; + + frame.command_buffer.beginRendering(mask_info); + frame.command_buffer.setViewport(0, std::array {scene_viewport}); + frame.command_buffer.setScissor(0, std::array {scene_scissor}); + if (m_voxel_pass != nullptr) { + m_voxel_pass->recordGlassMask(*frame.command_buffer, m_current_frame); + } + frame.command_buffer.endRendering(); + + sync::BarrierBatch after_mask; + after_mask.image(m_glass_mask.state, sync::Usage::fragment_sampled); + after_mask.flush(*frame.command_buffer); + // PROBE and Iradiance capture if (const auto* capture_frame = renderingFrame(); capture_frame != nullptr && capture_frame->probe_capture_index >= 0 && @@ -1166,6 +1203,7 @@ auto VulkanRenderer::recordFrame(FrameContext& frame, uint32_t image_index) noex const bool capture_frame = capture_check != nullptr && (capture_check->probe_capture_index >= 0 || capture_check->irradiance_capture_index >= 0); + // post process passes vk::ImageView post_source = getSceneColorView(); if (!capture_frame) { std::lock_guard lock(m_pass_mutex); @@ -1174,6 +1212,7 @@ auto VulkanRenderer::recordFrame(FrameContext& frame, uint32_t image_index) noex if (!pass->isEnabled() || !post_source) { continue; } + pass->setGlassSources(getGlassBackdropView(), getGlassMaskView()); // Sets glass mask for eveery post process pass const GpuScope scope(m_gpu_timer.get(), m_current_frame, *frame.command_buffer, pass->name()); post_source = pass->record(*frame.command_buffer, m_current_frame, post_source); } @@ -1234,7 +1273,7 @@ auto VulkanRenderer::recordFrame(FrameContext& frame, uint32_t image_index) noex const GpuScope scope(m_gpu_timer.get(), m_current_frame, *frame.command_buffer, "Present blit"); if (m_present_pipeline.isReady() && post_source && m_current_frame < m_present_sets.size()) { - if (m_present_bound_views[m_current_frame] != post_source) { + if (m_present_bound.update(m_current_frame, post_source)) { vk::DescriptorImageInfo image_info {}; image_info.imageLayout = vk::ImageLayout::eShaderReadOnlyOptimal; image_info.imageView = post_source; @@ -1244,7 +1283,6 @@ auto VulkanRenderer::recordFrame(FrameContext& frame, uint32_t image_index) noex *m_present_sets[m_current_frame], 0, 0, 1, vk::DescriptorType::eCombinedImageSampler, &image_info ); m_core->getDevice().updateDescriptorSets(write, {}); - m_present_bound_views[m_current_frame] = post_source; } frame.command_buffer.bindPipeline(vk::PipelineBindPoint::eGraphics, m_present_pipeline.getPipeline()); @@ -1411,16 +1449,21 @@ void VulkanRenderer::updateFrameResources(uint32_t frame_index, RenderFrame& fra auto VulkanRenderer::drawFrame(RenderFrame& frame_data) -> bool { ZoneScoped; + + // NO FRAMES LEFT TO DRAW if (m_frames.empty()) { return false; } + // IF MINIMIZED DO NOT DRAW if (!m_output_target->isPresentable()) { std::this_thread::sleep_for(std::chrono::milliseconds(50)); return false; } using clock = std::chrono::steady_clock; + +#if defined(TOAST_DEV_TOOLS) auto phase_start = clock::now(); auto end_phase = [&phase_start](std::atomic& counter) { const auto now = clock::now(); @@ -1429,33 +1472,41 @@ auto VulkanRenderer::drawFrame(RenderFrame& frame_data) -> bool { ); phase_start = now; }; +#endif toast::PhaseZones phases; TOAST_PHASE(phases, "Draw: uploads"); processPendingUploads(); flushResourceUploads(); +#if defined(TOAST_DEV_TOOLS) end_phase(m_perf_upload_ns); +#endif auto& frame = m_frames[m_current_frame]; TOAST_PHASE(phases, "Draw: wait frame fence"); std::ignore = m_core->getDevice().waitForFences(*frame.in_flight, true, std::numeric_limits::max()); + +#if defined(TOAST_DEV_TOOLS) end_phase(m_perf_gpu_wait_ns); +#endif + TOAST_PHASE(phases, "Draw: publish frames and timings"); frame.retired.clear(); publishCompletedFrames(); - m_core->updateTracyMemory(); +#if defined(TOAST_DEV_TOOLS) + m_core->updateTracyMemory(); if (m_gpu_timer != nullptr && !frame.was_probe_capture) { m_gpu_timer->collect(m_current_frame); -#if defined(TOAST_DEV_TOOLS) + reportGpuSpike(*m_gpu_timer); -#endif #ifdef TRACY_ENABLE plotGpuTimings(*m_gpu_timer); #endif } end_phase(m_perf_record_ns); +#endif TOAST_PHASE(phases, "Draw: acquire image"); auto acquired = m_output_target->acquireNextImage(std::numeric_limits::max(), *frame.image_available, VK_NULL_HANDLE); @@ -1466,7 +1517,10 @@ auto VulkanRenderer::drawFrame(RenderFrame& frame_data) -> bool { waitForOutputImage(); acquired = m_output_target->acquireNextImage(std::numeric_limits::max(), *frame.image_available, VK_NULL_HANDLE); } + +#if defined(TOAST_DEV_TOOLS) end_phase(m_perf_acquire_ns); +#endif if (acquired.result == vk::Result::eErrorOutOfDateKHR) { TOAST_WARN("Render", "Swapchain out of date on acquire; recreating"); @@ -1488,13 +1542,16 @@ auto VulkanRenderer::drawFrame(RenderFrame& frame_data) -> bool { std::ignore = m_core->getDevice().waitForFences(m_images_in_flight.at(image_index), true, std::numeric_limits::max()); } + +#if defined(TOAST_DEV_TOOLS) end_phase(m_perf_gpu_wait_ns); +#endif m_core->getDevice().resetFences(*frame.in_flight); m_images_in_flight[image_index] = *frame.in_flight; TOAST_PHASE(phases, "Draw: update frame resources"); - updateFrameResources(m_current_frame, frame_data); // FIXME dt + updateFrameResources(m_current_frame, frame_data); m_rendering_frame = &frame_data; TOAST_PHASE(phases, "Draw: update passes"); @@ -1529,7 +1586,9 @@ auto VulkanRenderer::drawFrame(RenderFrame& frame_data) -> bool { TOAST_PHASE(phases, "Draw: record frame"); recordFrame(frame, image_index); +#if defined(TOAST_DEV_TOOLS) end_phase(m_perf_record_ns); +#endif TOAST_PHASE(phases, "Draw: submit setup"); const bool present_sync = m_output_target->usesAcquirePresentSemaphores(); @@ -1586,7 +1645,9 @@ auto VulkanRenderer::drawFrame(RenderFrame& frame_data) -> bool { } // Steps the tick queued run on the compute queue while this frame renders m_core->asyncCompute().flushDeferred(); +#if defined(TOAST_DEV_TOOLS) end_phase(m_perf_submit_ns); +#endif #if defined(_WIN32) && defined(TOAST_DEV_TOOLS) if (m_core->getNsightMode() == NsightMode::graphics_capture) { @@ -1604,7 +1665,9 @@ auto VulkanRenderer::drawFrame(RenderFrame& frame_data) -> bool { TOAST_PHASE(phases, "Draw: present"); const auto present_result = m_output_target->present(image_index, present_sync ? signal_semaphore : vk::Semaphore {}); +#if defined(TOAST_DEV_TOOLS) end_phase(m_perf_present_ns); +#endif frame.last_image_index = image_index; frame.has_submitted = true; m_pending_publish.push_back(m_current_frame); @@ -1616,7 +1679,9 @@ auto VulkanRenderer::drawFrame(RenderFrame& frame_data) -> bool { if (previous.has_submitted) { std::ignore = m_core->getDevice().waitForFences(*previous.in_flight, true, std::numeric_limits::max()); } +#if defined(TOAST_DEV_TOOLS) end_phase(m_perf_gpu_wait_ns); +#endif } m_current_frame = (m_current_frame + 1) % static_cast(m_frames.size()); diff --git a/engine/src/toast/renderer/vulkan_renderer_resources.cpp b/engine/src/toast/renderer/vulkan_renderer_resources.cpp index 964dec9b7..0773722a7 100644 --- a/engine/src/toast/renderer/vulkan_renderer_resources.cpp +++ b/engine/src/toast/renderer/vulkan_renderer_resources.cpp @@ -27,6 +27,7 @@ #include "toast/renderer/shaders/shader_compiler.hpp" #include "toast/renderer/vulkan_renderer.hpp" #include "toast/renderer/vulkan_renderer_detail.hpp" +#include "vulkan/vulkan.hpp" #include #include @@ -325,6 +326,7 @@ void VulkanRenderer::createSceneColorResources() { create(m_scene_color, m_scene_color_format, "SceneColor", vk::ImageUsageFlagBits::eTransferSrc); create(m_glass_backdrop, m_scene_color_format, "GlassBackdrop", vk::ImageUsageFlagBits::eTransferDst); + create(m_glass_mask, vk::Format::eR8Unorm, "GlassMask"); create(m_scene_normal, m_scene_normal_format, "SceneNormal", vk::ImageUsageFlagBits::eTransferSrc); create(m_glass_backdrop_normal, m_scene_normal_format, "GlassBackdropNormal", vk::ImageUsageFlagBits::eTransferDst); create(m_scene_indirect, m_scene_indirect_format, "SceneIndirect"); @@ -459,7 +461,7 @@ void VulkanRenderer::createPresentResources() { const vk::DescriptorSetLayout set_layout = *layouts[0]; m_present_sets.clear(); m_depth_upscale_sets.clear(); - m_present_bound_views.assign(k_frames_in_flight, vk::ImageView {}); + m_present_bound.resize(k_frames_in_flight); for (uint32_t i = 0; i < k_frames_in_flight; ++i) { const vk::DescriptorSetAllocateInfo alloc_info(*m_descriptor_pool, 1, &set_layout); auto allocated = device.allocateDescriptorSets(alloc_info); @@ -469,7 +471,7 @@ void VulkanRenderer::createPresentResources() { m_depth_upscale_sets.push_back(std::move(depth_set[0])); setDebugName(*m_core, *m_depth_upscale_sets[i], std::format("VulkanRenderer DepthUpscaleSet[{}]", i)); } - m_depth_upscale_bound.assign(k_frames_in_flight, vk::ImageView {}); + m_depth_upscale_bound.resize(k_frames_in_flight); } void VulkanRenderer::createFrameResources() { @@ -776,7 +778,7 @@ auto VulkanRenderer::voxelDetailView() const -> vk::ImageView { void VulkanRenderer::queueResourceUpload(std::unique_ptr upload_job) { { - std::lock_guard lock(m_upload_mutex); + std::lock_guard lock(m_upload_mutex); m_upload_waiting.push_back(std::move(upload_job)); } pumpUploadQueue(); @@ -788,7 +790,7 @@ void VulkanRenderer::pumpUploadQueue() { while (true) { std::unique_ptr job; { - std::lock_guard lock(m_upload_mutex); + std::lock_guard lock(m_upload_mutex); if (m_upload_waiting.empty()) { return; } @@ -805,7 +807,7 @@ void VulkanRenderer::pumpUploadQueue() { m_upload_host_bytes.fetch_add(j->host_bytes, std::memory_order_acq_rel); { - std::lock_guard lock(m_upload_mutex); + std::lock_guard lock(m_upload_mutex); m_upload_staging.push_back(std::move(j)); } m_pending_upload_builds.fetch_sub(1, std::memory_order_acq_rel); @@ -870,7 +872,7 @@ void VulkanRenderer::flushResourceUploads() { std::vector> jobs_to_flush; { - std::lock_guard lock(m_upload_mutex); + std::lock_guard lock(m_upload_mutex); if (m_upload_staging.empty()) { return; } @@ -883,7 +885,7 @@ void VulkanRenderer::flushResourceUploads() { if (jobs.empty()) { return; } - std::lock_guard lock(m_upload_mutex); + std::lock_guard lock(m_upload_mutex); m_upload_staging.insert(m_upload_staging.begin(), std::make_move_iterator(jobs.begin()), std::make_move_iterator(jobs.end())); jobs.clear(); }; diff --git a/engine/src/toast/renderer/vulkan_renderer_scene.cpp b/engine/src/toast/renderer/vulkan_renderer_scene.cpp index d9bce3645..2c337b91b 100644 --- a/engine/src/toast/renderer/vulkan_renderer_scene.cpp +++ b/engine/src/toast/renderer/vulkan_renderer_scene.cpp @@ -366,14 +366,18 @@ void VulkanRenderer::tick(float time) noexcept { acquireFrameSlot(); } const bool got_slot = std::exchange(m_frame_slot, FrameSlot::none) == FrameSlot::held; +#if defined(TOAST_DEV_TOOLS) detail::addSingleWriter(m_perf_ticks, 1); - if (!got_slot) { detail::addSingleWriter(m_skipped_builds, 1); + } +#endif + if (!got_slot) { return; } - detail::addSingleWriter(m_perf_frames_built, 1); +#if defined(TOAST_DEV_TOOLS) + detail::addSingleWriter(m_perf_frames_built, 1); const auto build_start = std::chrono::steady_clock::now(); const auto count_build = [this, build_start] { detail::addSingleWriter( @@ -383,6 +387,9 @@ void VulkanRenderer::tick(float time) noexcept { ) ); }; +#else + const auto count_build = [] { }; +#endif TOAST_PHASE(phases, "Tick: reset frame"); auto& frame = getCurrentFrameBuild(); diff --git a/engine/src/toast/renderer/vulkan_renderer_thread.cpp b/engine/src/toast/renderer/vulkan_renderer_thread.cpp index 4c10943df..a75d940b0 100644 --- a/engine/src/toast/renderer/vulkan_renderer_thread.cpp +++ b/engine/src/toast/renderer/vulkan_renderer_thread.cpp @@ -118,9 +118,11 @@ void VulkanRenderer::mainRenderThread() try { RenderFrame frame_to_draw; bool has_frame = false; +#if defined(TOAST_DEV_TOOLS) std::array frame_time_window {}; size_t frame_time_cursor = 0; clock::time_point last_frame_time {}; +#endif while (m_running.load(std::memory_order_acquire)) { ZoneScopedN("VulkanRenderer::mainRenderThread"); @@ -133,6 +135,7 @@ void VulkanRenderer::mainRenderThread() try { continue; } + // applies queued resize const uint64_t pending_resize = m_pending_resize_packed.exchange(k_no_pending_resize, std::memory_order_acq_rel); if (pending_resize != k_no_pending_resize) { const auto extent = detail::unpackExtent(pending_resize); @@ -154,7 +157,9 @@ void VulkanRenderer::mainRenderThread() try { m_pending_resize_packed.load(std::memory_order_acquire) != k_no_pending_resize; }; +#if defined(TOAST_DEV_TOOLS) const auto frame_wait_start = clock::now(); +#endif if (m_ready_frames.empty()) { if (!has_frame || clamp_to_simulation) { m_frame_cv.wait(lock, wake_condition); @@ -165,10 +170,12 @@ void VulkanRenderer::mainRenderThread() try { } } } +#if defined(TOAST_DEV_TOOLS) detail::addSingleWriter( m_perf_frame_wait_ns, static_cast(std::chrono::duration_cast(clock::now() - frame_wait_start).count()) ); +#endif if (!m_running) { return; @@ -184,16 +191,21 @@ void VulkanRenderer::mainRenderThread() try { const uint64_t previous = std::exchange(m_last_drawn_sequence, frame_to_draw.sequence); if (frame_to_draw.sequence < previous) { +#if defined(TOAST_DEV_TOOLS) detail::addSingleWriter(m_out_of_order_frames, 1); +#endif TOAST_WARN( "VulkanRenderer", "Frame {} drawn after frame {} - render frames arrived out of order", frame_to_draw.sequence, previous ); - } else if (previous != 0 && frame_to_draw.sequence > previous + 1) { + } +#if defined(TOAST_DEV_TOOLS) + if (previous != 0 && frame_to_draw.sequence > previous + 1) { detail::addSingleWriter(m_dropped_frames, static_cast(frame_to_draw.sequence - previous - 1)); } +#endif } else if (!has_frame) { continue; } @@ -201,12 +213,16 @@ void VulkanRenderer::mainRenderThread() try { // Clamped frames are capped in waitForFrameSlot if (limit_hz > 0.0 && !clamp_to_simulation) { +#if defined(TOAST_DEV_TOOLS) const auto pacing_start = clock::now(); +#endif std::this_thread::sleep_until(next_frame_deadline); +#if defined(TOAST_DEV_TOOLS) detail::addSingleWriter( m_perf_pacing_ns, static_cast(std::chrono::duration_cast(clock::now() - pacing_start).count()) ); +#endif const auto interval = std::chrono::duration_cast(std::chrono::duration(1.0 / limit_hz)); const auto now = clock::now(); next_frame_deadline = (next_frame_deadline + interval > now) ? next_frame_deadline + interval : now + interval; @@ -242,9 +258,12 @@ void VulkanRenderer::mainRenderThread() try { } #endif +#if defined(TOAST_DEV_TOOLS) const auto draw_start = clock::now(); +#endif // A pass with no free output image rendered nothing if (drawFrame(frame_to_draw)) { +#if defined(TOAST_DEV_TOOLS) detail::addSingleWriter( m_perf_draw_work_ns, static_cast(std::chrono::duration_cast(clock::now() - draw_start).count()) @@ -253,7 +272,6 @@ void VulkanRenderer::mainRenderThread() try { if (!consumed_queued_frame) { detail::addSingleWriter(m_perf_repeated_draws, 1); } - { static constexpr size_t k_window = 60; const auto now = clock::now(); @@ -277,8 +295,10 @@ void VulkanRenderer::mainRenderThread() try { } last_frame_time = now; } +#endif } + // handling graphics capture if (do_capture && rdoc_api != nullptr) { rdoc_api->EndFrameCapture(nullptr, nullptr); TOAST_INFO("VulkanRenderer", "RenderDoc frame capture triggered"); @@ -303,6 +323,7 @@ void VulkanRenderer::mainRenderThread() try { m_free_frames.release(); } + // poll vram usage #ifdef TRACY_ENABLE { const auto memory_props = m_core->getPhysicalDevice().getMemoryProperties(); @@ -325,20 +346,22 @@ void VulkanRenderer::mainRenderThread() try { } catch (const vk::DeviceLostError& error) { // Nothing recovers a lost device and the abort would otherwise drop the queued logs TOAST_CRITICAL("Render", "GPU device lost on the render thread, shutting down: {}", error.what()); - logging::flush(); - std::abort(); } void VulkanRenderer::acquireFrameSlot() noexcept { using namespace std::chrono_literals; +#if defined(TOAST_DEV_TOOLS) const auto slot_wait_start = std::chrono::steady_clock::now(); +#endif m_frame_slot = m_free_frames.try_acquire_for(50ms) ? FrameSlot::held : FrameSlot::missed; +#if defined(TOAST_DEV_TOOLS) detail::addSingleWriter( m_perf_slot_wait_ns, static_cast( std::chrono::duration_cast(std::chrono::steady_clock::now() - slot_wait_start).count() ) ); +#endif } void VulkanRenderer::waitForFrameSlot() noexcept { diff --git a/engine/src/toast/scripting/lua_state.hpp b/engine/src/toast/scripting/lua_state.hpp index 694885803..f9462b9bd 100644 --- a/engine/src/toast/scripting/lua_state.hpp +++ b/engine/src/toast/scripting/lua_state.hpp @@ -30,6 +30,7 @@ #include #include #include +#include #include #include #include @@ -205,7 +206,7 @@ class TOAST_API LuaState { struct Entry { lua_State* state = nullptr; - std::recursive_mutex mutex; + TOAST_LOCKABLE(std::recursive_mutex, mutex, "Lua state"); std::atomic owner {0}; ///< token of the owning thread, 0 while free int depth = 0; ///< lock nesting, only touched by the owner std::mutex pending_mutex; diff --git a/engine/src/toast/settings/settings.hpp b/engine/src/toast/settings/settings.hpp index e2e402bdf..c82929aa7 100644 --- a/engine/src/toast/settings/settings.hpp +++ b/engine/src/toast/settings/settings.hpp @@ -15,6 +15,7 @@ #include #include #include +#include #include #include #include @@ -186,7 +187,7 @@ class TOAST_API Settings { auto operator()(std::string_view key) const -> size_t { return std::hash {}(key); } }; - std::recursive_mutex m_mutex; + TOAST_LOCKABLE(std::recursive_mutex, m_mutex, "Settings"); std::deque m_entries; std::unordered_map> m_by_key; diff --git a/engine/src/toast/thread_pool.cpp b/engine/src/toast/thread_pool.cpp index edb91f808..c294a13ca 100644 --- a/engine/src/toast/thread_pool.cpp +++ b/engine/src/toast/thread_pool.cpp @@ -20,7 +20,7 @@ void ThreadPool::enqueue(std::move_only_function&& job) { auto& o = get(); { - std::unique_lock lock(o.m.queue_mutex); + std::unique_lock lock(o.m.queue_mutex); o.m.jobs.emplace(std::move(job)); } @@ -29,7 +29,7 @@ void ThreadPool::enqueue(std::move_only_function&& job) { void ThreadPool::destroy() { { - std::unique_lock lock(m.queue_mutex); + std::unique_lock lock(m.queue_mutex); m.should_stop = true; } @@ -45,12 +45,12 @@ void ThreadPool::destroy() { } auto ThreadPool::busy() -> bool { - std::unique_lock lock(m.queue_mutex); + std::unique_lock lock(m.queue_mutex); return !m.jobs.empty() || m.active_jobs > 0; } void ThreadPool::waitIdle() { - std::unique_lock lock(m.queue_mutex); + std::unique_lock lock(m.queue_mutex); m.all_done.wait(lock, [this] { return m.jobs.empty() && m.active_jobs == 0; }); } @@ -82,7 +82,7 @@ void ThreadPool::threadLoop() { std::move_only_function job; { - std::unique_lock lock(m.queue_mutex); + std::unique_lock lock(m.queue_mutex); // track idle workers m.idle_workers.fetch_add(1, std::memory_order_release); m.job_available.wait(lock, [this] { return !m.jobs.empty() || m.should_stop; }); @@ -103,7 +103,7 @@ void ThreadPool::threadLoop() { // Decrement and notify waitIdle() if pool is now fully idle if (--m.active_jobs == 0) { - std::unique_lock lock(m.queue_mutex); + std::unique_lock lock(m.queue_mutex); if (m.jobs.empty()) { m.all_done.notify_all(); } diff --git a/engine/src/toast/thread_pool.hpp b/engine/src/toast/thread_pool.hpp index 5b52cbb44..4b8298cca 100644 --- a/engine/src/toast/thread_pool.hpp +++ b/engine/src/toast/thread_pool.hpp @@ -14,6 +14,7 @@ #include #include #include +#include #include #include #include @@ -138,15 +139,15 @@ class TOAST_API ThreadPool { static void enqueue(std::move_only_function&& job); struct { - std::atomic active_jobs = 0; ///< Number of jobs currently executing - std::atomic idle_workers = 0; ///< Number of workers waiting for a job - bool should_stop = false; ///< Flag to signal workers to stop - - std::mutex queue_mutex; ///< Mutex protecting the job queue - std::condition_variable job_available; ///< Notified when a job is enqueued or stop is requested - std::condition_variable all_done; ///< Notified when activeJobs hits 0 and queue is empty - std::vector workers; ///< Worker threads (auto-join on destruction) - std::queue> jobs; ///< Pending job queue + std::atomic active_jobs = 0; ///< Number of jobs currently executing + std::atomic idle_workers = 0; ///< Number of workers waiting for a job + bool should_stop = false; ///< Flag to signal workers to stop + + TOAST_LOCKABLE(std::mutex, queue_mutex, "Thread pool jobs"); ///< Mutex protecting the job queue + ConditionVariable job_available; ///< Notified when a job is enqueued or stop is requested + ConditionVariable all_done; ///< Notified when activeJobs hits 0 and queue is empty + std::vector workers; ///< Worker threads (auto-join on destruction) + std::queue> jobs; ///< Pending job queue } m; }; diff --git a/engine/src/toast/voxel/runtime_pool.cpp b/engine/src/toast/voxel/runtime_pool.cpp index 1aadff402..499fad512 100644 --- a/engine/src/toast/voxel/runtime_pool.cpp +++ b/engine/src/toast/voxel/runtime_pool.cpp @@ -8,10 +8,14 @@ auto runtimeBrickPool() -> BrickPool& { return *pool; } -auto runtimePoolMutex() -> std::recursive_mutex& { +auto runtimePoolMutex() -> TOAST_LOCKABLE_BASE(std::recursive_mutex) & { + struct Holder { + TOAST_LOCKABLE(std::recursive_mutex, mutex, "Voxel runtime pool"); + }; + // Leaked like the pool - static std::recursive_mutex* mutex = new std::recursive_mutex; - return *mutex; + static auto* holder = new Holder; + return holder->mutex; } } diff --git a/engine/src/toast/voxel/runtime_pool.hpp b/engine/src/toast/voxel/runtime_pool.hpp index 1816e9e68..7f97b0193 100644 --- a/engine/src/toast/voxel/runtime_pool.hpp +++ b/engine/src/toast/voxel/runtime_pool.hpp @@ -10,6 +10,7 @@ #include #include #include +#include namespace voxel { @@ -21,6 +22,6 @@ TOAST_API auto runtimeBrickPool() -> BrickPool&; /// Held while physics writes runtime volumes and while the renderer packs them [[nodiscard]] -TOAST_API auto runtimePoolMutex() -> std::recursive_mutex&; +TOAST_API auto runtimePoolMutex() -> TOAST_LOCKABLE_BASE(std::recursive_mutex) &; } diff --git a/engine/src/toast/world/node_owner.hpp b/engine/src/toast/world/node_owner.hpp index ca74fb04f..80da2f756 100644 --- a/engine/src/toast/world/node_owner.hpp +++ b/engine/src/toast/world/node_owner.hpp @@ -19,6 +19,7 @@ #include #include #include +#include #include #include #include @@ -63,7 +64,7 @@ class TOAST_API INodeOwner { auto isEditing() noexcept -> bool; [[nodiscard]] - auto treeMutex() const noexcept -> std::shared_mutex& { + auto treeMutex() const noexcept -> TOAST_SHARED_LOCKABLE_BASE(std::shared_mutex) & { return m_tree_mutex; } @@ -206,7 +207,7 @@ class TOAST_API INodeOwner { private: friend class CameraController; - mutable std::shared_mutex m_tree_mutex; + mutable TOAST_SHARED_LOCKABLE(std::shared_mutex, m_tree_mutex, "Node tree"); std::unordered_set<_detail::ControlBox> nodes; std::unique_ptr m_fallback_camera; From 439a463f19b16fb595e4b26b283b62bb9ed7f3ef Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dar=C3=ADo=20Rodr=C3=ADguez=20Mart=C3=ADnez?= Date: Mon, 9 Nov 2026 16:28:18 +0100 Subject: [PATCH 04/11] wip stuff --- engine/assets/shaders/gi_common.slang | 34 ++++--------------- engine/assets/shaders/gi_merge.slang | 26 ++++++++++---- engine/src/toast/assets/animation.cpp | 14 +++----- engine/src/toast/assets/animation.hpp | 13 ++++--- .../renderer/passes/lighting/gi_pass.cpp | 6 ++++ engine/src/toast/world/animation_player.cpp | 15 +++----- 6 files changed, 49 insertions(+), 59 deletions(-) diff --git a/engine/assets/shaders/gi_common.slang b/engine/assets/shaders/gi_common.slang index 84b387469..21f8a6779 100644 --- a/engine/assets/shaders/gi_common.slang +++ b/engine/assets/shaders/gi_common.slang @@ -297,39 +297,19 @@ struct GiHistory float rays; }; -/// 32 bit maths since f32tof16 needs shaderFloat16 and shaderInt16 which the device does not enable -/// Rounds to nearest and flushes under 2^-14 to zero and saturates past the largest half +/// GLSL.std.450 packing since f32tof16 needs shaderFloat16 and shaderInt16 which the device does not enable +/// Clamped first since PackHalf2x16 turns overflow into infinity uint giFloatToHalf(float value) { - const uint bits = asuint(value); - const uint sign = (bits >> 16) & 0x8000u; - int exponent = int((bits >> 23) & 0xffu) - 112; - uint mantissa = (bits & 0x7fffffu) + 0x1000u; - if ((mantissa & 0x800000u) != 0u) - { - mantissa = 0u; - exponent += 1; - } - if (exponent <= 0) - { - return sign; - } - if (exponent >= 31) - { - return sign | 0x7bffu; - } - return sign | (uint(exponent) << 10) | (mantissa >> 13); + const float2 clamped = float2(clamp(value, -65504.0, 65504.0), 0.0); + return spirv_asm { result:$$uint = OpExtInst glsl450 PackHalf2x16 $clamped }; } +/// Reads the low 16 bits of @p half float giHalfToFloat(uint half) { - const uint sign = (half & 0x8000u) << 16; - const uint exponent = (half >> 10) & 0x1fu; - if (exponent == 0u) - { - return asfloat(sign); - } - return asfloat(sign | ((exponent + 112u) << 23) | ((half & 0x3ffu) << 13)); + const float2 unpacked = spirv_asm { result:$$float2 = OpExtInst glsl450 UnpackHalf2x16 $half }; + return unpacked.x; } GiHistory giPackHistory(float3 radiance, float transmittance, float rays) diff --git a/engine/assets/shaders/gi_merge.slang b/engine/assets/shaders/gi_merge.slang index 4296c3e1b..8cc80f9ef 100644 --- a/engine/assets/shaders/gi_merge.slang +++ b/engine/assets/shaders/gi_merge.slang @@ -65,18 +65,30 @@ struct GiParents float total; }; -GiParents giParents(GiFrame frame, uint cascade, uint deposit, out int4 probeCell) +GiParents giParents(GiFrame frame, uint cascade, uint deposit, bool top, out int4 probeCell) { const GiProbe probe = gPool[frame.frame.z * frame.pool.x + frame.cascades[cascade].z + gDepositPool[deposit]]; probeCell = probe.cell; + + GiParents parents; + parents.total = 0.0; + // linkMain never fills top cascade neighbours and the top merges with the sky + if (top) + { + [unroll] + for (uint corner = 0u; corner < 8u; ++corner) + { + parents.merged[corner] = 0u; + parents.weight[corner] = 0.0; + } + return parents; + } + int3 base = int3(0, 0, 0); float3 upper = float3(0.0, 0.0, 0.0); giParentNeighbourhood(probe.cell.xyz, base, upper); const uint4 low = gNeighbours[deposit * 2u]; const uint4 high = gNeighbours[deposit * 2u + 1u]; - - GiParents parents; - parents.total = 0.0; // Branch free so the eight slot loads overlap [unroll] for (uint corner = 0u; corner < 8u; ++corner) @@ -244,7 +256,7 @@ void mergeMain(uint3 id : SV_DispatchThreadID) const uint2 source = gHistorySource[deposit]; const bool carried = giCarried(frame, cascade, source); int4 probeCell = int4(0, 0, 0, 0); - const GiParents parents = giParents(frame, cascade, deposit, probeCell); + const GiParents parents = giParents(frame, cascade, deposit, top, probeCell); // Stores last since the compiler cannot move a load past a store that may alias it GiBucket buckets[4]; [unroll] @@ -297,6 +309,7 @@ void irradianceMain(uint3 group : SV_GroupID, uint3 thread : SV_GroupThreadID, u const uint tile = pair + side; const uint deposit = frame.deposits[0].x + tile; const uint first = tile < count ? gDepositSlots[deposit] : kGiEmpty; + const bool top = frame.frame.y == 1u; if (direction == 0u) { const bool willWrite = first != kGiEmpty; @@ -304,7 +317,7 @@ void irradianceMain(uint3 group : SV_GroupID, uint3 thread : SV_GroupThreadID, u if (willWrite) { int4 cell = int4(0, 0, 0, 0); - gsParents[side] = giParents(frame, 0u, deposit, cell); + gsParents[side] = giParents(frame, 0u, deposit, top, cell); gsCell[side] = cell; } } @@ -312,7 +325,6 @@ void irradianceMain(uint3 group : SV_GroupID, uint3 thread : SV_GroupThreadID, u if (gsWrite[side]) { - const bool top = frame.frame.y == 1u; const uint2 source = gHistorySource[deposit]; const bool carried = giCarried(frame, 0u, source); const GiBucket bucket = giLoadBucket(frame, first, direction, source, carried); diff --git a/engine/src/toast/assets/animation.cpp b/engine/src/toast/assets/animation.cpp index 4480e940a..9d050374e 100644 --- a/engine/src/toast/assets/animation.cpp +++ b/engine/src/toast/assets/animation.cpp @@ -225,17 +225,11 @@ auto AnimationClip::sample(float time) const -> std::unordered_mapgpuTimer(); + static constexpr std::array k_merge_scopes { + "GI merge c0", "GI merge c1", "GI merge c2", "GI merge c3", "GI merge c4", "GI merge c5" + }; cmd.bindPipeline(vk::PipelineBindPoint::eCompute, m_merge_pipeline.getPipeline()); for (uint32_t i = cascades; i-- > 1;) { + const GpuScope scope(timer, frame_index, cmd, k_merge_scopes[i]); cmd.pushConstants(layout, vk::ShaderStageFlagBits::eAll, 0, sizeof(uint32_t), &i); cmd.dispatch(k_stride_groups, 1, 1); computeBarrier(cmd); } + const GpuScope scope(timer, frame_index, cmd, "GI irradiance"); sync::BarrierBatch barriers; barriers.image(m_atlas_state, sync::Usage::compute_storage_write); barriers.flush(cmd); diff --git a/engine/src/toast/world/animation_player.cpp b/engine/src/toast/world/animation_player.cpp index 3dc9cfa59..45457f24d 100644 --- a/engine/src/toast/world/animation_player.cpp +++ b/engine/src/toast/world/animation_player.cpp @@ -113,16 +113,11 @@ void AnimationPlayer::tick() { continue; } - // Only the components the clip actually keys - see NodePose - if (pose.has_translation) { - target->position = pose.translation; - } - if (pose.has_rotation) { - target->rotation = pose.rotation; - } - if (pose.has_scale) { - target->scale = pose.scale; - } + target->position = pose.translation; + target->rotation = pose.rotation; + // if (pose.has_scale) { + // target->scale = pose.scale; + // } target->syncTransform(); } } From 91bf581beba78556dfea9141fdcbba9a10ffa329 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dar=C3=ADo=20Rodr=C3=ADguez=20Mart=C3=ADnez?= Date: Thu, 12 Nov 2026 12:01:53 +0100 Subject: [PATCH 05/11] Bone attachments also tried to improve gi --- editor/Assets/Importers/GltfImporter.cs | 2 +- editor/Editors/PaletteView.axaml | 6 +- editor/Workspace/InspectorModels.cs | 19 + editor/Workspace/InspectorViewModel.cs | 1 + engine/assets/shaders/debris_draw.slang | 2 + engine/assets/shaders/gi_clip_bounce.slang | 109 ++ .../assets/shaders/gi_clip_bounce.slang.meta | 4 + engine/assets/shaders/gi_clip_common.slang | 105 ++ .../assets/shaders/gi_clip_common.slang.meta | 4 + engine/assets/shaders/gi_clip_debug.slang | 109 ++ .../assets/shaders/gi_clip_debug.slang.meta | 4 + engine/assets/shaders/gi_clip_down.slang | 132 ++ engine/assets/shaders/gi_clip_down.slang.meta | 4 + engine/assets/shaders/gi_clip_fill.slang | 228 ++++ engine/assets/shaders/gi_clip_fill.slang.meta | 4 + engine/assets/shaders/gi_clip_inject.slang | 159 +++ .../assets/shaders/gi_clip_inject.slang.meta | 4 + engine/assets/shaders/gi_clip_trace.slang | 38 + .../assets/shaders/gi_clip_trace.slang.meta | 4 + engine/assets/shaders/gi_sample.slang | 377 ++++++ engine/assets/shaders/lighting.slang | 34 +- engine/assets/shaders/mesh.slang | 2 + engine/assets/shaders/volumetrics.slang | 2 +- engine/assets/shaders/voxel_glass.slang | 17 + engine/assets/shaders/voxel_lighting.slang | 82 +- engine/assets/shaders/voxel_specular.slang | 2 +- engine/src/toast/assets/animation.cpp | 74 +- engine/src/toast/assets/animation.hpp | 41 +- engine/src/toast/assets/gltf_importer.cpp | 342 ++++- engine/src/toast/engine.cpp | 4 + engine/src/toast/physics/simulator.cpp | 44 +- engine/src/toast/physics/simulator.hpp | 2 + .../src/toast/renderer/core/vulkan_common.hpp | 2 + .../toast/renderer/lighting/gi_clip_math.hpp | 68 + .../renderer/lighting/gi_dirty_boxes.cpp | 97 ++ .../renderer/lighting/gi_dirty_boxes.hpp | 51 + .../renderer/passes/geometry/voxel_pass.cpp | 127 +- .../renderer/passes/geometry/voxel_pass.hpp | 18 +- .../passes/lighting/gi_clipmap_pass.cpp | 1174 +++++++++++++++++ .../passes/lighting/gi_clipmap_pass.hpp | 185 +++ .../renderer/passes/lighting/gi_pass.cpp | 102 +- .../renderer/passes/lighting/gi_pass.hpp | 10 +- .../resources/scene_descriptor_set.cpp | 61 + .../resources/scene_descriptor_set.hpp | 7 + .../toast/renderer/settings/gi_settings.hpp | 12 + .../renderer/settings/renderer_settings.cpp | 85 ++ engine/src/toast/renderer/vulkan_renderer.hpp | 16 + .../toast/renderer/vulkan_renderer_record.cpp | 42 +- .../renderer/vulkan_renderer_resources.cpp | 12 +- .../toast/renderer/vulkan_renderer_scene.cpp | 50 +- .../src/toast/voxel/assets/voxel_palette.cpp | 2 +- engine/src/toast/voxel/nodes/voxel_node.cpp | 20 +- engine/src/toast/voxel/nodes/voxel_node.hpp | 10 + engine/src/toast/world/animation_player.cpp | 101 +- engine/src/toast/world/animation_player.hpp | 28 +- engine/src/toast/world/bone_attachment.cpp | 49 + engine/src/toast/world/bone_attachment.hpp | 52 + engine/src/toast/world/clip_playback.hpp | 54 + engine/src/toast/world/mesh_node.cpp | 10 + engine/src/toast/world/mesh_node.hpp | 11 +- engine/src/toast/world/node.hpp | 6 + engine/src/toast/world/skeletal_node.cpp | 314 +++++ engine/src/toast/world/skeletal_node.hpp | 152 +++ engine/src/toast/world/workspace.cpp | 10 +- engine/src/toast/world/workspace_events.cpp | 7 +- engine/src/toast/world/workspace_events.hpp | 6 +- protos/workspace_events.proto | 1 + tests/assets/02-animation-binary.cpp | 2 +- tests/assets/04-animation-skin-only.cpp | 2 +- vcpkg.json | 3 +- 70 files changed, 4630 insertions(+), 290 deletions(-) create mode 100644 engine/assets/shaders/gi_clip_bounce.slang create mode 100644 engine/assets/shaders/gi_clip_bounce.slang.meta create mode 100644 engine/assets/shaders/gi_clip_common.slang create mode 100644 engine/assets/shaders/gi_clip_common.slang.meta create mode 100644 engine/assets/shaders/gi_clip_debug.slang create mode 100644 engine/assets/shaders/gi_clip_debug.slang.meta create mode 100644 engine/assets/shaders/gi_clip_down.slang create mode 100644 engine/assets/shaders/gi_clip_down.slang.meta create mode 100644 engine/assets/shaders/gi_clip_fill.slang create mode 100644 engine/assets/shaders/gi_clip_fill.slang.meta create mode 100644 engine/assets/shaders/gi_clip_inject.slang create mode 100644 engine/assets/shaders/gi_clip_inject.slang.meta create mode 100644 engine/assets/shaders/gi_clip_trace.slang create mode 100644 engine/assets/shaders/gi_clip_trace.slang.meta create mode 100644 engine/src/toast/renderer/lighting/gi_clip_math.hpp create mode 100644 engine/src/toast/renderer/lighting/gi_dirty_boxes.cpp create mode 100644 engine/src/toast/renderer/lighting/gi_dirty_boxes.hpp create mode 100644 engine/src/toast/renderer/passes/lighting/gi_clipmap_pass.cpp create mode 100644 engine/src/toast/renderer/passes/lighting/gi_clipmap_pass.hpp create mode 100644 engine/src/toast/world/bone_attachment.cpp create mode 100644 engine/src/toast/world/bone_attachment.hpp create mode 100644 engine/src/toast/world/clip_playback.hpp create mode 100644 engine/src/toast/world/skeletal_node.cpp create mode 100644 engine/src/toast/world/skeletal_node.hpp diff --git a/editor/Assets/Importers/GltfImporter.cs b/editor/Assets/Importers/GltfImporter.cs index 1325a38a2..07d31b67d 100644 --- a/editor/Assets/Importers/GltfImporter.cs +++ b/editor/Assets/Importers/GltfImporter.cs @@ -325,7 +325,7 @@ void PatchNode(JsonNode node) { animationUids.TryGetValue(skinAnimNode.GetValue(), out var skinAnimUid)) p["skin_animation"] = skinAnimUid; } - } else if (nodeType == "toast::AnimationPlayer") { + } else if (nodeType is "toast::AnimationPlayer" or "toast::SkeletalNode") { var p = node["params"]?.AsObject(); if (p != null && p["animation"] is { } animNode && animationUids.TryGetValue(animNode.GetValue(), out var animUid)) diff --git a/editor/Editors/PaletteView.axaml b/editor/Editors/PaletteView.axaml index a87e64544..70b8dd5d7 100644 --- a/editor/Editors/PaletteView.axaml +++ b/editor/Editors/PaletteView.axaml @@ -468,7 +468,7 @@ Grid.Column="0" Classes="lbl compact-text" Text="IOR" /> - - diff --git a/editor/Workspace/InspectorModels.cs b/editor/Workspace/InspectorModels.cs index 336cc97b5..6e5ea2fa2 100644 --- a/editor/Workspace/InspectorModels.cs +++ b/editor/Workspace/InspectorModels.cs @@ -336,6 +336,11 @@ public FieldVM(FieldInfo info) { } } + if (!info.IsArray && info.FieldType == "string_t" && ReflectionDatabase.HasAttr(info.Attributes, "Options")) { + Kind = WidgetKind.Enum; + HasDynamicOptions = true; + } + var isColor = ReflectionDatabase.HasAttr(info.Attributes, "Color"); if (isColor && !info.IsArray) { if (info.FieldType == "vec3_t") Kind = WidgetKind.Color3; @@ -483,6 +488,20 @@ internal FieldVM( _ => 0 }; public ObservableCollection EnumOptions { get; } = []; + + public bool HasDynamicOptions { get; } + + public void ApplyEngineOptions(IReadOnlyList options) { + if (!HasDynamicOptions || EnumOptions.SequenceEqual(options, StringComparer.Ordinal)) return; + EnumOptions.Clear(); + m_enumLabelToValue.Clear(); + m_enumValueToLabel.Clear(); + foreach (var option in options) { + EnumOptions.Add(option); + m_enumLabelToValue[option] = option; + m_enumValueToLabel[option] = option; + } + } internal string EngineValue => ToEngineString(); public IAsyncCanExecuteCommand PasteCommand => m_pasteCommand ??= new InspectorPasteCommand( component => m_clipboardHost?.PasteFieldAsync(this, ClipboardComponent(component)) ?? Task.CompletedTask, diff --git a/editor/Workspace/InspectorViewModel.cs b/editor/Workspace/InspectorViewModel.cs index fd016c0fc..bd1dcaabe 100644 --- a/editor/Workspace/InspectorViewModel.cs +++ b/editor/Workspace/InspectorViewModel.cs @@ -290,6 +290,7 @@ public InspectorViewModel(HierarchyViewModel? follow) { foreach (var p in e.Parameters) { if (!m_fieldByParam.TryGetValue(p.Name, out var vm)) continue; + vm.ApplyEngineOptions(p.Options); // don't clobber a value the user is actively editing if ((DateTime.UtcNow - vm.LastEdit).TotalMilliseconds < 250) continue; vm.ApplyEngineString(p.Value); diff --git a/engine/assets/shaders/debris_draw.slang b/engine/assets/shaders/debris_draw.slang index e85dd0bf0..4ef2460a9 100644 --- a/engine/assets/shaders/debris_draw.slang +++ b/engine/assets/shaders/debris_draw.slang @@ -1,6 +1,7 @@ // Opaque debris into the voxel G-buffer and glass debris blended forward like voxel glass import voxel_gbuffer; import lighting; +import gi_sample; import glass_common; struct PushConstants { @@ -221,6 +222,7 @@ GlassShade shadeDebrisGlass(VSOutput input) { surface.viewSpaceZ = mul(gCamera.view, float4(input.worldPosition, 1.0)).z; surface.pixel = input.position.xy; + gGiGathered = giCheap(input.worldPosition, normal); GlassShade shade; const ShadingResult lit = shadeSurfaceLighting(surface); if (lit.isDebugView) { diff --git a/engine/assets/shaders/gi_clip_bounce.slang b/engine/assets/shaders/gi_clip_bounce.slang new file mode 100644 index 000000000..523f9ec4b --- /dev/null +++ b/engine/assets/shaders/gi_clip_bounce.slang @@ -0,0 +1,109 @@ +// Set 0 is the engine scene holding the clipmap of the last frame +import lighting; +import gi_sample; +import gi_clip_common; + +/// Over pi per giClipFace of the level written and sampled as B10G11R11 through a second view +[[vk::binding(0, 1)]] +[[vk::image_format("r32ui")]] +RWTexture3D gAmbient[kGiClipFaces]; + +/// Word 0 counts the faces listMain found and each record from kFaceListHeader on is a global cell xyz and a face +[[vk::binding(1, 1)]] +RWStructuredBuffer gFaceList; + +static const uint kFaceListHeader = 4u; +/// Mirrors GiClipmapPass k_bounce_capacity and faces past it wait for the next round +static const uint kFaceListCapacity = 1u << 17; + +/// Mirrors gi_clip_fill GiClipFillPush +struct GiClipBouncePush +{ + /// xyz first global cell w level + int4 boxMin; + int4 boxSize; +}; + +[[vk::push_constant]] +GiClipBouncePush gPush; + +bool clipBounceSolid(GiClipFrame frame, uint level, int3 cell) +{ + const int3 texel = giClipWrap(cell, int(frame.size.x)); + return gGiClipOpacity[NonUniformResourceIndex(level)].Load(int4(texel, 0)).w > 0.0; +} + +[shader("compute")] +[numthreads(4, 4, 4)] +void listMain(uint3 id : SV_DispatchThreadID) +{ + if (any(int3(id) >= gPush.boxSize.xyz)) + { + return; + } + const GiClipFrame frame = gGiClipFrame[0]; + const uint level = uint(gPush.boxMin.w); + if (frame.size.z == 0u || level >= frame.size.y) + { + return; + } + const int resolution = int(frame.size.x); + const int3 low = int3(frame.levels[level].xyz); + const int3 global = gPush.boxMin.xyz + int3(id); + // Box is from this frame origin while the textures still hold the last frame level + if (any(global < low) || any(global >= low + resolution) || giClipInner(frame, level, global) || + !clipBounceSolid(frame, level, global)) + { + return; + } + for (uint face = 0u; face < kGiClipFaces; ++face) + { + const int3 neighbour = global + giClipFace(face); + const bool inside = all(neighbour >= low) && all(neighbour < low + resolution); + if (!inside || clipBounceSolid(frame, level, neighbour)) + { + continue; + } + uint slot; + InterlockedAdd(gFaceList[0], 1u, slot); + if (slot < kFaceListCapacity) + { + const uint record = kFaceListHeader + slot * 4u; + gFaceList[record] = uint(global.x); + gFaceList[record + 1u] = uint(global.y); + gFaceList[record + 2u] = uint(global.z); + gFaceList[record + 3u] = face; + } + } +} + +[shader("compute")] +[numthreads(64, 1, 1)] +void bounceMain(uint3 id : SV_DispatchThreadID) +{ + if (id.x >= min(gFaceList[0], kFaceListCapacity)) + { + return; + } + const GiClipFrame frame = gGiClipFrame[0]; + const uint level = uint(gPush.boxMin.w); + const uint record = kFaceListHeader + id.x * 4u; + const int3 global = int3(int(gFaceList[record]), int(gFaceList[record + 1u]), int(gFaceList[record + 2u])); + const uint face = gFaceList[record + 3u]; + const int3 texel = giClipWrap(global, int(frame.size.x)); + const float cellSize = frame.levels[level].w; + const float3 normal = float3(giClipFace(face)); + + float3 irradiance; + float sky; + const float turn = float((uint(texel.x) * 5u + uint(texel.y) * 11u + uint(texel.z) * 7u) & 15u) / 16.0; + if (!sampleGiClipmap(giClipCellCentre(frame, level, global) + normal * (0.5 * cellSize), normal, turn, irradiance, sky)) + { + irradiance = float3(0.0, 0.0, 0.0); + sky = 1.0; + } + const float3 ambient = + gCamera.ambientColorIntensity.rgb * gCamera.ambientColorIntensity.a + + (gCamera.environmentParams.x >= 0.5 ? gIrradianceMap.SampleLevel(normal, 0.0).rgb : float3(0.0, 0.0, 0.0)); + gAmbient[face][texel] = giClipPackRadiance(irradiance + sky * ambient); +} diff --git a/engine/assets/shaders/gi_clip_bounce.slang.meta b/engine/assets/shaders/gi_clip_bounce.slang.meta new file mode 100644 index 000000000..ad440f6a4 --- /dev/null +++ b/engine/assets/shaders/gi_clip_bounce.slang.meta @@ -0,0 +1,4 @@ +uid = "G1C1pBoun00" +type = "shader" +created_at = "2026-11-10T00:00:00.0000000Z" +modified_at = "2026-11-10T00:00:00.0000000Z" diff --git a/engine/assets/shaders/gi_clip_common.slang b/engine/assets/shaders/gi_clip_common.slang new file mode 100644 index 000000000..258ea9989 --- /dev/null +++ b/engine/assets/shaders/gi_clip_common.slang @@ -0,0 +1,105 @@ + +static const uint kGiClipMaxLevels = 6u; +/// Mirrors renderer::GiClipmapPass::k_faces +static const uint kGiClipFaces = 6u; + +/// Mirrors renderer::GiClipmapPass::FrameData +struct GiClipFrame +{ + float4x4 inverseViewProjection; + float4 camera; + /// xyz lowest global cell w meters per cell + float4 levels[kGiClipMaxLevels]; + /// x resolution y level count z 1 once lighting may read it w mips above the last level + uint4 size; +}; + +int3 giClipWrap(int3 cell, int resolution) +{ + // Unsigned since drivers get a signed remainder of a negative cell wrong unless the resolution is a power of two + return int3(uint3(cell + resolution * 65536) % uint(resolution)); +} + +/// Finest level whose box holds the point with one cell of margin or kGiClipMaxLevels outside all +uint giClipLevelAt(GiClipFrame frame, float3 world) +{ + const int resolution = int(frame.size.x); + for (uint level = 0u; level < frame.size.y; ++level) + { + const float4 box = frame.levels[level]; + const int3 cell = int3(floor(world / box.w)) - int3(box.xyz); + if (all(cell >= 1) && all(cell < resolution - 1)) + { + return level; + } + } + return kGiClipMaxLevels; +} + +static const float kGiClipFade = 8.0; + +/// Measured from the camera not the snapped box so the fade glides +float giClipLevelSoft(GiClipFrame frame, float3 world) +{ + // The box centre trails the camera by up to two cells and one more keeps the filter footprint inside + const float reach = 0.5 * float(frame.size.x) - 3.0; + const float3 offset = abs(world - frame.camera.xyz); + const float distance = max(offset.x, max(offset.y, offset.z)); + for (uint level = 0u; level < frame.size.y; ++level) + { + const float inside = reach - distance / frame.levels[level].w; + if (inside >= 0.0) + { + const bool last = level + 1u >= frame.size.y; + return float(level) + (last ? 0.0 : saturate(1.0 - inside / kGiClipFade)); + } + } + return float(kGiClipMaxLevels); +} + +bool giClipInner(GiClipFrame frame, uint level, int3 cell) +{ + if (level == 0u) + { + return false; + } + // Level origins are even so the finer box lands on whole cells of this level + const int3 low = int3(frame.levels[level - 1u].xyz) >> 1; + return all(cell >= low) && all(cell < low + int(frame.size.x) / 2); +} + +/// Outward normal with even faces positive and the axis in face >> 1 +int3 giClipFace(uint face) +{ + const int sign = (face & 1u) == 0u ? 1 : -1; + const uint axis = face >> 1; + return int3(axis == 0u ? sign : 0, axis == 1u ? sign : 0, axis == 2u ? sign : 0); +} + +/// Unsigned float of 5 exponent bits and @p bits of mantissa with tiny values flushed to 0 +uint giClipPackFloat(float value, uint bits) +{ + const uint raw = asuint(max(value, 0.0)); + const int exponent = int((raw >> 23) & 0xFFu) - 112; + if (exponent <= 0) + { + return 0u; + } + const uint mask = (1u << bits) - 1u; + if (exponent >= 31) + { + return (30u << bits) | mask; + } + return (uint(exponent) << bits) | ((raw >> (23u - bits)) & mask); +} + +/// B10G11R11 bits so a float view of the same texels filters them +uint giClipPackRadiance(float3 radiance) +{ + return giClipPackFloat(radiance.r, 6u) | (giClipPackFloat(radiance.g, 6u) << 11) | (giClipPackFloat(radiance.b, 5u) << 22); +} + +float3 giClipCellCentre(GiClipFrame frame, uint level, int3 cell) +{ + return (float3(cell) + 0.5) * frame.levels[level].w; +} diff --git a/engine/assets/shaders/gi_clip_common.slang.meta b/engine/assets/shaders/gi_clip_common.slang.meta new file mode 100644 index 000000000..571075307 --- /dev/null +++ b/engine/assets/shaders/gi_clip_common.slang.meta @@ -0,0 +1,4 @@ +uid = "G1C1pComm00" +type = "shader" +created_at = "2026-11-10T00:00:00.0000000Z" +modified_at = "2026-11-10T00:00:00.0000000Z" diff --git a/engine/assets/shaders/gi_clip_debug.slang b/engine/assets/shaders/gi_clip_debug.slang new file mode 100644 index 000000000..4bc50f43c --- /dev/null +++ b/engine/assets/shaders/gi_clip_debug.slang @@ -0,0 +1,109 @@ +import fullscreen; +import gi_clip_common; + +[[vk::binding(0, 0)]] +Sampler2D gSource; + +[[vk::binding(1, 0)]] +StructuredBuffer gClipFrame; + +[[vk::binding(2, 0)]] +Sampler3D gMaterial; + +[[vk::binding(3, 0)]] +Sampler3D gEmission; + +[[vk::binding(4, 0)]] +Sampler3D gRadiance[kGiClipFaces]; + +struct GiClipDebugPush +{ + uint level; + /// Mirrors renderer::GiSettings clip_debug_mode + uint mode; +}; + +[[vk::push_constant]] +GiClipDebugPush gPush; + +static const uint kGiClipDebugEmission = 1u; +static const uint kGiClipDebugOpacity = 2u; +static const uint kGiClipDebugRadiance = 3u; + +typedef FullscreenVSOutput VSOutput; + +[shader("vertex")] +VSOutput vertexMain(uint vertexId : SV_VertexID) +{ + return fullscreenTriangle(vertexId); +} + +[shader("fragment")] +float4 fragmentMain(VSOutput input) : SV_Target0 +{ + const float4 scene = gSource.Load(int3(int2(input.position.xy), 0)); + const GiClipFrame frame = gClipFrame[0]; + const uint level = min(gPush.level, frame.size.y - 1u); + const int resolution = int(frame.size.x); + const float cellSize = frame.levels[level].w; + + // Depth 0.5 is in front of the camera with or without reversed Z + const float4 ahead = mul(frame.inverseViewProjection, float4(input.uv * 2.0 - 1.0, 0.5, 1.0)); + float3 direction = normalize(ahead.xyz / ahead.w - frame.camera.xyz); + direction = select(abs(direction) > 1e-6, direction, float3(1e-6, 1e-6, 1e-6)); + const float3 origin = frame.camera.xyz / cellSize; + + const float3 boxMin = frame.levels[level].xyz; + const float3 boxMax = boxMin + float(resolution); + const float3 inverse = 1.0 / direction; + const float3 t0 = (boxMin - origin) * inverse; + const float3 t1 = (boxMax - origin) * inverse; + const float3 near = min(t0, t1); + const float3 far = max(t0, t1); + const float tEnter = max(max(near.x, max(near.y, near.z)), 0.0); + const float tExit = min(far.x, min(far.y, far.z)); + if (tEnter >= tExit) + { + return scene; + } + + const int3 low = int3(boxMin); + int3 cell = clamp(int3(floor(origin + direction * (tEnter + 1e-4))), low, low + resolution - 1); + const int3 stepSign = int3(sign(direction)); + const float3 cellT = abs(inverse); + float3 nextT = (float3(cell) + max(float3(stepSign), 0.0) - origin) * inverse; + int axis = near.x > near.y ? (near.x > near.z ? 0 : 2) : (near.y > near.z ? 1 : 2); + + for (int steps = 0; steps < 3 * resolution; ++steps) + { + const int4 texel = int4(giClipWrap(cell, resolution), 0); + const float4 material = gMaterial.Load(texel); + if (material.a > 0.0) + { + float3 colour = material.rgb; + if (gPush.mode == kGiClipDebugEmission) + { + colour = gEmission.Load(texel).rgb; + } + else if (gPush.mode == kGiClipDebugOpacity) + { + colour = float3(1.0, 1.0, 1.0); + } + if (gPush.mode == kGiClipDebugRadiance) + { + const uint face = uint(axis) * 2u + (stepSign[axis] > 0 ? 1u : 0u); + return float4(gRadiance[face].Load(texel).rgb, scene.a); + } + const float shade = axis == 0 ? 1.0 : (axis == 1 ? 0.8 : 0.6); + return float4(colour * shade, scene.a); + } + axis = nextT.x < nextT.y ? (nextT.x < nextT.z ? 0 : 2) : (nextT.y < nextT.z ? 1 : 2); + cell[axis] += stepSign[axis]; + nextT[axis] += cellT[axis]; + if (cell[axis] < low[axis] || cell[axis] >= low[axis] + resolution) + { + break; + } + } + return scene; +} diff --git a/engine/assets/shaders/gi_clip_debug.slang.meta b/engine/assets/shaders/gi_clip_debug.slang.meta new file mode 100644 index 000000000..e9d00c525 --- /dev/null +++ b/engine/assets/shaders/gi_clip_debug.slang.meta @@ -0,0 +1,4 @@ +uid = "G1C1pDebu00" +type = "shader" +created_at = "2026-11-10T00:00:00.0000000Z" +modified_at = "2026-11-10T00:00:00.0000000Z" diff --git a/engine/assets/shaders/gi_clip_down.slang b/engine/assets/shaders/gi_clip_down.slang new file mode 100644 index 000000000..484582a15 --- /dev/null +++ b/engine/assets/shaders/gi_clip_down.slang @@ -0,0 +1,132 @@ +import gi_clip_common; + +[[vk::binding(0, 0)]] +StructuredBuffer gClipFrame; + +/// xyz opacity along each axis and w the solid share of the children +[[vk::binding(1, 0)]] +Sampler3D gChildOpacity; + +/// Premultiplied face radiance of the children +[[vk::binding(2, 0)]] +Sampler3D gChildRadiance[kGiClipFaces]; + +[[vk::binding(3, 0)]] +Sampler3D gChildAmbient[kGiClipFaces]; + +[[vk::binding(4, 0)]] +[[vk::image_format("rgba8")]] +RWTexture3D gOpacity; + +[[vk::binding(5, 0)]] +[[vk::image_format("r32ui")]] +RWTexture3D gRadiance[kGiClipFaces]; + +[[vk::binding(6, 0)]] +[[vk::image_format("r32ui")]] +RWTexture3D gAmbient[kGiClipFaces]; + +/// Mirrors GiClipmapPass DownPush +struct GiClipDownPush +{ + /// xyz first global cell written w cells a side of the texture written + int4 boxMin; + /// xyz cells written w cells a side of the texture read + int4 boxSize; + /// x mip of the texture read + int4 mip; +}; + +[[vk::push_constant]] +GiClipDownPush gPush; + +struct ClipChildren +{ + /// Texel and mip of child i which sits at bit 0 x bit 1 y bit 2 z + int4 at[8]; + float4 opacity[8]; +}; + +ClipChildren clipDown(int3 parent, int3 texel) +{ + ClipChildren children; + float solid = 0.0; + for (uint i = 0u; i < 8u; ++i) + { + const int3 cell = parent * 2 + int3(i & 1u, (i >> 1) & 1u, i >> 2); + children.at[i] = int4(giClipWrap(cell, gPush.boxSize.w), gPush.mip.x); + children.opacity[i] = gChildOpacity.Load(children.at[i]); + solid += children.opacity[i].w; + } + + float3 blocked = float3(0.0, 0.0, 0.0); + for (uint axis = 0u; axis < 3u; ++axis) + { + const uint stride = 1u << axis; + for (uint i = 0u; i < 8u; ++i) + { + if ((i & stride) == 0u) + { + const float near = children.opacity[i][axis]; + blocked[axis] += near + (1.0 - near) * children.opacity[i | stride][axis]; + } + } + } + gOpacity[texel] = float4(blocked * 0.25, solid * 0.125); + + for (uint face = 0u; face < kGiClipFaces; ++face) + { + const uint axis = face >> 1; + const uint stride = 1u << axis; + const bool positive = (face & 1u) == 0u; + float3 radiance = float3(0.0, 0.0, 0.0); + for (uint i = 0u; i < 8u; ++i) + { + if ((i & stride) != 0u) + { + continue; + } + const uint front = positive ? (i | stride) : i; + const uint back = positive ? i : (i | stride); + radiance += gChildRadiance[face].Load(children.at[front]).rgb + + (1.0 - children.opacity[front][axis]) * gChildRadiance[face].Load(children.at[back]).rgb; + } + gRadiance[face][texel] = giClipPackRadiance(radiance * 0.25); + } + return children; +} + +[shader("compute")] +[numthreads(4, 4, 4)] +void downMain(uint3 id : SV_DispatchThreadID) +{ + if (any(int3(id) >= gPush.boxSize.xyz)) + { + return; + } + const int3 parent = gPush.boxMin.xyz + int3(id); + const int3 texel = giClipWrap(parent, gPush.boxMin.w); + const ClipChildren children = clipDown(parent, texel); + for (uint face = 0u; face < kGiClipFaces; ++face) + { + float3 ambient = float3(0.0, 0.0, 0.0); + for (uint i = 0u; i < 8u; ++i) + { + ambient += gChildAmbient[face].Load(children.at[i]).rgb; + } + // Averaged like the solid share so dividing gives the face irradiance + gAmbient[face][texel] = giClipPackRadiance(ambient * 0.125); + } +} + +[shader("compute")] +[numthreads(4, 4, 4)] +void mipMain(uint3 id : SV_DispatchThreadID) +{ + if (any(int3(id) >= gPush.boxSize.xyz)) + { + return; + } + const int3 parent = gPush.boxMin.xyz + int3(id); + clipDown(parent, giClipWrap(parent, gPush.boxMin.w)); +} diff --git a/engine/assets/shaders/gi_clip_down.slang.meta b/engine/assets/shaders/gi_clip_down.slang.meta new file mode 100644 index 000000000..eb343775c --- /dev/null +++ b/engine/assets/shaders/gi_clip_down.slang.meta @@ -0,0 +1,4 @@ +uid = "G1C1pDown00" +type = "shader" +created_at = "2026-11-11T00:00:00.0000000Z" +modified_at = "2026-11-11T00:00:00.0000000Z" diff --git a/engine/assets/shaders/gi_clip_fill.slang b/engine/assets/shaders/gi_clip_fill.slang new file mode 100644 index 000000000..f6d75033e --- /dev/null +++ b/engine/assets/shaders/gi_clip_fill.slang @@ -0,0 +1,228 @@ +// Set 1 is the voxel storage with the trace scene lists +import voxel_dda; +import gi_clip_common; + +[[vk::binding(0, 0)]] +StructuredBuffer gClipFrame; + +/// Albedo rgb and opacity a +[[vk::binding(1, 0)]] +[[vk::image_format("rgba8")]] +RWTexture3D gMaterial; + +[[vk::binding(2, 0)]] +[[vk::image_format("rgba16f")]] +RWTexture3D gEmission; + +/// xyz share of the cell cross section blocked along each axis and w 1 when anything is solid +[[vk::binding(3, 0)]] +[[vk::image_format("rgba8")]] +RWTexture3D gOpacity; + +/// Bounce irradiance per giClipFace which only the scroll clears here +[[vk::binding(4, 0)]] +[[vk::image_format("r32ui")]] +RWTexture3D gAmbient[kGiClipFaces]; + +// Mirrors scene_trace.slang which is not imported since it pulls in lighting +[[vk::binding(10, 1)]] +StructuredBuffer gTraceVolumes; +/// xyz centre w radius +[[vk::binding(11, 1)]] +StructuredBuffer gTraceBounds; +[[vk::binding(12, 1)]] +StructuredBuffer gTraceGrid; + +static const uint kTraceFarCount = 6u; +static const uint kTraceFarOffset = 8u; +static const uint kTraceEntriesOffset = 10u; +static const uint kTraceHeaderWords = 16u; + +struct GiClipFillPush +{ + /// xyz first global cell w level + int4 boxMin; + /// w 1 for cells that scrolled in + int4 boxSize; +}; + +[[vk::push_constant]] +GiClipFillPush gPush; + +static const uint kClipSide = 4u; +static const uint kClipSamples = kClipSide * kClipSide * kClipSide; + +struct ClipCell +{ + float3 albedo; + float albedoCount; + float3 emission; + /// One bit per sample at x + 4 y + 16 z with z 0 and 1 in x + uint2 solid; +}; + +bool clipSolidBit(ClipCell cell, uint index) +{ + return (((index < 32u ? cell.solid.x : cell.solid.y) >> (index & 31u)) & 1u) != 0u; +} + +void clipSample(uint v, float3 world, float gap, uint index, inout ClipCell cell) +{ + if (clipSolidBit(cell, index)) + { + return; + } + const VoxelInstance volume = gTraceVolumes[v]; + const VolumeRecord record = gVolumeRecords[volume.recordIndex]; + // Pyramid block at least as wide as the sample gap in voxels so nothing thinner slips between samples + const float gapVoxels = gap * length(volume.worldToVoxel[0].xyz); + const uint pyramid = uint(clamp(ceil(log2(max(gapVoxels, 1.0)) - 0.01), 0.0, float(kLevelCoarse))); + const int3 voxel = int3(floor(mul(volume.worldToVoxel, float4(world, 1.0)).xyz)); + // occupiedAtLevel only bounds the coarse cell and a coarse cell can reach past the bricks + const int3 dims = int3(record.brickDimsX, record.brickDimsY, record.brickDimsZ) * int(kBrickDim); + if (any(voxel < 0) || any(voxel >= dims) || !occupiedAtLevel(record, voxel, pyramid, true)) + { + return; + } + if (index < 32u) + { + cell.solid.x |= 1u << index; + } + else + { + cell.solid.y |= 1u << (index - 32u); + } + + uint material = voxelMaterialAt(record, voxel); + // A solid block of the pyramid can hold an empty voxel right at the sample + const int shift = int(min(pyramid, 3u)); + const int3 base = (voxel >> shift) << shift; + const int last = (1 << shift) - 1; + for (uint corner = 0u; corner < 8u && material == 0u && shift > 0; ++corner) + { + material = voxelMaterialAt(record, base + int3(corner & 1u, (corner >> 1) & 1u, corner >> 2) * last); + } + if (material == 0u) + { + return; + } + const PaletteSample palette = samplePalette(record, material); + cell.albedo += palette.albedo; + cell.albedoCount += 1.0; + cell.emission += palette.albedo * palette.emissive; +} + +/// 16 bits of one z layer at x + 4 y +uint clipLayer(ClipCell cell, uint z) +{ + return ((z < 2u ? cell.solid.x : cell.solid.y) >> ((z & 1u) * 16u)) & 0xFFFFu; +} + +float3 clipBlocked(ClipCell cell) +{ + float3 blocked = float3(0.0, 0.0, 0.0); + uint any = 0u; + for (uint z = 0u; z < kClipSide; ++z) + { + const uint layer = clipLayer(cell, z); + any |= layer; + for (uint i = 0u; i < kClipSide; ++i) + { + blocked.x += ((layer >> (i * 4u)) & 0xFu) != 0u ? 1.0 : 0.0; + blocked.y += (layer & (0x1111u << i)) != 0u ? 1.0 : 0.0; + } + } + blocked.z = float(countbits(any)); + return blocked / float(kClipSide * kClipSide); +} + +float3 clipSamplePoint(float3 low, float cellSize, uint index) +{ + return low + (float3(index & 3u, (index >> 2) & 3u, index >> 4) + 0.5) * (cellSize / float(kClipSide)); +} + +[shader("compute")] +[numthreads(4, 4, 4)] +void fillMain(uint3 id : SV_DispatchThreadID) +{ + if (any(int3(id) >= gPush.boxSize.xyz)) + { + return; + } + const GiClipFrame frame = gClipFrame[0]; + const uint level = uint(gPush.boxMin.w); + const float cellSize = frame.levels[level].w; + const int3 global = gPush.boxMin.xyz + int3(id); + const float3 low = float3(global) * cellSize; + const float3 centre = low + 0.5 * cellSize; + const float gap = cellSize / float(kClipSide); + + ClipCell cell; + cell.albedo = float3(0.0, 0.0, 0.0); + cell.albedoCount = 0.0; + cell.emission = float3(0.0, 0.0, 0.0); + cell.solid = uint2(0u, 0u); + + const uint farCount = gTraceGrid[kTraceFarCount]; + const uint farBase = gTraceGrid[kTraceFarOffset]; + for (uint f = 0u; f < farCount; ++f) + { + const uint v = gTraceGrid[farBase + f]; + const float4 bounds = gTraceBounds[v]; + if (distance(centre, bounds.xyz) > bounds.w + cellSize * 0.8661) + { + continue; + } + for (uint s = 0u; s < kClipSamples; ++s) + { + clipSample(v, clipSamplePoint(low, cellSize, s), gap, s, cell); + } + } + + const float3 gridOrigin = float3(asfloat(gTraceGrid[0]), asfloat(gTraceGrid[1]), asfloat(gTraceGrid[2])); + const float gridCell = asfloat(gTraceGrid[3]); + const int gridDim = int(gTraceGrid[4]); + const uint entriesBase = gTraceGrid[kTraceEntriesOffset]; + for (uint s = 0u; s < kClipSamples; ++s) + { + const float3 point = clipSamplePoint(low, cellSize, s); + const int3 g = int3(floor((point - gridOrigin) / gridCell)); + if (any(g < 0) || any(g >= gridDim)) + { + continue; + } + const uint index = uint(g.x + g.y * gridDim + g.z * gridDim * gridDim); + const uint first = gTraceGrid[kTraceHeaderWords + 2u * index]; + const uint count = gTraceGrid[kTraceHeaderWords + 2u * index + 1u]; + for (uint e = 0u; e < count; ++e) + { + const uint v = gTraceGrid[entriesBase + first + e]; + const float4 bounds = gTraceBounds[v]; + if (distance(point, bounds.xyz) > bounds.w) + { + continue; + } + clipSample(v, point, gap, s, cell); + } + } + + const int3 texel = giClipWrap(global, int(frame.size.x)); + const float3 albedo = cell.albedoCount > 0.0 ? cell.albedo / cell.albedoCount : float3(0.5, 0.5, 0.5); + const bool solid = any(cell.solid != 0u); + gMaterial[texel] = float4(albedo, solid ? 1.0 : 0.0); + // Over the solid samples like the albedo + gEmission[texel] = float4(cell.emission / max(cell.albedoCount, 1.0), 0.0); + // A slab seen edge on blocks only its share so cones over a floor are not swallowed by it + if (!giClipInner(frame, level, global)) + { + gOpacity[texel] = float4(clipBlocked(cell), solid ? 1.0 : 0.0); + } + // Cells that scrolled in hold the bounce of whatever wrapped there before + if (gPush.boxSize.w != 0) + { + for (uint face = 0u; face < kGiClipFaces; ++face) + { + gAmbient[face][texel] = 0u; + } + } +} diff --git a/engine/assets/shaders/gi_clip_fill.slang.meta b/engine/assets/shaders/gi_clip_fill.slang.meta new file mode 100644 index 000000000..35dd67f08 --- /dev/null +++ b/engine/assets/shaders/gi_clip_fill.slang.meta @@ -0,0 +1,4 @@ +uid = "G1C1pFi1100" +type = "shader" +created_at = "2026-11-10T00:00:00.0000000Z" +modified_at = "2026-11-10T00:00:00.0000000Z" diff --git a/engine/assets/shaders/gi_clip_inject.slang b/engine/assets/shaders/gi_clip_inject.slang new file mode 100644 index 000000000..e1c598520 --- /dev/null +++ b/engine/assets/shaders/gi_clip_inject.slang @@ -0,0 +1,159 @@ +import lighting; +import gi_clip_common; +import gi_clip_trace; + +[[vk::binding(0, 1)]] +StructuredBuffer gClipFrame; + +[[vk::binding(2, 1)]] +Sampler3D gEmission; + +/// One per giClipFace of the level written and sampled as B10G11R11 through a second view +[[vk::binding(3, 1)]] +[[vk::image_format("r32ui")]] +RWTexture3D gRadiance[kGiClipFaces]; + +/// Bounce irradiance over pi per giClipFace of the level written +[[vk::binding(4, 1)]] +Sampler3D gAmbient[kGiClipFaces]; + +/// xyz share of the cell blocked along each axis of the level written +[[vk::binding(5, 1)]] +Sampler3D gOpacity; + +/// Mirrors gi_clip_fill GiClipFillPush +struct GiClipInjectPush +{ + /// xyz first global cell w level + int4 boxMin; + int4 boxSize; +}; + +[[vk::push_constant]] +GiClipInjectPush gPush; + +static const uint kGiClipMaxLocalLights = 64u; + +float clipFaceCosines(uint exposed, float3 L) +{ + float cosines = 0.0; + for (uint face = 0u; face < kGiClipFaces; ++face) + { + if ((exposed & (1u << face)) != 0u) + { + cosines += max(dot(float3(giClipFace(face)), L), 0.0); + } + } + return cosines; +} + +struct ClipFaces +{ + float3 irradiance[kGiClipFaces]; +}; + +void clipAddLight(inout ClipFaces faces, uint exposed, float3 L, float3 radiance) +{ + for (uint face = 0u; face < kGiClipFaces; ++face) + { + if ((exposed & (1u << face)) != 0u) + { + faces.irradiance[face] += radiance * max(dot(float3(giClipFace(face)), L), 0.0); + } + } +} + +[shader("compute")] +[numthreads(4, 4, 4)] +void injectMain(uint3 id : SV_DispatchThreadID) +{ + if (any(int3(id) >= gPush.boxSize.xyz)) + { + return; + } + const GiClipFrame frame = gClipFrame[0]; + const uint level = uint(gPush.boxMin.w); + const int resolution = int(frame.size.x); + const float cellSize = frame.levels[level].w; + const int3 low = int3(frame.levels[level].xyz); + const int3 global = gPush.boxMin.xyz + int3(id); + if (giClipInner(frame, level, global)) + { + return; + } + const int3 texel = giClipWrap(global, resolution); + + const float4 material = gClipMaterial[level].Load(int4(texel, 0)); + // A neighbour outside the level counts as solid so the level edge never lights up + uint exposed = 0u; + for (uint face = 0u; face < kGiClipFaces && material.a > 0.0; ++face) + { + const int3 neighbour = global + giClipFace(face); + const int3 local = neighbour - low; + if (any(local < 0) || any(local >= resolution)) + { + continue; + } + if (gClipMaterial[level].Load(int4(giClipWrap(neighbour, resolution), 0)).a <= 0.0) + { + exposed |= 1u << face; + } + } + if (exposed == 0u) + { + for (uint face = 0u; face < kGiClipFaces; ++face) + { + gRadiance[face][texel] = 0u; + } + return; + } + + const float3 emission = gEmission.Load(int4(texel, 0)).rgb; + const float3 centre = giClipCellCentre(frame, level, global); + // Past the cell and its direct neighbours so they never shadow it + const float lift = 1.5 * cellSize; + const float sunReach = 0.5 * float(resolution) * frame.levels[frame.size.y - 1u].w; + ClipFaces faces; + for (uint face = 0u; face < kGiClipFaces; ++face) + { + faces.irradiance[face] = float3(0.0, 0.0, 0.0); + } + + for (uint di = 0u; di < gCamera.directionalLightCountPad.x; ++di) + { + const DirectionalLightGpu light = gCamera.directionalLights[di]; + const float3 L = normalize(-light.direction.xyz); + if (clipFaceCosines(exposed, L) <= 0.0) + { + continue; + } + const float visibility = giClipVisibility(frame, centre + L * lift, L * sunReach); + clipAddLight(faces, exposed, L, light.colorIntensity.rgb * (light.colorIntensity.a * visibility)); + } + + const uint lightCount = min(gClusterParams.lightCounts.x, kGiClipMaxLocalLights); + for (uint li = 0u; li < lightCount; ++li) + { + const GpuLight light = gLights[li]; + float3 L; + float distance; + const float3 radiance = lightSampleRadiance(light, centre, light.worldPosRange.xyz, L, distance); + if (all(radiance <= 0.0) || clipFaceCosines(exposed, L) <= 0.0) + { + continue; + } + // Stops short of the lamp so the cells holding it do not block it + const float visibility = giClipVisibility(frame, centre + L * lift, L * max(distance - 2.0 * lift, 0.0)); + clipAddLight(faces, exposed, L, radiance * visibility); + } + + // Premultiplied by the covered share of the cell so filtering and downsampling keep its energy + const float3 blocked = gOpacity.Load(int4(texel, 0)).xyz; + for (uint face = 0u; face < kGiClipFaces; ++face) + { + const bool open = (exposed & (1u << face)) != 0u; + const float3 bounce = gAmbient[face].Load(int4(texel, 0)).rgb; + const float3 radiance = emission + material.rgb * (faces.irradiance[face] / kPi + bounce); + gRadiance[face][texel] = open ? giClipPackRadiance(radiance * blocked[face >> 1]) : 0u; + } +} diff --git a/engine/assets/shaders/gi_clip_inject.slang.meta b/engine/assets/shaders/gi_clip_inject.slang.meta new file mode 100644 index 000000000..a558763ed --- /dev/null +++ b/engine/assets/shaders/gi_clip_inject.slang.meta @@ -0,0 +1,4 @@ +uid = "G1C1pInje00" +type = "shader" +created_at = "2026-11-10T00:00:00.0000000Z" +modified_at = "2026-11-10T00:00:00.0000000Z" diff --git a/engine/assets/shaders/gi_clip_trace.slang b/engine/assets/shaders/gi_clip_trace.slang new file mode 100644 index 000000000..c1f33b58b --- /dev/null +++ b/engine/assets/shaders/gi_clip_trace.slang @@ -0,0 +1,38 @@ +import gi_clip_common; + +/// Every level bound and unused slots repeat level 0 +[[vk::binding(1, 1)]] +Sampler3D gClipMaterial[kGiClipMaxLevels]; + +bool giClipSolid(GiClipFrame frame, uint level, float3 world) +{ + const int3 cell = int3(floor(world / frame.levels[level].w)); + return gClipMaterial[level].Load(int4(giClipWrap(cell, int(frame.size.x)), 0)).a > 0.0; +} + +/// 1 when nothing solid lies between origin and origin + segment and the caller offsets origin off its own cell +float giClipVisibility(GiClipFrame frame, float3 origin, float3 segment) +{ + const float reach = length(segment); + if (reach <= 0.0) + { + return 1.0; + } + const float3 direction = segment / reach; + float t = 0.0; + for (uint step = 0u; step < 512u && t < reach; ++step) + { + const float3 point = origin + direction * t; + const uint level = giClipLevelAt(frame, point); + if (level >= kGiClipMaxLevels) + { + return 1.0; + } + if (giClipSolid(frame, level, point)) + { + return 0.0; + } + t += 0.75 * frame.levels[level].w; + } + return 1.0; +} diff --git a/engine/assets/shaders/gi_clip_trace.slang.meta b/engine/assets/shaders/gi_clip_trace.slang.meta new file mode 100644 index 000000000..281fb0634 --- /dev/null +++ b/engine/assets/shaders/gi_clip_trace.slang.meta @@ -0,0 +1,4 @@ +uid = "G1C1pTrac00" +type = "shader" +created_at = "2026-11-10T00:00:00.0000000Z" +modified_at = "2026-11-10T00:00:00.0000000Z" diff --git a/engine/assets/shaders/gi_sample.slang b/engine/assets/shaders/gi_sample.slang index a9517c31a..e68cc85fc 100644 --- a/engine/assets/shaders/gi_sample.slang +++ b/engine/assets/shaders/gi_sample.slang @@ -1,5 +1,6 @@ // Set 0 written by SceneDescriptorSets from GiPass import gi_common; +import gi_clip_common; /// Copied by GiPass after its merge so this is the frame the tables belong to and frame.x 0 means no GI yet [[vk::binding(17, 0)]] @@ -18,6 +19,22 @@ StructuredBuffer gGiPool; [[vk::binding(21, 0)]] Sampler2D gGiIrradiance; +/// Published by GiClipmapPass after its inject and size.z 0 means no clipmap GI +[[vk::binding(24, 0)]] +StructuredBuffer gGiClipFrame; + +/// Face radiance at level * kGiClipFaces + face +[[vk::binding(25, 0)]] +Sampler3D gGiClipRadiance[kGiClipMaxLevels * kGiClipFaces]; + +/// xyz opacity along each axis and w the solid share +[[vk::binding(26, 0)]] +Sampler3D gGiClipOpacity[kGiClipMaxLevels]; + +/// Bounce irradiance over pi each face gathered at level * kGiClipFaces + face +[[vk::binding(27, 0)]] +Sampler3D gGiClipAmbient[kGiClipMaxLevels * kGiClipFaces]; + static const uint kRcMaxProbes = 32u; /// c0 tile per corner around @p base or kGiEmpty with each stage batched over all eight @@ -160,3 +177,363 @@ float radianceCascadesContactReach(float3 worldPosition) bool overlap = false; return frame.rays.x * giSpacing(frame, giLod(frame, worldPosition, overlap), 0u); } + +/// Diameter per meter of a 60 degree cone +static const float kGiClipConeSpread = 1.1547; +static const uint kGiClipConeSteps = 10u; +/// 0 since finer levels leave blind rings between cones that show as halos +static const float kGiClipConeBias = 0.0; +/// Cells of level 0 the cones start off the surface so its own cells do not shade it +static const float kGiClipConeLift = 1.5; +static const float kGiClipFaceWeight = 1e-4; + +/// Premultiplied radiance of the faces looking back at the ray and opacity along it +/// @p lod above 0 reads the mips of the last level which stand in for coarser levels over the same box +float4 giClipSample(GiClipFrame frame, uint level, float lod, float3 world, float3 direction) +{ + // The repeat sampler does the toroidal wrap + const float3 uvw = world / (frame.levels[level].w * float(frame.size.x)); + const float3 blocked = gGiClipOpacity[NonUniformResourceIndex(level)].SampleLevel(uvw, lod).xyz; + const float3 weight = direction * direction; + const float opacity = dot(weight, blocked); + if (opacity <= 0.0) + { + return float4(0.0, 0.0, 0.0, 0.0); + } + const uint base = level * kGiClipFaces; + float3 radiance = float3(0.0, 0.0, 0.0); + [unroll] + for (uint axis = 0u; axis < 3u; ++axis) + { + if (weight[axis] > kGiClipFaceWeight) + { + const uint face = base + axis * 2u + (direction[axis] > 0.0 ? 1u : 0u); + radiance += weight[axis] * gGiClipRadiance[NonUniformResourceIndex(face)].SampleLevel(uvw, lod).rgb; + } + } + // Each face is stored times its own coverage so this is already premultiplied + return float4(radiance, opacity); +} + +/// Weight and place of one of the eight filtered reads of a quadratic B-spline over the 27 cells around a point +float4 giClipSmoothTap(float3 cell, float3 f, float cells, uint tap) +{ + const float3 after = 0.5 * (0.5 + f) * (0.5 + f); + const float3 near = 1.0 - after; + const float3 before = 0.5 * (0.5 - f) * (0.5 - f); + const bool3 far = bool3((tap & 1u) != 0u, (tap & 2u) != 0u, (tap & 4u) != 0u); + const float3 share = select(far, after, near); + const float3 at = select(far, cell + 1.5, cell - 0.5 + (near - before) / near); + return float4(at / cells, share.x * share.y * share.z); +} + +/// Trilinear draws cells as creased pyramids so this rounds them at 8 reads per texture +/// The taps are worked out again for each read since holding all eight costs registers every pixel pays for +float4 giClipSampleSmooth(GiClipFrame frame, float3 world, float3 direction) +{ + const float cells = float(frame.size.x); + const float3 p = world / frame.levels[0].w; + const float3 cell = floor(p); + // Offset from the centre of the cell holding the point in -0.5 to 0.5 + const float3 f = p - cell - 0.5; + + float3 blocked = float3(0.0, 0.0, 0.0); + for (uint tap = 0u; tap < 8u; ++tap) + { + const float4 read = giClipSmoothTap(cell, f, cells, tap); + blocked += read.w * gGiClipOpacity[0].SampleLevel(read.xyz, 0.0).xyz; + } + const float3 weight = direction * direction; + const float opacity = dot(weight, blocked); + if (opacity <= 0.0) + { + return float4(0.0, 0.0, 0.0, 0.0); + } + const uint3 face = uint3(direction.x > 0.0 ? 1u : 0u, direction.y > 0.0 ? 3u : 2u, direction.z > 0.0 ? 5u : 4u); + float3 radiance = float3(0.0, 0.0, 0.0); + for (uint tap = 0u; tap < 8u; ++tap) + { + const float4 read = giClipSmoothTap(cell, f, cells, tap); + [unroll] + for (uint axis = 0u; axis < 3u; ++axis) + { + if (weight[axis] > kGiClipFaceWeight) + { + radiance += read.w * weight[axis] * + gGiClipRadiance[NonUniformResourceIndex(face[axis])].SampleLevel(read.xyz, 0.0).rgb; + } + } + } + return float4(radiance, opacity); +} + +float giClipSolidShare(GiClipFrame frame, uint level, float3 world) +{ + const float3 uvw = world / (frame.levels[level].w * float(frame.size.x)); + return gGiClipOpacity[NonUniformResourceIndex(level)].SampleLevel(uvw, 0.0).w; +} + +/// Radiance rgb and coverage a starting @p start meters along the cone and reading no level finer than @p base +/// Smooth above 0 reads level 0 through giClipSampleSmooth and is a compile time choice so shaders that only +/// take the plain cone do not carry the smooth filter +float4 giClipCone(GiClipFrame frame, float3 origin, float3 direction, float start, float base) +{ + const float cell = frame.levels[0].w; + const float last = float(frame.size.y - 1u); + float t = start; + float4 sum = float4(0.0, 0.0, 0.0, 0.0); + for (uint step = 0u; step < kGiClipConeSteps && sum.a < 0.98; ++step) + { + const float3 point = origin + direction * t; + const float held = giClipLevelSoft(frame, point); + if (held >= float(kGiClipMaxLevels)) + { + break; + } + const float diameter = max(kGiClipConeSpread * t, cell); + // Cones read cells as wide as themselves or leave blind rings so past the last level they climb its mips + const float wanted = clamp(log2(diameter / cell) - kGiClipConeBias, max(min(held, last), base), last + float(frame.size.w)); + float4 sample; + if (wanted > last) + { + sample = giClipSample(frame, uint(last), wanted - last, point, direction); + } + else + { + const uint fine = uint(floor(wanted)); + const uint coarse = min(fine + 1u, uint(last)); + const float blend = wanted - float(fine); + if (Smooth > 0 && fine == 0u && coarse != fine) + { + // Level 1 reaches past the 27 cells so where it holds nothing they are empty and one read settles it + sample = float4(0.0, 0.0, 0.0, 0.0); + if (giClipSolidShare(frame, coarse, point) > 0.0) + { + sample = giClipSampleSmooth(frame, point, direction); + if (blend > 0.0) + { + sample = lerp(sample, giClipSample(frame, coarse, 0.0, point, direction), blend); + } + } + } + else if (blend > 0.0 && coarse != fine) + { + // Coarse is built from fine so where it is empty so is fine and the step costs one read + sample = giClipSample(frame, coarse, 0.0, point, direction); + if (sample.a > 0.0) + { + sample = lerp(giClipSample(frame, fine, 0.0, point, direction), sample, blend); + } + } + else + { + sample = giClipSample(frame, fine, 0.0, point, direction); + } + } + sum += (1.0 - sum.a) * sample; + // One cell of the level read a step so each cell is composited once with no opacity correction + t += max(diameter, cell * exp2(wanted)); + } + return sum; +} + +float giClipCellAt(GiClipFrame frame, float3 worldPosition) +{ + return frame.levels[0].w * exp2(min(giClipLevelSoft(frame, worldPosition), float(frame.size.y - 1u))); +} + +/// xyz irradiance over pi and w the share of the hemisphere the cones left open +float4 giClipGather(GiClipFrame frame, float3 worldPosition, float3 normal, float turn, float base) +{ + // Coarser levels thicken every surface so the cones start further off it there + const float cell = frame.levels[0].w * exp2(base); + const float3 origin = worldPosition + normal * (kGiClipConeLift * cell); + const float side = normal.z >= 0.0 ? 1.0 : -1.0; + const float a = -1.0 / (side + normal.z); + const float b = normal.x * normal.y * a; + const float3 tangent = float3(1.0 + side * normal.x * normal.x * a, side * b, -side * normal.x); + const float3 bitangent = float3(b, side + normal.y * normal.y * a, -normal.y); + + float4 cone = giClipCone<1>(frame, origin, normal, 0.0, base); + float4 gathered = 0.25 * float4(cone.rgb, 1.0 - cone.a); + for (uint i = 0u; i < 5u; ++i) + { + const float angle = (float(i) + turn) * 1.25663706; + const float3 direction = normal * 0.5 + (tangent * cos(angle) + bitangent * sin(angle)) * 0.8660254; + cone = giClipCone<1>(frame, origin, direction, 0.0, base); + gathered += 0.15 * float4(cone.rgb, 1.0 - cone.a); + } + return gathered; +} + +/// @p turn in 0 to 1 spins the side cones by up to the fifth of a turn between two of them +/// Nothing here is random and lit pixels pass 0 since any per frame noise flickers around bright lights +bool sampleGiClipmap(float3 worldPosition, float3 normal, float turn, out float3 irradiance, out float sky) +{ + irradiance = float3(0.0, 0.0, 0.0); + sky = 0.0; + const GiClipFrame frame = gGiClipFrame[0]; + if (frame.size.z == 0u) + { + return false; + } + const float soft = giClipLevelSoft(frame, worldPosition); + if (soft >= float(kGiClipMaxLevels)) + { + return false; + } + const float last = float(frame.size.y - 1u); + const float base = floor(min(soft, last)); + float4 gathered = giClipGather(frame, worldPosition, normal, turn, base); + // Near a level edge two gathers cross fade since sliding one start between levels draws strips + const float fade = min(soft, last) - base; + if (fade > 0.0) + { + gathered = lerp(gathered, giClipGather(frame, worldPosition, normal, turn, base + 1.0), fade); + } + irradiance = gathered.rgb; + sky = gathered.a; + return true; +} + +bool sampleGiClipmapCheap(float3 worldPosition, float3 normal, out float3 irradiance, out float sky) +{ + irradiance = float3(0.0, 0.0, 0.0); + sky = 0.0; + const GiClipFrame frame = gGiClipFrame[0]; + if (frame.size.z == 0u) + { + return false; + } + const float soft = giClipLevelSoft(frame, worldPosition); + if (soft >= float(kGiClipMaxLevels)) + { + return false; + } + // The coarser level of a fade band alone so the band costs one cone too + const float base = ceil(min(soft, float(frame.size.y - 1u))); + const float3 origin = worldPosition + normal * (kGiClipConeLift * frame.levels[0].w * exp2(base)); + const float4 cone = giClipCone<0>(frame, origin, normal, 0.0, base); + irradiance = cone.rgb; + sky = 1.0 - cone.a; + return true; +} + +bool giIrradianceCheap(float3 worldPosition, float3 normal, out float3 irradiance, out float sky) +{ + if (sampleGiClipmapCheap(worldPosition, normal, irradiance, sky)) + { + return true; + } + sky = 0.0; + return sampleRadianceCascades(worldPosition, normal, irradiance); +} + +/// The clipmap when it is published else the cascades whose @p sky is 0 since they hold the sky +bool giIrradiance(float3 worldPosition, float3 normal, float turn, out float3 irradiance, out float sky) +{ + if (sampleGiClipmap(worldPosition, normal, turn, irradiance, sky)) + { + return true; + } + sky = 0.0; + return sampleRadianceCascades(worldPosition, normal, irradiance); +} + +/// Irradiance over pi the clipmap already gathered at the faces around a surface point and 0 share off any surface +float4 giClipAmbientAt(GiClipFrame frame, uint level, float3 worldPosition, float3 normal) +{ + const float3 uvw = worldPosition / (frame.levels[level].w * float(frame.size.x)); + const float share = gGiClipOpacity[NonUniformResourceIndex(level)].SampleLevel(uvw, 0.0).w; + const float3 weight = normal * normal; + const uint base = level * kGiClipFaces; + float3 irradiance = float3(0.0, 0.0, 0.0); + [unroll] + for (uint axis = 0u; axis < 3u; ++axis) + { + const uint face = base + axis * 2u + (normal[axis] > 0.0 ? 0u : 1u); + irradiance += weight[axis] * gGiClipAmbient[NonUniformResourceIndex(face)].SampleLevel(uvw, 0.0).rgb; + } + return float4(irradiance, share); +} + +/// Empty cells hold nothing so the filtered value is divided by the solid share around the point +bool sampleGiClipAmbient(float3 worldPosition, float3 normal, out float3 irradiance) +{ + irradiance = float3(0.0, 0.0, 0.0); + const GiClipFrame frame = gGiClipFrame[0]; + if (frame.size.z == 0u) + { + return false; + } + const float soft = giClipLevelSoft(frame, worldPosition); + if (soft >= float(kGiClipMaxLevels)) + { + return false; + } + const float last = float(frame.size.y - 1u); + const float level = min(soft, last); + const uint fine = uint(floor(level)); + float4 ambient = giClipAmbientAt(frame, fine, worldPosition, normal); + if (level > float(fine)) + { + ambient = lerp(ambient, giClipAmbientAt(frame, fine + 1u, worldPosition, normal), level - float(fine)); + } + if (ambient.a < 0.05) + { + return false; + } + irradiance = ambient.rgb / ambient.a; + return true; +} + +bool giHitIrradiance(float3 worldPosition, float3 normal, out float3 irradiance) +{ + if (sampleGiClipAmbient(worldPosition, normal, irradiance)) + { + return true; + } + return sampleRadianceCascades(worldPosition, normal, irradiance); +} + +bool giClipCovers(float3 worldPosition) +{ + const GiClipFrame frame = gGiClipFrame[0]; + return frame.size.z != 0u && giClipLevelSoft(frame, worldPosition) < float(kGiClipMaxLevels); +} + +bool giCover(float3 worldPosition, float3 normal) +{ + return giClipCovers(worldPosition) || radianceCascadesCover(worldPosition, normal); +} + +float giContactReach(float3 worldPosition) +{ + if (giClipCovers(worldPosition)) + { + return kGiClipConeLift * giClipCellAt(gGiClipFrame[0], worldPosition); + } + return radianceCascadesContactReach(worldPosition); +} + +/// Each shader calls the one it needs so it compiles only that path + +float4 giFull(float3 worldPosition, float3 normal) +{ + float3 irradiance; + float sky; + return giIrradiance(worldPosition, normal, 0.0, irradiance, sky) ? float4(irradiance, sky) : float4(0.0, 0.0, 0.0, -1.0); +} + +float4 giCheap(float3 worldPosition, float3 normal) +{ + float3 irradiance; + float sky; + return giIrradianceCheap(worldPosition, normal, irradiance, sky) ? float4(irradiance, sky) : float4(0.0, 0.0, 0.0, -1.0); +} + +float4 giCascades(float3 worldPosition, float3 normal) +{ + float3 irradiance; + return sampleRadianceCascades(worldPosition, normal, irradiance) ? float4(irradiance, 0.0) : float4(0.0, 0.0, 0.0, -1.0); +} diff --git a/engine/assets/shaders/lighting.slang b/engine/assets/shaders/lighting.slang index ce28a364c..0e18219ca 100644 --- a/engine/assets/shaders/lighting.slang +++ b/engine/assets/shaders/lighting.slang @@ -826,7 +826,18 @@ static const uint kShadowProbeTaps = 4u; static const float kWidePenumbraTexels = 6.0; static const uint kWidePenumbraTaps = 16u; -/// Walked per frame so TAA averages the rotation + +/// Indirect diffuse a shader worked out before shading as xyz irradiance over pi and w the open sky share +/// Below 0 means none and lighting never gathers on its own so each shader compiles only the gather it calls +static float4 gGiGathered = float4(0.0, 0.0, 0.0, -1.0); + +bool giSurfaceIrradiance(out float3 irradiance, out float sky) +{ + irradiance = gGiGathered.rgb; + sky = gGiGathered.w; + return gGiGathered.w >= 0.0; +} + float interleavedGradientNoise(float2 pixel) { const float2 shifted = pixel + 5.588238 * float(uint(gCamera.noiseParams.z) & 63u); @@ -1504,14 +1515,15 @@ float4 evaluateDebugView(Surface surface, ClusterCell cluster) case 5: { float3 cascadeIrradiance; - if (sampleRadianceCascades(surface.worldPosition, N, cascadeIrradiance)) + float cascadeSky; + const float3 ambientIrradiance = + gCamera.ambientColorIntensity.rgb * gCamera.ambientColorIntensity.a + + (gCamera.environmentParams.x >= 0.5 ? gIrradianceMap.SampleLevel(N, 0.0).rgb : float3(0.0, 0.0, 0.0)); + if (giSurfaceIrradiance(cascadeIrradiance, cascadeSky)) { - return float4(cascadeIrradiance, 1.0); + return float4(cascadeIrradiance + cascadeSky * ambientIrradiance, 1.0); } - return float4( - gCamera.ambientColorIntensity.rgb * gCamera.ambientColorIntensity.a + - (gCamera.environmentParams.x >= 0.5 ? gIrradianceMap.SampleLevel(N, 0.0).rgb : float3(0.0, 0.0, 0.0)), - 1.0); + return float4(ambientIrradiance, 1.0); } case 6: { @@ -1895,7 +1907,8 @@ ShadingResult evaluateLighting(Surface surface, ClusterC const float3 prefiltered = ambientSpecularRadiance(surface.worldPosition, reflect(-V, N), roughness, bestProbe, bestProbeWeight); float3 cascadeIrradiance; - const bool hasCascades = sampleRadianceCascades(surface.worldPosition, N, cascadeIrradiance); + float cascadeSky; + const bool hasCascades = giSurfaceIrradiance(cascadeIrradiance, cascadeSky); float3 volumeIrradiance = float3(0.0, 0.0, 0.0); bool hasVolumeIrradiance = !hasCascades && sampleIrradianceVolumes(surface.worldPosition, N, volumeIrradiance); @@ -1922,8 +1935,9 @@ ShadingResult evaluateLighting(Surface surface, ClusterC // The cascades already hold the sky and what it bounces off so they replace ambient and baked volumes if (hasCascades) { - irradiance = cascadeIrradiance; - result.contactReach = radianceCascadesContactReach(surface.worldPosition); + // The clipmap leaves the open share of the hemisphere to the ambient above and the cascades leave none + irradiance = cascadeIrradiance + cascadeSky * irradiance; + result.contactReach = giContactReach(surface.worldPosition); } float3 F0 = lerp(float3(0.04, 0.04, 0.04), albedo, metallic); diff --git a/engine/assets/shaders/mesh.slang b/engine/assets/shaders/mesh.slang index 6106b0abd..eae7a2d45 100644 --- a/engine/assets/shaders/mesh.slang +++ b/engine/assets/shaders/mesh.slang @@ -1,6 +1,7 @@ import toast; import lighting; +import gi_sample; import scene_normal; struct MaterialUBO @@ -271,6 +272,7 @@ float4 shadeSurface(VSOutput input, inout float4 outNormalRoughness, inout float surface.viewSpaceZ = input.viewSpaceZ; surface.pixel = input.position.xy; + gGiGathered = giFull(surface.worldPosition, normalize(surface.normal)); ShadingResult lit = shadeSurfaceLighting(surface); outIndirectDiffuse = lit.indirectDiffuse; diff --git a/engine/assets/shaders/volumetrics.slang b/engine/assets/shaders/volumetrics.slang index 203789476..1a5e417c9 100644 --- a/engine/assets/shaders/volumetrics.slang +++ b/engine/assets/shaders/volumetrics.slang @@ -233,7 +233,7 @@ float3 probeHitRadiance(SceneHit hit, float3 origin, float3 direction, inout uin const float3 normal = sceneHitNormal(hit, direction); const PaletteSample palette = samplePalette(gTraceVolumes[hit.volume].recordIndex, hit.material); float3 irradiance; - if (!sampleRadianceCascades(position, normal, irradiance)) + if (!giHitIrradiance(position, normal, irradiance)) { irradiance = gCamera.ambientColorIntensity.rgb * gCamera.ambientColorIntensity.a; if (gCamera.environmentParams.x >= 0.5) diff --git a/engine/assets/shaders/voxel_glass.slang b/engine/assets/shaders/voxel_glass.slang index ddf649f98..bad2480a4 100644 --- a/engine/assets/shaders/voxel_glass.slang +++ b/engine/assets/shaders/voxel_glass.slang @@ -1,6 +1,7 @@ // Forward glass one box per glass brick far to near import voxel_dda; import lighting; +import gi_sample; import scene_normal; import depth_convention; @@ -21,6 +22,8 @@ struct GlassPush uint refractionVoxels; /// Lit glass surfaces per brick and pixel past which layers only absorb uint litSurfaces; + /// 1 when gBackdropDepth holds this frame's opaque depth and the pipeline keeps only glass in front of it + uint depthTest; }; [[vk::push_constant]] @@ -151,6 +154,8 @@ float3 shadeInterface(float3 hitWorld, float3 normal, float3 view, float2 pixel, const float facing = pow(1.0 - saturate(dot(normal, view)), 5.0); fresnel = f0 + (1.0 - f0) * facing; + // Glass scatters a sliver of its diffuse light and a pixel can cross several panes + gGiGathered = giCheap(hitWorld, normal); // One pass split into lobes since each pass resamples every shadow map const ShadingResult lit = shadeSurfaceLighting(surface); debugView = lit.isDebugView; @@ -444,6 +449,18 @@ bool compositeGlass(VSOutput input, bool surfaceOnly, out GlassComposite result) { touched = true; firstT = t; + // Depth is written so the depth test runs after shading and hidden glass would be lit for nothing + if (gGlassPush.depthTest != 0u) + { + const float4 entry = mul(gCamera.viewProjection, float4(camera + worldDirection * t, 1.0)); + const float entryDepth = entry.z / entry.w; + const float opaque = gBackdropDepth.Load(int3(int2(input.position.xy), 0)).r; + // A margin so anything the real test might keep still reaches it + if (isCloserDepth(opaque, entryDepth) && abs(opaque - entryDepth) > 1e-5) + { + return false; + } + } } if (!inside && axis >= 0) diff --git a/engine/assets/shaders/voxel_lighting.slang b/engine/assets/shaders/voxel_lighting.slang index f624a5915..d0a96ad38 100644 --- a/engine/assets/shaders/voxel_lighting.slang +++ b/engine/assets/shaders/voxel_lighting.slang @@ -83,6 +83,11 @@ Sampler2D gNoisySpecular; [[vk::binding(10, 2)]] Sampler2D gDetailNormal; +/// Half resolution clipmap gather of fragmentGiGather with xyz irradiance over pi and w the open sky share +/// or below 0 where it gathered nothing +[[vk::binding(11, 2)]] +Sampler2D gGiGather; + typedef FullscreenVSOutput VSOutput; struct FSOutput @@ -410,6 +415,11 @@ static const uint kReuseSpatial = 2u; static const uint kSceneGlass = 4u; static const uint kAmbientRayQuery = 8u; static const uint kTracedSpecular = 16u; +/// Mirrors VoxelPass k_gi_gather and set when gGiGather holds this frame's half resolution gather +static const uint kGiGather = 32u; +/// Mirrors VoxelPass k_gi_clipmap +static const uint kGiClipmap = 64u; +static const float kGiGatherPlane = 0.15; /// Scene normal roughness of a pixel whose environment specular voxel_specular.slang replaces and SSR skips static const float kTracedMark = 2.0; @@ -791,6 +801,62 @@ SpatialOutput fragmentSpatialOpaque(VSOutput input) return spatialReuse(input, false); } +/// Pixel of each 2x2 block the gather shades which never changes so the result holds still +int2 giGatherPixel(int2 half) +{ + return min(half * 2, int2(gPush.viewport.xy) - 1); +} + +[shader("fragment")] +float4 fragmentGiGather(VSOutput input) : SV_Target0 +{ + const float4 none = float4(0.0, 0.0, 0.0, -1.0); + const int2 pixel = giGatherPixel(int2(input.position.xy)); + float3 normal; + if (!isLitVoxel(gAlbedo.Load(int3(pixel, 0)).a) || !isLitVoxelAt(pixel, normal)) + { + return none; + } + float3 irradiance; + float sky; + if (!sampleGiClipmap(positionAt(pixel), normal, 0.0, irradiance, sky)) + { + return none; + } + return float4(irradiance, sky); +} + +/// w below 0 when none does so the caller gathers on its own +float4 giGatherAt(int2 pixel, float3 position, float3 normal) +{ + const int2 size = (int2(gPush.viewport.xy) + 1) / 2; + const float2 at = float2(pixel) * 0.5; + const int2 base = int2(floor(at)); + const float2 blend = at - float2(base); + float4 sum = float4(0.0, 0.0, 0.0, 0.0); + float total = 0.0; + for (int tap = 0; tap < 4; ++tap) + { + const int2 corner = int2(tap & 1, tap >> 1); + const int2 half = clamp(base + corner, int2(0, 0), size - 1); + const float4 gathered = gGiGather.Load(int3(half, 0)); + const int2 source = giGatherPixel(half); + float3 sourceNormal; + if (gathered.a < 0.0 || !isLitVoxelAt(source, sourceNormal)) + { + continue; + } + const float2 side = lerp(1.0 - blend, blend, float2(corner)); + const float facing = saturate(dot(normal, sourceNormal)); + const float plane = saturate(1.0 - abs(dot(positionAt(source) - position, normal)) / kGiGatherPlane); + // A floor so a pixel right on a gather pixel still takes its neighbours when that one is rejected + const float weight = (side.x * side.y + 0.01) * facing * facing * facing * facing * plane; + sum += gathered * weight; + total += weight; + } + return total > 1e-4 ? sum / total : float4(0.0, 0.0, 0.0, -1.0); +} + [shader("fragment")] FSOutput fragmentMain(VSOutput input) { @@ -844,6 +910,20 @@ FSOutput fragmentMain(VSOutput input) surface.viewSpaceZ = mul(gCamera.view, float4(position, 1.0)).z; surface.pixel = input.position.xy; + if ((gPush.reuse.x & kGiClipmap) == 0u) + { + gGiGathered = giCascades(position, normal); + } + else + { + gGiGathered = (gPush.reuse.x & kGiGather) != 0u ? giGatherAt(pixel, position, faceNormal) : float4(0.0, 0.0, 0.0, -1.0); + // One cone for pixels with no gather pixel on their surface since a full gather here stalls the neighbourhood + if (gGiGathered.w < 0.0) + { + gGiGathered = giCheap(position, faceNormal); + } + } + // Glass scenes leave shadow mapped lights to fragmentMarched which tints them VoxelRayFreeFilter rayFree; rayFree.mapLights = (gPush.reuse.x & kSceneGlass) == 0u || isShadowDebugMode(gCamera.renderModePad.x); @@ -970,7 +1050,7 @@ float4 fragmentAmbient(VSOutput input) : SV_Target0 // Under the cascades the rays only add the contact detail their probe spacing blurs const float reach = float(gPush.reuse.w) * 0.01; - const float contactReach = radianceCascadesCover(position, normal) ? radianceCascadesContactReach(position) : 0.0; + const float contactReach = giCover(position, normal) ? giContactReach(position) : 0.0; const float3 shadowOrigin = position + faceNormal * (kShadowOriginOffset * kVoxelSize); const float occlusion = ambientOcclusion(normal, input.position.xy, shadowOrigin, contactReach > 0.0 ? min(reach, contactReach) : reach); // Premultiplied so the indirect fragmentMain left in noisy diffuse scales by occlusion diff --git a/engine/assets/shaders/voxel_specular.slang b/engine/assets/shaders/voxel_specular.slang index 7d3ddac26..0b743e266 100644 --- a/engine/assets/shaders/voxel_specular.slang +++ b/engine/assets/shaders/voxel_specular.slang @@ -230,7 +230,7 @@ float3 hitRadiance(SceneHit hit, float3 origin, float3 direction, float coneSlop const PaletteSample palette = samplePalette(gTraceVolumes[hit.volume].recordIndex, hit.material); float3 irradiance; - if (!sampleRadianceCascades(position, normal, irradiance)) + if (!giHitIrradiance(position, normal, irradiance)) { irradiance = gCamera.ambientColorIntensity.rgb * gCamera.ambientColorIntensity.a; if (gCamera.environmentParams.x >= 0.5) diff --git a/engine/src/toast/assets/animation.cpp b/engine/src/toast/assets/animation.cpp index 9d050374e..eb0063f91 100644 --- a/engine/src/toast/assets/animation.cpp +++ b/engine/src/toast/assets/animation.cpp @@ -237,6 +237,32 @@ auto AnimationClip::sample(float time) const -> std::unordered_map track_to_bone, std::span pose) const { + ZoneScoped; + const size_t count = std::min(tracks.size(), track_to_bone.size()); + for (size_t i = 0; i < count; ++i) { + const int32_t bone = track_to_bone[i]; + if (bone < 0 || std::cmp_greater_equal(bone, pose.size())) { + continue; + } + const auto& track = tracks[i]; + switch (track.target) { + case TrackTarget::translation: pose[bone].translation = track.sampleVec3(time); break; + case TrackTarget::rotation: pose[bone].rotation = track.sampleQuat(time); break; + case TrackTarget::scale: break; // ignored like sample() + } + } +} + +auto Skeleton::find(std::string_view bone_name) const -> int32_t { + for (size_t i = 0; i < bones.size(); ++i) { + if (bones[i].name == bone_name) { + return static_cast(i); + } + } + return -1; +} + Animation::Animation(std::span data) { ZoneScoped; Reader reader(data); @@ -293,6 +319,27 @@ Animation::Animation(std::span data) { m_skins.push_back(std::move(skin)); } + const auto skeleton_count = reader.read(); + m_skeletons.reserve(skeleton_count); + for (uint32_t i = 0; i < skeleton_count && !reader.overflowed(); ++i) { + Skeleton skeleton; + skeleton.name = reader.readString(); + const auto bone_count = reader.read(); + skeleton.bones.reserve(bone_count); + for (uint32_t b = 0; b < bone_count && !reader.overflowed(); ++b) { + Bone bone; + bone.name = reader.readString(); + bone.parent = reader.read(); + bone.rest = reader.read(); + // Parent below child is what lets SkeletalNode pose in one forward pass + if (bone.parent >= static_cast(b)) { + bone.parent = -1; + } + skeleton.bones.push_back(std::move(bone)); + } + m_skeletons.push_back(std::move(skeleton)); + } + if (reader.overflowed()) { TOAST_ERROR("Animation", "Truncated .tanim file; loaded {} clip(s) before running out of data", m_clips.size()); } @@ -307,7 +354,21 @@ auto Animation::findClip(std::string_view name) const -> const AnimationClip* { return nullptr; } -auto Animation::toBinary(const std::vector& clips, const std::vector& skins) -> std::vector { +auto Animation::findSkeleton(std::string_view name) const -> const Skeleton* { + if (name.empty()) { + return m_skeletons.empty() ? nullptr : &m_skeletons.front(); + } + for (const auto& skeleton : m_skeletons) { + if (skeleton.name == name) { + return &skeleton; + } + } + return nullptr; +} + +auto Animation::toBinary( + const std::vector& clips, const std::vector& skins, const std::vector& skeletons +) -> std::vector { ZoneScoped; Writer writer; writer.write(k_magic); @@ -340,6 +401,17 @@ auto Animation::toBinary(const std::vector& clips, const std::vec writer.writeArray(skin.inverse_bind_matrices); } + writer.write(static_cast(skeletons.size())); + for (const auto& skeleton : skeletons) { + writer.writeString(skeleton.name); + writer.write(static_cast(skeleton.bones.size())); + for (const auto& bone : skeleton.bones) { + writer.writeString(bone.name); + writer.write(bone.parent); + writer.write(bone.rest); + } + } + return writer.take(); } diff --git a/engine/src/toast/assets/animation.hpp b/engine/src/toast/assets/animation.hpp index 7f9027da8..573ba554f 100644 --- a/engine/src/toast/assets/animation.hpp +++ b/engine/src/toast/assets/animation.hpp @@ -27,7 +27,7 @@ namespace assets { namespace _detail { /// Binary layout version for .tanim; readers reject anything they don't recognise -inline constexpr uint32_t animation_format_version = 3; +inline constexpr uint32_t animation_format_version = 4; } /// @brief How a sampler interpolates between two keyframes, matching glTF's three modes @@ -96,6 +96,28 @@ struct NodePose { float _pad; }; +/// Local bone transform, trivially copyable since .tanim writes it raw +struct BonePose { + glm::quat rotation {1.0f, 0.0f, 0.0f, 0.0f}; + glm::vec3 translation {0.0f}; + glm::vec3 scale {1.0f}; +}; + +struct TOAST_API Bone { + std::string name; + int32_t parent = -1; ///< always below this bone index + BonePose rest; +}; + +struct TOAST_API Skeleton { + std::string name; + std::vector bones; + + /// @returns bone index or -1 + [[nodiscard]] + auto find(std::string_view bone_name) const -> int32_t; +}; + /// @brief A named set of tracks that play together struct TOAST_API AnimationClip { std::string name; @@ -110,6 +132,9 @@ struct TOAST_API AnimationClip { [[nodiscard]] auto sample(float time) const -> std::unordered_map; + /// Writes tracks whose @p track_to_bone entry is a valid bone into @p pose, no allocation + void sampleInto(float time, std::span track_to_bone, std::span pose) const; + /// @brief Wraps @p time into [0, duration], for looping playback [[nodiscard]] auto wrap(float time) const -> float { @@ -177,17 +202,29 @@ class TOAST_API Animation : public Asset { return m_skins; } + [[nodiscard]] + auto skeletons() const noexcept -> const std::vector& { + return m_skeletons; + } + + /// @returns the skeleton with this name, the first one for an empty name, or nullptr + [[nodiscard]] + auto findSkeleton(std::string_view name) const -> const Skeleton*; + /// @returns the clip with this name, or nullptr [[nodiscard]] auto findClip(std::string_view name) const -> const AnimationClip*; /// @brief Serialises clips + skins into the binary .tanim layout the constructor reads back [[nodiscard]] - static auto toBinary(const std::vector& clips, const std::vector& skins) -> std::vector; + static auto + toBinary(const std::vector& clips, const std::vector& skins, const std::vector& skeletons) + -> std::vector; private: std::vector m_clips; std::vector m_skins; + std::vector m_skeletons; }; } diff --git a/engine/src/toast/assets/gltf_importer.cpp b/engine/src/toast/assets/gltf_importer.cpp index c54418dc5..3184999e6 100644 --- a/engine/src/toast/assets/gltf_importer.cpp +++ b/engine/src/toast/assets/gltf_importer.cpp @@ -20,9 +20,11 @@ #include #include #include +#include #include #include #include +#include #include #define TINYGLTF3_IMPLEMENTATION #define TINYGLTF3_ENABLE_FS @@ -1109,8 +1111,7 @@ auto generateIntermediates(const std::filesystem::path& path) { constexpr double k_physical_intensity_threshold = 100.0; size_t physical_intensity_lights = 0; - auto node_transform = [&](const tg3_node& node) -> nlohmann::json { - nlohmann::json transform; + auto node_local_pose = [&](const tg3_node& node) -> BonePose { glm::mat4 local_transform = glm::mat4(1.0F); if (node.has_matrix) { @@ -1148,13 +1149,232 @@ auto generateIntermediates(const std::filesystem::path& path) { r = glm::quat(1.0F, 0.0F, 0.0F, 0.0F); } - transform["pos"] = {t.x, t.y, t.z}; - transform["rot"] = {r.x, r.y, r.z, r.w}; - transform["scl"] = {s.x, s.y, s.z}; + return BonePose {.rotation = r, .translation = t, .scale = s}; + }; + + auto pose_json = [](const BonePose& pose) -> nlohmann::json { + nlohmann::json transform; + transform["pos"] = {pose.translation.x, pose.translation.y, pose.translation.z}; + transform["rot"] = {pose.rotation.x, pose.rotation.y, pose.rotation.z, pose.rotation.w}; + transform["scl"] = {pose.scale.x, pose.scale.y, pose.scale.z}; return transform; }; - std::function walk_node = [&](int32_t node_idx) -> nlohmann::json { + auto node_transform = [&](const tg3_node& node) -> nlohmann::json { return pose_json(node_local_pose(node)); }; + + const auto node_count = static_cast(model.nodes_count); + std::vector node_parent(node_count, -1); + for (int32_t i = 0; i < node_count; ++i) { + for (uint32_t c = 0; c < model.nodes[i].children_count; ++c) { + const int32_t child = model.nodes[i].children[c]; + if (child >= 0 && child < node_count) { + node_parent[child] = i; + } + } + } + + std::vector is_joint(node_count, 0); + for (uint32_t sk = 0; sk < model.skins_count; ++sk) { + for (uint32_t j = 0; j < model.skins[sk].joints_count; ++j) { + const int32_t joint = model.skins[sk].joints[j]; + if (joint >= 0 && joint < node_count) { + is_joint[joint] = 1; + } + } + } + + const auto has_content = [&](int32_t idx) { + const auto& node = model.nodes[idx]; + return node.mesh != -1 || node.light != -1 || node.camera != -1; + }; + + // Bit 1 joint somewhere in the subtree, bit 2 content somewhere in the subtree + std::vector subtree_flags(node_count, 0); + std::vector subtree_done(node_count, 0); + std::function compute_subtree = [&](int32_t idx) -> uint8_t { + if (subtree_done[idx] != 0) { + return subtree_flags[idx]; + } + subtree_done[idx] = 1; + auto flags = static_cast((is_joint[idx] != 0 ? 1 : 0) | (has_content(idx) ? 2 : 0)); + for (uint32_t c = 0; c < model.nodes[idx].children_count; ++c) { + const int32_t child = model.nodes[idx].children[c]; + if (child >= 0 && child < node_count) { + flags |= compute_subtree(child); + } + } + subtree_flags[idx] = flags; + return flags; + }; + for (int32_t i = 0; i < node_count; ++i) { + compute_subtree(i); + } + + // Empty transform subtrees under a bone stay bones (leaf tails) rather than becoming attachments + const auto is_bone_child = [&](int32_t idx) { return (subtree_flags[idx] & 1) != 0 || (subtree_flags[idx] & 2) == 0; }; + + std::vector skin_group(skins.size()); + std::iota(skin_group.begin(), skin_group.end(), size_t {0}); + std::function group_of = [&](size_t sk) -> size_t { + return skin_group[sk] == sk ? sk : skin_group[sk] = group_of(skin_group[sk]); + }; + { + std::unordered_map joint_owner; + for (uint32_t sk = 0; sk < model.skins_count && sk < skins.size(); ++sk) { + for (uint32_t j = 0; j < model.skins[sk].joints_count; ++j) { + const auto [it, inserted] = joint_owner.try_emplace(model.skins[sk].joints[j], sk); + if (!inserted) { + skin_group[group_of(sk)] = group_of(it->second); + } + } + } + } + + struct SkeletonPlan { + int32_t host = -1; ///< glTF node the SkeletalNode goes under, -1 for scene top level + std::vector bone_nodes; + std::vector skinned_nodes; + }; + + std::vector skeletons; + std::vector skeleton_plans; + std::vector skin_skeleton(skins.size(), -1); + std::vector node_skeleton(node_count, -1); + + for (size_t sk = 0; sk < skins.size(); ++sk) { + const size_t group = group_of(sk); + if (group != sk) { + continue; + } + + std::vector joints; + for (size_t other = 0; other < skins.size(); ++other) { + if (group_of(other) != group) { + continue; + } + for (uint32_t j = 0; j < model.skins[other].joints_count; ++j) { + const int32_t joint = model.skins[other].joints[j]; + if (joint >= 0 && joint < node_count) { + joints.push_back(joint); + } + } + } + if (joints.empty()) { + continue; + } + + std::vector chain; + for (int32_t cursor = joints.front(); cursor >= 0; cursor = node_parent[cursor]) { + chain.push_back(cursor); + } + size_t lca_at = 0; + for (const int32_t joint : joints) { + std::unordered_set ancestors; + for (int32_t cursor = joint; cursor >= 0; cursor = node_parent[cursor]) { + ancestors.insert(cursor); + } + while (lca_at < chain.size() && !ancestors.contains(chain[lca_at])) { + ++lca_at; + } + } + + SkeletonPlan plan; + std::vector roots; + if (lca_at >= chain.size()) { + // Joints spread over separate top level trees, each tree root is a root bone + for (const int32_t joint : joints) { + int32_t top = joint; + while (node_parent[top] >= 0) { + top = node_parent[top]; + } + if (std::ranges::find(roots, top) == roots.end()) { + roots.push_back(top); + } + } + } else if (const int32_t lca = chain[lca_at]; is_joint[lca] != 0) { + plan.host = node_parent[lca]; + roots.push_back(lca); + } else { + // A non joint ancestor like the Blender Armature keeps its transform as a plain node + plan.host = lca; + for (uint32_t c = 0; c < model.nodes[lca].children_count; ++c) { + const int32_t child = model.nodes[lca].children[c]; + if (child >= 0 && child < node_count && (subtree_flags[child] & 1) != 0) { + roots.push_back(child); + } + } + } + + const auto skeleton_index = static_cast(skeletons.size()); + Skeleton skeleton; + skeleton.name = plan.host >= 0 ? node_name_at(plan.host) : node_name_at(roots.front()); + + // Depth first so a parent always precedes its children + std::function add_bone = [&](int32_t idx, int32_t parent_bone) { + const auto bone_index = static_cast(skeleton.bones.size()); + skeleton.bones.push_back( + Bone {.name = node_name_at(idx), .parent = parent_bone, .rest = node_local_pose(model.nodes[idx])} + ); + plan.bone_nodes.push_back(idx); + node_skeleton[idx] = skeleton_index; + for (uint32_t c = 0; c < model.nodes[idx].children_count; ++c) { + const int32_t child = model.nodes[idx].children[c]; + if (child >= 0 && child < node_count && node_skeleton[child] < 0 && is_bone_child(child)) { + add_bone(child, bone_index); + } + } + }; + for (const int32_t root : roots) { + if (node_skeleton[root] < 0) { + add_bone(root, -1); + } + } + + for (size_t other = 0; other < skins.size(); ++other) { + if (group_of(other) == group) { + skin_skeleton[other] = skeleton_index; + } + } + skeletons.push_back(std::move(skeleton)); + skeleton_plans.push_back(std::move(plan)); + } + + // Skinned meshes move directly under their SkeletalNode, glTF ignores their transform anyway + std::vector pulled_skeleton(node_count, -1); + for (int32_t i = 0; i < node_count; ++i) { + const int32_t skin = model.nodes[i].skin; + if (model.nodes[i].mesh != -1 && skin >= 0 && std::cmp_less(skin, skins.size()) && skin_skeleton[skin] >= 0 && + node_skeleton[i] < 0) { + pulled_skeleton[i] = skin_skeleton[skin]; + skeleton_plans[skin_skeleton[skin]].skinned_nodes.push_back(i); + } + } + + const auto skipped_in_walk = [&](int32_t idx) { return node_skeleton[idx] >= 0 || pulled_skeleton[idx] >= 0; }; + + std::unordered_set skeleton_covered; + std::function cover_subtree = [&](int32_t idx) { + skeleton_covered.insert(node_name_at(idx)); + for (uint32_t c = 0; c < model.nodes[idx].children_count; ++c) { + const int32_t child = model.nodes[idx].children[c]; + if (child >= 0 && child < node_count) { + cover_subtree(child); + } + } + }; + for (const auto& plan : skeleton_plans) { + for (const int32_t bone : plan.bone_nodes) { + cover_subtree(bone); + } + for (const int32_t skinned : plan.skinned_nodes) { + cover_subtree(skinned); + } + } + + std::function walk_node; + std::function emit_skeleton; + + walk_node = [&](int32_t node_idx) -> nlohmann::json { const tg3_node& node = model.nodes[node_idx]; nlohmann::json n; // Must match node_name_at()'s "node_N" fallback exactly - animation tracks target nodes by this @@ -1269,15 +1489,76 @@ auto generateIntermediates(const std::filesystem::path& path) { n["type"] = "toast::Node3D"; } - if (node.children_count > 0) { + const auto add_child = [&](nlohmann::json child) { if (!n.contains("children")) { n["children"] = nlohmann::json::array(); } - for (uint32_t i = 0; i < node.children_count; i++) { - n["children"].push_back(walk_node(node.children[i])); + n["children"].push_back(std::move(child)); + }; + for (uint32_t i = 0; i < node.children_count; i++) { + const int32_t child = node.children[i]; + if (child >= 0 && child < node_count && !skipped_in_walk(child)) { + add_child(walk_node(child)); } } + if (node_skeleton[node_idx] < 0) { + for (size_t sk = 0; sk < skeleton_plans.size(); ++sk) { + if (skeleton_plans[sk].host == node_idx) { + add_child(emit_skeleton(sk)); + } + } + } + + return n; + }; + + emit_skeleton = [&](size_t sk) -> nlohmann::json { + const auto& plan = skeleton_plans[sk]; + nlohmann::json n; + n["name"] = skeletons[sk].name + " Skeleton"; + n["type"] = "toast::SkeletalNode"; + n["transform"] = pose_json(BonePose {}); + // Bare filename patched to a UID by GltfImporter.cs, every .tanim carries the skeletons + n["params"]["animation"] = skin_file_name; + n["params"]["skeleton_name"] = skeletons[sk].name; + if (!clips.empty()) { + n["params"]["clip"] = clips.front().name; + } + n["children"] = nlohmann::json::array(); + + for (const int32_t skinned : plan.skinned_nodes) { + nlohmann::json mesh = walk_node(skinned); + mesh["transform"] = pose_json(BonePose {}); + n["children"].push_back(std::move(mesh)); + } + + for (const int32_t bone : plan.bone_nodes) { + nlohmann::json attached = nlohmann::json::array(); + if (has_content(bone)) { + nlohmann::json content = walk_node(bone); + content["transform"] = pose_json(BonePose {}); + attached.push_back(std::move(content)); + } else { + const auto& bone_node = model.nodes[bone]; + for (uint32_t c = 0; c < bone_node.children_count; ++c) { + const int32_t child = bone_node.children[c]; + if (child >= 0 && child < node_count && !skipped_in_walk(child)) { + attached.push_back(walk_node(child)); + } + } + } + if (attached.empty()) { + continue; + } + nlohmann::json attachment; + attachment["name"] = node_name_at(bone) + " Attachment"; + attachment["type"] = "toast::BoneAttachment"; + attachment["transform"] = pose_json(BonePose {}); + attachment["params"]["bone"] = node_name_at(bone); + attachment["children"] = std::move(attached); + n["children"].push_back(std::move(attachment)); + } return n; }; @@ -1291,14 +1572,30 @@ auto generateIntermediates(const std::filesystem::path& path) { scene_json["name"] = name; scene_json["children"] = nlohmann::json::array(); + std::vector emitted_skeleton(skeleton_plans.size(), 0); for (uint32_t j = 0; j < scene.nodes_count; j++) { - scene_json["children"].push_back(walk_node(scene.nodes[j])); + const int32_t top = scene.nodes[j]; + if (top < 0 || top >= node_count) { + continue; + } + if (const int32_t sk = node_skeleton[top]; sk >= 0 && skeleton_plans[sk].host < 0) { + if (emitted_skeleton[sk] == 0) { + emitted_skeleton[sk] = 1; + scene_json["children"].push_back(emit_skeleton(static_cast(sk))); + } + continue; + } + if (!skipped_in_walk(top)) { + scene_json["children"].push_back(walk_node(top)); + } } - // Has to be an ancestor of every joint, every skinned MeshNode and every animated node at once. - // Wrapping the whole scene is the only placement that satisfies all three without knowing in advance - // what the glTF targets - if (!clips.empty() || !skins.empty()) { + const bool needs_player = std::ranges::any_of(clips, [&](const AnimationClip& clip) { + return std::ranges::any_of(clip.tracks, [&](const AnimationTrack& track) { + return !skeleton_covered.contains(track.target_node); + }); + }); + if (needs_player) { scene_json["type"] = "toast::AnimationPlayer"; // The first clip's asset, since a player holds one animation at a time; the rest import alongside // it as their own assets for the user to swap in. Bare filename, see skin_animation above @@ -1364,14 +1661,14 @@ auto generateIntermediates(const std::filesystem::path& path) { // Save animations - one .tanim per clip, each with this glTF's skins alongside it (see // animation_file_names above for why) for (size_t i = 0; i < clips.size(); ++i) { - const auto binary = Animation::toBinary({clips[i]}, skins); + const auto binary = Animation::toBinary({clips[i]}, skins, skeletons); const std::filesystem::path out = cache_dir / (animation_file_names[i] + ".tanim"); std::ofstream f(out, std::ios::binary); f.write(reinterpret_cast(binary.data()), static_cast(binary.size())); } if (clips.empty() && !skins.empty()) { // Skeleton with no animation: still needs a file for MeshNode::skin_animation to resolve against - const auto binary = Animation::toBinary({}, skins); + const auto binary = Animation::toBinary({}, skins, skeletons); const std::filesystem::path out = cache_dir / (skin_file_name + ".tanim"); std::ofstream f(out, std::ios::binary); f.write(reinterpret_cast(binary.data()), static_cast(binary.size())); @@ -1500,7 +1797,7 @@ static void jsonToTnode(const nlohmann::json& scene_json, const std::filesystem: // AnimationPlayer: "animation" is the .tanim UID (patched by GltfImporter.cs like mesh/material // above), "clip" is a plain string naming which clip to autoplay - else if (basic.type == "toast::AnimationPlayer" && n.contains("params")) { + else if ((basic.type == "toast::AnimationPlayer" || basic.type == "toast::SkeletalNode") && n.contains("params")) { const auto& params = n["params"]; if (params.contains("animation")) { const auto animation_uid = params["animation"].get(); @@ -1519,6 +1816,17 @@ static void jsonToTnode(const nlohmann::json& scene_json, const std::filesystem: if (params.contains("clip")) { basic.fields.push_back({"m_clip_name", toast::FieldType::string_t, false, params["clip"].get()}); } + if (params.contains("skeleton_name")) { + basic.fields.push_back( + {"m_skeleton_name", toast::FieldType::string_t, false, params["skeleton_name"].get()} + ); + } + } + + else if (basic.type == "toast::BoneAttachment" && n.contains("params")) { + if (n["params"].contains("bone")) { + basic.fields.push_back({"m_bone", toast::FieldType::string_t, false, n["params"]["bone"].get()}); + } } // Camera and light params. walk_node() already emits these keyed by the engine's reflected field diff --git a/engine/src/toast/engine.cpp b/engine/src/toast/engine.cpp index 474fdaa7f..fe24798c7 100644 --- a/engine/src/toast/engine.cpp +++ b/engine/src/toast/engine.cpp @@ -33,6 +33,7 @@ #include "toast/renderer/passes/debug/grid_pass.hpp" #include "toast/renderer/passes/geometry/voxel_pass.hpp" #include "toast/renderer/passes/lighting/environment_pass.hpp" +#include "toast/renderer/passes/lighting/gi_clipmap_pass.hpp" #include "toast/renderer/passes/lighting/gi_pass.hpp" #include "toast/renderer/passes/lighting/reflection_probe_pass.hpp" #include "toast/renderer/passes/lighting/shadow_pass.hpp" @@ -127,6 +128,8 @@ auto addScenePasses( // Before the passes whose scene sets bind its cascades auto gi_pass = std::make_unique(core, scene_format, extent); renderer.setGiPass(gi_pass.get()); + auto gi_clipmap_pass = std::make_unique(core, scene_format, extent); + renderer.setGiClipmapPass(gi_clipmap_pass.get()); // Recorded in its own scopes so registration order here does not matter auto voxel_pass = std::make_unique(core, scene_format, depth_format, extent); @@ -139,6 +142,7 @@ auto addScenePasses( // First in the chain so the probes read depth before any post pass renderer.addPostProcessPass(std::move(gi_pass)); + renderer.addPostProcessPass(std::move(gi_clipmap_pass)); if (core.isRayTracingSupported()) { renderer.addPostProcessPass(std::make_unique(core, scene_format, extent)); diff --git a/engine/src/toast/physics/simulator.cpp b/engine/src/toast/physics/simulator.cpp index 44e6e3a6a..38eaecf7e 100644 --- a/engine/src/toast/physics/simulator.cpp +++ b/engine/src/toast/physics/simulator.cpp @@ -1428,7 +1428,9 @@ void Simulator::queuePendingFragments(std::span result } const Body* source_body = tryGetBody(shape->owner); - if (source_body != nullptr && source_body->type == BodyType::dynamic_body && not components_to_spawn.empty()) { + const bool keeps_largest = + source_body != nullptr && (source_body->type == BodyType::dynamic_body || data->anchor_mask == k_anchor_null); + if (keeps_largest && not components_to_spawn.empty()) { components_to_spawn.erase(std::ranges::max_element(components_to_spawn, {}, &DetachedComponent::voxel_count)); } @@ -1963,11 +1965,14 @@ void Simulator::syncEnabledState() { glm::any(glm::greaterThan(glm::abs(body->position - binding.node->world_position), glm::vec3(1.0e-5f))); const bool rotation_changed = 1.0f - std::abs(glm::dot(body->rotation, binding.node->world_rotation)) > 1.0e-5f; if (position_changed || rotation_changed) { - setTransform(binding.body, binding.node->world_position, binding.node->world_rotation); + followNodeTransform(binding.body, binding.node->world_position, binding.node->world_rotation); body = tryGetBody(binding.body); if (body == nullptr) { continue; } + } else if (body->type == BodyType::kinematic_body) { + body->linear_velocity = glm::vec3 {0.0f}; + body->angular_velocity = glm::vec3 {0.0f}; } } for (ColliderBinding& collider_binding : binding.colliders) { @@ -2006,11 +2011,14 @@ void Simulator::syncEnabledState() { glm::any(glm::greaterThan(glm::abs(body->position - binding.node->world_position), glm::vec3(1.0e-5f))); const bool rotation_changed = 1.0f - std::abs(glm::dot(body->rotation, binding.node->world_rotation)) > 1.0e-5f; if (position_changed || rotation_changed) { - setTransform(binding.body, binding.node->world_position, binding.node->world_rotation); + followNodeTransform(binding.body, binding.node->world_position, binding.node->world_rotation); body = tryGetBody(binding.body); if (body == nullptr) { continue; } + } else if (body->type == BodyType::kinematic_body) { + body->linear_velocity = glm::vec3 {0.0f}; + body->angular_velocity = glm::vec3 {0.0f}; } } @@ -4392,6 +4400,9 @@ auto Simulator::createVoxelShape(BodyID owner, toast::VoxelNode& node, toast::Vo const Shape* stored_shape = tryGetShape(shape); if (stored_shape != nullptr) { if (VoxelShapeData* data = tryGetVoxelData(stored_shape->voxel.data)) { + if (node.break_anchor == toast::BreakAnchor::largest_piece) { + data->anchor_mask = k_anchor_null; + } data->source_revision = part != nullptr ? part->revision : node.revision(); data->palette_uid = node.paletteUid(); bool& split_pending = part != nullptr ? part->split_pending : node.m_split_pending; @@ -4861,6 +4872,33 @@ auto Simulator::setTransform(BodyID body, const glm::vec3& position, const glm:: return true; } +void Simulator::followNodeTransform(BodyID id, const glm::vec3& position, const glm::quat& rotation) { + Body* body = tryGetBody(id); + if (body == nullptr || body->type != BodyType::kinematic_body) { + setTransform(id, position, rotation); + return; + } + + // Kinematic bodies never integrate so the velocity only feeds contacts, letting an animated body push + const float dt = static_cast(Accumulator::fixedDelta()); + const glm::vec3 previous_center = body->worldCenterOfMass(); + glm::quat delta = glm::normalize(rotation) * glm::conjugate(body->rotation); + if (delta.w < 0.0f) { + delta = -delta; + } + if (not setTransform(id, position, rotation)) { + return; + } + body = tryGetBody(id); + if (body == nullptr || not std::isfinite(dt) || dt <= 0.0f) { + return; + } + body->linear_velocity = (body->worldCenterOfMass() - previous_center) / dt; + const float angle = 2.0f * std::acos(std::clamp(delta.w, -1.0f, 1.0f)); + const float sin_half = std::sqrt(std::max(1.0f - (delta.w * delta.w), 0.0f)); + body->angular_velocity = sin_half > 1.0e-6f ? glm::vec3(delta.x, delta.y, delta.z) / sin_half * (angle / dt) : glm::vec3 {0.0f}; +} + auto Simulator::setLinearVelocity(BodyID body, const glm::vec3& velocity) -> bool { ZoneScopedN("physics::SetLinearVelocity"); ZoneValue(static_cast(body.slot)); diff --git a/engine/src/toast/physics/simulator.hpp b/engine/src/toast/physics/simulator.hpp index 384e6f520..4d27dacb0 100644 --- a/engine/src/toast/physics/simulator.hpp +++ b/engine/src/toast/physics/simulator.hpp @@ -548,6 +548,8 @@ class TOAST_API Simulator { static void setShapeEnabled(ShapeID shape, bool enabled); void syncEnabledState(); + /// Teleports to a node pose, kinematic bodies also get the step velocity so they push what they hit + void followNodeTransform(BodyID id, const glm::vec3& position, const glm::quat& rotation); [[nodiscard]] auto queryCandidates(BodyID ignored, const AABB& bounds, std::optional layers = std::nullopt) const diff --git a/engine/src/toast/renderer/core/vulkan_common.hpp b/engine/src/toast/renderer/core/vulkan_common.hpp index a54d8b3e7..6f4e0b3c7 100644 --- a/engine/src/toast/renderer/core/vulkan_common.hpp +++ b/engine/src/toast/renderer/core/vulkan_common.hpp @@ -43,6 +43,8 @@ inline constexpr vk::Format k_voxel_face_normal_format = vk::Format::eA2B10G10R1 /// Marched and sampled light terms before voxel_denoise.slang and never negative inline constexpr vk::Format k_voxel_noisy_format = vk::Format::eB10G11R11UfloatPack32; +/// Half resolution clipmap gather with a signed alpha marking pixels that gathered nothing +inline constexpr vk::Format k_voxel_gi_format = vk::Format::eR16G16B16A16Sfloat; /// voxel_lighting.slang packReservoir inline constexpr vk::Format k_voxel_reservoir_format = vk::Format::eR32G32B32A32Uint; diff --git a/engine/src/toast/renderer/lighting/gi_clip_math.hpp b/engine/src/toast/renderer/lighting/gi_clip_math.hpp new file mode 100644 index 000000000..71b26b2e2 --- /dev/null +++ b/engine/src/toast/renderer/lighting/gi_clip_math.hpp @@ -0,0 +1,68 @@ +/// @file gi_clip_math.hpp +/// @author dario +/// @date 10/11/2026 + +#pragma once + +#include +#include +#include + +namespace renderer::gi_clip { + +struct Box { + glm::ivec3 min {0}; + /// Exclusive + glm::ivec3 max {0}; +}; + +[[nodiscard]] +inline auto empty(const Box& box) -> bool { + return glm::any(glm::greaterThanEqual(box.min, box.max)); +} + +[[nodiscard]] +inline auto origin(glm::vec3 camera, float cell, int resolution) -> glm::ivec3 { + return 2 * glm::ivec3(glm::floor(camera / (2.0f * cell))) - glm::ivec3(resolution / 2); +} + +[[nodiscard]] +inline auto wrap(glm::ivec3 cell, int resolution) -> glm::ivec3 { + return ((cell % resolution) + resolution) % resolution; +} + +/// @return count written to @p out +inline auto scrolled(glm::ivec3 previous, glm::ivec3 current, int resolution, std::span out) -> uint32_t { + const glm::ivec3 delta = current - previous; + if (glm::any(glm::greaterThanEqual(glm::abs(delta), glm::ivec3(resolution)))) { + out[0] = {.min = current, .max = current + resolution}; + return 1; + } + Box rest {.min = current, .max = current + resolution}; + uint32_t count = 0; + for (int axis = 0; axis < 3; ++axis) { + if (delta[axis] == 0) { + continue; + } + Box slab = rest; + if (delta[axis] > 0) { + slab.min[axis] = previous[axis] + resolution; + rest.max[axis] = slab.min[axis]; + } else { + slab.max[axis] = previous[axis]; + rest.min[axis] = slab.max[axis]; + } + out[count++] = slab; + } + return count; +} + +[[nodiscard]] +inline auto cells(glm::vec3 low, glm::vec3 high, float cell, glm::ivec3 origin, int resolution) -> Box { + return { + .min = glm::max(glm::ivec3(glm::floor(low / cell)), origin), + .max = glm::min(glm::ivec3(glm::floor(high / cell)) + 1, origin + resolution), + }; +} + +} diff --git a/engine/src/toast/renderer/lighting/gi_dirty_boxes.cpp b/engine/src/toast/renderer/lighting/gi_dirty_boxes.cpp new file mode 100644 index 000000000..b99984a16 --- /dev/null +++ b/engine/src/toast/renderer/lighting/gi_dirty_boxes.cpp @@ -0,0 +1,97 @@ +/// @file gi_dirty_boxes.cpp +/// @author dario +/// @date 10/11/2026 + +#include "toast/renderer/lighting/gi_dirty_boxes.hpp" + +#include "toast/renderer/core/vulkan_common.hpp" +#include "toast/renderer/render_frame.hpp" +#include "toast/renderer/voxel/voxel_gpu_storage.hpp" + +#include +#include +#include +#include +#include + +namespace renderer { + +void GiDirtyBoxes::gather(const RenderFrame& frame, float motion_threshold) { + ZoneScoped; + const auto add = [&](glm::vec3 low, glm::vec3 high) { + if (m_boxes.size() < 2 * k_max_boxes) { + m_boxes.push_back(low); + m_boxes.push_back(high); + return; + } + auto last = m_boxes.end() - 2; + last[0] = glm::min(last[0], low); + last[1] = glm::max(last[1], high); + }; + + Counts& counts = m_counts; + const float threshold = std::max(motion_threshold, 0.0f); + + for (const auto& proxy : frame.voxel_instances) { + if (proxy.has_previous && proxy.model == proxy.previous_model) { + continue; + } + const glm::vec3 previous = glm::vec3(proxy.previous_model * proxy.inverse_model * glm::vec4(proxy.bounds_center, 1.0f)); + if (proxy.has_previous) { + const glm::mat3 change = glm::mat3(proxy.model) - glm::mat3(proxy.previous_model); + const float spread = + std::sqrt(glm::dot(change[0], change[0]) + glm::dot(change[1], change[1]) + glm::dot(change[2], change[2])); + const float scale = std::max(glm::length(glm::vec3(proxy.model[0])), 1e-6f); + const float motion = glm::distance(proxy.bounds_center, previous) + (spread * proxy.bounds_radius / scale); + counts.largest_motion = std::max(counts.largest_motion, motion); + if (motion < threshold) { + continue; + } + ++counts.moved; + } else { + ++counts.appeared; + } + const glm::vec3 radius(proxy.bounds_radius); + add(glm::min(proxy.bounds_center, previous) - radius, glm::max(proxy.bounds_center, previous) + radius); + } + + bool known = true; + if (frame.voxel_storage) { + const uint64_t generation = frame.voxel_storage->generation(); + if (generation != m_region_generation && m_region_generation != 0) { + m_models.clear(); + for (const auto& proxy : frame.voxel_instances) { + m_models.emplace(proxy.node_rid, proxy.model * glm::scale(glm::mat4(1.0f), glm::vec3(voxel::k_voxel_size))); + } + known = frame.voxel_storage->changeHistory().forEachSince(m_region_generation, [&](const VoxelRegion& region) { + const auto found = m_models.find(region.node_rid); + if (found == m_models.end()) { + return; + } + ++counts.edits; + glm::vec3 low(std::numeric_limits::max()); + glm::vec3 high(std::numeric_limits::lowest()); + for (uint32_t corner = 0; corner < 8; ++corner) { + const glm::vec3 local( + (corner & 1) != 0 ? region.max.x : region.min.x, + (corner & 2) != 0 ? region.max.y : region.min.y, + (corner & 4) != 0 ? region.max.z : region.min.z + ); + const glm::vec3 world = glm::vec3(found->second * glm::vec4(local, 1.0f)); + low = glm::min(low, world); + high = glm::max(high, world); + } + add(low, high); + }); + } + m_region_generation = generation; + } + m_known = m_known && known; +} + +auto GiDirtyBoxes::take(Counts& counts) -> bool { + counts = std::exchange(m_counts, Counts {}); + return std::exchange(m_known, true); +} + +} diff --git a/engine/src/toast/renderer/lighting/gi_dirty_boxes.hpp b/engine/src/toast/renderer/lighting/gi_dirty_boxes.hpp new file mode 100644 index 000000000..43cd692f7 --- /dev/null +++ b/engine/src/toast/renderer/lighting/gi_dirty_boxes.hpp @@ -0,0 +1,51 @@ +/// @file gi_dirty_boxes.hpp +/// @author dario +/// @date 10/11/2026 + +#pragma once + +#include +#include +#include +#include +#include + +namespace renderer { +struct RenderFrame; + +class GiDirtyBoxes { +public: + /// Past it every extra region grows the last box + static constexpr uint32_t k_max_boxes = 64; + + struct Counts { + uint32_t moved = 0; + uint32_t appeared = 0; + uint32_t edits = 0; + /// Meters including bodies under the motion threshold so physics jitter shows up + float largest_motion = 0.0f; + }; + + /// Every rendered frame so skipped updates still reach the next one + void gather(const RenderFrame& frame, float motion_threshold); + + /// Low then high per box + [[nodiscard]] + auto boxes() const -> std::span { + return m_boxes; + } + + /// @return false when edits were lost so the consumer must rebuild everything + auto take(Counts& counts) -> bool; + + void clear() { m_boxes.clear(); } + +private: + std::vector m_boxes; + std::unordered_map m_models; + Counts m_counts; + uint64_t m_region_generation = 0; + bool m_known = true; +}; + +} diff --git a/engine/src/toast/renderer/passes/geometry/voxel_pass.cpp b/engine/src/toast/renderer/passes/geometry/voxel_pass.cpp index 44d83c321..600e8b9e1 100644 --- a/engine/src/toast/renderer/passes/geometry/voxel_pass.cpp +++ b/engine/src/toast/renderer/passes/geometry/voxel_pass.cpp @@ -90,6 +90,10 @@ constexpr uint32_t k_scene_glass = 4; constexpr uint32_t k_ambient_ray_query = 8; /// Bits 8 to 15 carry the max roughness in 255ths constexpr uint32_t k_traced_specular = 16; +/// Mirrors voxel_lighting.slang kGiGather +constexpr uint32_t k_gi_gather = 32; +/// Mirrors voxel_lighting.slang kGiClipmap +constexpr uint32_t k_gi_clipmap = 64; /// ReSTIR reuse of last frame's reservoir at the reprojected pixel and two around it constexpr uint32_t k_reused_reservoirs = 3; @@ -450,6 +454,17 @@ void VoxelPass::createLighting(const VulkanCore& core, vk::Format scene_format, config.depth_write = false; m_lighting_pipeline.rebuild(core, config); + { + VulkanPipeline::Config gather = config; + gather.debug_name = "VoxelGiGather"; + gather.fragment_entry = "fragmentGiGather"; + gather.color_format = k_voxel_gi_format; + gather.extra_color_formats = {}; + gather.write_extra_color = false; + gather.write_color_alpha = true; + m_gi_gather_pipeline.rebuild(core, gather); + } + config.debug_name = "VoxelSpatialReuse"; config.fragment_entry = "fragmentSpatial"; config.color_format = k_voxel_noisy_format; @@ -844,6 +859,8 @@ auto VoxelPass::prepare(uint32_t frame_index) -> bool { m_shadow_instance_count = 0; m_marched_lights = false; m_ambient_rays = false; + m_gi_gather = false; + m_gi_clipmap = false; m_denoise_active = false; m_spatial_active = false; m_scene_glass = false; @@ -929,6 +946,11 @@ auto VoxelPass::prepare(uint32_t frame_index) -> bool { // Debug views and probe captures skip the denoiser const bool capture = frame->probe_capture_index >= 0 || frame->irradiance_capture_index >= 0; + const GiSettings& gi = VulkanRenderer::instance->giSettings(); + m_gi_clipmap = + gi.enabled.load(std::memory_order_relaxed) && gi.backend.load(std::memory_order_relaxed) == GiSettings::k_backend_clipmap; + // The gather target is sized for the main view so captures take the one cone path + m_gi_gather = m_gi_clipmap && !capture && m_gi_gather_pipeline.isReady(); m_denoise_active = (m_marched_lights || m_ambient_rays) && frame->render_mode == 0 && !capture && m_denoise_temporal_pipeline.isReady() && m_denoise_composite_pipeline.isReady() && (frame_index * 2) + 1 < m_denoise_sets.size() && m_denoise_history[1][1].isReady(); @@ -1415,39 +1437,10 @@ void VoxelPass::recordLighting(vk::CommandBuffer cmd, uint32_t frame_index, vk:: return; } - const std::array views { - instance->getVoxelAlbedoView(), - instance->getVoxelFaceNormalView(), - instance->getVoxelMaterialView(), - instance->getDepthView(), - instance->getVoxelPreviousReservoirView(), - instance->getSceneMotionView(), - instance->getVoxelCandidateReservoirView(), - instance->getSceneNormalView(), - instance->getVoxelNoisyDiffuseView(), - instance->getVoxelNoisySpecularView(), - instance->getVoxelDetailNormalView(), - }; - if (std::ranges::any_of(views, [](vk::ImageView view) { return !view; })) { + if (!updateGbufferSet(frame_index)) { return; } - // Safe since the fence of this slot was waited on - if (m_bound_gbuffer.update(frame_index, views)) { - DescriptorWriter writer; - for (uint32_t binding = 0; binding < views.size(); ++binding) { - writer.image( - *m_gbuffer_sets[frame_index], - binding, - vk::DescriptorType::eCombinedImageSampler, - *m_point_sampler, - views[binding], - binding == k_depth_binding ? vk::ImageLayout::eDepthReadOnlyOptimal : vk::ImageLayout::eShaderReadOnlyOptimal - ); - } - writer.flush(m_core->getDevice()); - } - m_lighting_scene_sets.updateTlas(frame_index); const auto height = static_cast(viewport.height); @@ -1469,7 +1462,8 @@ void VoxelPass::recordLighting(vk::CommandBuffer cmd, uint32_t frame_index, vk:: .reuse = glm::uvec4( (instance->voxelReservoirHistory() ? k_reuse_history : 0u) | (m_spatial_active ? k_reuse_spatial : 0u) | (m_scene_glass ? k_scene_glass : 0u) | (instance->voxelAmbientRayQuery() ? k_ambient_ray_query : 0u) | - traced_specular | (std::min(instance->voxelGlassShadowReach(), 0xFFFFu) << 16), + (m_gi_gather ? k_gi_gather : 0u) | (m_gi_clipmap ? k_gi_clipmap : 0u) | traced_specular | + (std::min(instance->voxelGlassShadowReach(), 0xFFFFu) << 16), k_reservoir_m_cap * instance->voxelLightCandidates(), k_reused_reservoirs, m_ambient_rays ? static_cast(std::lround(instance->voxelAmbientReach() * 100.0f)) : 0u @@ -1488,7 +1482,8 @@ void VoxelPass::recordLighting(vk::CommandBuffer cmd, uint32_t frame_index, vk:: .reuse = glm::uvec4( (instance->voxelReservoirHistory() ? k_reuse_history : 0u) | (m_spatial_active ? k_reuse_spatial : 0u) | (m_scene_glass ? k_scene_glass : 0u) | (instance->voxelAmbientRayQuery() ? k_ambient_ray_query : 0u) | - traced_specular | (std::min(instance->voxelGlassShadowReach(), 0xFFFFu) << 16), + (m_gi_gather ? k_gi_gather : 0u) | (m_gi_clipmap ? k_gi_clipmap : 0u) | traced_specular | + (std::min(instance->voxelGlassShadowReach(), 0xFFFFu) << 16), k_reservoir_m_cap * instance->voxelLightCandidates(), k_reused_reservoirs, m_ambient_rays ? static_cast(std::lround(instance->voxelAmbientReach() * 100.0f)) : 0u @@ -1605,6 +1600,8 @@ void VoxelPass::recordGlassBricks( .refraction_distance = renderer->voxelGlassRefractionDistance(), .refraction_voxels = renderer->voxelGlassRefractionVoxels(), .lit_surfaces = renderer->voxelGlassLitSurfaces(), + // Only the blended pass lights glass and it tests closer than the opaque depth + .depth_test = m_backdrop_depth_valid && &pipeline == &m_glass_pipeline ? 1u : 0u, }; cmd.pushConstants(layout, vk::ShaderStageFlagBits::eAll, 0, sizeof(GlassPush), &push); cmd.draw(36, count, 0, 0); @@ -1863,6 +1860,72 @@ void VoxelPass::recordMarched(vk::CommandBuffer cmd, uint32_t frame_index) { cmd.draw(3, 1, 0, 0); } +auto VoxelPass::updateGbufferSet(uint32_t frame_index) -> bool { + const auto* instance = VulkanRenderer::instance; + const std::array views { + instance->getVoxelAlbedoView(), + instance->getVoxelFaceNormalView(), + instance->getVoxelMaterialView(), + instance->getDepthView(), + instance->getVoxelPreviousReservoirView(), + instance->getSceneMotionView(), + instance->getVoxelCandidateReservoirView(), + instance->getSceneNormalView(), + instance->getVoxelNoisyDiffuseView(), + instance->getVoxelNoisySpecularView(), + instance->getVoxelDetailNormalView(), + instance->getVoxelGiView(), + }; + if (std::ranges::any_of(views, [](vk::ImageView view) { return !view; })) { + return false; + } + + // Safe since the fence of this slot was waited on + if (m_bound_gbuffer.update(frame_index, views)) { + DescriptorWriter writer; + for (uint32_t binding = 0; binding < views.size(); ++binding) { + writer.image( + *m_gbuffer_sets[frame_index], + binding, + vk::DescriptorType::eCombinedImageSampler, + *m_point_sampler, + views[binding], + binding == k_depth_binding ? vk::ImageLayout::eDepthReadOnlyOptimal : vk::ImageLayout::eShaderReadOnlyOptimal + ); + } + writer.flush(m_core->getDevice()); + } + return true; +} + +void VoxelPass::recordGiGather(vk::CommandBuffer cmd, uint32_t frame_index, vk::Extent2D viewport) { + ZoneScoped; + const auto* frame = VulkanRenderer::instance->renderingFrame(); + if (!m_gi_gather || frame == nullptr || frame_index >= m_gbuffer_sets.size() || frame_index >= m_lighting_storage_sets.size() || + !m_lighting_scene_sets.get(frame_index) || !updateGbufferSet(frame_index)) { + return; + } + m_lighting_scene_sets.updateTlas(frame_index); + + const LightingPushConstants push { + .inverse_view_projection = glm::inverse(frame->frame_data.jittered_view_projection), + .viewport = glm::vec4(static_cast(viewport.width), static_cast(viewport.height), 0.0f, 0.0f), + }; + const vk::PipelineLayout layout = *m_lighting_layout.getPipelineLayout(); + cmd.bindPipeline(vk::PipelineBindPoint::eGraphics, m_gi_gather_pipeline.getPipeline()); + cmd.bindDescriptorSets( + vk::PipelineBindPoint::eGraphics, + layout, + k_scene_set, + std::array { + m_lighting_scene_sets.get(frame_index), *m_lighting_storage_sets[frame_index], *m_gbuffer_sets[frame_index] + }, + {} + ); + cmd.pushConstants(layout, vk::ShaderStageFlagBits::eAll, 0, sizeof(LightingPushConstants), &push); + cmd.draw(3, 1, 0, 0); +} + void VoxelPass::recordAmbient(vk::CommandBuffer cmd, uint32_t frame_index) { ZoneScoped; if (!m_ambient_rays || !m_ambient_pipeline.isReady() || frame_index >= m_gbuffer_sets.size() || diff --git a/engine/src/toast/renderer/passes/geometry/voxel_pass.hpp b/engine/src/toast/renderer/passes/geometry/voxel_pass.hpp index ab0455767..a0c2ab24e 100644 --- a/engine/src/toast/renderer/passes/geometry/voxel_pass.hpp +++ b/engine/src/toast/renderer/passes/geometry/voxel_pass.hpp @@ -73,6 +73,14 @@ class VoxelPass : public IRenderPass { /// Writes scene colour indirect rounded normal and noisy diffuse while reading the G-buffer and depth void recordLighting(vk::CommandBuffer cmd, uint32_t frame_index, vk::Extent2D viewport); + [[nodiscard]] + auto giGatherActive() const noexcept -> bool { + return m_gi_gather; + } + + /// Inside a scope over the half resolution GI target and before recordLighting() which upsamples it + void recordGiGather(vk::CommandBuffer cmd, uint32_t frame_index, vk::Extent2D viewport); + /// After prepare() whether recordAmbient() has rays to trace [[nodiscard]] auto ambientRaysActive() const noexcept -> bool { @@ -111,6 +119,8 @@ class VoxelPass : public IRenderPass { void setBackdropCaptured(bool captured) noexcept { m_backdrop_captured = captured; } + void setBackdropDepthValid(bool valid) noexcept { m_backdrop_depth_valid = valid; } + /// After prepare() whether the lighting scope writes denoised terms [[nodiscard]] auto denoiseActive() const -> bool { @@ -370,7 +380,11 @@ class VoxelPass : public IRenderPass { uint32_t m_shadow_instance_count = 0; /// Albedo face normal material and depth last written into each set - DescriptorCache> m_bound_gbuffer; + DescriptorCache> m_bound_gbuffer; + auto updateGbufferSet(uint32_t frame_index) -> bool; + VulkanPipeline m_gi_gather_pipeline; + bool m_gi_gather = false; + bool m_gi_clipmap = false; VulkanPipeline m_spatial_pipeline; VulkanPipeline m_spatial_opaque_pipeline; VulkanPipeline m_marched_pipeline; @@ -379,6 +393,7 @@ class VoxelPass : public IRenderPass { bool m_spatial_active = false; bool m_scene_glass = false; bool m_backdrop_captured = false; + bool m_backdrop_depth_valid = false; bool m_glass_dual_source = false; vk::raii::Sampler m_backdrop_sampler = nullptr; vk::raii::Sampler m_backdrop_depth_sampler = nullptr; @@ -441,6 +456,7 @@ class VoxelPass : public IRenderPass { float refraction_distance = 0.0f; uint32_t refraction_voxels = 0; uint32_t lit_surfaces = 0; + uint32_t depth_test = 0; }; ShaderLayout m_glass_layout; diff --git a/engine/src/toast/renderer/passes/lighting/gi_clipmap_pass.cpp b/engine/src/toast/renderer/passes/lighting/gi_clipmap_pass.cpp new file mode 100644 index 000000000..e51c71744 --- /dev/null +++ b/engine/src/toast/renderer/passes/lighting/gi_clipmap_pass.cpp @@ -0,0 +1,1174 @@ +/// @file gi_clipmap_pass.cpp +/// @author dario +/// @date 10/11/2026 + +#include "toast/renderer/passes/lighting/gi_clipmap_pass.hpp" + +#include "toast/renderer/core/descriptor_writer.hpp" +#include "toast/renderer/core/gpu_sync.hpp" +#include "toast/renderer/core/gpu_timer.hpp" +#include "toast/renderer/lighting/gi_clip_math.hpp" +#include "toast/renderer/shaders/shader_cache.hpp" +#include "toast/renderer/voxel/voxel_gpu_storage.hpp" +#include "toast/renderer/voxel/voxel_trace_scene.hpp" +#include "toast/renderer/vulkan_renderer.hpp" + +#include + +namespace renderer { + +namespace { + +constexpr uint32_t k_fill_set = 0; +constexpr uint32_t k_storage_set = 1; +constexpr uint32_t k_fill_frame_binding = 0; +constexpr uint32_t k_fill_material_binding = 1; +constexpr uint32_t k_fill_emission_binding = 2; +constexpr uint32_t k_fill_opacity_binding = 3; +constexpr uint32_t k_fill_ambient_binding = 4; +/// Mirrors scene_trace.slang +constexpr uint32_t k_trace_volumes_binding = 10; +constexpr uint32_t k_trace_bounds_binding = 11; +constexpr uint32_t k_trace_grid_binding = 12; + +constexpr uint32_t k_debug_source_binding = 0; +constexpr uint32_t k_debug_frame_binding = 1; +constexpr uint32_t k_debug_material_binding = 2; +constexpr uint32_t k_debug_emission_binding = 3; +constexpr uint32_t k_debug_radiance_binding = 4; + +constexpr uint32_t k_inject_scene_set = 0; +constexpr uint32_t k_inject_set = 1; +constexpr uint32_t k_inject_frame_binding = 0; +constexpr uint32_t k_inject_material_binding = 1; +constexpr uint32_t k_inject_emission_binding = 2; +constexpr uint32_t k_inject_radiance_binding = 3; +constexpr uint32_t k_inject_ambient_binding = 4; +constexpr uint32_t k_inject_opacity_binding = 5; + +constexpr uint32_t k_down_frame_binding = 0; +constexpr uint32_t k_down_child_opacity_binding = 1; +constexpr uint32_t k_down_child_radiance_binding = 2; +constexpr uint32_t k_down_child_ambient_binding = 3; +constexpr uint32_t k_down_opacity_binding = 4; +constexpr uint32_t k_down_radiance_binding = 5; +constexpr uint32_t k_down_ambient_binding = 6; +constexpr size_t k_max_down_boxes = 16; + +constexpr uint32_t k_bounce_scene_set = 0; +constexpr uint32_t k_bounce_set = 1; +constexpr uint32_t k_bounce_ambient_binding = 0; +constexpr uint32_t k_bounce_list_binding = 1; +/// Mirrors gi_clip_bounce kFaceListCapacity and kFaceListHeader +constexpr uint32_t k_bounce_capacity = 1u << 17; +constexpr uint32_t k_bounce_header = 4; +/// Mirrors gi_clip_bounce bounceMain numthreads +constexpr uint32_t k_bounce_group = 64; +constexpr uint32_t k_inject_period = 8; + +/// Mirrors gi_clip_fill numthreads +constexpr int k_group = 4; +constexpr vk::Format k_material_format = vk::Format::eR8G8B8A8Unorm; +constexpr vk::Format k_emission_format = vk::Format::eR16G16B16A16Sfloat; +/// Same texel size so one image takes both views and only mandatory format features are used +constexpr vk::Format k_radiance_storage_format = vk::Format::eR32Uint; +constexpr vk::Format k_radiance_sampled_format = vk::Format::eB10G11R11UfloatPack32; + +/// Mirrors gi_clip_down GiClipDownPush +struct DownPush { + /// xyz first global cell written w cells a side of the texture written + glm::ivec4 box_min {0}; + /// xyz cells written w cells a side of the texture read + glm::ivec4 box_size {0}; + /// x mip of the texture read + glm::ivec4 mip {0}; +}; + +/// Mips above the last level down to 4 cells a side which the toroidal addressing needs to divide evenly +auto tailMips(uint32_t resolution) -> uint32_t { + uint32_t count = 0; + while (count < GiClipmapPass::k_max_tail && (resolution >> (count + 1)) >= 4 && resolution % (1u << (count + 1)) == 0) { + ++count; + } + return count; +} + +/// Mirrors gi_clip_fill GiClipFillPush +struct FillPush { + /// xyz first global cell w level + glm::ivec4 box_min {0}; + glm::ivec4 box_size {0}; +}; + +} + +GiClipmapPass::GiClipmapPass(const VulkanCore& core, vk::Format scene_format, vk::Extent2D extent) + : m_core(&core), + m_scene_format(scene_format), + m_extent(extent) { + ZoneScoped; + static_assert(sizeof(FrameData) == 192, "FrameData is mirrored by gi_clip_common GiClipFrame"); + + for (uint32_t i = 0; i < VulkanRenderer::k_frames_in_flight; ++i) { + vk::BufferCreateInfo buffer_ci {}; + buffer_ci.size = sizeof(FrameData); + buffer_ci.usage = vk::BufferUsageFlagBits::eStorageBuffer; + vma::AllocationCreateInfo alloc_ci {}; + alloc_ci.usage = vma::MemoryUsage::eAuto; + alloc_ci.flags = vma::AllocationCreateFlagBits::eMapped | vma::AllocationCreateFlagBits::eHostAccessSequentialWrite; + m_frame_data.push_back(core.getAllocator().createBuffer(buffer_ci, alloc_ci)); + setDebugName(core, *m_frame_data.back(), std::format("GiClipmapPass Frame[{}]", i)); + } + m_point_sampler = vk::raii::Sampler(core.getDevice(), nearestClampSamplerInfo()); + setDebugName(core, *m_point_sampler, "GiClipmapPass PointSampler"); + auto linear_ci = linearClampSamplerInfo(); + linear_ci.addressModeU = vk::SamplerAddressMode::eRepeat; + linear_ci.addressModeV = vk::SamplerAddressMode::eRepeat; + linear_ci.addressModeW = vk::SamplerAddressMode::eRepeat; + linear_ci.mipmapMode = vk::SamplerMipmapMode::eLinear; + linear_ci.maxLod = vk::LodClampNone; + m_linear_sampler = vk::raii::Sampler(core.getDevice(), linear_ci); + setDebugName(core, *m_linear_sampler, "GiClipmapPass LinearSampler"); + + vk::BufferCreateInfo published_ci {}; + published_ci.size = sizeof(FrameData); + published_ci.usage = vk::BufferUsageFlagBits::eStorageBuffer | vk::BufferUsageFlagBits::eTransferDst; + vma::AllocationCreateInfo published_alloc {}; + published_alloc.usage = vma::MemoryUsage::eAutoPreferDevice; + m_published.emplace(core.getAllocator().createBuffer(published_ci, published_alloc)); + setDebugName(core, **m_published, "GiClipmapPass PublishedFrame"); + + vk::ImageCreateInfo dummy_ci {}; + dummy_ci.imageType = vk::ImageType::e3D; + dummy_ci.format = k_material_format; + dummy_ci.extent = vk::Extent3D {1, 1, 1}; + dummy_ci.mipLevels = 1; + dummy_ci.arrayLayers = 1; + dummy_ci.samples = vk::SampleCountFlagBits::e1; + dummy_ci.tiling = vk::ImageTiling::eOptimal; + dummy_ci.usage = vk::ImageUsageFlagBits::eSampled | vk::ImageUsageFlagBits::eTransferDst; + dummy_ci.sharingMode = vk::SharingMode::eExclusive; + dummy_ci.initialLayout = vk::ImageLayout::eUndefined; + vma::AllocationCreateInfo dummy_alloc {}; + dummy_alloc.usage = vma::MemoryUsage::eAutoPreferDevice; + m_dummy.emplace(core.getAllocator().createImage(dummy_ci, dummy_alloc)); + setDebugName(core, **m_dummy, "GiClipmapPass Dummy"); + const vk::ImageSubresourceRange dummy_range {vk::ImageAspectFlagBits::eColor, 0, 1, 0, 1}; + vk::ImageViewCreateInfo dummy_view_ci {}; + dummy_view_ci.image = **m_dummy; + dummy_view_ci.viewType = vk::ImageViewType::e3D; + dummy_view_ci.format = k_material_format; + dummy_view_ci.subresourceRange = dummy_range; + m_dummy_view.emplace(core.getDevice(), dummy_view_ci); + + // Lighting binds both before the first fill so they start readable and empty + const auto& device = core.getDevice(); + const vk::raii::CommandPool one_shot_pool( + device, vk::CommandPoolCreateInfo(vk::CommandPoolCreateFlagBits::eTransient, core.getGraphicsQueueFamilyIndex()) + ); + auto cmd_buffers = + device.allocateCommandBuffers(vk::CommandBufferAllocateInfo(*one_shot_pool, vk::CommandBufferLevel::ePrimary, 1)); + const vk::raii::CommandBuffer cmd = std::move(cmd_buffers[0]); + cmd.begin(vk::CommandBufferBeginInfo(vk::CommandBufferUsageFlagBits::eOneTimeSubmit)); + cmd.fillBuffer(**m_published, 0, vk::WholeSize, 0u); + recordUndefinedToTransferDst(*cmd, **m_dummy, dummy_range); + cmd.clearColorImage(**m_dummy, vk::ImageLayout::eTransferDstOptimal, vk::ClearColorValue(0.0f, 0.0f, 0.0f, 0.0f), dummy_range); + recordTransferDstToShaderRead(*cmd, **m_dummy, dummy_range); + sync::BarrierBatch barriers; + barriers.memory(sync::Usage::transfer_dst, sync::Usage::general); + barriers.flush(*cmd); + cmd.end(); + submitAndWait(device, core.getGraphicsQueue(), core.graphicsSubmitMutex(), *cmd); + + if (!createPipelines(core)) { + setEnabled(false); + return; + } + m_debug_target.create(core, extent, scene_format, "GiClipmapPass Debug"); +} + +auto GiClipmapPass::createPipelines(const VulkanCore& core) -> bool { + ZoneScoped; + const auto fill_uid = assets::resolveURI("core://shaders/gi_clip_fill.slang"); + const auto fill_shader = fill_uid.has_value() ? ShaderCache::get().acquire(*fill_uid) : nullptr; + const auto debug_uid = assets::resolveURI("core://shaders/gi_clip_debug.slang"); + const auto debug_shader = debug_uid.has_value() ? ShaderCache::get().acquire(*debug_uid) : nullptr; + const auto inject_uid = assets::resolveURI("core://shaders/gi_clip_inject.slang"); + const auto inject_shader = inject_uid.has_value() ? ShaderCache::get().acquire(*inject_uid) : nullptr; + const auto bounce_uid = assets::resolveURI("core://shaders/gi_clip_bounce.slang"); + const auto bounce_shader = bounce_uid.has_value() ? ShaderCache::get().acquire(*bounce_uid) : nullptr; + const auto down_uid = assets::resolveURI("core://shaders/gi_clip_down.slang"); + const auto down_shader = down_uid.has_value() ? ShaderCache::get().acquire(*down_uid) : nullptr; + if (!fill_shader || !debug_shader || !inject_shader || !bounce_shader || !down_shader) { + TOAST_ERROR("Render", "GiClipmapPass shaders unavailable, the radiance clipmap is disabled"); + return false; + } + + m_fill_layout.rebuild(core, fill_shader->reflection, "GiClipmapPass Fill"); + VulkanPipeline::Config fill_config; + fill_config.pipeline_type = VulkanPipeline::PipelineType::compute; + fill_config.debug_name = "GiClipmapPass fillMain"; + fill_config.shader_spirv = fill_shader->spirv; + fill_config.pipeline_layout = *m_fill_layout.getPipelineLayout(); + fill_config.compute_entry = "fillMain"; + m_fill_pipeline.rebuild(core, fill_config); + + m_bounce_layout.rebuild(core, bounce_shader->reflection, "GiClipmapPass Bounce"); + VulkanPipeline::Config bounce_config; + bounce_config.pipeline_type = VulkanPipeline::PipelineType::compute; + bounce_config.debug_name = "GiClipmapPass bounceMain"; + bounce_config.shader_spirv = bounce_shader->spirv; + bounce_config.pipeline_layout = *m_bounce_layout.getPipelineLayout(); + bounce_config.compute_entry = "bounceMain"; + m_bounce_pipeline.rebuild(core, bounce_config); + bounce_config.debug_name = "GiClipmapPass listMain"; + bounce_config.compute_entry = "listMain"; + m_bounce_list_pipeline.rebuild(core, bounce_config); + + vk::BufferCreateInfo list_ci {}; + list_ci.size = sizeof(uint32_t) * (k_bounce_header + (4 * k_bounce_capacity)); + list_ci.usage = vk::BufferUsageFlagBits::eStorageBuffer | vk::BufferUsageFlagBits::eTransferDst; + vma::AllocationCreateInfo list_alloc {}; + list_alloc.usage = vma::MemoryUsage::eAutoPreferDevice; + m_bounce_list.emplace(core.getAllocator().createBuffer(list_ci, list_alloc)); + setDebugName(core, **m_bounce_list, "GiClipmapPass BounceList"); + + m_down_layout.rebuild(core, down_shader->reflection, "GiClipmapPass Down"); + VulkanPipeline::Config down_config; + down_config.pipeline_type = VulkanPipeline::PipelineType::compute; + down_config.debug_name = "GiClipmapPass downMain"; + down_config.shader_spirv = down_shader->spirv; + down_config.pipeline_layout = *m_down_layout.getPipelineLayout(); + down_config.compute_entry = "downMain"; + m_down_pipeline.rebuild(core, down_config); + down_config.debug_name = "GiClipmapPass mipMain"; + down_config.compute_entry = "mipMain"; + m_mip_pipeline.rebuild(core, down_config); + + m_inject_layout.rebuild(core, inject_shader->reflection, "GiClipmapPass Inject"); + VulkanPipeline::Config inject_config; + inject_config.pipeline_type = VulkanPipeline::PipelineType::compute; + inject_config.debug_name = "GiClipmapPass injectMain"; + inject_config.shader_spirv = inject_shader->spirv; + inject_config.pipeline_layout = *m_inject_layout.getPipelineLayout(); + inject_config.compute_entry = "injectMain"; + m_inject_pipeline.rebuild(core, inject_config); + + m_debug_layout.rebuild(core, debug_shader->reflection, "GiClipmapPass Debug"); + VulkanPipeline::Config config; + config.pipeline_type = VulkanPipeline::PipelineType::graphics; + config.debug_name = "GiClipmapPass Debug"; + config.color_format = m_scene_format; + config.write_color_alpha = true; + config.extent = m_extent; + config.shader_spirv = debug_shader->spirv; + config.pipeline_layout = *m_debug_layout.getPipelineLayout(); + config.vertex_bindings = {}; + config.vertex_attributes = {}; + config.cull_mode = vk::CullModeFlagBits::eNone; + config.depth_test = false; + config.depth_write = false; + m_debug_pipeline.rebuild(core, config); + + const auto& fill_layouts = m_fill_layout.getDescriptorSetLayouts(); + const auto& debug_layouts = m_debug_layout.getDescriptorSetLayouts(); + const auto& inject_layouts = m_inject_layout.getDescriptorSetLayouts(); + const auto& bounce_layouts = m_bounce_layout.getDescriptorSetLayouts(); + const auto& down_layouts = m_down_layout.getDescriptorSetLayouts(); + if (fill_layouts.size() <= k_storage_set || debug_layouts.empty() || inject_layouts.size() <= k_inject_set || + bounce_layouts.size() <= k_bounce_set || down_layouts.empty()) { + TOAST_ERROR("Render", "GiClipmapPass shader layouts have no descriptor sets, the radiance clipmap is disabled"); + return false; + } + + const vk::DescriptorPool pool = VulkanRenderer::instance->getDescriptorPoolHandle(); + const vk::DescriptorSetLayout fill_set_layout = *fill_layouts[k_fill_set]; + const vk::DescriptorSetLayout storage_set_layout = *fill_layouts[k_storage_set]; + const vk::DescriptorSetLayout debug_set_layout = *debug_layouts[0]; + const vk::DescriptorSetLayout inject_set_layout = *inject_layouts[k_inject_set]; + m_inject_scene_sets.create(core, inject_shader->reflection, *inject_layouts[k_inject_scene_set], "GiClipmapPass Inject"); + const vk::DescriptorSetLayout bounce_set_layout = *bounce_layouts[k_bounce_set]; + const vk::DescriptorSetLayout down_set_layout = *down_layouts[0]; + m_bounce_scene_sets.create(core, bounce_shader->reflection, *bounce_layouts[k_bounce_scene_set], "GiClipmapPass Bounce"); + constexpr auto storage = vk::DescriptorType::eStorageBuffer; + DescriptorWriter writer; + for (uint32_t i = 0; i < VulkanRenderer::k_frames_in_flight; ++i) { + for (uint32_t level = 0; level < k_max_levels; ++level) { + auto fill = core.getDevice().allocateDescriptorSets(vk::DescriptorSetAllocateInfo(pool, 1, &fill_set_layout)); + m_fill_sets.push_back(std::move(fill[0])); + setDebugName(core, *m_fill_sets.back(), std::format("GiClipmapPass FillSet[{}][{}]", i, level)); + writer.buffer(*m_fill_sets.back(), k_fill_frame_binding, storage, *m_frame_data[i]); + auto inject = core.getDevice().allocateDescriptorSets(vk::DescriptorSetAllocateInfo(pool, 1, &inject_set_layout)); + m_inject_sets.push_back(std::move(inject[0])); + setDebugName(core, *m_inject_sets.back(), std::format("GiClipmapPass InjectSet[{}][{}]", i, level)); + writer.buffer(*m_inject_sets.back(), k_inject_frame_binding, storage, *m_frame_data[i]); + auto bounce = core.getDevice().allocateDescriptorSets(vk::DescriptorSetAllocateInfo(pool, 1, &bounce_set_layout)); + m_bounce_sets.push_back(std::move(bounce[0])); + setDebugName(core, *m_bounce_sets.back(), std::format("GiClipmapPass BounceSet[{}][{}]", i, level)); + writer.buffer(*m_bounce_sets.back(), k_bounce_list_binding, storage, **m_bounce_list); + auto down = core.getDevice().allocateDescriptorSets(vk::DescriptorSetAllocateInfo(pool, 1, &down_set_layout)); + m_down_sets.push_back(std::move(down[0])); + setDebugName(core, *m_down_sets.back(), std::format("GiClipmapPass DownSet[{}][{}]", i, level)); + writer.buffer(*m_down_sets.back(), k_down_frame_binding, storage, *m_frame_data[i]); + } + for (uint32_t mip = 0; mip < k_max_tail; ++mip) { + auto set = core.getDevice().allocateDescriptorSets(vk::DescriptorSetAllocateInfo(pool, 1, &down_set_layout)); + m_mip_sets.push_back(std::move(set[0])); + setDebugName(core, *m_mip_sets.back(), std::format("GiClipmapPass MipSet[{}][{}]", i, mip)); + writer.buffer(*m_mip_sets.back(), k_down_frame_binding, storage, *m_frame_data[i]); + } + auto storage_set = core.getDevice().allocateDescriptorSets(vk::DescriptorSetAllocateInfo(pool, 1, &storage_set_layout)); + m_storage_sets.push_back(std::move(storage_set[0])); + setDebugName(core, *m_storage_sets.back(), std::format("GiClipmapPass StorageSet[{}]", i)); + auto debug = core.getDevice().allocateDescriptorSets(vk::DescriptorSetAllocateInfo(pool, 1, &debug_set_layout)); + m_debug_sets.push_back(std::move(debug[0])); + setDebugName(core, *m_debug_sets.back(), std::format("GiClipmapPass DebugSet[{}]", i)); + writer.buffer(*m_debug_sets.back(), k_debug_frame_binding, storage, *m_frame_data[i]); + } + writer.flush(core.getDevice()); + m_storage_bound.resize(VulkanRenderer::k_frames_in_flight); + m_debug_bound.resize(VulkanRenderer::k_frames_in_flight); + return m_fill_pipeline.isReady(); +} + +void GiClipmapPass::createLevels(uint32_t resolution, uint32_t levels) { + ZoneScoped; + const VulkanCore& core = *m_core; + if (m_level_count != 0) { + const std::lock_guard lock(core.graphicsSubmitMutex()); + core.getDevice().waitIdle(); + } + m_resolution = resolution; + m_level_count = levels; + m_tail = tailMips(resolution); + + const vk::ImageSubresourceRange range {vk::ImageAspectFlagBits::eColor, 0, 1, 0, 1}; + const auto create = [&](vk::Format format, + std::string_view name, + std::optional& image, + std::optional& view, + sync::ImageState& state, + vk::ImageCreateFlags flags = {}, + uint32_t mip_count = 1) { + vk::ImageCreateInfo image_ci {}; + image_ci.flags = flags; + image_ci.imageType = vk::ImageType::e3D; + image_ci.format = format; + image_ci.extent = vk::Extent3D {resolution, resolution, resolution}; + image_ci.mipLevels = mip_count; + image_ci.arrayLayers = 1; + image_ci.samples = vk::SampleCountFlagBits::e1; + image_ci.tiling = vk::ImageTiling::eOptimal; + image_ci.usage = vk::ImageUsageFlagBits::eStorage | vk::ImageUsageFlagBits::eSampled; + image_ci.sharingMode = vk::SharingMode::eExclusive; + image_ci.initialLayout = vk::ImageLayout::eUndefined; + vma::AllocationCreateInfo image_alloc {}; + image_alloc.usage = vma::MemoryUsage::eAutoPreferDevice; + view.reset(); + image.emplace(core.getAllocator().createImage(image_ci, image_alloc)); + setDebugName(core, **image, name); + vk::ImageViewCreateInfo view_ci {}; + view_ci.image = **image; + view_ci.viewType = vk::ImageViewType::e3D; + view_ci.format = format; + view_ci.subresourceRange = range; + view.emplace(core.getDevice(), view_ci); + state.reset(**image, vk::ImageSubresourceRange {vk::ImageAspectFlagBits::eColor, 0, mip_count, 0, 1}); + }; + + DescriptorWriter writer; + for (uint32_t i = 0; i < k_max_levels; ++i) { + Level& level = m_levels[i]; + if (i >= levels) { + level = Level {}; + continue; + } + const uint32_t mips = i + 1 == levels ? 1 + m_tail : 1; + create( + k_material_format, std::format("GiClipmapPass Material[{}]", i), level.material, level.material_view, level.material_state + ); + create( + k_emission_format, std::format("GiClipmapPass Emission[{}]", i), level.emission, level.emission_view, level.emission_state + ); + for (uint32_t f = 0; f < 2 * k_faces; ++f) { + const bool bounce = f >= k_faces; + Face& face = bounce ? level.ambient[f - k_faces] : level.faces[f]; + const uint32_t face_mips = bounce ? 1 : mips; + face.mip_views.clear(); + face.sampled_view.reset(); + create( + k_radiance_storage_format, + std::format("GiClipmapPass {}[{}][{}]", bounce ? "Ambient" : "Radiance", i, f % k_faces), + face.image, + face.storage_view, + face.state, + vk::ImageCreateFlagBits::eMutableFormat, + face_mips + ); + // The packed float format has no storage support so its view only samples + const vk::ImageViewUsageCreateInfo view_usage(vk::ImageUsageFlagBits::eSampled); + vk::ImageViewCreateInfo view_ci {}; + view_ci.pNext = &view_usage; + view_ci.image = **face.image; + view_ci.viewType = vk::ImageViewType::e3D; + view_ci.format = k_radiance_sampled_format; + view_ci.subresourceRange = vk::ImageSubresourceRange {vk::ImageAspectFlagBits::eColor, 0, face_mips, 0, 1}; + face.sampled_view.emplace(core.getDevice(), view_ci); + for (uint32_t mip = 1; mip < face_mips; ++mip) { + vk::ImageViewCreateInfo mip_ci {}; + mip_ci.image = **face.image; + mip_ci.viewType = vk::ImageViewType::e3D; + mip_ci.format = k_radiance_storage_format; + mip_ci.subresourceRange = vk::ImageSubresourceRange {vk::ImageAspectFlagBits::eColor, mip, 1, 0, 1}; + face.mip_views.emplace_back(core.getDevice(), mip_ci); + } + } + level.opacity_mip_views.clear(); + level.opacity_all_view.reset(); + create( + k_material_format, + std::format("GiClipmapPass Opacity[{}]", i), + level.opacity, + level.opacity_view, + level.opacity_state, + {}, + mips + ); + if (mips > 1) { + vk::ImageViewCreateInfo all_ci {}; + all_ci.image = **level.opacity; + all_ci.viewType = vk::ImageViewType::e3D; + all_ci.format = k_material_format; + all_ci.subresourceRange = vk::ImageSubresourceRange {vk::ImageAspectFlagBits::eColor, 0, mips, 0, 1}; + level.opacity_all_view.emplace(core.getDevice(), all_ci); + for (uint32_t mip = 1; mip < mips; ++mip) { + all_ci.subresourceRange = vk::ImageSubresourceRange {vk::ImageAspectFlagBits::eColor, mip, 1, 0, 1}; + level.opacity_mip_views.emplace_back(core.getDevice(), all_ci); + } + } + level.needs_full = true; + for (uint32_t frame = 0; frame < VulkanRenderer::k_frames_in_flight; ++frame) { + const vk::DescriptorSet set = *m_fill_sets[(frame * k_max_levels) + i]; + std::array ambient_storage; + std::array ambient_sampled; + for (uint32_t f = 0; f < k_faces; ++f) { + ambient_storage[f] = vk::DescriptorImageInfo(nullptr, **level.ambient[f].storage_view, vk::ImageLayout::eGeneral); + ambient_sampled[f] = + vk::DescriptorImageInfo(*m_point_sampler, **level.ambient[f].sampled_view, vk::ImageLayout::eShaderReadOnlyOptimal); + } + writer.imageArray(set, k_fill_ambient_binding, vk::DescriptorType::eStorageImage, ambient_storage); + writer.imageArray( + *m_bounce_sets[(frame * k_max_levels) + i], k_bounce_ambient_binding, vk::DescriptorType::eStorageImage, ambient_storage + ); + writer.imageArray( + *m_inject_sets[(frame * k_max_levels) + i], + k_inject_ambient_binding, + vk::DescriptorType::eCombinedImageSampler, + ambient_sampled + ); + writer.image( + set, k_fill_opacity_binding, vk::DescriptorType::eStorageImage, nullptr, **level.opacity_view, vk::ImageLayout::eGeneral + ); + writer.image( + set, + k_fill_material_binding, + vk::DescriptorType::eStorageImage, + nullptr, + **level.material_view, + vk::ImageLayout::eGeneral + ); + writer.image( + set, + k_fill_emission_binding, + vk::DescriptorType::eStorageImage, + nullptr, + **level.emission_view, + vk::ImageLayout::eGeneral + ); + } + } + std::array materials; + for (uint32_t i = 0; i < k_max_levels; ++i) { + materials[i] = vk::DescriptorImageInfo( + *m_point_sampler, **m_levels[i < levels ? i : 0].material_view, vk::ImageLayout::eShaderReadOnlyOptimal + ); + } + for (uint32_t i = 0; i < levels; ++i) { + const Level& level = m_levels[i]; + for (uint32_t frame = 0; frame < VulkanRenderer::k_frames_in_flight; ++frame) { + const vk::DescriptorSet set = *m_inject_sets[(frame * k_max_levels) + i]; + writer.imageArray(set, k_inject_material_binding, vk::DescriptorType::eCombinedImageSampler, materials); + writer.image( + set, + k_inject_emission_binding, + vk::DescriptorType::eCombinedImageSampler, + *m_point_sampler, + **level.emission_view, + vk::ImageLayout::eShaderReadOnlyOptimal + ); + std::array faces; + for (uint32_t f = 0; f < k_faces; ++f) { + faces[f] = vk::DescriptorImageInfo(nullptr, **level.faces[f].storage_view, vk::ImageLayout::eGeneral); + } + writer.imageArray(set, k_inject_radiance_binding, vk::DescriptorType::eStorageImage, faces); + writer.image( + set, + k_inject_opacity_binding, + vk::DescriptorType::eCombinedImageSampler, + *m_point_sampler, + **level.opacity_view, + vk::ImageLayout::eShaderReadOnlyOptimal + ); + if (i == 0) { + continue; + } + const Level& child = m_levels[i - 1]; + const vk::DescriptorSet down = *m_down_sets[(frame * k_max_levels) + i]; + constexpr auto sampled = vk::DescriptorType::eCombinedImageSampler; + constexpr auto read = vk::ImageLayout::eShaderReadOnlyOptimal; + std::array child_radiance; + std::array child_ambient; + std::array ambient; + for (uint32_t f = 0; f < k_faces; ++f) { + child_radiance[f] = vk::DescriptorImageInfo(*m_point_sampler, **child.faces[f].sampled_view, read); + child_ambient[f] = vk::DescriptorImageInfo(*m_point_sampler, **child.ambient[f].sampled_view, read); + ambient[f] = vk::DescriptorImageInfo(nullptr, **level.ambient[f].storage_view, vk::ImageLayout::eGeneral); + } + writer.image(down, k_down_child_opacity_binding, sampled, *m_point_sampler, **child.opacity_view, read); + writer.imageArray(down, k_down_child_radiance_binding, sampled, child_radiance); + writer.imageArray(down, k_down_child_ambient_binding, sampled, child_ambient); + writer.image( + down, + k_down_opacity_binding, + vk::DescriptorType::eStorageImage, + nullptr, + **level.opacity_view, + vk::ImageLayout::eGeneral + ); + writer.imageArray(down, k_down_radiance_binding, vk::DescriptorType::eStorageImage, faces); + writer.imageArray(down, k_down_ambient_binding, vk::DescriptorType::eStorageImage, ambient); + } + } + const Level& top = m_levels[levels - 1]; + for (uint32_t frame = 0; frame < VulkanRenderer::k_frames_in_flight; ++frame) { + for (uint32_t mip = 1; mip <= m_tail; ++mip) { + const vk::DescriptorSet set = *m_mip_sets[(frame * k_max_tail) + mip - 1]; + constexpr auto sampled = vk::DescriptorType::eCombinedImageSampler; + constexpr auto image = vk::DescriptorType::eStorageImage; + constexpr auto general = vk::ImageLayout::eGeneral; + std::array child_radiance; + std::array child_ambient; + std::array radiance; + std::array ambient; + for (uint32_t f = 0; f < k_faces; ++f) { + child_radiance[f] = vk::DescriptorImageInfo(*m_point_sampler, **top.faces[f].sampled_view, general); + radiance[f] = vk::DescriptorImageInfo(nullptr, *top.faces[f].mip_views[mip - 1], general); + // mipMain never touches the bounce so these only fill the layout + child_ambient[f] = + vk::DescriptorImageInfo(*m_point_sampler, **top.ambient[f].sampled_view, vk::ImageLayout::eShaderReadOnlyOptimal); + ambient[f] = vk::DescriptorImageInfo(nullptr, **top.ambient[f].storage_view, general); + } + writer.image(set, k_down_child_opacity_binding, sampled, *m_point_sampler, **top.opacity_all_view, general); + writer.imageArray(set, k_down_child_radiance_binding, sampled, child_radiance); + writer.imageArray(set, k_down_child_ambient_binding, sampled, child_ambient); + writer.image(set, k_down_opacity_binding, image, nullptr, *top.opacity_mip_views[mip - 1], general); + writer.imageArray(set, k_down_radiance_binding, image, radiance); + writer.imageArray(set, k_down_ambient_binding, image, ambient); + } + } + writer.flush(core.getDevice()); + m_debug_bound.invalidate(); + bumpTargetGeneration(); + TOAST_INFO( + "Render", + "GiClipmapPass {} levels of {} cells a side ({} MB)", + levels, + resolution, + (static_cast(resolution) * resolution * resolution * 64 * levels) >> 20 + ); +} + +void GiClipmapPass::gatherBodies(const RenderFrame& frame) { + const auto add = [&](glm::vec3 low, glm::vec3 high) { + if (m_body_boxes.size() < 2 * k_max_body_boxes) { + m_body_boxes.push_back(low); + m_body_boxes.push_back(high); + return; + } + auto last = m_body_boxes.end() - 2; + last[0] = glm::min(last[0], low); + last[1] = glm::max(last[1], high); + }; + const auto sphere = [&](const glm::vec4& bounds) { add(glm::vec3(bounds) - bounds.w, glm::vec3(bounds) + bounds.w); }; + + m_bodies_next.clear(); + for (const auto& proxy : frame.voxel_instances) { + const Body body {.model = proxy.model, .bounds = glm::vec4(proxy.bounds_center, proxy.bounds_radius)}; + m_bodies_next.emplace(proxy.node_rid, body); + const auto found = m_bodies.find(proxy.node_rid); + if (found == m_bodies.end()) { + sphere(body.bounds); + } else if (found->second.model != body.model) { + sphere(found->second.bounds); + sphere(body.bounds); + } + } + for (const auto& [rid, body] : m_bodies) { + if (!m_bodies_next.contains(rid)) { + sphere(body.bounds); + } + } + std::swap(m_bodies, m_bodies_next); +} + +auto GiClipmapPass::ambientViews() const -> std::array { + std::array views; + for (uint32_t i = 0; i < k_max_levels; ++i) { + for (uint32_t f = 0; f < k_faces; ++f) { + views[(i * k_faces) + f] = + m_level_count == 0 ? **m_dummy_view : **m_levels[i < m_level_count ? i : 0].ambient[f].sampled_view; + } + } + return views; +} + +auto GiClipmapPass::radianceViews() const -> std::array { + std::array views; + for (uint32_t i = 0; i < k_max_levels; ++i) { + for (uint32_t f = 0; f < k_faces; ++f) { + views[(i * k_faces) + f] = + m_level_count == 0 ? **m_dummy_view : **m_levels[i < m_level_count ? i : 0].faces[f].sampled_view; + } + } + return views; +} + +auto GiClipmapPass::opacityViews() const -> std::array { + std::array views; + for (uint32_t i = 0; i < k_max_levels; ++i) { + const Level& level = m_levels[i < m_level_count ? i : 0]; + views[i] = m_level_count == 0 ? **m_dummy_view + : (level.opacity_all_view.has_value() ? **level.opacity_all_view : **level.opacity_view); + } + return views; +} + +void GiClipmapPass::unpublish(vk::CommandBuffer cmd) { + if (!m_published_valid) { + return; + } + sync::BarrierBatch barriers; + barriers.memory(sync::Usage::fragment_storage_read, sync::Usage::transfer_dst); + barriers.memory(sync::Usage::compute_storage_read, sync::Usage::transfer_dst); + barriers.flush(cmd); + cmd.fillBuffer(**m_published, 0, vk::WholeSize, 0u); + barriers.memory(sync::Usage::transfer_dst, sync::Usage::fragment_storage_read); + barriers.memory(sync::Usage::transfer_dst, sync::Usage::compute_storage_read); + barriers.flush(cmd); + m_published_valid = false; +} + +void GiClipmapPass::markFull() { + for (Level& level : m_levels) { + level.needs_full = true; + } +} + +void GiClipmapPass::onResize(vk::Extent2D extent) { + m_extent = extent; + if (m_core != nullptr && m_debug_pipeline.isReady()) { + m_debug_target.create(*m_core, extent, m_scene_format, "GiClipmapPass Debug"); + m_debug_bound.invalidate(); + } +} + +auto GiClipmapPass::record(vk::CommandBuffer cmd, uint32_t frame_index, vk::ImageView source_view) -> vk::ImageView { + ZoneScoped; + auto* renderer = VulkanRenderer::instance; + const auto* frame = renderer->renderingFrame(); + const GiSettings& settings = renderer->giSettings(); + constexpr auto relaxed = std::memory_order_relaxed; + if (!settings.enabled.load(relaxed) || settings.backend.load(relaxed) != GiSettings::k_backend_clipmap || frame == nullptr || + frame_index >= m_storage_sets.size() || !m_fill_pipeline.isReady()) { + markFull(); + unpublish(cmd); + return source_view; + } + + gatherBodies(*frame); + // Bodies are tracked above against the last fill so only edits and new bodies come from here + m_dirty_boxes.gather(*frame, std::numeric_limits::max()); + GiDirtyBoxes::Counts counts; + const bool known = m_dirty_boxes.take(counts); + + const VoxelTraceScene* trace = renderer->voxelTraceScene(); + if (trace == nullptr || !frame->voxel_storage || !frame->voxel_storage->isReady()) { + m_dirty_boxes.clear(); + m_body_boxes.clear(); + markFull(); + unpublish(cmd); + return source_view; + } + + struct Tier { + uint32_t resolution; + uint32_t levels; + }; + + constexpr std::array k_tiers { + {{64, 3}, {96, 4}, {128, 4}, {128, 5}} + }; + const uint32_t quality = std::min(settings.quality.load(relaxed), GiSettings::k_quality_custom); + const bool custom = quality == GiSettings::k_quality_custom; + const uint32_t resolution = + custom ? std::clamp(settings.clip_resolution.load(relaxed), 32u, 256u) : k_tiers[quality].resolution; + const uint32_t level_count = + custom ? std::clamp(settings.clip_levels.load(relaxed), 1u, k_max_levels) : k_tiers[quality].levels; + if (resolution != m_resolution || level_count != m_level_count) { + createLevels(resolution, level_count); + markFull(); + } + const float cell = std::clamp(settings.clip_cell.load(relaxed), 0.05f, 4.0f); + if (cell != m_cell) { + m_cell = cell; + markFull(); + } + + // Safe since the fence of this slot was waited on + if (m_storage_bound.update(frame_index, frame->voxel_storage)) { + const vk::DescriptorSet set = *m_storage_sets[frame_index]; + writeVoxelStorageDescriptors(m_core->getDevice(), set, *frame->voxel_storage); + constexpr auto storage = vk::DescriptorType::eStorageBuffer; + DescriptorWriter writer; + writer.buffer(set, k_trace_volumes_binding, storage, trace->volumeBuffer(frame_index)); + writer.buffer(set, k_trace_bounds_binding, storage, trace->boundsBuffer(frame_index)); + writer.buffer(set, k_trace_grid_binding, storage, trace->gridBuffer(frame_index)); + writer.flush(m_core->getDevice()); + } + + // Before the fill so the clipmap is still the one lighting read last frame and its published frame addresses it + const int bounce_slab = std::max(static_cast(resolution) / static_cast(k_inject_period), 1); + const int bounce_phase = static_cast(m_frame % k_inject_period); + if (m_published_valid && m_bounce_pipeline.isReady() && m_bounce_list_pipeline.isReady() && !m_bounce_scene_sets.empty() && + !m_levels[0].needs_full) { + const GpuScope scope(renderer->gpuTimer(), frame_index, cmd, "GI clip bounce"); + sync::BarrierBatch barriers; + for (uint32_t i = 0; i < level_count; ++i) { + for (Face& face : m_levels[i].ambient) { + barriers.image(face.state, sync::Usage::compute_storage_write); + } + } + barriers.flush(cmd); + m_bounce_scene_sets.updateTlas(frame_index); + const vk::PipelineLayout layout = *m_bounce_layout.getPipelineLayout(); + cmd.bindDescriptorSets( + vk::PipelineBindPoint::eCompute, + layout, + k_bounce_scene_set, + std::array {m_bounce_scene_sets.get(frame_index)}, + {} + ); + const int bounce_side = static_cast(resolution); + for (uint32_t i = 0; i < level_count; ++i) { + const glm::ivec3 origin = m_levels[i].origin; + glm::ivec3 low = origin; + glm::ivec3 size(bounce_side); + low.z = origin.z + (bounce_phase * bounce_slab); + size.z = bounce_phase + 1 == static_cast(k_inject_period) ? (origin.z + bounce_side) - low.z : bounce_slab; + cmd.bindDescriptorSets( + vk::PipelineBindPoint::eCompute, + layout, + k_bounce_set, + std::array {*m_bounce_sets[(frame_index * k_max_levels) + i]}, + {} + ); + const FillPush push {.box_min = glm::ivec4(low, static_cast(i)), .box_size = glm::ivec4(size, 0)}; + cmd.pushConstants(layout, vk::ShaderStageFlagBits::eAll, 0, sizeof(push), &push); + + barriers.memory(sync::Usage::compute_storage_write, sync::Usage::transfer_dst); + barriers.flush(cmd); + cmd.fillBuffer(**m_bounce_list, 0, sizeof(uint32_t) * k_bounce_header, 0u); + barriers.memory(sync::Usage::transfer_dst, sync::Usage::compute_storage_write); + barriers.flush(cmd); + cmd.bindPipeline(vk::PipelineBindPoint::eCompute, m_bounce_list_pipeline.getPipeline()); + const glm::ivec3 groups = (size + (k_group - 1)) / k_group; + cmd.dispatch(static_cast(groups.x), static_cast(groups.y), static_cast(groups.z)); + + // Every group past the count leaves at once so the full capacity is dispatched without a readback + barriers.memory(sync::Usage::compute_storage_write, sync::Usage::compute_storage_write); + barriers.flush(cmd); + cmd.bindPipeline(vk::PipelineBindPoint::eCompute, m_bounce_pipeline.getPipeline()); + cmd.dispatch(k_bounce_capacity / k_bounce_group, 1, 1); + } + } + + const glm::vec3 camera = frame->frame_data.camera_position; + FrameData data { + .inverse_view_projection = glm::inverse(frame->frame_data.view_projection), + .camera = glm::vec4(camera, 0.0f), + .size = glm::uvec4(resolution, level_count, 1u, m_tail), + }; + + const int side = static_cast(resolution); + std::vector dirty = std::move(m_body_boxes); + m_body_boxes.clear(); + dirty.insert(dirty.end(), m_dirty_boxes.boxes().begin(), m_dirty_boxes.boxes().end()); + std::array, k_max_levels> boxes; + std::array whole {}; + std::array scrolled_boxes {}; + bool any = false; + for (uint32_t i = 0; i < level_count; ++i) { + Level& level = m_levels[i]; + const float level_cell = cell * static_cast(1u << i); + const glm::ivec3 origin = gi_clip::origin(camera, level_cell, side); + data.levels[i] = glm::vec4(glm::vec3(origin), level_cell); + if (level.needs_full || !known) { + boxes[i].push_back({.min = origin, .max = origin + side}); + whole[i] = true; + scrolled_boxes[i] = 1; + } else { + std::array slabs; + const uint32_t count = gi_clip::scrolled(level.origin, origin, side, slabs); + boxes[i].assign(slabs.begin(), slabs.begin() + count); + scrolled_boxes[i] = count; + for (size_t b = 0; b + 1 < dirty.size(); b += 2) { + const gi_clip::Box box = gi_clip::cells(dirty[b], dirty[b + 1], level_cell, origin, side); + if (!gi_clip::empty(box)) { + boxes[i].push_back(box); + } + } + } + level.origin = origin; + level.needs_full = false; + any = any || !boxes[i].empty(); + } + m_dirty_boxes.clear(); + + const auto& allocation = m_frame_data[frame_index].getAllocation(); + std::memcpy(allocation.getInfo().pMappedData, &data, sizeof(data)); + allocation.flush(0, sizeof(data)); + + if (any) { + const GpuScope scope(renderer->gpuTimer(), frame_index, cmd, "GI clip fill"); + sync::BarrierBatch barriers; + for (uint32_t i = 0; i < level_count; ++i) { + if (!boxes[i].empty()) { + barriers.image(m_levels[i].material_state, sync::Usage::compute_storage_write); + barriers.image(m_levels[i].emission_state, sync::Usage::compute_storage_write); + barriers.image(m_levels[i].opacity_state, sync::Usage::compute_storage_write); + for (Face& face : m_levels[i].ambient) { + barriers.image(face.state, sync::Usage::compute_storage_write); + } + } + } + barriers.flush(cmd); + + const vk::PipelineLayout layout = *m_fill_layout.getPipelineLayout(); + cmd.bindPipeline(vk::PipelineBindPoint::eCompute, m_fill_pipeline.getPipeline()); + cmd.bindDescriptorSets( + vk::PipelineBindPoint::eCompute, + layout, + k_storage_set, + std::array {*m_storage_sets[frame_index]}, + {} + ); + for (uint32_t i = 0; i < level_count; ++i) { + if (boxes[i].empty()) { + continue; + } + cmd.bindDescriptorSets( + vk::PipelineBindPoint::eCompute, + layout, + k_fill_set, + std::array {*m_fill_sets[(frame_index * k_max_levels) + i]}, + {} + ); + for (size_t b = 0; b < boxes[i].size(); ++b) { + const gi_clip::Box& box = boxes[i][b]; + const glm::ivec3 size = box.max - box.min; + const FillPush push { + .box_min = glm::ivec4(box.min, static_cast(i)), + .box_size = glm::ivec4(size, b < scrolled_boxes[i] ? 1 : 0), + }; + cmd.pushConstants(layout, vk::ShaderStageFlagBits::eAll, 0, sizeof(push), &push); + const glm::ivec3 groups = (size + (k_group - 1)) / k_group; + cmd.dispatch(static_cast(groups.x), static_cast(groups.y), static_cast(groups.z)); + } + } + } + + std::array, k_max_levels> injected; + if (m_inject_pipeline.isReady() && !m_inject_scene_sets.empty()) { + const GpuScope scope(renderer->gpuTimer(), frame_index, cmd, "GI clip inject"); + sync::BarrierBatch barriers; + for (uint32_t i = 0; i < level_count; ++i) { + barriers.image(m_levels[i].material_state, sync::Usage::shader_sampled); + barriers.image(m_levels[i].emission_state, sync::Usage::shader_sampled); + barriers.image(m_levels[i].opacity_state, sync::Usage::shader_sampled); + for (Face& face : m_levels[i].faces) { + barriers.image(face.state, sync::Usage::compute_storage_write); + } + for (Face& face : m_levels[i].ambient) { + barriers.image(face.state, sync::Usage::shader_sampled); + } + } + barriers.flush(cmd); + + m_inject_scene_sets.updateTlas(frame_index); + const vk::PipelineLayout layout = *m_inject_layout.getPipelineLayout(); + cmd.bindPipeline(vk::PipelineBindPoint::eCompute, m_inject_pipeline.getPipeline()); + cmd.bindDescriptorSets( + vk::PipelineBindPoint::eCompute, + layout, + k_inject_scene_set, + std::array {m_inject_scene_sets.get(frame_index)}, + {} + ); + const int slab = std::max(side / static_cast(k_inject_period), 1); + const int phase = static_cast(m_frame++ % k_inject_period); + for (uint32_t i = 0; i < level_count; ++i) { + std::vector& inject = injected[i]; + const glm::ivec3 origin = m_levels[i].origin; + const gi_clip::Box level_box {.min = origin, .max = origin + side}; + if (whole[i]) { + inject.push_back(level_box); + } else { + // One cell wider since a changed cell changes which faces of its neighbours are exposed + for (const gi_clip::Box& box : boxes[i]) { + inject.push_back({.min = glm::max(box.min - 1, level_box.min), .max = glm::min(box.max + 1, level_box.max)}); + } + // The rest relights round robin so a far occluder change still arrives + gi_clip::Box round = level_box; + round.min.z = origin.z + (phase * slab); + round.max.z = phase + 1 == static_cast(k_inject_period) ? level_box.max.z : round.min.z + slab; + inject.push_back(round); + } + cmd.bindDescriptorSets( + vk::PipelineBindPoint::eCompute, + layout, + k_inject_set, + std::array {*m_inject_sets[(frame_index * k_max_levels) + i]}, + {} + ); + for (const gi_clip::Box& box : inject) { + const glm::ivec3 size = box.max - box.min; + const FillPush push {.box_min = glm::ivec4(box.min, static_cast(i)), .box_size = glm::ivec4(size, 0)}; + cmd.pushConstants(layout, vk::ShaderStageFlagBits::eAll, 0, sizeof(push), &push); + const glm::ivec3 groups = (size + (k_group - 1)) / k_group; + cmd.dispatch(static_cast(groups.x), static_cast(groups.y), static_cast(groups.z)); + } + } + } + + std::vector written; + if (m_down_pipeline.isReady() && m_inject_pipeline.isReady() && !m_inject_scene_sets.empty() && level_count > 1) { + const GpuScope scope(renderer->gpuTimer(), frame_index, cmd, "GI clip downsample"); + const vk::PipelineLayout layout = *m_down_layout.getPipelineLayout(); + cmd.bindPipeline(vk::PipelineBindPoint::eCompute, m_down_pipeline.getPipeline()); + std::vector parents; + for (uint32_t i = 0; i + 1 < level_count; ++i) { + // The finer box in cells of the level written which is whole cells since level origins are even + const glm::ivec3 inner_min = m_levels[i].origin >> 1; + const gi_clip::Box inner {.min = inner_min, .max = inner_min + (side / 2)}; + parents.clear(); + if (whole[i] || whole[i + 1]) { + parents.push_back(inner); + } else { + const auto add = [&](const gi_clip::Box& box) { + const gi_clip::Box parent {.min = glm::max(box.min >> 1, inner.min), .max = glm::min((box.max + 1) >> 1, inner.max)}; + if (!gi_clip::empty(parent)) { + parents.push_back(parent); + } + }; + std::ranges::for_each(injected[i], add); + std::ranges::for_each(written, add); + if (parents.size() > k_max_down_boxes) { + gi_clip::Box bounds = parents.front(); + for (const gi_clip::Box& box : parents) { + bounds.min = glm::min(bounds.min, box.min); + bounds.max = glm::max(bounds.max, box.max); + } + parents.assign(1, bounds); + } + } + written = parents; + if (parents.empty()) { + continue; + } + sync::BarrierBatch barriers; + barriers.image(m_levels[i].opacity_state, sync::Usage::shader_sampled); + barriers.image(m_levels[i + 1].opacity_state, sync::Usage::compute_storage_write); + for (uint32_t f = 0; f < k_faces; ++f) { + barriers.image(m_levels[i].faces[f].state, sync::Usage::shader_sampled); + barriers.image(m_levels[i].ambient[f].state, sync::Usage::shader_sampled); + barriers.image(m_levels[i + 1].faces[f].state, sync::Usage::compute_storage_write); + barriers.image(m_levels[i + 1].ambient[f].state, sync::Usage::compute_storage_write); + } + barriers.flush(cmd); + cmd.bindDescriptorSets( + vk::PipelineBindPoint::eCompute, + layout, + 0, + std::array {*m_down_sets[(frame_index * k_max_levels) + i + 1]}, + {} + ); + for (const gi_clip::Box& box : parents) { + const glm::ivec3 size = box.max - box.min; + const DownPush push {.box_min = glm::ivec4(box.min, side), .box_size = glm::ivec4(size, side)}; + cmd.pushConstants(layout, vk::ShaderStageFlagBits::eAll, 0, sizeof(push), &push); + const glm::ivec3 groups = (size + (k_group - 1)) / k_group; + cmd.dispatch(static_cast(groups.x), static_cast(groups.y), static_cast(groups.z)); + } + } + } + + if (m_mip_pipeline.isReady() && m_tail > 0 && m_inject_pipeline.isReady() && !m_inject_scene_sets.empty()) { + const GpuScope scope(renderer->gpuTimer(), frame_index, cmd, "GI clip mips"); + const uint32_t last = level_count - 1; + Level& top = m_levels[last]; + std::vector changed = level_count > 1 ? written : std::vector {}; + changed.insert(changed.end(), injected[last].begin(), injected[last].end()); + sync::BarrierBatch barriers; + barriers.image(top.opacity_state, sync::Usage::general); + for (Face& face : top.faces) { + barriers.image(face.state, sync::Usage::general); + } + barriers.flush(cmd); + const vk::PipelineLayout layout = *m_down_layout.getPipelineLayout(); + cmd.bindPipeline(vk::PipelineBindPoint::eCompute, m_mip_pipeline.getPipeline()); + std::vector parents; + for (uint32_t mip = 1; mip <= m_tail; ++mip) { + const int parent_side = side >> mip; + parents.clear(); + if (whole[last]) { + // Any run of that many cells covers every texel + const glm::ivec3 low = top.origin >> static_cast(mip); + parents.push_back({.min = low, .max = low + parent_side}); + } else { + for (const gi_clip::Box& box : changed) { + gi_clip::Box parent {.min = box.min >> 1, .max = (box.max + 1) >> 1}; + parent.max = glm::min(parent.max, parent.min + parent_side); + if (!gi_clip::empty(parent)) { + parents.push_back(parent); + } + } + if (parents.size() > k_max_down_boxes) { + gi_clip::Box bounds = parents.front(); + for (const gi_clip::Box& box : parents) { + bounds.min = glm::min(bounds.min, box.min); + bounds.max = glm::max(bounds.max, box.max); + } + bounds.max = glm::min(bounds.max, bounds.min + parent_side); + parents.assign(1, bounds); + } + } + changed = parents; + if (parents.empty()) { + break; + } + barriers.memory(sync::Usage::general, sync::Usage::general); + barriers.flush(cmd); + cmd.bindDescriptorSets( + vk::PipelineBindPoint::eCompute, + layout, + 0, + std::array {*m_mip_sets[(frame_index * k_max_tail) + mip - 1]}, + {} + ); + for (const gi_clip::Box& box : parents) { + const glm::ivec3 size = box.max - box.min; + const DownPush push { + .box_min = glm::ivec4(box.min, parent_side), + .box_size = glm::ivec4(size, parent_side * 2), + .mip = glm::ivec4(static_cast(mip) - 1, 0, 0, 0), + }; + cmd.pushConstants(layout, vk::ShaderStageFlagBits::eAll, 0, sizeof(push), &push); + const glm::ivec3 groups = (size + (k_group - 1)) / k_group; + cmd.dispatch(static_cast(groups.x), static_cast(groups.y), static_cast(groups.z)); + } + } + } + + // Lighting of the next frame reads these so they end the frame sampled with the frame that addresses them + if (m_inject_pipeline.isReady() && !m_inject_scene_sets.empty()) { + sync::BarrierBatch barriers; + for (uint32_t i = 0; i < level_count; ++i) { + barriers.image(m_levels[i].material_state, sync::Usage::shader_sampled); + barriers.image(m_levels[i].opacity_state, sync::Usage::shader_sampled); + for (Face& face : m_levels[i].faces) { + barriers.image(face.state, sync::Usage::shader_sampled); + } + for (Face& face : m_levels[i].ambient) { + barriers.image(face.state, sync::Usage::shader_sampled); + } + } + barriers.memory(sync::Usage::transfer_dst, sync::Usage::transfer_dst); + barriers.memory(sync::Usage::fragment_storage_read, sync::Usage::transfer_dst); + barriers.memory(sync::Usage::compute_storage_read, sync::Usage::transfer_dst); + barriers.flush(cmd); + cmd.copyBuffer(*m_frame_data[frame_index], **m_published, vk::BufferCopy(0, 0, sizeof(FrameData))); + barriers.memory(sync::Usage::transfer_dst, sync::Usage::fragment_storage_read); + barriers.memory(sync::Usage::transfer_dst, sync::Usage::compute_storage_read); + barriers.flush(cmd); + m_published_valid = true; + } + + const uint32_t debug_view = settings.clip_debug_view.load(relaxed); + if (debug_view == 0 || !source_view || !m_debug_pipeline.isReady() || !m_debug_target.isReady()) { + return source_view; + } + return recordDebug( + cmd, + frame_index, + source_view, + std::min(debug_view - 1, level_count - 1), + std::min(settings.clip_debug_mode.load(relaxed), 3u) + ); +} + +auto GiClipmapPass::recordDebug( + vk::CommandBuffer cmd, uint32_t frame_index, vk::ImageView source_view, uint32_t level_index, uint32_t mode +) -> vk::ImageView { + ZoneScoped; + Level& level = m_levels[level_index]; + sync::BarrierBatch barriers; + barriers.image(level.material_state, sync::Usage::shader_sampled); + barriers.image(level.emission_state, sync::Usage::shader_sampled); + for (Face& face : level.faces) { + barriers.image(face.state, sync::Usage::shader_sampled); + } + barriers.flush(cmd); + + const std::array wanted { + source_view, **level.material_view, **level.emission_view, **level.faces[0].sampled_view + }; + if (m_debug_bound.update(frame_index, wanted)) { + constexpr auto sampled = vk::DescriptorType::eCombinedImageSampler; + constexpr auto read = vk::ImageLayout::eShaderReadOnlyOptimal; + const vk::DescriptorSet set = *m_debug_sets[frame_index]; + DescriptorWriter writer; + writer.image(set, k_debug_source_binding, sampled, *m_point_sampler, source_view, read); + writer.image(set, k_debug_material_binding, sampled, *m_point_sampler, **level.material_view, read); + writer.image(set, k_debug_emission_binding, sampled, *m_point_sampler, **level.emission_view, read); + std::array faces; + for (uint32_t f = 0; f < k_faces; ++f) { + faces[f] = vk::DescriptorImageInfo(*m_point_sampler, **level.faces[f].sampled_view, read); + } + writer.imageArray(set, k_debug_radiance_binding, sampled, faces); + writer.flush(m_core->getDevice()); + } + + const vk::PipelineLayout layout = *m_debug_layout.getPipelineLayout(); + m_debug_target.beginScope(cmd); + cmd.bindPipeline(vk::PipelineBindPoint::eGraphics, m_debug_pipeline.getPipeline()); + cmd.bindDescriptorSets( + vk::PipelineBindPoint::eGraphics, layout, 0, std::array {*m_debug_sets[frame_index]}, {} + ); + const std::array push {level_index, mode}; + cmd.pushConstants(layout, vk::ShaderStageFlagBits::eAll, 0, sizeof(push), push.data()); + cmd.draw(3, 1, 0, 0); + m_debug_target.endScope(cmd); + return m_debug_target.view(); +} + +} diff --git a/engine/src/toast/renderer/passes/lighting/gi_clipmap_pass.hpp b/engine/src/toast/renderer/passes/lighting/gi_clipmap_pass.hpp new file mode 100644 index 000000000..b6e70d1bd --- /dev/null +++ b/engine/src/toast/renderer/passes/lighting/gi_clipmap_pass.hpp @@ -0,0 +1,185 @@ +/// @file gi_clipmap_pass.hpp +/// @author dario +/// @date 10/11/2026 + +#pragma once + +#include "toast/renderer/core/descriptor_cache.hpp" +#include "toast/renderer/core/gpu_sync.hpp" +#include "toast/renderer/core/vulkan_common.hpp" +#include "toast/renderer/lighting/gi_dirty_boxes.hpp" +#include "toast/renderer/passes/post_process_pass_base.hpp" +#include "toast/renderer/resources/post_process_target.hpp" +#include "toast/renderer/resources/scene_descriptor_set.hpp" +#include "toast/renderer/shaders/shader_layout.hpp" +#include "toast/renderer/shaders/vulkan_pipeline.hpp" + +#include +#include +#include +#include +#include +#include + +namespace renderer { +class VulkanCore; +class VoxelGpuStorage; +struct RenderFrame; + +class GiClipmapPass : public IPostProcessPass { +public: + /// Mirrors gi_clip_common kGiClipMaxLevels + static constexpr uint32_t k_max_levels = 6; + static constexpr uint32_t k_max_tail = 5; + /// Mirrors gi_clip_common kGiClipFaces + static constexpr uint32_t k_faces = 6; + + GiClipmapPass(const VulkanCore& core, vk::Format scene_format, vk::Extent2D extent); + + [[nodiscard]] + auto name() const -> std::string_view override { + return "Radiance clipmap"; + } + + auto record(vk::CommandBuffer cmd, uint32_t frame_index, vk::ImageView source_view) -> vk::ImageView override; + + void onResize(vk::Extent2D extent) override; + + /// Copy of the last recorded frame with size.z 1 and zero while the clipmap holds nothing + [[nodiscard]] + auto publishedFrame() const -> vk::Buffer { + return m_published.has_value() ? **m_published : vk::Buffer {}; + } + + /// Sampled face view at level * k_faces + face where unused levels repeat level 0 and a dummy stands in before the first fill + [[nodiscard]] + auto radianceViews() const -> std::array; + + [[nodiscard]] + auto ambientViews() const -> std::array; + + [[nodiscard]] + auto opacityViews() const -> std::array; + + /// Linear and repeat so the toroidal wrap filters across the texture edge + [[nodiscard]] + auto radianceSampler() const -> vk::Sampler { + return *m_linear_sampler; + } + +private: + /// Mirrors gi_clip_common GiClipFrame + struct FrameData { + glm::mat4 inverse_view_projection {1.0f}; + glm::vec4 camera {0.0f}; + std::array levels {}; + glm::uvec4 size {0u}; + }; + + /// Lit outgoing radiance of one face direction written as R32 bits and sampled as B10G11R11 + struct Face { + std::optional image; + std::optional storage_view; + std::optional sampled_view; + std::vector mip_views; + sync::ImageState state; + }; + + struct Level { + std::optional material; + std::optional material_view; + sync::ImageState material_state; + std::optional emission; + std::optional emission_view; + sync::ImageState emission_state; + /// xyz opacity along each axis and w 1 when anything is solid + std::optional opacity; + std::optional opacity_view; + std::optional opacity_all_view; + std::vector opacity_mip_views; + sync::ImageState opacity_state; + std::array faces; + /// Bounce irradiance over pi each face gathered from the clipmap of the frame before + std::array ambient; + glm::ivec3 origin {0}; + bool needs_full = true; + }; + + auto createPipelines(const VulkanCore& core) -> bool; + /// Waits for the device so no frame in flight still reads the old images + void createLevels(uint32_t resolution, uint32_t levels); + void markFull(); + void unpublish(vk::CommandBuffer cmd); + void gatherBodies(const RenderFrame& frame); + auto recordDebug(vk::CommandBuffer cmd, uint32_t frame_index, vk::ImageView source_view, uint32_t level, uint32_t mode) + -> vk::ImageView; + + const VulkanCore* m_core = nullptr; + vk::Format m_scene_format = vk::Format::eUndefined; + vk::Extent2D m_extent {}; + + /// gi_clip_fill with the level in set 0 and the voxel storage plus trace lists in set 1 + ShaderLayout m_fill_layout; + VulkanPipeline m_fill_pipeline; + std::vector m_fill_sets; + std::vector m_storage_sets; + DescriptorCache> m_storage_bound; + + /// gi_clip_inject with the engine scene in set 0 and the clipmap in set 1 + ShaderLayout m_inject_layout; + VulkanPipeline m_inject_pipeline; + SceneDescriptorSets m_inject_scene_sets; + std::vector m_inject_sets; + + /// gi_clip_bounce with the engine scene in set 0 for last frame's clipmap and the ambient faces in set 1 + ShaderLayout m_bounce_layout; + VulkanPipeline m_bounce_pipeline; + SceneDescriptorSets m_bounce_scene_sets; + std::vector m_bounce_sets; + VulkanPipeline m_bounce_list_pipeline; + /// A count then one record per exposed face of the level being bounced + std::optional m_bounce_list; + + ShaderLayout m_down_layout; + VulkanPipeline m_down_pipeline; + std::vector m_down_sets; + VulkanPipeline m_mip_pipeline; + std::vector m_mip_sets; + uint32_t m_tail = 0; + uint32_t m_frame = 0; + + ShaderLayout m_debug_layout; + VulkanPipeline m_debug_pipeline; + PostProcessTarget m_debug_target; + std::vector m_debug_sets; + DescriptorCache> m_debug_bound; + + vk::raii::Sampler m_point_sampler = nullptr; + vk::raii::Sampler m_linear_sampler = nullptr; + std::optional m_published; + bool m_published_valid = false; + std::optional m_dummy; + std::optional m_dummy_view; + std::vector m_frame_data; + + std::array m_levels; + uint32_t m_resolution = 0; + uint32_t m_level_count = 0; + float m_cell = 0.0f; + + /// Edits and lost history only since bodies are compared against the last fill below + GiDirtyBoxes m_dirty_boxes; + + struct Body { + glm::mat4 model {1.0f}; + /// xyz centre w radius in world space + glm::vec4 bounds {0.0f}; + }; + + static constexpr size_t k_max_body_boxes = 256; + std::unordered_map m_bodies; + std::unordered_map m_bodies_next; + std::vector m_body_boxes; +}; + +} diff --git a/engine/src/toast/renderer/passes/lighting/gi_pass.cpp b/engine/src/toast/renderer/passes/lighting/gi_pass.cpp index a1f645eb8..c5d8ef0c9 100644 --- a/engine/src/toast/renderer/passes/lighting/gi_pass.cpp +++ b/engine/src/toast/renderer/passes/lighting/gi_pass.cpp @@ -407,9 +407,9 @@ void GiPass::createBuffers(const VulkanCore& core) { m_readback.clear(); m_dirty.clear(); for (uint32_t i = 0; i < VulkanRenderer::k_frames_in_flight; ++i) { - m_dirty.push_back( - hostBuffer(core, sizeof(glm::vec4) * (1 + (2 * k_max_dirty)), storage, false, std::format("GiPass Dirty[{}]", i)) - ); + m_dirty.push_back(hostBuffer( + core, sizeof(glm::vec4) * (1 + (2 * GiDirtyBoxes::k_max_boxes)), storage, false, std::format("GiPass Dirty[{}]", i) + )); const auto& dirty_allocation = m_dirty.back().getAllocation(); std::memset(dirty_allocation.getInfo().pMappedData, 0, sizeof(glm::vec4)); dirty_allocation.flush(0, sizeof(glm::vec4)); @@ -739,92 +739,31 @@ void GiPass::recordChange(vk::CommandBuffer cmd, uint32_t frame_index, vk::Image } void GiPass::gatherDirty() { - ZoneScoped; - const auto* frame = VulkanRenderer::instance->renderingFrame(); - const auto add = [&](glm::vec3 low, glm::vec3 high) { - if (m_dirty_scratch.size() < 2 * k_max_dirty) { - m_dirty_scratch.push_back(low); - m_dirty_scratch.push_back(high); - return; - } - auto last = m_dirty_scratch.end() - 2; - last[0] = glm::min(last[0], low); - last[1] = glm::max(last[1], high); - }; - - Stats& counts = m_dirty_pending; - const float threshold = std::max(VulkanRenderer::instance->giSettings().motion_threshold.load(std::memory_order_relaxed), 0.0f); - - for (const auto& proxy : frame->voxel_instances) { - if (proxy.has_previous && proxy.model == proxy.previous_model) { - continue; - } - const glm::vec3 previous = glm::vec3(proxy.previous_model * proxy.inverse_model * glm::vec4(proxy.bounds_center, 1.0f)); - if (proxy.has_previous) { - // Centre shift plus what the change of the linear part can move a point of the bounds - const glm::mat3 change = glm::mat3(proxy.model) - glm::mat3(proxy.previous_model); - const float spread = - std::sqrt(glm::dot(change[0], change[0]) + glm::dot(change[1], change[1]) + glm::dot(change[2], change[2])); - const float scale = std::max(glm::length(glm::vec3(proxy.model[0])), 1e-6f); - const float motion = glm::distance(proxy.bounds_center, previous) + (spread * proxy.bounds_radius / scale); - counts.largest_motion = std::max(counts.largest_motion, motion); - if (motion < threshold) { - continue; - } - ++counts.moved; - } else { - ++counts.appeared; - } - const glm::vec3 radius(proxy.bounds_radius); - add(glm::min(proxy.bounds_center, previous) - radius, glm::max(proxy.bounds_center, previous) + radius); - } - - bool known = true; - if (frame->voxel_storage) { - const uint64_t generation = frame->voxel_storage->generation(); - if (generation != m_region_generation && m_region_generation != 0) { - m_model_scratch.clear(); - for (const auto& proxy : frame->voxel_instances) { - m_model_scratch.emplace(proxy.node_rid, proxy.model * glm::scale(glm::mat4(1.0f), glm::vec3(voxel::k_voxel_size))); - } - known = frame->voxel_storage->changeHistory().forEachSince(m_region_generation, [&](const VoxelRegion& region) { - const auto found = m_model_scratch.find(region.node_rid); - if (found == m_model_scratch.end()) { - return; - } - ++counts.edits; - glm::vec3 low(std::numeric_limits::max()); - glm::vec3 high(std::numeric_limits::lowest()); - for (uint32_t corner = 0; corner < 8; ++corner) { - const glm::vec3 local( - (corner & 1) != 0 ? region.max.x : region.min.x, - (corner & 2) != 0 ? region.max.y : region.min.y, - (corner & 4) != 0 ? region.max.z : region.min.z - ); - const glm::vec3 world = glm::vec3(found->second * glm::vec4(local, 1.0f)); - low = glm::min(low, world); - high = glm::max(high, world); - } - add(low, high); - }); - } - m_region_generation = generation; - } - m_dirty_known = m_dirty_known && known; + m_dirty_boxes.gather( + *VulkanRenderer::instance->renderingFrame(), + VulkanRenderer::instance->giSettings().motion_threshold.load(std::memory_order_relaxed) + ); } auto GiPass::writeDirty(uint32_t frame_index) -> bool { - m_dirty_stats[frame_index] = std::exchange(m_dirty_pending, Stats {}); - const bool known = std::exchange(m_dirty_known, true); - const auto count = static_cast(m_dirty_scratch.size() / 2); + GiDirtyBoxes::Counts counts; + const bool known = m_dirty_boxes.take(counts); + Stats& stats = m_dirty_stats[frame_index]; + stats = Stats {}; + stats.moved = counts.moved; + stats.appeared = counts.appeared; + stats.edits = counts.edits; + stats.largest_motion = counts.largest_motion; + const auto boxes = m_dirty_boxes.boxes(); + const auto count = static_cast(boxes.size() / 2); const auto& allocation = m_dirty[frame_index].getAllocation(); auto* mapped = static_cast(allocation.getInfo().pMappedData); mapped[0] = glm::vec4(static_cast(count), 0.0f, 0.0f, 0.0f); for (uint32_t i = 0; i < count * 2; ++i) { - mapped[1 + i] = glm::vec4(m_dirty_scratch[i], 0.0f); + mapped[1 + i] = glm::vec4(boxes[i], 0.0f); } allocation.flush(0, sizeof(glm::vec4) * (1 + (count * 2))); - m_dirty_scratch.clear(); + m_dirty_boxes.clear(); return known; } @@ -1066,7 +1005,8 @@ auto GiPass::record(vk::CommandBuffer cmd, uint32_t frame_index, vk::ImageView s const auto* renderer = VulkanRenderer::instance; const auto* frame = renderer->renderingFrame(); const GiSettings& settings = renderer->giSettings(); - const bool enabled = settings.enabled.load(std::memory_order_relaxed); + const bool enabled = settings.enabled.load(std::memory_order_relaxed) && + settings.backend.load(std::memory_order_relaxed) == GiSettings::k_backend_cascades; // Lighting falls back to the flat ambient once the frame it reads says no GI if (!enabled && m_published_valid) { sync::BarrierBatch barriers; diff --git a/engine/src/toast/renderer/passes/lighting/gi_pass.hpp b/engine/src/toast/renderer/passes/lighting/gi_pass.hpp index 720e2694f..8a8aadf34 100644 --- a/engine/src/toast/renderer/passes/lighting/gi_pass.hpp +++ b/engine/src/toast/renderer/passes/lighting/gi_pass.hpp @@ -7,6 +7,7 @@ #include "toast/renderer/core/descriptor_cache.hpp" #include "toast/renderer/core/gpu_sync.hpp" #include "toast/renderer/core/vulkan_common.hpp" +#include "toast/renderer/lighting/gi_dirty_boxes.hpp" #include "toast/renderer/passes/post_process_pass_base.hpp" #include "toast/renderer/resources/post_process_target.hpp" #include "toast/renderer/resources/scene_descriptor_set.hpp" @@ -140,8 +141,6 @@ class GiPass : public IPostProcessPass { static constexpr uint32_t k_counter_pixel_hits = 39; /// Hits queued by point rays static constexpr uint32_t k_counter_point_hits = 40; - /// Mirrors gi_probes gDirty and past it every extra region grows the last box - static constexpr uint32_t k_max_dirty = 64; struct Cascade { uint32_t table_offset = 0; @@ -281,11 +280,8 @@ class GiPass : public IPostProcessPass { std::vector m_dirty; std::vector m_dirty_stats; - std::vector m_dirty_scratch; - Stats m_dirty_pending; - bool m_dirty_known = true; - std::unordered_map m_model_scratch; - uint64_t m_region_generation = 0; + /// gi_probes gDirty holds GiDirtyBoxes::k_max_boxes + GiDirtyBoxes m_dirty_boxes; uint32_t m_skipped = 0; Quality m_quality; /// Kept in shader read layout between frames diff --git a/engine/src/toast/renderer/resources/scene_descriptor_set.cpp b/engine/src/toast/renderer/resources/scene_descriptor_set.cpp index fe86e68a7..6fe11042e 100644 --- a/engine/src/toast/renderer/resources/scene_descriptor_set.cpp +++ b/engine/src/toast/renderer/resources/scene_descriptor_set.cpp @@ -3,6 +3,7 @@ #include "toast/renderer/core/descriptor_writer.hpp" #include "toast/renderer/passes/lighting/cluster_lighting_pass.hpp" #include "toast/renderer/passes/lighting/environment_pass.hpp" +#include "toast/renderer/passes/lighting/gi_clipmap_pass.hpp" #include "toast/renderer/passes/lighting/gi_pass.hpp" #include "toast/renderer/passes/lighting/reflection_probe_pass.hpp" #include "toast/renderer/passes/lighting/shadow_pass.hpp" @@ -27,6 +28,11 @@ void SceneDescriptorSets::create( m_scene_binding.reset(); m_bound_tlas.resize(VulkanRenderer::k_frames_in_flight); m_detail_binding.reset(); + m_clip_frame_binding.reset(); + m_clip_radiance_binding.reset(); + m_clip_material_binding.reset(); + m_clip_ambient_binding.reset(); + m_bound_clip.resize(VulkanRenderer::k_frames_in_flight); m_bound_detail.resize(VulkanRenderer::k_frames_in_flight); for (uint32_t i = 0; i < VulkanRenderer::k_frames_in_flight; ++i) { @@ -73,6 +79,24 @@ void SceneDescriptorSets::create( continue; } + // Written by updateTlas since the clipmap pass and its levels may not exist yet + if (binding.name == "gGiClipFrame") { + m_clip_frame_binding = binding.binding; + continue; + } + if (binding.name == "gGiClipRadiance") { + m_clip_radiance_binding = binding.binding; + continue; + } + if (binding.name == "gGiClipOpacity") { + m_clip_material_binding = binding.binding; + continue; + } + if (binding.name == "gGiClipAmbient") { + m_clip_ambient_binding = binding.binding; + continue; + } + if (binding.name == "gVoxelDetail") { const vk::ImageView detail = VulkanRenderer::instance->voxelDetailView(); writer.image( @@ -241,6 +265,43 @@ void SceneDescriptorSets::updateTlas(uint32_t frame_index) { writer.flush(m_core->getDevice()); } } + const auto* clipmap = VulkanRenderer::instance->giClipmapPass(); + const bool wants_clip = m_clip_frame_binding.has_value() || m_clip_radiance_binding.has_value() || + m_clip_material_binding.has_value() || m_clip_ambient_binding.has_value(); + if (m_core != nullptr && clipmap != nullptr && wants_clip && frame_index < m_bound_clip.size()) { + const auto radiance = clipmap->radianceViews(); + const auto material = clipmap->opacityViews(); + if (m_bound_clip.update(frame_index, std::array {radiance[0], material[0]})) { + constexpr auto sampled = vk::DescriptorType::eCombinedImageSampler; + constexpr auto read = vk::ImageLayout::eShaderReadOnlyOptimal; + DescriptorWriter writer; + if (m_clip_frame_binding.has_value()) { + writer.buffer(*m_sets[frame_index], *m_clip_frame_binding, vk::DescriptorType::eStorageBuffer, clipmap->publishedFrame()); + } + if (m_clip_radiance_binding.has_value()) { + std::vector infos; + for (const vk::ImageView view : radiance) { + infos.emplace_back(clipmap->radianceSampler(), view, read); + } + writer.imageArray(*m_sets[frame_index], *m_clip_radiance_binding, sampled, infos); + } + if (m_clip_material_binding.has_value()) { + std::vector infos; + for (const vk::ImageView view : material) { + infos.emplace_back(clipmap->radianceSampler(), view, read); + } + writer.imageArray(*m_sets[frame_index], *m_clip_material_binding, sampled, infos); + } + if (m_clip_ambient_binding.has_value()) { + std::vector infos; + for (const vk::ImageView view : clipmap->ambientViews()) { + infos.emplace_back(clipmap->radianceSampler(), view, read); + } + writer.imageArray(*m_sets[frame_index], *m_clip_ambient_binding, sampled, infos); + } + writer.flush(m_core->getDevice()); + } + } if (m_core == nullptr || !m_scene_binding.has_value() || frame_index >= m_bound_tlas.size()) { return; } diff --git a/engine/src/toast/renderer/resources/scene_descriptor_set.hpp b/engine/src/toast/renderer/resources/scene_descriptor_set.hpp index bf1f20a30..1de437f81 100644 --- a/engine/src/toast/renderer/resources/scene_descriptor_set.hpp +++ b/engine/src/toast/renderer/resources/scene_descriptor_set.hpp @@ -10,6 +10,7 @@ #include "toast/renderer/core/vulkan_common.hpp" #include "toast/renderer/shaders/shader_reflection.hpp" +#include #include #include #include @@ -51,6 +52,12 @@ class SceneDescriptorSets { std::optional m_detail_binding; DescriptorCache m_bound_detail; + std::optional m_clip_frame_binding; + std::optional m_clip_radiance_binding; + std::optional m_clip_material_binding; + std::optional m_clip_ambient_binding; + DescriptorCache> m_bound_clip; + /// Handle plus generation since a recreated structure can reuse a destroyed handle value DescriptorCache> m_bound_tlas; }; diff --git a/engine/src/toast/renderer/settings/gi_settings.hpp b/engine/src/toast/renderer/settings/gi_settings.hpp index 7d585b759..e12ea465a 100644 --- a/engine/src/toast/renderer/settings/gi_settings.hpp +++ b/engine/src/toast/renderer/settings/gi_settings.hpp @@ -43,6 +43,18 @@ struct GiSettings { std::atomic debug_view {0}; /// Mirrors gi_debug.slang kGiDebug with 0 cells 1 interval radiance 2 coverage 3 irradiance 4 history depth 5 change std::atomic debug_mode {0}; + + static constexpr uint32_t k_backend_cascades = 0; + static constexpr uint32_t k_backend_clipmap = 1; + std::atomic backend {k_backend_cascades}; + /// Meters per level 0 cell + std::atomic clip_cell {0.2f}; + std::atomic clip_resolution {128}; + std::atomic clip_levels {4}; + /// 0 off and otherwise 1 + the level drawn + std::atomic clip_debug_view {0}; + /// 0 albedo 1 emission 2 opacity 3 radiance + std::atomic clip_debug_mode {0}; }; } diff --git a/engine/src/toast/renderer/settings/renderer_settings.cpp b/engine/src/toast/renderer/settings/renderer_settings.cpp index cc00b371a..b03bc625a 100644 --- a/engine/src/toast/renderer/settings/renderer_settings.cpp +++ b/engine/src/toast/renderer/settings/renderer_settings.cpp @@ -1454,6 +1454,91 @@ void registerGi(VulkanRenderer& renderer) { .onChange([&gi](int64_t v) { gi.debug_mode.store(static_cast(std::clamp(v, 0, 5)), std::memory_order_relaxed); }); + + toast::settings::declareInt( + "renderer.gi.backend", + 0, + { + .label = "Backend", + .category = "Global illumination", + .description = "Radiance clipmap is in development and only fills its voxel clipmap so far, lighting gets no GI " + "from it yet", + .options = {"Radiance cascades", "Radiance clipmap"} + } + ) + .onChange([&gi](int64_t v) { + gi.backend.store(static_cast(std::clamp(v, 0, 1)), std::memory_order_relaxed); + }); + + toast::settings::declareFloat( + "renderer.gi.clip_cell", + 0.2, + {.label = "Clipmap cell", + .category = "Global illumination", + .description = "Meters per cell of clipmap level 0. Every level doubles it", + .min = 0.1, + .max = 1.0, + .step = 0.1} + ) + .onChange([&gi](double v) { + gi.clip_cell.store(std::clamp(static_cast(v), 0.1f, 1.0f), std::memory_order_relaxed); + }); + + toast::settings::declareInt( + "renderer.gi.clip_resolution", + 1, + { + .label = "Clipmap resolution", + .category = "Global illumination", + .description = "Cells per side of every clipmap level. Custom quality only", + .options = {"64", "128", "192"} + } + ) + .onChange([&gi](int64_t v) { + constexpr std::array k_resolutions {64, 128, 192}; + gi.clip_resolution.store(k_resolutions[static_cast(std::clamp(v, 0, 2))], std::memory_order_relaxed); + }); + + toast::settings::declareInt( + "renderer.gi.clip_levels", + 4, + {.label = "Clipmap levels", + .category = "Global illumination", + .description = "Clipmap levels around the camera. Custom quality only", + .min = 1.0, + .max = 6.0} + ) + .onChange([&gi](int64_t v) { + gi.clip_levels.store(static_cast(std::clamp(v, 1, 6)), std::memory_order_relaxed); + }); + + toast::settings::declareInt( + "renderer.gi.clip_debug_view", + 0, + { + .label = "Clipmap view", + .category = "Global illumination", + .description = "Draws the cells of one clipmap level in place of the scene", + .options = {"Off", "Level 0", "Level 1", "Level 2", "Level 3", "Level 4", "Level 5"} + } + ) + .onChange([&gi](int64_t v) { + gi.clip_debug_view.store(static_cast(std::clamp(v, 0, 6)), std::memory_order_relaxed); + }); + + toast::settings::declareInt( + "renderer.gi.clip_debug_mode", + 0, + { + .label = "Clipmap view shows", + .category = "Global illumination", + .description = "What the clipmap view draws per cell", + .options = {"Albedo", "Emission", "Opacity", "Radiance"} + } + ) + .onChange([&gi](int64_t v) { + gi.clip_debug_mode.store(static_cast(std::clamp(v, 0, 3)), std::memory_order_relaxed); + }); } auto presetDrivenValue(std::string_view key) -> std::optional { diff --git a/engine/src/toast/renderer/vulkan_renderer.hpp b/engine/src/toast/renderer/vulkan_renderer.hpp index 5e97177ab..591516c61 100644 --- a/engine/src/toast/renderer/vulkan_renderer.hpp +++ b/engine/src/toast/renderer/vulkan_renderer.hpp @@ -93,6 +93,7 @@ class SkinningPass; class VoxelPass; class DebrisPass; class GiPass; +class GiClipmapPass; class TracedSpecularPass; class TaaPass; class RayTracingScene; @@ -345,6 +346,11 @@ class VulkanRenderer { return m_voxel_face_normal.view.has_value() ? **m_voxel_face_normal.view : vk::ImageView {}; } + [[nodiscard]] + auto getVoxelGiView() const noexcept -> vk::ImageView { + return m_voxel_gi.view.has_value() ? **m_voxel_gi.view : vk::ImageView {}; + } + /// Marched and sampled diffuse over albedo before denoising [[nodiscard]] auto getVoxelNoisyDiffuseView() const noexcept -> vk::ImageView { @@ -889,6 +895,13 @@ class VulkanRenderer { void setGiPass(GiPass* pass) noexcept { m_gi_pass = pass; } + void setGiClipmapPass(GiClipmapPass* pass) noexcept { m_gi_clipmap_pass = pass; } + + [[nodiscard]] + auto giClipmapPass() const noexcept -> GiClipmapPass* { + return m_gi_clipmap_pass; + } + /// Still registered with addPostProcessPass so it runs in the post chain void setTracedSpecularPass(TracedSpecularPass* pass) noexcept { m_traced_specular_pass = pass; } @@ -1460,6 +1473,7 @@ class VulkanRenderer { DebrisPass* m_debris_pass = nullptr; GiPass* m_gi_pass = nullptr; + GiClipmapPass* m_gi_clipmap_pass = nullptr; bool m_glass_backdrop_captured = false; mutable std::mutex m_detail_mutex; @@ -1503,6 +1517,8 @@ class VulkanRenderer { SceneColorResources m_voxel_face_normal; SceneColorResources m_voxel_detail_normal; SceneColorResources m_voxel_noisy_diffuse; + /// Half the render extent + SceneColorResources m_voxel_gi; SceneColorResources m_voxel_noisy_specular; /// The voxel lighting writes the parity one and reads the other std::array m_voxel_reservoirs; diff --git a/engine/src/toast/renderer/vulkan_renderer_record.cpp b/engine/src/toast/renderer/vulkan_renderer_record.cpp index ae0f3329f..3228fb38a 100644 --- a/engine/src/toast/renderer/vulkan_renderer_record.cpp +++ b/engine/src/toast/renderer/vulkan_renderer_record.cpp @@ -261,7 +261,10 @@ void VulkanRenderer::updateVoxelTraceScene() { m_trace_volumes.clear(); const VoxelGpuStorage* storage = render_frame->voxel_storage.get(); if (storage != nullptr && storage->isReady()) { - const auto cap = std::min(voxelShadowInstances(), VoxelTraceScene::k_max_volumes); + // The clipmap fill reads this list so a capped volume would vanish from GI + const bool clipmap = m_gi_settings.backend.load(std::memory_order_relaxed) == GiSettings::k_backend_clipmap; + const auto cap = + clipmap ? VoxelTraceScene::k_max_volumes : std::min(voxelShadowInstances(), VoxelTraceScene::k_max_volumes); // Drawn volumes first so the cap drops off screen ones for (const bool visible : {true, false}) { for (const VoxelVolumeProxy& proxy : render_frame->voxel_instances) { @@ -425,6 +428,7 @@ void VulkanRenderer::recordMeshScene( } if (m_voxel_pass != nullptr) { m_voxel_pass->setBackdropCaptured(refract); + m_voxel_pass->setBackdropDepthValid(m_glass_backdrop_captured); } { @@ -671,6 +675,40 @@ auto VulkanRenderer::recordVoxelScopes( barriers.image(m_scene_motion.state, sync::Usage::fragment_sampled); barriers.flush(cmd); + if (m_voxel_gi.view.has_value()) { + if (m_voxel_pass->giGatherActive()) { + barriers.image(m_voxel_gi.state, sync::Usage::color_attachment); + barriers.flush(cmd); + const vk::Rect2D half { + { 0, 0}, + {(scissor.extent.width + 1) / 2, (scissor.extent.height + 1) / 2} + }; + const std::array gather_attachments {attachment(m_voxel_gi, vk::AttachmentLoadOp::eDontCare, clear_zero)}; + vk::RenderingInfo gather_info {}; + gather_info.renderArea = half; + gather_info.layerCount = 1; + gather_info.colorAttachmentCount = static_cast(gather_attachments.size()); + gather_info.pColorAttachments = gather_attachments.data(); + + cmd.beginRendering(gather_info); + cmd.setViewport( + 0, + std::array { + vk::Viewport {0.0f, 0.0f, static_cast(half.extent.width), static_cast(half.extent.height), 0.0f, 1.0f} + } + ); + cmd.setScissor(0, std::array {half}); + { + TracyVkZone(m_tracy_vk_ctx, cmd, "VoxelGiGather"); + const GpuScope scope(m_gpu_timer.get(), m_current_frame, cmd, "Voxel GI gather"); + m_voxel_pass->recordGiGather(cmd, m_current_frame, scissor.extent); + } + cmd.endRendering(); + } + barriers.image(m_voxel_gi.state, sync::Usage::fragment_sampled); + barriers.flush(cmd); + } + // A frame without voxel lighting in between or a probe capture leaves reservoirs another view wrote const auto* lit_frame = renderingFrame(); const uint64_t sequence = lit_frame != nullptr ? lit_frame->sequence : 0; @@ -1532,7 +1570,7 @@ auto VulkanRenderer::drawFrame(RenderFrame& frame_data) -> bool { return false; } if (acquired.result != vk::Result::eSuccess && acquired.result != vk::Result::eSuboptimalKHR) { - TOAST_CRITICAL("Render", "Toast Engine Error: Failed to acquire the next output image!"); + TOAST_CRITICAL("Render", "Failed to acquire the next output image!"); } const uint32_t image_index = acquired.value; diff --git a/engine/src/toast/renderer/vulkan_renderer_resources.cpp b/engine/src/toast/renderer/vulkan_renderer_resources.cpp index 0773722a7..f108b1399 100644 --- a/engine/src/toast/renderer/vulkan_renderer_resources.cpp +++ b/engine/src/toast/renderer/vulkan_renderer_resources.cpp @@ -298,13 +298,16 @@ void VulkanRenderer::createSceneColorResources() { TOAST_CRITICAL("Render", "Toast Engine Error: VulkanRenderer requires a non-zero output extent for the scene target!"); } - const auto create = [&]( - SceneColorResources& target, vk::Format format, std::string_view label, vk::ImageUsageFlags usage = {} - ) { + const auto create = [&](SceneColorResources& target, + vk::Format format, + std::string_view label, + vk::ImageUsageFlags usage = {}, + uint32_t divide = 1) { target.view.reset(); target.image.reset(); - const auto image_ci = colorTargetImageInfo(extent, format, usage); + const vk::Extent2D size {(extent.width + divide - 1) / divide, (extent.height + divide - 1) / divide}; + const auto image_ci = colorTargetImageInfo(size, format, usage); vma::AllocationCreateInfo allocation_ci {}; allocation_ci.usage = vma::MemoryUsage::eAutoPreferDevice; @@ -337,6 +340,7 @@ void VulkanRenderer::createSceneColorResources() { create(m_voxel_detail_normal, k_voxel_face_normal_format, "VoxelDetailNormal"); create(m_voxel_noisy_diffuse, k_voxel_noisy_format, "VoxelNoisyDiffuse"); create(m_voxel_noisy_specular, k_voxel_noisy_format, "VoxelNoisySpecular"); + create(m_voxel_gi, k_voxel_gi_format, "VoxelGi", {}, 2); create(m_voxel_reservoirs[0], k_voxel_reservoir_format, "VoxelReservoirs0"); create(m_voxel_reservoirs[1], k_voxel_reservoir_format, "VoxelReservoirs1"); create(m_voxel_candidate_reservoirs, k_voxel_reservoir_format, "VoxelCandidateReservoirs"); diff --git a/engine/src/toast/renderer/vulkan_renderer_scene.cpp b/engine/src/toast/renderer/vulkan_renderer_scene.cpp index 2c337b91b..0213fc6b7 100644 --- a/engine/src/toast/renderer/vulkan_renderer_scene.cpp +++ b/engine/src/toast/renderer/vulkan_renderer_scene.cpp @@ -42,7 +42,6 @@ #include #include #include -#include #include #include #include @@ -53,6 +52,7 @@ #include #include #include +#include #include #include @@ -158,45 +158,54 @@ auto pickSkin(const toast::MeshNode& node) -> const assets::Skin* { return nullptr; } -auto findAncestorAnimationPlayer(toast::Node& node) -> toast::AnimationPlayer* { +auto findAncestorSkeleton(toast::Node& node) -> toast::SkeletalNode* { toast::Box current = node.parent(); while (current.exists()) { - if (auto player = current.as(); player.exists()) { - return &*player; + if (auto skeletal = current.as(); skeletal.exists()) { + return &*skeletal; } current = current->parent(); } return nullptr; } -using SkinPoseKey = std::pair; +using SkinPoseKey = std::pair; using SkinPoseCache = std::map>; -void resolveSkinning( +/// @returns the posing skeleton when this call added its pose to the frame +auto resolveSkinning( toast::MeshNode& node, RenderFrame& frame, uint32_t& joint_offset, uint32_t& joint_count, bool& pool_exhausted_warned, SkinPoseCache& pose_cache -) { +) -> toast::SkeletalNode* { const assets::Skin* skin = pickSkin(node); if (skin == nullptr) { - return; + return nullptr; } - toast::AnimationPlayer* player = findAncestorAnimationPlayer(node); - if (player == nullptr) { - return; + toast::SkeletalNode* skeletal = findAncestorSkeleton(node); + if (skeletal == nullptr) { + return nullptr; } - if (const auto cached = pose_cache.find({player, skin}); cached != pose_cache.end()) { + if (const auto cached = pose_cache.find({skeletal, skin}); cached != pose_cache.end()) { joint_offset = cached->second.first; joint_count = cached->second.second; - return; + return nullptr; } - const auto joint_world_transforms = player->jointWorldTransforms(*skin); + const auto bones = skeletal->skinBones(*skin); + skeletal->syncTransform(); + const glm::mat4& skeletal_world = skeletal->getWorldTransform(); + std::vector joint_world_transforms(skin->joints.size(), skeletal_world); + for (size_t i = 0; i < bones.size() && i < joint_world_transforms.size(); ++i) { + if (bones[i] >= 0) { + joint_world_transforms[i] = skeletal_world * skeletal->boneModelTransform(bones[i]); + } + } const auto joint_matrices = skin->jointMatrices(joint_world_transforms); if (joint_matrices.empty()) { - return; + return nullptr; } if (frame.joint_matrices.size() + joint_matrices.size() > k_max_joint_matrices) { @@ -208,13 +217,14 @@ void resolveSkinning( k_max_joint_matrices ); } - return; + return nullptr; } joint_offset = static_cast(frame.joint_matrices.size()); joint_count = static_cast(joint_matrices.size()); frame.joint_matrices.insert(frame.joint_matrices.end(), joint_matrices.begin(), joint_matrices.end()); - pose_cache.emplace(SkinPoseKey {player, skin}, std::pair {joint_offset, joint_count}); + pose_cache.emplace(SkinPoseKey {skeletal, skin}, std::pair {joint_offset, joint_count}); + return skeletal; } /// Float in [1 2) whose mantissa hashes the light so ReSTIR finds it after rebuilds @@ -677,7 +687,11 @@ void VulkanRenderer::gatherMeshProxies(RenderFrame& frame) { uint32_t joint_offset = 0; uint32_t joint_count = 0; if (gpu_mesh.isSkinned()) { - resolveSkinning(*node, frame, joint_offset, joint_count, m_joint_matrix_pool_exhausted_warned, skin_pose_cache); + toast::SkeletalNode* posed = + resolveSkinning(*node, frame, joint_offset, joint_count, m_joint_matrix_pool_exhausted_warned, skin_pose_cache); + if (posed != nullptr && !posed->alwaysDrawsBones() && (isOutlined(posed->rid()) || isOutlined(node->rid()))) { + posed->drawBones(); + } } const glm::vec4 local_sphere = mesh_handle->boundingSphere(); diff --git a/engine/src/toast/voxel/assets/voxel_palette.cpp b/engine/src/toast/voxel/assets/voxel_palette.cpp index a8586384c..c9a910350 100644 --- a/engine/src/toast/voxel/assets/voxel_palette.cpp +++ b/engine/src/toast/voxel/assets/voxel_palette.cpp @@ -228,7 +228,7 @@ auto VoxelPalette::parseToml(const toml::table& table) -> Parsed { out.alpha = unit_or("alpha", 255); if (const toml::node* ior = entry->get("ior")) { - const std::optional value = ior->is_number() ? ior->value() : std::nullopt; + const std::optional value = ior->is_number() ? ior->value() : std::nullopt; if (!value || !(*value >= 1.0 && *value <= voxel::k_max_ior)) { throw fail(std::format("ior must be a number from 1 to {:.2f}", voxel::k_max_ior)); } diff --git a/engine/src/toast/voxel/nodes/voxel_node.cpp b/engine/src/toast/voxel/nodes/voxel_node.cpp index 4967d11cd..97519748b 100644 --- a/engine/src/toast/voxel/nodes/voxel_node.cpp +++ b/engine/src/toast/voxel/nodes/voxel_node.cpp @@ -10,6 +10,7 @@ #include #include #include +#include namespace toast { @@ -885,14 +886,19 @@ void VoxelNode::updateInspectorMessages() { }; static const toast::NodeMessage palette_message { .severity = toast::NodeMessage::warning, - .id = 1, + .id = 2, .text = "Voxel node has no valid palette", }; static const toast::NodeMessage material_message { .severity = toast::NodeMessage::warning, - .id = 1, + .id = 3, .text = "Voxel node has no valid physical material library", }; + static const toast::NodeMessage bone_message { + .severity = toast::NodeMessage::warning, + .id = 4, + .text = "Under a BoneAttachment use Kinematic with Break Anchor Largest Piece so physics follows the bone", + }; if (resolvedModel() != nullptr) { removeInspectorMessage(model_message); } else { @@ -908,6 +914,16 @@ void VoxelNode::updateInspectorMessages() { } else { addInspectorMessage(material_message); } + + bool on_bone = false; + for (toast::Box cursor = parent(); cursor.exists() && !on_bone; cursor = cursor->parent()) { + on_bone = cursor.as().exists(); + } + if (on_bone && (simulation_type != SimulationType::kinematic || break_anchor != BreakAnchor::largest_piece)) { + addInspectorMessage(bone_message); + } else { + removeInspectorMessage(bone_message); + } } void VoxelNode::onReflectedFieldChanged(std::string_view field_name) { diff --git a/engine/src/toast/voxel/nodes/voxel_node.hpp b/engine/src/toast/voxel/nodes/voxel_node.hpp index 7e6b0a989..a46947fdc 100644 --- a/engine/src/toast/voxel/nodes/voxel_node.hpp +++ b/engine/src/toast/voxel/nodes/voxel_node.hpp @@ -60,6 +60,12 @@ enum class SimulationType : uint8_t { dynamic = 2, ///< Fully simulated }; +/// Which voxels stay on a static or kinematic node when it breaks apart +enum class BreakAnchor : uint8_t { + bottom_face = 0, ///< Voxels connected to the model bottom face + largest_piece = 1, ///< The biggest connected piece, for props carried by a BoneAttachment +}; + struct VoxelPart { uint64_t key = 0; std::unique_ptr volume; @@ -565,6 +571,10 @@ class [[ToastNode, Icon("BoxMesh")]] TOAST_API VoxelNode : public Voxel { [[Reflect, Name("Simulation Type"), Enum("Static", "Kinematic", "Dynamic")]] SimulationType simulation_type = SimulationType::dynamic; + /// Ignored by dynamic nodes, they always keep the largest piece + [[Reflect, Name("Break Anchor"), Enum("Bottom Face", "Largest Piece")]] + BreakAnchor break_anchor = BreakAnchor::bottom_face; + [[Reflect, ReadOnly, Unit("kg")]] float mass = 0.0f; diff --git a/engine/src/toast/world/animation_player.cpp b/engine/src/toast/world/animation_player.cpp index 45457f24d..0ed92d74b 100644 --- a/engine/src/toast/world/animation_player.cpp +++ b/engine/src/toast/world/animation_player.cpp @@ -1,53 +1,57 @@ #include "animation_player.hpp" -#include "mesh_node.hpp" - namespace toast { +auto resolveClip(const assets::Animation& animation, std::string_view clip_name, std::string_view owner) + -> const assets::AnimationClip* { + // The importer writes one clip per .tanim so the Clip field is normally blank + if (clip_name.empty()) { + if (animation.clips().empty()) { + TOAST_WARN("Animation", "'{}': assigned animation asset has no clips", owner); + return nullptr; + } + return &animation.clips().front(); + } + const assets::AnimationClip* clip = animation.findClip(clip_name); + if (clip == nullptr) { + TOAST_WARN("Animation", "'{}': animation asset has no clip named '{}'", owner, clip_name); + } + return clip; +} + auto AnimationPlayer::play(std::string_view clip_name) -> bool { if (!m_animation.hasValue()) { TOAST_WARN("Animation", "AnimationPlayer '{}' has no animation asset assigned", name()); return false; } - // An empty name means "whatever this asset holds". The glTF importer writes one clip per .tanim, so the - // Clip field is normally left blank in the inspector and swapping animations is a matter of assigning a - // different asset - naming the clip is only needed for a hand-authored multi-clip file - const assets::AnimationClip* clip = nullptr; - if (clip_name.empty()) { - if (!m_animation->clips().empty()) { - clip = &m_animation->clips().front(); - } - } else { - clip = m_animation->findClip(clip_name); - } + const assets::AnimationClip* clip = resolveClip(*m_animation, clip_name, name()); if (clip == nullptr) { - if (clip_name.empty()) { - TOAST_WARN("Animation", "AnimationPlayer '{}': assigned animation asset has no clips", name()); - } else { - TOAST_WARN("Animation", "Animation asset has no clip named '{}'", clip_name); - } return false; } // A new clip targets a potentially different set of nodes, so the resolved-node memo is invalid - if (clip != m_active_clip) { + if (clip != m_playback.clip) { m_node_cache.clear(); } - m_active_clip = clip; - // Resolved name, not the requested one: an empty request has to leave the inspector showing what is - // actually playing rather than staying blank + m_playback.start(clip); m_clip_name = clip->name; - m_time = 0.0f; - m_playing = true; - m_paused = false; return true; } +auto AnimationPlayer::inspectorOptions(std::string_view field_name) -> std::vector { + std::vector options; + if (field_name == "m_clip_name" && m_animation.hasValue()) { + for (const auto& clip : m_animation->clips()) { + options.push_back(clip.name); + } + } + return options; +} + void AnimationPlayer::stop() { - m_playing = false; - m_time = 0.0f; + m_playback.stop(); } void AnimationPlayer::begin() { @@ -64,12 +68,6 @@ auto AnimationPlayer::resolveNode(const std::string& node_name) -> Node3D* { return it->second.exists() ? &*it->second : nullptr; } - // Descendants only, deliberately never this player itself. Node::find() searches from its origin - // inclusive, and the importer wraps a whole glTF scene in an AnimationPlayer named after that scene - - // which for a single-root file is the very name that root node also carries. Searching from `this` - // matches the wrapper and stops, so a transform track would pose the wrapper instead of the real node. A - // clip target always names an authored node, never the engine-inserted player, so skipping self is the - // correct rule in general rather than a workaround for that one collision Box found; for (const auto& child : children()) { Box cursor = child; @@ -82,32 +80,17 @@ auto AnimationPlayer::resolveNode(const std::string& node_name) -> Node3D* { } } - // Cached even when the lookup failed (an empty Box), so a clip targeting a node this tree doesn't have - // costs one subtree walk rather than one per frame forever m_node_cache.emplace(node_name, found); return found.exists() ? &*found : nullptr; } void AnimationPlayer::tick() { ZoneScoped; - if (!m_playing || m_paused || m_active_clip == nullptr) { + if (!m_playback.advance(static_cast(Time::delta()), m_speed, m_loop)) { return; } - m_time += static_cast(Time::delta()) * m_speed; - - if (m_active_clip->duration > 0.0f && m_time >= m_active_clip->duration) { - if (m_loop) { - m_time = m_active_clip->wrap(m_time); - } else { - // Hold the final pose rather than snapping back to bind, which is what a one-shot should leave - // behind - m_time = m_active_clip->duration; - m_playing = false; - } - } - - for (const auto& [node_name, pose] : m_active_clip->sample(m_time)) { + for (const auto& [node_name, pose] : m_playback.clip->sample(m_playback.time)) { Node3D* target = resolveNode(node_name); if (target == nullptr) { continue; @@ -115,26 +98,8 @@ void AnimationPlayer::tick() { target->position = pose.translation; target->rotation = pose.rotation; - // if (pose.has_scale) { - // target->scale = pose.scale; - // } target->syncTransform(); } } -auto AnimationPlayer::jointWorldTransforms(const assets::Skin& skin) -> std::vector { - std::vector transforms(skin.joints.size(), glm::mat4(1.0f)); - - for (size_t i = 0; i < skin.joints.size(); ++i) { - Node3D* joint = resolveNode(skin.joints[i]); - if (joint == nullptr) { - continue; // leaves identity, keeping later joint indices aligned - } - joint->syncTransform(); - transforms[i] = joint->getWorldTransform(); - } - - return transforms; -} - } diff --git a/engine/src/toast/world/animation_player.hpp b/engine/src/toast/world/animation_player.hpp index 34cd10e7d..b44c5ba78 100644 --- a/engine/src/toast/world/animation_player.hpp +++ b/engine/src/toast/world/animation_player.hpp @@ -6,6 +6,7 @@ */ #pragma once +#include "clip_playback.hpp" #include "node_3d.hpp" #include @@ -18,6 +19,8 @@ namespace toast { /** * @brief Drives node transforms from an Animation clip * + * For node trees without bones, skinned rigs use SkeletalNode + * * Targets are resolved by name against this player's descendants, never itself - so the same clip drives * several prefab instances independently * @@ -40,29 +43,21 @@ class [[ToastNode, Icon("Animation")]] TOAST_API AnimationPlayer : public Node3D [[Reflect]] void pause(bool value) { - m_paused = value; + m_playback.paused = value; } [[nodiscard]] auto isPlaying() const noexcept -> bool { - return m_playing; + return m_playback.playing; } /// @returns seconds into the current clip [[nodiscard]] auto time() const noexcept -> float { - return m_time; + return m_playback.time; } - void time(float seconds) noexcept { m_time = seconds; } - - /** - * @brief World transforms of a skin's joints, in joint-index order - * - * A joint the tree does not contain contributes an identity rather than shifting every later index - */ - [[nodiscard]] - auto jointWorldTransforms(const assets::Skin& skin) -> std::vector; + void time(float seconds) noexcept { m_playback.time = seconds; } /** * @brief Advances playback by one frame and writes the sampled pose onto its target nodes @@ -74,6 +69,7 @@ class [[ToastNode, Icon("Animation")]] TOAST_API AnimationPlayer : public Node3D private: void begin(); + auto inspectorOptions(std::string_view field_name) -> std::vector override; /// @brief Finds a node by name among this player's descendants, memoised for the lifetime of the clip auto resolveNode(const std::string& name) -> Node3D*; @@ -81,7 +77,7 @@ class [[ToastNode, Icon("Animation")]] TOAST_API AnimationPlayer : public Node3D [[Reflect, Name("Animation")]] assets::Handle m_animation; - [[Reflect, Name("Clip")]] + [[Reflect, Name("Clip"), Options]] std::string m_clip_name; [[Reflect, Name("Play On Begin")]] @@ -93,11 +89,7 @@ class [[ToastNode, Icon("Animation")]] TOAST_API AnimationPlayer : public Node3D [[Reflect, Unit("x"), Range(0.0, 10.0)]] float m_speed = 1.0f; - bool m_playing = false; - bool m_paused = false; - float m_time = 0.0f; - - const assets::AnimationClip* m_active_clip = nullptr; + ClipPlayback m_playback; // Name lookups walk the subtree, which is far too expensive to redo per track per frame. Cleared // whenever the clip changes, since a different clip may target an entirely different set of nodes diff --git a/engine/src/toast/world/bone_attachment.cpp b/engine/src/toast/world/bone_attachment.cpp new file mode 100644 index 000000000..035a0aede --- /dev/null +++ b/engine/src/toast/world/bone_attachment.cpp @@ -0,0 +1,49 @@ +#include "bone_attachment.hpp" + +#include "skeletal_node.hpp" + +namespace toast { + +auto BoneAttachment::inspectorOptions(std::string_view field_name) -> std::vector { + std::vector options; + auto skeletal = parent().as(); + if (field_name != "m_bone" || !skeletal.exists()) { + return options; + } + if (const assets::Skeleton* skeleton = skeletal->skeleton(); skeleton != nullptr) { + options.reserve(skeleton->bones.size()); + for (const auto& bone : skeleton->bones) { + options.push_back(bone.name); + } + } + return options; +} + +void BoneAttachment::updateInspectorMessages() { + static const NodeMessage no_skeleton { + .severity = NodeMessage::warning, + .id = 1, + .text = "BoneAttachment must be a direct child of a SkeletalNode", + }; + static const NodeMessage no_bone { + .severity = NodeMessage::warning, + .id = 2, + .text = "Bone not found in the parent skeleton", + }; + + auto skeletal = parent().as(); + if (!skeletal.exists()) { + addInspectorMessage(no_skeleton); + removeInspectorMessage(no_bone); + return; + } + removeInspectorMessage(no_skeleton); + + if (skeletal->boneIndex(m_bone) >= 0) { + removeInspectorMessage(no_bone); + } else { + addInspectorMessage(no_bone); + } +} + +} diff --git a/engine/src/toast/world/bone_attachment.hpp b/engine/src/toast/world/bone_attachment.hpp new file mode 100644 index 000000000..7a64527cd --- /dev/null +++ b/engine/src/toast/world/bone_attachment.hpp @@ -0,0 +1,52 @@ +/** + * @file bone_attachment.hpp + * @author dario + * @date 9 Nov 2026 + */ + +#pragma once +#include "node_3d.hpp" + +#include + +namespace assets { +struct Skeleton; +} + +namespace toast { + +/// Follows one bone of its parent SkeletalNode, offsets go on its children +class [[ToastNode, Icon("BoneAttachment")]] TOAST_API BoneAttachment : public Node3D { + friend class SkeletalNode; + +public: + BoneAttachment() = default; + + [[nodiscard]] + auto bone() const noexcept -> const std::string& { + return m_bone; + } + + void bone(std::string name) { + m_bone = std::move(name); + m_resolved_skeleton = nullptr; + } + +private: + void updateInspectorMessages() override; + auto inspectorOptions(std::string_view field_name) -> std::vector override; + + [[Reflect, Name("Bone"), Options]] + std::string m_bone; + + /// Off keeps world scale 1 since rigs often carry an armature scale the skin cancels out and physics + /// rejects voxel nodes with non unit world scale + [[Reflect, Name("Inherit Scale")]] + bool m_inherit_scale = false; + + const assets::Skeleton* m_resolved_skeleton = nullptr; + std::string m_resolved_name; + int32_t m_bone_index = -1; +}; + +} diff --git a/engine/src/toast/world/clip_playback.hpp b/engine/src/toast/world/clip_playback.hpp new file mode 100644 index 000000000..bcc1ef4a5 --- /dev/null +++ b/engine/src/toast/world/clip_playback.hpp @@ -0,0 +1,54 @@ +/** + * @file clip_playback.hpp + * @author dario + * @date 9 Nov 2026 + */ + +#pragma once +#include +#include + +namespace toast { + +/// Clip clock shared by AnimationPlayer and SkeletalNode +struct ClipPlayback { + const assets::AnimationClip* clip = nullptr; + float time = 0.0f; + bool playing = false; + bool paused = false; + + void start(const assets::AnimationClip* new_clip) { + clip = new_clip; + time = 0.0f; + playing = new_clip != nullptr; + paused = false; + } + + void stop() { + playing = false; + time = 0.0f; + } + + /// @returns false when nothing advanced so the pose is unchanged + auto advance(float delta, float speed, bool loop) -> bool { + if (!playing || paused || clip == nullptr) { + return false; + } + time += delta * speed; + if (clip->duration > 0.0f && time >= clip->duration) { + if (loop) { + time = clip->wrap(time); + } else { + time = clip->duration; + playing = false; + } + } + return true; + } +}; + +/// Empty name means the first clip, logs under @p owner when nothing matches +TOAST_API auto resolveClip(const assets::Animation& animation, std::string_view clip_name, std::string_view owner) + -> const assets::AnimationClip*; + +} diff --git a/engine/src/toast/world/mesh_node.cpp b/engine/src/toast/world/mesh_node.cpp index 623f31451..418d42174 100644 --- a/engine/src/toast/world/mesh_node.cpp +++ b/engine/src/toast/world/mesh_node.cpp @@ -18,6 +18,16 @@ void MeshNode::updateInspectorMessages() { } } +auto MeshNode::inspectorOptions(std::string_view field_name) -> std::vector { + std::vector options; + if (field_name == "m_skin_name" && m_skin_animation.hasValue()) { + for (const auto& skin : m_skin_animation->skins()) { + options.push_back(skin.name); + } + } + return options; +} + void MeshNode::init() { renderer::registerMeshNodeProxy(this); m_registered_proxy = true; diff --git a/engine/src/toast/world/mesh_node.hpp b/engine/src/toast/world/mesh_node.hpp index b820ebebd..c95958e48 100644 --- a/engine/src/toast/world/mesh_node.hpp +++ b/engine/src/toast/world/mesh_node.hpp @@ -53,14 +53,6 @@ class [[ToastNode, Icon("MeshItem")]] TOAST_API MeshNode : public Node3D { return m_material; } - /** - * @brief Which .tanim asset's Skin drives this mesh, if it's skinned - * - * Only meaningful when getMesh()->isSkinned(). The skeleton that actually poses the joints isn't - * referenced here - the renderer looks for the nearest toast::AnimationPlayer ancestor and resolves - * this Skin's joint names against its subtree, matching how AnimationPlayer itself resolves clip - * targets. That keeps this a data-only reference instead of a second cross-node link to keep in sync - */ [[nodiscard]] auto getSkinAnimation() const -> const assets::Handle& { return m_skin_animation; @@ -74,6 +66,7 @@ class [[ToastNode, Icon("MeshItem")]] TOAST_API MeshNode : public Node3D { private: void updateInspectorMessages() override; + auto inspectorOptions(std::string_view field_name) -> std::vector override; void init(); void end(); void destroy(); @@ -87,7 +80,7 @@ class [[ToastNode, Icon("MeshItem")]] TOAST_API MeshNode : public Node3D { [[Reflect, Name("Skin Animation")]] assets::Handle m_skin_animation; - [[Reflect, Name("Skin Name")]] + [[Reflect, Name("Skin Name"), Options]] std::string m_skin_name; bool m_registered_proxy = false; diff --git a/engine/src/toast/world/node.hpp b/engine/src/toast/world/node.hpp index 3a17c9b6c..133face20 100644 --- a/engine/src/toast/world/node.hpp +++ b/engine/src/toast/world/node.hpp @@ -450,6 +450,12 @@ class [[ToastNode, Icon("Circle")]] TOAST_API Node { virtual void updateInspectorMessages() { } + /// Dropdown choices for a field marked [[Options]], refreshed with every inspector update + [[nodiscard]] + virtual auto inspectorOptions(std::string_view field_name) -> std::vector { + return {}; + } + void addInspectorMessage(const NodeMessage& message) { for (auto& existing : m_messages) { if (existing == message) { diff --git a/engine/src/toast/world/skeletal_node.cpp b/engine/src/toast/world/skeletal_node.cpp new file mode 100644 index 000000000..e4d834111 --- /dev/null +++ b/engine/src/toast/world/skeletal_node.cpp @@ -0,0 +1,314 @@ +#include "skeletal_node.hpp" + +#include "bone_attachment.hpp" + +#include +#include +#include + +namespace toast { + +namespace { + +const glm::mat4 k_identity {1.0f}; + +auto poseMatrix(const assets::BonePose& pose) -> glm::mat4 { + return glm::translate(glm::mat4(1.0f), pose.translation) * glm::mat4_cast(pose.rotation) * + glm::scale(glm::mat4(1.0f), pose.scale); +} + +} + +auto SkeletalNode::play(std::string_view clip_name) -> bool { + if (!m_animation.hasValue()) { + TOAST_WARN("Animation", "SkeletalNode '{}' has no animation asset assigned", name()); + return false; + } + + const assets::AnimationClip* clip = resolveClip(*m_animation, clip_name, name()); + if (clip == nullptr) { + return false; + } + + if (clip != m_playback.clip) { + m_node_cache.clear(); + } + m_playback.start(clip); + m_clip_name = clip->name; + return true; +} + +void SkeletalNode::stop() { + m_playback.stop(); +} + +void SkeletalNode::init() { + if (renderer::VulkanRenderer::instance) { + renderer::VulkanRenderer::instance->registerDebugDraw(this, [](Node3D& node) { + if (auto& skeletal = static_cast(node); skeletal.m_draw_bones) { + skeletal.drawBones(); + } + }); + } +} + +void SkeletalNode::destroy() { + if (renderer::VulkanRenderer::instance) { + renderer::VulkanRenderer::instance->unregisterDebugDraw(this); + } +} + +void SkeletalNode::drawBones() { + const glm::vec4 k_bone_color {1.0f, 0.6f, 0.1f, 1.0f}; + if (bindSkeleton() == nullptr) { + return; + } + syncTransform(); + const glm::mat4& world = getWorldTransform(); + for (size_t bone = 0; bone < m_model.size(); ++bone) { + const glm::vec3 position {world * m_model[bone][3]}; + if (m_parents[bone] >= 0) { + debug::drawLine(glm::vec3(world * m_model[m_parents[bone]][3]), position, k_bone_color); + } else { + debug::drawSphere(position, 0.03f, k_bone_color, 8); + } + } +} + +void SkeletalNode::begin() { + if (m_play_on_begin && m_animation.hasValue()) { + play(m_clip_name); + } +} + +void SkeletalNode::updateInspectorMessages() { + static const NodeMessage no_skeleton { + .severity = NodeMessage::warning, + .id = 1, + .text = "SkeletalNode needs a Skeleton or Animation asset that contains a skeleton", + }; + + if (skeleton() != nullptr) { + removeInspectorMessage(no_skeleton); + } else { + addInspectorMessage(no_skeleton); + } +} + +auto SkeletalNode::inspectorOptions(std::string_view field_name) -> std::vector { + std::vector options; + if (field_name == "m_clip_name" && m_animation.hasValue()) { + for (const auto& clip : m_animation->clips()) { + options.push_back(clip.name); + } + } else if (field_name == "m_skeleton_name") { + const auto& source = m_skeleton_asset.hasValue() ? m_skeleton_asset : m_animation; + if (source.hasValue()) { + for (const auto& skeleton : source->skeletons()) { + options.push_back(skeleton.name); + } + } + } + return options; +} + +auto SkeletalNode::skeleton() -> const assets::Skeleton* { + return bindSkeleton(); +} + +auto SkeletalNode::bindSkeleton() -> const assets::Skeleton* { + const auto& source = m_skeleton_asset.hasValue() ? m_skeleton_asset : m_animation; + const assets::Skeleton* found = source.hasValue() ? source->findSkeleton(m_skeleton_name) : nullptr; + if (found == m_bound) { + return found; + } + + m_bound = found; + m_skin_bones.clear(); + m_track_clip = nullptr; + m_track_to_bone.clear(); + + const size_t count = found != nullptr ? found->bones.size() : 0; + m_local.resize(count); + m_model.assign(count, glm::mat4(1.0f)); + m_parents.resize(count); + for (size_t i = 0; i < count; ++i) { + m_local[i] = found->bones[i].rest; + m_parents[i] = found->bones[i].parent; + } + if (found != nullptr) { + computeModel(*found); + } + return found; +} + +void SkeletalNode::bindTracks(const assets::Skeleton& skeleton) { + if (m_track_clip == m_playback.clip) { + return; + } + m_track_clip = m_playback.clip; + m_track_to_bone.clear(); + if (m_track_clip == nullptr) { + return; + } + + m_track_to_bone.reserve(m_track_clip->tracks.size()); + for (const auto& track : m_track_clip->tracks) { + m_track_to_bone.push_back(skeleton.find(track.target_node)); + } +} + +void SkeletalNode::computeModel(const assets::Skeleton& skeleton) { + for (size_t i = 0; i < m_local.size(); ++i) { + const glm::mat4 local = poseMatrix(m_local[i]); + const int32_t parent = skeleton.bones[i].parent; + m_model[i] = parent >= 0 ? m_model[parent] * local : local; + } +} + +void SkeletalNode::applyNodeTracks() { + const auto* clip = m_playback.clip; + for (size_t i = 0; i < clip->tracks.size() && i < m_track_to_bone.size(); ++i) { + if (m_track_to_bone[i] >= 0) { + continue; + } + const auto& track = clip->tracks[i]; + Node3D* target = resolveNode(track.target_node); + if (target == nullptr) { + continue; + } + switch (track.target) { + case assets::TrackTarget::translation: target->position = track.sampleVec3(m_playback.time); break; + case assets::TrackTarget::rotation: target->rotation = track.sampleQuat(m_playback.time); break; + case assets::TrackTarget::scale: continue; + } + target->syncTransform(); + } +} + +void SkeletalNode::applyAttachments(const assets::Skeleton& skeleton) { + syncWorldTransform(); + const glm::mat4& skeletal_world = getWorldTransform(); + const glm::mat4 inverse_skeletal_world = glm::inverse(skeletal_world); + + for (const auto& child : children()) { + auto* attachment = reflect_cast(const_cast(&*child)); + if (attachment == nullptr) { + continue; + } + if (attachment->m_resolved_skeleton != &skeleton || attachment->m_resolved_name != attachment->m_bone) { + attachment->m_resolved_skeleton = &skeleton; + attachment->m_resolved_name = attachment->m_bone; + attachment->m_bone_index = skeleton.find(attachment->m_bone); + } + const int32_t bone = attachment->m_bone_index; + if (bone < 0 || std::cmp_greater_equal(bone, m_model.size())) { + continue; + } + + glm::vec3 skew {0.0f}; + glm::vec4 perspective {0.0f}; + glm::vec3 position {0.0f}; + glm::vec3 scale {1.0f}; + glm::quat rotation {1.0f, 0.0f, 0.0f, 0.0f}; + glm::mat4 local = m_model[bone]; + if (!attachment->m_inherit_scale) { + if (!glm::decompose(skeletal_world * local, scale, rotation, position, skew, perspective)) { + continue; + } + const glm::mat4 unscaled_world = glm::translate(glm::mat4(1.0f), position) * glm::mat4_cast(glm::normalize(rotation)); + local = inverse_skeletal_world * unscaled_world; + } + if (!glm::decompose(local, scale, rotation, position, skew, perspective)) { + continue; + } + attachment->position = position; + attachment->rotation = rotation; + attachment->scale = scale; + attachment->syncTransform(); + } +} + +auto SkeletalNode::resolveNode(const std::string& node_name) -> Node3D* { + if (const auto it = m_node_cache.find(node_name); it != m_node_cache.end()) { + return it->second.exists() ? &*it->second : nullptr; + } + + // Descendants only since the importer may give this node the same name as an authored one + Box found; + for (const auto& child : children()) { + Box cursor = child; + if (!cursor.exists()) { + continue; + } + if (auto match = cursor->find(node_name).as(); match.exists()) { + found = match; + break; + } + } + + m_node_cache.emplace(node_name, found); + return found.exists() ? &*found : nullptr; +} + +void SkeletalNode::tick() { + ZoneScoped; + const assets::Skeleton* skeleton = bindSkeleton(); + if (skeleton == nullptr) { + return; + } + + // Holds the last pose when paused or stopped so attachments still follow a moved skeleton asset + if (m_playback.advance(static_cast(Time::delta()), m_speed, m_loop)) { + bindTracks(*skeleton); + for (size_t i = 0; i < m_local.size(); ++i) { + m_local[i] = skeleton->bones[i].rest; + } + m_playback.clip->sampleInto(m_playback.time, m_track_to_bone, m_local); + computeModel(*skeleton); + applyNodeTracks(); + } + + applyAttachments(*skeleton); +} + +auto SkeletalNode::boneIndex(std::string_view bone_name) -> int32_t { + const assets::Skeleton* bound = bindSkeleton(); + return bound != nullptr ? bound->find(bone_name) : -1; +} + +auto SkeletalNode::boneName(int32_t bone) const -> std::string_view { + if (m_bound == nullptr || bone < 0 || std::cmp_greater_equal(bone, m_bound->bones.size())) { + return {}; + } + return m_bound->bones[bone].name; +} + +auto SkeletalNode::boneModelTransform(int32_t bone) const -> const glm::mat4& { + if (bone < 0 || std::cmp_greater_equal(bone, m_model.size())) { + return k_identity; + } + return m_model[bone]; +} + +auto SkeletalNode::boneWorldTransform(int32_t bone) -> glm::mat4 { + syncTransform(); + return getWorldTransform() * boneModelTransform(bone); +} + +auto SkeletalNode::skinBones(const assets::Skin& skin) -> std::span { + const assets::Skeleton* bound = bindSkeleton(); + if (bound == nullptr) { + return {}; + } + auto [it, inserted] = m_skin_bones.try_emplace(&skin); + if (inserted) { + it->second.reserve(skin.joints.size()); + for (const auto& joint : skin.joints) { + it->second.push_back(bound->find(joint)); + } + } + return it->second; +} + +} diff --git a/engine/src/toast/world/skeletal_node.hpp b/engine/src/toast/world/skeletal_node.hpp new file mode 100644 index 000000000..c51f668a9 --- /dev/null +++ b/engine/src/toast/world/skeletal_node.hpp @@ -0,0 +1,152 @@ +/** + * @file skeletal_node.hpp + * @author dario + * @date 9 Nov 2026 + */ + +#pragma once +#include "clip_playback.hpp" +#include "node_3d.hpp" + +#include +#include +#include +#include +#include +#include + +namespace toast { + +/** + * @brief Owns a skeleton pose and plays clips onto it + * + * Bones are arrays here, never scene nodes. Skinned MeshNode descendants read the pose through + * skinBones and boneModelTransform, BoneAttachment children get their transform written every tick. + * Clip tracks that name no bone fall back to descendant nodes by name + * + * @note Also ticked outside Play, by Workspace::tickAnimationPreviews() + */ +class [[ToastNode, Icon("Bone")]] TOAST_API SkeletalNode : public Node3D { +public: + SkeletalNode() = default; + + /// @returns false when the asset has no clip by that name + [[Reflect]] + auto play(std::string_view clip_name) -> bool; + + [[Reflect]] + void stop(); + + [[Reflect]] + void pause(bool value) { + m_playback.paused = value; + } + + [[nodiscard]] + auto isPlaying() const noexcept -> bool { + return m_playback.playing; + } + + [[nodiscard]] + auto time() const noexcept -> float { + return m_playback.time; + } + + void time(float seconds) noexcept { m_playback.time = seconds; } + + [[nodiscard, Reflect]] + auto boneIndex(std::string_view bone_name) -> int32_t; + + [[nodiscard]] + auto boneCount() const noexcept -> int32_t { + return static_cast(m_model.size()); + } + + [[nodiscard]] + auto boneName(int32_t bone) const -> std::string_view; + + [[nodiscard]] + auto boneModelTransform(int32_t bone) const -> const glm::mat4&; + + [[nodiscard]] + auto boneWorldTransform(int32_t bone) -> glm::mat4; + + [[nodiscard]] + auto boneParents() const noexcept -> std::span { + return m_parents; + } + + [[nodiscard]] + auto skeleton() -> const assets::Skeleton*; + + /// Skin joint index to bone index, -1 where this skeleton lacks the joint + [[nodiscard]] + auto skinBones(const assets::Skin& skin) -> std::span; + + /// Advances playback, poses bones and moves attachments, public for editor previews + void tick(); + + void drawBones(); + + [[nodiscard]] + auto alwaysDrawsBones() const noexcept -> bool { + return m_draw_bones; + } + +private: + void init(); + void destroy(); + void begin(); + void updateInspectorMessages() override; + auto inspectorOptions(std::string_view field_name) -> std::vector override; + + auto bindSkeleton() -> const assets::Skeleton*; + void bindTracks(const assets::Skeleton& skeleton); + void computeModel(const assets::Skeleton& skeleton); + void applyNodeTracks(); + void applyAttachments(const assets::Skeleton& skeleton); + auto resolveNode(const std::string& name) -> Node3D*; + + /// Empty uses the Animation asset since every .tanim carries its skeletons + [[Reflect, Name("Skeleton")]] + assets::Handle m_skeleton_asset; + + /// Empty means the first skeleton in the asset + [[Reflect, Name("Skeleton Name"), Options]] + std::string m_skeleton_name; + + [[Reflect, Name("Animation")]] + assets::Handle m_animation; + + [[Reflect, Name("Clip"), Options]] + std::string m_clip_name; + + [[Reflect, Name("Play On Begin")]] + bool m_play_on_begin = true; + + [[Reflect, Name("Loop")]] + bool m_loop = true; + + [[Reflect, Unit("x"), Range(0.0, 10.0)]] + float m_speed = 1.0f; + + /// Off still draws while selected in the editor + [[Reflect, Name("Draw Bones"), Group("Debug")]] + bool m_draw_bones = false; + + ClipPlayback m_playback; + + const assets::Skeleton* m_bound = nullptr; + std::vector m_local; + std::vector m_model; + std::vector m_parents; + + /// Per track of m_track_clip, -1 for tracks that target nodes + std::vector m_track_to_bone; + const assets::AnimationClip* m_track_clip = nullptr; + + std::unordered_map> m_skin_bones; + std::unordered_map> m_node_cache; +}; + +} diff --git a/engine/src/toast/world/workspace.cpp b/engine/src/toast/world/workspace.cpp index c7e214866..a3211831d 100644 --- a/engine/src/toast/world/workspace.cpp +++ b/engine/src/toast/world/workspace.cpp @@ -6,6 +6,7 @@ #include "node.hpp" #include "node_3d.hpp" #include "play_workspace.hpp" +#include "skeletal_node.hpp" #include "tree_lock.hpp" #include "workspace_events.hpp" @@ -2667,6 +2668,8 @@ void Workspace::tickAnimationPreviews(const Node& node) { // reflect_cast, not dynamic_cast - this engine deliberately has no RTTI/vtable-based dispatch for Node if (auto* player = reflect_cast(const_cast(&node))) { player->tick(); + } else if (auto* skeletal = reflect_cast(const_cast(&node))) { + skeletal->tick(); } for (const auto& child : node.children()) { tickAnimationPreviews(*child); @@ -2784,7 +2787,12 @@ void Workspace::tick() { } catch (const std::bad_any_cast&) { text = ""; } } - fields.emplace_back(field.name, text); + const nlohmann::json* attributes = field.attributeMap(); + if (attributes != nullptr && attributes->contains("Options")) { + fields.emplace_back(field.name, text, node->inspectorOptions(field.name)); + } else { + fields.emplace_back(field.name, text); + } } } diff --git a/engine/src/toast/world/workspace_events.cpp b/engine/src/toast/world/workspace_events.cpp index 022d4239b..df9f7105e 100644 --- a/engine/src/toast/world/workspace_events.cpp +++ b/engine/src/toast/world/workspace_events.cpp @@ -672,10 +672,15 @@ struct ProtoTraits { Proto p; p.set_name(e.name); p.set_value(e.value); + for (const auto& option : e.options) { + p.add_options(option); + } return p; } - static auto fromProto(const Proto& p) -> Event { return {p.name(), p.value()}; } + static auto fromProto(const Proto& p) -> Event { + return {p.name(), p.value(), std::vector(p.options().begin(), p.options().end())}; + } }; template<> diff --git a/engine/src/toast/world/workspace_events.hpp b/engine/src/toast/world/workspace_events.hpp index 516269b63..867820a7e 100644 --- a/engine/src/toast/world/workspace_events.hpp +++ b/engine/src/toast/world/workspace_events.hpp @@ -479,8 +479,12 @@ struct InspectorContent : Event { struct InspectorField { std::string name; std::string value; + std::vector options; - InspectorField(std::string_view name, std::string_view value) : name(name), value(value) { } + InspectorField(std::string_view name, std::string_view value, std::vector options = {}) + : name(name), + value(value), + options(std::move(options)) { } }; std::string uid; diff --git a/protos/workspace_events.proto b/protos/workspace_events.proto index 60a607e5b..5dbe89306 100644 --- a/protos/workspace_events.proto +++ b/protos/workspace_events.proto @@ -394,6 +394,7 @@ message EditorCameraGesture { message InspectorField { string name = 1; string value = 2; + repeated string options = 3; } message InspectorMessage { diff --git a/tests/assets/02-animation-binary.cpp b/tests/assets/02-animation-binary.cpp index 90744e49a..1e80db08e 100644 --- a/tests/assets/02-animation-binary.cpp +++ b/tests/assets/02-animation-binary.cpp @@ -64,7 +64,7 @@ TOAST_TEST_NAMED("Assets", "assets/02-animation-binary", test_assets_02_animatio skin.joints = {"Hips", "Spine", "Head"}; skin.inverse_bind_matrices = {glm::mat4(1.0f), glm::mat4(2.0f), glm::mat4(3.0f)}; - const auto bytes = assets::Animation::toBinary({clip}, {skin}); + const auto bytes = assets::Animation::toBinary({clip}, {skin}, {}); assert(!bytes.empty()); const assets::Animation loaded(bytes); diff --git a/tests/assets/04-animation-skin-only.cpp b/tests/assets/04-animation-skin-only.cpp index f93d381cd..7d941bb36 100644 --- a/tests/assets/04-animation-skin-only.cpp +++ b/tests/assets/04-animation-skin-only.cpp @@ -22,7 +22,7 @@ TOAST_TEST_NAMED("Assets", "assets/04-animation-skin-only", test_assets_04_anima skin.joints = {"Hips", "Spine", "Head"}; skin.inverse_bind_matrices = {glm::mat4(1.0f), glm::mat4(2.0f), glm::mat4(3.0f)}; - const auto bytes = assets::Animation::toBinary({}, {skin}); + const auto bytes = assets::Animation::toBinary({}, {skin}, {}); assert(!bytes.empty()); const assets::Animation loaded(bytes); diff --git a/vcpkg.json b/vcpkg.json index b12fbecda..54a959d38 100644 --- a/vcpkg.json +++ b/vcpkg.json @@ -142,8 +142,7 @@ "overrides": [ { "name": "tracy", - "version": "0.14.1", - "port-version": 1 + "version": "0.15.0" }, { "name": "lua", From b871609a7a963a4d6cc606f4c99a656d279c5d4e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dar=C3=ADo=20Rodr=C3=ADguez=20Mart=C3=ADnez?= Date: Fri, 13 Nov 2026 08:32:38 +0100 Subject: [PATCH 06/11] done some shi --- engine/CMakeLists.txt | 4 ++-- engine/src/toast/engine.cpp | 6 +++--- engine/src/toast/events/proto_event.hpp | 6 +++--- engine/src/toast/world/skeletal_node.cpp | 2 +- protos/logging.proto | 1 + protos/render_events.proto | 1 + protos/signals.proto | 1 + protos/window_events.proto | 1 + protos/workspace_events.proto | 1 + tools/log_server/CMakeLists.txt | 4 ++-- 10 files changed, 16 insertions(+), 11 deletions(-) diff --git a/engine/CMakeLists.txt b/engine/CMakeLists.txt index 8f03d4174..e3dd0e556 100644 --- a/engine/CMakeLists.txt +++ b/engine/CMakeLists.txt @@ -104,11 +104,11 @@ target_link_libraries(toast_engine Vulkan::Vulkan KTX::ktx unofficial::VulkanMemoryAllocator-Hpp::VulkanMemoryAllocator-Hpp - slang::gfx slang::slang protobuf::libprotobuf tinysplinecxx::tinysplinecxx + slang::slang protobuf::libprotobuf-lite tinysplinecxx::tinysplinecxx LZ4::lz4 toast_pack $<$,$>:imgui::imgui> - RmlUi::RmlUi + RmlUi::Core cpptrace::cpptrace $<$:${EXTERNAL_LIBS_DEBUG}> $<$>:${EXTERNAL_LIBS_RELEASE}> diff --git a/engine/src/toast/engine.cpp b/engine/src/toast/engine.cpp index fe24798c7..583033b7e 100644 --- a/engine/src/toast/engine.cpp +++ b/engine/src/toast/engine.cpp @@ -126,8 +126,8 @@ auto addScenePasses( const auto scene_format = renderer.getSceneColorFormat(); // Before the passes whose scene sets bind its cascades - auto gi_pass = std::make_unique(core, scene_format, extent); - renderer.setGiPass(gi_pass.get()); + // auto gi_pass = std::make_unique(core, scene_format, extent); + // renderer.setGiPass(gi_pass.get()); auto gi_clipmap_pass = std::make_unique(core, scene_format, extent); renderer.setGiClipmapPass(gi_clipmap_pass.get()); @@ -141,7 +141,7 @@ auto addScenePasses( renderer.addRenderPass(std::make_unique(core, scene_format, depth_format, extent)); // First in the chain so the probes read depth before any post pass - renderer.addPostProcessPass(std::move(gi_pass)); + // renderer.addPostProcessPass(std::move(gi_pass)); renderer.addPostProcessPass(std::move(gi_clipmap_pass)); if (core.isRayTracingSupported()) { diff --git a/engine/src/toast/events/proto_event.hpp b/engine/src/toast/events/proto_event.hpp index 5016f86df..49e3c20b2 100644 --- a/engine/src/toast/events/proto_event.hpp +++ b/engine/src/toast/events/proto_event.hpp @@ -63,7 +63,7 @@ void registerProtoEvent() { try { Proto p = Traits::toProto(ev); std::string bytes = p.SerializeAsString(); - std::string name {Proto::descriptor()->full_name()}; + std::string name {Proto::default_instance().GetTypeName()}; return callback( name.c_str(), reinterpret_cast(bytes.data()), @@ -72,7 +72,7 @@ void registerProtoEvent() { ) != 0; } catch (const std::exception& e) { // swallow serialization failures so one bad event doesn't kill the whole chain - TOAST_WARN("Events", "Failed to serialize event {}: {}", Proto::descriptor()->full_name(), e.what()); + TOAST_WARN("Events", "Failed to serialize event {}: {}", Proto::default_instance().GetTypeName(), e.what()); return false; } }, @@ -82,7 +82,7 @@ void registerProtoEvent() { .unsubscribe = [](Listener& l, const char* label) { l.unsubscribe(std::string_view {label}); }, }; - _detail::registerProtoEntry(std::string {Proto::descriptor()->full_name()}, entry); + _detail::registerProtoEntry(std::string {Proto::default_instance().GetTypeName()}, entry); } namespace _detail { diff --git a/engine/src/toast/world/skeletal_node.cpp b/engine/src/toast/world/skeletal_node.cpp index e4d834111..9e25a3cec 100644 --- a/engine/src/toast/world/skeletal_node.cpp +++ b/engine/src/toast/world/skeletal_node.cpp @@ -68,7 +68,7 @@ void SkeletalNode::drawBones() { for (size_t bone = 0; bone < m_model.size(); ++bone) { const glm::vec3 position {world * m_model[bone][3]}; if (m_parents[bone] >= 0) { - debug::drawLine(glm::vec3(world * m_model[m_parents[bone]][3]), position, k_bone_color); + debug::drawArrow(glm::vec3(world * m_model[m_parents[bone]][3]), position, k_bone_color); } else { debug::drawSphere(position, 0.03f, k_bone_color, 8); } diff --git a/protos/logging.proto b/protos/logging.proto index 651c353e1..53ec3b053 100644 --- a/protos/logging.proto +++ b/protos/logging.proto @@ -1,4 +1,5 @@ syntax = "proto3"; +option optimize_for = LITE_RUNTIME; package proto.logging; message LogData { diff --git a/protos/render_events.proto b/protos/render_events.proto index f92bb950d..91001afa6 100644 --- a/protos/render_events.proto +++ b/protos/render_events.proto @@ -1,4 +1,5 @@ syntax = "proto3"; +option optimize_for = LITE_RUNTIME; package proto.events; message RequestRenderPasses {} diff --git a/protos/signals.proto b/protos/signals.proto index 84bcbb99d..5f218e3fe 100644 --- a/protos/signals.proto +++ b/protos/signals.proto @@ -1,4 +1,5 @@ syntax = "proto3"; +option optimize_for = LITE_RUNTIME; package proto.events; enum SignalConnectionSource { diff --git a/protos/window_events.proto b/protos/window_events.proto index 8d829a398..df2e59215 100644 --- a/protos/window_events.proto +++ b/protos/window_events.proto @@ -1,4 +1,5 @@ syntax = "proto3"; +option optimize_for = LITE_RUNTIME; package proto.events; message ExitApplication {} diff --git a/protos/workspace_events.proto b/protos/workspace_events.proto index 5dbe89306..993278d00 100644 --- a/protos/workspace_events.proto +++ b/protos/workspace_events.proto @@ -1,4 +1,5 @@ syntax = "proto3"; +option optimize_for = LITE_RUNTIME; package proto.events; message HierarchyElement { diff --git a/tools/log_server/CMakeLists.txt b/tools/log_server/CMakeLists.txt index 5c613005a..e77165b70 100644 --- a/tools/log_server/CMakeLists.txt +++ b/tools/log_server/CMakeLists.txt @@ -32,7 +32,7 @@ set(LOG_SERVER_SOURCES src/main.cpp ${LOG_SERVER_CORE_SOURCES}) add_executable(log_server ${LOG_SERVER_SOURCES} ${LOG_SERVER_PROTO_SOURCES}) target_include_directories(log_server PRIVATE src "${LOG_SERVER_GENERATED_DIR}") -target_link_libraries(log_server PRIVATE protobuf::libprotobuf asio::asio Threads::Threads CURL::libcurl ZLIB::ZLIB nlohmann_json::nlohmann_json) +target_link_libraries(log_server PRIVATE protobuf::libprotobuf-lite asio::asio Threads::Threads CURL::libcurl ZLIB::ZLIB nlohmann_json::nlohmann_json) target_compile_definitions(log_server PRIVATE ASIO_STANDALONE ASIO_NO_DEPRECATED) if (MSVC) @@ -50,7 +50,7 @@ endforeach () add_executable(log_server_checks EXCLUDE_FROM_ALL checks/checks.cpp ${LOG_SERVER_CORE_SOURCES} ${LOG_SERVER_PROTO_SOURCES}) target_include_directories(log_server_checks PRIVATE src "${LOG_SERVER_GENERATED_DIR}") -target_link_libraries(log_server_checks PRIVATE protobuf::libprotobuf asio::asio Threads::Threads CURL::libcurl ZLIB::ZLIB nlohmann_json::nlohmann_json) +target_link_libraries(log_server_checks PRIVATE protobuf::libprotobuf-lite asio::asio Threads::Threads CURL::libcurl ZLIB::ZLIB nlohmann_json::nlohmann_json) target_compile_definitions(log_server_checks PRIVATE ASIO_STANDALONE ASIO_NO_DEPRECATED) if (MSVC) target_compile_definitions(log_server_checks PRIVATE NOMINMAX WIN32_LEAN_AND_MEAN NOGDI _CRT_SECURE_NO_WARNINGS) From 31342fe9aab35a1878c4d879ade09145746ab68f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dar=C3=ADo=20Rodr=C3=ADguez=20Mart=C3=ADnez?= Date: Fri, 13 Nov 2026 20:52:15 +0100 Subject: [PATCH 07/11] Sepparated skeletal assets and fixed GI? --- editor/Assets/Importers/GltfImporter.cs | 40 ++- editor/Assets/Types/SkeletonAsset.cs | 18 ++ engine/CMakeLists.txt | 2 +- engine/assets/shaders/gi_common.slang | 6 +- engine/assets/shaders/gi_sample.slang | 13 +- engine/assets/shaders/gt7_tonemap.slang | 3 +- engine/assets/shaders/lens_flare.slang | 2 +- engine/assets/shaders/lighting.slang | 6 +- engine/assets/shaders/scene_trace.slang | 3 +- engine/assets/shaders/voxel.slang | 8 +- engine/assets/shaders/voxel_glass.slang | 2 +- engine/assets/shaders/voxel_lighting.slang | 5 +- engine/assets/shaders/voxel_mesh.slang | 3 +- engine/assets/shaders/voxel_mesh_task.slang | 3 +- engine/src/toast/assets/animation.cpp | 260 ++---------------- engine/src/toast/assets/animation.hpp | 97 +------ engine/src/toast/assets/asset_manager.cpp | 3 +- engine/src/toast/assets/asset_registry.cpp | 1 + engine/src/toast/assets/binary_io.hpp | 100 +++++++ engine/src/toast/assets/gltf_importer.cpp | 160 +++++------ engine/src/toast/assets/skeleton.cpp | 121 ++++++++ engine/src/toast/assets/skeleton.hpp | 92 +++++++ engine/src/toast/assets/types.hpp | 1 + engine/src/toast/backtrace.cpp | 7 +- engine/src/toast/engine.cpp | 6 +- engine/src/toast/events/signal_bindings.hpp | 8 +- engine/src/toast/heap_tracking.cpp | 7 +- engine/src/toast/physics/joint.hpp | 7 +- engine/src/toast/physics/joint_solver.cpp | 3 +- .../src/toast/physics/nodes/hinge_joint.hpp | 3 +- engine/src/toast/physics/query_snapshot.hpp | 2 +- engine/src/toast/physics/raycast.hpp | 2 +- engine/src/toast/physics/simulator.cpp | 6 +- .../src/toast/renderer/core/vulkan_core.cpp | 2 +- .../renderer/passes/geometry/voxel_pass.cpp | 2 +- .../passes/lighting/gi_clipmap_pass.hpp | 2 +- .../renderer/shaders/shader_compiler.cpp | 1 - .../toast/renderer/voxel/voxel_blas_cache.hpp | 7 +- .../renderer/voxel/voxel_trace_scene.hpp | 4 +- engine/src/toast/renderer/vulkan_renderer.hpp | 3 +- .../toast/renderer/vulkan_renderer_scene.cpp | 33 +-- engine/src/toast/world/animation_player.cpp | 52 ++-- engine/src/toast/world/animation_player.hpp | 17 +- engine/src/toast/world/bone_attachment.cpp | 4 +- engine/src/toast/world/bone_attachment.hpp | 3 +- engine/src/toast/world/clip_playback.hpp | 13 +- engine/src/toast/world/light_gizmo.hpp | 1 - engine/src/toast/world/mesh_node.cpp | 16 +- engine/src/toast/world/mesh_node.hpp | 10 +- engine/src/toast/world/skeletal_node.cpp | 46 +--- engine/src/toast/world/skeletal_node.hpp | 32 +-- engine/src/toast/world/workspace.cpp | 4 +- tests/CMakeLists.txt | 2 +- tests/assets/02-animation-binary.cpp | 31 +-- tests/assets/04-animation-skin-only.cpp | 33 ++- 55 files changed, 630 insertions(+), 688 deletions(-) create mode 100644 editor/Assets/Types/SkeletonAsset.cs create mode 100644 engine/src/toast/assets/binary_io.hpp create mode 100644 engine/src/toast/assets/skeleton.cpp create mode 100644 engine/src/toast/assets/skeleton.hpp diff --git a/editor/Assets/Importers/GltfImporter.cs b/editor/Assets/Importers/GltfImporter.cs index 07d31b67d..58a113dff 100644 --- a/editor/Assets/Importers/GltfImporter.cs +++ b/editor/Assets/Importers/GltfImporter.cs @@ -69,7 +69,8 @@ public IReadOnlyList GetSettings() { AssetTypeRegistry.ByExtension(".tnode")!, AssetTypeRegistry.ByExtension(".ktx2")!, AssetTypeRegistry.ByExtension(".tmat")!, - AssetTypeRegistry.ByExtension(".tanim")! + AssetTypeRegistry.ByExtension(".tanim")!, + AssetTypeRegistry.ByExtension(".tskel")! ]; /// @@ -165,8 +166,10 @@ public async Task> Import( : []; var materials = m_settings.ImportMaterials ? byExtension.GetValueOrDefault(".tmat") ?? [] : []; var animations = m_settings.ImportAnimations ? byExtension.GetValueOrDefault(".tanim") ?? [] : []; + // Skeletons import even with animations off since BoneAttachments and skinned meshes need them + var skeletons = byExtension.GetValueOrDefault(".tskel") ?? []; var scenes = m_settings.GeneratePrefab ? byExtension.GetValueOrDefault(".json") ?? [] : []; - var totalItems = meshes.Count + textures.Count * 10 + materials.Count + animations.Count + + var totalItems = meshes.Count + textures.Count * 10 + materials.Count + animations.Count + skeletons.Count + scenes.Count * 2; // *2: patch + create var doneItems = 0; @@ -301,6 +304,23 @@ void ReportProgress() { } } + var skeletonUids = new Dictionary(); + foreach (var sk in skeletons) { + var skeletonName = Path.GetFileNameWithoutExtension(sk.Name); + var destPath = Path.Combine(destDir, skeletonName + ".tskel"); + var uid = UidGenerator.Generate(); + skeletonUids[skeletonName] = uid; + + log($"Skeleton {skeletonName}"); + File.Copy(sk.FullName, destPath, true); + var header = new MetaHeader + { Uid = uid, Type = AssetTypeRegistry.ByExtension(".tskel")!.Type, Source = ctx.SourceVirtualPath }; + MetaFile.Write(destPath, header, m_settings.ToSection()); + importedUids.Add(uid); + doneItems++; + ReportProgress(); + } + log("Rebuilding asset database..."); AssetDatabase.RebuildAssetDatabase(); @@ -321,15 +341,19 @@ void PatchNode(JsonNode node) { if (p["material"] is { } matNode && materialUids.TryGetValue(matNode.GetValue(), out var matUid)) p["material"] = matUid; - if (p["skin_animation"] is { } skinAnimNode && - animationUids.TryGetValue(skinAnimNode.GetValue(), out var skinAnimUid)) - p["skin_animation"] = skinAnimUid; } } else if (nodeType is "toast::AnimationPlayer" or "toast::SkeletalNode") { var p = node["params"]?.AsObject(); - if (p != null && p["animation"] is { } animNode && - animationUids.TryGetValue(animNode.GetValue(), out var animUid)) - p["animation"] = animUid; + if (p?["skeleton"] is { } skeletonNode && + skeletonUids.TryGetValue(skeletonNode.GetValue(), out var skeletonUid)) + p["skeleton"] = skeletonUid; + // Clips skipped by Import Animations have no UID and drop out of the list + if (p?["clips"] is JsonArray clipNames) + p["clips"] = new JsonArray(clipNames + .Select(c => animationUids.TryGetValue(c!.GetValue(), out var clipUid) ? clipUid : null) + .Where(clipUid => clipUid != null) + .Select(clipUid => (JsonNode)JsonValue.Create(clipUid)!) + .ToArray()); } if (node["children"] is not JsonArray children) return; diff --git a/editor/Assets/Types/SkeletonAsset.cs b/editor/Assets/Types/SkeletonAsset.cs new file mode 100644 index 000000000..a478037bf --- /dev/null +++ b/editor/Assets/Types/SkeletonAsset.cs @@ -0,0 +1,18 @@ +using Lucide.Avalonia; + +namespace editor.Assets.Types; + +public sealed class SkeletonAsset : BaseAsset { + public override string Type => "skeleton"; + public override string Extension => ".tskel"; + public override string DisplayName => "Skeleton"; + public override string ChipText => "SKEL"; + public override string ChipColor => "Purple"; + public override LucideIconKind Icon => LucideIconKind.Bone; + public override bool CanBeCreated => false; + public override string Category => "Visual"; + public override bool HasThumbnail => false; + public override bool CanBeEdited => false; + public override string EditorTool => ""; + public override string SchemaPath => ""; +} diff --git a/engine/CMakeLists.txt b/engine/CMakeLists.txt index e3dd0e556..bccd0b71c 100644 --- a/engine/CMakeLists.txt +++ b/engine/CMakeLists.txt @@ -176,7 +176,7 @@ target_compile_definitions(toast_engine PRIVATE TOAST_HEAP_CALLSTACK_DEPTH=${TOAST_HEAP_CALLSTACK_DEPTH} ) -# Keep Slang's Debug profile for Linux builds that retain C++ debug information. +# Linux builds with C++ debug info keep the Slang Debug profile target_compile_definitions(toast_engine PRIVATE $<$,$>:TOAST_SLANG_DEBUG_DEFAULT> ) diff --git a/engine/assets/shaders/gi_common.slang b/engine/assets/shaders/gi_common.slang index 21f8a6779..a9a36ccb9 100644 --- a/engine/assets/shaders/gi_common.slang +++ b/engine/assets/shaders/gi_common.slang @@ -205,8 +205,7 @@ uint giMortonSpread(uint value) return value; } -/// Two Morton ordered N by N halves so the four children of a direction are contiguous one cascade up -/// @p uv from giEncodeDirection so a ray split over every cascade encodes once +/// Morton ordered halves so the four children of a direction are contiguous one cascade up uint giDirectionIndex(float2 uv, uint cascade) { const uint side = giSide(cascade); @@ -297,8 +296,7 @@ struct GiHistory float rays; }; -/// GLSL.std.450 packing since f32tof16 needs shaderFloat16 and shaderInt16 which the device does not enable -/// Clamped first since PackHalf2x16 turns overflow into infinity +/// PackHalf2x16 since f32tof16 needs shaderFloat16 which is off and clamped since overflow packs as infinity uint giFloatToHalf(float value) { const float2 clamped = float2(clamp(value, -65504.0, 65504.0), 0.0); diff --git a/engine/assets/shaders/gi_sample.slang b/engine/assets/shaders/gi_sample.slang index e68cc85fc..4358f3710 100644 --- a/engine/assets/shaders/gi_sample.slang +++ b/engine/assets/shaders/gi_sample.slang @@ -187,8 +187,7 @@ static const float kGiClipConeBias = 0.0; static const float kGiClipConeLift = 1.5; static const float kGiClipFaceWeight = 1e-4; -/// Premultiplied radiance of the faces looking back at the ray and opacity along it -/// @p lod above 0 reads the mips of the last level which stand in for coarser levels over the same box +/// Premultiplied face radiance toward the ray and opacity along it where @p lod above 0 reads last level mips float4 giClipSample(GiClipFrame frame, uint level, float lod, float3 world, float3 direction) { // The repeat sampler does the toroidal wrap @@ -227,8 +226,7 @@ float4 giClipSmoothTap(float3 cell, float3 f, float cells, uint tap) return float4(at / cells, share.x * share.y * share.z); } -/// Trilinear draws cells as creased pyramids so this rounds them at 8 reads per texture -/// The taps are worked out again for each read since holding all eight costs registers every pixel pays for +/// Rounds the creases trilinear leaves at 8 reads per texture and recomputes taps per read to save registers float4 giClipSampleSmooth(GiClipFrame frame, float3 world, float3 direction) { const float cells = float(frame.size.x); @@ -273,9 +271,7 @@ float giClipSolidShare(GiClipFrame frame, uint level, float3 world) return gGiClipOpacity[NonUniformResourceIndex(level)].SampleLevel(uvw, 0.0).w; } -/// Radiance rgb and coverage a starting @p start meters along the cone and reading no level finer than @p base -/// Smooth above 0 reads level 0 through giClipSampleSmooth and is a compile time choice so shaders that only -/// take the plain cone do not carry the smooth filter +/// rgb radiance a coverage from @p start meters on with no level finer than @p base float4 giClipCone(GiClipFrame frame, float3 origin, float3 direction, float start, float base) { const float cell = frame.levels[0].w; @@ -366,8 +362,7 @@ float4 giClipGather(GiClipFrame frame, float3 worldPosition, float3 normal, floa return gathered; } -/// @p turn in 0 to 1 spins the side cones by up to the fifth of a turn between two of them -/// Nothing here is random and lit pixels pass 0 since any per frame noise flickers around bright lights +/// @p turn spins the side cones up to a fifth of a turn and lit pixels pass 0 since per frame noise flickers bool sampleGiClipmap(float3 worldPosition, float3 normal, float turn, out float3 irradiance, out float sky) { irradiance = float3(0.0, 0.0, 0.0); diff --git a/engine/assets/shaders/gt7_tonemap.slang b/engine/assets/shaders/gt7_tonemap.slang index 293889f98..691a8350b 100644 --- a/engine/assets/shaders/gt7_tonemap.slang +++ b/engine/assets/shaders/gt7_tonemap.slang @@ -170,8 +170,7 @@ float3 rec2020ToRec709(float3 c) dot(float3(-0.0181508, -0.1005789, 1.1187297), c)); } -/// Scene linear Rec.709 where 1.0 is paper white to the same space relative to paper white, at most peak over paper white -/// Both whites are framebuffer values with 1.0 at 100 nits and the peak never goes under the SDR paper white +/// Paper white relative Rec.709 in and out capped at peak over paper white with framebuffer 1.0 at 100 nits public float3 gt7ToneMap(float3 scene, float paperWhite, float peak, float toeStrength) { peak = max(peak, kGt7SdrPaperWhite); diff --git a/engine/assets/shaders/lens_flare.slang b/engine/assets/shaders/lens_flare.slang index 8a9596b74..038556475 100644 --- a/engine/assets/shaders/lens_flare.slang +++ b/engine/assets/shaders/lens_flare.slang @@ -1,4 +1,4 @@ -// Lens flare after Froyok's UE4 custom flare, ghosts and halo from a chroma shifted threshold, glare as luminance scaled streak quads +// After the Froyok UE4 custom lens flare import fullscreen; struct LensFlareParams diff --git a/engine/assets/shaders/lighting.slang b/engine/assets/shaders/lighting.slang index 0e18219ca..0ce04eff3 100644 --- a/engine/assets/shaders/lighting.slang +++ b/engine/assets/shaders/lighting.slang @@ -567,8 +567,7 @@ float emitterExtent(float4 shapeParams) static const float kOctagonRadiusScale = 1.0540925; static const uint kMaxEmitterVertices = 8u; -/// Vector irradiance of a uniform Lambert polygon seen from the origin and clipped to the horizon of N -/// Vertices are relative to the receiver, its dot with N is the cosine weighted solid angle +/// Vector irradiance of a Lambert polygon relative to the receiver whose dot with N is the cosine weighted solid angle float3 clippedPolygonVectorIrradiance(float3 vertices[kMaxEmitterVertices], uint count, float3 N) { float3 clipped[kMaxEmitterVertices + 2]; @@ -827,8 +826,7 @@ static const float kWidePenumbraTexels = 6.0; static const uint kWidePenumbraTaps = 16u; -/// Indirect diffuse a shader worked out before shading as xyz irradiance over pi and w the open sky share -/// Below 0 means none and lighting never gathers on its own so each shader compiles only the gather it calls +/// xyz irradiance over pi w open sky share and below 0 for none since lighting never gathers on its own static float4 gGiGathered = float4(0.0, 0.0, 0.0, -1.0); bool giSurfaceIrradiance(out float3 irradiance, out float sky) diff --git a/engine/assets/shaders/scene_trace.slang b/engine/assets/shaders/scene_trace.slang index 691b04950..1ca4c310f 100644 --- a/engine/assets/shaders/scene_trace.slang +++ b/engine/assets/shaders/scene_trace.slang @@ -1,5 +1,4 @@ -// Voxel rays across every traced volume through ray queries when the TLAS holds the volumes and a camera centred -// cell grid otherwise and both march the same volumes with voxel_dda +// Voxel rays through ray queries or a camera centred cell grid that both march with voxel_dda import voxel_dda; import lighting; diff --git a/engine/assets/shaders/voxel.slang b/engine/assets/shaders/voxel.slang index 1be2a8d54..23458f4c1 100644 --- a/engine/assets/shaders/voxel.slang +++ b/engine/assets/shaders/voxel.slang @@ -40,8 +40,7 @@ StructuredBuffer gVoxelCells; [[vk::binding(16, 1)]] Sampler2D gHiz; -/// Whether the pyramid proves a screen rect at nearest depth hidden, rects off screen or crossing the near plane are never hidden -/// Level k texels are 2 << k pixels wide so the widened rect touches at most 2x2 of them +/// Rects off screen or crossing the near plane never count as hidden bool hizRectHidden(float2 low, float2 high, float nearest) { const float2 size = float2(float(gPush.hizWidth), float(gPush.hizHeight)); @@ -72,7 +71,7 @@ bool hizRectHidden(float2 low, float2 high, float nearest) return isCloserDepth(farthest, nearest); } -/// Folds clip space points into the screen rect and nearest depth of hizRectHidden, false when one is on or behind the near plane +/// False when a point is on or behind the near plane bool hizAccumulate(float4 clip, inout float2 low, inout float2 high, inout float nearest) { if (clip.w <= 0.0 || clipNearDistance(clip) <= 0.0) @@ -298,8 +297,7 @@ void detailAxes(uint axis, out uint u, out uint v) v = axis == 2u ? 1u : 2u; } -/// Albedo and roughness of the palette entry modulated by its detail layer read in voxel space -/// Fragments keep the pattern of the volume they broke from through the record texture origin +/// Read in voxel space so fragments keep the pattern of their source volume through the record texture origin void applyDetail(PaletteSample palette, VolumeRecord record, RayHit hit, float3 cellPosition, float3 voxelsPerPixel, inout float3 albedo, inout float roughness, out float2 slope) { diff --git a/engine/assets/shaders/voxel_glass.slang b/engine/assets/shaders/voxel_glass.slang index bad2480a4..87d9cd98a 100644 --- a/engine/assets/shaders/voxel_glass.slang +++ b/engine/assets/shaders/voxel_glass.slang @@ -22,7 +22,7 @@ struct GlassPush uint refractionVoxels; /// Lit glass surfaces per brick and pixel past which layers only absorb uint litSurfaces; - /// 1 when gBackdropDepth holds this frame's opaque depth and the pipeline keeps only glass in front of it + /// 1 when gBackdropDepth holds this frame opaque depth and the pipeline keeps only glass in front of it uint depthTest; }; diff --git a/engine/assets/shaders/voxel_lighting.slang b/engine/assets/shaders/voxel_lighting.slang index d0a96ad38..bfb86a32c 100644 --- a/engine/assets/shaders/voxel_lighting.slang +++ b/engine/assets/shaders/voxel_lighting.slang @@ -83,8 +83,7 @@ Sampler2D gNoisySpecular; [[vk::binding(10, 2)]] Sampler2D gDetailNormal; -/// Half resolution clipmap gather of fragmentGiGather with xyz irradiance over pi and w the open sky share -/// or below 0 where it gathered nothing +/// Half resolution fragmentGiGather with xyz irradiance over pi w open sky share and below 0 for none [[vk::binding(11, 2)]] Sampler2D gGiGather; @@ -415,7 +414,7 @@ static const uint kReuseSpatial = 2u; static const uint kSceneGlass = 4u; static const uint kAmbientRayQuery = 8u; static const uint kTracedSpecular = 16u; -/// Mirrors VoxelPass k_gi_gather and set when gGiGather holds this frame's half resolution gather +/// Mirrors VoxelPass k_gi_gather and set when gGiGather holds this frame half resolution gather static const uint kGiGather = 32u; /// Mirrors VoxelPass k_gi_clipmap static const uint kGiClipmap = 64u; diff --git a/engine/assets/shaders/voxel_mesh.slang b/engine/assets/shaders/voxel_mesh.slang index b1b3e87e0..026d52c16 100644 --- a/engine/assets/shaders/voxel_mesh.slang +++ b/engine/assets/shaders/voxel_mesh.slang @@ -63,8 +63,7 @@ void quadMeshMain(uint3 group : SV_GroupID, uint thread : SV_GroupIndex, in payl } GroupMemoryBarrierWithGroupSync(); - // A quad with all four corners outside one frustum plane covers no pixel so it never becomes a vertex - // The survivors compact through a scan and the vertex and triangle counts shrink to them + // Quads with all corners outside one frustum plane drop and the survivors compact through a scan QuadVSOutput corners[4]; uint packedQuad = 0u; bool visible = false; diff --git a/engine/assets/shaders/voxel_mesh_task.slang b/engine/assets/shaders/voxel_mesh_task.slang index 5afb65f91..832bd14e9 100644 --- a/engine/assets/shaders/voxel_mesh_task.slang +++ b/engine/assets/shaders/voxel_mesh_task.slang @@ -25,8 +25,7 @@ struct CameraBrickView : IBrickView } } -/// Brick of a cell for the n th thread so the bricks nearest the eye come first and early depth rejects the rest -/// The axis the eye is farthest from the cell along orders slowest and an axis flips when the eye sits on its high side +/// Bricks nearest the eye come first so early depth rejects the rest uint nearToFarBrick(uint linear, float3 eyeToCell) { const float3 distance = abs(eyeToCell); diff --git a/engine/src/toast/assets/animation.cpp b/engine/src/toast/assets/animation.cpp index eb0063f91..a9f80a442 100644 --- a/engine/src/toast/assets/animation.cpp +++ b/engine/src/toast/assets/animation.cpp @@ -1,97 +1,13 @@ #include "animation.hpp" +#include "binary_io.hpp" + namespace assets { namespace { -/// @brief Bounds-checked sequential reader over the .tanim byte blob -/// -/// Every read goes through here so a truncated or corrupt file fails on the read that runs off the end -/// rather than quietly returning garbage that only shows up as a broken pose much later -class Reader { -public: - explicit Reader(std::span data) : m_data(data) { } - - template - auto read() -> T { - static_assert(std::is_trivially_copyable_v); - if (m_offset + sizeof(T) > m_data.size()) { - m_overflowed = true; - return T {}; - } - T value {}; - std::memcpy(&value, m_data.data() + m_offset, sizeof(T)); - m_offset += sizeof(T); - return value; - } - - auto readString() -> std::string { - const auto length = read(); - if (m_overflowed || m_offset + length > m_data.size()) { - m_overflowed = true; - return {}; - } - std::string value(reinterpret_cast(m_data.data() + m_offset), length); - m_offset += length; - return value; - } - - /// @brief Reads a length-prefixed array of trivially copyable values - template - auto readArray() -> std::vector { - const auto count = read(); - if (m_overflowed || m_offset + (static_cast(count) * sizeof(T)) > m_data.size()) { - m_overflowed = true; - return {}; - } - std::vector values(count); - if (count > 0) { - std::memcpy(values.data(), m_data.data() + m_offset, static_cast(count) * sizeof(T)); - m_offset += static_cast(count) * sizeof(T); - } - return values; - } - - [[nodiscard]] - auto overflowed() const -> bool { - return m_overflowed; - } - -private: - std::span m_data; - size_t m_offset = 0; - bool m_overflowed = false; -}; - -/// @brief Append-only writer producing the layout Reader expects -class Writer { -public: - template - void write(const T& value) { - static_assert(std::is_trivially_copyable_v); - const auto* bytes = reinterpret_cast(&value); - m_data.insert(m_data.end(), bytes, bytes + sizeof(T)); - } - - void writeString(const std::string& value) { - write(static_cast(value.size())); - m_data.insert(m_data.end(), value.begin(), value.end()); - } - - template - void writeArray(const std::vector& values) { - write(static_cast(values.size())); - if (!values.empty()) { - const auto* bytes = reinterpret_cast(values.data()); - m_data.insert(m_data.end(), bytes, bytes + (values.size() * sizeof(T))); - } - } - - auto take() -> std::vector { return std::move(m_data); } - -private: - std::vector m_data; -}; +using _detail::Reader; +using _detail::Writer; constexpr std::array k_magic {'T', 'A', 'N', 'M'}; @@ -200,20 +116,6 @@ auto AnimationTrack::sampleQuat(float time) const -> glm::quat { return glm::normalize(glm::slerp(quat_values[index], quat_values[index + 1], t)); } -auto Skin::jointMatrices(std::span joint_world_transforms) const -> std::vector { - ZoneScoped; - std::vector matrices(joints.size(), glm::mat4(1.0f)); - - for (size_t i = 0; i < joints.size(); ++i) { - const glm::mat4 world = i < joint_world_transforms.size() ? joint_world_transforms[i] : glm::mat4(1.0f); - // An empty inverse-bind array is legal in glTF and means identity for every joint - const glm::mat4 inverse_bind = i < inverse_bind_matrices.size() ? inverse_bind_matrices[i] : glm::mat4(1.0f); - matrices[i] = world * inverse_bind; - } - - return matrices; -} - auto AnimationClip::sample(float time) const -> std::unordered_map { ZoneScoped; std::unordered_map poses; @@ -254,15 +156,6 @@ void AnimationClip::sampleInto(float time, std::span track_to_bon } } -auto Skeleton::find(std::string_view bone_name) const -> int32_t { - for (size_t i = 0; i < bones.size(); ++i) { - if (bones[i].name == bone_name) { - return static_cast(i); - } - } - return -1; -} - Animation::Animation(std::span data) { ZoneScoped; Reader reader(data); @@ -281,137 +174,42 @@ Animation::Animation(std::span data) { return; } - const auto clip_count = reader.read(); - m_clips.reserve(clip_count); - for (uint32_t i = 0; i < clip_count && !reader.overflowed(); ++i) { - AnimationClip clip; - clip.name = reader.readString(); - clip.duration = reader.read(); - - const auto track_count = reader.read(); - clip.tracks.reserve(track_count); - for (uint32_t t = 0; t < track_count && !reader.overflowed(); ++t) { - AnimationTrack track; - track.target_node = reader.readString(); - track.target = static_cast(reader.read()); - track.interpolation = static_cast(reader.read()); - track.times = reader.readArray(); - track.vec3_values = reader.readArray(); - track.quat_values = reader.readArray(); - clip.tracks.push_back(std::move(track)); - } - m_clips.push_back(std::move(clip)); - } - - const auto skin_count = reader.read(); - m_skins.reserve(skin_count); - for (uint32_t i = 0; i < skin_count && !reader.overflowed(); ++i) { - Skin skin; - skin.name = reader.readString(); - skin.skeleton_root = reader.readString(); - - const auto joint_count = reader.read(); - skin.joints.reserve(joint_count); - for (uint32_t j = 0; j < joint_count && !reader.overflowed(); ++j) { - skin.joints.push_back(reader.readString()); - } - skin.inverse_bind_matrices = reader.readArray(); - m_skins.push_back(std::move(skin)); - } - - const auto skeleton_count = reader.read(); - m_skeletons.reserve(skeleton_count); - for (uint32_t i = 0; i < skeleton_count && !reader.overflowed(); ++i) { - Skeleton skeleton; - skeleton.name = reader.readString(); - const auto bone_count = reader.read(); - skeleton.bones.reserve(bone_count); - for (uint32_t b = 0; b < bone_count && !reader.overflowed(); ++b) { - Bone bone; - bone.name = reader.readString(); - bone.parent = reader.read(); - bone.rest = reader.read(); - // Parent below child is what lets SkeletalNode pose in one forward pass - if (bone.parent >= static_cast(b)) { - bone.parent = -1; - } - skeleton.bones.push_back(std::move(bone)); - } - m_skeletons.push_back(std::move(skeleton)); + m_clip.name = reader.readString(); + m_clip.duration = reader.read(); + const auto track_count = reader.read(); + m_clip.tracks.reserve(track_count); + for (uint32_t t = 0; t < track_count && !reader.overflowed(); ++t) { + AnimationTrack track; + track.target_node = reader.readString(); + track.target = static_cast(reader.read()); + track.interpolation = static_cast(reader.read()); + track.times = reader.readArray(); + track.vec3_values = reader.readArray(); + track.quat_values = reader.readArray(); + m_clip.tracks.push_back(std::move(track)); } if (reader.overflowed()) { - TOAST_ERROR("Animation", "Truncated .tanim file; loaded {} clip(s) before running out of data", m_clips.size()); - } -} - -auto Animation::findClip(std::string_view name) const -> const AnimationClip* { - for (const auto& clip : m_clips) { - if (clip.name == name) { - return &clip; - } + TOAST_ERROR("Animation", "Truncated .tanim file '{}'", m_clip.name); } - return nullptr; } -auto Animation::findSkeleton(std::string_view name) const -> const Skeleton* { - if (name.empty()) { - return m_skeletons.empty() ? nullptr : &m_skeletons.front(); - } - for (const auto& skeleton : m_skeletons) { - if (skeleton.name == name) { - return &skeleton; - } - } - return nullptr; -} - -auto Animation::toBinary( - const std::vector& clips, const std::vector& skins, const std::vector& skeletons -) -> std::vector { +auto Animation::toBinary(const AnimationClip& clip) -> std::vector { ZoneScoped; Writer writer; writer.write(k_magic); writer.write(_detail::animation_format_version); - - writer.write(static_cast(clips.size())); - for (const auto& clip : clips) { - writer.writeString(clip.name); - writer.write(clip.duration); - - writer.write(static_cast(clip.tracks.size())); - for (const auto& track : clip.tracks) { - writer.writeString(track.target_node); - writer.write(static_cast(track.target)); - writer.write(static_cast(track.interpolation)); - writer.writeArray(track.times); - writer.writeArray(track.vec3_values); - writer.writeArray(track.quat_values); - } + writer.writeString(clip.name); + writer.write(clip.duration); + writer.write(static_cast(clip.tracks.size())); + for (const auto& track : clip.tracks) { + writer.writeString(track.target_node); + writer.write(static_cast(track.target)); + writer.write(static_cast(track.interpolation)); + writer.writeArray(track.times); + writer.writeArray(track.vec3_values); + writer.writeArray(track.quat_values); } - - writer.write(static_cast(skins.size())); - for (const auto& skin : skins) { - writer.writeString(skin.name); - writer.writeString(skin.skeleton_root); - writer.write(static_cast(skin.joints.size())); - for (const auto& joint : skin.joints) { - writer.writeString(joint); - } - writer.writeArray(skin.inverse_bind_matrices); - } - - writer.write(static_cast(skeletons.size())); - for (const auto& skeleton : skeletons) { - writer.writeString(skeleton.name); - writer.write(static_cast(skeleton.bones.size())); - for (const auto& bone : skeleton.bones) { - writer.writeString(bone.name); - writer.write(bone.parent); - writer.write(bone.rest); - } - } - return writer.take(); } diff --git a/engine/src/toast/assets/animation.hpp b/engine/src/toast/assets/animation.hpp index 573ba554f..e2f093091 100644 --- a/engine/src/toast/assets/animation.hpp +++ b/engine/src/toast/assets/animation.hpp @@ -4,14 +4,12 @@ * * @brief Keyframe animation asset (.tanim), imported from glTF * - * One clip plus the skins it poses, one file per animation the glTF defines. Sampled by - * toast::AnimationPlayer, GPU-skinned by renderer::SkinningPass - * * Bump @ref _detail::animation_format_version on any layout change */ #pragma once #include "core_types.hpp" +#include "skeleton.hpp" #include #include @@ -27,7 +25,7 @@ namespace assets { namespace _detail { /// Binary layout version for .tanim; readers reject anything they don't recognise -inline constexpr uint32_t animation_format_version = 4; +inline constexpr uint32_t animation_format_version = 5; } /// @brief How a sampler interpolates between two keyframes, matching glTF's three modes @@ -96,28 +94,6 @@ struct NodePose { float _pad; }; -/// Local bone transform, trivially copyable since .tanim writes it raw -struct BonePose { - glm::quat rotation {1.0f, 0.0f, 0.0f, 0.0f}; - glm::vec3 translation {0.0f}; - glm::vec3 scale {1.0f}; -}; - -struct TOAST_API Bone { - std::string name; - int32_t parent = -1; ///< always below this bone index - BonePose rest; -}; - -struct TOAST_API Skeleton { - std::string name; - std::vector bones; - - /// @returns bone index or -1 - [[nodiscard]] - auto find(std::string_view bone_name) const -> int32_t; -}; - /// @brief A named set of tracks that play together struct TOAST_API AnimationClip { std::string name; @@ -146,45 +122,9 @@ struct TOAST_API AnimationClip { } }; -/** - * @brief A skeleton: the joint nodes a skinned mesh binds to - * - * jointMatrices() turns a posed node tree into the matrices a shader blends between. A mesh whose joints - * cannot be resolved gets no posed slice and falls back to bind pose rather than dropping - */ -struct TOAST_API Skin { - std::string name; - std::string skeleton_root; ///< node name, empty when glTF didn't specify one - std::vector joints; ///< node names, in the order joint indices refer to - std::vector inverse_bind_matrices; ///< parallel to joints; empty means identity for all - - /** - * @brief Builds the per-joint matrices a skinning shader multiplies vertices by - * - * `joint_world_transform * inverse_bind_matrix`, so the product expresses only deformation away from - * bind - which is what the vertex weights blend between - * - * @param joint_world_transforms World transforms of @ref joints, same order. A missing entry falls back - * to identity rather than being skipped, so the result always matches joints.size() and a shader - * can index it without bounds checks - * - * @note Supplied by the caller rather than walked here, so several instances can pose one skeleton asset - */ - [[nodiscard]] - auto jointMatrices(std::span joint_world_transforms) const -> std::vector; -}; - -/** - * @class Animation - * @brief A set of clips plus the skins they pose - * - * The format holds many clips, but the importer writes one per file so each is its own asset in the browser. - * Every file carries the skins too, so any one can pose the skeleton alone - and a glTF with skins but no - * animations still produces a clip-less file for MeshNode::skin_animation to point at - */ +/// One clip asset (.tanim) class TOAST_API Animation : public Asset { public: - /// @brief Parses the binary .tanim representation explicit Animation(std::span data); [[nodiscard]] @@ -193,38 +133,15 @@ class TOAST_API Animation : public Asset { } [[nodiscard]] - auto clips() const noexcept -> const std::vector& { - return m_clips; + auto clip() const noexcept -> const AnimationClip& { + return m_clip; } [[nodiscard]] - auto skins() const noexcept -> const std::vector& { - return m_skins; - } - - [[nodiscard]] - auto skeletons() const noexcept -> const std::vector& { - return m_skeletons; - } - - /// @returns the skeleton with this name, the first one for an empty name, or nullptr - [[nodiscard]] - auto findSkeleton(std::string_view name) const -> const Skeleton*; - - /// @returns the clip with this name, or nullptr - [[nodiscard]] - auto findClip(std::string_view name) const -> const AnimationClip*; - - /// @brief Serialises clips + skins into the binary .tanim layout the constructor reads back - [[nodiscard]] - static auto - toBinary(const std::vector& clips, const std::vector& skins, const std::vector& skeletons) - -> std::vector; + static auto toBinary(const AnimationClip& clip) -> std::vector; private: - std::vector m_clips; - std::vector m_skins; - std::vector m_skeletons; + AnimationClip m_clip; }; } diff --git a/engine/src/toast/assets/asset_manager.cpp b/engine/src/toast/assets/asset_manager.cpp index 99f552f85..bbc3bc5fe 100644 --- a/engine/src/toast/assets/asset_manager.cpp +++ b/engine/src/toast/assets/asset_manager.cpp @@ -603,7 +603,8 @@ auto isUiType(std::string_view type) -> bool { /// Types that cannot be rebuilt in place auto isReplacedOnReload(std::string_view type) -> bool { - return type == "mesh" || type == "texture" || type == "animation" || type == "schema" || type == "font" || type == "ui_image"; + return type == "mesh" || type == "texture" || type == "animation" || type == "skeleton" || type == "schema" || type == "font" || + type == "ui_image"; } auto isWatchedType(std::string_view type) -> bool { diff --git a/engine/src/toast/assets/asset_registry.cpp b/engine/src/toast/assets/asset_registry.cpp index 7d015e755..cd3ecdae3 100644 --- a/engine/src/toast/assets/asset_registry.cpp +++ b/engine/src/toast/assets/asset_registry.cpp @@ -35,6 +35,7 @@ void AssetRegistry::init() { s_raw["image_localization"] = [](std::vector d) { return std::make_unique(std::move(d)); }; s_raw["shader"] = [](std::vector d) { return std::make_unique(std::move(d)); }; s_raw["animation"] = [](const std::vector& d) { return std::make_unique(d); }; + s_raw["skeleton"] = [](const std::vector& d) { return std::make_unique(d); }; s_raw["voxel_model"] = [](const std::vector& d) { return std::make_unique(d); }; // Plain TOML loaders diff --git a/engine/src/toast/assets/binary_io.hpp b/engine/src/toast/assets/binary_io.hpp new file mode 100644 index 000000000..8d744265c --- /dev/null +++ b/engine/src/toast/assets/binary_io.hpp @@ -0,0 +1,100 @@ +/** + * @file binary_io.hpp + * @author dario + * @date 13 Nov 2026 + */ + +#pragma once +#include +#include +#include +#include +#include +#include + +namespace assets::_detail { + +class Reader { +public: + explicit Reader(std::span data) : m_data(data) { } + + template + auto read() -> T { + static_assert(std::is_trivially_copyable_v); + if (m_offset + sizeof(T) > m_data.size()) { + m_overflowed = true; + return T {}; + } + T value {}; + std::memcpy(&value, m_data.data() + m_offset, sizeof(T)); + m_offset += sizeof(T); + return value; + } + + auto readString() -> std::string { + const auto length = read(); + if (m_overflowed || m_offset + length > m_data.size()) { + m_overflowed = true; + return {}; + } + std::string value(reinterpret_cast(m_data.data() + m_offset), length); + m_offset += length; + return value; + } + + template + auto readArray() -> std::vector { + const auto count = read(); + if (m_overflowed || m_offset + (static_cast(count) * sizeof(T)) > m_data.size()) { + m_overflowed = true; + return {}; + } + std::vector values(count); + if (count > 0) { + std::memcpy(values.data(), m_data.data() + m_offset, static_cast(count) * sizeof(T)); + m_offset += static_cast(count) * sizeof(T); + } + return values; + } + + [[nodiscard]] + auto overflowed() const -> bool { + return m_overflowed; + } + +private: + std::span m_data; + size_t m_offset = 0; + bool m_overflowed = false; +}; + +class Writer { +public: + template + void write(const T& value) { + static_assert(std::is_trivially_copyable_v); + const auto* bytes = reinterpret_cast(&value); + m_data.insert(m_data.end(), bytes, bytes + sizeof(T)); + } + + void writeString(const std::string& value) { + write(static_cast(value.size())); + m_data.insert(m_data.end(), value.begin(), value.end()); + } + + template + void writeArray(const std::vector& values) { + write(static_cast(values.size())); + if (!values.empty()) { + const auto* bytes = reinterpret_cast(values.data()); + m_data.insert(m_data.end(), bytes, bytes + (values.size() * sizeof(T))); + } + } + + auto take() -> std::vector { return std::move(m_data); } + +private: + std::vector m_data; +}; + +} diff --git a/engine/src/toast/assets/gltf_importer.cpp b/engine/src/toast/assets/gltf_importer.cpp index 3184999e6..bf50c2d22 100644 --- a/engine/src/toast/assets/gltf_importer.cpp +++ b/engine/src/toast/assets/gltf_importer.cpp @@ -1061,29 +1061,24 @@ auto generateIntermediates(const std::filesystem::path& path) { ); } - // One .tanim per clip, not per glTF: six clips in one file is one asset-browser entry, with nothing to - // drag per animation. Each carries the skins too - small next to keyframe data, and it keeps every clip - // able to pose the skeleton alone - // - // Named here rather than at save time because the scene JSON references them by bare filename + // The scene JSON references each .tanim and .tskel by bare filename const std::string animation_base = path.stem().string(); + // glTF names are free text that would break the path or the stem GltfImporter.cs keys its UID maps by + const auto sanitize_file_name = [](std::string_view name, std::string fallback) { + std::string sanitized; + sanitized.reserve(name.size()); + for (const char c : name) { + const bool keep = std::isalnum(static_cast(c)) != 0 || c == '_' || c == '-'; + sanitized.push_back(keep ? c : '_'); + } + return sanitized.empty() ? fallback : sanitized; + }; std::vector animation_file_names; animation_file_names.reserve(clips.size()); { std::unordered_map animation_name_counts; for (size_t i = 0; i < clips.size(); ++i) { - // glTF clip names are free text ("Armature|Run Cycle.001"); anything outside this set would either - // break the path or split the stem GltfImporter.cs keys its UID map by - std::string sanitized; - sanitized.reserve(clips[i].name.size()); - for (const char c : clips[i].name) { - const bool keep = std::isalnum(static_cast(c)) != 0 || c == '_' || c == '-'; - sanitized.push_back(keep ? c : '_'); - } - if (sanitized.empty()) { - sanitized = "clip_" + std::to_string(i); - } - + const std::string sanitized = sanitize_file_name(clips[i].name, "clip_" + std::to_string(i)); std::string file_name = animation_base + "_" + sanitized; if (auto it = animation_name_counts.find(file_name); it != animation_name_counts.end()) { file_name = file_name + "_" + std::to_string(it->second); @@ -1098,10 +1093,6 @@ auto generateIntermediates(const std::filesystem::path& path) { } } - // A glTF can define a skeleton with no animation at all, and MeshNode::skin_animation still needs a file - // to point at - that case keeps the old single ".tanim" holding skins and no clips - const std::string skin_file_name = animation_file_names.empty() ? animation_base : animation_file_names.front(); - // Scenes std::vector scenes; scenes.reserve(model.scenes_count); @@ -1236,7 +1227,13 @@ auto generateIntermediates(const std::filesystem::path& path) { std::vector skinned_nodes; }; - std::vector skeletons; + struct SkeletonData { + std::string name; + std::vector bones; + std::vector skins; + }; + + std::vector skeletons; std::vector skeleton_plans; std::vector skin_skeleton(skins.size(), -1); std::vector node_skeleton(node_count, -1); @@ -1306,7 +1303,7 @@ auto generateIntermediates(const std::filesystem::path& path) { } const auto skeleton_index = static_cast(skeletons.size()); - Skeleton skeleton; + SkeletonData skeleton; skeleton.name = plan.host >= 0 ? node_name_at(plan.host) : node_name_at(roots.front()); // Depth first so a parent always precedes its children @@ -1333,12 +1330,32 @@ auto generateIntermediates(const std::filesystem::path& path) { for (size_t other = 0; other < skins.size(); ++other) { if (group_of(other) == group) { skin_skeleton[other] = skeleton_index; + skeleton.skins.push_back(skins[other]); } } skeletons.push_back(std::move(skeleton)); skeleton_plans.push_back(std::move(plan)); } + std::vector skeleton_file_names; + skeleton_file_names.reserve(skeletons.size()); + for (size_t sk = 0; sk < skeletons.size(); ++sk) { + std::string file_name = animation_base + "_" + sanitize_file_name(skeletons[sk].name, "skeleton"); + if (std::ranges::find(skeleton_file_names, file_name) != skeleton_file_names.end()) { + file_name += "_" + std::to_string(sk); + } + skeleton_file_names.push_back(std::move(file_name)); + } + + // Every clip of the glTF goes into each Clips list, names are bare file names patched to UIDs later + const auto clip_file_list = [&] { + nlohmann::json list = nlohmann::json::array(); + for (const auto& file_name : animation_file_names) { + list.push_back(file_name); + } + return list; + }; + // Skinned meshes move directly under their SkeletalNode, glTF ignores their transform anyway std::vector pulled_skeleton(node_count, -1); for (int32_t i = 0; i < node_count; ++i) { @@ -1392,13 +1409,9 @@ auto generateIntermediates(const std::filesystem::path& path) { // skin - node.skin indexes model.skins, which parses 1:1 into `skins` earlier in this function const bool has_skin = node.skin != -1 && std::cmp_less(node.skin, skins.size()); const auto apply_skin_params = [&](nlohmann::json& target) { - if (!has_skin) { - return; + if (has_skin) { + target["params"]["skin_name"] = skins[node.skin].name; } - // Bare filename, no extension, matching how "mesh"/"material" reference their targets and what - // GltfImporter.cs keys animationUids by. Patched to a UID there - target["params"]["skin_animation"] = skin_file_name; - target["params"]["skin_name"] = skins[node.skin].name; }; if (gltf_mesh.primitives_count == 1) { @@ -1518,11 +1531,10 @@ auto generateIntermediates(const std::filesystem::path& path) { n["name"] = skeletons[sk].name + " Skeleton"; n["type"] = "toast::SkeletalNode"; n["transform"] = pose_json(BonePose {}); - // Bare filename patched to a UID by GltfImporter.cs, every .tanim carries the skeletons - n["params"]["animation"] = skin_file_name; - n["params"]["skeleton_name"] = skeletons[sk].name; + n["params"]["skeleton"] = skeleton_file_names[sk]; + n["params"]["clips"] = clip_file_list(); if (!clips.empty()) { - n["params"]["clip"] = clips.front().name; + n["params"]["autoplay"] = clips.front().name; } n["children"] = nlohmann::json::array(); @@ -1597,12 +1609,8 @@ auto generateIntermediates(const std::filesystem::path& path) { }); if (needs_player) { scene_json["type"] = "toast::AnimationPlayer"; - // The first clip's asset, since a player holds one animation at a time; the rest import alongside - // it as their own assets for the user to swap in. Bare filename, see skin_animation above - scene_json["params"]["animation"] = skin_file_name; - if (!clips.empty()) { - scene_json["params"]["clip"] = clips.front().name; - } + scene_json["params"]["clips"] = clip_file_list(); + scene_json["params"]["autoplay"] = clips.front().name; } scenes.push_back(std::move(scene_json)); @@ -1658,23 +1666,18 @@ auto generateIntermediates(const std::filesystem::path& path) { } TOAST_TRACE("AssetManager", "Saved {} materials", materials.size()); - // Save animations - one .tanim per clip, each with this glTF's skins alongside it (see - // animation_file_names above for why) for (size_t i = 0; i < clips.size(); ++i) { - const auto binary = Animation::toBinary({clips[i]}, skins, skeletons); - const std::filesystem::path out = cache_dir / (animation_file_names[i] + ".tanim"); - std::ofstream f(out, std::ios::binary); + const auto binary = Animation::toBinary(clips[i]); + std::ofstream f(cache_dir / (animation_file_names[i] + ".tanim"), std::ios::binary); f.write(reinterpret_cast(binary.data()), static_cast(binary.size())); } - if (clips.empty() && !skins.empty()) { - // Skeleton with no animation: still needs a file for MeshNode::skin_animation to resolve against - const auto binary = Animation::toBinary({}, skins, skeletons); - const std::filesystem::path out = cache_dir / (skin_file_name + ".tanim"); - std::ofstream f(out, std::ios::binary); + for (size_t sk = 0; sk < skeletons.size(); ++sk) { + const auto binary = Skeleton::toBinary(skeletons[sk].name, skeletons[sk].bones, skeletons[sk].skins); + std::ofstream f(cache_dir / (skeleton_file_names[sk] + ".tskel"), std::ios::binary); f.write(reinterpret_cast(binary.data()), static_cast(binary.size())); } - if (!clips.empty() || !skins.empty()) { - TOAST_TRACE("AssetManager", "Saved {} animation asset(s), {} skin(s) each", std::max(clips.size(), 1), skins.size()); + if (!clips.empty() || !skeletons.empty()) { + TOAST_TRACE("AssetManager", "Saved {} animation asset(s), {} skeleton asset(s)", clips.size(), skeletons.size()); } // Save scenes @@ -1776,50 +1779,37 @@ static void jsonToTnode(const nlohmann::json& scene_json, const std::filesystem: ); } } - if (params.contains("skin_animation")) { - const auto skin_uid = params["skin_animation"].get(); - if (skin_uid.size() == 11) { - basic.fields.push_back( - {"m_skin_animation", toast::FieldType::uid_t, false, toast::UID(toast::UID::fromString(skin_uid))} - ); - } else { - TOAST_WARN( - "AssetManager", - "GLTF scene contains non-UID skin_animation reference '{}'; skipping m_skin_animation assignment", - skin_uid - ); - } - } if (params.contains("skin_name")) { basic.fields.push_back({"m_skin_name", toast::FieldType::string_t, false, params["skin_name"].get()}); } } - // AnimationPlayer: "animation" is the .tanim UID (patched by GltfImporter.cs like mesh/material - // above), "clip" is a plain string naming which clip to autoplay + // "skeleton" and "clips" are UIDs patched by GltfImporter.cs like mesh and material above else if ((basic.type == "toast::AnimationPlayer" || basic.type == "toast::SkeletalNode") && n.contains("params")) { const auto& params = n["params"]; - if (params.contains("animation")) { - const auto animation_uid = params["animation"].get(); - if (animation_uid.size() == 11) { - basic.fields.push_back( - {"m_animation", toast::FieldType::uid_t, false, toast::UID(toast::UID::fromString(animation_uid))} - ); - } else { - TOAST_WARN( - "AssetManager", - "GLTF scene contains non-UID animation reference '{}'; skipping m_animation assignment", - animation_uid - ); + const auto to_uid = [](const std::string& text) -> std::optional { + if (text.size() != 11) { + TOAST_WARN("AssetManager", "GLTF scene contains non-UID animation reference '{}'; skipping it", text); + return std::nullopt; + } + return toast::UID(toast::UID::fromString(text)); + }; + if (params.contains("skeleton")) { + if (const auto uid = to_uid(params["skeleton"].get())) { + basic.fields.push_back({"m_skeleton", toast::FieldType::uid_t, false, *uid}); } } - if (params.contains("clip")) { - basic.fields.push_back({"m_clip_name", toast::FieldType::string_t, false, params["clip"].get()}); + if (params.contains("clips")) { + std::vector clip_uids; + for (const auto& clip : params["clips"]) { + if (const auto uid = to_uid(clip.get())) { + clip_uids.push_back(*uid); + } + } + basic.fields.push_back({"m_clips", toast::FieldType::uid_t, true, std::move(clip_uids)}); } - if (params.contains("skeleton_name")) { - basic.fields.push_back( - {"m_skeleton_name", toast::FieldType::string_t, false, params["skeleton_name"].get()} - ); + if (params.contains("autoplay")) { + basic.fields.push_back({"m_autoplay", toast::FieldType::string_t, false, params["autoplay"].get()}); } } diff --git a/engine/src/toast/assets/skeleton.cpp b/engine/src/toast/assets/skeleton.cpp new file mode 100644 index 000000000..1dc8933e3 --- /dev/null +++ b/engine/src/toast/assets/skeleton.cpp @@ -0,0 +1,121 @@ +#include "skeleton.hpp" + +#include "binary_io.hpp" + +namespace assets { + +namespace { + +constexpr std::array k_magic {'T', 'S', 'K', 'L'}; + +} + +auto Skin::jointMatrices(std::span joint_world_transforms) const -> std::vector { + ZoneScoped; + std::vector matrices(joints.size(), glm::mat4(1.0f)); + for (size_t i = 0; i < joints.size(); ++i) { + const glm::mat4 world = i < joint_world_transforms.size() ? joint_world_transforms[i] : glm::mat4(1.0f); + const glm::mat4 inverse_bind = i < inverse_bind_matrices.size() ? inverse_bind_matrices[i] : glm::mat4(1.0f); + matrices[i] = world * inverse_bind; + } + return matrices; +} + +Skeleton::Skeleton(std::span data) { + ZoneScoped; + _detail::Reader reader(data); + + if (reader.read>() != k_magic) { + TOAST_ERROR("Animation", "Not a .tskel file (bad magic)"); + return; + } + const auto version = reader.read(); + if (version != _detail::skeleton_format_version) { + TOAST_ERROR( + "Animation", "Unsupported .tskel format version {} (this build reads {})", version, _detail::skeleton_format_version + ); + return; + } + + m_name = reader.readString(); + const auto bone_count = reader.read(); + m_bones.reserve(bone_count); + for (uint32_t b = 0; b < bone_count && !reader.overflowed(); ++b) { + Bone bone; + bone.name = reader.readString(); + bone.parent = reader.read(); + bone.rest = reader.read(); + // Parent below child is what lets SkeletalNode pose in one forward pass + if (bone.parent >= static_cast(b)) { + bone.parent = -1; + } + m_bones.push_back(std::move(bone)); + } + + const auto skin_count = reader.read(); + m_skins.reserve(skin_count); + for (uint32_t s = 0; s < skin_count && !reader.overflowed(); ++s) { + Skin skin; + skin.name = reader.readString(); + skin.skeleton_root = reader.readString(); + const auto joint_count = reader.read(); + skin.joints.reserve(joint_count); + for (uint32_t j = 0; j < joint_count && !reader.overflowed(); ++j) { + skin.joints.push_back(reader.readString()); + } + skin.inverse_bind_matrices = reader.readArray(); + m_skins.push_back(std::move(skin)); + } + + if (reader.overflowed()) { + TOAST_ERROR("Animation", "Truncated .tskel file '{}'", m_name); + } +} + +auto Skeleton::find(std::string_view bone_name) const -> int32_t { + for (size_t i = 0; i < m_bones.size(); ++i) { + if (m_bones[i].name == bone_name) { + return static_cast(i); + } + } + return -1; +} + +auto Skeleton::findSkin(std::string_view skin_name) const -> const Skin* { + if (skin_name.empty()) { + return m_skins.empty() ? nullptr : &m_skins.front(); + } + for (const auto& skin : m_skins) { + if (skin.name == skin_name) { + return &skin; + } + } + return nullptr; +} + +auto Skeleton::toBinary(std::string_view name, std::span bones, std::span skins) -> std::vector { + ZoneScoped; + _detail::Writer writer; + writer.write(k_magic); + writer.write(_detail::skeleton_format_version); + writer.writeString(std::string(name)); + writer.write(static_cast(bones.size())); + for (const auto& bone : bones) { + writer.writeString(bone.name); + writer.write(bone.parent); + writer.write(bone.rest); + } + writer.write(static_cast(skins.size())); + for (const auto& skin : skins) { + writer.writeString(skin.name); + writer.writeString(skin.skeleton_root); + writer.write(static_cast(skin.joints.size())); + for (const auto& joint : skin.joints) { + writer.writeString(joint); + } + writer.writeArray(skin.inverse_bind_matrices); + } + return writer.take(); +} + +} diff --git a/engine/src/toast/assets/skeleton.hpp b/engine/src/toast/assets/skeleton.hpp new file mode 100644 index 000000000..f3193b162 --- /dev/null +++ b/engine/src/toast/assets/skeleton.hpp @@ -0,0 +1,92 @@ +/** + * @file skeleton.hpp + * @author dario + * @date 13 Nov 2026 + */ + +#pragma once +#include "core_types.hpp" + +#include +#include +#include +#include +#include +#include +#include + +namespace assets { + +namespace _detail { +inline constexpr uint32_t skeleton_format_version = 1; +} + +/// Local bone transform, trivially copyable since .tskel writes it raw +struct BonePose { + glm::quat rotation {1.0f, 0.0f, 0.0f, 0.0f}; + glm::vec3 translation {0.0f}; + glm::vec3 scale {1.0f}; +}; + +struct TOAST_API Bone { + std::string name; + int32_t parent = -1; ///< always below this bone index + BonePose rest; +}; + +/// Joint names and inverse bind matrices a skinned mesh binds with +struct TOAST_API Skin { + std::string name; + std::string skeleton_root; ///< node name, empty when glTF gives none + std::vector joints; ///< bone names in the order vertex joint indices use + std::vector inverse_bind_matrices; ///< parallel to joints, empty means identity for all + + /// `joint_world * inverse_bind` per joint, a missing world entry counts as identity so the size always matches + [[nodiscard]] + auto jointMatrices(std::span joint_world_transforms) const -> std::vector; +}; + +/// Bone hierarchy (.tskel) posed by toast::SkeletalNode, plus the skins bound to it +class TOAST_API Skeleton : public Asset { +public: + explicit Skeleton(std::span data); + + [[nodiscard]] + auto type() const -> std::string_view override { + return "skeleton"; + } + + [[nodiscard]] + auto name() const noexcept -> const std::string& { + return m_name; + } + + /// Parent always precedes child + [[nodiscard]] + auto bones() const noexcept -> const std::vector& { + return m_bones; + } + + [[nodiscard]] + auto skins() const noexcept -> const std::vector& { + return m_skins; + } + + /// @returns bone index or -1 + [[nodiscard]] + auto find(std::string_view bone_name) const -> int32_t; + + /// @returns the skin with this name, the first one for an empty name, or nullptr + [[nodiscard]] + auto findSkin(std::string_view skin_name) const -> const Skin*; + + [[nodiscard]] + static auto toBinary(std::string_view name, std::span bones, std::span skins) -> std::vector; + +private: + std::string m_name; + std::vector m_bones; + std::vector m_skins; +}; + +} diff --git a/engine/src/toast/assets/types.hpp b/engine/src/toast/assets/types.hpp index 4ba919633..30880b74e 100644 --- a/engine/src/toast/assets/types.hpp +++ b/engine/src/toast/assets/types.hpp @@ -25,6 +25,7 @@ #include "schema.hpp" #include "script.hpp" #include "shader.hpp" +#include "skeleton.hpp" #include "texture.hpp" #include diff --git a/engine/src/toast/backtrace.cpp b/engine/src/toast/backtrace.cpp index 3a9dd69f3..1842b2903 100644 --- a/engine/src/toast/backtrace.cpp +++ b/engine/src/toast/backtrace.cpp @@ -18,7 +18,7 @@ namespace { constexpr std::size_t k_kept_frames = 16; -// Tracy symbolizes heap callstacks through dbghelp, which is not thread safe, so the logger stays out of it then +// dbghelp is not thread safe and Tracy symbolizes heap callstacks through it #if defined(_WIN32) && defined(TRACY_ENABLE) && defined(TOAST_TRACK_HEAP) && TOAST_HEAP_CALLSTACK_DEPTH > 0 #define TOAST_BACKTRACE_AVOID_DBGHELP #endif @@ -29,8 +29,7 @@ std::uint64_t g_cache_generation = 0; #ifdef _WIN32 std::unordered_set g_symbol_loaded_modules; -// we need to unload pdbs since the backtrace of the logs loads them for logging -// this is only a problem on windows btw +// log backtraces load pdbs that need unloading void unloadDbghelpSymbols() noexcept { using EnumCallback = BOOL(CALLBACK*)(PCSTR, DWORD64, PVOID); using EnumModules = BOOL(WINAPI*)(HANDLE, EnumCallback, PVOID); @@ -197,7 +196,7 @@ auto captureBacktrace(std::size_t skip) noexcept -> RawBacktrace { std::array addresses {}; const int captured = backtrace(addresses.data(), static_cast(skipped + RawBacktrace::k_capture_depth)); for (int i = static_cast(skipped); i < captured; ++i) { - // Return addresses point past the call, one back lands inside it as cpptrace's own capture does + // Return addresses point past the call so one back lands inside it like cpptrace does trace.frames[trace.count++] = reinterpret_cast(addresses[static_cast(i)]) - 1; } } diff --git a/engine/src/toast/engine.cpp b/engine/src/toast/engine.cpp index 583033b7e..fe24798c7 100644 --- a/engine/src/toast/engine.cpp +++ b/engine/src/toast/engine.cpp @@ -126,8 +126,8 @@ auto addScenePasses( const auto scene_format = renderer.getSceneColorFormat(); // Before the passes whose scene sets bind its cascades - // auto gi_pass = std::make_unique(core, scene_format, extent); - // renderer.setGiPass(gi_pass.get()); + auto gi_pass = std::make_unique(core, scene_format, extent); + renderer.setGiPass(gi_pass.get()); auto gi_clipmap_pass = std::make_unique(core, scene_format, extent); renderer.setGiClipmapPass(gi_clipmap_pass.get()); @@ -141,7 +141,7 @@ auto addScenePasses( renderer.addRenderPass(std::make_unique(core, scene_format, depth_format, extent)); // First in the chain so the probes read depth before any post pass - // renderer.addPostProcessPass(std::move(gi_pass)); + renderer.addPostProcessPass(std::move(gi_pass)); renderer.addPostProcessPass(std::move(gi_clipmap_pass)); if (core.isRayTracingSupported()) { diff --git a/engine/src/toast/events/signal_bindings.hpp b/engine/src/toast/events/signal_bindings.hpp index 132e88358..dc66963db 100644 --- a/engine/src/toast/events/signal_bindings.hpp +++ b/engine/src/toast/events/signal_bindings.hpp @@ -38,9 +38,7 @@ TOAST_API auto literalToAny(const std::type_info& type, std::string_view literal [[nodiscard]] TOAST_API auto literalToLuaAny(std::string_view lua_type, std::string_view literal) -> std::any; -/** - * @brief Converts a value so it matches the exact type a parameter expects - */ +/// Matches the exact type a parameter expects [[nodiscard]] TOAST_API auto coerce(const std::any& value, const std::type_info& type) -> std::any; @@ -49,10 +47,6 @@ TOAST_API auto resolveBindings( toast::Node& target, std::string_view function, std::span bindings, size_t signal_arg_count ) -> std::optional>; -/** - * @brief Calls function on target with the arguments the bindings pick - * @param signal_args the values the signal was fired with - */ TOAST_API void invokeBound( toast::Node& target, std::string_view function, std::span bindings, std::span signal_args diff --git a/engine/src/toast/heap_tracking.cpp b/engine/src/toast/heap_tracking.cpp index fbf1984d2..5d6042753 100644 --- a/engine/src/toast/heap_tracking.cpp +++ b/engine/src/toast/heap_tracking.cpp @@ -4,8 +4,7 @@ * @date 2026-11-02 */ -// Replaces the global allocation functions of toast_engine so Tracy sees every C++ heap allocation -// Everything forwards to malloc and free so memory still crosses DLL boundaries safely +// Forwards to malloc and free so memory still crosses DLL boundaries #if defined(TRACY_ENABLE) && defined(TOAST_TRACK_HEAP) #include @@ -25,9 +24,7 @@ namespace { -/// Addresses Tracy currently believes are live -/// Other modules free engine blocks with their own delete, and Tracy kills the session when an address is allocated twice or -/// freed untracked Storage comes from malloc since operator new would recurse +/// Tracy kills the session on an address allocated twice or freed untracked by another module class LiveSet { public: /// False when the address was already present diff --git a/engine/src/toast/physics/joint.hpp b/engine/src/toast/physics/joint.hpp index b97fac7e4..f2db6c8c9 100644 --- a/engine/src/toast/physics/joint.hpp +++ b/engine/src/toast/physics/joint.hpp @@ -34,11 +34,10 @@ enum class JointType : uint8_t { fixed }; -// Joint friction is the torque that holds the ends against turning per newton the joint carries, the friction of the -// material times the radius of the pin, in metres +// Material friction times pin radius in metres as torque per newton carried constexpr float k_default_joint_friction = 0.01f; -// The ends of a hinge or a pin with collision between them don't touch closer to the pin than this +// The ends of a hinge or a pin with collision between them never touch closer to the pin than this constexpr float k_joint_knuckle_radius = 0.1f; struct PinParams { @@ -63,7 +62,7 @@ struct HingeParams { auto operator==(const HingeParams&) const -> bool = default; }; -// todo: sliderjoint needs to be able to freely rotate +// TODO slider joint should rotate freely struct SliderParams { float bias = 0.3f; float linear_limit_lower = -1.0f; diff --git a/engine/src/toast/physics/joint_solver.cpp b/engine/src/toast/physics/joint_solver.cpp index 5fc71aa3d..0aae211e5 100644 --- a/engine/src/toast/physics/joint_solver.cpp +++ b/engine/src/toast/physics/joint_solver.cpp @@ -399,8 +399,7 @@ auto makeJoint(const JointDescriptor& descriptor, const Body& body_a, const Body joint.frame_a = frame_in(body_a); joint.frame_b = frame_in(body_b); - // A hinge angle is where b sits around the axis from the x of the frame, the way the limits are drawn. b is the end that - // moves when only one does. A body centred on the axis, like a wheel, has no side to sit on and starts at zero + // Angle of b around the axis from the frame x like the limits and zero for a body centred on the axis if (const auto* hinge = std::get_if(&descriptor.params); hinge != nullptr) { const glm::mat3 axes = glm::mat3_cast(descriptor.frame); const glm::vec3 arm = body_b.worldCenterOfMass() - descriptor.anchor; diff --git a/engine/src/toast/physics/nodes/hinge_joint.hpp b/engine/src/toast/physics/nodes/hinge_joint.hpp index 44f3561e2..1359d93b8 100644 --- a/engine/src/toast/physics/nodes/hinge_joint.hpp +++ b/engine/src/toast/physics/nodes/hinge_joint.hpp @@ -16,8 +16,7 @@ class [[ToastNode, Icon("HingeJoint"), Color("Green")]] TOAST_API HingeJoint : p [[Reflect, Range(0.0, 1.0)]] float bias = 0.3f; - /// Torque that holds the hinge against turning per newton it carries, the friction of the material times the radius of - /// the pin. Zero swings forever + /// Material friction times pin radius as torque per newton carried and zero swings forever [[Reflect, Unit("m"), Range(0.0, 0.1)]] float friction = k_default_joint_friction; diff --git a/engine/src/toast/physics/query_snapshot.hpp b/engine/src/toast/physics/query_snapshot.hpp index a45fbf459..1b057770e 100644 --- a/engine/src/toast/physics/query_snapshot.hpp +++ b/engine/src/toast/physics/query_snapshot.hpp @@ -22,7 +22,7 @@ struct QueryVoxel { uint32_t surface_revision = 0; }; -/// All data used by gameplay collision queries from one completed physics tick. +/// All data used by gameplay collision queries from one completed physics tick struct QuerySnapshot { AABBTree tree; std::vector bodies; diff --git a/engine/src/toast/physics/raycast.hpp b/engine/src/toast/physics/raycast.hpp index 4a9062b17..c223bfb9c 100644 --- a/engine/src/toast/physics/raycast.hpp +++ b/engine/src/toast/physics/raycast.hpp @@ -61,7 +61,7 @@ struct SphereHit { ShapeType shape_type = ShapeType::sphere; }; -/// The optional layer filter limits which bodies can overlap the sphere. +/// The optional layer filter limits which bodies can overlap the sphere TOAST_API auto sphereOverlap(glm::vec3 position, float radius, std::optional layers = std::nullopt) -> std::optional; diff --git a/engine/src/toast/physics/simulator.cpp b/engine/src/toast/physics/simulator.cpp index da3803c69..557d841fa 100644 --- a/engine/src/toast/physics/simulator.cpp +++ b/engine/src/toast/physics/simulator.cpp @@ -3983,11 +3983,7 @@ void Simulator::removeExclusion(BodyID a, BodyID b) { } } -// The ends of a joint that collide with each other -// - A hinge or a pin turns in a knuckle around its pin, so the two ends it holds never press on each other right there. A -// contact between them that close to the pin fights the joint, the joint pulls the ends back in and the contact pushes -// them out, and each push lifts the bodies a little for free, which keeps them swinging forever -// - The other end is a stop like the limits, a hinge or a slider bounces off it at least as much as off its limits +// Contacts near a pin fight the joint and pump energy into the swing so they drop void Simulator::adjustJointContacts(std::vector& manifolds) { if (m_joint_count == 0 || manifolds.empty()) { return; diff --git a/engine/src/toast/renderer/core/vulkan_core.cpp b/engine/src/toast/renderer/core/vulkan_core.cpp index e63cf48cd..fc7355f80 100644 --- a/engine/src/toast/renderer/core/vulkan_core.cpp +++ b/engine/src/toast/renderer/core/vulkan_core.cpp @@ -158,7 +158,7 @@ VKAPI_ATTR auto VKAPI_CALL debugCallback( default: return VK_FALSE; } - // The first line is the problem, the rest is the layer's explanation and the spec link + // First line is the problem and the rest is the layer explanation and spec link const auto [summary, body] = logging::splitFirstLine(message); const std::string line = std::format("[Vulkan Validation] [{}]: {}", message_type_string, summary); TOAST_MESSAGE(severity, "ValidationLayers", line, body); diff --git a/engine/src/toast/renderer/passes/geometry/voxel_pass.cpp b/engine/src/toast/renderer/passes/geometry/voxel_pass.cpp index 600e8b9e1..46ebbb0a1 100644 --- a/engine/src/toast/renderer/passes/geometry/voxel_pass.cpp +++ b/engine/src/toast/renderer/passes/geometry/voxel_pass.cpp @@ -1190,7 +1190,7 @@ void VoxelPass::recordNearQuads(vk::CommandBuffer cmd, uint32_t frame_index, boo cmd.bindPipeline(vk::PipelineBindPoint::eGraphics, m_mesh_quad_pipeline.getPipeline()); // voxel_mesh.slang reads the bucket as which near list to draw PushConstants push {.bucket = late ? 1u : 0u, .mode = k_draw_cells}; - // Only the late pyramid is final, see voxel_mesh_task.slang + // Only the late pyramid is final if (late && m_occlusion_active && m_hiz.isReady()) { push.hiz_levels = m_hiz.builtLevels(); push.hiz_width = m_hiz.builtExtent().width; diff --git a/engine/src/toast/renderer/passes/lighting/gi_clipmap_pass.hpp b/engine/src/toast/renderer/passes/lighting/gi_clipmap_pass.hpp index b6e70d1bd..17e6157b5 100644 --- a/engine/src/toast/renderer/passes/lighting/gi_clipmap_pass.hpp +++ b/engine/src/toast/renderer/passes/lighting/gi_clipmap_pass.hpp @@ -131,7 +131,7 @@ class GiClipmapPass : public IPostProcessPass { SceneDescriptorSets m_inject_scene_sets; std::vector m_inject_sets; - /// gi_clip_bounce with the engine scene in set 0 for last frame's clipmap and the ambient faces in set 1 + /// gi_clip_bounce with the engine scene in set 0 for the last frame clipmap and the ambient faces in set 1 ShaderLayout m_bounce_layout; VulkanPipeline m_bounce_pipeline; SceneDescriptorSets m_bounce_scene_sets; diff --git a/engine/src/toast/renderer/shaders/shader_compiler.cpp b/engine/src/toast/renderer/shaders/shader_compiler.cpp index 8249b05c1..9f85e787e 100644 --- a/engine/src/toast/renderer/shaders/shader_compiler.cpp +++ b/engine/src/toast/renderer/shaders/shader_compiler.cpp @@ -262,7 +262,6 @@ void logDiagnostics(const Slang::ComPtr& diagnostics, std::string_ const char* diag_c = static_cast(diag_ptr); const std::string diag_str(diag_c, diag_c + diag_size); - // Default to warning logging::Severity severity = logging::Severity::warning; if (diag_str.contains(": error ")) { diff --git a/engine/src/toast/renderer/voxel/voxel_blas_cache.hpp b/engine/src/toast/renderer/voxel/voxel_blas_cache.hpp index f963b873d..cb0eed214 100644 --- a/engine/src/toast/renderer/voxel/voxel_blas_cache.hpp +++ b/engine/src/toast/renderer/voxel/voxel_blas_cache.hpp @@ -19,8 +19,7 @@ namespace renderer { class VulkanCore; -/// One AABB per occupied brick per record where carving keeps a built BLAS correct and only a newly occupied brick rebuilds -/// @note Render thread only apart from stats() +/// Render thread only apart from stats() class VoxelBlasCache { public: /// Records this small keep the unit box since marching them whole is already short @@ -56,9 +55,7 @@ class VoxelBlasCache { VoxelBlasCache(const VulkanCore& core, uint32_t frames_in_flight); - /// Before the TLAS build once the fence of @p frame_index was waited on - /// @param records the volume records the trace scene instances this frame - /// @param budget bricks built per frame though the first build always goes ahead + /// Before the TLAS build once the fence of @p frame_index was waited on and the first build ignores @p budget void update( vk::CommandBuffer cmd, uint32_t frame_index, const VoxelGpuStorage& storage, std::span records, uint32_t budget diff --git a/engine/src/toast/renderer/voxel/voxel_trace_scene.hpp b/engine/src/toast/renderer/voxel/voxel_trace_scene.hpp index abcff57c8..618da9e7c 100644 --- a/engine/src/toast/renderer/voxel/voxel_trace_scene.hpp +++ b/engine/src/toast/renderer/voxel/voxel_trace_scene.hpp @@ -18,8 +18,7 @@ class VulkanCore; class RayTracingScene; class VoxelBlasCache; -/// Voxel volumes every marched ray walks in one order shared by scene_trace.slang and the ray query instances -/// Without ray queries rays walk a camera centred cell grid over the same list +/// Volume order shared by scene_trace.slang and the ray query instances class VoxelTraceScene { public: struct Volume { @@ -48,7 +47,6 @@ class VoxelTraceScene { /// Render thread before the acceleration structure builds and every pass that marches voxels void update(uint32_t frame_index, std::span volumes, glm::vec3 camera_position, float cell_size); - /// Builds the shared unit box once and adds the brick BLASes of @p bricks or the unit box per volume of the last update /// @return false while the unit box is not usable yet auto addRayQueryInstances( vk::CommandBuffer cmd, uint32_t frame_index, RayTracingScene& scene, const VoxelBlasCache* bricks, diff --git a/engine/src/toast/renderer/vulkan_renderer.hpp b/engine/src/toast/renderer/vulkan_renderer.hpp index 591516c61..9f276a55a 100644 --- a/engine/src/toast/renderer/vulkan_renderer.hpp +++ b/engine/src/toast/renderer/vulkan_renderer.hpp @@ -707,8 +707,7 @@ class VulkanRenderer { return m_glass_backdrop_depth.view ? **m_glass_backdrop_depth.view : vk::ImageView {}; } - /// Depth before glass wrote its own so GI and reflections see the surface behind a pane, the final depth when no backdrop was - /// copied + /// Depth before glass so GI and reflections see behind a pane and the final depth when no backdrop was copied [[nodiscard]] auto getOpaqueDepthView() const noexcept -> vk::ImageView { return m_glass_backdrop_captured && m_glass_backdrop_depth.view ? **m_glass_backdrop_depth.view : getDepthView(); diff --git a/engine/src/toast/renderer/vulkan_renderer_scene.cpp b/engine/src/toast/renderer/vulkan_renderer_scene.cpp index 0213fc6b7..7cc3211e5 100644 --- a/engine/src/toast/renderer/vulkan_renderer_scene.cpp +++ b/engine/src/toast/renderer/vulkan_renderer_scene.cpp @@ -134,30 +134,6 @@ auto lightIcon(toast::LightType type) -> const assets::Handle& return g_light_icons[index]; } -auto pickSkin(const toast::MeshNode& node) -> const assets::Skin* { - const auto& skin_animation = node.getSkinAnimation(); - if (!skin_animation.hasValue()) { - return nullptr; - } - - const auto& skins = skin_animation->skins(); - if (skins.empty()) { - return nullptr; - } - - const auto& skin_name = node.getSkinName(); - if (skin_name.empty()) { - return &skins.front(); - } - - for (const auto& skin : skins) { - if (skin.name == skin_name) { - return &skin; - } - } - return nullptr; -} - auto findAncestorSkeleton(toast::Node& node) -> toast::SkeletalNode* { toast::Box current = node.parent(); while (current.exists()) { @@ -178,13 +154,10 @@ auto resolveSkinning( toast::MeshNode& node, RenderFrame& frame, uint32_t& joint_offset, uint32_t& joint_count, bool& pool_exhausted_warned, SkinPoseCache& pose_cache ) -> toast::SkeletalNode* { - const assets::Skin* skin = pickSkin(node); - if (skin == nullptr) { - return nullptr; - } - toast::SkeletalNode* skeletal = findAncestorSkeleton(node); - if (skeletal == nullptr) { + const assets::Skeleton* skeleton = skeletal != nullptr ? skeletal->skeleton() : nullptr; + const assets::Skin* skin = skeleton != nullptr ? skeleton->findSkin(node.getSkinName()) : nullptr; + if (skin == nullptr) { return nullptr; } diff --git a/engine/src/toast/world/animation_player.cpp b/engine/src/toast/world/animation_player.cpp index 0ed92d74b..83545bd6a 100644 --- a/engine/src/toast/world/animation_player.cpp +++ b/engine/src/toast/world/animation_player.cpp @@ -2,30 +2,34 @@ namespace toast { -auto resolveClip(const assets::Animation& animation, std::string_view clip_name, std::string_view owner) +auto resolveClip(std::span> clips, std::string_view clip_name, std::string_view owner) -> const assets::AnimationClip* { - // The importer writes one clip per .tanim so the Clip field is normally blank - if (clip_name.empty()) { - if (animation.clips().empty()) { - TOAST_WARN("Animation", "'{}': assigned animation asset has no clips", owner); - return nullptr; + for (const auto& clip : clips) { + if (clip.hasValue() && (clip_name.empty() || clip->clip().name == clip_name)) { + return &clip->clip(); } - return &animation.clips().front(); } - const assets::AnimationClip* clip = animation.findClip(clip_name); - if (clip == nullptr) { - TOAST_WARN("Animation", "'{}': animation asset has no clip named '{}'", owner, clip_name); + if (clip_name.empty()) { + TOAST_WARN("Animation", "'{}' has no clips assigned", owner); + } else { + TOAST_WARN("Animation", "'{}' has no clip named '{}'", owner, clip_name); } - return clip; + return nullptr; } -auto AnimationPlayer::play(std::string_view clip_name) -> bool { - if (!m_animation.hasValue()) { - TOAST_WARN("Animation", "AnimationPlayer '{}' has no animation asset assigned", name()); - return false; +auto clipNames(std::span> clips) -> std::vector { + std::vector names; + names.reserve(clips.size()); + for (const auto& clip : clips) { + if (clip.hasValue()) { + names.push_back(clip->clip().name); + } } + return names; +} - const assets::AnimationClip* clip = resolveClip(*m_animation, clip_name, name()); +auto AnimationPlayer::play(std::string_view clip_name) -> bool { + const assets::AnimationClip* clip = resolveClip(m_clips, clip_name, name()); if (clip == nullptr) { return false; } @@ -34,20 +38,12 @@ auto AnimationPlayer::play(std::string_view clip_name) -> bool { if (clip != m_playback.clip) { m_node_cache.clear(); } - m_playback.start(clip); - m_clip_name = clip->name; return true; } auto AnimationPlayer::inspectorOptions(std::string_view field_name) -> std::vector { - std::vector options; - if (field_name == "m_clip_name" && m_animation.hasValue()) { - for (const auto& clip : m_animation->clips()) { - options.push_back(clip.name); - } - } - return options; + return field_name == "m_autoplay" ? clipNames(m_clips) : std::vector {}; } void AnimationPlayer::stop() { @@ -55,10 +51,8 @@ void AnimationPlayer::stop() { } void AnimationPlayer::begin() { - // No clip-name check: with one clip per asset the field is normally blank, and play() resolves that to - // the asset's only clip - if (m_play_on_begin && m_animation.hasValue()) { - play(m_clip_name); + if (!m_autoplay.empty()) { + play(m_autoplay); } } diff --git a/engine/src/toast/world/animation_player.hpp b/engine/src/toast/world/animation_player.hpp index b44c5ba78..191d96a49 100644 --- a/engine/src/toast/world/animation_player.hpp +++ b/engine/src/toast/world/animation_player.hpp @@ -19,8 +19,6 @@ namespace toast { /** * @brief Drives node transforms from an Animation clip * - * For node trees without bones, skinned rigs use SkeletalNode - * * Targets are resolved by name against this player's descendants, never itself - so the same clip drives * several prefab instances independently * @@ -33,8 +31,7 @@ class [[ToastNode, Icon("Animation")]] TOAST_API AnimationPlayer : public Node3D public: AnimationPlayer() = default; - /// @brief Starts the named clip from the beginning - /// @returns false when the asset has no clip by that name + /// Empty plays the first clip [[Reflect]] auto play(std::string_view clip_name) -> bool; @@ -74,14 +71,12 @@ class [[ToastNode, Icon("Animation")]] TOAST_API AnimationPlayer : public Node3D /// @brief Finds a node by name among this player's descendants, memoised for the lifetime of the clip auto resolveNode(const std::string& name) -> Node3D*; - [[Reflect, Name("Animation")]] - assets::Handle m_animation; - - [[Reflect, Name("Clip"), Options]] - std::string m_clip_name; + [[Reflect, Name("Clips")]] + std::vector> m_clips; - [[Reflect, Name("Play On Begin")]] - bool m_play_on_begin = true; + /// Played on begin, empty plays nothing + [[Reflect, Name("Autoplay"), Options]] + std::string m_autoplay; [[Reflect, Name("Loop")]] bool m_loop = true; diff --git a/engine/src/toast/world/bone_attachment.cpp b/engine/src/toast/world/bone_attachment.cpp index 035a0aede..ea92aa6d2 100644 --- a/engine/src/toast/world/bone_attachment.cpp +++ b/engine/src/toast/world/bone_attachment.cpp @@ -11,8 +11,8 @@ auto BoneAttachment::inspectorOptions(std::string_view field_name) -> std::vecto return options; } if (const assets::Skeleton* skeleton = skeletal->skeleton(); skeleton != nullptr) { - options.reserve(skeleton->bones.size()); - for (const auto& bone : skeleton->bones) { + options.reserve(skeleton->bones().size()); + for (const auto& bone : skeleton->bones()) { options.push_back(bone.name); } } diff --git a/engine/src/toast/world/bone_attachment.hpp b/engine/src/toast/world/bone_attachment.hpp index 7a64527cd..52a7bd337 100644 --- a/engine/src/toast/world/bone_attachment.hpp +++ b/engine/src/toast/world/bone_attachment.hpp @@ -39,8 +39,7 @@ class [[ToastNode, Icon("BoneAttachment")]] TOAST_API BoneAttachment : public No [[Reflect, Name("Bone"), Options]] std::string m_bone; - /// Off keeps world scale 1 since rigs often carry an armature scale the skin cancels out and physics - /// rejects voxel nodes with non unit world scale + /// Off keeps world scale 1 since physics rejects voxel nodes with non unit world scale [[Reflect, Name("Inherit Scale")]] bool m_inherit_scale = false; diff --git a/engine/src/toast/world/clip_playback.hpp b/engine/src/toast/world/clip_playback.hpp index bcc1ef4a5..c00ce11b1 100644 --- a/engine/src/toast/world/clip_playback.hpp +++ b/engine/src/toast/world/clip_playback.hpp @@ -5,8 +5,11 @@ */ #pragma once +#include +#include #include #include +#include namespace toast { @@ -47,8 +50,12 @@ struct ClipPlayback { } }; -/// Empty name means the first clip, logs under @p owner when nothing matches -TOAST_API auto resolveClip(const assets::Animation& animation, std::string_view clip_name, std::string_view owner) - -> const assets::AnimationClip*; +/// Empty name means the first loaded clip, logs under @p owner when nothing matches +TOAST_API auto + resolveClip(std::span> clips, std::string_view clip_name, std::string_view owner) + -> const assets::AnimationClip*; + +/// Names of the loaded clips, for an Autoplay dropdown +TOAST_API auto clipNames(std::span> clips) -> std::vector; } diff --git a/engine/src/toast/world/light_gizmo.hpp b/engine/src/toast/world/light_gizmo.hpp index 3738a9032..60d288810 100644 --- a/engine/src/toast/world/light_gizmo.hpp +++ b/engine/src/toast/world/light_gizmo.hpp @@ -2,7 +2,6 @@ * @file light_gizmo.hpp * @author dario * @date 29/10/2026 - * @brief Selected light shapes and the viewport handles that edit them, laid out like the collider size handles */ #pragma once diff --git a/engine/src/toast/world/mesh_node.cpp b/engine/src/toast/world/mesh_node.cpp index 418d42174..314e7cd87 100644 --- a/engine/src/toast/world/mesh_node.cpp +++ b/engine/src/toast/world/mesh_node.cpp @@ -1,5 +1,7 @@ #include "mesh_node.hpp" +#include "skeletal_node.hpp" + #include namespace toast { @@ -20,9 +22,17 @@ void MeshNode::updateInspectorMessages() { auto MeshNode::inspectorOptions(std::string_view field_name) -> std::vector { std::vector options; - if (field_name == "m_skin_name" && m_skin_animation.hasValue()) { - for (const auto& skin : m_skin_animation->skins()) { - options.push_back(skin.name); + if (field_name != "m_skin_name") { + return options; + } + for (Box cursor = parent(); cursor.exists(); cursor = cursor->parent()) { + if (auto skeletal = cursor.as(); skeletal.exists()) { + if (const assets::Skeleton* skeleton = skeletal->skeleton(); skeleton != nullptr) { + for (const auto& skin : skeleton->skins()) { + options.push_back(skin.name); + } + } + break; } } return options; diff --git a/engine/src/toast/world/mesh_node.hpp b/engine/src/toast/world/mesh_node.hpp index c95958e48..19e4970c7 100644 --- a/engine/src/toast/world/mesh_node.hpp +++ b/engine/src/toast/world/mesh_node.hpp @@ -53,12 +53,7 @@ class [[ToastNode, Icon("MeshItem")]] TOAST_API MeshNode : public Node3D { return m_material; } - [[nodiscard]] - auto getSkinAnimation() const -> const assets::Handle& { - return m_skin_animation; - } - - /// @returns which Skin inside skinAnimation() to use; empty means "the first one" + /// Skin inside the nearest SkeletalNode ancestor skeleton, empty is the first [[nodiscard]] auto getSkinName() const -> const std::string& { return m_skin_name; @@ -77,9 +72,6 @@ class [[ToastNode, Icon("MeshItem")]] TOAST_API MeshNode : public Node3D { [[Reflect]] assets::Handle m_material; - [[Reflect, Name("Skin Animation")]] - assets::Handle m_skin_animation; - [[Reflect, Name("Skin Name"), Options]] std::string m_skin_name; diff --git a/engine/src/toast/world/skeletal_node.cpp b/engine/src/toast/world/skeletal_node.cpp index 9e25a3cec..d63ce9375 100644 --- a/engine/src/toast/world/skeletal_node.cpp +++ b/engine/src/toast/world/skeletal_node.cpp @@ -20,12 +20,7 @@ auto poseMatrix(const assets::BonePose& pose) -> glm::mat4 { } auto SkeletalNode::play(std::string_view clip_name) -> bool { - if (!m_animation.hasValue()) { - TOAST_WARN("Animation", "SkeletalNode '{}' has no animation asset assigned", name()); - return false; - } - - const assets::AnimationClip* clip = resolveClip(*m_animation, clip_name, name()); + const assets::AnimationClip* clip = resolveClip(m_clips, clip_name, name()); if (clip == nullptr) { return false; } @@ -34,7 +29,6 @@ auto SkeletalNode::play(std::string_view clip_name) -> bool { m_node_cache.clear(); } m_playback.start(clip); - m_clip_name = clip->name; return true; } @@ -76,8 +70,8 @@ void SkeletalNode::drawBones() { } void SkeletalNode::begin() { - if (m_play_on_begin && m_animation.hasValue()) { - play(m_clip_name); + if (!m_autoplay.empty()) { + play(m_autoplay); } } @@ -85,7 +79,7 @@ void SkeletalNode::updateInspectorMessages() { static const NodeMessage no_skeleton { .severity = NodeMessage::warning, .id = 1, - .text = "SkeletalNode needs a Skeleton or Animation asset that contains a skeleton", + .text = "SkeletalNode needs a Skeleton asset", }; if (skeleton() != nullptr) { @@ -96,20 +90,7 @@ void SkeletalNode::updateInspectorMessages() { } auto SkeletalNode::inspectorOptions(std::string_view field_name) -> std::vector { - std::vector options; - if (field_name == "m_clip_name" && m_animation.hasValue()) { - for (const auto& clip : m_animation->clips()) { - options.push_back(clip.name); - } - } else if (field_name == "m_skeleton_name") { - const auto& source = m_skeleton_asset.hasValue() ? m_skeleton_asset : m_animation; - if (source.hasValue()) { - for (const auto& skeleton : source->skeletons()) { - options.push_back(skeleton.name); - } - } - } - return options; + return field_name == "m_autoplay" ? clipNames(m_clips) : std::vector {}; } auto SkeletalNode::skeleton() -> const assets::Skeleton* { @@ -117,8 +98,7 @@ auto SkeletalNode::skeleton() -> const assets::Skeleton* { } auto SkeletalNode::bindSkeleton() -> const assets::Skeleton* { - const auto& source = m_skeleton_asset.hasValue() ? m_skeleton_asset : m_animation; - const assets::Skeleton* found = source.hasValue() ? source->findSkeleton(m_skeleton_name) : nullptr; + const assets::Skeleton* found = m_skeleton.hasValue() ? &*m_skeleton : nullptr; if (found == m_bound) { return found; } @@ -128,13 +108,13 @@ auto SkeletalNode::bindSkeleton() -> const assets::Skeleton* { m_track_clip = nullptr; m_track_to_bone.clear(); - const size_t count = found != nullptr ? found->bones.size() : 0; + const size_t count = found != nullptr ? found->bones().size() : 0; m_local.resize(count); m_model.assign(count, glm::mat4(1.0f)); m_parents.resize(count); for (size_t i = 0; i < count; ++i) { - m_local[i] = found->bones[i].rest; - m_parents[i] = found->bones[i].parent; + m_local[i] = found->bones()[i].rest; + m_parents[i] = found->bones()[i].parent; } if (found != nullptr) { computeModel(*found); @@ -161,7 +141,7 @@ void SkeletalNode::bindTracks(const assets::Skeleton& skeleton) { void SkeletalNode::computeModel(const assets::Skeleton& skeleton) { for (size_t i = 0; i < m_local.size(); ++i) { const glm::mat4 local = poseMatrix(m_local[i]); - const int32_t parent = skeleton.bones[i].parent; + const int32_t parent = skeleton.bones()[i].parent; m_model[i] = parent >= 0 ? m_model[parent] * local : local; } } @@ -262,7 +242,7 @@ void SkeletalNode::tick() { if (m_playback.advance(static_cast(Time::delta()), m_speed, m_loop)) { bindTracks(*skeleton); for (size_t i = 0; i < m_local.size(); ++i) { - m_local[i] = skeleton->bones[i].rest; + m_local[i] = skeleton->bones()[i].rest; } m_playback.clip->sampleInto(m_playback.time, m_track_to_bone, m_local); computeModel(*skeleton); @@ -278,10 +258,10 @@ auto SkeletalNode::boneIndex(std::string_view bone_name) -> int32_t { } auto SkeletalNode::boneName(int32_t bone) const -> std::string_view { - if (m_bound == nullptr || bone < 0 || std::cmp_greater_equal(bone, m_bound->bones.size())) { + if (m_bound == nullptr || bone < 0 || std::cmp_greater_equal(bone, m_bound->bones().size())) { return {}; } - return m_bound->bones[bone].name; + return m_bound->bones()[bone].name; } auto SkeletalNode::boneModelTransform(int32_t bone) const -> const glm::mat4& { diff --git a/engine/src/toast/world/skeletal_node.hpp b/engine/src/toast/world/skeletal_node.hpp index c51f668a9..987f7a808 100644 --- a/engine/src/toast/world/skeletal_node.hpp +++ b/engine/src/toast/world/skeletal_node.hpp @@ -17,20 +17,12 @@ namespace toast { -/** - * @brief Owns a skeleton pose and plays clips onto it - * - * Bones are arrays here, never scene nodes. Skinned MeshNode descendants read the pose through - * skinBones and boneModelTransform, BoneAttachment children get their transform written every tick. - * Clip tracks that name no bone fall back to descendant nodes by name - * - * @note Also ticked outside Play, by Workspace::tickAnimationPreviews() - */ +/// Also ticked outside Play by Workspace::tickAnimationPreviews() class [[ToastNode, Icon("Bone")]] TOAST_API SkeletalNode : public Node3D { public: SkeletalNode() = default; - /// @returns false when the asset has no clip by that name + /// Empty plays the first clip [[Reflect]] auto play(std::string_view clip_name) -> bool; @@ -107,22 +99,16 @@ class [[ToastNode, Icon("Bone")]] TOAST_API SkeletalNode : public Node3D { void applyAttachments(const assets::Skeleton& skeleton); auto resolveNode(const std::string& name) -> Node3D*; - /// Empty uses the Animation asset since every .tanim carries its skeletons [[Reflect, Name("Skeleton")]] - assets::Handle m_skeleton_asset; - - /// Empty means the first skeleton in the asset - [[Reflect, Name("Skeleton Name"), Options]] - std::string m_skeleton_name; - - [[Reflect, Name("Animation")]] - assets::Handle m_animation; + assets::Handle m_skeleton; - [[Reflect, Name("Clip"), Options]] - std::string m_clip_name; + /// Bone name keyed, any clip plays on any skeleton with matching names + [[Reflect, Name("Clips")]] + std::vector> m_clips; - [[Reflect, Name("Play On Begin")]] - bool m_play_on_begin = true; + /// Played on begin, empty plays nothing + [[Reflect, Name("Autoplay"), Options]] + std::string m_autoplay; [[Reflect, Name("Loop")]] bool m_loop = true; diff --git a/engine/src/toast/world/workspace.cpp b/engine/src/toast/world/workspace.cpp index a3211831d..32dce6d85 100644 --- a/engine/src/toast/world/workspace.cpp +++ b/engine/src/toast/world/workspace.cpp @@ -43,7 +43,7 @@ namespace toast { namespace { -// Handle clicks before the runtime UI (priority 32) and gameplay input (priority 0). +// Ahead of the runtime UI at 32 and gameplay at 0 constexpr char k_gizmo_input_priority = 33; // TODO: i didnt know where to place the ray picking shit since theres no physics class yet, MOVE THIS SOMEWHERE ELSE! @@ -2525,7 +2525,7 @@ void Workspace::eventSubscriptions() { return true; }); - // Editor interaction only follows the editor camera; game view passes input to the game. + // The game view passes input to the game m_listener.subscribe([this](const auto& e) { if (m_handle.data() != Engine::get()->activeWorkspace().data()) { return false; diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index d6bcc91ac..486e419a2 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -44,7 +44,7 @@ if (BUILD_TESTING) endif() if (NOT WIN32) - # Slang's gfx library depends on X11; make it available when linking the test executable. + # Slang gfx needs X11 at link time find_package(X11 REQUIRED) target_link_libraries(toast_tests PRIVATE X11::X11) target_link_libraries(toast_tests PRIVATE stdc++exp) diff --git a/tests/assets/02-animation-binary.cpp b/tests/assets/02-animation-binary.cpp index 1e80db08e..a18f51939 100644 --- a/tests/assets/02-animation-binary.cpp +++ b/tests/assets/02-animation-binary.cpp @@ -13,8 +13,7 @@ auto nearly(float a, float b) -> bool { } TOAST_TEST_NAMED("Assets", "assets/02-animation-binary", test_assets_02_animation_binary) { - // One clip covering every track target and all three interpolation modes, plus a skin, so the round - // trip exercises every branch of the .tanim reader/writer + // Every track target and interpolation mode so the round trip hits every .tanim branch assets::AnimationClip clip; clip.name = "Walk"; clip.duration = 2.5f; @@ -58,25 +57,16 @@ TOAST_TEST_NAMED("Assets", "assets/02-animation-binary", test_assets_02_animatio }; clip.tracks.push_back(scale); - assets::Skin skin; - skin.name = "Body"; - skin.skeleton_root = "Hips"; - skin.joints = {"Hips", "Spine", "Head"}; - skin.inverse_bind_matrices = {glm::mat4(1.0f), glm::mat4(2.0f), glm::mat4(3.0f)}; - - const auto bytes = assets::Animation::toBinary({clip}, {skin}, {}); + const auto bytes = assets::Animation::toBinary(clip); assert(!bytes.empty()); const assets::Animation loaded(bytes); assert(loaded.type() == "animation"); - assert(loaded.clips().size() == 1); - assert(loaded.skins().size() == 1); - const auto* round_tripped = loaded.findClip("Walk"); - assert(round_tripped != nullptr); + const auto* round_tripped = &loaded.clip(); + assert(round_tripped->name == "Walk"); assert(nearly(round_tripped->duration, 2.5f)); assert(round_tripped->tracks.size() == 3); - assert(loaded.findClip("Run") == nullptr); const auto& t0 = round_tripped->tracks[0]; assert(t0.target_node == "Hips"); @@ -101,22 +91,13 @@ TOAST_TEST_NAMED("Assets", "assets/02-animation-binary", test_assets_02_animatio assert(t2.vec3_values.size() == 6); assert(nearly(t2.vec3_values[4].x, 2.0f)); - const auto& loaded_skin = loaded.skins()[0]; - assert(loaded_skin.name == "Body"); - assert(loaded_skin.skeleton_root == "Hips"); - assert(loaded_skin.joints.size() == 3); - assert(loaded_skin.joints[2] == "Head"); - assert(loaded_skin.inverse_bind_matrices.size() == 3); - assert(nearly(loaded_skin.inverse_bind_matrices[2][0][0], 3.0f)); - // A truncated file must be rejected rather than silently yielding partial garbage const std::vector truncated(bytes.begin(), bytes.begin() + (bytes.size() / 2)); const assets::Animation partial(truncated); - assert(partial.clips().size() <= 1); + assert(partial.clip().tracks.size() <= 3); // Wrong magic entirely const std::vector junk {'N', 'O', 'P', 'E', 0, 0, 0, 0}; const assets::Animation rejected(junk); - assert(rejected.clips().empty()); - assert(rejected.skins().empty()); + assert(rejected.clip().tracks.empty()); } diff --git a/tests/assets/04-animation-skin-only.cpp b/tests/assets/04-animation-skin-only.cpp index 7d941bb36..41d6bfe8a 100644 --- a/tests/assets/04-animation-skin-only.cpp +++ b/tests/assets/04-animation-skin-only.cpp @@ -2,7 +2,8 @@ #include #include -#include +#include +#include namespace { @@ -12,9 +13,7 @@ auto nearly(float a, float b) -> bool { } -// The glTF importer writes one .tanim per clip, and a glTF that defines a skeleton but no animation still -// needs a file for MeshNode::skin_animation to resolve against - a clip-less .tanim. Nothing else in the -// engine produces one, so the reader's zero-clip path only exists for this case +// A skinned mesh draws in bind pose from a .tskel alone TOAST_TEST_NAMED("Assets", "assets/04-animation-skin-only", test_assets_04_animation_skin_only) { assets::Skin skin; skin.name = "Body"; @@ -22,18 +21,24 @@ TOAST_TEST_NAMED("Assets", "assets/04-animation-skin-only", test_assets_04_anima skin.joints = {"Hips", "Spine", "Head"}; skin.inverse_bind_matrices = {glm::mat4(1.0f), glm::mat4(2.0f), glm::mat4(3.0f)}; - const auto bytes = assets::Animation::toBinary({}, {skin}, {}); + const std::vector bones { + {.name = "Hips", .parent = -1}, + {.name = "Spine", .parent = 0}, + {.name = "Head", .parent = 1}, + }; + const auto bytes = assets::Skeleton::toBinary("Armature", bones, std::span(&skin, 1)); assert(!bytes.empty()); - const assets::Animation loaded(bytes); - assert(loaded.type() == "animation"); - assert(loaded.clips().empty()); + const assets::Skeleton loaded(bytes); + assert(loaded.type() == "skeleton"); + assert(loaded.name() == "Armature"); + assert(loaded.bones().size() == 3); + assert(loaded.bones()[2].parent == 1); + assert(loaded.find("Spine") == 1); + assert(loaded.find("Tail") == -1); assert(loaded.skins().size() == 1); - - // Asking for any clip has to come back empty-handed rather than reaching into an empty vector - - // AnimationPlayer::play() calls this before it has any way of knowing the asset is clip-less - assert(loaded.findClip("Walk") == nullptr); - assert(loaded.findClip("") == nullptr); + assert(loaded.findSkin("") == &loaded.skins()[0]); + assert(loaded.findSkin("Missing") == nullptr); const auto& loaded_skin = loaded.skins()[0]; assert(loaded_skin.name == "Body"); @@ -43,8 +48,6 @@ TOAST_TEST_NAMED("Assets", "assets/04-animation-skin-only", test_assets_04_anima assert(loaded_skin.inverse_bind_matrices.size() == 3); assert(nearly(loaded_skin.inverse_bind_matrices[1][0][0], 2.0f)); - // The skin still poses without any clip driving it: joint matrices are joint_world * inverse_bind, so a - // skeleton-only asset is enough to draw a skinned mesh in bind pose const std::vector world_transforms(3, glm::mat4(1.0f)); const auto matrices = loaded_skin.jointMatrices(world_transforms); assert(matrices.size() == 3); From 9a971321533b4d39f0e1697218366e2b754592f3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dar=C3=ADo=20Rodr=C3=ADguez=20Mart=C3=ADnez?= Date: Fri, 13 Nov 2026 21:54:49 +0100 Subject: [PATCH 08/11] Fixed animation clip crash --- engine/src/toast/world/animation_player.cpp | 17 ++++++++++----- engine/src/toast/world/animation_player.hpp | 1 + engine/src/toast/world/clip_playback.hpp | 23 +++++++++++++++++---- engine/src/toast/world/skeletal_node.cpp | 18 ++++++++++++---- engine/src/toast/world/skeletal_node.hpp | 1 + 5 files changed, 47 insertions(+), 13 deletions(-) diff --git a/engine/src/toast/world/animation_player.cpp b/engine/src/toast/world/animation_player.cpp index 83545bd6a..0d416538d 100644 --- a/engine/src/toast/world/animation_player.cpp +++ b/engine/src/toast/world/animation_player.cpp @@ -3,10 +3,10 @@ namespace toast { auto resolveClip(std::span> clips, std::string_view clip_name, std::string_view owner) - -> const assets::AnimationClip* { + -> const assets::Handle* { for (const auto& clip : clips) { if (clip.hasValue() && (clip_name.empty() || clip->clip().name == clip_name)) { - return &clip->clip(); + return &clip; } } if (clip_name.empty()) { @@ -29,19 +29,26 @@ auto clipNames(std::span> clips) -> std: } auto AnimationPlayer::play(std::string_view clip_name) -> bool { - const assets::AnimationClip* clip = resolveClip(m_clips, clip_name, name()); + const auto* clip = resolveClip(m_clips, clip_name, name()); if (clip == nullptr) { return false; } // A new clip targets a potentially different set of nodes, so the resolved-node memo is invalid - if (clip != m_playback.clip) { + if (&(*clip)->clip() != m_playback.clip) { m_node_cache.clear(); } - m_playback.start(clip); + m_playback.start(*clip); return true; } +void AnimationPlayer::onReflectedFieldChanged(std::string_view field_name) { + Node3D::onReflectedFieldChanged(field_name); + if (field_name == "m_clips") { + m_playback.dropIfRemoved(m_clips); + } +} + auto AnimationPlayer::inspectorOptions(std::string_view field_name) -> std::vector { return field_name == "m_autoplay" ? clipNames(m_clips) : std::vector {}; } diff --git a/engine/src/toast/world/animation_player.hpp b/engine/src/toast/world/animation_player.hpp index 191d96a49..092172770 100644 --- a/engine/src/toast/world/animation_player.hpp +++ b/engine/src/toast/world/animation_player.hpp @@ -67,6 +67,7 @@ class [[ToastNode, Icon("Animation")]] TOAST_API AnimationPlayer : public Node3D private: void begin(); auto inspectorOptions(std::string_view field_name) -> std::vector override; + void onReflectedFieldChanged(std::string_view field_name) override; /// @brief Finds a node by name among this player's descendants, memoised for the lifetime of the clip auto resolveNode(const std::string& name) -> Node3D*; diff --git a/engine/src/toast/world/clip_playback.hpp b/engine/src/toast/world/clip_playback.hpp index c00ce11b1..89edb7a7d 100644 --- a/engine/src/toast/world/clip_playback.hpp +++ b/engine/src/toast/world/clip_playback.hpp @@ -5,6 +5,7 @@ */ #pragma once +#include #include #include #include @@ -15,18 +16,32 @@ namespace toast { /// Clip clock shared by AnimationPlayer and SkeletalNode struct ClipPlayback { + /// Held so removing the clip from Clips cannot free it under playback + assets::Handle asset; const assets::AnimationClip* clip = nullptr; float time = 0.0f; bool playing = false; bool paused = false; - void start(const assets::AnimationClip* new_clip) { - clip = new_clip; + void start(const assets::Handle& new_asset) { + asset = new_asset; + clip = asset.hasValue() ? &asset->clip() : nullptr; time = 0.0f; - playing = new_clip != nullptr; + playing = clip != nullptr; paused = false; } + /// Stops and releases the clip once it is no longer in @p clips + void dropIfRemoved(std::span> clips) { + if (!asset.hasValue() || + std::ranges::any_of(clips, [&](const auto& candidate) { return candidate.hasValue() && &*candidate == &*asset; })) { + return; + } + stop(); + asset = {}; + clip = nullptr; + } + void stop() { playing = false; time = 0.0f; @@ -53,7 +68,7 @@ struct ClipPlayback { /// Empty name means the first loaded clip, logs under @p owner when nothing matches TOAST_API auto resolveClip(std::span> clips, std::string_view clip_name, std::string_view owner) - -> const assets::AnimationClip*; + -> const assets::Handle*; /// Names of the loaded clips, for an Autoplay dropdown TOAST_API auto clipNames(std::span> clips) -> std::vector; diff --git a/engine/src/toast/world/skeletal_node.cpp b/engine/src/toast/world/skeletal_node.cpp index d63ce9375..e54f7597a 100644 --- a/engine/src/toast/world/skeletal_node.cpp +++ b/engine/src/toast/world/skeletal_node.cpp @@ -20,18 +20,28 @@ auto poseMatrix(const assets::BonePose& pose) -> glm::mat4 { } auto SkeletalNode::play(std::string_view clip_name) -> bool { - const assets::AnimationClip* clip = resolveClip(m_clips, clip_name, name()); + const auto* clip = resolveClip(m_clips, clip_name, name()); if (clip == nullptr) { return false; } - if (clip != m_playback.clip) { + if (&(*clip)->clip() != m_playback.clip) { m_node_cache.clear(); } - m_playback.start(clip); + m_playback.start(*clip); + // The previous clip may be freed and a new one allocated at its address + m_track_clip = nullptr; return true; } +void SkeletalNode::onReflectedFieldChanged(std::string_view field_name) { + Node3D::onReflectedFieldChanged(field_name); + if (field_name == "m_clips") { + m_playback.dropIfRemoved(m_clips); + m_track_clip = nullptr; + } +} + void SkeletalNode::stop() { m_playback.stop(); } @@ -62,7 +72,7 @@ void SkeletalNode::drawBones() { for (size_t bone = 0; bone < m_model.size(); ++bone) { const glm::vec3 position {world * m_model[bone][3]}; if (m_parents[bone] >= 0) { - debug::drawArrow(glm::vec3(world * m_model[m_parents[bone]][3]), position, k_bone_color); + debug::drawArrow(glm::vec3(world * m_model[m_parents[bone]][3]), position, k_bone_color, .05f); } else { debug::drawSphere(position, 0.03f, k_bone_color, 8); } diff --git a/engine/src/toast/world/skeletal_node.hpp b/engine/src/toast/world/skeletal_node.hpp index 987f7a808..4cb070679 100644 --- a/engine/src/toast/world/skeletal_node.hpp +++ b/engine/src/toast/world/skeletal_node.hpp @@ -91,6 +91,7 @@ class [[ToastNode, Icon("Bone")]] TOAST_API SkeletalNode : public Node3D { void begin(); void updateInspectorMessages() override; auto inspectorOptions(std::string_view field_name) -> std::vector override; + void onReflectedFieldChanged(std::string_view field_name) override; auto bindSkeleton() -> const assets::Skeleton*; void bindTracks(const assets::Skeleton& skeleton); From 4f7fe013cb97d822cdef57ddd8fca17f370c9e3d Mon Sep 17 00:00:00 2001 From: Xein Date: Sat, 14 Nov 2026 13:47:04 +0100 Subject: [PATCH 09/11] fix clang-tidy warnings --- engine/src/toast/assets/animation.hpp | 2 +- engine/src/toast/assets/gltf_importer.cpp | 2 +- engine/src/toast/assets/skeleton.cpp | 4 +++- .../toast/renderer/passes/lighting/gi_clipmap_pass.cpp | 9 +++++++-- .../toast/renderer/resources/scene_descriptor_set.cpp | 2 ++ 5 files changed, 14 insertions(+), 5 deletions(-) diff --git a/engine/src/toast/assets/animation.hpp b/engine/src/toast/assets/animation.hpp index e2f093091..bc0f6f6eb 100644 --- a/engine/src/toast/assets/animation.hpp +++ b/engine/src/toast/assets/animation.hpp @@ -91,7 +91,7 @@ struct NodePose { // uint8_t has_translation = false; // uint8_t has_rotation = false; - float _pad; + float pad; }; /// @brief A named set of tracks that play together diff --git a/engine/src/toast/assets/gltf_importer.cpp b/engine/src/toast/assets/gltf_importer.cpp index bf50c2d22..83c050d3b 100644 --- a/engine/src/toast/assets/gltf_importer.cpp +++ b/engine/src/toast/assets/gltf_importer.cpp @@ -1064,7 +1064,7 @@ auto generateIntermediates(const std::filesystem::path& path) { // The scene JSON references each .tanim and .tskel by bare filename const std::string animation_base = path.stem().string(); // glTF names are free text that would break the path or the stem GltfImporter.cs keys its UID maps by - const auto sanitize_file_name = [](std::string_view name, std::string fallback) { + const auto sanitize_file_name = [](std::string_view name, const std::string& fallback) { std::string sanitized; sanitized.reserve(name.size()); for (const char c : name) { diff --git a/engine/src/toast/assets/skeleton.cpp b/engine/src/toast/assets/skeleton.cpp index 1dc8933e3..4fdc7030a 100644 --- a/engine/src/toast/assets/skeleton.cpp +++ b/engine/src/toast/assets/skeleton.cpp @@ -2,6 +2,8 @@ #include "binary_io.hpp" +#include + namespace assets { namespace { @@ -46,7 +48,7 @@ Skeleton::Skeleton(std::span data) { bone.parent = reader.read(); bone.rest = reader.read(); // Parent below child is what lets SkeletalNode pose in one forward pass - if (bone.parent >= static_cast(b)) { + if (std::cmp_greater_equal(bone.parent, b)) { bone.parent = -1; } m_bones.push_back(std::move(bone)); diff --git a/engine/src/toast/renderer/passes/lighting/gi_clipmap_pass.cpp b/engine/src/toast/renderer/passes/lighting/gi_clipmap_pass.cpp index e51c71744..d2ae36dc9 100644 --- a/engine/src/toast/renderer/passes/lighting/gi_clipmap_pass.cpp +++ b/engine/src/toast/renderer/passes/lighting/gi_clipmap_pass.cpp @@ -647,8 +647,13 @@ auto GiClipmapPass::opacityViews() const -> std::array views; for (uint32_t i = 0; i < k_max_levels; ++i) { const Level& level = m_levels[i < m_level_count ? i : 0]; - views[i] = m_level_count == 0 ? **m_dummy_view - : (level.opacity_all_view.has_value() ? **level.opacity_all_view : **level.opacity_view); + if (m_level_count == 0) { + views[i] = **m_dummy_view; + } else if (level.opacity_all_view.has_value()) { + views[i] = **level.opacity_all_view; + } else { + views[i] = **level.opacity_view; + } } return views; } diff --git a/engine/src/toast/renderer/resources/scene_descriptor_set.cpp b/engine/src/toast/renderer/resources/scene_descriptor_set.cpp index 6fe11042e..c0bbccba6 100644 --- a/engine/src/toast/renderer/resources/scene_descriptor_set.cpp +++ b/engine/src/toast/renderer/resources/scene_descriptor_set.cpp @@ -280,6 +280,7 @@ void SceneDescriptorSets::updateTlas(uint32_t frame_index) { } if (m_clip_radiance_binding.has_value()) { std::vector infos; + infos.reserve(radiance.size()); for (const vk::ImageView view : radiance) { infos.emplace_back(clipmap->radianceSampler(), view, read); } @@ -287,6 +288,7 @@ void SceneDescriptorSets::updateTlas(uint32_t frame_index) { } if (m_clip_material_binding.has_value()) { std::vector infos; + infos.reserve(material.size()); for (const vk::ImageView view : material) { infos.emplace_back(clipmap->radianceSampler(), view, read); } From 79df526aacd64b0248a43f2f6369d3ddf4010a83 Mon Sep 17 00:00:00 2001 From: Xein Date: Sat, 14 Nov 2026 14:53:31 +0100 Subject: [PATCH 10/11] fix animation sampling test for NodePose without scale/flags --- tests/assets/03-animation-sampling.cpp | 7 +------ 1 file changed, 1 insertion(+), 6 deletions(-) diff --git a/tests/assets/03-animation-sampling.cpp b/tests/assets/03-animation-sampling.cpp index 27025a4aa..5de33334d 100644 --- a/tests/assets/03-animation-sampling.cpp +++ b/tests/assets/03-animation-sampling.cpp @@ -112,15 +112,10 @@ TOAST_TEST_NAMED("Assets", "assets/03-animation-sampling", test_assets_03_animat assert(poses.size() == 2); const auto& bone = poses.at("Bone"); - assert(bone.has_translation); - assert(!bone.has_rotation); // untouched components must stay unflagged - assert(!bone.has_scale); assert(nearly(bone.translation, glm::vec3(5.0f, 10.0f, 15.0f))); const auto& other_pose = poses.at("Other"); - assert(other_pose.has_scale); - assert(!other_pose.has_translation); - assert(nearly(other_pose.scale, glm::vec3(2.0f))); + assert(nearly(other_pose.translation, glm::vec3(0.0f))); // --- Loop wrapping --- assert(nearly(clip.wrap(0.5f), 0.5f)); From 49629e254034249885bceae543d54b28adde1f7d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dar=C3=ADo=20Rodr=C3=ADguez=20Mart=C3=ADnez?= Date: Sun, 15 Nov 2026 13:13:31 +0100 Subject: [PATCH 11/11] stupid bug --- engine/src/toast/world/skeletal_node.cpp | 1 + engine/src/toast/world/skeletal_node.hpp | 2 ++ 2 files changed, 3 insertions(+) diff --git a/engine/src/toast/world/skeletal_node.cpp b/engine/src/toast/world/skeletal_node.cpp index e54f7597a..6b8243371 100644 --- a/engine/src/toast/world/skeletal_node.cpp +++ b/engine/src/toast/world/skeletal_node.cpp @@ -114,6 +114,7 @@ auto SkeletalNode::bindSkeleton() -> const assets::Skeleton* { } m_bound = found; + m_bound_asset = found != nullptr ? m_skeleton : assets::Handle {}; m_skin_bones.clear(); m_track_clip = nullptr; m_track_to_bone.clear(); diff --git a/engine/src/toast/world/skeletal_node.hpp b/engine/src/toast/world/skeletal_node.hpp index 4cb070679..bb6fa206c 100644 --- a/engine/src/toast/world/skeletal_node.hpp +++ b/engine/src/toast/world/skeletal_node.hpp @@ -123,6 +123,8 @@ class [[ToastNode, Icon("Bone")]] TOAST_API SkeletalNode : public Node3D { ClipPlayback m_playback; + /// Held so a cleared or swapped Skeleton field cannot free m_bound or reuse its address + assets::Handle m_bound_asset; const assets::Skeleton* m_bound = nullptr; std::vector m_local; std::vector m_model;