refactor(ore): convert ore classes to be virtual with per backend implementations (#12599) e5c20369ec * started pulling out ore objects into dynamic variants * d3d11,12 and gl updated to use dynamic types * vulkan and gl now compiling * started ore wgpu * wgpu ore compiles * build system sorted * started metal impl * metal / gl update * fixed compile and linker errors * fixed convert renderpass to unique ptr * updated gm helper * missing macro guard * wrong macro * remove invalid assert * better define guard * same * build file tweaks * better macros * wasm compiling * redone stuff * properly handle emscrupten * linux link issue fix * missing filter reset * another try * another try Co-authored-by: Jonathon Copeland <jcopela4@gmail.com>
diff --git a/.rive_head b/.rive_head index ca85904..b66ec7d 100644 --- a/.rive_head +++ b/.rive_head
@@ -1 +1 @@ -679b808585a2c0dbb5da885c243e3c7f46769f0c +e5c20369ec8495836b573350d1bbfa190dd783d4
diff --git a/renderer/include/rive/renderer/d3d11/render_context_d3d_impl.hpp b/renderer/include/rive/renderer/d3d11/render_context_d3d_impl.hpp index 34adb00..d093690 100644 --- a/renderer/include/rive/renderer/d3d11/render_context_d3d_impl.hpp +++ b/renderer/include/rive/renderer/d3d11/render_context_d3d_impl.hpp
@@ -190,6 +190,7 @@ #ifdef RIVE_CANVAS rcp<RenderCanvas> makeRenderCanvas(uint32_t width, uint32_t height) override; + std::unique_ptr<rive::ore::Context> makeOreContext() override; #endif const D3DCapabilities& d3dCapabilities() const { return m_d3dCapabilities; }
diff --git a/renderer/include/rive/renderer/d3d12/render_context_d3d12_impl.hpp b/renderer/include/rive/renderer/d3d12/render_context_d3d12_impl.hpp index e5a0ae1..a6816ac 100644 --- a/renderer/include/rive/renderer/d3d12/render_context_d3d12_impl.hpp +++ b/renderer/include/rive/renderer/d3d12/render_context_d3d12_impl.hpp
@@ -113,6 +113,7 @@ #ifdef RIVE_CANVAS rcp<RenderCanvas> makeRenderCanvas(uint32_t width, uint32_t height) override; + std::unique_ptr<rive::ore::Context> makeOreContext() override; #endif #define IMPLEMENT_RIVE_BUFFER(Name, m_buffer) \
diff --git a/renderer/include/rive/renderer/gl/render_context_gl_impl.hpp b/renderer/include/rive/renderer/gl/render_context_gl_impl.hpp index 9e4af37..2c2082e 100644 --- a/renderer/include/rive/renderer/gl/render_context_gl_impl.hpp +++ b/renderer/include/rive/renderer/gl/render_context_gl_impl.hpp
@@ -65,6 +65,8 @@ rcp<RenderCanvas> makeRenderCanvas(uint32_t width, uint32_t height) override; + std::unique_ptr<rive::ore::Context> makeOreContext() override; + // GL-only: returns a Y-flipped companion of a Rive 2D RenderCanvas // texture, lazily allocating it on first call. Returns nullptr if // `sourceTex` is not a canvas target (i.e. it's a regular image).
diff --git a/renderer/include/rive/renderer/metal/render_context_metal_impl.h b/renderer/include/rive/renderer/metal/render_context_metal_impl.h index 1111fc9..d21c86e 100644 --- a/renderer/include/rive/renderer/metal/render_context_metal_impl.h +++ b/renderer/include/rive/renderer/metal/render_context_metal_impl.h
@@ -144,6 +144,7 @@ #ifdef RIVE_CANVAS rcp<RenderCanvas> makeRenderCanvas(uint32_t width, uint32_t height) override; + std::unique_ptr<rive::ore::Context> makeOreContext() override; #endif // Atomic mode requires a barrier between overlapping draws. We have to
diff --git a/renderer/include/rive/renderer/ore/ore_bind_group.hpp b/renderer/include/rive/renderer/ore/ore_bind_group.hpp index 2899015..3fabf33 100644 --- a/renderer/include/rive/renderer/ore/ore_bind_group.hpp +++ b/renderer/include/rive/renderer/ore/ore_bind_group.hpp
@@ -5,6 +5,7 @@ #pragma once #include "rive/refcnt.hpp" +#include "utils/lite_rtti.hpp" #include "rive/renderer/ore/ore_types.hpp" #include "rive/renderer/ore/ore_buffer.hpp" #include "rive/renderer/ore/ore_texture.hpp" @@ -13,24 +14,6 @@ #include <vector> -#if defined(ORE_BACKEND_METAL) -#import <Metal/Metal.h> -#endif -#if defined(ORE_BACKEND_D3D11) -#include <d3d11.h> -#include <wrl/client.h> -#endif -#if defined(ORE_BACKEND_D3D12) -#include <d3d12.h> -#include <wrl/client.h> -#endif -#if defined(ORE_BACKEND_WGPU) -#include <webgpu/webgpu_cpp.h> -#endif -#if defined(ORE_BACKEND_VK) -#include <vulkan/vulkan.h> -#endif - namespace rive::ore { @@ -41,7 +24,7 @@ // Sampler), ensuring they remain alive for the BindGroup's lifetime. // // Created via Context::makeBindGroup(). Bound via RenderPass::setBindGroup(). -class BindGroup : public RefCnt<BindGroup> +class BindGroup : public RefCnt<BindGroup>, public ENABLE_LITE_RTTI(BindGroup) { public: uint32_t dynamicOffsetCount() const { return m_dynamicOffsetCount; } @@ -52,26 +35,14 @@ BindGroupLayout* layout() const { return m_layoutRef.get(); } Context* context() const { return m_context; } -private: + virtual ~BindGroup() = default; + + // Default: immediately free. Backends that need deferred GPU-resource + // destruction (D3D12, Vulkan) override this. + virtual void onRefCntReachedZero() const { delete this; } + +protected: friend class Context; -#if defined(ORE_BACKEND_METAL) - friend class ContextMetal; -#endif -#if defined(ORE_BACKEND_GL) - friend class ContextGL; -#endif -#if defined(ORE_BACKEND_D3D11) - friend class ContextD3D11; -#endif -#if defined(ORE_BACKEND_D3D12) - friend class ContextD3D12; -#endif -#if defined(ORE_BACKEND_WGPU) - friend class ContextWGPU; -#endif -#if defined(ORE_BACKEND_VK) - friend class ContextVulkan; -#endif friend class RenderPass; BindGroup() = default; @@ -81,8 +52,7 @@ // The layout this BindGroup conforms to. Holds the per-backend native // layout handle alive for the BindGroup's lifetime — Vulkan's // VkDescriptorSetLayout in particular must outlive every VkDescriptorSet - // allocated from it. Replaces the prior `m_vkPipelineRef` (which kept - // the layout alive transitively via the pipeline). + // allocated from it. rcp<BindGroupLayout> m_layoutRef; // Lifecycle: hold rcp<> refs to all bound resources so they stay alive @@ -96,182 +66,6 @@ // to call context->deferBindGroupDestroy() instead of dropping the // last rcp<> directly, keeping the object alive until endFrame(). Context* m_context = nullptr; - - // Vulkan: VkDescriptorSetLayout lifetime is governed by `m_layoutRef` - // above (the BindGroupLayout owns the DSL handle). The descriptor set - // is allocated from Context's persistent pool at makeBindGroup time. -#if defined(ORE_BACKEND_VK) - VkDescriptorSet m_vkDescriptorSet = VK_NULL_HANDLE; -#endif -#if defined(ORE_BACKEND_WGPU) - wgpu::BindGroup m_wgpuBindGroup; - // wgpu handles are internally ref-counted; no extra Pipeline ref needed. -#endif -#if defined(ORE_BACKEND_D3D12) - // Descriptors pre-copied to CPU heap at makeBindGroup() time. - // Copied to GPU heap at setBindGroup() time. - // - // Arrays are indexed by SLOT (0-7, matching the shader's `register(t/s/b)` - // index), not by insertion order. Unbound slots have their bit cleared in - // the corresponding *SlotMask; setBindGroup() fills them with null - // descriptors so the root-signature-declared 8-slot tables are fully - // populated. Storing by slot is essential: the root sig's SRV and sampler - // descriptor tables assume GPU-heap slot == shader register, so packing by - // insertion order (the prior layout) silently read from wrong slots when - // the script used a non-dense binding layout. - D3D12_CPU_DESCRIPTOR_HANDLE m_d3dSrvHandles[8] = {}; - // Weak refs to the underlying textures bound at each SRV slot. Used by - // `d3d12ApplyBindGroup` to insert a state-transition barrier when the - // texture isn't already in a shader-resource state (e.g. a - // depth-stencil texture born in `DEPTH_WRITE` and never attached to a - // render pass — the GBV `id=1358 Incompatible texture barrier - // layout` case the `ore_binding_shadow_sampler_d32` GM hits). - // `m_retainedViews` keeps the views alive; the textures are owned by - // those views, so the raw pointers here are safe for the BindGroup's - // lifetime. - Texture* m_d3dSrvTextures[8] = {}; - D3D12_CPU_DESCRIPTOR_HANDLE m_d3dSamplerHandles[8] = {}; - D3D12_GPU_VIRTUAL_ADDRESS m_d3dUBOAddresses[8] = {}; - // UBO byte sizes per slot. Used by `setBindGroup` to create CBV - // descriptors on-the-fly into the shader-visible heap (D3D12 CBVs - // live inside the merged CBV/SRV/UAV descriptor table). - uint32_t m_d3dUBOSizes[8] = {}; - uint8_t m_d3dSrvSlotMask = 0; // bit i = slot i has a bound SRV - uint8_t m_d3dSamplerSlotMask = 0; // bit i = slot i has a bound sampler - uint8_t m_d3dUBOSlotMask = 0; // bit i = slot i has a bound UBO - // bit i = slot i's UBO has hasDynamicOffset=true. setBindGroup() consumes - // one entry from dynamicOffsets[] per set bit, in ascending slot order. - uint8_t m_d3dUBODynamicOffsetMask = 0; -#endif -#if defined(ORE_BACKEND_METAL) - // Metal: flat resource arrays applied at setBindGroup time. - // - // Per-stage Metal slots are stored independently per resource: Metal - // has separate VS / FS argument tables, and the allocator is free to - // assign different per-stage slots, so VS-only UBO A and FS-only UBO B - // can share Metal slot 0 in their own stages. Each `*Slot` is - // `BindingMap::kAbsent` when the binding isn't visible to that stage; - // setBindGroup then skips the per-stage emit instead of forwarding `0` - // (which would clobber another resource's slot). - // - // `binding` carries the WGSL `@binding` value, used as the sort key - // for dynamic-offset ordering: WebGPU requires `dynamicOffsets[i]` to - // be consumed in BindGroupLayout entry order, which is ascending - // `@binding` within a kind. Sorting at construction time makes the - // BindGroup robust to callers who pass `desc.ubos[]` in any order. - struct MTLBufferBinding - { - id<MTLBuffer> buffer = nil; - uint32_t offset = 0; - uint32_t binding = 0; // WGSL @binding — sort key for dynamicOffsets[]. - uint16_t vsSlot = 0xFFFF; // BindingMap::kAbsent. - uint16_t fsSlot = 0xFFFF; - // Populated from `BindGroupLayout::hasDynamicOffset(binding)` at - // makeBindGroup time. setBindGroup consumes one `dynamicOffsets[]` - // entry per `hasDynamicOffset=true` UBO in `binding`-ascending order. - bool hasDynamicOffset = false; - }; - struct MTLTextureBinding - { - id<MTLTexture> texture = nil; - uint16_t vsSlot = 0xFFFF; - uint16_t fsSlot = 0xFFFF; - }; - struct MTLSamplerBinding - { - id<MTLSamplerState> sampler = nil; - uint16_t vsSlot = 0xFFFF; - uint16_t fsSlot = 0xFFFF; - }; - std::vector<MTLBufferBinding> m_mtlBuffers; - std::vector<MTLTextureBinding> m_mtlTextures; - std::vector<MTLSamplerBinding> m_mtlSamplers; -#endif -#if defined(ORE_BACKEND_GL) - // GL: single slot per binding (GL has a flat global namespace across - // stages, no per-stage register split). `binding` carries the WGSL - // `@binding` value, used as the sort key for dynamic-offset ordering - // (consumed in BindGroupLayout-entry order regardless of the - // caller-supplied `desc.ubos[]` shape). - struct GLUBOBinding - { - unsigned int buffer = 0; - uint32_t offset = 0; - uint32_t size = 0; - uint32_t binding = 0; // WGSL @binding — sort key for dynamicOffsets[]. - uint32_t slot = 0; // GL binding point (allocator's global slot). - // Populated from `BindGroupLayout::hasDynamicOffset(binding)` at - // makeBindGroup time. setBindGroup consumes one `dynamicOffsets[]` - // entry per `hasDynamicOffset=true` UBO in `binding`-ascending order. - bool hasDynamicOffset = false; - }; - struct GLTexBinding - { - unsigned int texture = 0; - unsigned int target = 0; - uint32_t slot = 0; - }; - struct GLSamplerBinding - { - unsigned int sampler = 0; - uint32_t slot = 0; - }; - std::vector<GLUBOBinding> m_glUBOs; - std::vector<GLTexBinding> m_glTextures; - std::vector<GLSamplerBinding> m_glSamplers; -#endif -#if defined(ORE_BACKEND_D3D11) - // D3D11: store resource pointers + per-stage register slots. - // - // D3D11 has independent VS / PS register namespaces (`b0` in VS is a - // different register than `b0` in PS). The allocator is free to assign - // different per-stage register numbers, so VS-only and PS-only - // resources can share register 0 in their own stages. Each `*Slot` is - // `BindingMap::kAbsent` when the binding isn't visible to that stage; - // setBindGroup then skips the per-stage `VSSet*` / `PSSet*` call so - // we don't overwrite another resource's slot. - // - // `binding` carries the WGSL `@binding` value, used as the sort key - // for dynamic-offset ordering (same shape as the Metal binding) so - // `dynamicOffsets[]` consumption matches BindGroupLayout-entry - // order regardless of caller-supplied `desc.ubos[]` shape. - // - // `offset`/`size` are in bytes; applied via VSSetConstantBuffers1 / - // PSSetConstantBuffers1 (which take firstConstant / numConstants in - // 16-byte units — D3D11 requires 256-byte alignment ≡ 16 constants). - struct D3D11UBOBinding - { - ID3D11Buffer* buffer = nullptr; // Weak ref; rcp held in - // m_retainedBuffers. - uint32_t binding = 0; // WGSL @binding — sort key for dynamicOffsets[]. - uint16_t vsSlot = 0xFFFF; // BindingMap::kAbsent. - uint16_t psSlot = 0xFFFF; - uint32_t offset = 0; - uint32_t size = 0; - // Populated from `BindGroupLayout::hasDynamicOffset(binding)` at - // makeBindGroup time. setBindGroup consumes one `dynamicOffsets[]` - // entry per `hasDynamicOffset=true` UBO in `binding`-ascending order. - bool hasDynamicOffset = false; - }; - struct D3D11TexBinding - { - ID3D11ShaderResourceView* srv = nullptr; // Weak ref. - uint16_t vsSlot = 0xFFFF; - uint16_t psSlot = 0xFFFF; - }; - struct D3D11SamplerBinding - { - ID3D11SamplerState* sampler = nullptr; // Weak ref. - uint16_t vsSlot = 0xFFFF; - uint16_t psSlot = 0xFFFF; - }; - std::vector<D3D11UBOBinding> m_d3d11UBOs; - std::vector<D3D11TexBinding> m_d3d11Textures; - std::vector<D3D11SamplerBinding> m_d3d11Samplers; -#endif - -public: - void onRefCntReachedZero() const; }; } // namespace rive::ore
diff --git a/renderer/include/rive/renderer/ore/ore_bind_group_layout.hpp b/renderer/include/rive/renderer/ore/ore_bind_group_layout.hpp index 30a8581..84c8531 100644 --- a/renderer/include/rive/renderer/ore/ore_bind_group_layout.hpp +++ b/renderer/include/rive/renderer/ore/ore_bind_group_layout.hpp
@@ -5,61 +5,29 @@ #pragma once #include "rive/refcnt.hpp" +#include "utils/lite_rtti.hpp" #include "rive/renderer/ore/ore_types.hpp" #include "rive/renderer/ore/ore_binding_map.hpp" #include <string> #include <vector> -// Only the backends that store a native handle on `BindGroupLayout` need -// their headers here. Metal / D3D11 / GL keep entries-only layouts (no -// native handle), so their backend headers are NOT pulled in — that lets -// the cross-backend `ore_bind_group_layout.cpp` compile as plain C++. -#if defined(ORE_BACKEND_D3D12) -#include <d3d12.h> -#include <wrl/client.h> -#endif -#if defined(ORE_BACKEND_WGPU) -#include <webgpu/webgpu_cpp.h> -#endif -#if defined(ORE_BACKEND_VK) -#include <vulkan/vulkan.h> -#endif - namespace rive::ore { class Context; - -#if defined(ORE_BACKEND_D3D12) -// Per-group root-parameter metadata for D3D12. Moved from `Pipeline` (where -// it was historically derived from the binding map at pipeline build time) -// onto `BindGroupLayout` so multiple pipelines that share a layout produce -// the same per-group descriptor-table shape. The composing root signature -// is still per-pipeline (D3D12 root sigs are cross-group). -struct D3D12GroupRootParams -{ - int8_t cbvSrvUavRootParamIdx = -1; - int8_t samplerRootParamIdx = -1; - uint8_t cbvCount = 0; - uint8_t srvCount = 0; - uint8_t uavCount = 0; - uint8_t samplerCount = 0; - uint8_t cbvBaseGlobalSlot = 0; - uint8_t srvBaseGlobalSlot = 0; - uint8_t uavBaseGlobalSlot = 0; - uint8_t samplerBaseGlobalSlot = 0; -}; -#endif +class ContextMetal; +class ContextGL; +class ContextD3D11; // Public Ore type — created via `Context::makeBindGroupLayout`. Carries the // user-supplied entries plus per-backend baked layout handles. // // Lifetime: outlives any `Pipeline` or `BindGroup` that references it. // `Pipeline` holds `rcp<BindGroupLayout> m_layouts[kMaxBindGroups]`; -// `BindGroup` holds `rcp<BindGroupLayout> m_layoutRef`. Vulkan's -// `vkDestroyDescriptorSetLayout` runs only after the last consumer drops. -class BindGroupLayout : public RefCnt<BindGroupLayout> +// `BindGroup` holds `rcp<BindGroupLayout> m_layoutRef`. +class BindGroupLayout : public RefCnt<BindGroupLayout>, + public ENABLE_LITE_RTTI(BindGroupLayout) { public: uint32_t groupIndex() const { return m_groupIndex; } @@ -68,74 +36,32 @@ return m_entries; } -#if defined(ORE_BACKEND_D3D12) - // D3D12-only: per-group descriptor-table shape (counts + base global - // slots). Read by `buildPerPipelineRootSig` to compose the root sig. - const D3D12GroupRootParams& d3dGroupParams() const - { - return m_d3dGroupParams; - } -#endif - // True if entry for `binding` (within this layout's group) is a UBO - // declared with `hasDynamicOffset = true`. Replaces - // `Pipeline::isDynamicUBO()`. Each backend's BindGroup caches this at - // makeBindGroup time per-slot to know when to consume from - // `dynamicOffsets[]` at setBindGroup time. + // declared with `hasDynamicOffset = true`. bool hasDynamicOffset(uint32_t binding) const; // Find the entry for a given binding. Returns nullptr if not present. const BindGroupLayoutEntry* findEntry(uint32_t binding) const; -private: + virtual ~BindGroupLayout() = default; + + // Default: immediately free. Backends that need deferred GPU-resource + // destruction (D3D12, Vulkan) override this. + virtual void onRefCntReachedZero() const { delete this; } + +protected: friend class Context; -#if defined(ORE_BACKEND_METAL) friend class ContextMetal; -#endif -#if defined(ORE_BACKEND_GL) friend class ContextGL; -#endif -#if defined(ORE_BACKEND_D3D11) friend class ContextD3D11; -#endif -#if defined(ORE_BACKEND_D3D12) - friend class ContextD3D12; -#endif -#if defined(ORE_BACKEND_WGPU) - friend class ContextWGPU; -#endif -#if defined(ORE_BACKEND_VK) - friend class ContextVulkan; -#endif BindGroupLayout() = default; uint32_t m_groupIndex = 0; std::vector<BindGroupLayoutEntry> m_entries; - // Context back-pointer for deferred-destruction routing through - // Context::vkDeferDestroy / d3dDeferDestroy. Weak ref. + // Context back-pointer for deferred-destruction routing. Weak ref. Context* m_context = nullptr; - -#if defined(ORE_BACKEND_VK) - VkDevice m_vkDevice = VK_NULL_HANDLE; - VkDescriptorSetLayout m_vkDSL = VK_NULL_HANDLE; - PFN_vkDestroyDescriptorSetLayout m_vkDestroyDescriptorSetLayout = nullptr; -#endif -#if defined(ORE_BACKEND_WGPU) - wgpu::BindGroupLayout m_wgpuBGL; -#endif -#if defined(ORE_BACKEND_D3D12) - D3D12GroupRootParams m_d3dGroupParams; -#endif - // Metal / D3D11 / GL / D3D12-bind-side: the user-supplied entries above - // plus shader-resolved native slots per-stage are sufficient to drive - // makeBindGroup for those backends. Slots are looked up via the - // pipeline's BindingMap at makeBindGroup time and validated against - // this layout at makePipeline time. - -public: - void onRefCntReachedZero() const; }; // Validate user-supplied layouts against the shader's reflected binding map. @@ -145,21 +71,13 @@ // shader's stageMask, texture dim/sample type compatible. // // Returns true on success. On failure, populates `*outError` with a human- -// readable diagnostic (e.g. "@group(1) @binding(0): layout declares -// uniformBuffer but shader expects sampledTexture") and returns false. Never -// asserts. -// -// Called by every backend's `makePipeline` after the user-supplied layouts -// have been collected, before any backend-specific build work. +// readable diagnostic and returns false. Never asserts. bool validateLayoutsAgainstBindingMap(const BindingMap& bindingMap, BindGroupLayout* const* layouts, uint32_t layoutCount, std::string* outError); -// Color outputs require a fragment shader. Mirrors Dawn's -// ValidateRenderPipelineDescriptor invariant. Depth-only pipelines -// (colorCount == 0) may legitimately omit the fragment module — the -// rasterizer still writes depth. +// Color outputs require a fragment shader. bool validateColorRequiresFragment(uint32_t colorCount, bool hasFragmentModule, std::string* outError);
diff --git a/renderer/include/rive/renderer/ore/ore_buffer.hpp b/renderer/include/rive/renderer/ore/ore_buffer.hpp index e940f6d..3a1c317 100644 --- a/renderer/include/rive/renderer/ore/ore_buffer.hpp +++ b/renderer/include/rive/renderer/ore/ore_buffer.hpp
@@ -5,115 +5,38 @@ #pragma once #include "rive/refcnt.hpp" +#include "utils/lite_rtti.hpp" #include "rive/renderer/ore/ore_types.hpp" -#if defined(ORE_BACKEND_METAL) -#import <Metal/Metal.h> -#endif -// Note: load_gles_extensions.hpp (glad) is intentionally NOT included here. -// GL object handles are GLuint = unsigned int; no glad needed in the header. -#if defined(ORE_BACKEND_D3D11) -#include <d3d11.h> -#include <wrl/client.h> -#endif -#if defined(ORE_BACKEND_D3D12) -#include <d3d12.h> -#include <wrl/client.h> -#endif -#if defined(ORE_BACKEND_WGPU) -#include <webgpu/webgpu_cpp.h> -#endif -#if defined(ORE_BACKEND_VK) -#include <vulkan/vulkan.h> -VK_DEFINE_HANDLE(VmaAllocator); -VK_DEFINE_HANDLE(VmaAllocation); -#endif - namespace rive::ore { class Context; -#if defined(ORE_BACKEND_VK) -class ContextVulkan; -#endif -#if defined(ORE_BACKEND_D3D12) -class ContextD3D12; -#endif -class Buffer : public RefCnt<Buffer> +class Buffer : public RefCnt<Buffer>, public ENABLE_LITE_RTTI(Buffer) { public: uint32_t size() const { return m_size; } BufferUsage usage() const { return m_usage; } - void update(const void* data, uint32_t size, uint32_t offset = 0); + virtual void update(const void* data, + uint32_t size, + uint32_t offset = 0) = 0; -private: + virtual ~Buffer() = default; + + // Default: immediately free the CPU object. Backends that need deferred + // GPU-resource destruction (D3D12, Vulkan) override this. + virtual void onRefCntReachedZero() const { delete this; } + +protected: friend class Context; -#if defined(ORE_BACKEND_METAL) - friend class ContextMetal; -#endif -#if defined(ORE_BACKEND_GL) - friend class ContextGL; -#endif -#if defined(ORE_BACKEND_D3D11) - friend class ContextD3D11; -#endif -#if defined(ORE_BACKEND_D3D12) - friend class ContextD3D12; -#endif -#if defined(ORE_BACKEND_WGPU) - friend class ContextWGPU; -#endif -#if defined(ORE_BACKEND_VK) - friend class ContextVulkan; -#endif friend class RenderPass; Buffer(uint32_t size, BufferUsage usage) : m_size(size), m_usage(usage) {} uint32_t m_size; BufferUsage m_usage; - -#if defined(ORE_BACKEND_METAL) - id<MTLBuffer> m_mtlBuffer = nil; -#endif -#if defined(ORE_BACKEND_GL) - unsigned int m_glBuffer = 0; - unsigned int m_glTarget = 0; -#endif -#if defined(ORE_BACKEND_D3D11) - Microsoft::WRL::ComPtr<ID3D11Buffer> m_d3d11Buffer; - ID3D11DeviceContext* m_d3d11Context = - nullptr; // Weak ref, set by Context::makeBuffer. -#endif -#if defined(ORE_BACKEND_WGPU) - wgpu::Buffer m_wgpuBuffer; - wgpu::Queue - m_wgpuQueue; // Weak ref (addref'd copy), set by Context::makeBuffer. -#endif -#if defined(ORE_BACKEND_VK) - VkBuffer m_vkBuffer = VK_NULL_HANDLE; - VmaAllocation m_vmaAllocation = VK_NULL_HANDLE; - void* m_vkMappedPtr = nullptr; - VkDevice m_vkDevice = VK_NULL_HANDLE; // Weak ref. - VmaAllocator m_vmaAllocator = VK_NULL_HANDLE; // Weak ref. - // Back-ref so onRefCntReachedZero() can route the vmaDestroyBuffer call - // through ContextVulkan::vkDeferDestroy() in external-CB mode. Weak ref. - ContextVulkan* m_vkOreContext = nullptr; -#endif -#if defined(ORE_BACKEND_D3D12) - // UPLOAD heap — persistently mapped; GPU reads directly (acceptable for - // tests). - Microsoft::WRL::ComPtr<ID3D12Resource> m_d3dBuffer; - void* m_d3dMappedPtr = nullptr; - // Back-ref so onRefCntReachedZero() can route the ComPtr release through - // ContextD3D12::d3dDeferDestroy() in external-CL mode. Weak ref. - ContextD3D12* m_d3dOreContext = nullptr; -#endif - -public: - void onRefCntReachedZero() const; }; } // namespace rive::ore
diff --git a/renderer/include/rive/renderer/ore/ore_context.hpp b/renderer/include/rive/renderer/ore/ore_context.hpp index 76094c0..dfd4481 100644 --- a/renderer/include/rive/renderer/ore/ore_context.hpp +++ b/renderer/include/rive/renderer/ore/ore_context.hpp
@@ -73,8 +73,9 @@ std::string* outError = nullptr) = 0; virtual rcp<BindGroup> makeBindGroup(const BindGroupDesc& desc) = 0; - virtual RenderPass beginRenderPass(const RenderPassDesc& desc, - std::string* outError = nullptr) = 0; + virtual std::unique_ptr<RenderPass> beginRenderPass( + const RenderPassDesc& desc, + std::string* outError = nullptr) = 0; // Frame lifecycle (owned-CL form). For external-CL mode, see the // typed beginFrame overload on the relevant per-backend subclass
diff --git a/renderer/include/rive/renderer/ore/ore_context_d3d11.hpp b/renderer/include/rive/renderer/ore/ore_context_d3d11.hpp index 2ce88c6..dc5559e 100644 --- a/renderer/include/rive/renderer/ore/ore_context_d3d11.hpp +++ b/renderer/include/rive/renderer/ore/ore_context_d3d11.hpp
@@ -32,8 +32,9 @@ std::string* outError = nullptr) override; rcp<BindGroup> makeBindGroup(const BindGroupDesc& desc) override; - RenderPass beginRenderPass(const RenderPassDesc& desc, - std::string* outError = nullptr) override; + std::unique_ptr<RenderPass> beginRenderPass( + const RenderPassDesc& desc, + std::string* outError = nullptr) override; void beginFrame() override; void endFrame() override; @@ -48,9 +49,9 @@ ContextD3D11& operator=(const ContextD3D11&) = delete; private: - friend class RenderPass; - friend class BindGroup; - friend class Texture; + friend class RenderPassD3D11; + friend class BindGroupD3D11; + friend class TextureD3D11; ContextD3D11() = default; @@ -65,8 +66,8 @@ rcp<BindGroup> d3d11MakeBindGroup(const BindGroupDesc& desc); rcp<BindGroupLayout> d3d11MakeBindGroupLayout( const BindGroupLayoutDesc& desc); - RenderPass d3d11BeginRenderPass(const RenderPassDesc& desc, - std::string* outError); + std::unique_ptr<RenderPass> d3d11BeginRenderPass(const RenderPassDesc& desc, + std::string* outError); rcp<TextureView> d3d11WrapCanvasTexture(gpu::RenderCanvas* canvas); rcp<TextureView> d3d11WrapRiveTexture(gpu::Texture* gpuTex, uint32_t w,
diff --git a/renderer/include/rive/renderer/ore/ore_context_d3d12.hpp b/renderer/include/rive/renderer/ore/ore_context_d3d12.hpp index 9db4818..01f7b98 100644 --- a/renderer/include/rive/renderer/ore/ore_context_d3d12.hpp +++ b/renderer/include/rive/renderer/ore/ore_context_d3d12.hpp
@@ -36,8 +36,9 @@ std::string* outError = nullptr) override; rcp<BindGroup> makeBindGroup(const BindGroupDesc& desc) override; - RenderPass beginRenderPass(const RenderPassDesc& desc, - std::string* outError = nullptr) override; + std::unique_ptr<RenderPass> beginRenderPass( + const RenderPassDesc& desc, + std::string* outError = nullptr) override; void beginFrame() override; void endFrame() override; @@ -71,9 +72,9 @@ ContextD3D12& operator=(const ContextD3D12&) = delete; private: - friend class RenderPass; - friend class BindGroup; - friend class Texture; + friend class RenderPassD3D12; + friend class BindGroupD3D12; + friend class TextureD3D12; ContextD3D12() = default; @@ -88,8 +89,8 @@ rcp<BindGroup> d3d12MakeBindGroup(const BindGroupDesc& desc); rcp<BindGroupLayout> d3d12MakeBindGroupLayout( const BindGroupLayoutDesc& desc); - RenderPass d3d12BeginRenderPass(const RenderPassDesc& desc, - std::string* outError); + std::unique_ptr<RenderPass> d3d12BeginRenderPass(const RenderPassDesc& desc, + std::string* outError); rcp<TextureView> d3d12WrapCanvasTexture(gpu::RenderCanvas* canvas); rcp<TextureView> d3d12WrapRiveTexture(gpu::Texture* gpuTex, uint32_t w,
diff --git a/renderer/include/rive/renderer/ore/ore_context_gl.hpp b/renderer/include/rive/renderer/ore/ore_context_gl.hpp index de760d2..da92146 100644 --- a/renderer/include/rive/renderer/ore/ore_context_gl.hpp +++ b/renderer/include/rive/renderer/ore/ore_context_gl.hpp
@@ -13,6 +13,10 @@ namespace rive::ore { +class RenderPassGL; +class BindGroupGL; +class TextureGL; + class ContextGL : public Context { public: @@ -31,8 +35,9 @@ std::string* outError = nullptr) override; rcp<BindGroup> makeBindGroup(const BindGroupDesc& desc) override; - RenderPass beginRenderPass(const RenderPassDesc& desc, - std::string* outError = nullptr) override; + std::unique_ptr<RenderPass> beginRenderPass( + const RenderPassDesc& desc, + std::string* outError = nullptr) override; void beginFrame() override; void endFrame() override; @@ -47,9 +52,9 @@ ContextGL& operator=(const ContextGL&) = delete; private: - friend class RenderPass; - friend class BindGroup; - friend class Texture; + friend class RenderPassGL; + friend class BindGroupGL; + friend class TextureGL; ContextGL() = default;
diff --git a/renderer/include/rive/renderer/ore/ore_context_metal.hpp b/renderer/include/rive/renderer/ore/ore_context_metal.hpp index 4e60fe7..9f246a4 100644 --- a/renderer/include/rive/renderer/ore/ore_context_metal.hpp +++ b/renderer/include/rive/renderer/ore/ore_context_metal.hpp
@@ -11,6 +11,10 @@ namespace rive::ore { +class RenderPassMetal; +class BindGroupMetal; +class TextureMetal; + class ContextMetal : public Context { public: @@ -30,8 +34,9 @@ std::string* outError = nullptr) override; rcp<BindGroup> makeBindGroup(const BindGroupDesc& desc) override; - RenderPass beginRenderPass(const RenderPassDesc& desc, - std::string* outError = nullptr) override; + std::unique_ptr<RenderPass> beginRenderPass( + const RenderPassDesc& desc, + std::string* outError = nullptr) override; void beginFrame() override; void endFrame() override; @@ -46,9 +51,9 @@ ContextMetal& operator=(const ContextMetal&) = delete; private: - friend class RenderPass; - friend class BindGroup; - friend class Texture; + friend class RenderPassMetal; + friend class BindGroupMetal; + friend class TextureMetal; ContextMetal() = default; @@ -63,8 +68,8 @@ rcp<Pipeline> mtlMakePipeline(const PipelineDesc& desc, std::string* outError); rcp<BindGroup> mtlMakeBindGroup(const BindGroupDesc& desc); - RenderPass mtlBeginRenderPass(const RenderPassDesc& desc, - std::string* outError); + std::unique_ptr<RenderPass> mtlBeginRenderPass(const RenderPassDesc& desc, + std::string* outError); rcp<TextureView> mtlWrapCanvasTexture(gpu::RenderCanvas* canvas); id<MTLDevice> m_mtlDevice = nil;
diff --git a/renderer/include/rive/renderer/ore/ore_context_vulkan.hpp b/renderer/include/rive/renderer/ore/ore_context_vulkan.hpp index 32ded7f..a78abbb 100644 --- a/renderer/include/rive/renderer/ore/ore_context_vulkan.hpp +++ b/renderer/include/rive/renderer/ore/ore_context_vulkan.hpp
@@ -5,7 +5,7 @@ #pragma once #include "rive/renderer/ore/ore_context.hpp" - +#include "rive/renderer/vulkan/vulkan_context.hpp" #include <functional> #include <utility> #include <vk_mem_alloc.h> @@ -64,13 +64,9 @@ // The caller is responsible for creating all Vulkan objects and the VMA // allocator. Ore does not manage device lifetime. static std::unique_ptr<ContextVulkan> Make( - VkInstance instance, - VkPhysicalDevice physicalDevice, - VkDevice device, + const rcp<rive::gpu::VulkanContext> vk, VkQueue queue, - uint32_t queueFamilyIndex, - VmaAllocator allocator, - PFN_vkGetInstanceProcAddr pfnGetInstanceProcAddr); + uint32_t queueFamilyIndex); ~ContextVulkan() override; @@ -85,8 +81,9 @@ std::string* outError = nullptr) override; rcp<BindGroup> makeBindGroup(const BindGroupDesc& desc) override; - RenderPass beginRenderPass(const RenderPassDesc& desc, - std::string* outError = nullptr) override; + std::unique_ptr<RenderPass> beginRenderPass( + const RenderPassDesc& desc, + std::string* outError = nullptr) override; void beginFrame() override; void endFrame() override; @@ -118,85 +115,18 @@ // Called by makePipeline() (with DONT_CARE ops) and beginRenderPass(). VkRenderPass getOrCreateRenderPass(const VKRenderPassKey&); - // Vulkan function dispatch table. - // Populated by Make(); all call sites use m_vk.Xxx(...) to avoid direct - // vkXxx() symbols which are stripped when VK_NO_PROTOTYPES is defined. -#define ORE_VK_INSTANCE_COMMANDS(F) \ - F(GetDeviceProcAddr) \ - F(GetPhysicalDeviceProperties) \ - F(GetPhysicalDeviceFeatures) - -#define ORE_VK_DEVICE_COMMANDS(F) \ - F(AllocateCommandBuffers) \ - F(AllocateDescriptorSets) \ - F(FreeDescriptorSets) \ - F(BeginCommandBuffer) \ - F(CmdBeginRenderPass) \ - F(CmdBindDescriptorSets) \ - F(CmdBindIndexBuffer) \ - F(CmdBindPipeline) \ - F(CmdBindVertexBuffers) \ - F(CmdCopyBufferToImage) \ - F(CmdDraw) \ - F(CmdDrawIndexed) \ - F(CmdEndRenderPass) \ - F(CmdPipelineBarrier) \ - F(CmdSetBlendConstants) \ - F(CmdSetScissor) \ - F(CmdSetStencilReference) \ - F(CmdSetViewport) \ - F(CreateCommandPool) \ - F(CreateDescriptorPool) \ - F(CreateDescriptorSetLayout) \ - F(CreateFramebuffer) \ - F(CreateGraphicsPipelines) \ - F(CreateImageView) \ - F(CreatePipelineLayout) \ - F(CreateRenderPass) \ - F(CreateSampler) \ - F(CreateShaderModule) \ - F(DestroyCommandPool) \ - F(DestroyDescriptorPool) \ - F(DestroyDescriptorSetLayout) \ - F(DestroyFramebuffer) \ - F(DestroyImageView) \ - F(DestroyPipeline) \ - F(DestroyPipelineLayout) \ - F(DestroyRenderPass) \ - F(DestroySampler) \ - F(DestroyShaderModule) \ - F(EndCommandBuffer) \ - F(CreateFence) \ - F(DestroyFence) \ - F(WaitForFences) \ - F(ResetFences) \ - F(QueueSubmit) \ - F(QueueWaitIdle) \ - F(ResetCommandBuffer) \ - F(ResetDescriptorPool) \ - F(UpdateDescriptorSets) - - struct VkFn - { -#define DECLARE_VK_CMD(CMD) PFN_vk##CMD CMD = nullptr; - ORE_VK_INSTANCE_COMMANDS(DECLARE_VK_CMD) - ORE_VK_DEVICE_COMMANDS(DECLARE_VK_CMD) -#undef DECLARE_VK_CMD - }; - ContextVulkan(const ContextVulkan&) = delete; ContextVulkan& operator=(const ContextVulkan&) = delete; private: - friend class RenderPass; - friend class BindGroup; - friend class Texture; + friend class RenderPassVulkan; + friend class BindGroupVulkan; + friend class TextureVulkan; - ContextVulkan() = default; + ContextVulkan(const rcp<rive::gpu::VulkanContext> vk) : m_vk(vk) {} - VkFn m_vk; - VkPhysicalDevice m_vkPhysicalDevice = VK_NULL_HANDLE; - VkDevice m_vkDevice = VK_NULL_HANDLE; + const rcp<rive::gpu::VulkanContext> m_vk; + VkQueue m_vkQueue = VK_NULL_HANDLE; uint32_t m_vkQueueFamily = 0; VmaAllocator m_vmaAllocator = VK_NULL_HANDLE;
diff --git a/renderer/include/rive/renderer/ore/ore_context_wgpu.hpp b/renderer/include/rive/renderer/ore/ore_context_wgpu.hpp index 44891d5..6a58384 100644 --- a/renderer/include/rive/renderer/ore/ore_context_wgpu.hpp +++ b/renderer/include/rive/renderer/ore/ore_context_wgpu.hpp
@@ -7,7 +7,7 @@ #include "rive/renderer/ore/ore_context.hpp" #include <webgpu/webgpu_cpp.h> -#ifndef RIVE_DAWN +#ifdef RIVE_WAGYU #include <webgpu/webgpu_wagyu.h> #endif @@ -36,8 +36,9 @@ std::string* outError = nullptr) override; rcp<BindGroup> makeBindGroup(const BindGroupDesc& desc) override; - RenderPass beginRenderPass(const RenderPassDesc& desc, - std::string* outError = nullptr) override; + std::unique_ptr<RenderPass> beginRenderPass( + const RenderPassDesc& desc, + std::string* outError = nullptr) override; void beginFrame() override; void endFrame() override; @@ -69,9 +70,9 @@ ContextWGPU& operator=(const ContextWGPU&) = delete; private: - friend class RenderPass; - friend class BindGroup; - friend class Texture; + friend class RenderPassWGPU; + friend class BindGroupWGPU; + friend class TextureWGPU; ContextWGPU() = default;
diff --git a/renderer/include/rive/renderer/ore/ore_pipeline.hpp b/renderer/include/rive/renderer/ore/ore_pipeline.hpp index a2915dd..09ed7ef 100644 --- a/renderer/include/rive/renderer/ore/ore_pipeline.hpp +++ b/renderer/include/rive/renderer/ore/ore_pipeline.hpp
@@ -5,54 +5,28 @@ #pragma once #include "rive/refcnt.hpp" +#include "utils/lite_rtti.hpp" #include "rive/renderer/ore/ore_types.hpp" #include "rive/renderer/ore/ore_bind_group_layout.hpp" #include "rive/renderer/ore/ore_shader_module.hpp" #include <vector> -#if defined(ORE_BACKEND_METAL) -#import <Metal/Metal.h> -#endif -// Note: load_gles_extensions.hpp (glad) is intentionally NOT included here. -// GL object handles are GLuint = unsigned int; no glad needed in the header. -#if defined(ORE_BACKEND_D3D11) -#include <d3d11.h> -#include <wrl/client.h> -#endif -#if defined(ORE_BACKEND_D3D12) -#include <d3d12.h> -#include <wrl/client.h> -#endif -#if defined(ORE_BACKEND_WGPU) -#include <webgpu/webgpu_cpp.h> -#endif -#if defined(ORE_BACKEND_VK) -#include <vulkan/vulkan.h> -#endif - namespace rive::ore { class Context; -#if defined(ORE_BACKEND_VK) -class ContextVulkan; -#endif -#if defined(ORE_BACKEND_D3D12) -class ContextD3D12; -#endif -class Pipeline : public RefCnt<Pipeline> +class Pipeline : public RefCnt<Pipeline>, public ENABLE_LITE_RTTI(Pipeline) { public: const PipelineDesc& desc() const { return m_desc; } // (group, binding) → per-backend native slot map for this pipeline's // resources. Copied from the vertex / fragment ShaderModule at - // construction. Consumed by each flatten-backend's `makeBindGroup` - // to translate a `BindGroupDesc::*Entry::slot` (= WGSL `@binding`) - // into the backend's native slot (Metal buffer index, HLSL register, - // GL binding point, D3D12 `BaseShaderRegister`). + // construction. Consumed by each backend's `makeBindGroup` to translate + // a `BindGroupDesc::*Entry::slot` (= WGSL `@binding`) into the backend's + // native slot. BindingMap m_bindingMap; // Layouts the pipeline was created with — one per `@group(N)`. Keeps @@ -62,26 +36,14 @@ // matching WebGPU's exact-layout requirement). rcp<BindGroupLayout> m_layouts[kMaxBindGroups]; -private: + virtual ~Pipeline() = default; + + // Default: immediately free. Backends that need deferred GPU-resource + // destruction (D3D12, Vulkan) override this. + virtual void onRefCntReachedZero() const { delete this; } + +protected: friend class Context; -#if defined(ORE_BACKEND_METAL) - friend class ContextMetal; -#endif -#if defined(ORE_BACKEND_GL) - friend class ContextGL; -#endif -#if defined(ORE_BACKEND_D3D11) - friend class ContextD3D11; -#endif -#if defined(ORE_BACKEND_D3D12) - friend class ContextD3D12; -#endif -#if defined(ORE_BACKEND_WGPU) - friend class ContextWGPU; -#endif -#if defined(ORE_BACKEND_VK) - friend class ContextVulkan; -#endif friend class RenderPass; Pipeline(const PipelineDesc& desc) : m_desc(desc) @@ -111,69 +73,6 @@ } PipelineDesc m_desc; - -#if defined(ORE_BACKEND_METAL) - id<MTLRenderPipelineState> m_mtlPipeline = nil; - id<MTLDepthStencilState> m_mtlDepthStencil = nil; -#endif -#if defined(ORE_BACKEND_GL) - unsigned int m_glProgram = 0; -#endif -#if defined(ORE_BACKEND_D3D11) - Microsoft::WRL::ComPtr<ID3D11InputLayout> m_d3dInputLayout; - Microsoft::WRL::ComPtr<ID3D11RasterizerState> m_d3dRasterizer; - Microsoft::WRL::ComPtr<ID3D11DepthStencilState> m_d3dDepthStencil; - Microsoft::WRL::ComPtr<ID3D11BlendState> m_d3dBlend; - ID3D11VertexShader* m_d3dVS = nullptr; - ID3D11PixelShader* m_d3dPS = nullptr; - // Strong refs to keep ShaderModules alive for the lifetime of the - // Pipeline. Without these, Luau GC can destroy the ScriptedShader - // (and its ShaderModules) while the Pipeline still references them, - // causing use-after-free crashes in the D3D11 driver. - rcp<ShaderModule> m_vsModule; - rcp<ShaderModule> m_psModule; -#endif -#if defined(ORE_BACKEND_WGPU) - wgpu::Device m_wgpuDevice; // Needed to create bind groups at draw time. - wgpu::RenderPipeline m_wgpuPipeline; - wgpu::PipelineLayout m_wgpuPipelineLayout; -#endif -#if defined(ORE_BACKEND_VK) - VkDevice m_vkDevice = VK_NULL_HANDLE; - VkPipelineLayout m_vkPipelineLayout = VK_NULL_HANDLE; - VkPipeline m_vkPipeline = VK_NULL_HANDLE; - VkPrimitiveTopology m_vkTopology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST; - // Function pointers for cleanup (loaded by Context::makePipeline). - PFN_vkDestroyPipeline m_vkDestroyPipeline = nullptr; - PFN_vkDestroyPipelineLayout m_vkDestroyPipelineLayout = nullptr; - // Back-ref so onRefCntReachedZero() can route the actual vkDestroy* calls - // through ContextVulkan::vkDeferDestroy() when an external command buffer - // is active (the host hasn't submitted yet). Weak ref. - ContextVulkan* m_vkOreContext = nullptr; -#endif -#if defined(ORE_BACKEND_D3D12) - Microsoft::WRL::ComPtr<ID3D12PipelineState> m_d3dPSO; - // Per-pipeline root signature composed from per-group descriptor-table - // shapes carried by each `m_layouts[g]->m_d3dGroupParams`. The root - // sig itself is per-pipeline (cross-group) but consumes the layouts' - // per-group params at build time. - Microsoft::WRL::ComPtr<ID3D12RootSignature> m_d3dRootSigOwned; - // Per-group root-parameter indices (set at root sig build time) + - // per-kind register ranges (mirrored from each layout's - // m_d3dGroupParams). Consumed at setBindGroup time to dispatch - // descriptor writes into the right root parameter. - D3D12GroupRootParams m_d3dGroupParams[kMaxBindGroups]{}; - D3D12_PRIMITIVE_TOPOLOGY m_d3dTopology = - D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST; - UINT m_d3dVertexStrides[8] = {}; // Per-slot vertex strides. - // Back-ref so onRefCntReachedZero() can route the ComPtr release through - // ContextD3D12::d3dDeferDestroy() when an external command list is active. - // Weak ref. - ContextD3D12* m_d3dOreContext = nullptr; -#endif - -public: - void onRefCntReachedZero() const; }; } // namespace rive::ore
diff --git a/renderer/include/rive/renderer/ore/ore_render_pass.hpp b/renderer/include/rive/renderer/ore/ore_render_pass.hpp index 4b66d2b..16723ed 100644 --- a/renderer/include/rive/renderer/ore/ore_render_pass.hpp +++ b/renderer/include/rive/renderer/ore/ore_render_pass.hpp
@@ -7,29 +7,6 @@ #include "rive/refcnt.hpp" #include "rive/renderer/ore/ore_types.hpp" -#if defined(ORE_BACKEND_METAL) -#import <Metal/Metal.h> -#endif -// Note: load_gles_extensions.hpp (glad) is intentionally NOT included here. -// GL object handles are GLuint = unsigned int; no glad needed in the header. -#if defined(ORE_BACKEND_D3D11) -#include <d3d11.h> -#endif -#if defined(ORE_BACKEND_D3D12) -#include <d3d12.h> -#include <wrl/client.h> -#endif -#if defined(ORE_BACKEND_WGPU) -#include <webgpu/webgpu_cpp.h> -#endif -#if defined(ORE_BACKEND_VK) -#include <vulkan/vulkan.h> -namespace rive::gpu -{ -class RenderTargetVulkan; -} -#endif - namespace rive::ore { @@ -39,101 +16,76 @@ class Pipeline; class BindGroup; class Context; -#if defined(ORE_BACKEND_VK) -class ContextVulkan; -#endif -#if defined(ORE_BACKEND_D3D12) -class ContextD3D12; -#endif -#if defined(ORE_BACKEND_WGPU) -class ContextWGPU; -#endif class RenderPass { public: - void setPipeline(Pipeline* pipeline); + virtual void setPipeline(Pipeline* pipeline) = 0; - void setVertexBuffer(uint32_t slot, Buffer* buffer, uint32_t offset = 0); - void setIndexBuffer(Buffer* buffer, - IndexFormat format, - uint32_t offset = 0); + virtual void setVertexBuffer(uint32_t slot, + Buffer* buffer, + uint32_t offset = 0) = 0; + virtual void setIndexBuffer(Buffer* buffer, + IndexFormat format, + uint32_t offset = 0) = 0; // Bind a pre-created BindGroup, optionally overriding dynamic UBO offsets. - // Dynamic-ness is declared on the pipeline (`PipelineDesc::dynamicUBOs`) - // and cached per-slot on the BindGroup at creation. - // dynamicOffsets: one uint32 per dynamic UBO in this group, in the order - // they appear in `BindGroupDesc::ubos` (matches WebGPU semantics when - // the caller lists UBOs in ascending-slot order, the typical pattern). - void setBindGroup(uint32_t groupIndex, - BindGroup* bg, - const uint32_t* dynamicOffsets = nullptr, - uint32_t dynamicOffsetCount = 0); + virtual void setBindGroup(uint32_t groupIndex, + BindGroup* bg, + const uint32_t* dynamicOffsets = nullptr, + uint32_t dynamicOffsetCount = 0) = 0; - void setViewport(float x, - float y, - float width, - float height, - float minDepth = 0.0f, - float maxDepth = 1.0f); - void setScissorRect(uint32_t x, - uint32_t y, - uint32_t width, - uint32_t height); + virtual void setViewport(float x, + float y, + float width, + float height, + float minDepth = 0.0f, + float maxDepth = 1.0f) = 0; + virtual void setScissorRect(uint32_t x, + uint32_t y, + uint32_t width, + uint32_t height) = 0; - void setStencilReference(uint32_t ref); - void setBlendColor(float r, float g, float b, float a); + virtual void setStencilReference(uint32_t ref) = 0; + virtual void setBlendColor(float r, float g, float b, float a) = 0; - void draw(uint32_t vertexCount, - uint32_t instanceCount = 1, - uint32_t firstVertex = 0, - uint32_t firstInstance = 0); + virtual void draw(uint32_t vertexCount, + uint32_t instanceCount = 1, + uint32_t firstVertex = 0, + uint32_t firstInstance = 0) = 0; - void drawIndexed(uint32_t indexCount, - uint32_t instanceCount = 1, - uint32_t firstIndex = 0, - int32_t baseVertex = 0, - uint32_t firstInstance = 0); + virtual void drawIndexed(uint32_t indexCount, + uint32_t instanceCount = 1, + uint32_t firstIndex = 0, + int32_t baseVertex = 0, + uint32_t firstInstance = 0) = 0; - void finish(); + virtual void finish() = 0; bool isFinished() const { return m_finished; } - ~RenderPass(); + virtual ~RenderPass() = default; - RenderPass(RenderPass&& other) noexcept; - RenderPass& operator=(RenderPass&&) noexcept; RenderPass(const RenderPass&) = delete; RenderPass& operator=(const RenderPass&) = delete; -private: + // Populate attachment metadata from the descriptor. Called by every + // backend's beginRenderPass() immediately after constructing the + // RenderPass; defined inline because it only reads cross-backend + // texture/view accessors that are uniform across backends. + inline void populateAttachmentMetadata(const RenderPassDesc& desc); + virtual void validate() const {}; + +protected: friend class Context; -#if defined(ORE_BACKEND_METAL) - friend class ContextMetal; -#endif -#if defined(ORE_BACKEND_GL) - friend class ContextGL; -#endif -#if defined(ORE_BACKEND_D3D11) - friend class ContextD3D11; -#endif -#if defined(ORE_BACKEND_D3D12) - friend class ContextD3D12; -#endif -#if defined(ORE_BACKEND_WGPU) - friend class ContextWGPU; -#endif -#if defined(ORE_BACKEND_VK) - friend class ContextVulkan; -#endif RenderPass() = default; + RenderPass(Context* context) : m_context(context) {} bool m_finished = false; // Attachment metadata — populated by beginRenderPass() from the // RenderPassDesc via populateAttachmentMetadata(). Used by setPipeline() - // for format/sampleCount validation (matches WebGPU spec: validation at - // setPipeline time). + // for format/sampleCount validation. TextureFormat m_colorFormats[4] = {}; uint32_t m_colorCount = 0; TextureFormat m_depthFormat = {}; @@ -141,267 +93,16 @@ uint32_t m_sampleCount = 1; // Cross-backend back-pointer used by the pipeline-compat validator to - // route errors through Context::setLastError(). Populated by every - // backend's beginRenderPass() alongside the per-backend context fields - // (m_vkContext, m_wgpuContext, ...). Weak ref. + // route errors through Context::setLastError(). Weak ref. Context* m_context = nullptr; - // Lifecycle: strong refs to bound BindGroups prevent Lua GC from freeing + // Lifecycle: strong refs to bound BindGroups prevent GC from freeing // them between setBindGroup() and finish(). Released in finish(). rcp<BindGroup> m_boundGroups[kMaxBindGroups]; - void validate() const; - - // Populate attachment metadata from the descriptor. Called by every - // backend's beginRenderPass() immediately after constructing the - // RenderPass; defined inline because it only reads cross-backend - // texture/view accessors that are uniform across backends. - inline void populateAttachmentMetadata(const RenderPassDesc& desc); - // WebGPU-spec pipeline/attachment compatibility check, invoked from - // every backend's setPipeline(). Compares the pipeline's declared - // color/depth formats and sampleCount against the attachments this - // pass was begun with. Returns true on match; on mismatch populates - // Context::lastError() and returns false. + // every backend's setPipeline(). inline bool checkPipelineCompat(const Pipeline* pipeline) const; - - // Move cross-backend fields (m_context, attachment metadata, - // m_boundGroups) from `other` into `*this` and clear them on `other`. - // Called from every backend's move ctor / move-assign so that new - // cross-backend fields only need to be wired once. - inline void moveCrossBackendFieldsFrom(RenderPass& other) - { - m_finished = other.m_finished; - for (uint32_t i = 0; i < 4; ++i) - m_colorFormats[i] = other.m_colorFormats[i]; - m_colorCount = other.m_colorCount; - m_depthFormat = other.m_depthFormat; - m_hasDepth = other.m_hasDepth; - m_sampleCount = other.m_sampleCount; - m_context = other.m_context; - for (uint32_t i = 0; i < kMaxBindGroups; ++i) - m_boundGroups[i] = std::move(other.m_boundGroups[i]); - other.m_finished = true; - other.m_context = nullptr; - } - - // Shared across all non-Metal backends that track the current - // pipeline. Strong ref (rcp) — same lifetime guarantee as - // `m_boundGroups[]`. The Lua bridge can GC its `Pipeline` userdata - // between `setPipeline` and `finish`, so a raw pointer would - // dangle by the next `draw()`. The rcp keeps the Pipeline alive - // until `finish()` clears the field. -#if defined(ORE_BACKEND_GL) || defined(ORE_BACKEND_D3D11) || \ - defined(ORE_BACKEND_WGPU) || defined(ORE_BACKEND_VK) - rcp<Pipeline> m_currentPipeline; -#endif - - // GL keeps an explicit stencil-reference cache because - // `glStencilFuncSeparate` bundles compare + ref + readMask into a - // single call — re-applying compare from the new pipeline at - // `setPipeline` time would otherwise drop any reference value the - // caller set earlier on the pass. WebGPU semantics are pass-state: - // `setStencilReference` persists across pipeline changes. - // Other backends either keep stencil ref on the encoder/cmd-buf - // (Metal, Vulkan dynamic state, D3D12 OMSetStencilRef) or rebind it - // via the API directly without losing the value. -#if defined(ORE_BACKEND_GL) - uint32_t m_glStencilRef = 0; -#endif - -#if defined(ORE_BACKEND_METAL) - // Metal implementation helpers — shared by metal-only and metal+gl builds. - // Defined inline in ore_render_pass_metal.mm. - inline void mtlSetPipeline(Pipeline* pipeline); - inline void mtlSetVertexBuffer(uint32_t slot, - Buffer* buffer, - uint32_t offset); - inline void mtlSetIndexBuffer(Buffer* buffer, - IndexFormat format, - uint32_t offset); - inline void mtlSetBindGroup(BindGroup* bg, - uint32_t groupIndex, - const uint32_t* dynamicOffsets, - uint32_t dynamicOffsetCount); - inline void mtlSetViewport(float x, - float y, - float width, - float height, - float minDepth, - float maxDepth); - inline void mtlSetScissorRect(uint32_t x, - uint32_t y, - uint32_t width, - uint32_t height); - inline void mtlSetStencilRef(uint32_t ref); - inline void mtlSetBlendColor(float r, float g, float b, float a); - inline void mtlDraw(uint32_t vertexCount, - uint32_t instanceCount, - uint32_t firstVertex, - uint32_t firstInstance); - inline void mtlDrawIndexed(uint32_t indexCount, - uint32_t instanceCount, - uint32_t firstIndex, - int32_t baseVertex, - uint32_t firstInstance); - inline void mtlFinish(); - - id<MTLRenderCommandEncoder> m_mtlEncoder = nil; - id<MTLCommandBuffer> m_mtlCommandBuffer = nil; - id<MTLBuffer> m_mtlIndexBuffer = nil; - MTLIndexType m_mtlIndexType = MTLIndexTypeUInt16; - uint32_t m_mtlIndexBufferOffset = 0; - MTLPrimitiveType m_mtlPrimitiveType = MTLPrimitiveTypeTriangle; -#endif -#if defined(ORE_BACKEND_GL) - unsigned int m_glFBO = 0; - unsigned int m_glVAO = 0; - unsigned int m_prevVAO = 0; // Saved host VAO to restore in finish(). - unsigned int m_prevFBO = 0; // Saved host FBO to restore in finish(). - bool m_ownsFBO = false; - bool m_ownsVAO = false; - // (Cross-backend m_context lives outside this guard — see line ~117.) - uint32_t m_viewportWidth = 0; - uint32_t m_viewportHeight = 0; - uint32_t m_maxSamplerSlot = 0; // Track highest sampler slot for cleanup. - uint32_t m_maxAttribSlot = 0; // Track highest vertex attrib for cleanup. - bool m_usedSamplers = false; - bool m_usedAttribs = false; - IndexFormat m_glIndexFormat = IndexFormat::uint16; - - // MSAA resolve targets (populated by beginRenderPass when - // ColorAttachment::resolveTarget is set). - struct GLResolveInfo - { - uint32_t colorIndex = 0; - unsigned int resolveTex = 0; - unsigned int resolveTarget = 0; // GL target (e.g. GL_TEXTURE_2D). - uint32_t width = 0; - uint32_t height = 0; - }; - GLResolveInfo m_glResolves[4] = {}; - uint32_t m_glResolveCount = 0; -#endif -#if defined(ORE_BACKEND_D3D11) - ID3D11DeviceContext* m_d3d11Context = nullptr; - D3D11_PRIMITIVE_TOPOLOGY m_d3d11Topology = - D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST; - DXGI_FORMAT m_d3d11IndexFormat = DXGI_FORMAT_R16_UINT; - uint32_t m_d3d11IndexOffset = 0; - uint32_t m_d3d11StencilRef = 0; - float m_d3d11BlendFactor[4] = {}; - // MSAA resolve: pairs of (msaaTexture, resolveTexture) + format + - // per-view subresource indices. D3D11 subresource index is - // mipLevel + (arraySlice * mipCount), so recording both endpoints - // at pass-begin time (where the view desc is accessible) means - // finish() just passes them through to ResolveSubresource. - struct D3D11ResolveEntry - { - ID3D11Resource* msaa = nullptr; - ID3D11Resource* resolve = nullptr; - DXGI_FORMAT format = DXGI_FORMAT_UNKNOWN; - uint32_t msaaSubresource = 0; - uint32_t resolveSubresource = 0; - }; - D3D11ResolveEntry m_d3d11Resolves[4]; - uint32_t m_d3d11ResolveCount = 0; -#endif -#if defined(ORE_BACKEND_WGPU) - ContextWGPU* m_wgpuContext = nullptr; - wgpu::RenderPassEncoder m_wgpuPassEncoder; - wgpu::Buffer m_wgpuIndexBuffer; - wgpu::IndexFormat m_wgpuIndexFormat = wgpu::IndexFormat::Uint16; - uint64_t m_wgpuIndexOffset = 0; -#endif -#if defined(ORE_BACKEND_VK) - ContextVulkan* m_vkContext = nullptr; - VkCommandBuffer m_vkCmdBuf = VK_NULL_HANDLE; // Weak ref (owned by Context). - VkFramebuffer m_vkFramebuffer = - VK_NULL_HANDLE; // Created per-pass, destroyed in finish(). - VkBuffer m_vkIndexBuffer = VK_NULL_HANDLE; - VkIndexType m_vkIndexType = VK_INDEX_TYPE_UINT16; - VkDeviceSize m_vkIndexOffset = 0; - // Color attachment images for the post-render layout transition - // (COLOR_ATTACHMENT_OPTIMAL → SHADER_READ_ONLY_OPTIMAL). - VkImage m_vkColorImages[4] = {}; - uint32_t m_vkColorBaseLayer[4] = {}; - uint32_t m_vkColorLayerCount[4] = {}; - uint32_t m_vkColorCount = 0; - // Weak back-refs to Rive's render targets so finish() can update their - // lastAccess tracking after the layout transition. - gpu::RenderTargetVulkan* m_vkColorRenderTargets[4] = {}; - // Depth attachment image for the post-render barrier - // (DEPTH_STENCIL_ATTACHMENT_OPTIMAL → SHADER_READ_ONLY_OPTIMAL). - VkImage m_vkDepthImage = VK_NULL_HANDLE; - uint32_t m_vkDepthBaseLayer = 0; - uint32_t m_vkDepthLayerCount = 0; -#endif -#if defined(ORE_BACKEND_D3D12) - // D3D12 setBindGroup body — shared between the D3D12-only translation - // unit (ore_render_pass_d3d12.cpp) and the combined D3D11+D3D12 one - // (ore_render_pass_d3d11_d3d12.cpp). Defined inline in - // ore_d3d12_bind_group_apply.hpp, which both .cpp files include. - inline void d3d12ApplyBindGroup(uint32_t groupIndex, - BindGroup* bg, - const uint32_t* dynamicOffsets, - uint32_t dynamicOffsetCount); - - ID3D12GraphicsCommandList* m_d3dCmdList = - nullptr; // Weak ref (owned by Context). - ID3D12Device* m_d3dDevice = nullptr; // Weak ref. - ContextD3D12* m_d3dContext = nullptr; // Weak ref. - // Strong ref — same Lua-GC reasoning as the cross-backend - // `m_currentPipeline` above. The D3D12-only field exists because - // D3D12's setPipeline path is split between this TU and the - // d3d11+d3d12 combined TU; both share this storage. - rcp<Pipeline> m_d3dCurrentPipeline; - // Root signature currently bound on the command list. Compared against - // each new pipeline's `m_d3dRootSigOwned` in `setPipeline` so we only - // call `SetGraphicsRootSignature` when the sig actually changes (each - // Ore D3D12 pipeline owns its own per-pipeline root sig — RFC v5 - // §3.2.2). Weak ref; freed by the owning Pipeline. - ID3D12RootSignature* m_d3dCurrentRootSig = nullptr; - // Pending descriptor state (accumulated per setPipeline/setBindGroup). - D3D12_GPU_VIRTUAL_ADDRESS m_d3dPendingUBOs[8] = {}; - D3D12_CPU_DESCRIPTOR_HANDLE m_d3dPendingSrvHandles[8] = {}; - D3D12_CPU_DESCRIPTOR_HANDLE m_d3dPendingSamplerHandles[8] = {}; - DXGI_FORMAT m_d3dIndexFormat = DXGI_FORMAT_R16_UINT; - uint32_t m_d3dIndexOffset = 0; - uint32_t m_d3dStencilRef = 0; - float m_d3dBlendFactor[4] = {}; - // Color attachment resources for barrier in finish() (RT → final). - // Parallel arrays: m_d3dColorTextures provides the Ore Texture back-ref so - // finish() can keep Texture::m_d3dCurrentState in sync with the actual - // resource state after the end-of-pass transition. - ID3D12Resource* m_d3dColorResources[4] = {}; - Texture* m_d3dColorTextures[4] = {}; - D3D12_RESOURCE_STATES m_d3dColorFinalStates[4] = {}; - uint32_t m_d3dColorCount = 0; - ID3D12Resource* m_d3dDepthResource = nullptr; - Texture* m_d3dDepthTexture = nullptr; - D3D12_RESOURCE_STATES m_d3dDepthFinalState = D3D12_RESOURCE_STATE_COMMON; - // MSAA resolve pairs (populated at beginRenderPass, executed in finish). - // D3D12 subresource index is mipLevel + arraySlice * mipCount for the - // common single-plane case. - struct D3D12ResolveEntry - { - ID3D12Resource* msaa = nullptr; - ID3D12Resource* resolve = nullptr; - // Back-ref to the resolve target's Ore Texture so finish() can update - // Texture::m_d3dCurrentState after the resolve barrier chain. - Texture* resolveTex = nullptr; - DXGI_FORMAT format = DXGI_FORMAT_UNKNOWN; - uint32_t msaaSubresource = 0; - uint32_t resolveSubresource = 0; - // Resolve target's prior state, to restore after resolve. - D3D12_RESOURCE_STATES resolvePriorState = D3D12_RESOURCE_STATE_COMMON; - // Resolve target's final state (what finish() should leave it in). - D3D12_RESOURCE_STATES resolveFinalState = - D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE; - }; - D3D12ResolveEntry m_d3dResolves[4] = {}; - uint32_t m_d3dResolveCount = 0; -#endif }; } // namespace rive::ore
diff --git a/renderer/include/rive/renderer/ore/ore_sampler.hpp b/renderer/include/rive/renderer/ore/ore_sampler.hpp index 30f2384..ee520a8 100644 --- a/renderer/include/rive/renderer/ore/ore_sampler.hpp +++ b/renderer/include/rive/renderer/ore/ore_sampler.hpp
@@ -5,94 +5,28 @@ #pragma once #include "rive/refcnt.hpp" +#include "utils/lite_rtti.hpp" #include "rive/renderer/ore/ore_types.hpp" -#if defined(ORE_BACKEND_METAL) -#import <Metal/Metal.h> -#endif -// Note: load_gles_extensions.hpp (glad) is intentionally NOT included here. -// GL object handles are GLuint = unsigned int; no glad needed in the header. -#if defined(ORE_BACKEND_D3D11) -#include <d3d11.h> -#include <wrl/client.h> -#endif -#if defined(ORE_BACKEND_D3D12) -#include <d3d12.h> -#include <wrl/client.h> -#endif -#if defined(ORE_BACKEND_WGPU) -#include <webgpu/webgpu_cpp.h> -#endif -#if defined(ORE_BACKEND_VK) -#include <vulkan/vulkan.h> -#endif - namespace rive::ore { class Context; -#if defined(ORE_BACKEND_VK) -class ContextVulkan; -#endif -#if defined(ORE_BACKEND_D3D12) -class ContextD3D12; -#endif -class Sampler : public RefCnt<Sampler> +class Sampler : public RefCnt<Sampler>, public ENABLE_LITE_RTTI(Sampler) { -private: +public: + virtual ~Sampler() = default; + + // Default: immediately free. Backends that need deferred GPU-resource + // destruction (D3D12, Vulkan) override this. + virtual void onRefCntReachedZero() const { delete this; } + +protected: friend class Context; -#if defined(ORE_BACKEND_METAL) - friend class ContextMetal; -#endif -#if defined(ORE_BACKEND_GL) - friend class ContextGL; -#endif -#if defined(ORE_BACKEND_D3D11) - friend class ContextD3D11; -#endif -#if defined(ORE_BACKEND_D3D12) - friend class ContextD3D12; -#endif -#if defined(ORE_BACKEND_WGPU) - friend class ContextWGPU; -#endif -#if defined(ORE_BACKEND_VK) - friend class ContextVulkan; -#endif friend class RenderPass; Sampler() = default; - -#if defined(ORE_BACKEND_METAL) - id<MTLSamplerState> m_mtlSampler = nil; -#endif -#if defined(ORE_BACKEND_GL) - unsigned int m_glSampler = 0; -#endif -#if defined(ORE_BACKEND_D3D11) - Microsoft::WRL::ComPtr<ID3D11SamplerState> m_d3dSampler; -#endif -#if defined(ORE_BACKEND_WGPU) - wgpu::Sampler m_wgpuSampler; -#endif -#if defined(ORE_BACKEND_VK) - VkSampler m_vkSampler = VK_NULL_HANDLE; - VkDevice m_vkDevice = VK_NULL_HANDLE; // Weak ref. - PFN_vkDestroySampler m_vkDestroySampler = nullptr; - // Back-ref so onRefCntReachedZero() can route destruction through - // ContextVulkan::vkDeferDestroy() in external-CB mode. Weak ref. - ContextVulkan* m_vkOreContext = nullptr; -#endif -#if defined(ORE_BACKEND_D3D12) - D3D12_CPU_DESCRIPTOR_HANDLE m_d3dSamplerHandle = {}; // {0} = invalid. - // Back-ref so onRefCntReachedZero() can route destruction through - // ContextD3D12::d3dDeferDestroy() in external-CL mode. Weak ref. - ContextD3D12* m_d3dOreContext = nullptr; -#endif - -public: - void onRefCntReachedZero() const; }; } // namespace rive::ore
diff --git a/renderer/include/rive/renderer/ore/ore_shader_module.hpp b/renderer/include/rive/renderer/ore/ore_shader_module.hpp index 6f499c5..194c45a 100644 --- a/renderer/include/rive/renderer/ore/ore_shader_module.hpp +++ b/renderer/include/rive/renderer/ore/ore_shader_module.hpp
@@ -5,6 +5,7 @@ #pragma once #include "rive/refcnt.hpp" +#include "utils/lite_rtti.hpp" #include "rive/renderer/ore/ore_binding_map.hpp" #include "rive/renderer/ore/ore_types.hpp" @@ -13,38 +14,13 @@ #include <string> #include <vector> -#if defined(ORE_BACKEND_METAL) -#import <Metal/Metal.h> -#endif -// Note: load_gles_extensions.hpp (glad) is intentionally NOT included here. -// GL object handles are GLuint = unsigned int; no glad needed in the header. -#if defined(ORE_BACKEND_D3D11) -#include <d3d11.h> -#include <d3dcompiler.h> -#include <wrl/client.h> -#include <algorithm> -#include <mutex> -#include <vector> -#include <string> -#endif -#if defined(ORE_BACKEND_D3D12) -#include <d3d12.h> -#include <wrl/client.h> -#include <vector> -#endif -#if defined(ORE_BACKEND_WGPU) -#include <webgpu/webgpu_cpp.h> -#endif -#if defined(ORE_BACKEND_VK) -#include <vulkan/vulkan.h> -#endif - namespace rive::ore { class Context; -class ShaderModule : public RefCnt<ShaderModule> +class ShaderModule : public RefCnt<ShaderModule>, + public ENABLE_LITE_RTTI(ShaderModule) { public: /// Texture-sampler pair from RSTB shader reflection. @@ -69,7 +45,6 @@ BindingMap m_bindingMap; #ifdef TRACK_RIVE_SHADER_ID - // Set from desc.shaderAssetId in applyBindingMapFromDesc. uint32_t m_shaderAssetId = 0; uint32_t shaderAssetId() const { return m_shaderAssetId; } #endif @@ -147,161 +122,17 @@ } } -private: + virtual ~ShaderModule() = default; + + // Default: immediately free. No backend currently needs deferred + // destruction for shader modules. + virtual void onRefCntReachedZero() const { delete this; } + +protected: friend class Context; -#if defined(ORE_BACKEND_METAL) - friend class ContextMetal; -#endif -#if defined(ORE_BACKEND_GL) - friend class ContextGL; -#endif -#if defined(ORE_BACKEND_D3D11) - friend class ContextD3D11; -#endif -#if defined(ORE_BACKEND_D3D12) - friend class ContextD3D12; -#endif -#if defined(ORE_BACKEND_WGPU) - friend class ContextWGPU; -#endif -#if defined(ORE_BACKEND_VK) - friend class ContextVulkan; -#endif friend class Pipeline; ShaderModule() = default; - -#if defined(ORE_BACKEND_METAL) - id<MTLLibrary> m_mtlLibrary = nil; -#endif -#if defined(ORE_BACKEND_GL) - unsigned int m_glShader = 0; - unsigned int m_glShaderType = 0; // GL_VERTEX_SHADER or GL_FRAGMENT_SHADER. -#endif -#if defined(ORE_BACKEND_D3D11) - std::vector<uint8_t> m_bytecode; - ShaderStage m_stage = ShaderStage::autoDetect; - Microsoft::WRL::ComPtr<ID3D11VertexShader> m_d3dVertexShader; - Microsoft::WRL::ComPtr<ID3D11PixelShader> m_d3dPixelShader; - - // HLSL source compiled at first pipeline use via ensureD3DShaders. - std::string m_hlslSource; - std::string m_hlslEntryPoint; - - // Guards ensureD3DShaders against concurrent first-call from two - // pipelines sharing this ShaderModule. - std::once_flag m_d3dInitFlag; - - // outError, if non-null, receives the D3DCompile error log so the - // caller can route it to Context::m_lastError. - void ensureD3DShaders(ID3D11Device* device, std::string* outError = nullptr) - { - std::call_once(m_d3dInitFlag, - [&]() { ensureD3DShadersImpl(device, outError); }); - } - - void ensureD3DShadersImpl(ID3D11Device* device, std::string* outError) - { - if (m_hlslSource.empty()) - return; - - // Normalize line endings (SPIRV-Cross outputs \r\n on Windows). - m_hlslSource.erase( - std::remove(m_hlslSource.begin(), m_hlslSource.end(), '\r'), - m_hlslSource.end()); - - const char* target = - (m_stage == ShaderStage::fragment) ? "ps_5_0" : "vs_5_0"; - const char* entry = - m_hlslEntryPoint.empty() ? "main" : m_hlslEntryPoint.c_str(); - Microsoft::WRL::ComPtr<ID3DBlob> compiledBlob; - Microsoft::WRL::ComPtr<ID3DBlob> errors; - HRESULT hr = D3DCompile(m_hlslSource.c_str(), - m_hlslSource.size(), - nullptr, - nullptr, - nullptr, - entry, - target, - D3DCOMPILE_ENABLE_STRICTNESS | - D3DCOMPILE_OPTIMIZATION_LEVEL3, - 0, - compiledBlob.GetAddressOf(), - errors.GetAddressOf()); - if (FAILED(hr)) - { - if (outError) - { - const char* errMsg = - errors - ? static_cast<const char*>(errors->GetBufferPointer()) - : "(no error log)"; - char buf[1024]; - snprintf(buf, - sizeof(buf), - "D3DCompile failed (entry=%s target=%s " - "hr=0x%08x): %s", - entry, - target, - static_cast<unsigned>(hr), - errMsg); - *outError = buf; - } - return; - } - - const void* code = compiledBlob->GetBufferPointer(); - SIZE_T codeSize = compiledBlob->GetBufferSize(); - // Store compiled bytecode for CreateInputLayout. - m_bytecode.assign(static_cast<const uint8_t*>(code), - static_cast<const uint8_t*>(code) + codeSize); - - if (m_stage == ShaderStage::fragment) - { - device->CreatePixelShader(code, - codeSize, - nullptr, - m_d3dPixelShader.GetAddressOf()); - } - else if (m_stage == ShaderStage::vertex) - { - device->CreateVertexShader(code, - codeSize, - nullptr, - m_d3dVertexShader.GetAddressOf()); - } - else - { - HRESULT hr = - device->CreateVertexShader(code, - codeSize, - nullptr, - m_d3dVertexShader.GetAddressOf()); - if (FAILED(hr)) - { - device->CreatePixelShader(code, - codeSize, - nullptr, - m_d3dPixelShader.GetAddressOf()); - } - } - } -#endif -#if defined(ORE_BACKEND_WGPU) - wgpu::ShaderModule m_wgpuShaderModule; -#endif -#if defined(ORE_BACKEND_VK) - VkShaderModule m_vkShaderModule = VK_NULL_HANDLE; - VkDevice m_vkDevice = VK_NULL_HANDLE; // Weak ref. - PFN_vkDestroyShaderModule m_vkDestroyShaderModule = nullptr; -#endif -#if defined(ORE_BACKEND_D3D12) - std::vector<uint8_t> m_d3dBytecode; - bool m_d3dIsVertex = false; // True = VS, False = PS. -#endif - -public: - void onRefCntReachedZero() const; }; } // namespace rive::ore
diff --git a/renderer/include/rive/renderer/ore/ore_texture.hpp b/renderer/include/rive/renderer/ore/ore_texture.hpp index e422993..73e6008 100644 --- a/renderer/include/rive/renderer/ore/ore_texture.hpp +++ b/renderer/include/rive/renderer/ore/ore_texture.hpp
@@ -5,46 +5,15 @@ #pragma once #include "rive/refcnt.hpp" +#include "utils/lite_rtti.hpp" #include "rive/renderer/ore/ore_types.hpp" -#if defined(ORE_BACKEND_METAL) -#import <Metal/Metal.h> -#endif -// Note: load_gles_extensions.hpp (glad) is intentionally NOT included here. -// GL object handles are GLuint = unsigned int; no glad needed in the header. -#if defined(ORE_BACKEND_D3D11) -#include <d3d11.h> -#include <wrl/client.h> -#endif -#if defined(ORE_BACKEND_D3D12) -#include <d3d12.h> -#include <wrl/client.h> -#endif -#if defined(ORE_BACKEND_WGPU) -#include <webgpu/webgpu_cpp.h> -#endif -#if defined(ORE_BACKEND_VK) -#include <vulkan/vulkan.h> -VK_DEFINE_HANDLE(VmaAllocator); -VK_DEFINE_HANDLE(VmaAllocation); -namespace rive::gpu -{ -class RenderTargetVulkan; -} -#endif - namespace rive::ore { class Context; -#if defined(ORE_BACKEND_VK) -class ContextVulkan; -#endif -#if defined(ORE_BACKEND_D3D12) -class ContextD3D12; -#endif -class Texture : public RefCnt<Texture> +class Texture : public RefCnt<Texture>, public ENABLE_LITE_RTTI(Texture) { public: uint32_t width() const { return m_width; } @@ -56,32 +25,16 @@ uint32_t sampleCount() const { return m_sampleCount; } bool isRenderTarget() const { return m_renderTarget; } - void upload(const TextureDataDesc& data); + virtual void upload(const TextureDataDesc& data) = 0; -#if defined(ORE_BACKEND_METAL) - id<MTLTexture> mtlTexture() const { return m_mtlTexture; } -#endif + virtual ~Texture() = default; -private: + // Default: immediately free. Backends that need deferred GPU-resource + // destruction (D3D12, Vulkan) override this. + virtual void onRefCntReachedZero() const { delete this; } + +protected: friend class Context; -#if defined(ORE_BACKEND_METAL) - friend class ContextMetal; -#endif -#if defined(ORE_BACKEND_GL) - friend class ContextGL; -#endif -#if defined(ORE_BACKEND_D3D11) - friend class ContextD3D11; -#endif -#if defined(ORE_BACKEND_D3D12) - friend class ContextD3D12; -#endif -#if defined(ORE_BACKEND_WGPU) - friend class ContextWGPU; -#endif -#if defined(ORE_BACKEND_VK) - friend class ContextVulkan; -#endif friend class TextureView; friend class RenderPass; @@ -104,54 +57,10 @@ bool m_renderTarget; uint32_t m_numMipmaps; uint32_t m_sampleCount; - -#if defined(ORE_BACKEND_METAL) - id<MTLTexture> m_mtlTexture = nil; -#endif -#if defined(ORE_BACKEND_GL) - unsigned int m_glTexture = 0; - unsigned int m_glRenderbuffer = 0; // Non-zero for MSAA render targets - // (renderbuffer-backed, not texture). - unsigned int m_glTarget = 0; - bool m_glOwnsTexture = true; // False for borrowed textures (e.g. - // wrapCanvasTexture). -#endif -#if defined(ORE_BACKEND_D3D11) - Microsoft::WRL::ComPtr<ID3D11Resource> m_d3d11Texture; - ID3D11DeviceContext* m_d3d11Context = - nullptr; // Weak ref, set by Context::makeTexture. -#endif -#if defined(ORE_BACKEND_WGPU) - wgpu::Texture m_wgpuTexture; - wgpu::Queue - m_wgpuQueue; // Weak ref (addref'd copy), set by Context::makeTexture. -#endif -#if defined(ORE_BACKEND_VK) - VkImage m_vkImage = VK_NULL_HANDLE; - VmaAllocation m_vmaAllocation = VK_NULL_HANDLE; - VkImageLayout m_vkLayout = VK_IMAGE_LAYOUT_UNDEFINED; - VkDevice m_vkDevice = VK_NULL_HANDLE; // Weak ref. - VmaAllocator m_vmaAllocator = VK_NULL_HANDLE; // Weak ref. - // Back-pointer to the owning ContextVulkan. upload() reads the current - // frame CB and VK dispatch table through it, and onRefCntReachedZero() - // routes vmaDestroyImage through ContextVulkan::vkDeferDestroy() in - // external-CB mode. - ContextVulkan* m_vkOreContext = nullptr; -#endif -#if defined(ORE_BACKEND_D3D12) - Microsoft::WRL::ComPtr<ID3D12Resource> m_d3dTexture; - D3D12_RESOURCE_STATES m_d3dCurrentState = D3D12_RESOURCE_STATE_COMMON; - bool m_d3dIsExternal = false; // true for wrapCanvasTexture. - ID3D12Device* m_d3dDevice = nullptr; // Weak ref. - // Set by ContextD3D12::makeTexture so upload() can schedule copy commands. - ContextD3D12* m_d3dOreContext = nullptr; // Weak ref. -#endif - -public: - void onRefCntReachedZero() const; }; -class TextureView : public RefCnt<TextureView> +class TextureView : public RefCnt<TextureView>, + public ENABLE_LITE_RTTI(TextureView) { public: Texture* texture() const { return m_texture.get(); } @@ -162,33 +71,14 @@ uint32_t baseLayer() const { return m_baseLayer; } uint32_t layerCount() const { return m_layerCount; } -#if defined(ORE_BACKEND_METAL) - id<MTLTexture> mtlTexture() const - { - return m_mtlTextureView ? m_mtlTextureView : m_texture->m_mtlTexture; - } -#endif + virtual ~TextureView() = default; -private: + // Default: immediately free. Backends that need deferred GPU-resource + // destruction (D3D12, Vulkan) override this. + virtual void onRefCntReachedZero() const { delete this; } + +protected: friend class Context; -#if defined(ORE_BACKEND_METAL) - friend class ContextMetal; -#endif -#if defined(ORE_BACKEND_GL) - friend class ContextGL; -#endif -#if defined(ORE_BACKEND_D3D11) - friend class ContextD3D11; -#endif -#if defined(ORE_BACKEND_D3D12) - friend class ContextD3D12; -#endif -#if defined(ORE_BACKEND_WGPU) - friend class ContextWGPU; -#endif -#if defined(ORE_BACKEND_VK) - friend class ContextVulkan; -#endif friend class RenderPass; TextureView(rcp<Texture> texture, const TextureViewDesc& desc) : @@ -208,43 +98,6 @@ uint32_t m_mipCount; uint32_t m_baseLayer; uint32_t m_layerCount; - -#if defined(ORE_BACKEND_METAL) - id<MTLTexture> m_mtlTextureView = nil; -#endif -#if defined(ORE_BACKEND_GL) - unsigned int m_glTextureView = 0; // GL 4.3 view, or 0 (use base texture). -#endif -#if defined(ORE_BACKEND_D3D11) - Microsoft::WRL::ComPtr<ID3D11ShaderResourceView> m_d3dSRV; - Microsoft::WRL::ComPtr<ID3D11RenderTargetView> m_d3dRTV; - Microsoft::WRL::ComPtr<ID3D11DepthStencilView> m_d3dDSV; -#endif -#if defined(ORE_BACKEND_WGPU) - wgpu::TextureView m_wgpuTextureView; -#endif -#if defined(ORE_BACKEND_VK) - VkImageView m_vkImageView = VK_NULL_HANDLE; - VkDevice m_vkDevice = VK_NULL_HANDLE; // Weak ref. - PFN_vkDestroyImageView m_vkDestroyImageView = nullptr; - // Set only for canvas-backed views (wrapCanvasTexture). Used by - // RenderPass::finish() to update Rive's layout tracking. - gpu::RenderTargetVulkan* m_vkRenderTarget = nullptr; // Weak ref. - // Back-ref so onRefCntReachedZero() can route the destroy through - // ContextVulkan::vkDeferDestroy() in external-CB mode. Weak ref. - ContextVulkan* m_vkOreContext = nullptr; -#endif -#if defined(ORE_BACKEND_D3D12) - D3D12_CPU_DESCRIPTOR_HANDLE m_d3dSrvHandle = {}; // {0} = invalid. - D3D12_CPU_DESCRIPTOR_HANDLE m_d3dRtvHandle = {}; - D3D12_CPU_DESCRIPTOR_HANDLE m_d3dDsvHandle = {}; - // Back-ref so onRefCntReachedZero() can route destruction through - // ContextD3D12::d3dDeferDestroy() in external-CL mode. Weak ref. - ContextD3D12* m_d3dOreContext = nullptr; -#endif - -public: - void onRefCntReachedZero() const; }; } // namespace rive::ore
diff --git a/renderer/include/rive/renderer/render_context_impl.hpp b/renderer/include/rive/renderer/render_context_impl.hpp index 6d16ea7..875ec1b 100644 --- a/renderer/include/rive/renderer/render_context_impl.hpp +++ b/renderer/include/rive/renderer/render_context_impl.hpp
@@ -7,6 +7,17 @@ #include "rive/renderer/render_context.hpp" #include "rive/gpu_texture_format.hpp" +#ifdef RIVE_CANVAS +#include <memory> +#endif + +#ifdef RIVE_CANVAS +namespace rive::ore +{ +class Context; +}; +#endif + namespace rive::gpu { #ifdef RIVE_CANVAS @@ -55,6 +66,9 @@ { return nullptr; } + + // If canvas is enabled then the backend Impl MUST implement this. + virtual std::unique_ptr<rive::ore::Context> makeOreContext() = 0; #endif // Resize GPU buffers. These methods cannot fail, and must allocate the
diff --git a/renderer/include/rive/renderer/vulkan/render_context_vulkan_impl.hpp b/renderer/include/rive/renderer/vulkan/render_context_vulkan_impl.hpp index c146652..3abbe7f 100644 --- a/renderer/include/rive/renderer/vulkan/render_context_vulkan_impl.hpp +++ b/renderer/include/rive/renderer/vulkan/render_context_vulkan_impl.hpp
@@ -89,6 +89,7 @@ #ifdef RIVE_CANVAS rcp<RenderCanvas> makeRenderCanvas(uint32_t width, uint32_t height) override; + std::unique_ptr<rive::ore::Context> makeOreContext() override; #endif void hotloadShaders(rive::Span<const uint32_t> spirvData);
diff --git a/renderer/include/rive/renderer/vulkan/vulkan_context.hpp b/renderer/include/rive/renderer/vulkan/vulkan_context.hpp index 581ea6d..4b18939 100644 --- a/renderer/include/rive/renderer/vulkan/vulkan_context.hpp +++ b/renderer/include/rive/renderer/vulkan/vulkan_context.hpp
@@ -67,6 +67,7 @@ F(GetDeviceProcAddr) \ F(GetPhysicalDeviceFormatProperties) \ F(GetPhysicalDeviceProperties) \ + F(GetPhysicalDeviceFeatures) \ F(SetDebugUtilsObjectNameEXT) #define RIVE_VULKAN_DEVICE_COMMANDS(F) \ @@ -80,6 +81,8 @@ F(CmdBindVertexBuffers) \ F(CmdBlitImage) \ F(CmdClearColorImage) \ + F(CmdSetStencilReference) \ + F(CmdSetBlendConstants) \ F(CmdCopyBufferToImage) \ F(CmdDraw) \ F(CmdDrawIndexed) \ @@ -93,6 +96,7 @@ F(CreateDescriptorPool) \ F(CreateDescriptorSetLayout) \ F(CreateFramebuffer) \ + F(CreateFence) \ F(CreateGraphicsPipelines) \ F(CreateImageView) \ F(CreatePipelineLayout) \ @@ -102,6 +106,7 @@ F(DestroyCommandPool) \ F(DestroyDescriptorPool) \ F(DestroyDescriptorSetLayout) \ + F(DestroyFence) \ F(DestroyFramebuffer) \ F(DestroyImageView) \ F(DestroyPipeline) \ @@ -111,10 +116,14 @@ F(DestroyShaderModule) \ F(EndCommandBuffer) \ F(FreeCommandBuffers) \ + F(FreeDescriptorSets) \ F(QueueSubmit) \ F(QueueWaitIdle) \ + F(ResetCommandBuffer) \ F(ResetDescriptorPool) \ - F(UpdateDescriptorSets) + F(ResetFences) \ + F(UpdateDescriptorSets) \ + F(WaitForFences) #define DECLARE_VULKAN_COMMAND(CMD) const PFN_vk##CMD CMD; RIVE_VULKAN_INSTANCE_COMMANDS(DECLARE_VULKAN_COMMAND)
diff --git a/renderer/include/rive/renderer/webgpu/render_context_webgpu_impl.hpp b/renderer/include/rive/renderer/webgpu/render_context_webgpu_impl.hpp index ef9cfb1..a294eea 100644 --- a/renderer/include/rive/renderer/webgpu/render_context_webgpu_impl.hpp +++ b/renderer/include/rive/renderer/webgpu/render_context_webgpu_impl.hpp
@@ -95,6 +95,8 @@ #ifdef RIVE_CANVAS rcp<RenderCanvas> makeRenderCanvas(uint32_t width, uint32_t height) override; + + std::unique_ptr<rive::ore::Context> makeOreContext() override; #endif private:
diff --git a/renderer/premake5_pls_renderer.lua b/renderer/premake5_pls_renderer.lua index 070c9a4..7807aa0 100644 --- a/renderer/premake5_pls_renderer.lua +++ b/renderer/premake5_pls_renderer.lua
@@ -34,15 +34,6 @@ defines({ 'RIVE_DESKTOP_GL' }) end --- Ore backend selection — defined globally so tests and consumers also see them. --- Only active when --with_rive_canvas is enabled. --- RIVE_ORE is defined whenever any ore backend is active, so C++ code can guard --- ore API calls without enumerating every backend. -filter({ 'system:macosx or ios', 'options:with_rive_canvas' }) -do - defines({ 'ORE_BACKEND_METAL', 'RIVE_ORE' }) -end - -- Enable @try/@catch in Metal ORE for graceful error handling at runtime. -- Not used in tools/fuzz builds where crashing on Metal exceptions is preferred. filter({ 'system:macosx or ios', 'options:with_objc_exceptions' }) @@ -50,68 +41,16 @@ defines({ 'RIVE_OBJC_EXCEPTIONS=1' }) end --- macOS also gets ORE_BACKEND_GL so ore GMs work with ANGLE (GL on desktop). -filter({ 'system:macosx', 'options:with_rive_canvas', 'options:not no_gl' }) -do - defines({ 'ORE_BACKEND_GL' }) -end - -filter({ 'system:windows', 'options:with_rive_canvas' }) -do - defines({ 'ORE_BACKEND_D3D11', 'ORE_BACKEND_D3D12', 'RIVE_ORE' }) -end - --- Windows + Dawn: ore routes through Dawn's WebGPU device. Supersedes D3D11 --- and D3D12 ore backends. -filter({ 'system:windows', 'options:with_rive_canvas', 'options:with-dawn' }) -do - defines({ 'ORE_BACKEND_WGPU' }) - removedefines({ 'ORE_BACKEND_D3D11' }) - removedefines({ 'ORE_BACKEND_D3D12' }) -end - filter('system:android') do defines({ 'RIVE_ANDROID' }) end -filter({ 'system:android', 'options:with_rive_canvas', 'options:not with_wagyu', 'options:not no_gl' }) -do - defines({ 'ORE_BACKEND_GL', 'RIVE_ORE' }) -end - --- Android + wagyu: Ore routes through the WebGPU/wagyu device instead of raw GL. --- Runtime dispatch inside ORE_BACKEND_WGPU selects GLSLRAW (GLES) or GLSL (Vulkan). -filter({ 'system:android', 'options:with_rive_canvas', 'options:with_wagyu' }) -do - defines({ 'ORE_BACKEND_WGPU', 'RIVE_ORE' }) -end - --- Android + native Vulkan (no wagyu): raw Vulkan ORE backend. --- Takes SPIR-V directly; traditional VkRenderPass for TBDR tile memory efficiency. --- When GL is also enabled (the default), both backends coexist in the same binary --- via VK+GL dispatch files (src/ore/vulkan/ore_*_vk_gl.cpp). -filter({ 'system:android', 'options:with_rive_canvas', 'options:not with_wagyu', 'options:with_vulkan' }) -do - defines({ 'ORE_BACKEND_VK' }) -end - --- Linux: native Vulkan ORE backend (requires --with_vulkan for headers and VMA). --- Also enables the ORE GL backend so the same binary can service `--backend gl` --- via the VK+GL dispatch TUs, parallel to the Android VK+GL configuration. -filter({ 'system:linux', 'options:with_rive_canvas', 'options:with_vulkan' }) -do - defines({ 'ORE_BACKEND_VK', 'ORE_BACKEND_GL', 'RIVE_ORE' }) -end - - newoption({ trigger = 'with_objc_exceptions', description = 'enable @try/@catch in Metal ORE (requires -fobjc-exceptions)', }) - - newoption({ trigger = 'with-dawn', description = 'compile in support for webgpu via dawn', @@ -127,18 +66,6 @@ defines({ 'RIVE_WEBGL' }) end --- Emscripten + wagyu: Ore routes through the WebGPU/wagyu device. --- Runtime dispatch inside ORE_BACKEND_WGPU selects GLSLRAW (GLES) or GLSL (Vulkan). -filter({ 'system:emscripten', 'options:with_rive_canvas', 'options:with_wagyu' }) -do - defines({ 'ORE_BACKEND_WGPU', 'RIVE_ORE' }) -end - -filter({ 'system:emscripten', 'options:with_rive_canvas', 'options:not with_wagyu', 'options:not no_gl' }) -do - defines({ 'ORE_BACKEND_GL', 'RIVE_ORE' }) -end - newoption({ trigger = 'with-webgpu', description = 'compile in native support for webgpu', @@ -286,6 +213,39 @@ microprofile = dependency.github(RIVE_MICROPROFILE_URL, RIVE_MICROPROFILE_VERSION) end +-- Ore defines outside of project because we want them to be defined for every proeject +filter({ 'options:with_rive_canvas' }) +do + defines({ 'RIVE_ORE' }) +end + +filter({ 'system:macosx or ios', 'options:not nop-obj-c', 'options:with_rive_canvas' }) +do + defines({ 'ORE_BACKEND_METAL' }) +end + +filter({ 'system:windows', 'options:with_rive_canvas' }) +do + defines({ 'ORE_BACKEND_D3D11', 'ORE_BACKEND_D3D12' }) +end + +-- No gl for iOS +filter({ 'system:not ios', 'options:with_rive_canvas', 'options:not no_gl' }) +do + defines({ 'ORE_BACKEND_GL' }) +end + +-- No vulkan for iOS +filter({ 'system:not ios', 'options:with_rive_canvas', 'options:with_vulkan' }) +do + defines({ 'ORE_BACKEND_VK' }) +end + +filter({ 'options:with_rive_canvas', 'options:with-dawn or with-webgpu' }) +do + defines({ 'ORE_BACKEND_WGPU' }) +end + project('rive_pls_renderer') do kind('StaticLib') @@ -380,113 +340,54 @@ buildoptions({ '-fobjc-arc' }) end - -- Shared cross-backend Ore sources. Compiled whenever canvas is on, - -- regardless of which GPU backend(s) are active. + -- Enable -fobjc-exceptions for .mm files when @try/@catch is active. + -- Uses a files: filter so the flag doesn't hit .cpp compilations + -- (clang warns on -fobjc-exceptions for non-ObjC++ sources). + filter({ + 'system:macosx or ios', + 'options:not nop-obj-c', + 'options:with_objc_exceptions', + 'files:**.mm', + }) + do + buildoptions({ '-fobjc-exceptions' }) + end + filter({ 'options:with_rive_canvas' }) do - files({ 'src/ore/*.cpp' }) + files({ 'src/ore/*.cpp', 'src/ore/*.hpp' }) end filter({ 'system:macosx or ios', 'options:not nop-obj-c', 'options:with_rive_canvas' }) do - files({ 'src/ore/metal/*.mm' }) + files({ 'src/ore/metal/*.mm', 'src/ore/metal/*.hpp' }) end - -- Enable -fobjc-exceptions for .mm files when @try/@catch is active. - -- Uses a files: filter so the flag doesn't hit .cpp compilations - -- (clang warns on -fobjc-exceptions for non-ObjC++ sources). - filter({ - 'system:macosx or ios', - 'options:not nop-obj-c', - 'options:with_objc_exceptions', - 'files:**.mm', - }) + filter({ 'system:windows', 'options:with_rive_canvas' }) do - buildoptions({ '-fobjc-exceptions' }) + files({ 'src/ore/d3d11/*.cpp', 'src/ore/d3d11/*.hpp' }) + files({ 'src/ore/d3d12/*.cpp', 'src/ore/d3d12/*.hpp' }) end - -- Enable -fobjc-exceptions for .mm files when @try/@catch is active. - -- Uses a files: filter so the flag doesn't hit .cpp compilations - -- (clang warns on -fobjc-exceptions for non-ObjC++ sources). - filter({ - 'system:macosx or ios', - 'options:not nop-obj-c', - 'options:with_objc_exceptions', - 'files:**.mm', - }) + -- No gl for iOS + filter({ 'system:not ios', 'options:with_rive_canvas', 'options:not no_gl' }) do - buildoptions({ '-fobjc-exceptions' }) + files({ 'src/ore/gl/*.cpp', 'src/ore/gl/*.hpp' }) end - - -- macOS also compiles the ore GL backend (via ObjC++ wrappers) so ore - -- works with ANGLE. Both METAL and GL backends coexist in the same binary. filter({ 'system:macosx', 'options:not nop-obj-c', 'options:with_rive_canvas', 'options:not no_gl' }) do files({ 'src/ore/gl/*.mm' }) end - - filter({ 'system:windows', 'options:with_rive_canvas' }) + filter({ 'options:with_rive_canvas', 'options:with_vulkan' }) do - files({ 'src/ore/d3d11/*.cpp' }) - files({ 'src/ore/d3d12/*.cpp' }) + files({ 'src/ore/vulkan/*.cpp', 'src/ore/vulkan/*.hpp'}) end - -- Windows + Dawn: ore uses the WebGPU device exposed by Dawn. Supersedes - -- D3D11 and D3D12 ore backends — Dawn provides the GPU abstraction. - filter({ 'system:windows', 'options:with_rive_canvas', 'options:with-dawn' }) + filter({ 'options:with_rive_canvas', 'options:with-dawn or with-webgpu' }) do - files({ 'src/ore/wgpu/*.cpp' }) - removefiles({ 'src/ore/d3d11/*.cpp' }) - removefiles({ 'src/ore/d3d12/*.cpp' }) - end - - - filter({ 'system:android', 'options:with_rive_canvas', 'options:not with_wagyu', 'options:not with_vulkan', 'options:not no_gl' }) - do - files({ 'src/ore/gl/*.cpp' }) - end - - filter({ 'system:android', 'options:with_rive_canvas', 'options:with_wagyu' }) - do - files({ 'src/ore/wgpu/*.cpp' }) - end - - filter({ 'system:emscripten', 'options:with_rive_canvas', 'options:with_wagyu' }) - do - files({ 'src/ore/wgpu/*.cpp' }) - end - - -- Android VK: always include Vulkan backend files. - filter({ 'system:android', 'options:with_rive_canvas', 'options:not with_wagyu', 'options:with_vulkan' }) - do - files({ 'src/ore/vulkan/*.cpp' }) - end - - -- Android VK+GL: both backends coexist. Standalone files compile to - -- static-helper-only objects (method bodies guarded out by the other - -- backend's define). VK+GL dispatch files (ore_*_vk_gl.cpp) in the - -- vulkan/ directory provide the actual method implementations. - filter({ 'system:android', 'options:with_rive_canvas', 'options:not with_wagyu', 'options:with_vulkan', 'options:not no_gl' }) - do - files({ 'src/ore/gl/*.cpp' }) - end - - if _OPTIONS['with_vulkan'] then - filter({ 'system:linux', 'options:with_rive_canvas' }) - do - externalincludedirs({ - vulkan_headers .. '/include', - vulkan_memory_allocator .. '/include', - }) - files({ 'src/ore/vulkan/*.cpp', 'src/ore/gl/*.cpp' }) - end - end - - filter({ 'system:emscripten', 'options:with_rive_canvas', 'options:not with_wagyu', 'options:not no_gl' }) - do - files({ 'src/ore/gl/*.cpp' }) + files({ 'src/ore/wgpu/*.cpp', 'src/ore/wgpu/*.hpp' }) end filter({ 'options:with-dawn' })
diff --git a/renderer/src/d3d11/render_context_d3d_impl.cpp b/renderer/src/d3d11/render_context_d3d_impl.cpp index 91f74d1..c58e4d9 100644 --- a/renderer/src/d3d11/render_context_d3d_impl.cpp +++ b/renderer/src/d3d11/render_context_d3d_impl.cpp
@@ -8,6 +8,7 @@ #ifdef RIVE_CANVAS #include "rive/renderer/render_canvas.hpp" +#include <rive/renderer/ore/ore_context_d3d11.hpp> #endif #include "rive/renderer/texture.hpp" #include "rive/profiler/profiler_macros.h" @@ -1052,6 +1053,12 @@ return make_rcp<RenderCanvas>(std::move(renderImage), std::move(renderTarget)); } + +std::unique_ptr<rive::ore::Context> RenderContextD3DImpl::makeOreContext() +{ + return rive::ore::ContextD3D11::Make(m_gpu.Get(), m_gpuContext.Get()); +} + #endif class BufferRingD3D : public BufferRing
diff --git a/renderer/src/d3d12/render_context_d3d12_impl.cpp b/renderer/src/d3d12/render_context_d3d12_impl.cpp index 0749204..2657153 100644 --- a/renderer/src/d3d12/render_context_d3d12_impl.cpp +++ b/renderer/src/d3d12/render_context_d3d12_impl.cpp
@@ -6,6 +6,7 @@ #include "rive/renderer/d3d/d3d_constants.hpp" #ifdef RIVE_CANVAS #include "rive/renderer/render_canvas.hpp" +#include "rive/renderer/ore/ore_context_d3d12.hpp" #endif #include "rive/profiler/profiler_macros.h" #include "rive/renderer/d3d/d3d_utils.hpp" @@ -807,6 +808,12 @@ return make_rcp<RenderCanvas>(std::move(renderImage), std::move(renderTarget)); } + +std::unique_ptr<rive::ore::Context> RenderContextD3D12Impl::makeOreContext() +{ + assert(m_canvasQueue); + return rive::ore::ContextD3D12::Make(m_device.Get(), m_canvasQueue); +} #endif void rive::gpu::RenderContextD3D12Impl::resizeGradientTexture(uint32_t width,
diff --git a/renderer/src/gl/render_context_gl_impl.cpp b/renderer/src/gl/render_context_gl_impl.cpp index 0ad6e3e..7ae754c 100644 --- a/renderer/src/gl/render_context_gl_impl.cpp +++ b/renderer/src/gl/render_context_gl_impl.cpp
@@ -9,6 +9,7 @@ #include "rive/renderer/draw.hpp" #ifdef RIVE_CANVAS #include "rive/renderer/render_canvas.hpp" +#include "rive/renderer/ore/ore_context_gl.hpp" #endif #include "rive/renderer/render_context_impl.hpp" #include "rive/renderer/rive_renderer.hpp" @@ -781,6 +782,11 @@ std::move(renderTarget)); } +std::unique_ptr<rive::ore::Context> RenderContextGLImpl::makeOreContext() +{ + return rive::ore::ContextGL::Make(); +} + // ──────────────────────────────────────────────────────────────────────────── // Canvas mirror registry implementation (GL-only "imported canvas" handling) // ────────────────────────────────────────────────────────────────────────────
diff --git a/renderer/src/metal/render_context_metal_impl.mm b/renderer/src/metal/render_context_metal_impl.mm index 9448d5a..0905172 100644 --- a/renderer/src/metal/render_context_metal_impl.mm +++ b/renderer/src/metal/render_context_metal_impl.mm
@@ -8,6 +8,7 @@ #include "rive/renderer/buffer_ring.hpp" #ifdef RIVE_CANVAS #include "rive/renderer/render_canvas.hpp" +#include "rive/renderer/ore/ore_context_metal.hpp" #endif #include "rive/renderer/texture.hpp" #include "rive/renderer/rive_render_buffer.hpp" @@ -921,6 +922,12 @@ return make_rcp<RenderCanvas>(std::move(renderImage), std::move(renderTarget)); } + +std::unique_ptr<rive::ore::Context> RenderContextMetalImpl::makeOreContext() +{ + assert(m_commandQueue); + return rive::ore::ContextMetal::Make(m_gpu, m_commandQueue); +} #endif std::unique_ptr<BufferRing> RenderContextMetalImpl::makeUniformBufferRing(
diff --git a/renderer/src/ore/d3d11/ore_bind_group_d3d11.cpp b/renderer/src/ore/d3d11/ore_bind_group_d3d11.cpp index 7003480..f2164a0 100644 --- a/renderer/src/ore/d3d11/ore_bind_group_d3d11.cpp +++ b/renderer/src/ore/d3d11/ore_bind_group_d3d11.cpp
@@ -2,22 +2,7 @@ * Copyright 2025 Rive */ -#include "rive/renderer/ore/ore_bind_group.hpp" +#include "ore_bind_group_d3d11.hpp" namespace rive::ore -{ - -#if defined(ORE_BACKEND_D3D11) && !defined(ORE_BACKEND_D3D12) - -void BindGroup::onRefCntReachedZero() const -{ - // Deferred destruction is handled at the Lua GC level via - // Context::deferBindGroupDestroy(), which keeps the rcp<> alive - // until after endFrame(). By the time refcount reaches zero here, - // the GPU is guaranteed to be done. - delete this; -} - -#endif // ORE_BACKEND_D3D11 && !ORE_BACKEND_D3D12 - -} // namespace rive::ore +{} // namespace rive::ore
diff --git a/renderer/src/ore/d3d11/ore_bind_group_d3d11.hpp b/renderer/src/ore/d3d11/ore_bind_group_d3d11.hpp new file mode 100644 index 0000000..bb7c880 --- /dev/null +++ b/renderer/src/ore/d3d11/ore_bind_group_d3d11.hpp
@@ -0,0 +1,49 @@ +#pragma once +#include "rive/renderer/ore/ore_bind_group.hpp" +#include "rive/renderer/ore/ore_binding_map.hpp" +#include <d3d11.h> +#include <cstdint> +#include <vector> + +namespace rive::ore +{ +class ContextD3D11; + +class BindGroupD3D11 : public LITE_RTTI_OVERRIDE(BindGroup, BindGroupD3D11) +{ +public: + struct D3D11UBOBinding + { + ID3D11Buffer* buffer = + nullptr; // raw ptr; ComPtr in ShaderModule keeps it alive + uint32_t binding = 0; // WGSL @binding, for sort + uint16_t vsSlot = BindingMap::kAbsent; + uint16_t psSlot = BindingMap::kAbsent; + uint32_t offset = 0; + uint32_t size = 0; + bool hasDynamicOffset = false; + }; + struct D3D11TexBinding + { + ID3D11ShaderResourceView* srv = nullptr; + uint16_t vsSlot = BindingMap::kAbsent; + uint16_t psSlot = BindingMap::kAbsent; + }; + struct D3D11SamplerBinding + { + ID3D11SamplerState* sampler = nullptr; + uint16_t vsSlot = BindingMap::kAbsent; + uint16_t psSlot = BindingMap::kAbsent; + }; + + BindGroupD3D11() = default; + ~BindGroupD3D11() override = default; + +private: + friend class ContextD3D11; + friend class RenderPassD3D11; + std::vector<D3D11UBOBinding> m_d3d11UBOs; + std::vector<D3D11TexBinding> m_d3d11Textures; + std::vector<D3D11SamplerBinding> m_d3d11Samplers; +}; +} // namespace rive::ore
diff --git a/renderer/src/ore/d3d11/ore_buffer_d3d11.cpp b/renderer/src/ore/d3d11/ore_buffer_d3d11.cpp index 5c968f6..5a381ef 100644 --- a/renderer/src/ore/d3d11/ore_buffer_d3d11.cpp +++ b/renderer/src/ore/d3d11/ore_buffer_d3d11.cpp
@@ -2,7 +2,7 @@ * Copyright 2025 Rive */ -#include "rive/renderer/ore/ore_buffer.hpp" +#include "ore_buffer_d3d11.hpp" #include "rive/rive_types.hpp" #include <d3d11.h> @@ -10,9 +10,9 @@ namespace rive::ore { -#if defined(ORE_BACKEND_D3D11) && !defined(ORE_BACKEND_D3D12) +#if defined(ORE_BACKEND_D3D11) -void Buffer::update(const void* data, uint32_t size, uint32_t offset) +void BufferD3D11::update(const void* data, uint32_t size, uint32_t offset) { assert(offset + size <= m_size); assert(m_d3d11Context != nullptr); @@ -36,9 +36,6 @@ memcpy(static_cast<uint8_t*>(mapped.pData) + offset, data, size); m_d3d11Context->Unmap(m_d3d11Buffer.Get(), 0); } - -void Buffer::onRefCntReachedZero() const { delete this; } - #endif // ORE_BACKEND_D3D11 && !ORE_BACKEND_D3D12 } // namespace rive::ore
diff --git a/renderer/src/ore/d3d11/ore_buffer_d3d11.hpp b/renderer/src/ore/d3d11/ore_buffer_d3d11.hpp new file mode 100644 index 0000000..b3fff40 --- /dev/null +++ b/renderer/src/ore/d3d11/ore_buffer_d3d11.hpp
@@ -0,0 +1,25 @@ +#pragma once +#include "rive/renderer/ore/ore_buffer.hpp" +#include <d3d11.h> +#include <wrl/client.h> + +namespace rive::ore +{ +class ContextD3D11; + +class BufferD3D11 : public LITE_RTTI_OVERRIDE(Buffer, BufferD3D11) +{ +public: + BufferD3D11(uint32_t size, BufferUsage usage) : + lite_rtti_override(size, usage) + {} + ~BufferD3D11() override = default; // ComPtr released automatically + void update(const void* data, uint32_t size, uint32_t offset) override; + +private: + friend class ContextD3D11; + friend class RenderPassD3D11; + Microsoft::WRL::ComPtr<ID3D11Buffer> m_d3d11Buffer; + ID3D11DeviceContext* m_d3d11Context = nullptr; // Weak ref. +}; +} // namespace rive::ore
diff --git a/renderer/src/ore/d3d11/ore_context_d3d11.cpp b/renderer/src/ore/d3d11/ore_context_d3d11.cpp index 5a7e9e2..bcf1d37 100644 --- a/renderer/src/ore/d3d11/ore_context_d3d11.cpp +++ b/renderer/src/ore/d3d11/ore_context_d3d11.cpp
@@ -3,13 +3,13 @@ */ #include "rive/renderer/ore/ore_context_d3d11.hpp" -#include "rive/renderer/ore/ore_bind_group.hpp" -#include "rive/renderer/ore/ore_buffer.hpp" -#include "rive/renderer/ore/ore_texture.hpp" -#include "rive/renderer/ore/ore_sampler.hpp" -#include "rive/renderer/ore/ore_shader_module.hpp" -#include "rive/renderer/ore/ore_pipeline.hpp" -#include "rive/renderer/ore/ore_render_pass.hpp" +#include "ore_bind_group_d3d11.hpp" +#include "ore_buffer_d3d11.hpp" +#include "ore_texture_d3d11.hpp" +#include "ore_sampler_d3d11.hpp" +#include "ore_shader_module_d3d11.hpp" +#include "ore_pipeline_d3d11.hpp" +#include "ore_render_pass_d3d11.hpp" #include "rive/renderer/render_canvas.hpp" #include "rive/renderer/d3d11/render_context_d3d_impl.hpp" #include "rive/rive_types.hpp" @@ -435,7 +435,7 @@ return nullptr; } - auto buffer = rcp<Buffer>(new Buffer(desc.size, desc.usage)); + auto buffer = rcp<BufferD3D11>(new BufferD3D11(desc.size, desc.usage)); buffer->m_d3d11Context = m_d3d11Context.Get(); D3D11_BUFFER_DESC bd{}; @@ -516,7 +516,7 @@ return nullptr; } - auto texture = rcp<Texture>(new Texture(desc)); + auto texture = rcp<TextureD3D11>(new TextureD3D11(desc)); texture->m_d3d11Context = m_d3d11Context.Get(); UINT bindFlags = D3D11_BIND_SHADER_RESOURCE; @@ -595,11 +595,11 @@ rcp<TextureView> ContextD3D11::d3d11MakeTextureView(const TextureViewDesc& desc) { - Texture* tex = desc.texture; + TextureD3D11* tex = lite_rtti_cast<TextureD3D11*>(desc.texture); if (!tex) return nullptr; - auto view = rcp<TextureView>(new TextureView(ref_rcp(tex), desc)); + auto view = rcp<TextureViewD3D11>(new TextureViewD3D11(ref_rcp(tex), desc)); const D3D11FormatInfo fmtInfo = oreFormatInfo(tex->format()); @@ -772,7 +772,7 @@ sd.MinLOD = desc.minLod; sd.MaxLOD = desc.maxLod; - auto sampler = rcp<Sampler>(new Sampler()); + auto sampler = rcp<SamplerD3D11>(new SamplerD3D11()); HRESULT hr = m_d3d11Device->CreateSamplerState( &sd, sampler->m_d3dSampler.ReleaseAndGetAddressOf()); @@ -788,7 +788,7 @@ rcp<ShaderModule> ContextD3D11::d3d11MakeShaderModule( const ShaderModuleDesc& desc) { - auto module = rcp<ShaderModule>(new ShaderModule()); + auto module = rcp<ShaderModuleD3D11>(new ShaderModuleD3D11()); module->m_stage = desc.stage; // HLSL source compiled at first pipeline use via ensureD3DShaders. @@ -810,7 +810,7 @@ rcp<Pipeline> ContextD3D11::d3d11MakePipeline(const PipelineDesc& desc, std::string* outError) { - auto pipeline = rcp<Pipeline>(new Pipeline(desc)); + auto pipeline = rcp<PipelineD3D11>(new PipelineD3D11(desc)); // --- Validate user-supplied layouts against shader binding map --- { @@ -834,12 +834,15 @@ // Keep ShaderModules alive for the lifetime of the Pipeline. // The Luau GC can destroy the ScriptedShader (which owns the // ShaderModule rcp) at any time after script init. - pipeline->m_vsModule = ref_rcp(desc.vertexModule); - if (desc.fragmentModule != nullptr) - pipeline->m_psModule = ref_rcp(desc.fragmentModule); + auto vertexModule = lite_rtti_cast<ShaderModuleD3D11*>(desc.vertexModule); + auto fragmentModule = + lite_rtti_cast<ShaderModuleD3D11*>(desc.fragmentModule); + pipeline->m_vsModule = ref_rcp(vertexModule); + if (fragmentModule != nullptr) + pipeline->m_psModule = ref_rcp(fragmentModule); std::string compileErr; - desc.vertexModule->ensureD3DShaders(m_d3d11Device.Get(), &compileErr); + vertexModule->ensureD3DShaders(m_d3d11Device.Get(), &compileErr); if (!compileErr.empty()) { setLastError("Ore D3D11 VS: %s", compileErr.c_str()); @@ -847,9 +850,9 @@ *outError = m_lastError; return nullptr; } - if (desc.fragmentModule != nullptr) + if (fragmentModule != nullptr) { - desc.fragmentModule->ensureD3DShaders(m_d3d11Device.Get(), &compileErr); + fragmentModule->ensureD3DShaders(m_d3d11Device.Get(), &compileErr); if (!compileErr.empty()) { setLastError("Ore D3D11 PS: %s", compileErr.c_str()); @@ -859,9 +862,9 @@ } } - pipeline->m_d3dVS = desc.vertexModule->m_d3dVertexShader.Get(); + pipeline->m_d3dVS = vertexModule->m_d3dVertexShader.Get(); if (desc.fragmentModule != nullptr) - pipeline->m_d3dPS = desc.fragmentModule->m_d3dPixelShader.Get(); + pipeline->m_d3dPS = fragmentModule->m_d3dPixelShader.Get(); if (!pipeline->m_d3dVS || (desc.fragmentModule != nullptr && !pipeline->m_d3dPS)) @@ -906,7 +909,7 @@ } } - const auto& vsBytecode = desc.vertexModule->m_bytecode; + const auto& vsBytecode = vertexModule->m_bytecode; HRESULT hr = m_d3d11Device->CreateInputLayout( elements, elementCount, @@ -1055,7 +1058,7 @@ return nullptr; } - auto bg = rcp<BindGroup>(new BindGroup()); + auto bg = rcp<BindGroupD3D11>(new BindGroupD3D11()); bg->m_context = this; bg->m_layoutRef = ref_rcp(layout); @@ -1114,8 +1117,10 @@ for (uint32_t i = 0; i < nBufs; ++i) { const auto& entry = desc.ubos[i]; - BindGroup::D3D11UBOBinding binding{}; - binding.buffer = entry.buffer->m_d3d11Buffer.Get(); + BindGroupD3D11::D3D11UBOBinding binding{}; + auto buffer = lite_rtti_cast<BufferD3D11*>(entry.buffer); + assert(buffer); + binding.buffer = buffer->m_d3d11Buffer.Get(); binding.binding = entry.slot; if (!lookupStages(entry.slot, BindingKind::uniformBuffer, @@ -1137,8 +1142,8 @@ // `desc.ubos[]` ordering (WebGPU contract; matches Dawn). std::sort(bg->m_d3d11UBOs.begin(), bg->m_d3d11UBOs.end(), - [](const BindGroup::D3D11UBOBinding& a, - const BindGroup::D3D11UBOBinding& b) { + [](const BindGroupD3D11::D3D11UBOBinding& a, + const BindGroupD3D11::D3D11UBOBinding& b) { return a.binding < b.binding; }); @@ -1148,8 +1153,10 @@ for (uint32_t i = 0; i < nTexs; ++i) { const auto& entry = desc.textures[i]; - BindGroup::D3D11TexBinding binding{}; - binding.srv = entry.view->m_d3dSRV.Get(); + BindGroupD3D11::D3D11TexBinding binding{}; + auto view = lite_rtti_cast<TextureViewD3D11*>(entry.view); + assert(view); + binding.srv = view->m_d3dSRV.Get(); if (!lookupStages(entry.slot, BindingKind::sampledTexture, &binding.vsSlot, @@ -1165,8 +1172,10 @@ for (uint32_t i = 0; i < nSamps; ++i) { const auto& entry = desc.samplers[i]; - BindGroup::D3D11SamplerBinding binding{}; - binding.sampler = entry.sampler->m_d3dSampler.Get(); + BindGroupD3D11::D3D11SamplerBinding binding{}; + auto sampler = lite_rtti_cast<SamplerD3D11*>(entry.sampler); + assert(sampler); + binding.sampler = sampler->m_d3dSampler.Get(); if (!lookupStages(entry.slot, BindingKind::sampler, &binding.vsSlot, @@ -1207,19 +1216,25 @@ // d3d11BeginRenderPass // ============================================================================ -RenderPass ContextD3D11::d3d11BeginRenderPass(const RenderPassDesc& desc, - std::string* outError) +std::unique_ptr<RenderPass> ContextD3D11::d3d11BeginRenderPass( + const RenderPassDesc& desc, + std::string* outError) { // Collect RTVs and DSV. ID3D11RenderTargetView* rtvs[4] = {}; for (uint32_t i = 0; i < desc.colorCount; ++i) { - rtvs[i] = desc.colorAttachments[i].view->m_d3dRTV.Get(); + auto view = + lite_rtti_cast<TextureViewD3D11*>(desc.colorAttachments[i].view); + assert(view); + rtvs[i] = view->m_d3dRTV.Get(); } - ID3D11DepthStencilView* dsv = desc.depthStencil.view - ? desc.depthStencil.view->m_d3dDSV.Get() - : nullptr; + ID3D11DepthStencilView* dsv = nullptr; + if (auto view = lite_rtti_cast<TextureViewD3D11*>(desc.depthStencil.view)) + { + dsv = view->m_d3dDSV.Get(); + } m_d3d11Context->OMSetRenderTargets(desc.colorCount, rtvs, dsv); @@ -1289,29 +1304,36 @@ } } - RenderPass pass; - pass.m_context = this; - pass.m_d3d11Context = m_d3d11Context.Get(); - pass.populateAttachmentMetadata(desc); + std::unique_ptr<RenderPassD3D11> pass = std::make_unique<RenderPassD3D11>(); + pass->m_context = this; + pass->m_d3d11Context = m_d3d11Context.Get(); + pass->populateAttachmentMetadata(desc); // Record MSAA resolve pairs for finish(). Subresource index follows // D3D11's formula: mipLevel + (arraySlice * mipCount). - pass.m_d3d11ResolveCount = 0; + pass->m_d3d11ResolveCount = 0; for (uint32_t i = 0; i < desc.colorCount; ++i) { const auto& ca = desc.colorAttachments[i]; if (ca.resolveTarget && ca.view) { - auto& entry = pass.m_d3d11Resolves[pass.m_d3d11ResolveCount++]; - entry.msaa = ca.view->texture()->m_d3d11Texture.Get(); - entry.resolve = ca.resolveTarget->texture()->m_d3d11Texture.Get(); + auto& entry = pass->m_d3d11Resolves[pass->m_d3d11ResolveCount++]; + auto view = lite_rtti_cast<TextureViewD3D11*>(ca.view); + assert(view); + auto texture = lite_rtti_cast<TextureD3D11*>(view->texture()); + assert(texture); + entry.msaa = texture->m_d3d11Texture.Get(); + auto resolveTexture = + lite_rtti_cast<TextureD3D11*>(ca.resolveTarget->texture()); + assert(resolveTexture); + entry.resolve = resolveTexture->m_d3d11Texture.Get(); entry.format = oreFormatInfo(ca.resolveTarget->texture()->format()).resource; - const uint32_t msaaMipCount = ca.view->texture()->numMipmaps(); + const uint32_t msaaMipCount = view->texture()->numMipmaps(); const uint32_t resolveMipCount = ca.resolveTarget->texture()->numMipmaps(); entry.msaaSubresource = - ca.view->baseMipLevel() + ca.view->baseLayer() * msaaMipCount; + view->baseMipLevel() + view->baseLayer() * msaaMipCount; entry.resolveSubresource = ca.resolveTarget->baseMipLevel() + ca.resolveTarget->baseLayer() * resolveMipCount; @@ -1362,7 +1384,7 @@ texDesc.numMipmaps = 1; texDesc.sampleCount = 1; - auto texture = rcp<Texture>(new Texture(texDesc)); + auto texture = rcp<TextureD3D11>(new TextureD3D11(texDesc)); texture->m_d3d11Texture = d3dTex; // Borrow — RenderCanvas owns it. texture->m_d3d11Context = m_d3d11Context.Get(); @@ -1374,7 +1396,8 @@ viewDesc.baseLayer = 0; viewDesc.layerCount = 1; - auto view = rcp<TextureView>(new TextureView(std::move(texture), viewDesc)); + auto view = rcp<TextureViewD3D11>( + new TextureViewD3D11(std::move(texture), viewDesc)); // Borrow the existing RTV from the D3D render target (AddRefs via ComPtr). view->m_d3dRTV = d3dTarget->targetRTV(); return view; @@ -1421,7 +1444,7 @@ texDesc.numMipmaps = 1; texDesc.sampleCount = 1; - auto texture = rcp<Texture>(new Texture(texDesc)); + auto texture = rcp<TextureD3D11>(new TextureD3D11(texDesc)); texture->m_d3d11Texture = d3dTex; // Borrow — caller owns via RenderImage. texture->m_d3d11Context = m_d3d11Context.Get(); @@ -1433,7 +1456,8 @@ viewDesc.baseLayer = 0; viewDesc.layerCount = 1; - auto view = rcp<TextureView>(new TextureView(std::move(texture), viewDesc)); + auto view = rcp<TextureViewD3D11>( + new TextureViewD3D11(std::move(texture), viewDesc)); // Create an SRV for sampling. The canvas path borrows an existing RTV, // but for image sampling we need a ShaderResourceView. D3D11_SHADER_RESOURCE_VIEW_DESC srvDesc{}; @@ -1555,8 +1579,9 @@ return d3d11MakeBindGroupLayout(desc); } -RenderPass ContextD3D11::beginRenderPass(const RenderPassDesc& desc, - std::string* outError) +std::unique_ptr<RenderPass> ContextD3D11::beginRenderPass( + const RenderPassDesc& desc, + std::string* outError) { finishActiveRenderPass(); return d3d11BeginRenderPass(desc, outError);
diff --git a/renderer/src/ore/d3d11/ore_pipeline_d3d11.cpp b/renderer/src/ore/d3d11/ore_pipeline_d3d11.cpp index 13e5495..66637b0 100644 --- a/renderer/src/ore/d3d11/ore_pipeline_d3d11.cpp +++ b/renderer/src/ore/d3d11/ore_pipeline_d3d11.cpp
@@ -2,18 +2,4 @@ * Copyright 2025 Rive */ -#include "rive/renderer/ore/ore_pipeline.hpp" -#include "rive/renderer/ore/ore_bind_group_layout.hpp" - -namespace rive::ore -{ - -#if defined(ORE_BACKEND_D3D11) && !defined(ORE_BACKEND_D3D12) - -void Pipeline::onRefCntReachedZero() const { delete this; } - -void BindGroupLayout::onRefCntReachedZero() const { delete this; } - -#endif // ORE_BACKEND_D3D11 && !ORE_BACKEND_D3D12 - -} // namespace rive::ore +#include "ore_pipeline_d3d11.hpp"
diff --git a/renderer/src/ore/d3d11/ore_pipeline_d3d11.hpp b/renderer/src/ore/d3d11/ore_pipeline_d3d11.hpp new file mode 100644 index 0000000..e1a8034 --- /dev/null +++ b/renderer/src/ore/d3d11/ore_pipeline_d3d11.hpp
@@ -0,0 +1,31 @@ +#pragma once +#include "rive/renderer/ore/ore_pipeline.hpp" +#include "ore_shader_module_d3d11.hpp" +#include <d3d11.h> +#include <wrl/client.h> + +namespace rive::ore +{ +class ContextD3D11; + +class PipelineD3D11 : public LITE_RTTI_OVERRIDE(Pipeline, PipelineD3D11) +{ +public: + PipelineD3D11(const PipelineDesc& desc) : lite_rtti_override(desc) {} + ~PipelineD3D11() override = default; // ComPtrs released automatically + +private: + friend class ContextD3D11; + friend class RenderPassD3D11; + // Raw shader pointers — valid as long as m_vsModule / m_psModule are alive. + ID3D11VertexShader* m_d3dVS = nullptr; + ID3D11PixelShader* m_d3dPS = nullptr; + Microsoft::WRL::ComPtr<ID3D11InputLayout> m_d3dInputLayout; + Microsoft::WRL::ComPtr<ID3D11RasterizerState> m_d3dRasterizer; + Microsoft::WRL::ComPtr<ID3D11DepthStencilState> m_d3dDepthStencil; + Microsoft::WRL::ComPtr<ID3D11BlendState> m_d3dBlend; + // Keep modules alive so that m_d3dVS / m_d3dPS remain valid. + rcp<ShaderModuleD3D11> m_vsModule; + rcp<ShaderModuleD3D11> m_psModule; +}; +} // namespace rive::ore
diff --git a/renderer/src/ore/d3d11/ore_render_pass_d3d11.cpp b/renderer/src/ore/d3d11/ore_render_pass_d3d11.cpp index 9283dd5..d17aa53 100644 --- a/renderer/src/ore/d3d11/ore_render_pass_d3d11.cpp +++ b/renderer/src/ore/d3d11/ore_render_pass_d3d11.cpp
@@ -2,14 +2,14 @@ * Copyright 2025 Rive */ -#include "rive/renderer/ore/ore_render_pass.hpp" -#include "rive/renderer/ore/ore_bind_group.hpp" -#include "rive/renderer/ore/ore_buffer.hpp" -#include "rive/renderer/ore/ore_texture.hpp" -#include "rive/renderer/ore/ore_sampler.hpp" -#include "rive/renderer/ore/ore_pipeline.hpp" -#include "rive/renderer/ore/ore_shader_module.hpp" -#include "rive/renderer/ore/ore_context_d3d11.hpp" // for RenderPass inline bodies +#include "ore_render_pass_d3d11.hpp" +#include "ore_bind_group_d3d11.hpp" +#include "ore_buffer_d3d11.hpp" +#include "ore_texture_d3d11.hpp" +#include "ore_sampler_d3d11.hpp" +#include "ore_pipeline_d3d11.hpp" +#include "ore_shader_module_d3d11.hpp" +#include "rive/renderer/ore/ore_context_d3d11.hpp" // for RenderPassD3D11 inline bodies #include "rive/rive_types.hpp" #include <d3d11.h> @@ -18,7 +18,7 @@ { // ============================================================================ -// D3D11 static helpers — used by both the standalone D3D11-only RenderPass +// D3D11 static helpers — used by both the standalone D3D11-only RenderPassD3D11 // methods below and by the combined D3D11+D3D12 dispatch file // (ore_render_pass_d3d11_d3d12.cpp) which #includes this file. // ============================================================================ @@ -61,12 +61,12 @@ #endif // ORE_BACKEND_D3D11 // ============================================================================ -// RenderPass — D3D11-only method definitions +// RenderPassD3D11 — D3D11-only method definitions // ============================================================================ -#if defined(ORE_BACKEND_D3D11) && !defined(ORE_BACKEND_D3D12) +#if defined(ORE_BACKEND_D3D11) -RenderPass::~RenderPass() +RenderPassD3D11::~RenderPassD3D11() { if (!m_finished && m_d3d11Context != nullptr) { @@ -74,16 +74,15 @@ } } -RenderPass::RenderPass(RenderPass&& other) noexcept : - m_currentPipeline(std::move(other.m_currentPipeline)), +RenderPassD3D11::RenderPassD3D11(RenderPassD3D11&& other) noexcept : m_d3d11Context(other.m_d3d11Context), + m_currentPipeline(std::move(other.m_currentPipeline)), m_d3d11Topology(other.m_d3d11Topology), m_d3d11IndexFormat(other.m_d3d11IndexFormat), m_d3d11IndexOffset(other.m_d3d11IndexOffset), m_d3d11StencilRef(other.m_d3d11StencilRef), m_d3d11ResolveCount(other.m_d3d11ResolveCount) { - moveCrossBackendFieldsFrom(other); m_d3d11BlendFactor[0] = other.m_d3d11BlendFactor[0]; m_d3d11BlendFactor[1] = other.m_d3d11BlendFactor[1]; m_d3d11BlendFactor[2] = other.m_d3d11BlendFactor[2]; @@ -93,7 +92,7 @@ other.m_d3d11Context = nullptr; } -RenderPass& RenderPass::operator=(RenderPass&& other) noexcept +RenderPassD3D11& RenderPassD3D11::operator=(RenderPassD3D11&& other) noexcept { if (this != &other) { @@ -101,7 +100,6 @@ { finish(); } - moveCrossBackendFieldsFrom(other); m_d3d11Context = other.m_d3d11Context; m_currentPipeline = std::move(other.m_currentPipeline); m_d3d11Topology = other.m_d3d11Topology; @@ -120,15 +118,16 @@ return *this; } -void RenderPass::validate() const +void RenderPassD3D11::validate() const { - assert(!m_finished && "RenderPass already finished"); + assert(!m_finished && "RenderPassD3D11 already finished"); assert(m_d3d11Context != nullptr); } -void RenderPass::setPipeline(Pipeline* pipeline) +void RenderPassD3D11::setPipeline(Pipeline* inPipeline) { validate(); + auto* pipeline = static_cast<PipelineD3D11*>(inPipeline); if (!checkPipelineCompat(pipeline)) return; m_currentPipeline = ref_rcp(pipeline); @@ -150,9 +149,12 @@ 0xFFFFFFFF); } -void RenderPass::setVertexBuffer(uint32_t slot, Buffer* buffer, uint32_t offset) +void RenderPassD3D11::setVertexBuffer(uint32_t slot, + Buffer* inBuffer, + uint32_t offset) { validate(); + auto buffer = static_cast<BufferD3D11*>(inBuffer); UINT stride = (m_currentPipeline && slot < m_currentPipeline->desc().vertexBufferCount) ? m_currentPipeline->desc().vertexBuffers[slot].stride @@ -162,11 +164,12 @@ m_d3d11Context->IASetVertexBuffers(slot, 1, &buf, &stride, &off); } -void RenderPass::setIndexBuffer(Buffer* buffer, - IndexFormat format, - uint32_t offset) +void RenderPassD3D11::setIndexBuffer(Buffer* inBuffer, + IndexFormat format, + uint32_t offset) { validate(); + auto buffer = static_cast<BufferD3D11*>(inBuffer); m_d3d11IndexFormat = oreIndexFormatToDXGI(format); m_d3d11IndexOffset = offset; m_d3d11Context->IASetIndexBuffer(buffer->m_d3d11Buffer.Get(), @@ -174,12 +177,13 @@ offset); } -void RenderPass::setBindGroup(uint32_t groupIndex, - BindGroup* bg, - const uint32_t* dynamicOffsets, - uint32_t dynamicOffsetCount) +void RenderPassD3D11::setBindGroup(uint32_t groupIndex, + BindGroup* inBg, + const uint32_t* dynamicOffsets, + uint32_t dynamicOffsetCount) { validate(); + auto bg = static_cast<BindGroupD3D11*>(inBg); assert(bg != nullptr); // Hold a strong reference so the BindGroup stays alive until finish(). @@ -284,12 +288,12 @@ } } -void RenderPass::setViewport(float x, - float y, - float width, - float height, - float minDepth, - float maxDepth) +void RenderPassD3D11::setViewport(float x, + float y, + float width, + float height, + float minDepth, + float maxDepth) { validate(); D3D11_VIEWPORT vp{}; @@ -312,10 +316,10 @@ m_d3d11Context->RSSetScissorRects(1, &scissor); } -void RenderPass::setScissorRect(uint32_t x, - uint32_t y, - uint32_t width, - uint32_t height) +void RenderPassD3D11::setScissorRect(uint32_t x, + uint32_t y, + uint32_t width, + uint32_t height) { validate(); D3D11_RECT rect{}; @@ -326,7 +330,7 @@ m_d3d11Context->RSSetScissorRects(1, &rect); } -void RenderPass::setStencilReference(uint32_t ref) +void RenderPassD3D11::setStencilReference(uint32_t ref) { validate(); m_d3d11StencilRef = ref; @@ -338,7 +342,7 @@ } } -void RenderPass::setBlendColor(float r, float g, float b, float a) +void RenderPassD3D11::setBlendColor(float r, float g, float b, float a) { validate(); m_d3d11BlendFactor[0] = r; @@ -353,10 +357,10 @@ } } -void RenderPass::draw(uint32_t vertexCount, - uint32_t instanceCount, - uint32_t firstVertex, - uint32_t firstInstance) +void RenderPassD3D11::draw(uint32_t vertexCount, + uint32_t instanceCount, + uint32_t firstVertex, + uint32_t firstInstance) { validate(); if (instanceCount > 1 || firstInstance != 0) @@ -372,11 +376,11 @@ } } -void RenderPass::drawIndexed(uint32_t indexCount, - uint32_t instanceCount, - uint32_t firstIndex, - int32_t baseVertex, - uint32_t firstInstance) +void RenderPassD3D11::drawIndexed(uint32_t indexCount, + uint32_t instanceCount, + uint32_t firstIndex, + int32_t baseVertex, + uint32_t firstInstance) { validate(); if (instanceCount > 1 || firstInstance != 0 || baseVertex != 0) @@ -393,7 +397,7 @@ } } -void RenderPass::finish() +void RenderPassD3D11::finish() { if (m_finished) return;
diff --git a/renderer/src/ore/d3d11/ore_render_pass_d3d11.hpp b/renderer/src/ore/d3d11/ore_render_pass_d3d11.hpp new file mode 100644 index 0000000..6bce763 --- /dev/null +++ b/renderer/src/ore/d3d11/ore_render_pass_d3d11.hpp
@@ -0,0 +1,80 @@ +#pragma once +#include "rive/renderer/ore/ore_render_pass.hpp" +#include "ore_pipeline_d3d11.hpp" +#include "rive/refcnt.hpp" +#include <d3d11.h> +#include <cstdint> + +namespace rive::ore +{ +class ContextD3D11; + +class RenderPassD3D11 : public RenderPass +{ +public: + void setPipeline(Pipeline* pipeline) override; + void setVertexBuffer(uint32_t slot, + Buffer* buffer, + uint32_t offset = 0) override; + void setIndexBuffer(Buffer* buffer, + IndexFormat format, + uint32_t offset = 0) override; + void setBindGroup(uint32_t groupIndex, + BindGroup* bg, + const uint32_t* dynamicOffsets = nullptr, + uint32_t dynamicOffsetCount = 0) override; + void setViewport(float x, + float y, + float width, + float height, + float minDepth = 0.0f, + float maxDepth = 1.0f) override; + void setScissorRect(uint32_t x, + uint32_t y, + uint32_t width, + uint32_t height) override; + void setStencilReference(uint32_t ref) override; + void setBlendColor(float r, float g, float b, float a) override; + void draw(uint32_t vertexCount, + uint32_t instanceCount = 1, + uint32_t firstVertex = 0, + uint32_t firstInstance = 0) override; + void drawIndexed(uint32_t indexCount, + uint32_t instanceCount = 1, + uint32_t firstIndex = 0, + int32_t baseVertex = 0, + uint32_t firstInstance = 0) override; + void finish() override; + + void validate() const override; + + RenderPassD3D11() = default; + RenderPassD3D11(Context* context) : RenderPass(context) {} + ~RenderPassD3D11() override; + RenderPassD3D11(RenderPassD3D11&& other) noexcept; + RenderPassD3D11& operator=(RenderPassD3D11&&) noexcept; + + struct D3D11ResolveEntry + { + ID3D11Resource* resolve = nullptr; + UINT resolveSubresource = 0; + ID3D11Resource* msaa = nullptr; + UINT msaaSubresource = 0; + DXGI_FORMAT format = DXGI_FORMAT_UNKNOWN; + }; + +private: + friend class ContextD3D11; + + ID3D11DeviceContext* m_d3d11Context = nullptr; // weak ref + rcp<PipelineD3D11> m_currentPipeline; + D3D11_PRIMITIVE_TOPOLOGY m_d3d11Topology = + D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST; + DXGI_FORMAT m_d3d11IndexFormat = DXGI_FORMAT_R16_UINT; + uint32_t m_d3d11IndexOffset = 0; + uint32_t m_d3d11StencilRef = 0; + float m_d3d11BlendFactor[4] = {}; + uint32_t m_d3d11ResolveCount = 0; + D3D11ResolveEntry m_d3d11Resolves[4]; +}; +} // namespace rive::ore
diff --git a/renderer/src/ore/d3d11/ore_sampler_d3d11.cpp b/renderer/src/ore/d3d11/ore_sampler_d3d11.cpp index 59f8c5f..91f19a8 100644 --- a/renderer/src/ore/d3d11/ore_sampler_d3d11.cpp +++ b/renderer/src/ore/d3d11/ore_sampler_d3d11.cpp
@@ -3,14 +3,3 @@ */ #include "rive/renderer/ore/ore_sampler.hpp" - -namespace rive::ore -{ - -#if defined(ORE_BACKEND_D3D11) && !defined(ORE_BACKEND_D3D12) - -void Sampler::onRefCntReachedZero() const { delete this; } - -#endif // ORE_BACKEND_D3D11 && !ORE_BACKEND_D3D12 - -} // namespace rive::ore
diff --git a/renderer/src/ore/d3d11/ore_sampler_d3d11.hpp b/renderer/src/ore/d3d11/ore_sampler_d3d11.hpp new file mode 100644 index 0000000..7ea499f --- /dev/null +++ b/renderer/src/ore/d3d11/ore_sampler_d3d11.hpp
@@ -0,0 +1,20 @@ +#pragma once +#include "rive/renderer/ore/ore_sampler.hpp" +#include <d3d11.h> +#include <wrl/client.h> + +namespace rive::ore +{ +class ContextD3D11; + +class SamplerD3D11 : public LITE_RTTI_OVERRIDE(Sampler, SamplerD3D11) +{ +public: + SamplerD3D11() = default; + ~SamplerD3D11() override = default; // ComPtr released automatically + +private: + friend class ContextD3D11; + Microsoft::WRL::ComPtr<ID3D11SamplerState> m_d3dSampler; +}; +} // namespace rive::ore
diff --git a/renderer/src/ore/d3d11/ore_shader_module_d3d11.cpp b/renderer/src/ore/d3d11/ore_shader_module_d3d11.cpp index 3c1aaf6..9040efc 100644 --- a/renderer/src/ore/d3d11/ore_shader_module_d3d11.cpp +++ b/renderer/src/ore/d3d11/ore_shader_module_d3d11.cpp
@@ -3,14 +3,104 @@ */ #include "rive/renderer/ore/ore_shader_module.hpp" - +#include "ore_shader_module_d3d11.hpp" +#include <d3d11.h> +#include <d3dcompiler.h> namespace rive::ore { -#if defined(ORE_BACKEND_D3D11) && !defined(ORE_BACKEND_D3D12) +void rive::ore::ShaderModuleD3D11::ensureD3DShaders(ID3D11Device* device, + std::string* outError) +{ + std::call_once(m_d3dInitFlag, + [&]() { ensureD3DShadersImpl(device, outError); }); +} -void ShaderModule::onRefCntReachedZero() const { delete this; } +void ShaderModuleD3D11::ensureD3DShadersImpl(ID3D11Device* device, + std::string* outError) +{ + if (m_hlslSource.empty()) + return; -#endif // ORE_BACKEND_D3D11 && !ORE_BACKEND_D3D12 + // Normalize line endings (SPIRV-Cross outputs \r\n on Windows). + m_hlslSource.erase( + std::remove(m_hlslSource.begin(), m_hlslSource.end(), '\r'), + m_hlslSource.end()); + + const char* target = + (m_stage == ShaderStage::fragment) ? "ps_5_0" : "vs_5_0"; + const char* entry = + m_hlslEntryPoint.empty() ? "main" : m_hlslEntryPoint.c_str(); + Microsoft::WRL::ComPtr<ID3DBlob> compiledBlob; + Microsoft::WRL::ComPtr<ID3DBlob> errors; + HRESULT hr = D3DCompile(m_hlslSource.c_str(), + m_hlslSource.size(), + nullptr, + nullptr, + nullptr, + entry, + target, + D3DCOMPILE_ENABLE_STRICTNESS | + D3DCOMPILE_OPTIMIZATION_LEVEL3, + 0, + compiledBlob.GetAddressOf(), + errors.GetAddressOf()); + if (FAILED(hr)) + { + if (outError) + { + const char* errMsg = + errors ? static_cast<const char*>(errors->GetBufferPointer()) + : "(no error log)"; + char buf[1024]; + snprintf(buf, + sizeof(buf), + "D3DCompile failed (entry=%s target=%s " + "hr=0x%08x): %s", + entry, + target, + static_cast<unsigned>(hr), + errMsg); + *outError = buf; + } + return; + } + + const void* code = compiledBlob->GetBufferPointer(); + SIZE_T codeSize = compiledBlob->GetBufferSize(); + // Store compiled bytecode for CreateInputLayout. + m_bytecode.assign(static_cast<const uint8_t*>(code), + static_cast<const uint8_t*>(code) + codeSize); + + if (m_stage == ShaderStage::fragment) + { + device->CreatePixelShader(code, + codeSize, + nullptr, + m_d3dPixelShader.GetAddressOf()); + } + else if (m_stage == ShaderStage::vertex) + { + device->CreateVertexShader(code, + codeSize, + nullptr, + m_d3dVertexShader.GetAddressOf()); + } + else + { + HRESULT hr = + device->CreateVertexShader(code, + codeSize, + nullptr, + m_d3dVertexShader.GetAddressOf()); + if (FAILED(hr)) + { + device->CreatePixelShader(code, + codeSize, + nullptr, + m_d3dPixelShader.GetAddressOf()); + } + } +} } // namespace rive::ore
diff --git a/renderer/src/ore/d3d11/ore_shader_module_d3d11.hpp b/renderer/src/ore/d3d11/ore_shader_module_d3d11.hpp new file mode 100644 index 0000000..0688584 --- /dev/null +++ b/renderer/src/ore/d3d11/ore_shader_module_d3d11.hpp
@@ -0,0 +1,40 @@ +#pragma once +#include "rive/renderer/ore/ore_shader_module.hpp" +#include "rive/renderer/ore/ore_types.hpp" +#include <d3d11.h> +#include <wrl/client.h> +#include <string> +#include <mutex> + +namespace rive::ore +{ +class ContextD3D11; + +class ShaderModuleD3D11 + : public LITE_RTTI_OVERRIDE(ShaderModule, ShaderModuleD3D11) +{ +public: + ShaderModuleD3D11() = default; + ~ShaderModuleD3D11() override = default; // ComPtrs released automatically + + // Lazily compiles m_hlslSource into m_d3dVertexShader / m_d3dPixelShader + // on the first pipeline build. AMD drivers crash on cross-process DXBC, + // so compilation is deferred until a device context is available. + void ensureD3DShaders(ID3D11Device* device, std::string* outError); + void ensureD3DShadersImpl(ID3D11Device* device, std::string* outError); + +private: + friend class ContextD3D11; + ShaderStage m_stage = ShaderStage::autoDetect; + // HLSL source compiled at first pipeline use via ensureD3DShaders. + std::string m_hlslSource; + std::string m_hlslEntryPoint; + Microsoft::WRL::ComPtr<ID3D11VertexShader> m_d3dVertexShader; + Microsoft::WRL::ComPtr<ID3D11PixelShader> m_d3dPixelShader; + std::vector<uint8_t> m_bytecode; + + // Guards ensureD3DShaders against concurrent first-call from two + // pipelines sharing this ShaderModule. + std::once_flag m_d3dInitFlag; +}; +} // namespace rive::ore
diff --git a/renderer/src/ore/d3d11/ore_texture_d3d11.cpp b/renderer/src/ore/d3d11/ore_texture_d3d11.cpp index b9152b8..2b1ddb5 100644 --- a/renderer/src/ore/d3d11/ore_texture_d3d11.cpp +++ b/renderer/src/ore/d3d11/ore_texture_d3d11.cpp
@@ -2,7 +2,7 @@ * Copyright 2025 Rive */ -#include "rive/renderer/ore/ore_texture.hpp" +#include "ore_texture_d3d11.hpp" #include "rive/rive_types.hpp" #include <d3d11.h> @@ -10,9 +10,9 @@ namespace rive::ore { -#if defined(ORE_BACKEND_D3D11) && !defined(ORE_BACKEND_D3D12) +#if defined(ORE_BACKEND_D3D11) -void Texture::upload(const TextureDataDesc& data) +void TextureD3D11::upload(const TextureDataDesc& data) { assert(m_d3d11Context != nullptr); assert(m_d3d11Texture != nullptr); @@ -37,10 +37,6 @@ data.bytesPerRow * data.rowsPerImage); } -void Texture::onRefCntReachedZero() const { delete this; } - -void TextureView::onRefCntReachedZero() const { delete this; } - -#endif // ORE_BACKEND_D3D11 && !ORE_BACKEND_D3D12 +#endif // ORE_BACKEND_D3D11 } // namespace rive::ore
diff --git a/renderer/src/ore/d3d11/ore_texture_d3d11.hpp b/renderer/src/ore/d3d11/ore_texture_d3d11.hpp new file mode 100644 index 0000000..5985b49 --- /dev/null +++ b/renderer/src/ore/d3d11/ore_texture_d3d11.hpp
@@ -0,0 +1,39 @@ +#pragma once +#include "rive/renderer/ore/ore_texture.hpp" +#include <d3d11.h> +#include <wrl/client.h> + +namespace rive::ore +{ +class ContextD3D11; + +class TextureD3D11 : public LITE_RTTI_OVERRIDE(Texture, TextureD3D11) +{ +public: + TextureD3D11(const TextureDesc& desc) : lite_rtti_override(desc) {} + ~TextureD3D11() override = default; // ComPtr released automatically + void upload(const TextureDataDesc& data) override; + +private: + friend class ContextD3D11; + // ID3D11Resource accommodates both ID3D11Texture2D and ID3D11Texture3D. + Microsoft::WRL::ComPtr<ID3D11Resource> m_d3d11Texture; + ID3D11DeviceContext* m_d3d11Context = nullptr; // Weak ref. +}; + +class TextureViewD3D11 + : public LITE_RTTI_OVERRIDE(TextureView, TextureViewD3D11) +{ +public: + TextureViewD3D11(rcp<Texture> texture, const TextureViewDesc& desc) : + lite_rtti_override(std::move(texture), desc) + {} + ~TextureViewD3D11() override = default; // ComPtrs released automatically + +private: + friend class ContextD3D11; + Microsoft::WRL::ComPtr<ID3D11ShaderResourceView> m_d3dSRV; + Microsoft::WRL::ComPtr<ID3D11RenderTargetView> m_d3dRTV; + Microsoft::WRL::ComPtr<ID3D11DepthStencilView> m_d3dDSV; +}; +} // namespace rive::ore
diff --git a/renderer/src/ore/d3d12/ore_bind_group_d3d11_d3d12.cpp b/renderer/src/ore/d3d12/ore_bind_group_d3d11_d3d12.cpp deleted file mode 100644 index ee9aae5..0000000 --- a/renderer/src/ore/d3d12/ore_bind_group_d3d11_d3d12.cpp +++ /dev/null
@@ -1,26 +0,0 @@ -/* - * Copyright 2025 Rive - */ - -// Combined D3D11 + D3D12 BindGroup implementation for Windows. -// Compiled when both ORE_BACKEND_D3D11 and ORE_BACKEND_D3D12 are active. - -#if defined(ORE_BACKEND_D3D11) && defined(ORE_BACKEND_D3D12) - -#include "rive/renderer/ore/ore_bind_group.hpp" - -namespace rive::ore -{ - -void BindGroup::onRefCntReachedZero() const -{ - // Deferred destruction is handled at the Lua GC level via - // Context::deferBindGroupDestroy(), which keeps the rcp<> alive - // until after endFrame(). By the time refcount reaches zero here, - // the GPU is guaranteed to be done. - delete this; -} - -} // namespace rive::ore - -#endif // ORE_BACKEND_D3D11 && ORE_BACKEND_D3D12
diff --git a/renderer/src/ore/d3d12/ore_bind_group_d3d12.cpp b/renderer/src/ore/d3d12/ore_bind_group_d3d12.cpp index f4ecf5d..0d93aa8 100644 --- a/renderer/src/ore/d3d12/ore_bind_group_d3d12.cpp +++ b/renderer/src/ore/d3d12/ore_bind_group_d3d12.cpp
@@ -2,25 +2,4 @@ * Copyright 2025 Rive */ -#include "rive/renderer/ore/ore_bind_group.hpp" - -namespace rive::ore -{ - -// --- Public method definitions (D3D12-only builds) --- -// When both D3D11 and D3D12 are compiled, the combined -// ore_context_d3d11_d3d12.cpp file provides these methods with dispatch. -#if defined(ORE_BACKEND_D3D12) && !defined(ORE_BACKEND_D3D11) - -void BindGroup::onRefCntReachedZero() const -{ - // Deferred destruction is handled at the Lua GC level via - // Context::deferBindGroupDestroy(), which keeps the rcp<> alive - // until after endFrame(). By the time refcount reaches zero here, - // the GPU is guaranteed to be done. - delete this; -} - -#endif // D3D12-only - -} // namespace rive::ore +#include "ore_bind_group_d3d12.hpp"
diff --git a/renderer/src/ore/d3d12/ore_bind_group_d3d12.hpp b/renderer/src/ore/d3d12/ore_bind_group_d3d12.hpp new file mode 100644 index 0000000..8ae7595 --- /dev/null +++ b/renderer/src/ore/d3d12/ore_bind_group_d3d12.hpp
@@ -0,0 +1,34 @@ +#pragma once +#include "rive/renderer/ore/ore_bind_group.hpp" +#include "rive/renderer/ore/ore_texture.hpp" +#include <d3d12.h> +#include <cstdint> + +namespace rive::ore +{ +class ContextD3D12; + +class BindGroupD3D12 : public LITE_RTTI_OVERRIDE(BindGroup, BindGroupD3D12) +{ +public: + BindGroupD3D12() = default; + ~BindGroupD3D12() override = default; + +private: + friend class ContextD3D12; + friend class RenderPassD3D12; + // UBO (CBV) slots — GPU virtual addresses and sizes indexed by native slot. + D3D12_GPU_VIRTUAL_ADDRESS m_d3dUBOAddresses[8] = {}; + uint32_t m_d3dUBOSizes[8] = {}; + uint8_t m_d3dUBOSlotMask = 0; + uint8_t m_d3dUBODynamicOffsetMask = 0; + // SRV (texture) slots — CPU descriptor handles and texture back-refs. + D3D12_CPU_DESCRIPTOR_HANDLE m_d3dSrvHandles[8] = {}; + Texture* m_d3dSrvTextures[8] = + {}; // Weak refs; kept alive by m_retainedViews. + uint8_t m_d3dSrvSlotMask = 0; + // Sampler slots — CPU descriptor handles. + D3D12_CPU_DESCRIPTOR_HANDLE m_d3dSamplerHandles[8] = {}; + uint8_t m_d3dSamplerSlotMask = 0; +}; +} // namespace rive::ore
diff --git a/renderer/src/ore/d3d12/ore_bind_group_layout_d3d12.hpp b/renderer/src/ore/d3d12/ore_bind_group_layout_d3d12.hpp new file mode 100644 index 0000000..e9b83a1 --- /dev/null +++ b/renderer/src/ore/d3d12/ore_bind_group_layout_d3d12.hpp
@@ -0,0 +1,28 @@ +#pragma once +#include "rive/renderer/ore/ore_bind_group_layout.hpp" +#include "ore_pipeline_d3d12.hpp" // D3D12GroupRootParams + +namespace rive::ore +{ +class ContextD3D12; + +class BindGroupLayoutD3D12 + : public LITE_RTTI_OVERRIDE(BindGroupLayout, BindGroupLayoutD3D12) +{ +public: + BindGroupLayoutD3D12() = default; + ~BindGroupLayoutD3D12() override = default; + + // Accessor for use by D3D12 root-signature builder. + const D3D12GroupRootParams& d3dGroupParams() const + { + return m_d3dGroupParams; + } + + virtual void onRefCntReachedZero() const override; + +private: + friend class ContextD3D12; + D3D12GroupRootParams m_d3dGroupParams; +}; +} // namespace rive::ore
diff --git a/renderer/src/ore/d3d12/ore_buffer_d3d11_d3d12.cpp b/renderer/src/ore/d3d12/ore_buffer_d3d11_d3d12.cpp deleted file mode 100644 index 480a562..0000000 --- a/renderer/src/ore/d3d12/ore_buffer_d3d11_d3d12.cpp +++ /dev/null
@@ -1,63 +0,0 @@ -/* - * Copyright 2025 Rive - */ - -// Combined D3D11 + D3D12 Buffer implementation for Windows. -// Compiled when both ORE_BACKEND_D3D11 and ORE_BACKEND_D3D12 are active. - -#if defined(ORE_BACKEND_D3D11) && defined(ORE_BACKEND_D3D12) - -#include "rive/renderer/ore/ore_buffer.hpp" -#include "rive/renderer/ore/ore_context_d3d12.hpp" -#include "rive/rive_types.hpp" - -#include <d3d11.h> -#include <d3d12.h> -#include <cassert> -#include <cstring> - -namespace rive::ore -{ - -void Buffer::update(const void* data, uint32_t size, uint32_t offset) -{ - assert(offset + size <= m_size); - if (m_d3d11Buffer) - { - // D3D11 path — map, copy, unmap. - assert(m_d3d11Context != nullptr); - D3D11_MAPPED_SUBRESOURCE mapped{}; - D3D11_MAP mapType = (m_usage == BufferUsage::uniform) - ? D3D11_MAP_WRITE_DISCARD - : D3D11_MAP_WRITE_NO_OVERWRITE; - [[maybe_unused]] HRESULT hr = - m_d3d11Context->Map(m_d3d11Buffer.Get(), 0, mapType, 0, &mapped); - assert(SUCCEEDED(hr)); - memcpy(static_cast<uint8_t*>(mapped.pData) + offset, data, size); - m_d3d11Context->Unmap(m_d3d11Buffer.Get(), 0); - } - else - { - // D3D12 path — UPLOAD heap buffer is persistently mapped. - assert(m_d3dBuffer != nullptr); - assert(m_d3dMappedPtr != nullptr); - memcpy(static_cast<uint8_t*>(m_d3dMappedPtr) + offset, data, size); - } -} - -void Buffer::onRefCntReachedZero() const -{ - // m_d3dOreContext is only set on D3D12-backed buffers (see - // d3d12MakeBuffer). D3D11-backed buffers keep the immediate-delete path - // unchanged. - ContextD3D12* ctx = m_d3dOreContext; - auto destroy = [p = const_cast<Buffer*>(this)]() { delete p; }; - if (ctx != nullptr) - ctx->d3dDeferDestroy(std::move(destroy)); - else - destroy(); -} - -} // namespace rive::ore - -#endif // ORE_BACKEND_D3D11 && ORE_BACKEND_D3D12
diff --git a/renderer/src/ore/d3d12/ore_buffer_d3d12.cpp b/renderer/src/ore/d3d12/ore_buffer_d3d12.cpp index a4fe63b..c52b967 100644 --- a/renderer/src/ore/d3d12/ore_buffer_d3d12.cpp +++ b/renderer/src/ore/d3d12/ore_buffer_d3d12.cpp
@@ -2,7 +2,7 @@ * Copyright 2025 Rive */ -#include "rive/renderer/ore/ore_buffer.hpp" +#include "ore_buffer_d3d12.hpp" #include "rive/renderer/ore/ore_context_d3d12.hpp" #include "rive/rive_types.hpp" @@ -16,9 +16,9 @@ // --- Public method definitions (D3D12-only builds) --- // When both D3D11 and D3D12 are compiled, the combined // ore_context_d3d11_d3d12.cpp file provides these methods with dispatch. -#if defined(ORE_BACKEND_D3D12) && !defined(ORE_BACKEND_D3D11) +#if defined(ORE_BACKEND_D3D12) -void Buffer::update(const void* data, uint32_t size, uint32_t offset) +void BufferD3D12::update(const void* data, uint32_t size, uint32_t offset) { assert(offset + size <= m_size); assert(m_d3dBuffer != nullptr); @@ -28,10 +28,10 @@ memcpy(static_cast<uint8_t*>(m_d3dMappedPtr) + offset, data, size); } -void Buffer::onRefCntReachedZero() const +void BufferD3D12::onRefCntReachedZero() const { ContextD3D12* ctx = m_d3dOreContext; - auto destroy = [p = const_cast<Buffer*>(this)]() { delete p; }; + auto destroy = [p = const_cast<BufferD3D12*>(this)]() { delete p; }; if (ctx != nullptr) ctx->d3dDeferDestroy(std::move(destroy)); else
diff --git a/renderer/src/ore/d3d12/ore_buffer_d3d12.hpp b/renderer/src/ore/d3d12/ore_buffer_d3d12.hpp new file mode 100644 index 0000000..9c9e816 --- /dev/null +++ b/renderer/src/ore/d3d12/ore_buffer_d3d12.hpp
@@ -0,0 +1,31 @@ +#pragma once +#include "rive/renderer/ore/ore_buffer.hpp" +#include <d3d12.h> +#include <wrl/client.h> + +namespace rive::ore +{ +class ContextD3D12; + +class BufferD3D12 : public LITE_RTTI_OVERRIDE(Buffer, BufferD3D12) +{ +public: + BufferD3D12(uint32_t size, BufferUsage usage) : + lite_rtti_override(size, usage) + {} + ~BufferD3D12() override = default; // ComPtr released automatically + void update(const void* data, uint32_t size, uint32_t offset) override; + // D3D12 defers the entire CPU object deletion until after GPU fence. + void onRefCntReachedZero() const override; + +private: + friend class ContextD3D12; + friend class RenderPassD3D12; + // UPLOAD heap — persistently mapped; GPU reads directly. + Microsoft::WRL::ComPtr<ID3D12Resource> m_d3dBuffer; + void* m_d3dMappedPtr = nullptr; + // Back-ref so onRefCntReachedZero() can route deletion through + // ContextD3D12::d3dDeferDestroy() in external-CL mode. Weak ref. + ContextD3D12* m_d3dOreContext = nullptr; +}; +} // namespace rive::ore
diff --git a/renderer/src/ore/d3d12/ore_context_d3d12.cpp b/renderer/src/ore/d3d12/ore_context_d3d12.cpp index 912b32b..1723422 100644 --- a/renderer/src/ore/d3d12/ore_context_d3d12.cpp +++ b/renderer/src/ore/d3d12/ore_context_d3d12.cpp
@@ -3,12 +3,14 @@ */ #include "rive/renderer/ore/ore_context_d3d12.hpp" -#include "rive/renderer/ore/ore_buffer.hpp" -#include "rive/renderer/ore/ore_texture.hpp" -#include "rive/renderer/ore/ore_sampler.hpp" -#include "rive/renderer/ore/ore_shader_module.hpp" -#include "rive/renderer/ore/ore_pipeline.hpp" -#include "rive/renderer/ore/ore_render_pass.hpp" +#include "ore_buffer_d3d12.hpp" +#include "ore_texture_d3d12.hpp" +#include "ore_sampler_d3d12.hpp" +#include "ore_shader_module_d3d12.hpp" +#include "ore_pipeline_d3d12.hpp" +#include "ore_bind_group_d3d12.hpp" +#include "ore_bind_group_layout_d3d12.hpp" +#include "ore_render_pass_d3d12.hpp" #include "rive/renderer/render_canvas.hpp" #include "rive/renderer/d3d12/render_context_d3d12_impl.hpp" #include "rive/rive_types.hpp" @@ -866,7 +868,7 @@ rcp<Buffer> ContextD3D12::d3d12MakeBuffer(const BufferDesc& desc) { #if defined(ORE_BACKEND_D3D12) - auto buffer = rcp<Buffer>(new Buffer(desc.size, desc.usage)); + auto buffer = rcp<BufferD3D12>(new BufferD3D12(desc.size, desc.usage)); buffer->m_d3dOreContext = this; // All ORE buffers live in UPLOAD heap — simple, safe for test workloads. @@ -920,7 +922,7 @@ rcp<Texture> ContextD3D12::d3d12MakeTexture(const TextureDesc& desc) { #if defined(ORE_BACKEND_D3D12) - auto texture = rcp<Texture>(new Texture(desc)); + auto texture = rcp<TextureD3D12>(new TextureD3D12(desc)); texture->m_d3dDevice = m_d3dDevice.Get(); texture->m_d3dOreContext = this; @@ -1005,11 +1007,11 @@ rcp<TextureView> ContextD3D12::d3d12MakeTextureView(const TextureViewDesc& desc) { #if defined(ORE_BACKEND_D3D12) - Texture* tex = desc.texture; + TextureD3D12* tex = lite_rtti_cast<TextureD3D12*>(desc.texture); if (!tex) return nullptr; - auto view = rcp<TextureView>(new TextureView(ref_rcp(tex), desc)); + auto view = rcp<TextureViewD3D12>(new TextureViewD3D12(ref_rcp(tex), desc)); view->m_d3dOreContext = this; const D3D12FormatInfo fmtInfo = oreFormatInfoD3D12(tex->format()); @@ -1223,7 +1225,7 @@ rcp<Sampler> ContextD3D12::d3d12MakeSampler(const SamplerDesc& desc) { #if defined(ORE_BACKEND_D3D12) - auto sampler = rcp<Sampler>(new Sampler()); + auto sampler = rcp<SamplerD3D12>(new SamplerD3D12()); sampler->m_d3dOreContext = this; D3D12_CPU_DESCRIPTOR_HANDLE handle = @@ -1264,7 +1266,7 @@ const ShaderModuleDesc& desc) { #if defined(ORE_BACKEND_D3D12) - auto module = rcp<ShaderModule>(new ShaderModule()); + auto module = rcp<ShaderModuleD3D12>(new ShaderModuleD3D12()); // HLSL source compiled in-process via D3DCompile. AMD drivers crash on // cross-process DXBC, so we never ingest pre-compiled bytecode. @@ -1329,7 +1331,7 @@ { (void)outError; #if defined(ORE_BACKEND_D3D12) - auto pipeline = rcp<Pipeline>(new Pipeline(desc)); + auto pipeline = rcp<PipelineD3D12>(new PipelineD3D12(desc)); pipeline->m_d3dOreContext = this; pipeline->m_d3dTopology = oreTopologyToD3D12(desc.topology); @@ -1492,12 +1494,15 @@ // --- Build PSO --- D3D12_GRAPHICS_PIPELINE_STATE_DESC psoDesc = {}; psoDesc.pRootSignature = pipeline->m_d3dRootSigOwned.Get(); - psoDesc.VS.pShaderBytecode = desc.vertexModule->m_d3dBytecode.data(); - psoDesc.VS.BytecodeLength = desc.vertexModule->m_d3dBytecode.size(); - if (desc.fragmentModule != nullptr) + auto vertexModule = lite_rtti_cast<ShaderModuleD3D12*>(desc.vertexModule); + auto fragmentModule = + lite_rtti_cast<ShaderModuleD3D12*>(desc.fragmentModule); + psoDesc.VS.pShaderBytecode = vertexModule->m_d3dBytecode.data(); + psoDesc.VS.BytecodeLength = vertexModule->m_d3dBytecode.size(); + if (fragmentModule != nullptr) { - psoDesc.PS.pShaderBytecode = desc.fragmentModule->m_d3dBytecode.data(); - psoDesc.PS.BytecodeLength = desc.fragmentModule->m_d3dBytecode.size(); + psoDesc.PS.pShaderBytecode = fragmentModule->m_d3dBytecode.data(); + psoDesc.PS.BytecodeLength = fragmentModule->m_d3dBytecode.size(); } // else: psoDesc.PS stays zero — D3D12 allows null PS for depth-only. psoDesc.BlendState = blendDesc; @@ -1554,7 +1559,7 @@ return nullptr; } - auto bg = rcp<BindGroup>(new BindGroup()); + auto bg = rcp<BindGroupD3D12>(new BindGroupD3D12()); bg->m_context = this; bg->m_layoutRef = ref_rcp(layout); @@ -1620,11 +1625,12 @@ if (!nativeSlot(entry.slot, BindingKind::uniformBuffer, &slot)) continue; assert(slot < 8); + auto buffer = lite_rtti_cast<BufferD3D12*>(entry.buffer); + assert(buffer != nullptr); bg->m_d3dUBOAddresses[slot] = - entry.buffer->m_d3dBuffer->GetGPUVirtualAddress() + entry.offset; + buffer->m_d3dBuffer->GetGPUVirtualAddress() + entry.offset; bg->m_d3dUBOSizes[slot] = - entry.size > 0 ? entry.size - : static_cast<uint32_t>(entry.buffer->size()); + entry.size > 0 ? entry.size : static_cast<uint32_t>(buffer->size()); bg->m_d3dUBOSlotMask |= static_cast<uint8_t>(1u << slot); if (layout->hasDynamicOffset(entry.slot)) bg->m_d3dUBODynamicOffsetMask |= static_cast<uint8_t>(1u << slot); @@ -1635,27 +1641,29 @@ for (uint32_t i = 0; i < desc.textureCount; ++i) { const auto& entry = desc.textures[i]; - assert(entry.view != nullptr); + auto view = lite_rtti_cast<TextureViewD3D12*>(entry.view); + assert(view != nullptr); uint32_t slot = 0; if (!nativeSlot(entry.slot, BindingKind::sampledTexture, &slot)) continue; assert(slot < 8); - bg->m_d3dSrvHandles[slot] = entry.view->m_d3dSrvHandle; - bg->m_d3dSrvTextures[slot] = entry.view->texture(); + bg->m_d3dSrvHandles[slot] = view->m_d3dSrvHandle; + bg->m_d3dSrvTextures[slot] = view->texture(); bg->m_d3dSrvSlotMask |= static_cast<uint8_t>(1u << slot); - bg->m_retainedViews.push_back(ref_rcp(entry.view)); + bg->m_retainedViews.push_back(ref_rcp(view)); } // Sampler bindings. for (uint32_t i = 0; i < desc.samplerCount; ++i) { const auto& entry = desc.samplers[i]; - assert(entry.sampler != nullptr); + auto sampler = lite_rtti_cast<SamplerD3D12*>(entry.sampler); + assert(sampler != nullptr); uint32_t slot = 0; if (!nativeSlot(entry.slot, BindingKind::sampler, &slot)) continue; assert(slot < 8); - bg->m_d3dSamplerHandles[slot] = entry.sampler->m_d3dSamplerHandle; + bg->m_d3dSamplerHandles[slot] = sampler->m_d3dSamplerHandle; bg->m_d3dSamplerSlotMask |= static_cast<uint8_t>(1u << slot); bg->m_retainedSamplers.push_back(ref_rcp(entry.sampler)); } @@ -1682,7 +1690,7 @@ kMaxBindGroups); return nullptr; } - auto layout = rcp<BindGroupLayout>(new BindGroupLayout()); + auto layout = rcp<BindGroupLayoutD3D12>(new BindGroupLayoutD3D12()); layout->m_context = this; layout->m_groupIndex = desc.groupIndex; layout->m_entries.reserve(desc.entryCount); @@ -1704,23 +1712,22 @@ // d3d12BeginRenderPass // ============================================================================ -RenderPass ContextD3D12::d3d12BeginRenderPass(const RenderPassDesc& desc, - std::string* outError) +std::unique_ptr<RenderPass> ContextD3D12::d3d12BeginRenderPass( + const RenderPassDesc& desc, + std::string* outError) { #if defined(ORE_BACKEND_D3D12) // Flush any pending texture uploads before rendering. d3d12FlushUploads(); - RenderPass pass; - pass.m_context = this; - pass.m_d3dCmdList = m_d3dCmdList; - pass.m_d3dDevice = m_d3dDevice.Get(); - pass.m_d3dContext = this; + std::unique_ptr<RenderPassD3D12> pass(new RenderPassD3D12(this)); + pass->m_d3dCmdList = m_d3dCmdList; + pass->m_d3dDevice = m_d3dDevice.Get(); + pass->m_d3dContext = this; // `m_d3dCurrentRootSig` starts nullptr; the first `setPipeline` // calls `SetGraphicsRootSignature` with the pipeline's sig (every // pipeline ships with its own per RFC v5 §3.2.2). - pass.populateAttachmentMetadata(desc); - + pass->populateAttachmentMetadata(desc); // Collect RTVs and DSV handles, transitioning resources to the correct // state. D3D12_CPU_DESCRIPTOR_HANDLE rtvHandles[4] = {}; @@ -1729,10 +1736,12 @@ for (uint32_t i = 0; i < desc.colorCount; ++i) { - TextureView* view = desc.colorAttachments[i].view; + TextureViewD3D12* view = + lite_rtti_cast<TextureViewD3D12*>(desc.colorAttachments[i].view); assert(view != nullptr); - Texture* tex = view->texture(); + TextureD3D12* tex = lite_rtti_cast<TextureD3D12*>(view->texture()); + assert(tex != nullptr); if (tex->m_d3dCurrentState != D3D12_RESOURCE_STATE_RENDER_TARGET) { D3D12_RESOURCE_BARRIER barrier = {}; @@ -1749,23 +1758,26 @@ rtvHandles[i] = view->m_d3dRtvHandle; // Record resource + final state for finish() to transition back. - pass.m_d3dColorResources[i] = tex->m_d3dTexture.Get(); - pass.m_d3dColorTextures[i] = tex; + pass->m_d3dColorResources[i] = tex->m_d3dTexture.Get(); + pass->m_d3dColorTextures[i] = tex; // External (canvas) textures go back to COMMON; ORE-owned go to // PIXEL_SHADER_RESOURCE. const D3D12_RESOURCE_STATES colourFinalState = tex->m_d3dIsExternal ? D3D12_RESOURCE_STATE_COMMON : D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE; - pass.m_d3dColorFinalStates[i] = colourFinalState; - pass.m_d3dColorCount++; + pass->m_d3dColorFinalStates[i] = colourFinalState; + pass->m_d3dColorCount++; // Record MSAA resolve pair if present. D3D12 subresource index // for the common single-plane case is mipLevel + arraySlice*mipCount. - TextureView* resolveView = desc.colorAttachments[i].resolveTarget; + TextureViewD3D12* resolveView = lite_rtti_cast<TextureViewD3D12*>( + desc.colorAttachments[i].resolveTarget); if (resolveView != nullptr && resolveView->texture() != nullptr) { - Texture* resolveTex = resolveView->texture(); - auto& r = pass.m_d3dResolves[pass.m_d3dResolveCount++]; + TextureD3D12* resolveTex = + lite_rtti_cast<TextureD3D12*>(resolveView->texture()); + assert(resolveTex != nullptr); + auto& r = pass->m_d3dResolves[pass->m_d3dResolveCount++]; r.msaa = tex->m_d3dTexture.Get(); r.resolve = resolveTex->m_d3dTexture.Get(); r.resolveTex = resolveTex; @@ -1786,8 +1798,11 @@ if (desc.depthStencil.view) { - TextureView* dsView = desc.depthStencil.view; - Texture* dsTex = dsView->texture(); + TextureViewD3D12* dsView = + lite_rtti_cast<TextureViewD3D12*>(desc.depthStencil.view); + assert(dsView != nullptr); + TextureD3D12* dsTex = lite_rtti_cast<TextureD3D12*>(dsView->texture()); + assert(dsTex != nullptr); D3D12_RESOURCE_STATES dsTarget = D3D12_RESOURCE_STATE_DEPTH_WRITE; if (dsTex->m_d3dCurrentState != dsTarget) @@ -1806,12 +1821,12 @@ dsvHandle = dsView->m_d3dDsvHandle; hasDsv = true; - pass.m_d3dDepthResource = dsTex->m_d3dTexture.Get(); - pass.m_d3dDepthTexture = dsTex; + pass->m_d3dDepthResource = dsTex->m_d3dTexture.Get(); + pass->m_d3dDepthTexture = dsTex; // When the depth is stored the caller intends to sample it as a // shader resource (e.g. shadow map read-back), so transition to // PIXEL_SHADER_RESOURCE. Otherwise DEPTH_READ is sufficient. - pass.m_d3dDepthFinalState = + pass->m_d3dDepthFinalState = (desc.depthStencil.depthStoreOp == StoreOp::store) ? D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE : D3D12_RESOURCE_STATE_DEPTH_READ; @@ -1936,7 +1951,7 @@ texDesc.numMipmaps = 1; texDesc.sampleCount = 1; - auto texture = rcp<Texture>(new Texture(texDesc)); + auto texture = rcp<TextureD3D12>(new TextureD3D12(texDesc)); texture->m_d3dTexture = d3dTex->resource(); // Borrow — RenderCanvas owns it. texture->m_d3dCurrentState = D3D12_RESOURCE_STATE_COMMON; @@ -1952,7 +1967,8 @@ viewDesc.baseLayer = 0; viewDesc.layerCount = 1; - auto view = rcp<TextureView>(new TextureView(std::move(texture), viewDesc)); + auto view = rcp<TextureViewD3D12>( + new TextureViewD3D12(std::move(texture), viewDesc)); view->m_d3dOreContext = this; // Create the RTV in our CPU RTV heap. @@ -2016,7 +2032,7 @@ texDesc.numMipmaps = 1; texDesc.sampleCount = 1; - auto texture = rcp<Texture>(new Texture(texDesc)); + auto texture = rcp<TextureD3D12>(new TextureD3D12(texDesc)); texture->m_d3dTexture = d3dTex->resource(); // Borrow. texture->m_d3dCurrentState = D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE; texture->m_d3dIsExternal = true; @@ -2053,7 +2069,8 @@ viewDesc.baseLayer = 0; viewDesc.layerCount = 1; - auto view = rcp<TextureView>(new TextureView(std::move(texture), viewDesc)); + auto view = rcp<TextureViewD3D12>( + new TextureViewD3D12(std::move(texture), viewDesc)); view->m_d3dOreContext = this; // Create SRV for sampling (images are read-only, no RTV needed). if (m_d3dCpuSrvAllocated >= 1024) @@ -2127,8 +2144,9 @@ return d3d12MakeBindGroupLayout(desc); } -RenderPass ContextD3D12::beginRenderPass(const RenderPassDesc& desc, - std::string* outError) +std::unique_ptr<RenderPass> ContextD3D12::beginRenderPass( + const RenderPassDesc& desc, + std::string* outError) { finishActiveRenderPass(); return d3d12BeginRenderPass(desc, outError);
diff --git a/renderer/src/ore/d3d12/ore_d3d12_bind_group_apply.hpp b/renderer/src/ore/d3d12/ore_d3d12_bind_group_apply.hpp index abdc888..9f72938 100644 --- a/renderer/src/ore/d3d12/ore_d3d12_bind_group_apply.hpp +++ b/renderer/src/ore/d3d12/ore_d3d12_bind_group_apply.hpp
@@ -16,27 +16,28 @@ #pragma once -#include "rive/renderer/ore/ore_render_pass.hpp" -#include "rive/renderer/ore/ore_bind_group.hpp" -#include "rive/renderer/ore/ore_context.hpp" -#include "rive/renderer/ore/ore_pipeline.hpp" +#include "rive/renderer/ore/ore_context_d3d12.hpp" +#include "ore_render_pass_d3d12.hpp" +#include "ore_bind_group_d3d12.hpp" +#include "ore_pipeline_d3d12.hpp" #include <d3d12.h> #include <cassert> #include <climits> #include <cstdint> +#include "ore_texture_d3d12.hpp" namespace rive::ore { -inline void RenderPass::d3d12ApplyBindGroup(uint32_t groupIndex, - BindGroup* bg, - const uint32_t* dynamicOffsets, - uint32_t dynamicOffsetCount) +inline void RenderPassD3D12::d3d12ApplyBindGroup(uint32_t groupIndex, + BindGroupD3D12* bg, + const uint32_t* dynamicOffsets, + uint32_t dynamicOffsetCount) { assert(groupIndex < 4); // RFC v4 §9.1 / §14.2. - Pipeline* pipe = m_d3dCurrentPipeline.get(); + PipelineD3D12* pipe = m_d3dCurrentPipeline.get(); assert(pipe != nullptr && pipe->m_d3dRootSigOwned && "d3d12ApplyBindGroup: pipeline missing per-pipeline root sig — " "every Ore D3D12 pipeline must ship with a populated binding map"); @@ -129,7 +130,8 @@ uint8_t globalSlot = gp.srvBaseGlobalSlot + i; if (!(bg->m_d3dSrvSlotMask & (1u << globalSlot))) continue; - Texture* tex = bg->m_d3dSrvTextures[globalSlot]; + TextureD3D12* tex = + lite_rtti_cast<TextureD3D12*>(bg->m_d3dSrvTextures[globalSlot]); if (tex == nullptr) continue; // Require *full* coverage of both shader-stage bits, not
diff --git a/renderer/src/ore/d3d12/ore_d3d12_root_sig.hpp b/renderer/src/ore/d3d12/ore_d3d12_root_sig.hpp index 5743a89..178d2e0 100644 --- a/renderer/src/ore/d3d12/ore_d3d12_root_sig.hpp +++ b/renderer/src/ore/d3d12/ore_d3d12_root_sig.hpp
@@ -126,7 +126,9 @@ if (g >= layoutCount || layouts == nullptr || layouts[g] == nullptr) continue; - const D3D12GroupRootParams& src = layouts[g]->d3dGroupParams(); + auto layout = lite_rtti_cast<BindGroupLayoutD3D12*>(layouts[g]); + assert(layout && "BindGroupLayout must be a BindGroupLayoutD3D12"); + const D3D12GroupRootParams& src = layout->d3dGroupParams(); D3D12GroupRootParams& out = groupOut[g]; // Mirror counts + base global slots from the layout. Indices get
diff --git a/renderer/src/ore/d3d12/ore_pipeline_d3d11_d3d12.cpp b/renderer/src/ore/d3d12/ore_pipeline_d3d11_d3d12.cpp deleted file mode 100644 index eb8b2b8..0000000 --- a/renderer/src/ore/d3d12/ore_pipeline_d3d11_d3d12.cpp +++ /dev/null
@@ -1,44 +0,0 @@ -/* - * Copyright 2025 Rive - */ - -// Combined D3D11 + D3D12 Pipeline implementation for Windows. -// Compiled when both ORE_BACKEND_D3D11 and ORE_BACKEND_D3D12 are active. - -#if defined(ORE_BACKEND_D3D11) && defined(ORE_BACKEND_D3D12) - -#include "rive/renderer/ore/ore_pipeline.hpp" -#include "rive/renderer/ore/ore_bind_group_layout.hpp" -#include "rive/renderer/ore/ore_context_d3d12.hpp" - -namespace rive::ore -{ - -void Pipeline::onRefCntReachedZero() const -{ - // m_d3dOreContext is only set on D3D12-backed pipelines (see - // d3d12MakePipeline). D3D11-backed pipelines keep the immediate-delete - // path unchanged. - ContextD3D12* ctx = m_d3dOreContext; - auto destroy = [p = const_cast<Pipeline*>(this)]() { delete p; }; - if (ctx != nullptr) - ctx->d3dDeferDestroy(std::move(destroy)); - else - destroy(); -} - -void BindGroupLayout::onRefCntReachedZero() const -{ - // m_context is set for D3D12 layouts (deferred destroy); D3D11 layouts - // have m_context == nullptr and use the immediate-delete path. - ContextD3D12* ctx = static_cast<ContextD3D12*>(m_context); - auto destroy = [p = const_cast<BindGroupLayout*>(this)]() { delete p; }; - if (ctx != nullptr) - ctx->d3dDeferDestroy(std::move(destroy)); - else - destroy(); -} - -} // namespace rive::ore - -#endif // ORE_BACKEND_D3D11 && ORE_BACKEND_D3D12
diff --git a/renderer/src/ore/d3d12/ore_pipeline_d3d12.cpp b/renderer/src/ore/d3d12/ore_pipeline_d3d12.cpp index d4c977e..fe4ae81 100644 --- a/renderer/src/ore/d3d12/ore_pipeline_d3d12.cpp +++ b/renderer/src/ore/d3d12/ore_pipeline_d3d12.cpp
@@ -2,8 +2,8 @@ * Copyright 2025 Rive */ -#include "rive/renderer/ore/ore_pipeline.hpp" -#include "rive/renderer/ore/ore_bind_group_layout.hpp" +#include "ore_pipeline_d3d12.hpp" +#include "ore_bind_group_layout_d3d12.hpp" #include "rive/renderer/ore/ore_context_d3d12.hpp" namespace rive::ore @@ -12,9 +12,9 @@ // --- Public method definitions (D3D12-only builds) --- // When both D3D11 and D3D12 are compiled, the combined // ore_context_d3d11_d3d12.cpp file provides these methods with dispatch. -#if defined(ORE_BACKEND_D3D12) && !defined(ORE_BACKEND_D3D11) +#if defined(ORE_BACKEND_D3D12) -void Pipeline::onRefCntReachedZero() const +void PipelineD3D12::onRefCntReachedZero() const { // Capture the context before `delete this` invalidates `m_d3dOreContext`. // In owned-CL mode d3dDeferDestroy runs the closure immediately, matching @@ -23,19 +23,21 @@ // D3D12 resource destroy) can't happen while the host's command list // still references the pipeline state object. ContextD3D12* ctx = m_d3dOreContext; - auto destroy = [p = const_cast<Pipeline*>(this)]() { delete p; }; + auto destroy = [p = const_cast<PipelineD3D12*>(this)]() { delete p; }; if (ctx != nullptr) ctx->d3dDeferDestroy(std::move(destroy)); else destroy(); } -void BindGroupLayout::onRefCntReachedZero() const +void BindGroupLayoutD3D12::onRefCntReachedZero() const { // Layout has no GPU handle on D3D12 (root sig owns the descriptor // table shape; it's per-pipeline). Just delete. ContextD3D12* ctx = static_cast<ContextD3D12*>(m_context); - auto destroy = [p = const_cast<BindGroupLayout*>(this)]() { delete p; }; + auto destroy = [p = const_cast<BindGroupLayoutD3D12*>(this)]() { + delete p; + }; if (ctx != nullptr) ctx->d3dDeferDestroy(std::move(destroy)); else
diff --git a/renderer/src/ore/d3d12/ore_pipeline_d3d12.hpp b/renderer/src/ore/d3d12/ore_pipeline_d3d12.hpp new file mode 100644 index 0000000..f47358c --- /dev/null +++ b/renderer/src/ore/d3d12/ore_pipeline_d3d12.hpp
@@ -0,0 +1,52 @@ +#pragma once +#include "rive/renderer/ore/ore_pipeline.hpp" +#include <d3d12.h> +#include <wrl/client.h> +#include <cstdint> + +namespace rive::ore +{ +class ContextD3D12; + +// Per-group descriptor-table shape for D3D12 root signatures. +// Populated by ContextD3D12::makeBindGroupLayout() via +// tallyGroupFromLayoutDesc() and copied into PipelineD3D12::m_d3dGroupParams by +// makePipeline(). +struct D3D12GroupRootParams +{ + uint8_t cbvCount = 0; + uint8_t srvCount = 0; + uint8_t uavCount = 0; + uint8_t samplerCount = 0; + uint8_t cbvBaseGlobalSlot = 0; + uint8_t srvBaseGlobalSlot = 0; + uint8_t uavBaseGlobalSlot = 0; + uint8_t samplerBaseGlobalSlot = 0; + // Root-parameter indices assigned at PSO build time (-1 = absent). + int8_t cbvSrvUavRootParamIdx = -1; + int8_t samplerRootParamIdx = -1; +}; + +class PipelineD3D12 : public LITE_RTTI_OVERRIDE(Pipeline, PipelineD3D12) +{ +public: + PipelineD3D12(const PipelineDesc& desc) : lite_rtti_override(desc) {} + ~PipelineD3D12() override = default; // ComPtrs released automatically + // Defers deletion until after GPU fence. + void onRefCntReachedZero() const override; + +private: + friend class ContextD3D12; + friend class RenderPassD3D12; + Microsoft::WRL::ComPtr<ID3D12PipelineState> m_d3dPSO; + Microsoft::WRL::ComPtr<ID3D12RootSignature> m_d3dRootSigOwned; + D3D12_PRIMITIVE_TOPOLOGY m_d3dTopology = D3D_PRIMITIVE_TOPOLOGY_UNDEFINED; + // Mirrored from BindGroupLayouts at makePipeline() time. + D3D12GroupRootParams m_d3dGroupParams[kMaxBindGroups]; + // Per-VB stride for setVertexBuffer(). + uint32_t m_d3dVertexStrides[8] = {}; + // Back-ref so onRefCntReachedZero() can route deletion through + // ContextD3D12::d3dDeferDestroy() in external-CL mode. Weak ref. + ContextD3D12* m_d3dOreContext = nullptr; +}; +} // namespace rive::ore
diff --git a/renderer/src/ore/d3d12/ore_render_pass_d3d11_d3d12.cpp b/renderer/src/ore/d3d12/ore_render_pass_d3d11_d3d12.cpp deleted file mode 100644 index 5bab608..0000000 --- a/renderer/src/ore/d3d12/ore_render_pass_d3d11_d3d12.cpp +++ /dev/null
@@ -1,697 +0,0 @@ -/* - * Copyright 2025 Rive - */ - -// Combined D3D11 + D3D12 RenderPass implementation for Windows. -// Compiled when both ORE_BACKEND_D3D11 and ORE_BACKEND_D3D12 are active. -// Provides all RenderPass method definitions with runtime dispatch: -// passes initialized via the D3D11 context path (m_d3d11Context != nullptr) -// use D3D11; passes initialized via the D3D12 context path -// (m_d3dCmdList != nullptr) use D3D12. - -#if defined(ORE_BACKEND_D3D11) && defined(ORE_BACKEND_D3D12) - -// Pull in D3D12 static helpers (none currently, but keeps the pattern). -#include "ore_render_pass_d3d12.cpp" - -// Pull in D3D11 static helpers (oreTopologyToD3D, oreIndexFormatToDXGI). -#include "../d3d11/ore_render_pass_d3d11.cpp" - -#include "rive/renderer/ore/ore_render_pass.hpp" -#include "rive/renderer/ore/ore_bind_group.hpp" -#include "rive/renderer/ore/ore_context_d3d11.hpp" -#include "rive/renderer/ore/ore_context_d3d12.hpp" -#include "rive/renderer/ore/ore_buffer.hpp" -#include "rive/renderer/ore/ore_texture.hpp" -#include "rive/renderer/ore/ore_sampler.hpp" -#include "rive/renderer/ore/ore_pipeline.hpp" -#include "rive/rive_types.hpp" -#include "ore_d3d12_bind_group_apply.hpp" - -namespace rive::ore -{ - -// ============================================================================ -// RenderPass — lifecycle -// ============================================================================ - -RenderPass::~RenderPass() -{ - if (!m_finished && (m_d3d11Context != nullptr || m_d3dCmdList != nullptr)) - finish(); -} - -RenderPass::RenderPass(RenderPass&& other) noexcept : - // D3D11 members - m_currentPipeline(std::move(other.m_currentPipeline)), - m_d3d11Context(other.m_d3d11Context), - m_d3d11Topology(other.m_d3d11Topology), - m_d3d11IndexFormat(other.m_d3d11IndexFormat), - m_d3d11IndexOffset(other.m_d3d11IndexOffset), - m_d3d11StencilRef(other.m_d3d11StencilRef), - m_d3d11ResolveCount(other.m_d3d11ResolveCount), - // D3D12 members - m_d3dCmdList(other.m_d3dCmdList), - m_d3dDevice(other.m_d3dDevice), - m_d3dContext(other.m_d3dContext), - m_d3dCurrentPipeline(std::move(other.m_d3dCurrentPipeline)), - m_d3dIndexFormat(other.m_d3dIndexFormat), - m_d3dIndexOffset(other.m_d3dIndexOffset), - m_d3dStencilRef(other.m_d3dStencilRef), - m_d3dColorCount(other.m_d3dColorCount), - m_d3dDepthResource(other.m_d3dDepthResource), - m_d3dDepthFinalState(other.m_d3dDepthFinalState) -{ - moveCrossBackendFieldsFrom(other); - // D3D11 arrays - m_d3d11BlendFactor[0] = other.m_d3d11BlendFactor[0]; - m_d3d11BlendFactor[1] = other.m_d3d11BlendFactor[1]; - m_d3d11BlendFactor[2] = other.m_d3d11BlendFactor[2]; - m_d3d11BlendFactor[3] = other.m_d3d11BlendFactor[3]; - for (uint32_t i = 0; i < m_d3d11ResolveCount; ++i) - m_d3d11Resolves[i] = other.m_d3d11Resolves[i]; - // D3D12 arrays - for (int i = 0; i < 8; ++i) - { - m_d3dPendingUBOs[i] = other.m_d3dPendingUBOs[i]; - m_d3dPendingSrvHandles[i] = other.m_d3dPendingSrvHandles[i]; - m_d3dPendingSamplerHandles[i] = other.m_d3dPendingSamplerHandles[i]; - } - for (int i = 0; i < 4; ++i) - { - m_d3dBlendFactor[i] = other.m_d3dBlendFactor[i]; - m_d3dColorResources[i] = other.m_d3dColorResources[i]; - m_d3dColorTextures[i] = other.m_d3dColorTextures[i]; - m_d3dColorFinalStates[i] = other.m_d3dColorFinalStates[i]; - m_d3dResolves[i] = other.m_d3dResolves[i]; - } - m_d3dDepthTexture = other.m_d3dDepthTexture; - m_d3dResolveCount = other.m_d3dResolveCount; - - other.m_d3d11Context = nullptr; - other.m_d3dCmdList = nullptr; - other.m_d3dDevice = nullptr; - other.m_d3dContext = nullptr; - other.m_d3dDepthResource = nullptr; - other.m_d3dDepthTexture = nullptr; - other.m_d3dColorCount = 0; - other.m_d3dResolveCount = 0; -} - -RenderPass& RenderPass::operator=(RenderPass&& other) noexcept -{ - if (this != &other) - { - if (!m_finished && - (m_d3d11Context != nullptr || m_d3dCmdList != nullptr)) - finish(); - - moveCrossBackendFieldsFrom(other); - // D3D11 - m_d3d11Context = other.m_d3d11Context; - m_currentPipeline = std::move(other.m_currentPipeline); - m_d3d11Topology = other.m_d3d11Topology; - m_d3d11IndexFormat = other.m_d3d11IndexFormat; - m_d3d11IndexOffset = other.m_d3d11IndexOffset; - m_d3d11StencilRef = other.m_d3d11StencilRef; - m_d3d11BlendFactor[0] = other.m_d3d11BlendFactor[0]; - m_d3d11BlendFactor[1] = other.m_d3d11BlendFactor[1]; - m_d3d11BlendFactor[2] = other.m_d3d11BlendFactor[2]; - m_d3d11BlendFactor[3] = other.m_d3d11BlendFactor[3]; - m_d3d11ResolveCount = other.m_d3d11ResolveCount; - for (uint32_t i = 0; i < m_d3d11ResolveCount; ++i) - m_d3d11Resolves[i] = other.m_d3d11Resolves[i]; - // D3D12 - m_d3dCmdList = other.m_d3dCmdList; - m_d3dDevice = other.m_d3dDevice; - m_d3dContext = other.m_d3dContext; - m_d3dCurrentPipeline = std::move(other.m_d3dCurrentPipeline); - m_d3dIndexFormat = other.m_d3dIndexFormat; - m_d3dIndexOffset = other.m_d3dIndexOffset; - m_d3dStencilRef = other.m_d3dStencilRef; - m_d3dColorCount = other.m_d3dColorCount; - m_d3dDepthResource = other.m_d3dDepthResource; - m_d3dDepthFinalState = other.m_d3dDepthFinalState; - for (int i = 0; i < 8; ++i) - { - m_d3dPendingUBOs[i] = other.m_d3dPendingUBOs[i]; - m_d3dPendingSrvHandles[i] = other.m_d3dPendingSrvHandles[i]; - m_d3dPendingSamplerHandles[i] = other.m_d3dPendingSamplerHandles[i]; - } - for (int i = 0; i < 4; ++i) - { - m_d3dBlendFactor[i] = other.m_d3dBlendFactor[i]; - m_d3dColorResources[i] = other.m_d3dColorResources[i]; - m_d3dColorTextures[i] = other.m_d3dColorTextures[i]; - m_d3dColorFinalStates[i] = other.m_d3dColorFinalStates[i]; - m_d3dResolves[i] = other.m_d3dResolves[i]; - } - m_d3dDepthTexture = other.m_d3dDepthTexture; - m_d3dResolveCount = other.m_d3dResolveCount; - - other.m_d3d11Context = nullptr; - other.m_d3dCmdList = nullptr; - other.m_d3dDevice = nullptr; - other.m_d3dContext = nullptr; - other.m_d3dDepthResource = nullptr; - other.m_d3dDepthTexture = nullptr; - other.m_d3dColorCount = 0; - other.m_d3dResolveCount = 0; - } - return *this; -} - -void RenderPass::validate() const -{ - assert(!m_finished && "RenderPass already finished"); - assert(m_d3d11Context != nullptr || m_d3dCmdList != nullptr); -} - -// ============================================================================ -// setPipeline -// ============================================================================ - -void RenderPass::setPipeline(Pipeline* pipeline) -{ - validate(); - if (!checkPipelineCompat(pipeline)) - return; - if (m_d3d11Context) - { - m_currentPipeline = ref_rcp(pipeline); - const auto& desc = pipeline->desc(); - - m_d3d11Context->VSSetShader(pipeline->m_d3dVS, nullptr, 0); - m_d3d11Context->PSSetShader(pipeline->m_d3dPS, nullptr, 0); - m_d3d11Context->IASetInputLayout(pipeline->m_d3dInputLayout.Get()); - - m_d3d11Topology = oreTopologyToD3D(desc.topology); - m_d3d11Context->IASetPrimitiveTopology(m_d3d11Topology); - - m_d3d11Context->RSSetState(pipeline->m_d3dRasterizer.Get()); - m_d3d11Context->OMSetDepthStencilState( - pipeline->m_d3dDepthStencil.Get(), - m_d3d11StencilRef); - m_d3d11Context->OMSetBlendState(pipeline->m_d3dBlend.Get(), - m_d3d11BlendFactor, - 0xFFFFFFFF); - return; - } - - // D3D12 path. - m_d3dCurrentPipeline = ref_rcp(pipeline); - m_d3dCmdList->SetPipelineState(pipeline->m_d3dPSO.Get()); - m_d3dCmdList->IASetPrimitiveTopology(pipeline->m_d3dTopology); - // Each pipeline owns its own root sig (RFC v5 §3.2.2); rebind on - // change. See ore_render_pass_d3d12.cpp for the matching block — - // both files must stay in sync on this logic. - ID3D12RootSignature* rootSig = pipeline->m_d3dRootSigOwned.Get(); - if (rootSig != m_d3dCurrentRootSig) - { - m_d3dCmdList->SetGraphicsRootSignature(rootSig); - m_d3dCurrentRootSig = rootSig; - } - m_d3dCmdList->OMSetStencilRef(m_d3dStencilRef); - m_d3dCmdList->OMSetBlendFactor(m_d3dBlendFactor); -} - -// ============================================================================ -// setVertexBuffer -// ============================================================================ - -void RenderPass::setVertexBuffer(uint32_t slot, Buffer* buffer, uint32_t offset) -{ - validate(); - if (m_d3d11Context) - { - UINT stride = (m_currentPipeline && - slot < m_currentPipeline->desc().vertexBufferCount) - ? m_currentPipeline->desc().vertexBuffers[slot].stride - : 0; - ID3D11Buffer* buf = buffer->m_d3d11Buffer.Get(); - UINT off = offset; - m_d3d11Context->IASetVertexBuffers(slot, 1, &buf, &stride, &off); - return; - } - - // D3D12 path. - assert(buffer->m_d3dBuffer != nullptr); - UINT stride = (m_d3dCurrentPipeline && - slot < m_d3dCurrentPipeline->desc().vertexBufferCount) - ? m_d3dCurrentPipeline->m_d3dVertexStrides[slot] - : 0; - D3D12_VERTEX_BUFFER_VIEW vbv = {}; - vbv.BufferLocation = buffer->m_d3dBuffer->GetGPUVirtualAddress() + offset; - vbv.SizeInBytes = buffer->m_size - offset; - vbv.StrideInBytes = stride; - m_d3dCmdList->IASetVertexBuffers(slot, 1, &vbv); -} - -// ============================================================================ -// setIndexBuffer -// ============================================================================ - -void RenderPass::setIndexBuffer(Buffer* buffer, - IndexFormat format, - uint32_t offset) -{ - validate(); - if (m_d3d11Context) - { - m_d3d11IndexFormat = oreIndexFormatToDXGI(format); - m_d3d11IndexOffset = offset; - m_d3d11Context->IASetIndexBuffer(buffer->m_d3d11Buffer.Get(), - m_d3d11IndexFormat, - offset); - return; - } - - // D3D12 path. - assert(buffer->m_d3dBuffer != nullptr); - m_d3dIndexFormat = (format == IndexFormat::uint32) ? DXGI_FORMAT_R32_UINT - : DXGI_FORMAT_R16_UINT; - m_d3dIndexOffset = offset; - D3D12_INDEX_BUFFER_VIEW ibv = {}; - ibv.BufferLocation = buffer->m_d3dBuffer->GetGPUVirtualAddress() + offset; - ibv.SizeInBytes = buffer->m_size - offset; - ibv.Format = m_d3dIndexFormat; - m_d3dCmdList->IASetIndexBuffer(&ibv); -} - -// ============================================================================ -// setBindGroup -// ============================================================================ - -void RenderPass::setBindGroup(uint32_t groupIndex, - BindGroup* bg, - const uint32_t* dynamicOffsets, - uint32_t dynamicOffsetCount) -{ - validate(); - assert(bg != nullptr); - m_boundGroups[groupIndex] = ref_rcp(bg); - - if (m_d3d11Context) - { - // m_d3d11UBOs is sorted by WGSL `@binding` ascending at - // makeBindGroup time, so `dynamicOffsets[i]` here pairs with - // the i-th dynamic UBO in BindGroupLayout-entry order. - uint32_t dynIdx = 0; - ID3D11DeviceContext1* ctx1 = - m_context - ? static_cast<ContextD3D11*>(m_context)->m_d3d11Context1.Get() - : nullptr; - for (const auto& ubo : bg->m_d3d11UBOs) - { - ID3D11Buffer* buf = ubo.buffer; - uint32_t offsetBytes = ubo.offset; - if (ubo.hasDynamicOffset && dynIdx < dynamicOffsetCount) - { - offsetBytes += dynamicOffsets[dynIdx]; - ++dynIdx; - } - // D3D11.1 spec: `NumConstants` must be a multiple of 16 - // (256 bytes), minimum 16. NVIDIA enforces strictly — - // passing 1 silently drops the offset and re-reads from - // buffer start. See sibling fix in - // `ore_render_pass_d3d11.cpp`. - const bool useOffsetPath = - (offsetBytes != 0 && ctx1 != nullptr && ubo.size != 0); - const UINT firstConstant = useOffsetPath ? (offsetBytes / 16) : 0; - const UINT numConstantsRaw = (ubo.size + 15) / 16; - const UINT numConstants = - useOffsetPath - ? (numConstantsRaw < 16 ? 16u - : ((numConstantsRaw + 15u) & ~15u)) - : 0; - // Per-stage emit: VS / PS register namespaces are independent - // on D3D11. Skip the stage whose slot is `kAbsent` so we don't - // clobber another resource's register. - if (ubo.vsSlot != BindingMap::kAbsent) - { - if (useOffsetPath) - ctx1->VSSetConstantBuffers1(ubo.vsSlot, - 1, - &buf, - &firstConstant, - &numConstants); - else - m_d3d11Context->VSSetConstantBuffers(ubo.vsSlot, 1, &buf); - } - if (ubo.psSlot != BindingMap::kAbsent) - { - if (useOffsetPath) - ctx1->PSSetConstantBuffers1(ubo.psSlot, - 1, - &buf, - &firstConstant, - &numConstants); - else - m_d3d11Context->PSSetConstantBuffers(ubo.psSlot, 1, &buf); - } - } - for (const auto& tex : bg->m_d3d11Textures) - { - if (tex.vsSlot != BindingMap::kAbsent) - m_d3d11Context->VSSetShaderResources(tex.vsSlot, 1, &tex.srv); - if (tex.psSlot != BindingMap::kAbsent) - m_d3d11Context->PSSetShaderResources(tex.psSlot, 1, &tex.srv); - } - for (const auto& samp : bg->m_d3d11Samplers) - { - if (samp.vsSlot != BindingMap::kAbsent) - m_d3d11Context->VSSetSamplers(samp.vsSlot, 1, &samp.sampler); - if (samp.psSlot != BindingMap::kAbsent) - m_d3d11Context->PSSetSamplers(samp.psSlot, 1, &samp.sampler); - } - return; - } - - // D3D12 path. Shared body lives in ore_d3d12_bind_group_apply.hpp so - // the D3D12-only file (ore_render_pass_d3d12.cpp) and this combined - // file call the same implementation. - d3d12ApplyBindGroup(groupIndex, bg, dynamicOffsets, dynamicOffsetCount); -} - -// ============================================================================ -// setViewport / setScissorRect -// ============================================================================ - -void RenderPass::setViewport(float x, - float y, - float width, - float height, - float minDepth, - float maxDepth) -{ - validate(); - if (m_d3d11Context) - { - D3D11_VIEWPORT vp{}; - vp.TopLeftX = x; - vp.TopLeftY = y; - vp.Width = width; - vp.Height = height; - vp.MinDepth = minDepth; - vp.MaxDepth = maxDepth; - m_d3d11Context->RSSetViewports(1, &vp); - D3D11_RECT scissor{}; - scissor.left = static_cast<LONG>(x); - scissor.top = static_cast<LONG>(y); - scissor.right = static_cast<LONG>(x + width); - scissor.bottom = static_cast<LONG>(y + height); - m_d3d11Context->RSSetScissorRects(1, &scissor); - return; - } - - // D3D12 path. - D3D12_VIEWPORT vp = {x, y, width, height, minDepth, maxDepth}; - m_d3dCmdList->RSSetViewports(1, &vp); - D3D12_RECT scissor = {(LONG)x, - (LONG)y, - (LONG)(x + width), - (LONG)(y + height)}; - m_d3dCmdList->RSSetScissorRects(1, &scissor); -} - -void RenderPass::setScissorRect(uint32_t x, - uint32_t y, - uint32_t width, - uint32_t height) -{ - validate(); - if (m_d3d11Context) - { - D3D11_RECT rect{}; - rect.left = static_cast<LONG>(x); - rect.top = static_cast<LONG>(y); - rect.right = static_cast<LONG>(x + width); - rect.bottom = static_cast<LONG>(y + height); - m_d3d11Context->RSSetScissorRects(1, &rect); - return; - } - - // D3D12 path. - D3D12_RECT rect = {(LONG)x, (LONG)y, (LONG)(x + width), (LONG)(y + height)}; - m_d3dCmdList->RSSetScissorRects(1, &rect); -} - -// ============================================================================ -// setStencilReference / setBlendColor -// ============================================================================ - -void RenderPass::setStencilReference(uint32_t ref) -{ - validate(); - if (m_d3d11Context) - { - m_d3d11StencilRef = ref; - if (m_currentPipeline) - { - m_d3d11Context->OMSetDepthStencilState( - m_currentPipeline->m_d3dDepthStencil.Get(), - ref); - } - return; - } - - // D3D12 path. - m_d3dStencilRef = ref; - m_d3dCmdList->OMSetStencilRef(ref); -} - -void RenderPass::setBlendColor(float r, float g, float b, float a) -{ - validate(); - if (m_d3d11Context) - { - m_d3d11BlendFactor[0] = r; - m_d3d11BlendFactor[1] = g; - m_d3d11BlendFactor[2] = b; - m_d3d11BlendFactor[3] = a; - if (m_currentPipeline) - { - m_d3d11Context->OMSetBlendState(m_currentPipeline->m_d3dBlend.Get(), - m_d3d11BlendFactor, - 0xFFFFFFFF); - } - return; - } - - // D3D12 path. - m_d3dBlendFactor[0] = r; - m_d3dBlendFactor[1] = g; - m_d3dBlendFactor[2] = b; - m_d3dBlendFactor[3] = a; - m_d3dCmdList->OMSetBlendFactor(m_d3dBlendFactor); -} - -// ============================================================================ -// draw / drawIndexed -// ============================================================================ - -void RenderPass::draw(uint32_t vertexCount, - uint32_t instanceCount, - uint32_t firstVertex, - uint32_t firstInstance) -{ - validate(); - if (m_d3d11Context) - { - if (instanceCount > 1 || firstInstance != 0) - { - m_d3d11Context->DrawInstanced(vertexCount, - instanceCount, - firstVertex, - firstInstance); - } - else - { - m_d3d11Context->Draw(vertexCount, firstVertex); - } - return; - } - - // D3D12 path. - m_d3dCmdList->DrawInstanced(vertexCount, - instanceCount, - firstVertex, - firstInstance); -} - -void RenderPass::drawIndexed(uint32_t indexCount, - uint32_t instanceCount, - uint32_t firstIndex, - int32_t baseVertex, - uint32_t firstInstance) -{ - validate(); - if (m_d3d11Context) - { - if (instanceCount > 1 || firstInstance != 0 || baseVertex != 0) - { - m_d3d11Context->DrawIndexedInstanced(indexCount, - instanceCount, - firstIndex, - baseVertex, - firstInstance); - } - else - { - m_d3d11Context->DrawIndexed(indexCount, firstIndex, 0); - } - return; - } - - // D3D12 path. - m_d3dCmdList->DrawIndexedInstanced(indexCount, - instanceCount, - firstIndex, - baseVertex, - firstInstance); -} - -// ============================================================================ -// finish -// ============================================================================ - -void RenderPass::finish() -{ - if (m_finished) - return; - m_finished = true; - - if (m_d3d11Context != nullptr) - { - // Unbind render targets so attached textures can be used as SRVs. - m_d3d11Context->OMSetRenderTargets(0, nullptr, nullptr); - - // Resolve MSAA render targets to their 1x resolve targets. - for (uint32_t i = 0; i < m_d3d11ResolveCount; ++i) - { - const auto& r = m_d3d11Resolves[i]; - m_d3d11Context->ResolveSubresource(r.resolve, - r.resolveSubresource, - r.msaa, - r.msaaSubresource, - r.format); - } - - m_d3d11Context = nullptr; - return; - } - - if (m_d3dCmdList == nullptr) - return; - - // MSAA resolve (D3D12 path). Mirrors ore_render_pass_d3d12.cpp. - if (m_d3dResolveCount > 0) - { - D3D12_RESOURCE_BARRIER pre[8] = {}; - uint32_t preCount = 0; - for (uint32_t i = 0; i < m_d3dResolveCount; ++i) - { - const auto& r = m_d3dResolves[i]; - pre[preCount].Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; - pre[preCount].Transition.pResource = r.msaa; - pre[preCount].Transition.StateBefore = - D3D12_RESOURCE_STATE_RENDER_TARGET; - pre[preCount].Transition.StateAfter = - D3D12_RESOURCE_STATE_RESOLVE_SOURCE; - pre[preCount].Transition.Subresource = r.msaaSubresource; - ++preCount; - - pre[preCount].Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; - pre[preCount].Transition.pResource = r.resolve; - pre[preCount].Transition.StateBefore = r.resolvePriorState; - pre[preCount].Transition.StateAfter = - D3D12_RESOURCE_STATE_RESOLVE_DEST; - pre[preCount].Transition.Subresource = r.resolveSubresource; - ++preCount; - } - m_d3dCmdList->ResourceBarrier(preCount, pre); - - for (uint32_t i = 0; i < m_d3dResolveCount; ++i) - { - const auto& r = m_d3dResolves[i]; - m_d3dCmdList->ResolveSubresource(r.resolve, - r.resolveSubresource, - r.msaa, - r.msaaSubresource, - r.format); - } - - D3D12_RESOURCE_BARRIER post[4] = {}; - uint32_t postCount = 0; - for (uint32_t i = 0; i < m_d3dResolveCount; ++i) - { - const auto& r = m_d3dResolves[i]; - post[postCount].Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; - post[postCount].Transition.pResource = r.resolve; - post[postCount].Transition.StateBefore = - D3D12_RESOURCE_STATE_RESOLVE_DEST; - post[postCount].Transition.StateAfter = r.resolveFinalState; - post[postCount].Transition.Subresource = r.resolveSubresource; - ++postCount; - // Keep the resolve target's tracked state in sync. - if (r.resolveTex != nullptr) - r.resolveTex->m_d3dCurrentState = r.resolveFinalState; - } - if (postCount > 0) - m_d3dCmdList->ResourceBarrier(postCount, post); - } - - // Transition colour attachments back to their post-pass state. MSAA - // srcs that were resolved are now in RESOLVE_SOURCE; others RENDER_TARGET. - for (uint32_t i = 0; i < m_d3dColorCount; ++i) - { - if (!m_d3dColorResources[i]) - continue; - - D3D12_RESOURCE_STATES stateBefore = D3D12_RESOURCE_STATE_RENDER_TARGET; - for (uint32_t r = 0; r < m_d3dResolveCount; ++r) - { - if (m_d3dResolves[r].msaa == m_d3dColorResources[i]) - { - stateBefore = D3D12_RESOURCE_STATE_RESOLVE_SOURCE; - break; - } - } - - D3D12_RESOURCE_BARRIER barrier = {}; - barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; - barrier.Transition.pResource = m_d3dColorResources[i]; - barrier.Transition.StateBefore = stateBefore; - barrier.Transition.StateAfter = m_d3dColorFinalStates[i]; - barrier.Transition.Subresource = - D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES; - m_d3dCmdList->ResourceBarrier(1, &barrier); - - if (m_d3dColorTextures[i] != nullptr) - m_d3dColorTextures[i]->m_d3dCurrentState = m_d3dColorFinalStates[i]; - } - - // Transition depth/stencil if present. - if (m_d3dDepthResource) - { - D3D12_RESOURCE_BARRIER barrier = {}; - barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; - barrier.Transition.pResource = m_d3dDepthResource; - barrier.Transition.StateBefore = D3D12_RESOURCE_STATE_DEPTH_WRITE; - barrier.Transition.StateAfter = m_d3dDepthFinalState; - barrier.Transition.Subresource = - D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES; - m_d3dCmdList->ResourceBarrier(1, &barrier); - - if (m_d3dDepthTexture != nullptr) - m_d3dDepthTexture->m_d3dCurrentState = m_d3dDepthFinalState; - } - - m_d3dCmdList = nullptr; - m_d3dDevice = nullptr; - m_d3dContext = nullptr; -} - -} // namespace rive::ore - -#endif // ORE_BACKEND_D3D11 && ORE_BACKEND_D3D12
diff --git a/renderer/src/ore/d3d12/ore_render_pass_d3d12.cpp b/renderer/src/ore/d3d12/ore_render_pass_d3d12.cpp index d3422c7..829b6c3 100644 --- a/renderer/src/ore/d3d12/ore_render_pass_d3d12.cpp +++ b/renderer/src/ore/d3d12/ore_render_pass_d3d12.cpp
@@ -2,7 +2,7 @@ * Copyright 2025 Rive */ -#include "rive/renderer/ore/ore_render_pass.hpp" +#include "ore_render_pass_d3d12.hpp" #include "rive/renderer/ore/ore_bind_group.hpp" #include "rive/renderer/ore/ore_context_d3d12.hpp" #include "rive/renderer/ore/ore_buffer.hpp" @@ -15,26 +15,22 @@ #include <d3d12.h> #include <cassert> #include <cstring> +#include "ore_buffer_d3d12.hpp" namespace rive::ore { -// --- Public method definitions (D3D12-only builds) --- -// When both D3D11 and D3D12 are compiled, the combined -// ore_context_d3d11_d3d12.cpp file provides these methods with dispatch. -#if defined(ORE_BACKEND_D3D12) && !defined(ORE_BACKEND_D3D11) - // ============================================================================ // RenderPass — lifecycle // ============================================================================ -RenderPass::~RenderPass() +RenderPassD3D12::~RenderPassD3D12() { if (!m_finished && m_d3dCmdList != nullptr) finish(); } -RenderPass::RenderPass(RenderPass&& other) noexcept +RenderPassD3D12::RenderPassD3D12(RenderPassD3D12&& other) noexcept #if defined(ORE_BACKEND_D3D12) : m_d3dCmdList(other.m_d3dCmdList), @@ -49,7 +45,6 @@ m_d3dDepthFinalState(other.m_d3dDepthFinalState) #endif { - moveCrossBackendFieldsFrom(other); #if defined(ORE_BACKEND_D3D12) for (int i = 0; i < 8; ++i) { @@ -77,13 +72,12 @@ #endif } -RenderPass& RenderPass::operator=(RenderPass&& other) noexcept +RenderPassD3D12& RenderPassD3D12::operator=(RenderPassD3D12&& other) noexcept { if (this != &other) { if (!m_finished && m_d3dCmdList != nullptr) finish(); - moveCrossBackendFieldsFrom(other); #if defined(ORE_BACKEND_D3D12) m_d3dCmdList = other.m_d3dCmdList; m_d3dDevice = other.m_d3dDevice; @@ -123,7 +117,7 @@ return *this; } -void RenderPass::validate() const +void RenderPassD3D12::validate() const { assert(!m_finished && "RenderPass already finished"); #if defined(ORE_BACKEND_D3D12) @@ -135,10 +129,11 @@ // setPipeline // ============================================================================ -void RenderPass::setPipeline(Pipeline* pipeline) +void RenderPassD3D12::setPipeline(Pipeline* inPipeline) { #if defined(ORE_BACKEND_D3D12) validate(); + auto pipeline = lite_rtti_cast<PipelineD3D12*>(inPipeline); if (!checkPipelineCompat(pipeline)) return; m_d3dCurrentPipeline = ref_rcp(pipeline); @@ -167,10 +162,13 @@ // setVertexBuffer // ============================================================================ -void RenderPass::setVertexBuffer(uint32_t slot, Buffer* buffer, uint32_t offset) +void RenderPassD3D12::setVertexBuffer(uint32_t slot, + Buffer* inBuffer, + uint32_t offset) { #if defined(ORE_BACKEND_D3D12) validate(); + auto buffer = lite_rtti_cast<BufferD3D12*>(inBuffer); assert(buffer->m_d3dBuffer != nullptr); UINT stride = (m_d3dCurrentPipeline && @@ -194,12 +192,13 @@ // setIndexBuffer // ============================================================================ -void RenderPass::setIndexBuffer(Buffer* buffer, - IndexFormat format, - uint32_t offset) +void RenderPassD3D12::setIndexBuffer(Buffer* inBuffer, + IndexFormat format, + uint32_t offset) { #if defined(ORE_BACKEND_D3D12) validate(); + auto buffer = lite_rtti_cast<BufferD3D12*>(inBuffer); assert(buffer->m_d3dBuffer != nullptr); m_d3dIndexFormat = (format == IndexFormat::uint32) ? DXGI_FORMAT_R32_UINT @@ -218,13 +217,14 @@ #endif } -void RenderPass::setBindGroup(uint32_t groupIndex, - BindGroup* bg, - const uint32_t* dynamicOffsets, - uint32_t dynamicOffsetCount) +void RenderPassD3D12::setBindGroup(uint32_t groupIndex, + BindGroup* inBg, + const uint32_t* dynamicOffsets, + uint32_t dynamicOffsetCount) { #if defined(ORE_BACKEND_D3D12) validate(); + auto bg = lite_rtti_cast<BindGroupD3D12*>(inBg); assert(bg != nullptr); // Hold a strong reference so the BindGroup stays alive until finish(). m_boundGroups[groupIndex] = ref_rcp(bg); @@ -241,12 +241,12 @@ // setViewport / setScissorRect // ============================================================================ -void RenderPass::setViewport(float x, - float y, - float width, - float height, - float minDepth, - float maxDepth) +void RenderPassD3D12::setViewport(float x, + float y, + float width, + float height, + float minDepth, + float maxDepth) { #if defined(ORE_BACKEND_D3D12) validate(); @@ -269,10 +269,10 @@ #endif } -void RenderPass::setScissorRect(uint32_t x, - uint32_t y, - uint32_t width, - uint32_t height) +void RenderPassD3D12::setScissorRect(uint32_t x, + uint32_t y, + uint32_t width, + uint32_t height) { #if defined(ORE_BACKEND_D3D12) validate(); @@ -290,7 +290,7 @@ // setStencilReference / setBlendColor // ============================================================================ -void RenderPass::setStencilReference(uint32_t ref) +void RenderPassD3D12::setStencilReference(uint32_t ref) { #if defined(ORE_BACKEND_D3D12) validate(); @@ -301,7 +301,7 @@ #endif } -void RenderPass::setBlendColor(float r, float g, float b, float a) +void RenderPassD3D12::setBlendColor(float r, float g, float b, float a) { #if defined(ORE_BACKEND_D3D12) validate(); @@ -322,10 +322,10 @@ // draw / drawIndexed // ============================================================================ -void RenderPass::draw(uint32_t vertexCount, - uint32_t instanceCount, - uint32_t firstVertex, - uint32_t firstInstance) +void RenderPassD3D12::draw(uint32_t vertexCount, + uint32_t instanceCount, + uint32_t firstVertex, + uint32_t firstInstance) { #if defined(ORE_BACKEND_D3D12) validate(); @@ -341,11 +341,11 @@ #endif } -void RenderPass::drawIndexed(uint32_t indexCount, - uint32_t instanceCount, - uint32_t firstIndex, - int32_t baseVertex, - uint32_t firstInstance) +void RenderPassD3D12::drawIndexed(uint32_t indexCount, + uint32_t instanceCount, + uint32_t firstIndex, + int32_t baseVertex, + uint32_t firstInstance) { #if defined(ORE_BACKEND_D3D12) validate(); @@ -367,7 +367,7 @@ // finish // ============================================================================ -void RenderPass::finish() +void RenderPassD3D12::finish() { if (m_finished) return; @@ -503,7 +503,4 @@ m_d3dContext = nullptr; #endif } - -#endif // D3D12-only - } // namespace rive::ore
diff --git a/renderer/src/ore/d3d12/ore_render_pass_d3d12.hpp b/renderer/src/ore/d3d12/ore_render_pass_d3d12.hpp new file mode 100644 index 0000000..f4f59cc --- /dev/null +++ b/renderer/src/ore/d3d12/ore_render_pass_d3d12.hpp
@@ -0,0 +1,136 @@ +#pragma once +#include "rive/renderer/ore/ore_render_pass.hpp" +#include "rive/renderer/ore/ore_context_d3d12.hpp" + +#include <d3d12.h> +#include <wrl/client.h> + +namespace rive::ore +{ +class PipelineD3D12; +class RenderPassD3D12 : public RenderPass +{ +public: + void setPipeline(Pipeline* pipeline) override; + + void setVertexBuffer(uint32_t slot, + Buffer* buffer, + uint32_t offset = 0) override; + void setIndexBuffer(Buffer* buffer, + IndexFormat format, + uint32_t offset = 0) override; + + // Bind a pre-created BindGroup, optionally overriding dynamic UBO offsets. + // Dynamic-ness is declared on the pipeline (`PipelineDesc::dynamicUBOs`) + // and cached per-slot on the BindGroup at creation. + // dynamicOffsets: one uint32 per dynamic UBO in this group, in the order + // they appear in `BindGroupDesc::ubos` (matches WebGPU semantics when + // the caller lists UBOs in ascending-slot order, the typical pattern). + void setBindGroup(uint32_t groupIndex, + BindGroup* bg, + const uint32_t* dynamicOffsets = nullptr, + uint32_t dynamicOffsetCount = 0) override; + + void setViewport(float x, + float y, + float width, + float height, + float minDepth = 0.0f, + float maxDepth = 1.0f) override; + void setScissorRect(uint32_t x, + uint32_t y, + uint32_t width, + uint32_t height) override; + + void setStencilReference(uint32_t ref) override; + void setBlendColor(float r, float g, float b, float a) override; + + void draw(uint32_t vertexCount, + uint32_t instanceCount = 1, + uint32_t firstVertex = 0, + uint32_t firstInstance = 0) override; + + void drawIndexed(uint32_t indexCount, + uint32_t instanceCount = 1, + uint32_t firstIndex = 0, + int32_t baseVertex = 0, + uint32_t firstInstance = 0) override; + + void validate() const override; + + void finish() override; + + RenderPassD3D12(RenderPassD3D12&& other) noexcept; + RenderPassD3D12& operator=(RenderPassD3D12&&) noexcept; + RenderPassD3D12(ContextD3D12* context) : RenderPass(context) {} + ~RenderPassD3D12() override; + +private: + // D3D12 setBindGroup body — shared between the D3D12-only translation + // unit (ore_render_pass_d3d12.cpp) and the combined D3D11+D3D12 one + // (ore_render_pass_d3d11_d3d12.cpp). Defined inline in + // ore_d3d12_bind_group_apply.hpp, which both .cpp files include. + inline void d3d12ApplyBindGroup(uint32_t groupIndex, + BindGroupD3D12* bg, + const uint32_t* dynamicOffsets, + uint32_t dynamicOffsetCount); + + ID3D12GraphicsCommandList* m_d3dCmdList = + nullptr; // Weak ref (owned by Context). + ID3D12Device* m_d3dDevice = nullptr; // Weak ref. + ContextD3D12* m_d3dContext = nullptr; // Weak ref. + // Strong ref — same Lua-GC reasoning as the cross-backend + // `m_currentPipeline` above. The D3D12-only field exists because + // D3D12's setPipeline path is split between this TU and the + // d3d11+d3d12 combined TU; both share this storage. + rcp<PipelineD3D12> m_d3dCurrentPipeline; + // Root signature currently bound on the command list. Compared against + // each new pipeline's `m_d3dRootSigOwned` in `setPipeline` so we only + // call `SetGraphicsRootSignature` when the sig actually changes (each + // Ore D3D12 pipeline owns its own per-pipeline root sig — RFC v5 + // §3.2.2). Weak ref; freed by the owning Pipeline. + ID3D12RootSignature* m_d3dCurrentRootSig = nullptr; + // Pending descriptor state (accumulated per setPipeline/setBindGroup). + D3D12_GPU_VIRTUAL_ADDRESS m_d3dPendingUBOs[8] = {}; + D3D12_CPU_DESCRIPTOR_HANDLE m_d3dPendingSrvHandles[8] = {}; + D3D12_CPU_DESCRIPTOR_HANDLE m_d3dPendingSamplerHandles[8] = {}; + DXGI_FORMAT m_d3dIndexFormat = DXGI_FORMAT_R16_UINT; + uint32_t m_d3dIndexOffset = 0; + uint32_t m_d3dStencilRef = 0; + float m_d3dBlendFactor[4] = {}; + // Color attachment resources for barrier in finish() (RT → final). + // Parallel arrays: m_d3dColorTextures provides the Ore Texture back-ref so + // finish() can keep Texture::m_d3dCurrentState in sync with the actual + // resource state after the end-of-pass transition. + ID3D12Resource* m_d3dColorResources[4] = {}; + TextureD3D12* m_d3dColorTextures[4] = {}; + D3D12_RESOURCE_STATES m_d3dColorFinalStates[4] = {}; + uint32_t m_d3dColorCount = 0; + ID3D12Resource* m_d3dDepthResource = nullptr; + TextureD3D12* m_d3dDepthTexture = nullptr; + D3D12_RESOURCE_STATES m_d3dDepthFinalState = D3D12_RESOURCE_STATE_COMMON; + // MSAA resolve pairs (populated at beginRenderPass, executed in finish). + // D3D12 subresource index is mipLevel + arraySlice * mipCount for the + // common single-plane case. + struct D3D12ResolveEntry + { + ID3D12Resource* msaa = nullptr; + ID3D12Resource* resolve = nullptr; + // Back-ref to the resolve target's Ore Texture so finish() can update + // Texture::m_d3dCurrentState after the resolve barrier chain. + TextureD3D12* resolveTex = nullptr; + DXGI_FORMAT format = DXGI_FORMAT_UNKNOWN; + uint32_t msaaSubresource = 0; + uint32_t resolveSubresource = 0; + // Resolve target's prior state, to restore after resolve. + D3D12_RESOURCE_STATES resolvePriorState = D3D12_RESOURCE_STATE_COMMON; + // Resolve target's final state (what finish() should leave it in). + D3D12_RESOURCE_STATES resolveFinalState = + D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE; + }; + D3D12ResolveEntry m_d3dResolves[4] = {}; + uint32_t m_d3dResolveCount = 0; + friend class ContextD3D12; +}; + +} // namespace rive::ore \ No newline at end of file
diff --git a/renderer/src/ore/d3d12/ore_sampler_d3d11_d3d12.cpp b/renderer/src/ore/d3d12/ore_sampler_d3d11_d3d12.cpp deleted file mode 100644 index 29bce96..0000000 --- a/renderer/src/ore/d3d12/ore_sampler_d3d11_d3d12.cpp +++ /dev/null
@@ -1,31 +0,0 @@ -/* - * Copyright 2025 Rive - */ - -// Combined D3D11 + D3D12 Sampler implementation for Windows. -// Compiled when both ORE_BACKEND_D3D11 and ORE_BACKEND_D3D12 are active. - -#if defined(ORE_BACKEND_D3D11) && defined(ORE_BACKEND_D3D12) - -#include "rive/renderer/ore/ore_sampler.hpp" -#include "rive/renderer/ore/ore_context_d3d12.hpp" - -namespace rive::ore -{ - -void Sampler::onRefCntReachedZero() const -{ - // m_d3dOreContext is only set on D3D12-backed samplers (see - // d3d12MakeSampler). D3D11-backed samplers keep the immediate-delete - // path unchanged. - ContextD3D12* ctx = m_d3dOreContext; - auto destroy = [p = const_cast<Sampler*>(this)]() { delete p; }; - if (ctx != nullptr) - ctx->d3dDeferDestroy(std::move(destroy)); - else - destroy(); -} - -} // namespace rive::ore - -#endif // ORE_BACKEND_D3D11 && ORE_BACKEND_D3D12
diff --git a/renderer/src/ore/d3d12/ore_sampler_d3d12.cpp b/renderer/src/ore/d3d12/ore_sampler_d3d12.cpp index 662f343..f412d10 100644 --- a/renderer/src/ore/d3d12/ore_sampler_d3d12.cpp +++ b/renderer/src/ore/d3d12/ore_sampler_d3d12.cpp
@@ -2,7 +2,7 @@ * Copyright 2025 Rive */ -#include "rive/renderer/ore/ore_sampler.hpp" +#include "ore_sampler_d3d12.hpp" #include "rive/renderer/ore/ore_context_d3d12.hpp" namespace rive::ore @@ -11,12 +11,12 @@ // --- Public method definitions (D3D12-only builds) --- // When both D3D11 and D3D12 are compiled, the combined // ore_context_d3d11_d3d12.cpp file provides these methods with dispatch. -#if defined(ORE_BACKEND_D3D12) && !defined(ORE_BACKEND_D3D11) +#if defined(ORE_BACKEND_D3D12) -void Sampler::onRefCntReachedZero() const +void SamplerD3D12::onRefCntReachedZero() const { ContextD3D12* ctx = m_d3dOreContext; - auto destroy = [p = const_cast<Sampler*>(this)]() { delete p; }; + auto destroy = [p = const_cast<SamplerD3D12*>(this)]() { delete p; }; if (ctx != nullptr) ctx->d3dDeferDestroy(std::move(destroy)); else
diff --git a/renderer/src/ore/d3d12/ore_sampler_d3d12.hpp b/renderer/src/ore/d3d12/ore_sampler_d3d12.hpp new file mode 100644 index 0000000..6c9152e --- /dev/null +++ b/renderer/src/ore/d3d12/ore_sampler_d3d12.hpp
@@ -0,0 +1,24 @@ +#pragma once +#include "rive/renderer/ore/ore_sampler.hpp" +#include <d3d12.h> + +namespace rive::ore +{ +class ContextD3D12; + +class SamplerD3D12 : public LITE_RTTI_OVERRIDE(Sampler, SamplerD3D12) +{ +public: + SamplerD3D12() = default; + ~SamplerD3D12() override = default; + // Defers the entire CPU object deletion until after GPU fence. + void onRefCntReachedZero() const override; + +private: + friend class ContextD3D12; + D3D12_CPU_DESCRIPTOR_HANDLE m_d3dSamplerHandle = {}; + // Back-ref so onRefCntReachedZero() can route deletion through + // ContextD3D12::d3dDeferDestroy() in external-CL mode. Weak ref. + ContextD3D12* m_d3dOreContext = nullptr; +}; +} // namespace rive::ore
diff --git a/renderer/src/ore/d3d12/ore_shader_module_d3d11_d3d12.cpp b/renderer/src/ore/d3d12/ore_shader_module_d3d11_d3d12.cpp deleted file mode 100644 index 539dad8..0000000 --- a/renderer/src/ore/d3d12/ore_shader_module_d3d11_d3d12.cpp +++ /dev/null
@@ -1,19 +0,0 @@ -/* - * Copyright 2025 Rive - */ - -// Combined D3D11 + D3D12 ShaderModule implementation for Windows. -// Compiled when both ORE_BACKEND_D3D11 and ORE_BACKEND_D3D12 are active. - -#if defined(ORE_BACKEND_D3D11) && defined(ORE_BACKEND_D3D12) - -#include "rive/renderer/ore/ore_shader_module.hpp" - -namespace rive::ore -{ - -void ShaderModule::onRefCntReachedZero() const { delete this; } - -} // namespace rive::ore - -#endif // ORE_BACKEND_D3D11 && ORE_BACKEND_D3D12
diff --git a/renderer/src/ore/d3d12/ore_shader_module_d3d12.cpp b/renderer/src/ore/d3d12/ore_shader_module_d3d12.cpp index 74ddc81..912a70f 100644 --- a/renderer/src/ore/d3d12/ore_shader_module_d3d12.cpp +++ b/renderer/src/ore/d3d12/ore_shader_module_d3d12.cpp
@@ -2,18 +2,4 @@ * Copyright 2025 Rive */ -#include "rive/renderer/ore/ore_shader_module.hpp" - -namespace rive::ore -{ - -// --- Public method definitions (D3D12-only builds) --- -// When both D3D11 and D3D12 are compiled, the combined -// ore_context_d3d11_d3d12.cpp file provides these methods with dispatch. -#if defined(ORE_BACKEND_D3D12) && !defined(ORE_BACKEND_D3D11) - -void ShaderModule::onRefCntReachedZero() const { delete this; } - -#endif // D3D12-only - -} // namespace rive::ore +#include "ore_shader_module_d3d12.hpp"
diff --git a/renderer/src/ore/d3d12/ore_shader_module_d3d12.hpp b/renderer/src/ore/d3d12/ore_shader_module_d3d12.hpp new file mode 100644 index 0000000..5b03982 --- /dev/null +++ b/renderer/src/ore/d3d12/ore_shader_module_d3d12.hpp
@@ -0,0 +1,22 @@ +#pragma once +#include "rive/renderer/ore/ore_shader_module.hpp" +#include <cstdint> +#include <vector> + +namespace rive::ore +{ +class ContextD3D12; + +class ShaderModuleD3D12 + : public LITE_RTTI_OVERRIDE(ShaderModule, ShaderModuleD3D12) +{ +public: + ShaderModuleD3D12() = default; + ~ShaderModuleD3D12() override = default; + +private: + friend class ContextD3D12; + std::vector<uint8_t> m_d3dBytecode; + bool m_d3dIsVertex = false; +}; +} // namespace rive::ore
diff --git a/renderer/src/ore/d3d12/ore_texture_d3d11_d3d12.cpp b/renderer/src/ore/d3d12/ore_texture_d3d11_d3d12.cpp deleted file mode 100644 index 04727c8..0000000 --- a/renderer/src/ore/d3d12/ore_texture_d3d11_d3d12.cpp +++ /dev/null
@@ -1,218 +0,0 @@ -/* - * Copyright 2025 Rive - */ - -// Combined D3D11 + D3D12 Texture implementation for Windows. -// Compiled when both ORE_BACKEND_D3D11 and ORE_BACKEND_D3D12 are active. - -#if defined(ORE_BACKEND_D3D11) && defined(ORE_BACKEND_D3D12) - -#include "rive/renderer/ore/ore_texture.hpp" -#include "rive/renderer/ore/ore_context_d3d12.hpp" -#include "rive/rive_types.hpp" - -#include <d3d11.h> -#include <d3d12.h> -#include <wrl/client.h> -#include <cassert> -#include <cstring> - -using Microsoft::WRL::ComPtr; - -namespace rive::ore -{ - -void Texture::upload(const TextureDataDesc& data) -{ - assert(data.data != nullptr); - - if (m_d3d11Texture) - { - // D3D11 path — UpdateSubresource. - assert(m_d3d11Context != nullptr); - - UINT subresource = - D3D11CalcSubresource(data.mipLevel, data.layer, m_numMipmaps); - - D3D11_BOX box{}; - box.left = data.x; - box.top = data.y; - box.front = data.z; - box.right = data.x + data.width; - box.bottom = data.y + data.height; - box.back = data.z + data.depth; - - m_d3d11Context->UpdateSubresource(m_d3d11Texture.Get(), - subresource, - &box, - data.data, - data.bytesPerRow, - data.bytesPerRow * data.rowsPerImage); - } - else - { - // D3D12 path — staging upload buffer + copy command. - assert(m_d3dTexture != nullptr); - assert(m_d3dDevice != nullptr); - assert(m_d3dOreContext != nullptr); - assert(!m_d3dIsExternal && - "Cannot upload into an external (canvas-wrapped) texture"); - - ContextD3D12* ctx = m_d3dOreContext; - - // Open the upload command list if not already recording. - if (!ctx->m_d3dUploadListOpen) - { - ctx->m_d3dUploadAllocator->Reset(); - ctx->m_d3dUploadCmdList->Reset(ctx->m_d3dUploadAllocator.Get(), - nullptr); - ctx->m_d3dUploadListOpen = true; - } - - // Compute the placed footprint for the requested subresource. - // D3D12 subresource index = `mipSlice + arraySlice * MipLevels` - // (see D3D12CalcSubresource). See sibling fix in - // ore_texture_d3d12.cpp. - D3D12_RESOURCE_DESC texDesc = m_d3dTexture->GetDesc(); - UINT subresource = - data.mipLevel + data.layer * static_cast<UINT>(texDesc.MipLevels); - - D3D12_PLACED_SUBRESOURCE_FOOTPRINT footprint = {}; - UINT numRows = 0; - UINT64 rowBytes = 0; - UINT64 totalBytes = 0; - m_d3dDevice->GetCopyableFootprints(&texDesc, - subresource, - 1, - /*baseOffset=*/0, - &footprint, - &numRows, - &rowBytes, - &totalBytes); - - // Allocate a staging (UPLOAD heap) buffer. - D3D12_HEAP_PROPERTIES uploadHeap = {}; - uploadHeap.Type = D3D12_HEAP_TYPE_UPLOAD; - - D3D12_RESOURCE_DESC bufDesc = {}; - bufDesc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; - bufDesc.Width = totalBytes; - bufDesc.Height = 1; - bufDesc.DepthOrArraySize = 1; - bufDesc.MipLevels = 1; - bufDesc.Format = DXGI_FORMAT_UNKNOWN; - bufDesc.SampleDesc.Count = 1; - bufDesc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; - bufDesc.Flags = D3D12_RESOURCE_FLAG_NONE; - - ComPtr<ID3D12Resource> staging; - [[maybe_unused]] HRESULT hr = m_d3dDevice->CreateCommittedResource( - &uploadHeap, - D3D12_HEAP_FLAG_NONE, - &bufDesc, - D3D12_RESOURCE_STATE_GENERIC_READ, - nullptr, - IID_PPV_ARGS(staging.GetAddressOf())); - assert(SUCCEEDED(hr) && - "Texture::upload: staging buffer creation failed"); - - // Map and copy row by row, respecting the D3D12 pitch alignment. - void* mapped = nullptr; - D3D12_RANGE readRange = {0, 0}; - staging->Map(0, &readRange, &mapped); - - const uint8_t* src = static_cast<const uint8_t*>(data.data); - uint8_t* dst = static_cast<uint8_t*>(mapped); - UINT64 srcRow = data.bytesPerRow ? data.bytesPerRow : rowBytes; - UINT64 dstRow = footprint.Footprint.RowPitch; - - for (UINT row = 0; row < numRows; ++row) - memcpy(dst + row * dstRow, src + row * srcRow, (size_t)rowBytes); - - staging->Unmap(0, nullptr); - - // If the texture is not in COPY_DEST state, transition it. - if (m_d3dCurrentState != D3D12_RESOURCE_STATE_COPY_DEST) - { - D3D12_RESOURCE_BARRIER barrier = {}; - barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; - barrier.Transition.pResource = m_d3dTexture.Get(); - barrier.Transition.StateBefore = m_d3dCurrentState; - barrier.Transition.StateAfter = D3D12_RESOURCE_STATE_COPY_DEST; - barrier.Transition.Subresource = - D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES; - ctx->m_d3dUploadCmdList->ResourceBarrier(1, &barrier); - m_d3dCurrentState = D3D12_RESOURCE_STATE_COPY_DEST; - } - - // Record the copy. - D3D12_TEXTURE_COPY_LOCATION dst_loc = {}; - dst_loc.pResource = m_d3dTexture.Get(); - dst_loc.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX; - dst_loc.SubresourceIndex = subresource; - - D3D12_TEXTURE_COPY_LOCATION src_loc = {}; - src_loc.pResource = staging.Get(); - src_loc.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT; - src_loc.PlacedFootprint = footprint; - - D3D12_BOX box = {}; - box.left = data.x; - box.top = data.y; - box.front = data.z; - box.right = data.x + data.width; - box.bottom = data.y + data.height; - box.back = data.z + data.depth; - - ctx->m_d3dUploadCmdList->CopyTextureRegion(&dst_loc, - data.x, - data.y, - data.z, - &src_loc, - &box); - - // Transition to PIXEL_SHADER_RESOURCE so it's ready to sample. - { - D3D12_RESOURCE_BARRIER barrier = {}; - barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; - barrier.Transition.pResource = m_d3dTexture.Get(); - barrier.Transition.StateBefore = D3D12_RESOURCE_STATE_COPY_DEST; - barrier.Transition.StateAfter = - D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE; - barrier.Transition.Subresource = - D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES; - ctx->m_d3dUploadCmdList->ResourceBarrier(1, &barrier); - m_d3dCurrentState = D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE; - } - - // Keep the staging buffer alive until the GPU is done. - ctx->m_d3dPendingUploads.push_back(std::move(staging)); - } -} - -void Texture::onRefCntReachedZero() const -{ - // m_d3dOreContext is only set on D3D12-backed textures (see - // d3d12MakeTexture / d3d12WrapCanvasTexture / d3d12WrapRiveTexture). - // D3D11-backed textures keep the immediate-delete path unchanged. - ContextD3D12* ctx = m_d3dOreContext; - auto destroy = [p = const_cast<Texture*>(this)]() { delete p; }; - if (ctx != nullptr) - ctx->d3dDeferDestroy(std::move(destroy)); - else - destroy(); -} - -void TextureView::onRefCntReachedZero() const -{ - ContextD3D12* ctx = m_d3dOreContext; - auto destroy = [p = const_cast<TextureView*>(this)]() { delete p; }; - if (ctx != nullptr) - ctx->d3dDeferDestroy(std::move(destroy)); - else - destroy(); -} - -} // namespace rive::ore - -#endif // ORE_BACKEND_D3D11 && ORE_BACKEND_D3D12
diff --git a/renderer/src/ore/d3d12/ore_texture_d3d12.cpp b/renderer/src/ore/d3d12/ore_texture_d3d12.cpp index 7c31e0b..f5f5d1f 100644 --- a/renderer/src/ore/d3d12/ore_texture_d3d12.cpp +++ b/renderer/src/ore/d3d12/ore_texture_d3d12.cpp
@@ -2,7 +2,7 @@ * Copyright 2025 Rive */ -#include "rive/renderer/ore/ore_texture.hpp" +#include "ore_texture_d3d12.hpp" #include "rive/renderer/ore/ore_context_d3d12.hpp" #include "rive/rive_types.hpp" @@ -16,12 +16,7 @@ namespace rive::ore { -// --- Public method definitions (D3D12-only builds) --- -// When both D3D11 and D3D12 are compiled, the combined -// ore_context_d3d11_d3d12.cpp file provides these methods with dispatch. -#if defined(ORE_BACKEND_D3D12) && !defined(ORE_BACKEND_D3D11) - -void Texture::upload(const TextureDataDesc& data) +void TextureD3D12::upload(const TextureDataDesc& data) { #if defined(ORE_BACKEND_D3D12) assert(m_d3dTexture != nullptr); @@ -167,26 +162,23 @@ #endif } -void Texture::onRefCntReachedZero() const +void TextureD3D12::onRefCntReachedZero() const { ContextD3D12* ctx = m_d3dOreContext; - auto destroy = [p = const_cast<Texture*>(this)]() { delete p; }; + auto destroy = [p = const_cast<TextureD3D12*>(this)]() { delete p; }; if (ctx != nullptr) ctx->d3dDeferDestroy(std::move(destroy)); else destroy(); } -void TextureView::onRefCntReachedZero() const +void TextureViewD3D12::onRefCntReachedZero() const { ContextD3D12* ctx = m_d3dOreContext; - auto destroy = [p = const_cast<TextureView*>(this)]() { delete p; }; + auto destroy = [p = const_cast<TextureViewD3D12*>(this)]() { delete p; }; if (ctx != nullptr) ctx->d3dDeferDestroy(std::move(destroy)); else destroy(); } - -#endif // D3D12-only - } // namespace rive::ore
diff --git a/renderer/src/ore/d3d12/ore_texture_d3d12.hpp b/renderer/src/ore/d3d12/ore_texture_d3d12.hpp new file mode 100644 index 0000000..d0657e7 --- /dev/null +++ b/renderer/src/ore/d3d12/ore_texture_d3d12.hpp
@@ -0,0 +1,50 @@ +#pragma once +#include "rive/renderer/ore/ore_texture.hpp" +#include <d3d12.h> +#include <wrl/client.h> + +namespace rive::ore +{ +class ContextD3D12; + +class TextureD3D12 : public LITE_RTTI_OVERRIDE(Texture, TextureD3D12) +{ +public: + TextureD3D12(const TextureDesc& desc) : lite_rtti_override(desc) {} + ~TextureD3D12() override = default; // ComPtr released automatically + void upload(const TextureDataDesc& data) override; + // Defers the entire CPU+GPU object deletion until after GPU fence. + void onRefCntReachedZero() const override; + +private: + friend class ContextD3D12; + friend class RenderPassD3D12; + Microsoft::WRL::ComPtr<ID3D12Resource> m_d3dTexture; + D3D12_RESOURCE_STATES m_d3dCurrentState = D3D12_RESOURCE_STATE_COMMON; + bool m_d3dIsExternal = false; // true for wrapCanvasTexture. + ID3D12Device* m_d3dDevice = nullptr; // Weak ref. + // Back-ref so upload() and onRefCntReachedZero() can route through + // ContextD3D12. Weak ref. + ContextD3D12* m_d3dOreContext = nullptr; +}; + +class TextureViewD3D12 + : public LITE_RTTI_OVERRIDE(TextureView, TextureViewD3D12) +{ +public: + TextureViewD3D12(rcp<Texture> texture, const TextureViewDesc& desc) : + lite_rtti_override(std::move(texture), desc) + {} + ~TextureViewD3D12() override = default; + // Defers deletion until after GPU fence. + void onRefCntReachedZero() const override; + +private: + friend class ContextD3D12; + D3D12_CPU_DESCRIPTOR_HANDLE m_d3dSrvHandle = {}; + D3D12_CPU_DESCRIPTOR_HANDLE m_d3dRtvHandle = {}; + D3D12_CPU_DESCRIPTOR_HANDLE m_d3dDsvHandle = {}; + // Back-ref for deferred deletion in external-CL mode. Weak ref. + ContextD3D12* m_d3dOreContext = nullptr; +}; +} // namespace rive::ore
diff --git a/renderer/src/ore/gl/ore_bind_group_gl.cpp b/renderer/src/ore/gl/ore_bind_group_gl.cpp index 3bfaef9..a161a18 100644 --- a/renderer/src/ore/gl/ore_bind_group_gl.cpp +++ b/renderer/src/ore/gl/ore_bind_group_gl.cpp
@@ -2,23 +2,4 @@ * Copyright 2025 Rive */ -#include "rive/renderer/ore/ore_bind_group.hpp" - -namespace rive::ore -{ - -#if defined(ORE_BACKEND_GL) && !defined(ORE_BACKEND_METAL) && \ - !defined(ORE_BACKEND_VK) - -void BindGroup::onRefCntReachedZero() const -{ - // Deferred destruction is handled at the Lua GC level via - // Context::deferBindGroupDestroy(), which keeps the rcp<> alive - // until after endFrame(). By the time refcount reaches zero here, - // the GPU is guaranteed to be done. - delete this; -} - -#endif // ORE_BACKEND_GL && !ORE_BACKEND_METAL - -} // namespace rive::ore +#include "ore_bind_group_gl.hpp"
diff --git a/renderer/src/ore/gl/ore_bind_group_gl.hpp b/renderer/src/ore/gl/ore_bind_group_gl.hpp new file mode 100644 index 0000000..c4064b1 --- /dev/null +++ b/renderer/src/ore/gl/ore_bind_group_gl.hpp
@@ -0,0 +1,45 @@ +#pragma once +#include "rive/renderer/ore/ore_bind_group.hpp" +#include <cstdint> +#include <vector> + +namespace rive::ore +{ +class ContextGL; +class RenderPassGL; + +class BindGroupGL : public LITE_RTTI_OVERRIDE(BindGroup, BindGroupGL) +{ +public: + struct GLUBOBinding + { + unsigned int buffer = 0; // GLuint + uint32_t offset = 0; + uint32_t size = 0; + uint32_t binding = 0; // WGSL @binding, for sort + uint32_t slot = 0; // GL UBO binding point + bool hasDynamicOffset = false; + }; + struct GLTexBinding + { + unsigned int texture = 0; // GLuint + unsigned int target = 0; // GLenum (GL_TEXTURE_2D etc.) + uint32_t slot = 0; // texture unit + }; + struct GLSamplerBinding + { + unsigned int sampler = 0; // GLuint + uint32_t slot = 0; // sampler unit + }; + + BindGroupGL() = default; + ~BindGroupGL() override = default; + +private: + friend class ContextGL; + friend class RenderPassGL; + std::vector<GLUBOBinding> m_glUBOs; + std::vector<GLTexBinding> m_glTextures; + std::vector<GLSamplerBinding> m_glSamplers; +}; +} // namespace rive::ore
diff --git a/renderer/src/ore/gl/ore_buffer_gl.cpp b/renderer/src/ore/gl/ore_buffer_gl.cpp index 7ae793a..cc8b585 100644 --- a/renderer/src/ore/gl/ore_buffer_gl.cpp +++ b/renderer/src/ore/gl/ore_buffer_gl.cpp
@@ -3,16 +3,15 @@ */ #include "rive/renderer/gl/load_gles_extensions.hpp" -#include "rive/renderer/ore/ore_buffer.hpp" +#include "ore_buffer_gl.hpp" #include "rive/rive_types.hpp" namespace rive::ore { -#if defined(ORE_BACKEND_GL) && !defined(ORE_BACKEND_METAL) && \ - !defined(ORE_BACKEND_VK) +#if defined(ORE_BACKEND_GL) -void Buffer::update(const void* data, uint32_t size, uint32_t offset) +void BufferGL::update(const void* data, uint32_t size, uint32_t offset) { assert(offset + size <= m_size); assert(m_glBuffer != 0); @@ -40,7 +39,7 @@ } } -void Buffer::onRefCntReachedZero() const +void BufferGL::onRefCntReachedZero() const { if (m_glBuffer != 0) { @@ -50,6 +49,6 @@ delete this; } -#endif // ORE_BACKEND_GL && !ORE_BACKEND_METAL +#endif // ORE_BACKEND_GL } // namespace rive::ore
diff --git a/renderer/src/ore/gl/ore_buffer_gl.hpp b/renderer/src/ore/gl/ore_buffer_gl.hpp new file mode 100644 index 0000000..968df2a --- /dev/null +++ b/renderer/src/ore/gl/ore_buffer_gl.hpp
@@ -0,0 +1,23 @@ +#pragma once +#include "rive/renderer/ore/ore_buffer.hpp" + +namespace rive::ore +{ +class ContextGL; +class RenderPassGL; + +class BufferGL : public LITE_RTTI_OVERRIDE(Buffer, BufferGL) +{ +public: + BufferGL(uint32_t size, BufferUsage usage) : lite_rtti_override(size, usage) + {} + ~BufferGL() override = default; + void update(const void* data, uint32_t size, uint32_t offset) override; + + void onRefCntReachedZero() const override; + friend class ContextGL; + friend class RenderPassGL; + unsigned int m_glBuffer = 0; + unsigned int m_glTarget = 0; +}; +} // namespace rive::ore
diff --git a/renderer/src/ore/gl/ore_context_gl.cpp b/renderer/src/ore/gl/ore_context_gl.cpp index c443d7d..3f63b3e 100644 --- a/renderer/src/ore/gl/ore_context_gl.cpp +++ b/renderer/src/ore/gl/ore_context_gl.cpp
@@ -4,14 +4,14 @@ #include "rive/renderer/gl/load_gles_extensions.hpp" #include "rive/renderer/gl/render_target_gl.hpp" -#include "rive/renderer/ore/ore_bind_group.hpp" -#include "rive/renderer/ore/ore_buffer.hpp" #include "rive/renderer/ore/ore_context_gl.hpp" -#include "rive/renderer/ore/ore_pipeline.hpp" -#include "rive/renderer/ore/ore_render_pass.hpp" -#include "rive/renderer/ore/ore_sampler.hpp" -#include "rive/renderer/ore/ore_shader_module.hpp" -#include "rive/renderer/ore/ore_texture.hpp" +#include "ore_bind_group_gl.hpp" +#include "ore_buffer_gl.hpp" +#include "ore_pipeline_gl.hpp" +#include "ore_render_pass_gl.hpp" +#include "ore_sampler_gl.hpp" +#include "ore_shader_module_gl.hpp" +#include "ore_texture_gl.hpp" #include "rive/renderer/render_canvas.hpp" #include "rive/rive_types.hpp" @@ -107,13 +107,13 @@ RIVE_UNREACHABLE(); } -static bool isDepthFormat(TextureFormat fmt) -{ - return fmt == TextureFormat::depth16unorm || - fmt == TextureFormat::depth24plusStencil8 || - fmt == TextureFormat::depth32float || - fmt == TextureFormat::depth32floatStencil8; -} +// static bool isDepthFormat(TextureFormat fmt) +//{ +// return fmt == TextureFormat::depth16unorm || +// fmt == TextureFormat::depth24plusStencil8 || +// fmt == TextureFormat::depth32float || +// fmt == TextureFormat::depth32floatStencil8; +// } static GLenum oreTextureTypeToGLTarget(TextureType type) { @@ -323,7 +323,7 @@ rcp<Buffer> ContextGL::makeBuffer(const BufferDesc& desc) { - auto buffer = rcp<Buffer>(new Buffer(desc.size, desc.usage)); + auto buffer = rcp<BufferGL>(new BufferGL(desc.size, desc.usage)); glGenBuffers(1, &buffer->m_glBuffer); @@ -369,7 +369,7 @@ rcp<Texture> ContextGL::makeTexture(const TextureDesc& desc) { - auto texture = rcp<Texture>(new Texture(desc)); + auto texture = rcp<TextureGL>(new TextureGL(desc)); glGenTextures(1, &texture->m_glTexture); texture->m_glTarget = oreTextureTypeToGLTarget(desc.type); @@ -469,7 +469,7 @@ if (!tex) return nullptr; - auto view = rcp<TextureView>(new TextureView(ref_rcp(tex), desc)); + auto view = rcp<TextureViewGL>(new TextureViewGL(ref_rcp(tex), desc)); // GLES3 doesn't have glTextureView. We store m_glTextureView = 0 // and use the base texture at bind time. FBO attachment targeting @@ -485,7 +485,7 @@ rcp<Sampler> ContextGL::makeSampler(const SamplerDesc& desc) { - auto sampler = rcp<Sampler>(new Sampler()); + auto sampler = rcp<SamplerGL>(new SamplerGL()); glGenSamplers(1, &sampler->m_glSampler); GLuint s = sampler->m_glSampler; @@ -534,7 +534,7 @@ rcp<ShaderModule> ContextGL::makeShaderModule(const ShaderModuleDesc& desc) { - auto module = rcp<ShaderModule>(new ShaderModule()); + auto module = rcp<ShaderModuleGL>(new ShaderModuleGL()); const char* source = static_cast<const char*>(desc.code); @@ -669,7 +669,7 @@ rcp<Pipeline> ContextGL::makePipeline(const PipelineDesc& desc, std::string* outError) { - auto pipeline = rcp<Pipeline>(new Pipeline(desc)); + auto pipeline = rcp<PipelineGL>(new PipelineGL(desc)); // --- Validate user-supplied layouts against shader binding map --- { @@ -691,10 +691,14 @@ } pipeline->m_glProgram = glCreateProgram(); - glAttachShader(pipeline->m_glProgram, desc.vertexModule->m_glShader); + auto* vertMod = lite_rtti_cast<ShaderModuleGL*>(desc.vertexModule); + assert(vertMod); + glAttachShader(pipeline->m_glProgram, vertMod->m_glShader); if (desc.fragmentModule != nullptr) { - glAttachShader(pipeline->m_glProgram, desc.fragmentModule->m_glShader); + auto* fragMod = lite_rtti_cast<ShaderModuleGL*>(desc.fragmentModule); + assert(fragMod); + glAttachShader(pipeline->m_glProgram, fragMod->m_glShader); } else { @@ -768,7 +772,7 @@ groupIndex); return nullptr; } - auto bg = rcp<BindGroup>(new BindGroup()); + auto bg = rcp<BindGroupGL>(new BindGroupGL()); bg->m_context = this; bg->m_layoutRef = ref_rcp(layout); @@ -824,8 +828,10 @@ for (uint32_t i = 0; i < nBufs; ++i) { const auto& entry = desc.ubos[i]; - BindGroup::GLUBOBinding binding{}; - binding.buffer = entry.buffer->m_glBuffer; + BindGroupGL::GLUBOBinding binding{}; + auto* buf = lite_rtti_cast<BufferGL*>(entry.buffer); + assert(buf); + binding.buffer = buf->m_glBuffer; binding.offset = entry.offset; binding.size = entry.size != 0 ? entry.size @@ -839,23 +845,26 @@ bg->m_glUBOs.push_back(binding); bg->m_retainedBuffers.push_back(ref_rcp(entry.buffer)); } - std::sort( - bg->m_glUBOs.begin(), - bg->m_glUBOs.end(), - [](const BindGroup::GLUBOBinding& a, const BindGroup::GLUBOBinding& b) { - return a.binding < b.binding; - }); + std::sort(bg->m_glUBOs.begin(), + bg->m_glUBOs.end(), + [](const BindGroupGL::GLUBOBinding& a, + const BindGroupGL::GLUBOBinding& b) { + return a.binding < b.binding; + }); uint32_t nTexs = std::min(desc.textureCount, 8u); bg->m_glTextures.reserve(nTexs); for (uint32_t i = 0; i < nTexs; ++i) { const auto& entry = desc.textures[i]; - BindGroup::GLTexBinding binding{}; - binding.texture = entry.view->m_glTextureView != 0 - ? entry.view->m_glTextureView - : entry.view->texture()->m_glTexture; - binding.target = entry.view->texture()->m_glTarget; + BindGroupGL::GLTexBinding binding{}; + auto* viewGL = lite_rtti_cast<TextureViewGL*>(entry.view); + assert(viewGL); + auto* texGL = lite_rtti_cast<TextureGL*>(entry.view->texture()); + assert(texGL); + binding.texture = viewGL->m_glTextureView != 0 ? viewGL->m_glTextureView + : texGL->m_glTexture; + binding.target = texGL->m_glTarget; if (!nativeSlot(entry.slot, BindingKind::sampledTexture, &binding.slot)) continue; bg->m_glTextures.push_back(binding); @@ -867,8 +876,10 @@ for (uint32_t i = 0; i < nSamps; ++i) { const auto& entry = desc.samplers[i]; - BindGroup::GLSamplerBinding binding{}; - binding.sampler = entry.sampler->m_glSampler; + BindGroupGL::GLSamplerBinding binding{}; + auto* samp = lite_rtti_cast<SamplerGL*>(entry.sampler); + assert(samp); + binding.sampler = samp->m_glSampler; if (!nativeSlot(entry.slot, BindingKind::sampler, &binding.slot)) continue; bg->m_glSamplers.push_back(binding); @@ -906,26 +917,26 @@ // beginRenderPass // ============================================================================ -RenderPass ContextGL::beginRenderPass(const RenderPassDesc& desc, - std::string* outError) +std::unique_ptr<RenderPass> ContextGL::beginRenderPass( + const RenderPassDesc& desc, + std::string* outError) { finishActiveRenderPass(); - RenderPass pass; - pass.m_context = this; - pass.populateAttachmentMetadata(desc); + auto pass = std::make_unique<RenderPassGL>(this); + pass->populateAttachmentMetadata(desc); // Save the host renderer's VAO and FBO so we can restore them in finish(). GLint prevVAO = 0, prevFBO = 0; glGetIntegerv(GL_VERTEX_ARRAY_BINDING, &prevVAO); glGetIntegerv(GL_FRAMEBUFFER_BINDING, &prevFBO); - pass.m_prevVAO = static_cast<unsigned int>(prevVAO); - pass.m_prevFBO = static_cast<unsigned int>(prevFBO); + pass->m_prevVAO = static_cast<unsigned int>(prevVAO); + pass->m_prevFBO = static_cast<unsigned int>(prevFBO); // Create an FBO for this render pass. - glGenFramebuffers(1, &pass.m_glFBO); - pass.m_ownsFBO = true; - glBindFramebuffer(GL_FRAMEBUFFER, pass.m_glFBO); + glGenFramebuffers(1, &pass->m_glFBO); + pass->m_ownsFBO = true; + glBindFramebuffer(GL_FRAMEBUFFER, pass->m_glFBO); // Attach color targets. GLenum drawBuffers[4] = {}; @@ -934,31 +945,32 @@ const auto& ca = desc.colorAttachments[i]; if (ca.view) { - Texture* tex = ca.view->texture(); + auto* texGL = lite_rtti_cast<TextureGL*>(ca.view->texture()); + assert(texGL); GLenum attachment = GL_COLOR_ATTACHMENT0 + i; - if (tex->m_glRenderbuffer != 0) + if (texGL->m_glRenderbuffer != 0) { glFramebufferRenderbuffer(GL_FRAMEBUFFER, attachment, GL_RENDERBUFFER, - tex->m_glRenderbuffer); + texGL->m_glRenderbuffer); } - else if (tex->type() == TextureType::cube) + else if (texGL->type() == TextureType::cube) { glFramebufferTexture2D(GL_FRAMEBUFFER, attachment, GL_TEXTURE_CUBE_MAP_POSITIVE_X + ca.view->baseLayer(), - tex->m_glTexture, + texGL->m_glTexture, ca.view->baseMipLevel()); } - else if (tex->type() == TextureType::array2D || - tex->type() == TextureType::texture3D) + else if (texGL->type() == TextureType::array2D || + texGL->type() == TextureType::texture3D) { glFramebufferTextureLayer(GL_FRAMEBUFFER, attachment, - tex->m_glTexture, + texGL->m_glTexture, ca.view->baseMipLevel(), ca.view->baseLayer()); } @@ -967,19 +979,22 @@ glFramebufferTexture2D(GL_FRAMEBUFFER, attachment, GL_TEXTURE_2D, - tex->m_glTexture, + texGL->m_glTexture, ca.view->baseMipLevel()); } // Record resolve target for MSAA blit in finish(). if (ca.resolveTarget) { - auto& r = pass.m_glResolves[pass.m_glResolveCount++]; + auto* resolveTexGL = + lite_rtti_cast<TextureGL*>(ca.resolveTarget->texture()); + assert(resolveTexGL); + auto& r = pass->m_glResolves[pass->m_glResolveCount++]; r.colorIndex = i; - r.resolveTex = ca.resolveTarget->texture()->m_glTexture; - r.resolveTarget = ca.resolveTarget->texture()->m_glTarget; - r.width = tex->width(); - r.height = tex->height(); + r.resolveTex = resolveTexGL->m_glTexture; + r.resolveTarget = resolveTexGL->m_glTarget; + r.width = texGL->width(); + r.height = texGL->height(); } drawBuffers[i] = attachment; @@ -994,28 +1009,30 @@ // Attach depth/stencil. if (desc.depthStencil.view) { - Texture* depthTex = desc.depthStencil.view->texture(); + auto* depthTexGL = + lite_rtti_cast<TextureGL*>(desc.depthStencil.view->texture()); + assert(depthTexGL); GLenum depthAttachment; - TextureFormat depthFmt = depthTex->format(); + TextureFormat depthFmt = depthTexGL->format(); bool hasStencil = (depthFmt == TextureFormat::depth24plusStencil8 || depthFmt == TextureFormat::depth32floatStencil8); depthAttachment = hasStencil ? GL_DEPTH_STENCIL_ATTACHMENT : GL_DEPTH_ATTACHMENT; - if (depthTex->m_glRenderbuffer != 0) + if (depthTexGL->m_glRenderbuffer != 0) { glFramebufferRenderbuffer(GL_FRAMEBUFFER, depthAttachment, GL_RENDERBUFFER, - depthTex->m_glRenderbuffer); + depthTexGL->m_glRenderbuffer); } else { glFramebufferTexture2D(GL_FRAMEBUFFER, depthAttachment, GL_TEXTURE_2D, - depthTex->m_glTexture, + depthTexGL->m_glTexture, desc.depthStencil.view->baseMipLevel()); } } @@ -1075,9 +1092,9 @@ // Create a dedicated VAO for this render pass so Ore's vertex attrib state // doesn't contaminate the host renderer's VAO (e.g., Rive's draw VAO). - glGenVertexArrays(1, &pass.m_glVAO); - pass.m_ownsVAO = true; - glBindVertexArray(pass.m_glVAO); + glGenVertexArrays(1, &pass->m_glVAO); + pass->m_ownsVAO = true; + glBindVertexArray(pass->m_glVAO); // Set a default viewport from the first color or depth attachment so // scripts that omit setViewport() still render correctly. Metal infers @@ -1096,8 +1113,8 @@ if (defaultW > 0 && defaultH > 0) { glViewport(0, 0, defaultW, defaultH); - pass.m_viewportWidth = defaultW; - pass.m_viewportHeight = defaultH; + pass->m_viewportWidth = defaultW; + pass->m_viewportHeight = defaultH; } return pass; @@ -1125,7 +1142,7 @@ texDesc.numMipmaps = 1; texDesc.sampleCount = 1; - auto texture = rcp<Texture>(new Texture(texDesc)); + auto texture = rcp<TextureGL>(new TextureGL(texDesc)); texture->m_glTexture = texID; // Borrow — RenderCanvas owns it. texture->m_glTarget = GL_TEXTURE_2D; texture->m_glOwnsTexture = false; @@ -1138,7 +1155,7 @@ viewDesc.baseLayer = 0; viewDesc.layerCount = 1; - return rcp<TextureView>(new TextureView(std::move(texture), viewDesc)); + return rcp<TextureViewGL>(new TextureViewGL(std::move(texture), viewDesc)); } rcp<TextureView> ContextGL::wrapRiveTexture(gpu::Texture* gpuTex, @@ -1162,7 +1179,7 @@ texDesc.numMipmaps = 1; texDesc.sampleCount = 1; - auto texture = rcp<Texture>(new Texture(texDesc)); + auto texture = rcp<TextureGL>(new TextureGL(texDesc)); texture->m_glTexture = texID; // Borrow — caller owns via RenderImage. texture->m_glTarget = GL_TEXTURE_2D; texture->m_glOwnsTexture = false; @@ -1175,7 +1192,7 @@ viewDesc.baseLayer = 0; viewDesc.layerCount = 1; - return rcp<TextureView>(new TextureView(std::move(texture), viewDesc)); + return rcp<TextureViewGL>(new TextureViewGL(std::move(texture), viewDesc)); } } // namespace rive::ore
diff --git a/renderer/src/ore/gl/ore_pipeline_gl.cpp b/renderer/src/ore/gl/ore_pipeline_gl.cpp index d222f77..7c9e0d5 100644 --- a/renderer/src/ore/gl/ore_pipeline_gl.cpp +++ b/renderer/src/ore/gl/ore_pipeline_gl.cpp
@@ -3,16 +3,14 @@ */ #include "rive/renderer/gl/load_gles_extensions.hpp" -#include "rive/renderer/ore/ore_pipeline.hpp" -#include "rive/renderer/ore/ore_bind_group_layout.hpp" +#include "ore_pipeline_gl.hpp" namespace rive::ore { -#if defined(ORE_BACKEND_GL) && !defined(ORE_BACKEND_METAL) && \ - !defined(ORE_BACKEND_VK) +#if defined(ORE_BACKEND_GL) -void Pipeline::onRefCntReachedZero() const +void PipelineGL::onRefCntReachedZero() const { if (m_glProgram != 0) { @@ -21,8 +19,6 @@ delete this; } -void BindGroupLayout::onRefCntReachedZero() const { delete this; } - -#endif // ORE_BACKEND_GL && !ORE_BACKEND_METAL && !ORE_BACKEND_VK +#endif // ORE_BACKEND_GL } // namespace rive::ore
diff --git a/renderer/src/ore/gl/ore_pipeline_gl.hpp b/renderer/src/ore/gl/ore_pipeline_gl.hpp new file mode 100644 index 0000000..311a3c5 --- /dev/null +++ b/renderer/src/ore/gl/ore_pipeline_gl.hpp
@@ -0,0 +1,21 @@ +#pragma once +#include "rive/renderer/ore/ore_pipeline.hpp" + +namespace rive::ore +{ +class ContextGL; +class RenderPassGL; + +class PipelineGL : public LITE_RTTI_OVERRIDE(Pipeline, PipelineGL) +{ +public: + PipelineGL(const PipelineDesc& desc) : lite_rtti_override(desc) {} + ~PipelineGL() override = default; + void onRefCntReachedZero() const override; + +private: + friend class ContextGL; + friend class RenderPassGL; + unsigned int m_glProgram = 0; // GLuint; 0 = unlinked +}; +} // namespace rive::ore
diff --git a/renderer/src/ore/gl/ore_render_pass_gl.cpp b/renderer/src/ore/gl/ore_render_pass_gl.cpp index 02cf8ee..aa16243 100644 --- a/renderer/src/ore/gl/ore_render_pass_gl.cpp +++ b/renderer/src/ore/gl/ore_render_pass_gl.cpp
@@ -3,13 +3,12 @@ */ #include "rive/renderer/gl/load_gles_extensions.hpp" -#include "rive/renderer/ore/ore_render_pass.hpp" -#include "rive/renderer/ore/ore_bind_group.hpp" -#include "rive/renderer/ore/ore_buffer.hpp" -#include "rive/renderer/ore/ore_texture.hpp" -#include "rive/renderer/ore/ore_sampler.hpp" -#include "rive/renderer/ore/ore_pipeline.hpp" -#include "rive/renderer/ore/ore_context_gl.hpp" // for RenderPass inline bodies +#include "ore_render_pass_gl.hpp" +#include "ore_buffer_gl.hpp" +#include "ore_pipeline_gl.hpp" +#include "ore_bind_group_gl.hpp" +#include "ore_texture_gl.hpp" +#include "rive/renderer/ore/ore_context_gl.hpp" #include "rive/rive_types.hpp" namespace rive::ore @@ -134,7 +133,6 @@ RIVE_UNREACHABLE(); } -// Vertex format → GL type, component count, normalized. struct GLVertexInfo { GLenum type; @@ -185,16 +183,15 @@ } // ============================================================================ -// RenderPass +// RenderPassGL // ============================================================================ // When both Metal and GL are compiled (macOS), ore_render_pass_metal_gl.mm -// provides all RenderPass method bodies with runtime dispatch. This file +// provides all RenderPassGL method bodies with runtime dispatch. This file // only contributes the static helper functions in that case. -#if defined(ORE_BACKEND_GL) && !defined(ORE_BACKEND_METAL) && \ - !defined(ORE_BACKEND_VK) +#if defined(ORE_BACKEND_GL) -RenderPass::~RenderPass() +RenderPassGL::~RenderPassGL() { if (!m_finished && m_context != nullptr) { @@ -202,80 +199,25 @@ } } -RenderPass::RenderPass(RenderPass&& other) noexcept : - m_glFBO(other.m_glFBO), - m_glVAO(other.m_glVAO), - m_prevVAO(other.m_prevVAO), - m_prevFBO(other.m_prevFBO), - m_ownsFBO(other.m_ownsFBO), - m_ownsVAO(other.m_ownsVAO), - m_currentPipeline(std::move(other.m_currentPipeline)), - m_viewportWidth(other.m_viewportWidth), - m_viewportHeight(other.m_viewportHeight), - m_maxSamplerSlot(other.m_maxSamplerSlot), - m_maxAttribSlot(other.m_maxAttribSlot), - m_usedSamplers(other.m_usedSamplers), - m_usedAttribs(other.m_usedAttribs), - m_glResolveCount(other.m_glResolveCount) -{ - moveCrossBackendFieldsFrom(other); - for (uint32_t i = 0; i < m_glResolveCount; ++i) - m_glResolves[i] = other.m_glResolves[i]; - other.m_ownsFBO = false; - other.m_ownsVAO = false; - other.m_glResolveCount = 0; -} - -RenderPass& RenderPass::operator=(RenderPass&& other) noexcept -{ - if (this != &other) - { - if (!m_finished && m_context != nullptr) - { - finish(); - } - moveCrossBackendFieldsFrom(other); - m_glFBO = other.m_glFBO; - m_glVAO = other.m_glVAO; - m_prevVAO = other.m_prevVAO; - m_prevFBO = other.m_prevFBO; - m_ownsFBO = other.m_ownsFBO; - m_ownsVAO = other.m_ownsVAO; - m_currentPipeline = std::move(other.m_currentPipeline); - m_viewportWidth = other.m_viewportWidth; - m_viewportHeight = other.m_viewportHeight; - m_maxSamplerSlot = other.m_maxSamplerSlot; - m_maxAttribSlot = other.m_maxAttribSlot; - m_usedSamplers = other.m_usedSamplers; - m_usedAttribs = other.m_usedAttribs; - m_glResolveCount = other.m_glResolveCount; - for (uint32_t i = 0; i < m_glResolveCount; ++i) - m_glResolves[i] = other.m_glResolves[i]; - other.m_ownsFBO = false; - other.m_ownsVAO = false; - other.m_glResolveCount = 0; - } - return *this; -} - -void RenderPass::validate() const +void RenderPassGL::validate() const { assert(!m_finished && "RenderPass already finished"); assert(m_context != nullptr); } -void RenderPass::setPipeline(Pipeline* pipeline) +void RenderPassGL::setPipeline(Pipeline* pipeline) { validate(); if (!checkPipelineCompat(pipeline)) return; m_currentPipeline = ref_rcp(pipeline); + auto* glPipeline = lite_rtti_cast<PipelineGL*>(pipeline); + assert(glPipeline); const auto& desc = pipeline->desc(); - glUseProgram(pipeline->m_glProgram); + glUseProgram(glPipeline->m_glProgram); - // Cull mode. if (desc.cullMode == CullMode::none) { glDisable(GL_CULL_FACE); @@ -287,11 +229,9 @@ } // Face winding — inverted to compensate for the WGSL→GLSL Y-flip - // baked into every vertex shader at compile time. The same approach - // is used by wgpu and Dawn's GL backends. + // baked into every vertex shader at compile time. glFrontFace(desc.winding == FaceWinding::counterClockwise ? GL_CW : GL_CCW); - // Depth. if (desc.depthStencil.depthCompare != CompareFunction::always || desc.depthStencil.depthWriteEnabled) { @@ -304,7 +244,6 @@ glDisable(GL_DEPTH_TEST); } - // Depth bias (polygon offset). if (desc.depthStencil.depthBias != 0 || desc.depthStencil.depthBiasSlopeScale != 0.0f) { @@ -317,7 +256,6 @@ glDisable(GL_POLYGON_OFFSET_FILL); } - // Stencil. bool hasStencil = (desc.stencilFront.compare != CompareFunction::always || desc.stencilFront.failOp != StencilOp::keep || desc.stencilFront.depthFailOp != StencilOp::keep || @@ -354,7 +292,6 @@ glDisable(GL_STENCIL_TEST); } - // Blending — GLES3 only supports global blend (colorTargets[0]). if (desc.colorCount > 0 && desc.colorTargets[0].blendEnabled) { glEnable(GL_BLEND); @@ -371,7 +308,6 @@ glDisable(GL_BLEND); } - // Color write mask (global on GLES3). if (desc.colorCount > 0) { auto mask = desc.colorTargets[0].writeMask; @@ -382,15 +318,19 @@ } } -void RenderPass::setVertexBuffer(uint32_t slot, Buffer* buffer, uint32_t offset) +void RenderPassGL::setVertexBuffer(uint32_t slot, + Buffer* buffer, + uint32_t offset) { validate(); assert(m_currentPipeline != nullptr && "setPipeline must be called first"); assert(slot < m_currentPipeline->desc().vertexBufferCount); const auto& layout = m_currentPipeline->desc().vertexBuffers[slot]; + auto* glBuffer = lite_rtti_cast<BufferGL*>(buffer); + assert(glBuffer); - glBindBuffer(GL_ARRAY_BUFFER, buffer->m_glBuffer); + glBindBuffer(GL_ARRAY_BUFFER, glBuffer->m_glBuffer); for (uint32_t i = 0; i < layout.attributeCount; ++i) { @@ -428,48 +368,43 @@ } if (layout.stepMode == VertexStepMode::instance) - { glVertexAttribDivisor(attr.shaderSlot, 1); - } else - { glVertexAttribDivisor(attr.shaderSlot, 0); - } - // Track for cleanup in finish(). if (!m_usedAttribs || attr.shaderSlot > m_maxAttribSlot) m_maxAttribSlot = attr.shaderSlot; m_usedAttribs = true; } } -void RenderPass::setIndexBuffer(Buffer* buffer, - IndexFormat format, - uint32_t offset) +void RenderPassGL::setIndexBuffer(Buffer* buffer, + IndexFormat format, + uint32_t offset) { validate(); - glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, buffer->m_glBuffer); + auto* glBuffer = lite_rtti_cast<BufferGL*>(buffer); + assert(glBuffer); + glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, glBuffer->m_glBuffer); m_glIndexFormat = format; (void)offset; } -void RenderPass::setBindGroup(uint32_t groupIndex, - BindGroup* bg, - const uint32_t* dynamicOffsets, - uint32_t dynamicOffsetCount) +void RenderPassGL::setBindGroup(uint32_t groupIndex, + BindGroup* bg, + const uint32_t* dynamicOffsets, + uint32_t dynamicOffsetCount) { validate(); assert(bg != nullptr); - // Hold a strong reference so the BindGroup stays alive until finish(). m_boundGroups[groupIndex] = ref_rcp(bg); + auto* glBg = lite_rtti_cast<BindGroupGL*>(bg); + assert(glBg); uint32_t dynIdx = 0; - // Bind UBOs via glBindBufferRange. Dynamic-offset flag is cached - // on the binding from `Pipeline::isDynamicUBO()` at makeBindGroup - // time; consume one `dynamicOffsets[]` entry per dynamic UBO. - for (const auto& ubo : bg->m_glUBOs) + for (const auto& ubo : glBg->m_glUBOs) { uint32_t offset = ubo.offset; if (ubo.hasDynamicOffset && dynIdx < dynamicOffsetCount) @@ -484,20 +419,17 @@ ubo.size); } - // Bind textures. - for (const auto& tex : bg->m_glTextures) + for (const auto& tex : glBg->m_glTextures) { glActiveTexture(GL_TEXTURE0 + tex.slot); glBindTexture(tex.target, tex.texture); - // Track for cleanup in finish(). if (!m_usedSamplers || tex.slot > m_maxSamplerSlot) m_maxSamplerSlot = tex.slot; m_usedSamplers = true; } - // Bind samplers. - for (const auto& samp : bg->m_glSamplers) + for (const auto& samp : glBg->m_glSamplers) { glBindSampler(samp.slot, samp.sampler); @@ -507,22 +439,16 @@ } } -void RenderPass::setViewport(float x, - float y, - float width, - float height, - float minDepth, - float maxDepth) +void RenderPassGL::setViewport(float x, + float y, + float width, + float height, + float minDepth, + float maxDepth) { validate(); m_viewportWidth = static_cast<uint32_t>(width); m_viewportHeight = static_cast<uint32_t>(height); - // Ore NDC convention: Y-up clip space, depth in [0, 1]. - // GLES has Y-up natively, so no viewport flip is needed here (unlike - // Vulkan). The depth range mismatch (GLES [-1,1] vs ore's [0,1]) and - // the Y-flip required by the Vulkan-style WGSL coordinate space are - // both corrected in the compiled vertex shader at WGSL→GLSL compile - // time — no runtime fixup is needed. glViewport(static_cast<GLint>(x), static_cast<GLint>(y), static_cast<GLsizei>(width), @@ -530,23 +456,19 @@ glDepthRangef(minDepth, maxDepth); } -void RenderPass::setScissorRect(uint32_t x, - uint32_t y, - uint32_t width, - uint32_t height) +void RenderPassGL::setScissorRect(uint32_t x, + uint32_t y, + uint32_t width, + uint32_t height) { validate(); glEnable(GL_SCISSOR_TEST); glScissor(x, y, width, height); } -void RenderPass::setStencilReference(uint32_t ref) +void RenderPassGL::setStencilReference(uint32_t ref) { validate(); - // Cache the ref so a subsequent `setPipeline` re-applies it. WebGPU - // semantics: `setStencilReference` is pass-state and persists across - // pipeline changes — calling it BEFORE the first `setPipeline` is - // valid, so we must not depend on `m_currentPipeline` here. m_glStencilRef = ref; if (m_currentPipeline) { @@ -562,38 +484,34 @@ } } -void RenderPass::setBlendColor(float r, float g, float b, float a) +void RenderPassGL::setBlendColor(float r, float g, float b, float a) { validate(); glBlendColor(r, g, b, a); } -void RenderPass::draw(uint32_t vertexCount, - uint32_t instanceCount, - uint32_t firstVertex, - uint32_t firstInstance) +void RenderPassGL::draw(uint32_t vertexCount, + uint32_t instanceCount, + uint32_t firstVertex, + uint32_t firstInstance) { validate(); assert(m_currentPipeline != nullptr); GLenum mode = oreTopologyToGL(m_currentPipeline->desc().topology); - (void)firstInstance; // GLES3 doesn't support base instance. + (void)firstInstance; if (instanceCount > 1) - { glDrawArraysInstanced(mode, firstVertex, vertexCount, instanceCount); - } else - { glDrawArrays(mode, firstVertex, vertexCount); - } } -void RenderPass::drawIndexed(uint32_t indexCount, - uint32_t instanceCount, - uint32_t firstIndex, - int32_t baseVertex, - uint32_t firstInstance) +void RenderPassGL::drawIndexed(uint32_t indexCount, + uint32_t instanceCount, + uint32_t firstIndex, + int32_t baseVertex, + uint32_t firstInstance) { validate(); assert(m_currentPipeline != nullptr); @@ -606,30 +524,29 @@ const void* offset = reinterpret_cast<const void*>( static_cast<uintptr_t>(firstIndex * indexSize)); - (void)baseVertex; // Not supported on base GLES3. - (void)firstInstance; // Not supported on GLES3. + (void)baseVertex; + (void)firstInstance; if (instanceCount > 1) - { glDrawElementsInstanced(mode, indexCount, indexType, offset, instanceCount); - } else - { glDrawElements(mode, indexCount, indexType, offset); - } } -void RenderPass::finish() +void RenderPassGL::finish() { if (m_finished) return; m_finished = true; - // Restore defaults. + m_currentPipeline = nullptr; + for (auto& bg : m_boundGroups) + bg.reset(); + glDisable(GL_SCISSOR_TEST); glDisable(GL_BLEND); glDisable(GL_DEPTH_TEST); @@ -639,9 +556,6 @@ glDepthMask(GL_TRUE); glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE); - // Unbind sampler objects and textures so they don't override texture - // parameters in subsequent draws by the host renderer (e.g. Rive's MSAA - // path). if (m_usedSamplers) { for (uint32_t i = 0; i <= m_maxSamplerSlot; ++i) @@ -654,22 +568,14 @@ glActiveTexture(GL_TEXTURE0); } - // Disable vertex attrib arrays that were enabled, so they don't - // contaminate the host renderer's VAO state. if (m_usedAttribs) { for (uint32_t i = 0; i <= m_maxAttribSlot; ++i) glDisableVertexAttribArray(i); } - // Unbind the global array buffer. (GL_ELEMENT_ARRAY_BUFFER is VAO state - // and will be cleaned up when the per-pass VAO is deleted below — we must - // NOT unbind it here because on some WebGL2 implementations the EBO=0 - // can leak through the VAO delete/restore and corrupt the host VAO.) glBindBuffer(GL_ARRAY_BUFFER, 0); - // Delete the per-pass VAO and restore the host renderer's VAO so its - // element-array-buffer binding (and other attrib state) is intact. if (m_ownsVAO && m_glVAO != 0) { glDeleteVertexArrays(1, &m_glVAO); @@ -677,7 +583,6 @@ } glBindVertexArray(m_prevVAO); - // Resolve MSAA renderbuffers → single-sample resolve targets. if (m_glResolveCount > 0) { GLuint resolveFBO; @@ -685,11 +590,9 @@ for (uint32_t i = 0; i < m_glResolveCount; ++i) { const auto& r = m_glResolves[i]; - // Read from the render pass FBO (MSAA renderbuffer attached). glBindFramebuffer(GL_READ_FRAMEBUFFER, m_glFBO); glReadBuffer(GL_COLOR_ATTACHMENT0 + r.colorIndex); - // Write to a temp FBO with the single-sample resolve texture. glBindFramebuffer(GL_DRAW_FRAMEBUFFER, resolveFBO); glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, @@ -711,16 +614,13 @@ glDeleteFramebuffers(1, &resolveFBO); } - // Delete our FBO and restore the host renderer's FBO. if (m_ownsFBO && m_glFBO != 0) - { glDeleteFramebuffers(1, &m_glFBO); - } glBindFramebuffer(GL_FRAMEBUFFER, m_prevFBO); m_context = nullptr; } -#endif // ORE_BACKEND_GL && !ORE_BACKEND_METAL +#endif // ORE_BACKEND_GL } // namespace rive::ore
diff --git a/renderer/src/ore/gl/ore_render_pass_gl.hpp b/renderer/src/ore/gl/ore_render_pass_gl.hpp new file mode 100644 index 0000000..6aa2d36 --- /dev/null +++ b/renderer/src/ore/gl/ore_render_pass_gl.hpp
@@ -0,0 +1,86 @@ +#pragma once +#include "rive/renderer/ore/ore_render_pass.hpp" +#include "rive/renderer/ore/ore_pipeline.hpp" +#include "rive/refcnt.hpp" +#include <cstdint> + +namespace rive::ore +{ +class ContextGL; + +class RenderPassGL : public RenderPass +{ +public: + void setPipeline(Pipeline* pipeline) override; + void setVertexBuffer(uint32_t slot, + Buffer* buffer, + uint32_t offset = 0) override; + void setIndexBuffer(Buffer* buffer, + IndexFormat format, + uint32_t offset = 0) override; + void setBindGroup(uint32_t groupIndex, + BindGroup* bg, + const uint32_t* dynamicOffsets = nullptr, + uint32_t dynamicOffsetCount = 0) override; + void setViewport(float x, + float y, + float width, + float height, + float minDepth = 0.0f, + float maxDepth = 1.0f) override; + void setScissorRect(uint32_t x, + uint32_t y, + uint32_t width, + uint32_t height) override; + void setStencilReference(uint32_t ref) override; + void setBlendColor(float r, float g, float b, float a) override; + void draw(uint32_t vertexCount, + uint32_t instanceCount = 1, + uint32_t firstVertex = 0, + uint32_t firstInstance = 0) override; + void drawIndexed(uint32_t indexCount, + uint32_t instanceCount = 1, + uint32_t firstIndex = 0, + int32_t baseVertex = 0, + uint32_t firstInstance = 0) override; + void finish() override; + + void validate() const override; + + RenderPassGL() = default; + RenderPassGL(Context* context) : RenderPass(context) {} + ~RenderPassGL() override; + RenderPassGL(RenderPassGL&& other) noexcept; + RenderPassGL& operator=(RenderPassGL&&) noexcept; + + struct GLResolveEntry + { + unsigned int colorIndex = 0; // attachment index + unsigned int resolveTarget = 0; // GLenum (e.g. GL_TEXTURE_2D) + unsigned int resolveTex = 0; // GLuint + uint32_t width = 0; + uint32_t height = 0; + }; + +private: + friend class ContextGL; + + unsigned int m_glFBO = 0; // GLuint + unsigned int m_glVAO = 0; // GLuint + unsigned int m_prevVAO = 0; // GLuint saved before this pass + unsigned int m_prevFBO = 0; // GLuint saved before this pass + bool m_ownsFBO = false; + bool m_ownsVAO = false; + rcp<Pipeline> m_currentPipeline; + uint32_t m_viewportWidth = 0; + uint32_t m_viewportHeight = 0; + uint32_t m_maxSamplerSlot = 0; + uint32_t m_maxAttribSlot = 0; + bool m_usedSamplers = false; + bool m_usedAttribs = false; + IndexFormat m_glIndexFormat = IndexFormat::uint16; + uint32_t m_glStencilRef = 0; + uint32_t m_glResolveCount = 0; + GLResolveEntry m_glResolves[4]; +}; +} // namespace rive::ore
diff --git a/renderer/src/ore/gl/ore_sampler_gl.cpp b/renderer/src/ore/gl/ore_sampler_gl.cpp index b50c53f..0744197 100644 --- a/renderer/src/ore/gl/ore_sampler_gl.cpp +++ b/renderer/src/ore/gl/ore_sampler_gl.cpp
@@ -3,15 +3,14 @@ */ #include "rive/renderer/gl/load_gles_extensions.hpp" -#include "rive/renderer/ore/ore_sampler.hpp" +#include "ore_sampler_gl.hpp" namespace rive::ore { -#if defined(ORE_BACKEND_GL) && !defined(ORE_BACKEND_METAL) && \ - !defined(ORE_BACKEND_VK) +#if defined(ORE_BACKEND_GL) -void Sampler::onRefCntReachedZero() const +void SamplerGL::onRefCntReachedZero() const { if (m_glSampler != 0) { @@ -21,6 +20,6 @@ delete this; } -#endif // ORE_BACKEND_GL && !ORE_BACKEND_METAL +#endif // ORE_BACKEND_GL } // namespace rive::ore
diff --git a/renderer/src/ore/gl/ore_sampler_gl.hpp b/renderer/src/ore/gl/ore_sampler_gl.hpp new file mode 100644 index 0000000..d45c378 --- /dev/null +++ b/renderer/src/ore/gl/ore_sampler_gl.hpp
@@ -0,0 +1,19 @@ +#pragma once +#include "rive/renderer/ore/ore_sampler.hpp" + +namespace rive::ore +{ +class ContextGL; + +class SamplerGL : public LITE_RTTI_OVERRIDE(Sampler, SamplerGL) +{ +public: + SamplerGL() = default; + ~SamplerGL() override = default; + void onRefCntReachedZero() const override; + +private: + friend class ContextGL; + unsigned int m_glSampler = 0; // GLuint +}; +} // namespace rive::ore
diff --git a/renderer/src/ore/gl/ore_shader_module_gl.cpp b/renderer/src/ore/gl/ore_shader_module_gl.cpp index f13c553..3c9ff73 100644 --- a/renderer/src/ore/gl/ore_shader_module_gl.cpp +++ b/renderer/src/ore/gl/ore_shader_module_gl.cpp
@@ -3,15 +3,14 @@ */ #include "rive/renderer/gl/load_gles_extensions.hpp" -#include "rive/renderer/ore/ore_shader_module.hpp" +#include "ore_shader_module_gl.hpp" namespace rive::ore { -#if defined(ORE_BACKEND_GL) && !defined(ORE_BACKEND_METAL) && \ - !defined(ORE_BACKEND_VK) +#if defined(ORE_BACKEND_GL) -void ShaderModule::onRefCntReachedZero() const +void ShaderModuleGL::onRefCntReachedZero() const { if (m_glShader != 0) { @@ -20,6 +19,6 @@ delete this; } -#endif // ORE_BACKEND_GL && !ORE_BACKEND_METAL +#endif // ORE_BACKEND_GL } // namespace rive::ore
diff --git a/renderer/src/ore/gl/ore_shader_module_gl.hpp b/renderer/src/ore/gl/ore_shader_module_gl.hpp new file mode 100644 index 0000000..5a516e0 --- /dev/null +++ b/renderer/src/ore/gl/ore_shader_module_gl.hpp
@@ -0,0 +1,21 @@ +#pragma once +#include "rive/renderer/ore/ore_shader_module.hpp" + +namespace rive::ore +{ +class ContextGL; + +class ShaderModuleGL : public LITE_RTTI_OVERRIDE(ShaderModule, ShaderModuleGL) +{ +public: + ShaderModuleGL() = default; + ~ShaderModuleGL() override = default; + void onRefCntReachedZero() const override; + +private: + friend class ContextGL; + unsigned int m_glShader = 0; // GLuint + unsigned int m_glShaderType = + 0; // GLenum (GL_VERTEX_SHADER or GL_FRAGMENT_SHADER) +}; +} // namespace rive::ore
diff --git a/renderer/src/ore/gl/ore_texture_gl.cpp b/renderer/src/ore/gl/ore_texture_gl.cpp index 6451962..3487cc2 100644 --- a/renderer/src/ore/gl/ore_texture_gl.cpp +++ b/renderer/src/ore/gl/ore_texture_gl.cpp
@@ -3,7 +3,7 @@ */ #include "rive/renderer/gl/load_gles_extensions.hpp" -#include "rive/renderer/ore/ore_texture.hpp" +#include "ore_texture_gl.hpp" #include "rive/rive_types.hpp" namespace rive::ore @@ -157,34 +157,31 @@ } } -static bool isDepthFormat(TextureFormat fmt) -{ - return fmt == TextureFormat::depth16unorm || - fmt == TextureFormat::depth24plusStencil8 || - fmt == TextureFormat::depth32float || - fmt == TextureFormat::depth32floatStencil8; -} +// static bool isDepthFormat(TextureFormat fmt) +//{ +// return fmt == TextureFormat::depth16unorm || +// fmt == TextureFormat::depth24plusStencil8 || +// fmt == TextureFormat::depth32float || +// fmt == TextureFormat::depth32floatStencil8; +// } -static GLenum oreTextureTypeToGLTarget(TextureType type) -{ - switch (type) - { - case TextureType::texture2D: - return GL_TEXTURE_2D; - case TextureType::cube: - return GL_TEXTURE_CUBE_MAP; - case TextureType::texture3D: - return GL_TEXTURE_3D; - case TextureType::array2D: - return GL_TEXTURE_2D_ARRAY; - } - RIVE_UNREACHABLE(); -} +// static GLenum oreTextureTypeToGLTarget(TextureType type) +//{ +// switch (type) +// { +// case TextureType::texture2D: +// return GL_TEXTURE_2D; +// case TextureType::cube: +// return GL_TEXTURE_CUBE_MAP; +// case TextureType::texture3D: +// return GL_TEXTURE_3D; +// case TextureType::array2D: +// return GL_TEXTURE_2D_ARRAY; +// } +// RIVE_UNREACHABLE(); +// } -// Block-compressed format detection. For these formats, `bytesPerRow` is -// the byte size of a row of compressed *blocks* (4×4 for BC1/BC3/BC7/ETC2/ -// ASTC4x4, 6×6 / 8×8 for the corresponding ASTC variants), and the upload -// path must go through `glCompressedTexSubImage*` with `imageSize` bytes. +// Block-compressed format detection. static bool isCompressedFormat(TextureFormat fmt) { switch (fmt) @@ -203,40 +200,22 @@ } } -#if defined(ORE_BACKEND_GL) && !defined(ORE_BACKEND_METAL) && \ - !defined(ORE_BACKEND_VK) +#if defined(ORE_BACKEND_GL) -void Texture::upload(const TextureDataDesc& data) +void TextureGL::upload(const TextureDataDesc& data) { assert(m_glTexture != 0); assert(data.data != nullptr); - // GLES3 has no `GL_BGRA8` internal format, and uploading BGRA bytes - // through `GL_RGBA + GL_UNSIGNED_BYTE` silently swizzles channels - // (red ↔ blue) in the resulting texture. Reject explicitly here - // rather than letting the corruption render. Callers that need - // BGRA-source data on GL should pre-swizzle in software or use - // `rgba8unorm`. (BGRA *render targets* — e.g. canvas wrapping — - // remain valid since they don't go through this upload path.) assert(m_format != TextureFormat::bgra8unorm && "GLES3 cannot upload BGRA pixels — " "pre-swizzle to rgba8unorm or use a different format"); - // Force the active unit to GL_TEXTURE0 before a transient bind. See - // Context::makeTexture() for the full rationale — Rive PLS reserves - // units 8..14 and a naked glBindTexture() on one of those units would - // clobber Rive's state. glActiveTexture(GL_TEXTURE0); glBindTexture(m_glTarget, m_glTexture); GLenum internalFmt = oreFormatToGLInternal(m_format); - // Compressed formats route through `glCompressedTexSubImage*` with a - // byte count, not format/type. `bytesPerRow * rowsPerImage` is the - // total compressed byte size for one slice; multiply by `depth` for - // 3D / array uploads. Pre-fix the GL backend always called - // `glTexSubImage*` regardless of format — uploads of any compressed - // texture (ETC2/BC/ASTC) failed silently with `GL_INVALID_OPERATION`. if (isCompressedFormat(m_format)) { const uint32_t imageSize = @@ -289,12 +268,6 @@ GLenum format = oreFormatToGLFormat(m_format); GLenum type = oreFormatToGLType(m_format); - // Honor `bytesPerRow` / `rowsPerImage` for non-tightly-packed source - // data via `GL_UNPACK_ROW_LENGTH` / `GL_UNPACK_IMAGE_HEIGHT`. Save + - // restore so we don't trash the host's pixel-store state. Pre-fix the - // GL backend ignored these fields — uploads from a sub-rect of a - // larger source buffer (or from a layout that pads rows) read garbage - // bytes between rows. GLint savedRowLength = 0, savedImageHeight = 0; glGetIntegerv(GL_UNPACK_ROW_LENGTH, &savedRowLength); glGetIntegerv(GL_UNPACK_IMAGE_HEIGHT, &savedImageHeight); @@ -349,14 +322,13 @@ data.data); } - // Restore host pixel-store state. glPixelStorei(GL_UNPACK_ROW_LENGTH, savedRowLength); glPixelStorei(GL_UNPACK_IMAGE_HEIGHT, savedImageHeight); glBindTexture(m_glTarget, 0); } -void Texture::onRefCntReachedZero() const +void TextureGL::onRefCntReachedZero() const { if (m_glRenderbuffer != 0 && m_glOwnsTexture) { @@ -371,7 +343,7 @@ delete this; } -void TextureView::onRefCntReachedZero() const +void TextureViewGL::onRefCntReachedZero() const { if (m_glTextureView != 0) { @@ -381,6 +353,6 @@ delete this; } -#endif // ORE_BACKEND_GL && !ORE_BACKEND_METAL +#endif // ORE_BACKEND_GL } // namespace rive::ore
diff --git a/renderer/src/ore/gl/ore_texture_gl.hpp b/renderer/src/ore/gl/ore_texture_gl.hpp new file mode 100644 index 0000000..3a9ce60 --- /dev/null +++ b/renderer/src/ore/gl/ore_texture_gl.hpp
@@ -0,0 +1,37 @@ +#pragma once +#include "rive/renderer/ore/ore_texture.hpp" + +namespace rive::ore +{ +class ContextGL; + +class TextureGL : public LITE_RTTI_OVERRIDE(Texture, TextureGL) +{ +public: + TextureGL(const TextureDesc& desc) : lite_rtti_override(desc) {} + ~TextureGL() override = default; + void upload(const TextureDataDesc& data) override; + void onRefCntReachedZero() const override; + +private: + friend class ContextGL; + unsigned int m_glTexture = 0; + unsigned int m_glRenderbuffer = 0; + unsigned int m_glTarget = 0; // GLenum + bool m_glOwnsTexture = false; +}; + +class TextureViewGL : public LITE_RTTI_OVERRIDE(TextureView, TextureViewGL) +{ +public: + TextureViewGL(rcp<Texture> texture, const TextureViewDesc& desc) : + lite_rtti_override(std::move(texture), desc) + {} + ~TextureViewGL() override = default; + void onRefCntReachedZero() const override; + +private: + friend class ContextGL; + unsigned int m_glTextureView = 0; // GLenum; 0 means use base texture +}; +} // namespace rive::ore
diff --git a/renderer/src/ore/metal/ore_bind_group_metal.hpp b/renderer/src/ore/metal/ore_bind_group_metal.hpp new file mode 100644 index 0000000..d779cc0 --- /dev/null +++ b/renderer/src/ore/metal/ore_bind_group_metal.hpp
@@ -0,0 +1,47 @@ +#pragma once +#include "rive/renderer/ore/ore_bind_group.hpp" +#include "rive/renderer/ore/ore_binding_map.hpp" +#import <Metal/Metal.h> +#include <vector> + +namespace rive::ore +{ +class ContextMetal; +class RenderPassMetal; + +class BindGroupMetal : public LITE_RTTI_OVERRIDE(BindGroup, BindGroupMetal) +{ +public: + struct MTLBufferBinding + { + id<MTLBuffer> buffer = nil; + uint32_t offset = 0; + uint32_t binding = 0; // WGSL @binding, for sort + bool hasDynamicOffset = false; + uint16_t vsSlot = BindingMap::kAbsent; + uint16_t fsSlot = BindingMap::kAbsent; + }; + struct MTLTextureBinding + { + id<MTLTexture> texture = nil; + uint16_t vsSlot = BindingMap::kAbsent; + uint16_t fsSlot = BindingMap::kAbsent; + }; + struct MTLSamplerBinding + { + id<MTLSamplerState> sampler = nil; + uint16_t vsSlot = BindingMap::kAbsent; + uint16_t fsSlot = BindingMap::kAbsent; + }; + + BindGroupMetal() = default; + ~BindGroupMetal() override = default; // ARC releases Metal objects + +private: + friend class ContextMetal; + friend class RenderPassMetal; + std::vector<MTLBufferBinding> m_mtlBuffers; + std::vector<MTLTextureBinding> m_mtlTextures; + std::vector<MTLSamplerBinding> m_mtlSamplers; +}; +} // namespace rive::ore
diff --git a/renderer/src/ore/metal/ore_bind_group_metal.mm b/renderer/src/ore/metal/ore_bind_group_metal.mm index 4bbf26d..8b851c0 100644 --- a/renderer/src/ore/metal/ore_bind_group_metal.mm +++ b/renderer/src/ore/metal/ore_bind_group_metal.mm
@@ -2,25 +2,7 @@ * Copyright 2025 Rive */ -#include "rive/renderer/ore/ore_bind_group.hpp" -#include "rive/renderer/ore/ore_context_metal.hpp" - -#import <Metal/Metal.h> +#include "ore_bind_group_metal.hpp" namespace rive::ore -{ - -#if !defined(ORE_BACKEND_GL) - -void BindGroup::onRefCntReachedZero() const -{ - // Deferred destruction is handled at the Lua GC level via - // Context::deferBindGroupDestroy(), which keeps the rcp<> alive - // until after endFrame(). By the time refcount reaches zero here, - // the GPU is guaranteed to be done. - delete this; -} - -#endif // !ORE_BACKEND_GL - -} // namespace rive::ore +{} // namespace rive::ore
diff --git a/renderer/src/ore/metal/ore_bind_group_metal_gl.mm b/renderer/src/ore/metal/ore_bind_group_metal_gl.mm deleted file mode 100644 index 2fffd62..0000000 --- a/renderer/src/ore/metal/ore_bind_group_metal_gl.mm +++ /dev/null
@@ -1,29 +0,0 @@ -/* - * Copyright 2025 Rive - */ - -// Combined Metal + GL BindGroup implementation for macOS. -// Compiled when both ORE_BACKEND_METAL and ORE_BACKEND_GL are active. - -#if defined(ORE_BACKEND_METAL) && defined(ORE_BACKEND_GL) - -#include "rive/renderer/gl/load_gles_extensions.hpp" -#include "rive/renderer/ore/ore_bind_group.hpp" -#include "rive/renderer/ore/ore_context_metal.hpp" - -#import <Metal/Metal.h> - -namespace rive::ore -{ - -void BindGroup::onRefCntReachedZero() const -{ - // Deferred destruction is handled at the Lua GC level via - // Context::deferBindGroupDestroy(). By the time refcount reaches - // zero here, the GPU is guaranteed to be done. - delete this; -} - -} // namespace rive::ore - -#endif // ORE_BACKEND_METAL && ORE_BACKEND_GL
diff --git a/renderer/src/ore/metal/ore_buffer_metal.hpp b/renderer/src/ore/metal/ore_buffer_metal.hpp new file mode 100644 index 0000000..c169825 --- /dev/null +++ b/renderer/src/ore/metal/ore_buffer_metal.hpp
@@ -0,0 +1,24 @@ +#pragma once +#include "rive/renderer/ore/ore_buffer.hpp" +#import <Metal/Metal.h> + +namespace rive::ore +{ +class ContextMetal; +class RenderPassMetal; + +class BufferMetal : public LITE_RTTI_OVERRIDE(Buffer, BufferMetal) +{ +public: + BufferMetal(uint32_t size, BufferUsage usage) : + lite_rtti_override(size, usage) + {} + ~BufferMetal() override = default; // ARC releases m_mtlBuffer + void update(const void* data, uint32_t size, uint32_t offset) override; + +private: + friend class ContextMetal; + friend class RenderPassMetal; + id<MTLBuffer> m_mtlBuffer = nil; +}; +} // namespace rive::ore
diff --git a/renderer/src/ore/metal/ore_buffer_metal.mm b/renderer/src/ore/metal/ore_buffer_metal.mm index 60cc2db..c161c00 100644 --- a/renderer/src/ore/metal/ore_buffer_metal.mm +++ b/renderer/src/ore/metal/ore_buffer_metal.mm
@@ -2,7 +2,7 @@ * Copyright 2025 Rive */ -#include "rive/renderer/ore/ore_buffer.hpp" +#include "ore_buffer_metal.hpp" #include "rive/rive_types.hpp" #import <Metal/Metal.h> @@ -10,20 +10,10 @@ namespace rive::ore { -#if !defined(ORE_BACKEND_GL) - -void Buffer::update(const void* data, uint32_t size, uint32_t offset) +void BufferMetal::update(const void* data, uint32_t size, uint32_t offset) { assert(offset + size <= m_size); memcpy(static_cast<uint8_t*>([m_mtlBuffer contents]) + offset, data, size); } -void Buffer::onRefCntReachedZero() const -{ - // Release the Metal buffer by destroying this object. - delete this; -} - -#endif // !ORE_BACKEND_GL - } // namespace rive::ore
diff --git a/renderer/src/ore/metal/ore_buffer_metal_gl.mm b/renderer/src/ore/metal/ore_buffer_metal_gl.mm deleted file mode 100644 index aff3e86..0000000 --- a/renderer/src/ore/metal/ore_buffer_metal_gl.mm +++ /dev/null
@@ -1,44 +0,0 @@ -/* - * Copyright 2025 Rive - */ - -// Combined Metal + GL Buffer implementation for macOS. -// Compiled when both ORE_BACKEND_METAL and ORE_BACKEND_GL are active. - -#if defined(ORE_BACKEND_METAL) && defined(ORE_BACKEND_GL) - -#include "rive/renderer/gl/load_gles_extensions.hpp" -#include "rive/renderer/ore/ore_buffer.hpp" -#include "rive/rive_types.hpp" - -#import <Metal/Metal.h> - -namespace rive::ore -{ - -void Buffer::update(const void* data, uint32_t size, uint32_t offset) -{ - assert(offset + size <= m_size); - if (m_glBuffer != 0) - { - glBindBuffer(m_glTarget, m_glBuffer); - glBufferSubData(m_glTarget, offset, size, data); - glBindBuffer(m_glTarget, 0); - return; - } - memcpy(static_cast<uint8_t*>([m_mtlBuffer contents]) + offset, data, size); -} - -void Buffer::onRefCntReachedZero() const -{ - if (m_glBuffer != 0) - { - GLuint buf = m_glBuffer; - glDeleteBuffers(1, &buf); - } - delete this; -} - -} // namespace rive::ore - -#endif // ORE_BACKEND_METAL && ORE_BACKEND_GL
diff --git a/renderer/src/ore/metal/ore_context_metal.mm b/renderer/src/ore/metal/ore_context_metal.mm index 6e89f93..d7b0520 100644 --- a/renderer/src/ore/metal/ore_context_metal.mm +++ b/renderer/src/ore/metal/ore_context_metal.mm
@@ -3,12 +3,13 @@ */ #include "rive/renderer/ore/ore_context_metal.hpp" -#include "rive/renderer/ore/ore_buffer.hpp" -#include "rive/renderer/ore/ore_texture.hpp" -#include "rive/renderer/ore/ore_sampler.hpp" -#include "rive/renderer/ore/ore_shader_module.hpp" -#include "rive/renderer/ore/ore_pipeline.hpp" -#include "rive/renderer/ore/ore_render_pass.hpp" +#include "ore_bind_group_metal.hpp" +#include "ore_buffer_metal.hpp" +#include "ore_pipeline_metal.hpp" +#include "ore_render_pass_metal.hpp" +#include "ore_sampler_metal.hpp" +#include "ore_shader_module_metal.hpp" +#include "ore_texture_metal.hpp" #include "rive/renderer/render_canvas.hpp" #include "rive/renderer/metal/render_context_metal_impl.h" #include "rive/rive_types.hpp" @@ -281,24 +282,6 @@ RIVE_UNREACHABLE(); } -static MTLPrimitiveType orePrimitiveTopologyToMTL(PrimitiveTopology topo) -{ - switch (topo) - { - case PrimitiveTopology::pointList: - return MTLPrimitiveTypePoint; - case PrimitiveTopology::lineList: - return MTLPrimitiveTypeLine; - case PrimitiveTopology::lineStrip: - return MTLPrimitiveTypeLineStrip; - case PrimitiveTopology::triangleList: - return MTLPrimitiveTypeTriangle; - case PrimitiveTopology::triangleStrip: - return MTLPrimitiveTypeTriangleStrip; - } - RIVE_UNREACHABLE(); -} - static MTLVertexFormat oreVertexFormatToMTL(VertexFormat fmt) { switch (fmt) @@ -341,32 +324,6 @@ RIVE_UNREACHABLE(); } -static MTLCullMode oreCullModeToMTL(CullMode mode) -{ - switch (mode) - { - case CullMode::none: - return MTLCullModeNone; - case CullMode::front: - return MTLCullModeFront; - case CullMode::back: - return MTLCullModeBack; - } - RIVE_UNREACHABLE(); -} - -static MTLWinding oreWindingToMTL(FaceWinding winding) -{ - switch (winding) - { - case FaceWinding::clockwise: - return MTLWindingClockwise; - case FaceWinding::counterClockwise: - return MTLWindingCounterClockwise; - } - RIVE_UNREACHABLE(); -} - static MTLColorWriteMask oreColorWriteMaskToMTL(ColorWriteMask mask) { MTLColorWriteMask mtl = MTLColorWriteMaskNone; @@ -381,20 +338,6 @@ return mtl; } -static MTLIndexType oreIndexFormatToMTL(IndexFormat format) -{ - switch (format) - { - case IndexFormat::uint16: - return MTLIndexTypeUInt16; - case IndexFormat::uint32: - return MTLIndexTypeUInt32; - case IndexFormat::none: - break; - } - RIVE_UNREACHABLE(); -} - // Metal uses a single [[buffer(n)]] namespace for both vertex buffers and // uniform/constant buffers. WGSL→MSL compilation assigns uniform buffers // starting at buffer index 0. To avoid collisions we reserve the first N @@ -471,7 +414,7 @@ inline rcp<Buffer> ContextMetal::mtlMakeBuffer(const BufferDesc& desc) { - auto buffer = rcp<Buffer>(new Buffer(desc.size, desc.usage)); + auto buffer = rcp<BufferMetal>(new BufferMetal(desc.size, desc.usage)); if (desc.data) { buffer->m_mtlBuffer = @@ -544,7 +487,7 @@ td.usage |= MTLTextureUsagePixelFormatView; } - auto texture = rcp<Texture>(new Texture(desc)); + auto texture = rcp<TextureMetal>(new TextureMetal(desc)); #if RIVE_OBJC_EXCEPTIONS @try { @@ -573,10 +516,10 @@ inline rcp<TextureView> ContextMetal::mtlMakeTextureView( const TextureViewDesc& desc) { - Texture* tex = desc.texture; + auto tex = lite_rtti_cast<TextureMetal*>(desc.texture); assert(tex != nullptr); - auto view = rcp<TextureView>(new TextureView(ref_rcp(tex), desc)); + auto view = rcp<TextureViewMetal>(new TextureViewMetal(ref_rcp(tex), desc)); if (tex->m_mtlTexture.textureType == MTLTextureType2DMultisample) return view; @@ -635,7 +578,7 @@ sd.label = @(desc.label); } - auto sampler = rcp<Sampler>(new Sampler()); + auto sampler = rcp<SamplerMetal>(new SamplerMetal()); sampler->m_mtlSampler = [m_mtlDevice newSamplerStateWithDescriptor:sd]; return sampler; } @@ -643,7 +586,7 @@ inline rcp<ShaderModule> ContextMetal::mtlMakeShaderModule( const ShaderModuleDesc& desc) { - auto module = rcp<ShaderModule>(new ShaderModule()); + auto module = rcp<ShaderModuleMetal>(new ShaderModuleMetal()); NSError* err = nil; NSString* source = [[NSString alloc] initWithBytes:desc.code @@ -665,7 +608,7 @@ inline rcp<Pipeline> ContextMetal::mtlMakePipeline(const PipelineDesc& desc, std::string* outError) { - auto pipeline = rcp<Pipeline>(new Pipeline(desc)); + auto pipeline = rcp<PipelineMetal>(new PipelineMetal(desc)); // --- Validate user-supplied layouts against shader binding map --- { @@ -689,14 +632,16 @@ MTLRenderPipelineDescriptor* rpd = [[MTLRenderPipelineDescriptor alloc] init]; + auto vertexModule = lite_rtti_cast<ShaderModuleMetal*>(desc.vertexModule); + assert(vertexModule != nullptr); // Vertex function. - if (desc.vertexModule->m_mtlLibrary == nil) + if (vertexModule->m_mtlLibrary == nil) { if (outError) *outError = "vertex shader library is nil"; return nullptr; } - rpd.vertexFunction = [desc.vertexModule->m_mtlLibrary + rpd.vertexFunction = [vertexModule->m_mtlLibrary newFunctionWithName:@(desc.vertexEntryPoint)]; if (rpd.vertexFunction == nil) { @@ -710,15 +655,16 @@ } // Fragment function. Depth-only pipelines leave it nil — Metal allows // a vertex-only pipeline that writes only depth. - if (desc.fragmentModule != nullptr) + if (auto fragmentModule = + lite_rtti_cast<ShaderModuleMetal*>(desc.fragmentModule)) { - if (desc.fragmentModule->m_mtlLibrary == nil) + if (fragmentModule->m_mtlLibrary == nil) { if (outError) *outError = "fragment shader library is nil"; return nullptr; } - rpd.fragmentFunction = [desc.fragmentModule->m_mtlLibrary + rpd.fragmentFunction = [fragmentModule->m_mtlLibrary newFunctionWithName:@(desc.fragmentEntryPoint)]; if (rpd.fragmentFunction == nil) { @@ -903,7 +849,7 @@ return nullptr; } - auto bg = rcp<BindGroup>(new BindGroup()); + auto bg = rcp<BindGroupMetal>(new BindGroupMetal()); bg->m_context = this; bg->m_layoutRef = ref_rcp(layout); @@ -957,12 +903,14 @@ }; uint32_t nBufs = std::min(desc.uboCount, 8u); + bg->m_mtlBuffers.reserve(nBufs); for (uint32_t i = 0; i < nBufs; i++) { const auto& u = desc.ubos[i]; - bg->m_retainedBuffers.push_back(ref_rcp(u.buffer)); - BindGroup::MTLBufferBinding binding; - binding.buffer = u.buffer->m_mtlBuffer; + auto* buf = lite_rtti_cast<BufferMetal*>(u.buffer); + assert(buf); + BindGroupMetal::MTLBufferBinding binding; + binding.buffer = buf->m_mtlBuffer; binding.offset = u.offset; binding.binding = u.slot; if (!lookupStages(u.slot, @@ -974,49 +922,56 @@ if (binding.hasDynamicOffset) bg->m_dynamicOffsetCount++; bg->m_mtlBuffers.push_back(binding); + bg->m_retainedBuffers.push_back(ref_rcp(u.buffer)); } // Sort UBOs by WGSL @binding so dynamicOffsets[] is consumed in // BindGroupLayout-entry order (WebGPU contract). std::sort(bg->m_mtlBuffers.begin(), bg->m_mtlBuffers.end(), - [](const BindGroup::MTLBufferBinding& a, - const BindGroup::MTLBufferBinding& b) { + [](const BindGroupMetal::MTLBufferBinding& a, + const BindGroupMetal::MTLBufferBinding& b) { return a.binding < b.binding; }); uint32_t nTexs = std::min(desc.textureCount, 8u); + bg->m_mtlTextures.reserve(nTexs); for (uint32_t i = 0; i < nTexs; i++) { const auto& t = desc.textures[i]; - bg->m_retainedViews.push_back(ref_rcp(t.view)); - BindGroup::MTLTextureBinding binding; - binding.texture = t.view->mtlTexture(); + auto* view = lite_rtti_cast<TextureViewMetal*>(t.view); + assert(view); + BindGroupMetal::MTLTextureBinding binding; + binding.texture = view->mtlTexture(); if (!lookupStages(t.slot, BindingKind::sampledTexture, &binding.vsSlot, &binding.fsSlot)) continue; bg->m_mtlTextures.push_back(binding); + bg->m_retainedViews.push_back(ref_rcp(t.view)); } uint32_t nSamps = std::min(desc.samplerCount, 8u); + bg->m_mtlSamplers.reserve(nSamps); for (uint32_t i = 0; i < nSamps; i++) { const auto& s = desc.samplers[i]; - bg->m_retainedSamplers.push_back(ref_rcp(s.sampler)); - BindGroup::MTLSamplerBinding binding; - binding.sampler = s.sampler->m_mtlSampler; + auto* samp = lite_rtti_cast<SamplerMetal*>(s.sampler); + assert(samp); + BindGroupMetal::MTLSamplerBinding binding; + binding.sampler = samp->m_mtlSampler; if (!lookupStages( s.slot, BindingKind::sampler, &binding.vsSlot, &binding.fsSlot)) continue; bg->m_mtlSamplers.push_back(binding); + bg->m_retainedSamplers.push_back(ref_rcp(s.sampler)); } return bg; } -inline RenderPass ContextMetal::mtlBeginRenderPass(const RenderPassDesc& desc, - std::string* outError) +inline std::unique_ptr<RenderPass> ContextMetal::mtlBeginRenderPass( + const RenderPassDesc& desc, std::string* outError) { assert(m_mtlCommandBuffer != nil); @@ -1026,11 +981,14 @@ for (uint32_t i = 0; i < desc.colorCount; ++i) { const auto& ca = desc.colorAttachments[i]; - id<MTLTexture> mtlTex = ca.view->mtlTexture(); + auto* view = lite_rtti_cast<TextureViewMetal*>(ca.view); + assert(view); + id<MTLTexture> mtlTex = view->mtlTexture(); + auto* baseTex = static_cast<TextureMetal*>(view->texture()); rpd.colorAttachments[i].texture = mtlTex; - bool hasView = (mtlTex != ca.view->texture()->mtlTexture()); - rpd.colorAttachments[i].level = hasView ? 0 : ca.view->baseMipLevel(); - rpd.colorAttachments[i].slice = hasView ? 0 : ca.view->baseLayer(); + bool hasView = (mtlTex != baseTex->mtlTexture()); + rpd.colorAttachments[i].level = hasView ? 0 : view->baseMipLevel(); + rpd.colorAttachments[i].slice = hasView ? 0 : view->baseLayer(); rpd.colorAttachments[i].loadAction = oreLoadOpToMTL(ca.loadOp); rpd.colorAttachments[i].storeAction = oreStoreOpToMTL(ca.storeOp); rpd.colorAttachments[i].clearColor = MTLClearColorMake( @@ -1038,14 +996,18 @@ if (ca.resolveTarget) { - id<MTLTexture> resolveTex = ca.resolveTarget->mtlTexture(); + auto* resolveView = + lite_rtti_cast<TextureViewMetal*>(ca.resolveTarget); + assert(resolveView); + id<MTLTexture> resolveTex = resolveView->mtlTexture(); rpd.colorAttachments[i].resolveTexture = resolveTex; - bool resolveHasView = - (resolveTex != ca.resolveTarget->texture()->mtlTexture()); + auto* resolveBaseTex = + static_cast<TextureMetal*>(resolveView->texture()); + bool resolveHasView = (resolveTex != resolveBaseTex->mtlTexture()); rpd.colorAttachments[i].resolveLevel = - resolveHasView ? 0 : ca.resolveTarget->baseMipLevel(); + resolveHasView ? 0 : resolveView->baseMipLevel(); rpd.colorAttachments[i].resolveSlice = - resolveHasView ? 0 : ca.resolveTarget->baseLayer(); + resolveHasView ? 0 : resolveView->baseLayer(); // Honor the user's storeOp on the MSAA buffer: when they // ask for `Store` AND a resolve target, use Metal's // combined `StoreAndMultisampleResolve` so the MSAA @@ -1062,29 +1024,30 @@ if (desc.depthStencil.view) { - id<MTLTexture> depthTex = desc.depthStencil.view->mtlTexture(); - bool depthHasView = - (depthTex != desc.depthStencil.view->texture()->mtlTexture()); + auto* dsView = + lite_rtti_cast<TextureViewMetal*>(desc.depthStencil.view); + assert(dsView); + id<MTLTexture> depthTex = dsView->mtlTexture(); + auto* dsTex = static_cast<TextureMetal*>(dsView->texture()); + bool depthHasView = (depthTex != dsTex->mtlTexture()); rpd.depthAttachment.texture = depthTex; - rpd.depthAttachment.level = - depthHasView ? 0 : desc.depthStencil.view->baseMipLevel(); - rpd.depthAttachment.slice = - depthHasView ? 0 : desc.depthStencil.view->baseLayer(); + rpd.depthAttachment.level = depthHasView ? 0 : dsView->baseMipLevel(); + rpd.depthAttachment.slice = depthHasView ? 0 : dsView->baseLayer(); rpd.depthAttachment.loadAction = oreLoadOpToMTL(desc.depthStencil.depthLoadOp); rpd.depthAttachment.storeAction = oreStoreOpToMTL(desc.depthStencil.depthStoreOp); rpd.depthAttachment.clearDepth = desc.depthStencil.depthClearValue; - TextureFormat depthFmt = desc.depthStencil.view->texture()->format(); + TextureFormat depthFmt = dsTex->format(); if (depthFmt == TextureFormat::depth24plusStencil8 || depthFmt == TextureFormat::depth32floatStencil8) { rpd.stencilAttachment.texture = depthTex; rpd.stencilAttachment.level = - depthHasView ? 0 : desc.depthStencil.view->baseMipLevel(); + depthHasView ? 0 : dsView->baseMipLevel(); rpd.stencilAttachment.slice = - depthHasView ? 0 : desc.depthStencil.view->baseLayer(); + depthHasView ? 0 : dsView->baseLayer(); rpd.stencilAttachment.loadAction = oreLoadOpToMTL(desc.depthStencil.stencilLoadOp); rpd.stencilAttachment.storeAction = @@ -1111,11 +1074,10 @@ encoder.label = @(desc.label); } - RenderPass pass; - pass.m_context = this; - pass.m_mtlEncoder = encoder; - pass.m_mtlCommandBuffer = m_mtlCommandBuffer; - pass.populateAttachmentMetadata(desc); + auto pass = std::make_unique<RenderPassMetal>(this); + pass->m_mtlEncoder = encoder; + pass->m_mtlCommandBuffer = m_mtlCommandBuffer; + pass->populateAttachmentMetadata(desc); return pass; } @@ -1141,7 +1103,7 @@ texDesc.numMipmaps = 1; texDesc.sampleCount = 1; - auto texture = rcp<Texture>(new Texture(texDesc)); + auto texture = rcp<TextureMetal>(new TextureMetal(texDesc)); texture->m_mtlTexture = mtlTexture; TextureViewDesc viewDesc{}; @@ -1152,7 +1114,8 @@ viewDesc.baseLayer = 0; viewDesc.layerCount = 1; - auto view = rcp<TextureView>(new TextureView(std::move(texture), viewDesc)); + auto view = rcp<TextureViewMetal>( + new TextureViewMetal(std::move(texture), viewDesc)); view->m_mtlTextureView = mtlTexture; return view; } @@ -1310,8 +1273,8 @@ // beginRenderPass // ============================================================================ -RenderPass ContextMetal::beginRenderPass(const RenderPassDesc& desc, - std::string* outError) +std::unique_ptr<RenderPass> ContextMetal::beginRenderPass( + const RenderPassDesc& desc, std::string* outError) { finishActiveRenderPass(); return mtlBeginRenderPass(desc, outError); @@ -1346,7 +1309,7 @@ texDesc.numMipmaps = 1; texDesc.sampleCount = 1; - auto texture = rcp<Texture>(new Texture(texDesc)); + auto texture = rcp<TextureMetal>(new TextureMetal(texDesc)); texture->m_mtlTexture = mtlTex; // Borrow — caller owns via RenderImage. TextureViewDesc viewDesc{}; @@ -1357,7 +1320,8 @@ viewDesc.baseLayer = 0; viewDesc.layerCount = 1; - auto view = rcp<TextureView>(new TextureView(std::move(texture), viewDesc)); + auto view = rcp<TextureViewMetal>( + new TextureViewMetal(std::move(texture), viewDesc)); view->m_mtlTextureView = mtlTex; return view; }
diff --git a/renderer/src/ore/metal/ore_pipeline_metal.hpp b/renderer/src/ore/metal/ore_pipeline_metal.hpp new file mode 100644 index 0000000..fa1b3d8 --- /dev/null +++ b/renderer/src/ore/metal/ore_pipeline_metal.hpp
@@ -0,0 +1,22 @@ +#pragma once +#include "rive/renderer/ore/ore_pipeline.hpp" +#import <Metal/Metal.h> + +namespace rive::ore +{ +class ContextMetal; +class RenderPassMetal; + +class PipelineMetal : public LITE_RTTI_OVERRIDE(Pipeline, PipelineMetal) +{ +public: + PipelineMetal(const PipelineDesc& desc) : lite_rtti_override(desc) {} + ~PipelineMetal() override = default; // ARC releases Metal objects + +private: + friend class ContextMetal; + friend class RenderPassMetal; + id<MTLRenderPipelineState> m_mtlPipeline = nil; + id<MTLDepthStencilState> m_mtlDepthStencil = nil; +}; +} // namespace rive::ore
diff --git a/renderer/src/ore/metal/ore_pipeline_metal.mm b/renderer/src/ore/metal/ore_pipeline_metal.mm index 4af28d7..3b1c3e4 100644 --- a/renderer/src/ore/metal/ore_pipeline_metal.mm +++ b/renderer/src/ore/metal/ore_pipeline_metal.mm
@@ -2,18 +2,7 @@ * Copyright 2025 Rive */ -#include "rive/renderer/ore/ore_pipeline.hpp" -#include "rive/renderer/ore/ore_bind_group_layout.hpp" +#include "ore_pipeline_metal.hpp" namespace rive::ore -{ - -#if !defined(ORE_BACKEND_GL) - -void Pipeline::onRefCntReachedZero() const { delete this; } - -void BindGroupLayout::onRefCntReachedZero() const { delete this; } - -#endif // !ORE_BACKEND_GL - -} // namespace rive::ore +{} // namespace rive::ore
diff --git a/renderer/src/ore/metal/ore_pipeline_metal_gl.mm b/renderer/src/ore/metal/ore_pipeline_metal_gl.mm deleted file mode 100644 index 8b1c842..0000000 --- a/renderer/src/ore/metal/ore_pipeline_metal_gl.mm +++ /dev/null
@@ -1,30 +0,0 @@ -/* - * Copyright 2025 Rive - */ - -// Combined Metal + GL Pipeline implementation for macOS. -// Compiled when both ORE_BACKEND_METAL and ORE_BACKEND_GL are active. - -#if defined(ORE_BACKEND_METAL) && defined(ORE_BACKEND_GL) - -#include "rive/renderer/gl/load_gles_extensions.hpp" -#include "rive/renderer/ore/ore_pipeline.hpp" -#include "rive/renderer/ore/ore_bind_group_layout.hpp" - -namespace rive::ore -{ - -void Pipeline::onRefCntReachedZero() const -{ - if (m_glProgram != 0) - { - glDeleteProgram(m_glProgram); - } - delete this; -} - -void BindGroupLayout::onRefCntReachedZero() const { delete this; } - -} // namespace rive::ore - -#endif // ORE_BACKEND_METAL && ORE_BACKEND_GL
diff --git a/renderer/src/ore/metal/ore_render_pass_metal.hpp b/renderer/src/ore/metal/ore_render_pass_metal.hpp new file mode 100644 index 0000000..8def8e8 --- /dev/null +++ b/renderer/src/ore/metal/ore_render_pass_metal.hpp
@@ -0,0 +1,67 @@ +#pragma once +#include "rive/renderer/ore/ore_render_pass.hpp" +#include "rive/renderer/ore/ore_pipeline.hpp" +#include "rive/refcnt.hpp" + +#import <Metal/Metal.h> + +namespace rive::ore +{ +class ContextMetal; + +class RenderPassMetal : public RenderPass +{ +public: + void setPipeline(Pipeline* pipeline) override; + void setVertexBuffer(uint32_t slot, + Buffer* buffer, + uint32_t offset = 0) override; + void setIndexBuffer(Buffer* buffer, + IndexFormat format, + uint32_t offset = 0) override; + void setBindGroup(uint32_t groupIndex, + BindGroup* bg, + const uint32_t* dynamicOffsets = nullptr, + uint32_t dynamicOffsetCount = 0) override; + void setViewport(float x, + float y, + float width, + float height, + float minDepth = 0.0f, + float maxDepth = 1.0f) override; + void setScissorRect(uint32_t x, + uint32_t y, + uint32_t width, + uint32_t height) override; + void setStencilReference(uint32_t ref) override; + void setBlendColor(float r, float g, float b, float a) override; + void draw(uint32_t vertexCount, + uint32_t instanceCount = 1, + uint32_t firstVertex = 0, + uint32_t firstInstance = 0) override; + void drawIndexed(uint32_t indexCount, + uint32_t instanceCount = 1, + uint32_t firstIndex = 0, + int32_t baseVertex = 0, + uint32_t firstInstance = 0) override; + void finish() override; + void validate() const override; + + RenderPassMetal() = default; + RenderPassMetal(Context* context) : RenderPass(context) {} + ~RenderPassMetal() override; + RenderPassMetal(RenderPassMetal&& other) noexcept; + RenderPassMetal& operator=(RenderPassMetal&&) noexcept; + +private: + friend class ContextMetal; + + id<MTLRenderCommandEncoder> m_mtlEncoder = nil; + id<MTLCommandBuffer> m_mtlCommandBuffer = nil; + id<MTLBuffer> m_mtlIndexBuffer = nil; + MTLIndexType m_mtlIndexType = MTLIndexTypeUInt16; + NSUInteger m_mtlIndexBufferOffset = 0; + MTLPrimitiveType m_mtlPrimitiveType = MTLPrimitiveTypeTriangle; + rcp<Pipeline> m_currentPipeline; +}; +} // namespace rive::ore
diff --git a/renderer/src/ore/metal/ore_render_pass_metal.mm b/renderer/src/ore/metal/ore_render_pass_metal.mm index 300f981..5022a9d 100644 --- a/renderer/src/ore/metal/ore_render_pass_metal.mm +++ b/renderer/src/ore/metal/ore_render_pass_metal.mm
@@ -2,13 +2,11 @@ * Copyright 2025 Rive */ -#include "rive/renderer/ore/ore_render_pass.hpp" -#include "rive/renderer/ore/ore_bind_group.hpp" -#include "rive/renderer/ore/ore_buffer.hpp" -#include "rive/renderer/ore/ore_texture.hpp" -#include "rive/renderer/ore/ore_sampler.hpp" -#include "rive/renderer/ore/ore_pipeline.hpp" -#include "rive/renderer/ore/ore_context_metal.hpp" // for RenderPass inline bodies +#include "ore_render_pass_metal.hpp" +#include "ore_buffer_metal.hpp" +#include "ore_pipeline_metal.hpp" +#include "ore_bind_group_metal.hpp" +#include "rive/renderer/ore/ore_context_metal.hpp" #include "rive/rive_types.hpp" #import <Metal/Metal.h> @@ -74,25 +72,76 @@ RIVE_UNREACHABLE(); } -// Must match kMetalVertexBufferBase in ore_context_metal.mm — vertex buffers -// are bound at slots [kMetalVertexBufferBase, ...) to avoid colliding with -// uniform buffers mapped to the low buffer indices ([[buffer(0)]] etc). +// Vertex buffers are bound at slots [kMetalVertexBufferBase, ...) to avoid +// colliding with uniform buffers mapped to the low buffer indices +// ([[buffer(0)]] etc). Must stay in sync with ore_context_metal.mm. static constexpr uint32_t kMetalVertexBufferBase = 16; // ============================================================================ -// Metal implementation helpers (inline) -// Shared between metal-only and metal+gl builds. +// RenderPassMetal // ============================================================================ -inline void RenderPass::mtlSetPipeline(Pipeline* pipeline) +RenderPassMetal::~RenderPassMetal() { - [m_mtlEncoder setRenderPipelineState:pipeline->m_mtlPipeline]; - [m_mtlEncoder setDepthStencilState:pipeline->m_mtlDepthStencil]; + if (!m_finished && m_mtlEncoder != nil) + finish(); +} + +RenderPassMetal::RenderPassMetal(RenderPassMetal&& other) noexcept : + m_mtlEncoder(other.m_mtlEncoder), + m_mtlCommandBuffer(other.m_mtlCommandBuffer), + m_mtlIndexBuffer(other.m_mtlIndexBuffer), + m_mtlIndexType(other.m_mtlIndexType), + m_mtlIndexBufferOffset(other.m_mtlIndexBufferOffset), + m_mtlPrimitiveType(other.m_mtlPrimitiveType), + m_currentPipeline(std::move(other.m_currentPipeline)) +{ + other.m_mtlEncoder = nil; + other.m_mtlCommandBuffer = nil; + other.m_mtlIndexBuffer = nil; +} + +RenderPassMetal& RenderPassMetal::operator=(RenderPassMetal&& other) noexcept +{ + if (this != &other) + { + if (!m_finished && m_mtlEncoder != nil) + finish(); + m_mtlEncoder = other.m_mtlEncoder; + m_mtlCommandBuffer = other.m_mtlCommandBuffer; + m_mtlIndexBuffer = other.m_mtlIndexBuffer; + m_mtlIndexType = other.m_mtlIndexType; + m_mtlIndexBufferOffset = other.m_mtlIndexBufferOffset; + m_mtlPrimitiveType = other.m_mtlPrimitiveType; + m_currentPipeline = std::move(other.m_currentPipeline); + other.m_mtlEncoder = nil; + other.m_mtlCommandBuffer = nil; + other.m_mtlIndexBuffer = nil; + } + return *this; +} + +void RenderPassMetal::validate() const +{ + assert(!m_finished && "RenderPassMetal already finished"); + assert(m_mtlEncoder != nil); +} + +void RenderPassMetal::setPipeline(Pipeline* pipeline) +{ + validate(); + if (!checkPipelineCompat(pipeline)) + return; + + auto* p = static_cast<PipelineMetal*>(pipeline); + [m_mtlEncoder setRenderPipelineState:p->m_mtlPipeline]; + [m_mtlEncoder setDepthStencilState:p->m_mtlDepthStencil]; const auto& desc = pipeline->desc(); [m_mtlEncoder setCullMode:oreCullModeToMTL(desc.cullMode)]; [m_mtlEncoder setFrontFacingWinding:oreWindingToMTL(desc.winding)]; m_mtlPrimitiveType = orePrimitiveTopologyToMTL(desc.topology); + m_currentPipeline = ref_rcp(pipeline); if (desc.depthStencil.depthBias != 0 || desc.depthStencil.depthBiasSlopeScale != 0.0f) @@ -103,43 +152,44 @@ } } -inline void RenderPass::mtlSetVertexBuffer(uint32_t slot, - Buffer* buffer, - uint32_t offset) +void RenderPassMetal::setVertexBuffer(uint32_t slot, + Buffer* buffer, + uint32_t offset) { - [m_mtlEncoder setVertexBuffer:buffer->m_mtlBuffer + validate(); + auto* b = static_cast<BufferMetal*>(buffer); + [m_mtlEncoder setVertexBuffer:b->m_mtlBuffer offset:offset atIndex:slot + kMetalVertexBufferBase]; } -inline void RenderPass::mtlSetIndexBuffer(Buffer* buffer, - IndexFormat format, - uint32_t offset) +void RenderPassMetal::setIndexBuffer(Buffer* buffer, + IndexFormat format, + uint32_t offset) { - m_mtlIndexBuffer = buffer->m_mtlBuffer; + validate(); + auto* b = static_cast<BufferMetal*>(buffer); + m_mtlIndexBuffer = b->m_mtlBuffer; m_mtlIndexType = oreIndexFormatToMTL(format); m_mtlIndexBufferOffset = offset; } -inline void RenderPass::mtlSetBindGroup(BindGroup* bg, - uint32_t groupIndex, - const uint32_t* dynamicOffsets, - uint32_t dynamicOffsetCount) +void RenderPassMetal::setBindGroup(uint32_t groupIndex, + BindGroup* bg, + const uint32_t* dynamicOffsets, + uint32_t dynamicOffsetCount) { + validate(); + m_boundGroups[groupIndex] = ref_rcp(bg); + + auto* bgMetal = static_cast<BindGroupMetal*>(bg); (void)groupIndex; - // m_mtlBuffers is sorted by WGSL `@binding` ascending at makeBindGroup - // time, so `dynamicOffsets[i]` here pairs with the i-th dynamic UBO - // in BindGroupLayout-entry order — matching WebGPU semantics - // independently of the caller's `desc.ubos[]` order. uint32_t dynIdx = 0; - for (auto& b : bg->m_mtlBuffers) + for (auto& b : bgMetal->m_mtlBuffers) { uint32_t offset = b.offset; if (b.hasDynamicOffset && dynIdx < dynamicOffsetCount) offset += dynamicOffsets[dynIdx++]; - // Per-stage emit: skip the stage whose slot is kAbsent so we - // don't clobber another resource's slot in that stage's argument - // table. if (b.vsSlot != BindingMap::kAbsent) [m_mtlEncoder setVertexBuffer:b.buffer offset:offset @@ -149,14 +199,14 @@ offset:offset atIndex:b.fsSlot]; } - for (auto& t : bg->m_mtlTextures) + for (auto& t : bgMetal->m_mtlTextures) { if (t.vsSlot != BindingMap::kAbsent) [m_mtlEncoder setVertexTexture:t.texture atIndex:t.vsSlot]; if (t.fsSlot != BindingMap::kAbsent) [m_mtlEncoder setFragmentTexture:t.texture atIndex:t.fsSlot]; } - for (auto& s : bg->m_mtlSamplers) + for (auto& s : bgMetal->m_mtlSamplers) { if (s.vsSlot != BindingMap::kAbsent) [m_mtlEncoder setVertexSamplerState:s.sampler atIndex:s.vsSlot]; @@ -165,9 +215,10 @@ } } -inline void RenderPass::mtlSetViewport( +void RenderPassMetal::setViewport( float x, float y, float width, float height, float minDepth, float maxDepth) { + validate(); MTLViewport vp = { .originX = (double)x, .originY = (double)y, @@ -179,35 +230,34 @@ [m_mtlEncoder setViewport:vp]; } -inline void RenderPass::mtlSetScissorRect(uint32_t x, - uint32_t y, - uint32_t width, - uint32_t height) +void RenderPassMetal::setScissorRect(uint32_t x, + uint32_t y, + uint32_t width, + uint32_t height) { - MTLScissorRect rect = { - .x = x, - .y = y, - .width = width, - .height = height, - }; + validate(); + MTLScissorRect rect = {.x = x, .y = y, .width = width, .height = height}; [m_mtlEncoder setScissorRect:rect]; } -inline void RenderPass::mtlSetStencilRef(uint32_t ref) +void RenderPassMetal::setStencilReference(uint32_t ref) { + validate(); [m_mtlEncoder setStencilReferenceValue:ref]; } -inline void RenderPass::mtlSetBlendColor(float r, float g, float b, float a) +void RenderPassMetal::setBlendColor(float r, float g, float b, float a) { + validate(); [m_mtlEncoder setBlendColorRed:r green:g blue:b alpha:a]; } -inline void RenderPass::mtlDraw(uint32_t vertexCount, - uint32_t instanceCount, - uint32_t firstVertex, - uint32_t firstInstance) +void RenderPassMetal::draw(uint32_t vertexCount, + uint32_t instanceCount, + uint32_t firstVertex, + uint32_t firstInstance) { + validate(); [m_mtlEncoder drawPrimitives:m_mtlPrimitiveType vertexStart:firstVertex vertexCount:vertexCount @@ -215,12 +265,13 @@ baseInstance:firstInstance]; } -inline void RenderPass::mtlDrawIndexed(uint32_t indexCount, - uint32_t instanceCount, - uint32_t firstIndex, - int32_t baseVertex, - uint32_t firstInstance) +void RenderPassMetal::drawIndexed(uint32_t indexCount, + uint32_t instanceCount, + uint32_t firstIndex, + int32_t baseVertex, + uint32_t firstInstance) { + validate(); assert(m_mtlIndexBuffer != nil && "Must call setIndexBuffer before drawIndexed"); @@ -240,165 +291,19 @@ baseInstance:firstInstance]; } -inline void RenderPass::mtlFinish() -{ - [m_mtlEncoder endEncoding]; - m_mtlEncoder = nil; -} - -// ============================================================================ -// RenderPass -// ============================================================================ - -// When both Metal and GL are compiled (macOS), ore_render_pass_metal_gl.mm -// provides all RenderPass method bodies with runtime dispatch. This file -// only contributes the static helper functions in that case. -#if !defined(ORE_BACKEND_GL) - -RenderPass::~RenderPass() -{ - if (!m_finished && m_mtlEncoder != nil) - { - finish(); - } -} - -RenderPass::RenderPass(RenderPass&& other) noexcept : - m_mtlEncoder(other.m_mtlEncoder), - m_mtlCommandBuffer(other.m_mtlCommandBuffer), - m_mtlIndexBuffer(other.m_mtlIndexBuffer), - m_mtlIndexType(other.m_mtlIndexType), - m_mtlIndexBufferOffset(other.m_mtlIndexBufferOffset), - m_mtlPrimitiveType(other.m_mtlPrimitiveType) -{ - moveCrossBackendFieldsFrom(other); - other.m_mtlEncoder = nil; - other.m_mtlCommandBuffer = nil; - other.m_mtlIndexBuffer = nil; -} - -RenderPass& RenderPass::operator=(RenderPass&& other) noexcept -{ - if (this != &other) - { - if (!m_finished && m_mtlEncoder != nil) - { - finish(); - } - moveCrossBackendFieldsFrom(other); - m_mtlEncoder = other.m_mtlEncoder; - m_mtlCommandBuffer = other.m_mtlCommandBuffer; - m_mtlIndexBuffer = other.m_mtlIndexBuffer; - m_mtlIndexType = other.m_mtlIndexType; - m_mtlIndexBufferOffset = other.m_mtlIndexBufferOffset; - m_mtlPrimitiveType = other.m_mtlPrimitiveType; - other.m_mtlEncoder = nil; - other.m_mtlCommandBuffer = nil; - other.m_mtlIndexBuffer = nil; - } - return *this; -} - -void RenderPass::validate() const -{ - assert(!m_finished && "RenderPass already finished"); - assert(m_mtlEncoder != nil); -} - -void RenderPass::setPipeline(Pipeline* pipeline) -{ - validate(); - if (!checkPipelineCompat(pipeline)) - return; - mtlSetPipeline(pipeline); -} - -void RenderPass::setVertexBuffer(uint32_t slot, Buffer* buffer, uint32_t offset) -{ - validate(); - mtlSetVertexBuffer(slot, buffer, offset); -} - -void RenderPass::setIndexBuffer(Buffer* buffer, - IndexFormat format, - uint32_t offset) -{ - validate(); - mtlSetIndexBuffer(buffer, format, offset); -} - -void RenderPass::setBindGroup(uint32_t groupIndex, - BindGroup* bg, - const uint32_t* dynamicOffsets, - uint32_t dynamicOffsetCount) -{ - validate(); - m_boundGroups[groupIndex] = ref_rcp(bg); - mtlSetBindGroup(bg, groupIndex, dynamicOffsets, dynamicOffsetCount); -} - -void RenderPass::setViewport( - float x, float y, float width, float height, float minDepth, float maxDepth) -{ - validate(); - mtlSetViewport(x, y, width, height, minDepth, maxDepth); -} - -void RenderPass::setScissorRect(uint32_t x, - uint32_t y, - uint32_t width, - uint32_t height) -{ - validate(); - mtlSetScissorRect(x, y, width, height); -} - -void RenderPass::setStencilReference(uint32_t ref) -{ - validate(); - mtlSetStencilRef(ref); -} - -void RenderPass::setBlendColor(float r, float g, float b, float a) -{ - validate(); - mtlSetBlendColor(r, g, b, a); -} - -void RenderPass::draw(uint32_t vertexCount, - uint32_t instanceCount, - uint32_t firstVertex, - uint32_t firstInstance) -{ - validate(); - mtlDraw(vertexCount, instanceCount, firstVertex, firstInstance); -} - -void RenderPass::drawIndexed(uint32_t indexCount, - uint32_t instanceCount, - uint32_t firstIndex, - int32_t baseVertex, - uint32_t firstInstance) -{ - validate(); - mtlDrawIndexed( - indexCount, instanceCount, firstIndex, baseVertex, firstInstance); -} - -void RenderPass::finish() +void RenderPassMetal::finish() { if (m_finished) return; m_finished = true; if (m_mtlEncoder != nil) { - mtlFinish(); + [m_mtlEncoder endEncoding]; + m_mtlEncoder = nil; } - // Release bound BindGroup refs. for (auto& bg : m_boundGroups) bg.reset(); + m_currentPipeline.reset(); } -#endif // !ORE_BACKEND_GL - } // namespace rive::ore
diff --git a/renderer/src/ore/metal/ore_render_pass_metal_gl.mm b/renderer/src/ore/metal/ore_render_pass_metal_gl.mm deleted file mode 100644 index 1c2ca8c..0000000 --- a/renderer/src/ore/metal/ore_render_pass_metal_gl.mm +++ /dev/null
@@ -1,537 +0,0 @@ -/* - * Copyright 2025 Rive - */ - -// Combined Metal + GL RenderPass implementation for macOS. -// Compiled when both ORE_BACKEND_METAL and ORE_BACKEND_GL are active. -// Provides all RenderPass method definitions with runtime dispatch: -// passes initialized via the Metal context path (m_mtlEncoder != nil) use -// Metal; passes initialized via the GL context path (m_context != nullptr) -// use GL. - -#if defined(ORE_BACKEND_METAL) && defined(ORE_BACKEND_GL) - -// Pull in Metal static helpers (orePrimitiveTopologyToMTL, etc.). -// The !defined(ORE_BACKEND_GL) guard in ore_render_pass_metal.mm excludes -// RenderPass method bodies, so we get only the static helper functions. -#include "ore_render_pass_metal.mm" - -// Pull in GL static helpers (oreTopologyToGL, oreBlendFactorToGL, etc.). -// The !defined(ORE_BACKEND_METAL) guard in ore_render_pass_gl.cpp excludes -// RenderPass method bodies, so we get only the static helper functions. -#include "../gl/ore_render_pass_gl.cpp" - -#include "rive/renderer/gl/load_gles_extensions.hpp" -#include "rive/renderer/ore/ore_render_pass.hpp" -#include "rive/renderer/ore/ore_bind_group.hpp" -#include "rive/renderer/ore/ore_buffer.hpp" -#include "rive/renderer/ore/ore_texture.hpp" -#include "rive/renderer/ore/ore_sampler.hpp" -#include "rive/renderer/ore/ore_pipeline.hpp" - -namespace rive::ore -{ - -RenderPass::~RenderPass() -{ - if (!m_finished) - { - if (m_mtlEncoder != nil || m_context != nullptr) - finish(); - } -} - -RenderPass::RenderPass(RenderPass&& other) noexcept : - // Metal members - m_mtlEncoder(other.m_mtlEncoder), - m_mtlCommandBuffer(other.m_mtlCommandBuffer), - m_mtlIndexBuffer(other.m_mtlIndexBuffer), - m_mtlIndexType(other.m_mtlIndexType), - m_mtlIndexBufferOffset(other.m_mtlIndexBufferOffset), - m_mtlPrimitiveType(other.m_mtlPrimitiveType), - // GL members - m_glFBO(other.m_glFBO), - m_glVAO(other.m_glVAO), - m_ownsFBO(other.m_ownsFBO), - m_ownsVAO(other.m_ownsVAO), - m_currentPipeline(std::move(other.m_currentPipeline)), - m_viewportWidth(other.m_viewportWidth), - m_viewportHeight(other.m_viewportHeight), - m_maxSamplerSlot(other.m_maxSamplerSlot), - m_maxAttribSlot(other.m_maxAttribSlot), - m_usedSamplers(other.m_usedSamplers), - m_usedAttribs(other.m_usedAttribs) -{ - moveCrossBackendFieldsFrom(other); - other.m_mtlEncoder = nil; - other.m_mtlCommandBuffer = nil; - other.m_mtlIndexBuffer = nil; - other.m_ownsFBO = false; - other.m_ownsVAO = false; -} - -RenderPass& RenderPass::operator=(RenderPass&& other) noexcept -{ - if (this != &other) - { - if (!m_finished && (m_mtlEncoder != nil || m_context != nullptr)) - finish(); - moveCrossBackendFieldsFrom(other); - m_mtlEncoder = other.m_mtlEncoder; - m_mtlCommandBuffer = other.m_mtlCommandBuffer; - m_mtlIndexBuffer = other.m_mtlIndexBuffer; - m_mtlIndexType = other.m_mtlIndexType; - m_mtlIndexBufferOffset = other.m_mtlIndexBufferOffset; - m_mtlPrimitiveType = other.m_mtlPrimitiveType; - m_glFBO = other.m_glFBO; - m_glVAO = other.m_glVAO; - m_ownsFBO = other.m_ownsFBO; - m_ownsVAO = other.m_ownsVAO; - m_currentPipeline = std::move(other.m_currentPipeline); - m_viewportWidth = other.m_viewportWidth; - m_viewportHeight = other.m_viewportHeight; - m_maxSamplerSlot = other.m_maxSamplerSlot; - m_maxAttribSlot = other.m_maxAttribSlot; - m_usedSamplers = other.m_usedSamplers; - m_usedAttribs = other.m_usedAttribs; - other.m_mtlEncoder = nil; - other.m_mtlCommandBuffer = nil; - other.m_mtlIndexBuffer = nil; - other.m_ownsFBO = false; - other.m_ownsVAO = false; - } - return *this; -} - -void RenderPass::validate() const -{ - assert(!m_finished && "RenderPass already finished"); - assert(m_mtlEncoder != nil || m_context != nullptr); -} - -void RenderPass::setPipeline(Pipeline* pipeline) -{ - validate(); - if (!checkPipelineCompat(pipeline)) - return; - if (m_mtlEncoder != nil) - { - mtlSetPipeline(pipeline); - return; - } - - // GL path. - m_currentPipeline = ref_rcp(pipeline); - const auto& desc = pipeline->desc(); - glUseProgram(pipeline->m_glProgram); - - if (desc.cullMode == CullMode::none) - { - glDisable(GL_CULL_FACE); - } - else - { - glEnable(GL_CULL_FACE); - glCullFace(desc.cullMode == CullMode::front ? GL_FRONT : GL_BACK); - } - - glFrontFace(desc.winding == FaceWinding::counterClockwise ? GL_CCW : GL_CW); - - if (desc.depthStencil.depthCompare != CompareFunction::always || - desc.depthStencil.depthWriteEnabled) - { - glEnable(GL_DEPTH_TEST); - glDepthFunc(oreCompareFunctionToGL(desc.depthStencil.depthCompare)); - glDepthMask(desc.depthStencil.depthWriteEnabled ? GL_TRUE : GL_FALSE); - } - else - { - glDisable(GL_DEPTH_TEST); - } - - if (desc.depthStencil.depthBias != 0 || - desc.depthStencil.depthBiasSlopeScale != 0.0f) - { - glEnable(GL_POLYGON_OFFSET_FILL); - glPolygonOffset(desc.depthStencil.depthBiasSlopeScale, - static_cast<float>(desc.depthStencil.depthBias)); - } - else - { - glDisable(GL_POLYGON_OFFSET_FILL); - } - - bool hasStencil = (desc.stencilFront.compare != CompareFunction::always || - desc.stencilFront.failOp != StencilOp::keep || - desc.stencilFront.depthFailOp != StencilOp::keep || - desc.stencilFront.passOp != StencilOp::keep || - desc.stencilBack.compare != CompareFunction::always || - desc.stencilBack.failOp != StencilOp::keep || - desc.stencilBack.depthFailOp != StencilOp::keep || - desc.stencilBack.passOp != StencilOp::keep); - - if (hasStencil) - { - glEnable(GL_STENCIL_TEST); - glStencilMaskSeparate(GL_FRONT, desc.stencilWriteMask); - glStencilMaskSeparate(GL_BACK, desc.stencilWriteMask); - glStencilFuncSeparate(GL_FRONT, - oreCompareFunctionToGL(desc.stencilFront.compare), - 0, - desc.stencilReadMask); - glStencilFuncSeparate(GL_BACK, - oreCompareFunctionToGL(desc.stencilBack.compare), - 0, - desc.stencilReadMask); - glStencilOpSeparate(GL_FRONT, - oreStencilOpToGL(desc.stencilFront.failOp), - oreStencilOpToGL(desc.stencilFront.depthFailOp), - oreStencilOpToGL(desc.stencilFront.passOp)); - glStencilOpSeparate(GL_BACK, - oreStencilOpToGL(desc.stencilBack.failOp), - oreStencilOpToGL(desc.stencilBack.depthFailOp), - oreStencilOpToGL(desc.stencilBack.passOp)); - } - else - { - glDisable(GL_STENCIL_TEST); - } - - if (desc.colorCount > 0 && desc.colorTargets[0].blendEnabled) - { - glEnable(GL_BLEND); - const auto& b = desc.colorTargets[0].blend; - glBlendFuncSeparate(oreBlendFactorToGL(b.srcColor), - oreBlendFactorToGL(b.dstColor), - oreBlendFactorToGL(b.srcAlpha), - oreBlendFactorToGL(b.dstAlpha)); - glBlendEquationSeparate(oreBlendOpToGL(b.colorOp), - oreBlendOpToGL(b.alphaOp)); - } - else - { - glDisable(GL_BLEND); - } - - if (desc.colorCount > 0) - { - auto mask = desc.colorTargets[0].writeMask; - glColorMask((mask & ColorWriteMask::red) != ColorWriteMask::none, - (mask & ColorWriteMask::green) != ColorWriteMask::none, - (mask & ColorWriteMask::blue) != ColorWriteMask::none, - (mask & ColorWriteMask::alpha) != ColorWriteMask::none); - } -} - -void RenderPass::setVertexBuffer(uint32_t slot, Buffer* buffer, uint32_t offset) -{ - validate(); - if (m_mtlEncoder != nil) - { - mtlSetVertexBuffer(slot, buffer, offset); - return; - } - - // GL path. - assert(m_currentPipeline != nullptr && "setPipeline must be called first"); - assert(slot < m_currentPipeline->desc().vertexBufferCount); - - const auto& layout = m_currentPipeline->desc().vertexBuffers[slot]; - glBindBuffer(GL_ARRAY_BUFFER, buffer->m_glBuffer); - - for (uint32_t i = 0; i < layout.attributeCount; ++i) - { - const auto& attr = layout.attributes[i]; - GLVertexInfo info = oreVertexFormatToGL(attr.format); - glEnableVertexAttribArray(attr.shaderSlot); - - bool isIntType = - (info.type == GL_UNSIGNED_INT || info.type == GL_INT || - info.type == GL_UNSIGNED_BYTE || info.type == GL_BYTE || - info.type == GL_UNSIGNED_SHORT || info.type == GL_SHORT) && - !info.normalized; - - if (isIntType) - { - glVertexAttribIPointer( - attr.shaderSlot, - info.count, - info.type, - layout.stride, - reinterpret_cast<const void*>( - static_cast<uintptr_t>(attr.offset + offset))); - } - else - { - glVertexAttribPointer( - attr.shaderSlot, - info.count, - info.type, - info.normalized, - layout.stride, - reinterpret_cast<const void*>( - static_cast<uintptr_t>(attr.offset + offset))); - } - - if (layout.stepMode == VertexStepMode::instance) - glVertexAttribDivisor(attr.shaderSlot, 1); - else - glVertexAttribDivisor(attr.shaderSlot, 0); - - if (!m_usedAttribs || attr.shaderSlot > m_maxAttribSlot) - m_maxAttribSlot = attr.shaderSlot; - m_usedAttribs = true; - } -} - -void RenderPass::setIndexBuffer(Buffer* buffer, - IndexFormat format, - uint32_t offset) -{ - validate(); - if (m_mtlEncoder != nil) - { - mtlSetIndexBuffer(buffer, format, offset); - return; - } - - // GL path. - glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, buffer->m_glBuffer); - m_glIndexFormat = format; - (void)offset; -} - -void RenderPass::setBindGroup(uint32_t groupIndex, - BindGroup* bg, - const uint32_t* dynamicOffsets, - uint32_t dynamicOffsetCount) -{ - validate(); - m_boundGroups[groupIndex] = ref_rcp(bg); - - if (m_mtlEncoder != nil) - { - mtlSetBindGroup(bg, groupIndex, dynamicOffsets, dynamicOffsetCount); - return; - } - - // GL path. - (void)groupIndex; - uint32_t dynIdx = 0; - for (auto& b : bg->m_glUBOs) - { - uint32_t offset = b.offset; - if (b.hasDynamicOffset && dynIdx < dynamicOffsetCount) - offset += dynamicOffsets[dynIdx++]; - glBindBufferRange(GL_UNIFORM_BUFFER, b.slot, b.buffer, offset, b.size); - } - for (auto& t : bg->m_glTextures) - { - glActiveTexture(GL_TEXTURE0 + t.slot); - glBindTexture(t.target, t.texture); - if (!m_usedSamplers || t.slot > m_maxSamplerSlot) - m_maxSamplerSlot = t.slot; - m_usedSamplers = true; - } - for (auto& s : bg->m_glSamplers) - { - glBindSampler(s.slot, s.sampler); - } -} - -void RenderPass::setViewport( - float x, float y, float width, float height, float minDepth, float maxDepth) -{ - validate(); - if (m_mtlEncoder != nil) - { - mtlSetViewport(x, y, width, height, minDepth, maxDepth); - return; - } - - // GL path. - m_viewportWidth = static_cast<uint32_t>(width); - m_viewportHeight = static_cast<uint32_t>(height); - glViewport(static_cast<GLint>(x), - static_cast<GLint>(y), - static_cast<GLsizei>(width), - static_cast<GLsizei>(height)); - glDepthRangef(minDepth, maxDepth); -} - -void RenderPass::setScissorRect(uint32_t x, - uint32_t y, - uint32_t width, - uint32_t height) -{ - validate(); - if (m_mtlEncoder != nil) - { - mtlSetScissorRect(x, y, width, height); - return; - } - - // GL path. - glEnable(GL_SCISSOR_TEST); - glScissor(x, y, width, height); -} - -void RenderPass::setStencilReference(uint32_t ref) -{ - validate(); - if (m_mtlEncoder != nil) - { - mtlSetStencilRef(ref); - return; - } - - // GL path. - if (m_currentPipeline) - { - const auto& desc = m_currentPipeline->desc(); - glStencilFuncSeparate(GL_FRONT, - oreCompareFunctionToGL(desc.stencilFront.compare), - ref, - desc.stencilReadMask); - glStencilFuncSeparate(GL_BACK, - oreCompareFunctionToGL(desc.stencilBack.compare), - ref, - desc.stencilReadMask); - } -} - -void RenderPass::setBlendColor(float r, float g, float b, float a) -{ - validate(); - if (m_mtlEncoder != nil) - { - mtlSetBlendColor(r, g, b, a); - return; - } - - // GL path. - glBlendColor(r, g, b, a); -} - -void RenderPass::draw(uint32_t vertexCount, - uint32_t instanceCount, - uint32_t firstVertex, - uint32_t firstInstance) -{ - validate(); - if (m_mtlEncoder != nil) - { - mtlDraw(vertexCount, instanceCount, firstVertex, firstInstance); - return; - } - - // GL path. - assert(m_currentPipeline != nullptr); - GLenum mode = oreTopologyToGL(m_currentPipeline->desc().topology); - (void)firstInstance; - if (instanceCount > 1) - glDrawArraysInstanced(mode, firstVertex, vertexCount, instanceCount); - else - glDrawArrays(mode, firstVertex, vertexCount); -} - -void RenderPass::drawIndexed(uint32_t indexCount, - uint32_t instanceCount, - uint32_t firstIndex, - int32_t baseVertex, - uint32_t firstInstance) -{ - validate(); - if (m_mtlEncoder != nil) - { - mtlDrawIndexed( - indexCount, instanceCount, firstIndex, baseVertex, firstInstance); - return; - } - - // GL path. - assert(m_currentPipeline != nullptr); - GLenum mode = oreTopologyToGL(m_currentPipeline->desc().topology); - GLenum indexType = (m_glIndexFormat == IndexFormat::uint32) - ? GL_UNSIGNED_INT - : GL_UNSIGNED_SHORT; - uint32_t indexSize = - (indexType == GL_UNSIGNED_INT) ? sizeof(uint32_t) : sizeof(uint16_t); - const void* offset = reinterpret_cast<const void*>( - static_cast<uintptr_t>(firstIndex * indexSize)); - (void)baseVertex; - (void)firstInstance; - if (instanceCount > 1) - glDrawElementsInstanced( - mode, indexCount, indexType, offset, instanceCount); - else - glDrawElements(mode, indexCount, indexType, offset); -} - -void RenderPass::finish() -{ - if (m_finished) - return; - m_finished = true; - - // Release bound BindGroup refs. - for (auto& bg : m_boundGroups) - bg.reset(); - - if (m_mtlEncoder != nil) - { - mtlFinish(); - return; - } - - // GL path. - glDisable(GL_SCISSOR_TEST); - glDisable(GL_BLEND); - glDisable(GL_DEPTH_TEST); - glDisable(GL_STENCIL_TEST); - glDisable(GL_CULL_FACE); - glDisable(GL_POLYGON_OFFSET_FILL); - glDepthMask(GL_TRUE); - glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE); - - if (m_usedSamplers) - { - for (uint32_t i = 0; i <= m_maxSamplerSlot; ++i) - { - glActiveTexture(GL_TEXTURE0 + i); - glBindTexture(GL_TEXTURE_2D, 0); - glBindTexture(GL_TEXTURE_CUBE_MAP, 0); - glBindSampler(i, 0); - } - glActiveTexture(GL_TEXTURE0); - } - - if (m_usedAttribs) - { - for (uint32_t i = 0; i <= m_maxAttribSlot; ++i) - glDisableVertexAttribArray(i); - } - - glBindBuffer(GL_ARRAY_BUFFER, 0); - // NOTE: GL_ELEMENT_ARRAY_BUFFER is VAO state — do NOT unbind it here. - // The per-pass VAO deletion below handles cleanup. Unbinding it could - // corrupt the host renderer's VAO on some WebGL2 implementations. - - if (m_ownsVAO && m_glVAO != 0) - { - glDeleteVertexArrays(1, &m_glVAO); - m_glVAO = 0; - } - - if (m_ownsFBO && m_glFBO != 0) - { - glDeleteFramebuffers(1, &m_glFBO); - } - glBindFramebuffer(GL_FRAMEBUFFER, 0); - - m_context = nullptr; -} - -} // namespace rive::ore - -#endif // ORE_BACKEND_METAL && ORE_BACKEND_GL
diff --git a/renderer/src/ore/metal/ore_sampler_metal.hpp b/renderer/src/ore/metal/ore_sampler_metal.hpp new file mode 100644 index 0000000..65fda00 --- /dev/null +++ b/renderer/src/ore/metal/ore_sampler_metal.hpp
@@ -0,0 +1,19 @@ +#pragma once +#include "rive/renderer/ore/ore_sampler.hpp" +#import <Metal/Metal.h> + +namespace rive::ore +{ +class ContextMetal; + +class SamplerMetal : public LITE_RTTI_OVERRIDE(Sampler, SamplerMetal) +{ +public: + SamplerMetal() = default; + ~SamplerMetal() override = default; // ARC releases m_mtlSampler + +private: + friend class ContextMetal; + id<MTLSamplerState> m_mtlSampler = nil; +}; +} // namespace rive::ore
diff --git a/renderer/src/ore/metal/ore_sampler_metal.mm b/renderer/src/ore/metal/ore_sampler_metal.mm index 2a40b57..545a697 100644 --- a/renderer/src/ore/metal/ore_sampler_metal.mm +++ b/renderer/src/ore/metal/ore_sampler_metal.mm
@@ -2,15 +2,7 @@ * Copyright 2025 Rive */ -#include "rive/renderer/ore/ore_sampler.hpp" +#include "ore_sampler_metal.hpp" namespace rive::ore -{ - -#if !defined(ORE_BACKEND_GL) - -void Sampler::onRefCntReachedZero() const { delete this; } - -#endif // !ORE_BACKEND_GL - -} // namespace rive::ore +{} // namespace rive::ore
diff --git a/renderer/src/ore/metal/ore_sampler_metal_gl.mm b/renderer/src/ore/metal/ore_sampler_metal_gl.mm deleted file mode 100644 index dd54110..0000000 --- a/renderer/src/ore/metal/ore_sampler_metal_gl.mm +++ /dev/null
@@ -1,28 +0,0 @@ -/* - * Copyright 2025 Rive - */ - -// Combined Metal + GL Sampler implementation for macOS. -// Compiled when both ORE_BACKEND_METAL and ORE_BACKEND_GL are active. - -#if defined(ORE_BACKEND_METAL) && defined(ORE_BACKEND_GL) - -#include "rive/renderer/gl/load_gles_extensions.hpp" -#include "rive/renderer/ore/ore_sampler.hpp" - -namespace rive::ore -{ - -void Sampler::onRefCntReachedZero() const -{ - if (m_glSampler != 0) - { - GLuint samp = m_glSampler; - glDeleteSamplers(1, &samp); - } - delete this; -} - -} // namespace rive::ore - -#endif // ORE_BACKEND_METAL && ORE_BACKEND_GL
diff --git a/renderer/src/ore/metal/ore_shader_module_metal.hpp b/renderer/src/ore/metal/ore_shader_module_metal.hpp new file mode 100644 index 0000000..bc7fed8 --- /dev/null +++ b/renderer/src/ore/metal/ore_shader_module_metal.hpp
@@ -0,0 +1,20 @@ +#pragma once +#include "rive/renderer/ore/ore_shader_module.hpp" +#import <Metal/Metal.h> + +namespace rive::ore +{ +class ContextMetal; + +class ShaderModuleMetal + : public LITE_RTTI_OVERRIDE(ShaderModule, ShaderModuleMetal) +{ +public: + ShaderModuleMetal() = default; + ~ShaderModuleMetal() override = default; // ARC releases m_mtlLibrary + +private: + friend class ContextMetal; + id<MTLLibrary> m_mtlLibrary = nil; +}; +} // namespace rive::ore
diff --git a/renderer/src/ore/metal/ore_shader_module_metal.mm b/renderer/src/ore/metal/ore_shader_module_metal.mm index 8778b1a..17b5cd6 100644 --- a/renderer/src/ore/metal/ore_shader_module_metal.mm +++ b/renderer/src/ore/metal/ore_shader_module_metal.mm
@@ -2,15 +2,4 @@ * Copyright 2025 Rive */ -#include "rive/renderer/ore/ore_shader_module.hpp" - -namespace rive::ore -{ - -#if !defined(ORE_BACKEND_GL) - -void ShaderModule::onRefCntReachedZero() const { delete this; } - -#endif // !ORE_BACKEND_GL - -} // namespace rive::ore +#include "ore_shader_module_metal.hpp"
diff --git a/renderer/src/ore/metal/ore_shader_module_metal_gl.mm b/renderer/src/ore/metal/ore_shader_module_metal_gl.mm deleted file mode 100644 index 53b6aec..0000000 --- a/renderer/src/ore/metal/ore_shader_module_metal_gl.mm +++ /dev/null
@@ -1,27 +0,0 @@ -/* - * Copyright 2025 Rive - */ - -// Combined Metal + GL ShaderModule implementation for macOS. -// Compiled when both ORE_BACKEND_METAL and ORE_BACKEND_GL are active. - -#if defined(ORE_BACKEND_METAL) && defined(ORE_BACKEND_GL) - -#include "rive/renderer/gl/load_gles_extensions.hpp" -#include "rive/renderer/ore/ore_shader_module.hpp" - -namespace rive::ore -{ - -void ShaderModule::onRefCntReachedZero() const -{ - if (m_glShader != 0) - { - glDeleteShader(m_glShader); - } - delete this; -} - -} // namespace rive::ore - -#endif // ORE_BACKEND_METAL && ORE_BACKEND_GL
diff --git a/renderer/src/ore/metal/ore_texture_metal.hpp b/renderer/src/ore/metal/ore_texture_metal.hpp new file mode 100644 index 0000000..128f2bc --- /dev/null +++ b/renderer/src/ore/metal/ore_texture_metal.hpp
@@ -0,0 +1,41 @@ +#pragma once +#include "rive/renderer/ore/ore_texture.hpp" +#import <Metal/Metal.h> + +namespace rive::ore +{ +class ContextMetal; + +class TextureMetal : public LITE_RTTI_OVERRIDE(Texture, TextureMetal) +{ +public: + TextureMetal(const TextureDesc& desc) : lite_rtti_override(desc) {} + ~TextureMetal() override = default; // ARC releases m_mtlTexture + void upload(const TextureDataDesc& data) override; + id<MTLTexture> mtlTexture() const { return m_mtlTexture; } + +private: + friend class ContextMetal; + id<MTLTexture> m_mtlTexture = nil; +}; + +class TextureViewMetal + : public LITE_RTTI_OVERRIDE(TextureView, TextureViewMetal) +{ +public: + TextureViewMetal(rcp<Texture> texture, const TextureViewDesc& desc) : + lite_rtti_override(std::move(texture), desc) + {} + ~TextureViewMetal() override = default; + id<MTLTexture> mtlTexture() const + { + return m_mtlTextureView + ? m_mtlTextureView + : static_cast<TextureMetal*>(m_texture.get())->mtlTexture(); + } + +private: + friend class ContextMetal; + id<MTLTexture> m_mtlTextureView = nil; +}; +} // namespace rive::ore
diff --git a/renderer/src/ore/metal/ore_texture_metal.mm b/renderer/src/ore/metal/ore_texture_metal.mm index 8fe293d..81c6158 100644 --- a/renderer/src/ore/metal/ore_texture_metal.mm +++ b/renderer/src/ore/metal/ore_texture_metal.mm
@@ -2,7 +2,7 @@ * Copyright 2025 Rive */ -#include "rive/renderer/ore/ore_texture.hpp" +#include "ore_texture_metal.hpp" #include "rive/rive_types.hpp" #import <Metal/Metal.h> @@ -10,9 +10,7 @@ namespace rive::ore { -#if !defined(ORE_BACKEND_GL) - -void Texture::upload(const TextureDataDesc& data) +void TextureMetal::upload(const TextureDataDesc& data) { assert(m_mtlTexture != nil); assert(data.data != nullptr); @@ -22,10 +20,7 @@ // Apple's `replaceRegion:` docs require `bytesPerImage = 0` for // non-array 2D textures (Metal API Validation aborts on any other - // value). For texture3D / array2D / cubeArray the value is the - // per-slice stride. Pre-fix this passed - // `bytesPerRow * rowsPerImage` unconditionally, which trips the - // validator on every 2D upload. + // value). For texture3D / array2D the value is the per-slice stride. const NSUInteger mtlBytesPerImage = (m_type == TextureType::texture3D || m_type == TextureType::array2D) ? static_cast<NSUInteger>(data.bytesPerRow) * data.rowsPerImage @@ -39,10 +34,4 @@ bytesPerImage:mtlBytesPerImage]; } -void Texture::onRefCntReachedZero() const { delete this; } - -void TextureView::onRefCntReachedZero() const { delete this; } - -#endif // !ORE_BACKEND_GL - } // namespace rive::ore
diff --git a/renderer/src/ore/metal/ore_texture_metal_gl.mm b/renderer/src/ore/metal/ore_texture_metal_gl.mm deleted file mode 100644 index 7c0ac6c..0000000 --- a/renderer/src/ore/metal/ore_texture_metal_gl.mm +++ /dev/null
@@ -1,113 +0,0 @@ -/* - * Copyright 2025 Rive - */ - -// Combined Metal + GL Texture implementation for macOS. -// Compiled when both ORE_BACKEND_METAL and ORE_BACKEND_GL are active. - -#if defined(ORE_BACKEND_METAL) && defined(ORE_BACKEND_GL) - -#include "rive/renderer/gl/load_gles_extensions.hpp" -#include "rive/renderer/ore/ore_texture.hpp" -#include "rive/rive_types.hpp" - -#import <Metal/Metal.h> - -// Pull in GL static helpers (format conversion functions). -// The #ifndef ORE_BACKEND_METAL guard in ore_texture_gl.cpp excludes -// class method bodies, so we get only the helper functions. -#include "../gl/ore_texture_gl.cpp" - -namespace rive::ore -{ - -void Texture::upload(const TextureDataDesc& data) -{ - assert(data.data != nullptr); - - if (m_glTexture != 0) - { - glBindTexture(m_glTarget, m_glTexture); - - GLenum internalFmt = oreFormatToGLInternal(m_format); - GLenum format = oreFormatToGLFormat(m_format); - GLenum type = oreFormatToGLType(m_format); - (void)internalFmt; - - if (m_glTarget == GL_TEXTURE_3D || m_glTarget == GL_TEXTURE_2D_ARRAY) - { - glTexSubImage3D(m_glTarget, - data.mipLevel, - data.x, - data.y, - data.layer, - data.width, - data.height, - data.depth, - format, - type, - data.data); - } - else if (m_glTarget == GL_TEXTURE_CUBE_MAP) - { - glTexSubImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + data.layer, - data.mipLevel, - data.x, - data.y, - data.width, - data.height, - format, - type, - data.data); - } - else - { - glTexSubImage2D(m_glTarget, - data.mipLevel, - data.x, - data.y, - data.width, - data.height, - format, - type, - data.data); - } - - glBindTexture(m_glTarget, 0); - return; - } - - assert(m_mtlTexture != nil); - MTLRegion region = MTLRegionMake3D( - data.x, data.y, data.z, data.width, data.height, data.depth); - [m_mtlTexture replaceRegion:region - mipmapLevel:data.mipLevel - slice:data.layer - withBytes:data.data - bytesPerRow:data.bytesPerRow - bytesPerImage:data.bytesPerRow * data.rowsPerImage]; -} - -void Texture::onRefCntReachedZero() const -{ - if (m_glTexture != 0 && m_glOwnsTexture) - { - GLuint tex = m_glTexture; - glDeleteTextures(1, &tex); - } - delete this; -} - -void TextureView::onRefCntReachedZero() const -{ - if (m_glTextureView != 0) - { - GLuint tex = m_glTextureView; - glDeleteTextures(1, &tex); - } - delete this; -} - -} // namespace rive::ore - -#endif // ORE_BACKEND_METAL && ORE_BACKEND_GL
diff --git a/renderer/src/ore/vulkan/ore_bind_group_layout_vulkan.hpp b/renderer/src/ore/vulkan/ore_bind_group_layout_vulkan.hpp new file mode 100644 index 0000000..777cd9b --- /dev/null +++ b/renderer/src/ore/vulkan/ore_bind_group_layout_vulkan.hpp
@@ -0,0 +1,25 @@ +#pragma once +#include "rive/renderer/ore/ore_bind_group_layout.hpp" +#include <vulkan/vulkan.h> + +namespace rive::ore +{ +class ContextVulkan; + +class BindGroupLayoutVulkan + : public LITE_RTTI_OVERRIDE(BindGroupLayout, BindGroupLayoutVulkan) +{ +public: + BindGroupLayoutVulkan() = default; + ~BindGroupLayoutVulkan() override = default; + // Defers vkDestroyDescriptorSetLayout through + // ContextVulkan::vkDeferDestroy(). + void onRefCntReachedZero() const override; + +private: + friend class ContextVulkan; + VkDevice m_vkDevice = VK_NULL_HANDLE; // Weak ref. + VkDescriptorSetLayout m_vkDSL = VK_NULL_HANDLE; + PFN_vkDestroyDescriptorSetLayout m_vkDestroyDescriptorSetLayout = nullptr; +}; +} // namespace rive::ore
diff --git a/renderer/src/ore/vulkan/ore_bind_group_vulkan.cpp b/renderer/src/ore/vulkan/ore_bind_group_vulkan.cpp index e79d2bc..c37d618 100644 --- a/renderer/src/ore/vulkan/ore_bind_group_vulkan.cpp +++ b/renderer/src/ore/vulkan/ore_bind_group_vulkan.cpp
@@ -2,15 +2,13 @@ * Copyright 2025 Rive */ -#include "rive/renderer/ore/ore_bind_group.hpp" +#include "ore_bind_group_vulkan.hpp" #include "rive/renderer/ore/ore_context_vulkan.hpp" namespace rive::ore { -#if !defined(ORE_BACKEND_GL) - -void BindGroup::onRefCntReachedZero() const +void BindGroupVulkan::onRefCntReachedZero() const { // Free the VkDescriptorSet back to the persistent pool. Without // this the pool grows unbounded — long editor sessions hit @@ -28,14 +26,12 @@ if (m_vkDescriptorSet != VK_NULL_HANDLE && ctx != nullptr && ctx->m_vkPersistentDescriptorPool != VK_NULL_HANDLE) { - ctx->m_vk.FreeDescriptorSets(ctx->m_vkDevice, - ctx->m_vkPersistentDescriptorPool, - 1, - &m_vkDescriptorSet); + ctx->m_vk->FreeDescriptorSets(ctx->m_vk->device, + ctx->m_vkPersistentDescriptorPool, + 1, + &m_vkDescriptorSet); } delete this; } -#endif // !ORE_BACKEND_GL - } // namespace rive::ore
diff --git a/renderer/src/ore/vulkan/ore_bind_group_vulkan.hpp b/renderer/src/ore/vulkan/ore_bind_group_vulkan.hpp new file mode 100644 index 0000000..af06d2d --- /dev/null +++ b/renderer/src/ore/vulkan/ore_bind_group_vulkan.hpp
@@ -0,0 +1,25 @@ +#pragma once +#include "rive/renderer/ore/ore_bind_group.hpp" +#include <vulkan/vulkan.h> + +namespace rive::ore +{ +class ContextVulkan; + +class BindGroupVulkan : public LITE_RTTI_OVERRIDE(BindGroup, BindGroupVulkan) +{ +public: + BindGroupVulkan() = default; + ~BindGroupVulkan() override = default; + // Deferred destruction is handled at the Lua GC level via + // Context::deferBindGroupDestroy(). By the time refcount reaches zero, + // the GPU is guaranteed to be done. + + void onRefCntReachedZero() const override; + +private: + friend class ContextVulkan; + friend class RenderPassVulkan; + VkDescriptorSet m_vkDescriptorSet = VK_NULL_HANDLE; +}; +} // namespace rive::ore
diff --git a/renderer/src/ore/vulkan/ore_buffer_vulkan.cpp b/renderer/src/ore/vulkan/ore_buffer_vulkan.cpp index 1fe3474..3e9d46c 100644 --- a/renderer/src/ore/vulkan/ore_buffer_vulkan.cpp +++ b/renderer/src/ore/vulkan/ore_buffer_vulkan.cpp
@@ -2,7 +2,7 @@ * Copyright 2025 Rive */ -#include "rive/renderer/ore/ore_buffer.hpp" +#include "ore_buffer_vulkan.hpp" #include "rive/renderer/ore/ore_context_vulkan.hpp" #include <vk_mem_alloc.h> @@ -13,16 +13,14 @@ namespace rive::ore { -#if !defined(ORE_BACKEND_GL) - -void Buffer::update(const void* data, uint32_t size, uint32_t offset) +void BufferVulkan::update(const void* data, uint32_t size, uint32_t offset) { assert(offset + size <= m_size); assert(m_vkMappedPtr != nullptr); memcpy(static_cast<uint8_t*>(m_vkMappedPtr) + offset, data, size); } -void Buffer::onRefCntReachedZero() const +void BufferVulkan::onRefCntReachedZero() const { VmaAllocator allocator = m_vmaAllocator; VkBuffer buf = m_vkBuffer; @@ -42,5 +40,4 @@ destroy(); } -#endif // !ORE_BACKEND_GL } // namespace rive::ore
diff --git a/renderer/src/ore/vulkan/ore_buffer_vulkan.hpp b/renderer/src/ore/vulkan/ore_buffer_vulkan.hpp new file mode 100644 index 0000000..00bb9b0 --- /dev/null +++ b/renderer/src/ore/vulkan/ore_buffer_vulkan.hpp
@@ -0,0 +1,36 @@ +#pragma once +#include "rive/renderer/ore/ore_buffer.hpp" +#include <vulkan/vulkan.h> +VK_DEFINE_HANDLE(VmaAllocator); +VK_DEFINE_HANDLE(VmaAllocation); + +namespace rive::ore +{ +class ContextVulkan; + +class BufferVulkan : public LITE_RTTI_OVERRIDE(Buffer, BufferVulkan) +{ +public: + BufferVulkan(uint32_t size, BufferUsage usage) : + lite_rtti_override(size, usage) + {} + // Destructor defers GPU buffer destruction via ContextVulkan. + ~BufferVulkan() override = default; + void update(const void* data, uint32_t size, uint32_t offset) override; + // Vulkan frees the CPU object immediately; GPU resource is deferred + // via the destructor. + void onRefCntReachedZero() const override; + +private: + friend class ContextVulkan; + friend class RenderPassVulkan; + VkBuffer m_vkBuffer = VK_NULL_HANDLE; + VmaAllocation m_vmaAllocation = VK_NULL_HANDLE; + void* m_vkMappedPtr = nullptr; + VkDevice m_vkDevice = VK_NULL_HANDLE; // Weak ref. + VmaAllocator m_vmaAllocator = VK_NULL_HANDLE; // Weak ref. + // Back-ref so the destructor can route vmaDestroyBuffer through + // ContextVulkan::vkDeferDestroy() in external-CB mode. Weak ref. + ContextVulkan* m_vkOreContext = nullptr; +}; +} // namespace rive::ore
diff --git a/renderer/src/ore/vulkan/ore_context_vulkan.cpp b/renderer/src/ore/vulkan/ore_context_vulkan.cpp index af9dc22..7404e60 100644 --- a/renderer/src/ore/vulkan/ore_context_vulkan.cpp +++ b/renderer/src/ore/vulkan/ore_context_vulkan.cpp
@@ -3,12 +3,14 @@ */ #include "rive/renderer/ore/ore_context_vulkan.hpp" -#include "rive/renderer/ore/ore_buffer.hpp" -#include "rive/renderer/ore/ore_texture.hpp" -#include "rive/renderer/ore/ore_sampler.hpp" -#include "rive/renderer/ore/ore_shader_module.hpp" -#include "rive/renderer/ore/ore_pipeline.hpp" -#include "rive/renderer/ore/ore_render_pass.hpp" +#include "ore_buffer_vulkan.hpp" +#include "ore_texture_vulkan.hpp" +#include "ore_sampler_vulkan.hpp" +#include "ore_shader_module_vulkan.hpp" +#include "ore_pipeline_vulkan.hpp" +#include "ore_render_pass_vulkan.hpp" +#include "ore_bind_group_vulkan.hpp" +#include "ore_bind_group_layout_vulkan.hpp" #include "rive/renderer/render_canvas.hpp" #include "rive/renderer/vulkan/render_target_vulkan.hpp" @@ -141,16 +143,16 @@ ContextVulkan::~ContextVulkan() { - if (m_vkDevice == VK_NULL_HANDLE) + if (m_vk->device == VK_NULL_HANDLE) return; // Wait for any in-flight GPU work before tearing down resources. Use // QueueWaitIdle to also cover the external-CB path where the host owns // the frame fence and may have submitted work Ore doesn't track. if (m_vkQueue != VK_NULL_HANDLE) - m_vk.QueueWaitIdle(m_vkQueue); + m_vk->QueueWaitIdle(m_vkQueue); if (m_vkFrameFence != VK_NULL_HANDLE) - m_vk.DestroyFence(m_vkDevice, m_vkFrameFence, nullptr); + m_vk->DestroyFence(m_vk->device, m_vkFrameFence, nullptr); // Drop any BindGroups that were deferred past the final endFrame(). Their // descriptor sets live in m_vkPersistentDescriptorPool and must go away @@ -162,24 +164,24 @@ // Drain the render pass cache. for (auto& [key, rp] : m_vkRenderPassCache) - m_vk.DestroyRenderPass(m_vkDevice, rp, nullptr); + m_vk->DestroyRenderPass(m_vk->device, rp, nullptr); m_vkRenderPassCache.clear(); if (m_vkDescriptorPool != VK_NULL_HANDLE) - m_vk.DestroyDescriptorPool(m_vkDevice, m_vkDescriptorPool, nullptr); + m_vk->DestroyDescriptorPool(m_vk->device, m_vkDescriptorPool, nullptr); // The persistent pool backs BindGroups (allocated lazily in makeBindGroup). // Destroying it implicitly frees any remaining descriptor sets it owns. if (m_vkPersistentDescriptorPool != VK_NULL_HANDLE) - m_vk.DestroyDescriptorPool(m_vkDevice, - m_vkPersistentDescriptorPool, - nullptr); + m_vk->DestroyDescriptorPool(m_vk->device, + m_vkPersistentDescriptorPool, + nullptr); if (m_vkEmptyDSL != VK_NULL_HANDLE) - m_vk.DestroyDescriptorSetLayout(m_vkDevice, m_vkEmptyDSL, nullptr); + m_vk->DestroyDescriptorSetLayout(m_vk->device, m_vkEmptyDSL, nullptr); if (m_vkCommandPool != VK_NULL_HANDLE) - m_vk.DestroyCommandPool(m_vkDevice, m_vkCommandPool, nullptr); + m_vk->DestroyCommandPool(m_vk->device, m_vkCommandPool, nullptr); } // ============================================================================ @@ -187,44 +189,24 @@ // ============================================================================ std::unique_ptr<ContextVulkan> ContextVulkan::Make( - VkInstance instance, - VkPhysicalDevice physicalDevice, - VkDevice device, + const rcp<rive::gpu::VulkanContext> vk, VkQueue queue, - uint32_t queueFamilyIndex, - VmaAllocator allocator, - PFN_vkGetInstanceProcAddr pfnGetInstanceProcAddr) + uint32_t queueFamilyIndex) { - auto ctx = std::unique_ptr<ContextVulkan>(new ContextVulkan()); - ctx->m_vkPhysicalDevice = physicalDevice; - ctx->m_vkDevice = device; + auto ctx = std::unique_ptr<ContextVulkan>(new ContextVulkan(vk)); ctx->m_vkQueue = queue; ctx->m_vkQueueFamily = queueFamilyIndex; - ctx->m_vmaAllocator = allocator; - - // Load instance-level function pointers. -#define LOAD_INSTANCE_CMD(CMD) \ - ctx->m_vk.CMD = reinterpret_cast<PFN_vk##CMD>( \ - pfnGetInstanceProcAddr(instance, "vk" #CMD)); - ORE_VK_INSTANCE_COMMANDS(LOAD_INSTANCE_CMD) -#undef LOAD_INSTANCE_CMD - - // Load device-level function pointers via GetDeviceProcAddr. -#define LOAD_DEVICE_CMD(CMD) \ - ctx->m_vk.CMD = reinterpret_cast<PFN_vk##CMD>( \ - ctx->m_vk.GetDeviceProcAddr(device, "vk" #CMD)); - ORE_VK_DEVICE_COMMANDS(LOAD_DEVICE_CMD) -#undef LOAD_DEVICE_CMD + ctx->m_vmaAllocator = vk->allocator(); // Command pool: reset-per-command-buffer for single-threaded use. VkCommandPoolCreateInfo poolCI{}; poolCI.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO; poolCI.flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT; poolCI.queueFamilyIndex = queueFamilyIndex; - ctx->m_vk.CreateCommandPool(device, - &poolCI, - nullptr, - &ctx->m_vkCommandPool); + ctx->m_vk->CreateCommandPool(ctx->m_vk->device, + &poolCI, + nullptr, + &ctx->m_vkCommandPool); // Single reusable command buffer. VkCommandBufferAllocateInfo cbAI{}; @@ -232,7 +214,9 @@ cbAI.commandPool = ctx->m_vkCommandPool; cbAI.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY; cbAI.commandBufferCount = 1; - ctx->m_vk.AllocateCommandBuffers(device, &cbAI, &ctx->m_vkCommandBuffer); + ctx->m_vk->AllocateCommandBuffers(ctx->m_vk->device, + &cbAI, + &ctx->m_vkCommandBuffer); // Descriptor pool: sized generously for per-frame allocation + reset. // 3 sets per draw × 256 draws per frame × 3 types = 2304 descriptors. @@ -247,10 +231,10 @@ dpCI.maxSets = 768; dpCI.poolSizeCount = 3; dpCI.pPoolSizes = poolSizes; - ctx->m_vk.CreateDescriptorPool(device, - &dpCI, - nullptr, - &ctx->m_vkDescriptorPool); + ctx->m_vk->CreateDescriptorPool(ctx->m_vk->device, + &dpCI, + nullptr, + &ctx->m_vkDescriptorPool); // Frame fence — signaled after each endFrame() QueueSubmit, waited on // in the next beginFrame() (or the destructor) so we never destroy @@ -259,13 +243,16 @@ VkFenceCreateInfo fenceCI{}; fenceCI.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO; fenceCI.flags = VK_FENCE_CREATE_SIGNALED_BIT; - ctx->m_vk.CreateFence(device, &fenceCI, nullptr, &ctx->m_vkFrameFence); + ctx->m_vk->CreateFence(ctx->m_vk->device, + &fenceCI, + nullptr, + &ctx->m_vkFrameFence); // Populate features from physical device properties. VkPhysicalDeviceProperties props{}; - ctx->m_vk.GetPhysicalDeviceProperties(physicalDevice, &props); + ctx->m_vk->GetPhysicalDeviceProperties(ctx->m_vk->physicalDevice, &props); VkPhysicalDeviceFeatures feat{}; - ctx->m_vk.GetPhysicalDeviceFeatures(physicalDevice, &feat); + ctx->m_vk->GetPhysicalDeviceFeatures(ctx->m_vk->physicalDevice, &feat); Features& f = ctx->m_features; f.colorBufferFloat = true; // All Vulkan 1.1+ support rgba16f attachments. @@ -302,7 +289,7 @@ void ContextVulkan::vkDrainDeferred() { for (VkFramebuffer fb : m_vkDeferredFramebuffers) - m_vk.DestroyFramebuffer(m_vkDevice, fb, nullptr); + m_vk->DestroyFramebuffer(m_vk->device, fb, nullptr); m_vkDeferredFramebuffers.clear(); for (auto& buf : m_vkDeferredStagingBuffers) @@ -335,7 +322,7 @@ VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO}; ci.bindingCount = 0; ci.pBindings = nullptr; - m_vk.CreateDescriptorSetLayout(m_vkDevice, &ci, nullptr, &m_vkEmptyDSL); + m_vk->CreateDescriptorSetLayout(m_vk->device, &ci, nullptr, &m_vkEmptyDSL); return m_vkEmptyDSL; } @@ -353,7 +340,8 @@ barriers.reserve(m_vkPendingInitialTransitions.size()); for (const auto& pt : m_vkPendingInitialTransitions) { - if (pt.texture->m_vkLayout != VK_IMAGE_LAYOUT_UNDEFINED) + auto texture = lite_rtti_cast<TextureVulkan*>(pt.texture.get()); + if (texture->m_vkLayout != VK_IMAGE_LAYOUT_UNDEFINED) continue; VkImageMemoryBarrier b{}; @@ -364,27 +352,27 @@ b.newLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; b.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; b.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; - b.image = pt.texture->m_vkImage; + b.image = texture->m_vkImage; b.subresourceRange.aspectMask = pt.aspectMask; b.subresourceRange.baseMipLevel = 0; b.subresourceRange.levelCount = VK_REMAINING_MIP_LEVELS; b.subresourceRange.baseArrayLayer = 0; b.subresourceRange.layerCount = VK_REMAINING_ARRAY_LAYERS; barriers.push_back(b); - pt.texture->m_vkLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; + texture->m_vkLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; } if (!barriers.empty()) { - m_vk.CmdPipelineBarrier(m_vkCommandBuffer, - VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, - VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, - 0, - 0, - nullptr, - 0, - nullptr, - static_cast<uint32_t>(barriers.size()), - barriers.data()); + m_vk->CmdPipelineBarrier(m_vkCommandBuffer, + VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, + VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, + 0, + 0, + nullptr, + 0, + nullptr, + static_cast<uint32_t>(barriers.size()), + barriers.data()); } m_vkPendingInitialTransitions.clear(); } @@ -405,15 +393,15 @@ m_vkExternalCmdBuf = false; // Reset the descriptor pool — all sets from last frame are invalid. - m_vk.ResetDescriptorPool(m_vkDevice, m_vkDescriptorPool, 0); + m_vk->ResetDescriptorPool(m_vk->device, m_vkDescriptorPool, 0); // Begin the frame command buffer. - m_vk.ResetCommandBuffer(m_vkCommandBuffer, 0); + m_vk->ResetCommandBuffer(m_vkCommandBuffer, 0); VkCommandBufferBeginInfo beginInfo{}; beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO; beginInfo.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT; - m_vk.BeginCommandBuffer(m_vkCommandBuffer, &beginInfo); + m_vk->BeginCommandBuffer(m_vkCommandBuffer, &beginInfo); // Flush any lazy-init barriers queued between frames (e.g. BindGroups // created before beginFrame that referenced a still-UNDEFINED texture). @@ -427,7 +415,7 @@ m_deferredBindGroups.clear(); vkDrainDeferred(); - m_vk.ResetDescriptorPool(m_vkDevice, m_vkDescriptorPool, 0); + m_vk->ResetDescriptorPool(m_vk->device, m_vkDescriptorPool, 0); m_vkCommandBuffer = externalCb; m_vkExternalCmdBuf = true; @@ -441,7 +429,11 @@ { #if defined(ORE_BACKEND_VK) if (m_vkFrameFence != VK_NULL_HANDLE) - m_vk.WaitForFences(m_vkDevice, 1, &m_vkFrameFence, VK_TRUE, UINT64_MAX); + m_vk->WaitForFences(m_vk->device, + 1, + &m_vkFrameFence, + VK_TRUE, + UINT64_MAX); #endif } @@ -455,18 +447,18 @@ return; } - m_vk.EndCommandBuffer(m_vkCommandBuffer); + m_vk->EndCommandBuffer(m_vkCommandBuffer); VkSubmitInfo submitInfo{}; submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO; submitInfo.commandBufferCount = 1; submitInfo.pCommandBuffers = &m_vkCommandBuffer; - m_vk.ResetFences(m_vkDevice, 1, &m_vkFrameFence); - m_vk.QueueSubmit(m_vkQueue, 1, &submitInfo, m_vkFrameFence); + m_vk->ResetFences(m_vk->device, 1, &m_vkFrameFence); + m_vk->QueueSubmit(m_vkQueue, 1, &submitInfo, m_vkFrameFence); // Wait for GPU completion before returning — callers destroy Ore // resources (textures, views, pipelines) after endFrame(), and those // must not be in use by the GPU. Matches D3D12's endFrame() behavior. - m_vk.WaitForFences(m_vkDevice, 1, &m_vkFrameFence, VK_TRUE, UINT64_MAX); + m_vk->WaitForFences(m_vk->device, 1, &m_vkFrameFence, VK_TRUE, UINT64_MAX); vkDrainDeferred(); } @@ -613,7 +605,7 @@ rpCI.pDependencies = deps; VkRenderPass rp = VK_NULL_HANDLE; - m_vk.CreateRenderPass(m_vkDevice, &rpCI, nullptr, &rp); + m_vk->CreateRenderPass(m_vk->device, &rpCI, nullptr, &rp); m_vkRenderPassCache.emplace_back(key, rp); return rp; @@ -625,8 +617,8 @@ rcp<Buffer> ContextVulkan::makeBuffer(const BufferDesc& desc) { - auto buffer = rcp<Buffer>(new Buffer(desc.size, desc.usage)); - buffer->m_vkDevice = m_vkDevice; + auto buffer = rcp<BufferVulkan>(new BufferVulkan(desc.size, desc.usage)); + buffer->m_vkDevice = m_vk->device; buffer->m_vmaAllocator = m_vmaAllocator; buffer->m_vkOreContext = this; @@ -677,8 +669,8 @@ rcp<Texture> ContextVulkan::makeTexture(const TextureDesc& desc) { - auto texture = rcp<Texture>(new Texture(desc)); - texture->m_vkDevice = m_vkDevice; + auto texture = rcp<TextureVulkan>(new TextureVulkan(desc)); + texture->m_vkDevice = m_vk->device; texture->m_vmaAllocator = m_vmaAllocator; texture->m_vkOreContext = this; @@ -748,12 +740,13 @@ rcp<TextureView> ContextVulkan::makeTextureView(const TextureViewDesc& desc) { - Texture* tex = desc.texture; + TextureVulkan* tex = lite_rtti_cast<TextureVulkan*>(desc.texture); if (!tex) return nullptr; - auto view = rcp<TextureView>(new TextureView(ref_rcp(tex), desc)); - view->m_vkDevice = m_vkDevice; + auto view = + rcp<TextureViewVulkan>(new TextureViewVulkan(ref_rcp(tex), desc)); + view->m_vkDevice = m_vk->device; view->m_vkOreContext = this; VkImageAspectFlags aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; @@ -808,8 +801,8 @@ viewCI.subresourceRange.layerCount = desc.layerCount > 0 ? desc.layerCount : VK_REMAINING_ARRAY_LAYERS; - m_vk.CreateImageView(m_vkDevice, &viewCI, nullptr, &view->m_vkImageView); - view->m_vkDestroyImageView = m_vk.DestroyImageView; + m_vk->CreateImageView(m_vk->device, &viewCI, nullptr, &view->m_vkImageView); + view->m_vkDestroyImageView = m_vk->DestroyImageView; return view; } @@ -820,8 +813,8 @@ rcp<Sampler> ContextVulkan::makeSampler(const SamplerDesc& desc) { - auto sampler = rcp<Sampler>(new Sampler()); - sampler->m_vkDevice = m_vkDevice; + auto sampler = rcp<SamplerVulkan>(new SamplerVulkan()); + sampler->m_vkDevice = m_vk->device; sampler->m_vkOreContext = this; auto filterToVk = [](Filter f) { @@ -887,8 +880,8 @@ sCI.maxLod = desc.maxLod; sCI.borderColor = VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK; - m_vk.CreateSampler(m_vkDevice, &sCI, nullptr, &sampler->m_vkSampler); - sampler->m_vkDestroySampler = m_vk.DestroySampler; + m_vk->CreateSampler(m_vk->device, &sCI, nullptr, &sampler->m_vkSampler); + sampler->m_vkDestroySampler = m_vk->DestroySampler; return sampler; } @@ -899,25 +892,25 @@ rcp<ShaderModule> ContextVulkan::makeShaderModule(const ShaderModuleDesc& desc) { - auto module = rcp<ShaderModule>(new ShaderModule()); - module->m_vkDevice = m_vkDevice; + auto module = rcp<ShaderModuleVulkan>(new ShaderModuleVulkan()); + module->m_vkDevice = m_vk->device; VkShaderModuleCreateInfo smCI{}; smCI.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO; smCI.codeSize = desc.codeSize; smCI.pCode = static_cast<const uint32_t*>(desc.code); - VkResult result = m_vk.CreateShaderModule(m_vkDevice, - &smCI, - nullptr, - &module->m_vkShaderModule); + VkResult result = m_vk->CreateShaderModule(m_vk->device, + &smCI, + nullptr, + &module->m_vkShaderModule); if (result != VK_SUCCESS || module->m_vkShaderModule == VK_NULL_HANDLE) { setLastError("Ore Vulkan: vkCreateShaderModule failed (VkResult=%d)", static_cast<int>(result)); return nullptr; } - module->m_vkDestroyShaderModule = m_vk.DestroyShaderModule; + module->m_vkDestroyShaderModule = m_vk->DestroyShaderModule; module->applyBindingMapFromDesc(desc); return module; @@ -937,17 +930,17 @@ kMaxBindGroups); return nullptr; } - auto layout = rcp<BindGroupLayout>(new BindGroupLayout()); + auto layout = rcp<BindGroupLayoutVulkan>(new BindGroupLayoutVulkan()); layout->m_context = this; layout->m_groupIndex = desc.groupIndex; layout->m_entries.reserve(desc.entryCount); for (uint32_t i = 0; i < desc.entryCount; ++i) layout->m_entries.push_back(desc.entries[i]); - layout->m_vkDevice = m_vkDevice; - layout->m_vkDestroyDescriptorSetLayout = m_vk.DestroyDescriptorSetLayout; - layout->m_vkDSL = createDSLFromLayoutDesc(m_vk.CreateDescriptorSetLayout, - m_vkDevice, + layout->m_vkDevice = m_vk->device; + layout->m_vkDestroyDescriptorSetLayout = m_vk->DestroyDescriptorSetLayout; + layout->m_vkDSL = createDSLFromLayoutDesc(m_vk->CreateDescriptorSetLayout, + m_vk->device, desc); if (layout->m_vkDSL == VK_NULL_HANDLE) { @@ -970,7 +963,9 @@ setLastError("makeBindGroup: BindGroupDesc::layout is null"); return nullptr; } - BindGroupLayout* layout = desc.layout; + BindGroupLayoutVulkan* layout = + lite_rtti_cast<BindGroupLayoutVulkan*>(desc.layout); + assert(layout != nullptr); const uint32_t groupIndex = layout->groupIndex(); if (groupIndex >= kMaxBindGroups) { @@ -981,7 +976,7 @@ return nullptr; } - auto bg = rcp<BindGroup>(new BindGroup()); + auto bg = rcp<BindGroupVulkan>(new BindGroupVulkan()); bg->m_context = this; bg->m_layoutRef = ref_rcp(layout); @@ -1011,10 +1006,10 @@ ci.maxSets = 256; ci.poolSizeCount = 4; ci.pPoolSizes = poolSizes; - m_vk.CreateDescriptorPool(m_vkDevice, - &ci, - nullptr, - &m_vkPersistentDescriptorPool); + m_vk->CreateDescriptorPool(m_vk->device, + &ci, + nullptr, + &m_vkPersistentDescriptorPool); } // Allocate a descriptor set from the persistent pool using the layout's @@ -1026,9 +1021,9 @@ allocInfo.descriptorSetCount = 1; allocInfo.pSetLayouts = &dsl; - VkResult result = m_vk.AllocateDescriptorSets(m_vkDevice, - &allocInfo, - &bg->m_vkDescriptorSet); + VkResult result = m_vk->AllocateDescriptorSets(m_vk->device, + &allocInfo, + &bg->m_vkDescriptorSet); if (result != VK_SUCCESS) { // Allocation failed — pool may be exhausted. @@ -1095,9 +1090,10 @@ assert(writeIdx < kMaxWrites && bufInfoIdx < kMaxWrites); VkDescriptorBufferInfo& bi = bufferInfos[bufInfoIdx++]; - bi.buffer = ubo.buffer->m_vkBuffer; + auto buffer = lite_rtti_cast<BufferVulkan*>(ubo.buffer); + bi.buffer = buffer->m_vkBuffer; bi.offset = ubo.offset; - bi.range = (ubo.size > 0) ? ubo.size : ubo.buffer->size(); + bi.range = (ubo.size > 0) ? ubo.size : buffer->size(); VkWriteDescriptorSet& w = writes[writeIdx++]; w.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; @@ -1132,7 +1128,7 @@ // lazy-initialize-on-first-use semantic. The layout is updated // at flush time, not here, so an intervening upload() still sees // UNDEFINED and emits the correct upload barrier sequence. - Texture* baseTex = tex.view->texture(); + auto baseTex = lite_rtti_cast<TextureVulkan*>(tex.view->texture()); if (baseTex->m_vkLayout == VK_IMAGE_LAYOUT_UNDEFINED) { VkImageAspectFlags aspect = @@ -1146,7 +1142,9 @@ } VkDescriptorImageInfo& ii = imageInfos[imgInfoIdx++]; - ii.imageView = tex.view->m_vkImageView; + auto view = lite_rtti_cast<TextureViewVulkan*>(tex.view); + assert(view != nullptr); + ii.imageView = view->m_vkImageView; ii.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; ii.sampler = VK_NULL_HANDLE; // Sampler bound separately. @@ -1172,7 +1170,8 @@ assert(writeIdx < kMaxWrites && imgInfoIdx < kMaxWrites); VkDescriptorImageInfo& ii = imageInfos[imgInfoIdx++]; - ii.sampler = samp.sampler->m_vkSampler; + auto sampler = lite_rtti_cast<SamplerVulkan*>(samp.sampler); + ii.sampler = sampler->m_vkSampler; ii.imageView = VK_NULL_HANDLE; ii.imageLayout = VK_IMAGE_LAYOUT_UNDEFINED; @@ -1190,7 +1189,7 @@ if (writeIdx > 0) { - m_vk.UpdateDescriptorSets(m_vkDevice, writeIdx, writes, 0, nullptr); + m_vk->UpdateDescriptorSets(m_vk->device, writeIdx, writes, 0, nullptr); } return bg; @@ -1200,8 +1199,9 @@ // beginRenderPass // ============================================================================ -RenderPass ContextVulkan::beginRenderPass(const RenderPassDesc& desc, - std::string* outError) +std::unique_ptr<RenderPass> ContextVulkan::beginRenderPass( + const RenderPassDesc& desc, + std::string* outError) { finishActiveRenderPass(); @@ -1211,11 +1211,12 @@ // makeBindGroup must be emitted here. vkFlushPendingInitialTransitions(); - RenderPass pass; - pass.m_context = this; - pass.m_vkContext = this; - pass.m_vkCmdBuf = m_vkCommandBuffer; - pass.populateAttachmentMetadata(desc); + std::unique_ptr<RenderPassVulkan> pass = + std::make_unique<RenderPassVulkan>(); + pass->m_context = this; + pass->m_vkContext = this; + pass->m_vkCmdBuf = m_vkCommandBuffer; + pass->populateAttachmentMetadata(desc); // Build render pass key from the actual load/store ops + formats. // Attachment layout in `attachViews`: [color × N][resolve × N_resolve] @@ -1232,12 +1233,12 @@ VkImageView resolveViews[4]{}; bool anyResolve = false; - pass.m_vkColorCount = desc.colorCount; + pass->m_vkColorCount = desc.colorCount; for (uint32_t i = 0; i < desc.colorCount; ++i) { const ColorAttachment& ca = desc.colorAttachments[i]; assert(ca.view != nullptr); - Texture* tex = ca.view->texture(); + auto tex = lite_rtti_cast<TextureVulkan*>(ca.view->texture()); key.colorFormats[i] = tex->format(); key.colorLoadOps[i] = ca.loadOp; key.colorStoreOps[i] = ca.storeOp; @@ -1245,19 +1246,22 @@ if (key.colorHasResolve[i]) { anyResolve = true; - resolveViews[i] = ca.resolveTarget->m_vkImageView; + auto resolveView = + lite_rtti_cast<TextureViewVulkan*>(ca.resolveTarget); + resolveViews[i] = resolveView->m_vkImageView; } if (key.sampleCount == 1) key.sampleCount = tex->sampleCount(); passWidth = tex->width(); passHeight = tex->height(); - attachViews[attachCount++] = ca.view->m_vkImageView; + auto view = lite_rtti_cast<TextureViewVulkan*>(ca.view); + attachViews[attachCount++] = view->m_vkImageView; // Store image handle, layer range, and render target back-ref for // finish(). - pass.m_vkColorImages[i] = tex->m_vkImage; - pass.m_vkColorBaseLayer[i] = ca.view->baseLayer(); - pass.m_vkColorLayerCount[i] = ca.view->layerCount(); - pass.m_vkColorRenderTargets[i] = ca.view->m_vkRenderTarget; + pass->m_vkColorImages[i] = tex->m_vkImage; + pass->m_vkColorBaseLayer[i] = view->baseLayer(); + pass->m_vkColorLayerCount[i] = view->layerCount(); + pass->m_vkColorRenderTargets[i] = view->m_vkRenderTarget; } // Resolve image views must be appended in the same order as the @@ -1275,16 +1279,18 @@ if (desc.depthStencil.view != nullptr) { - Texture* dsTex = desc.depthStencil.view->texture(); + auto dsTex = + lite_rtti_cast<TextureVulkan*>(desc.depthStencil.view->texture()); key.hasDepth = true; key.depthFormat = dsTex->format(); key.depthLoadOp = desc.depthStencil.depthLoadOp; key.depthStoreOp = desc.depthStencil.depthStoreOp; - attachViews[attachCount++] = desc.depthStencil.view->m_vkImageView; + auto view = lite_rtti_cast<TextureViewVulkan*>(desc.depthStencil.view); + attachViews[attachCount++] = view->m_vkImageView; // Store depth image handle and layer range for finish() barrier. - pass.m_vkDepthImage = dsTex->m_vkImage; - pass.m_vkDepthBaseLayer = desc.depthStencil.view->baseLayer(); - pass.m_vkDepthLayerCount = desc.depthStencil.view->layerCount(); + pass->m_vkDepthImage = dsTex->m_vkImage; + pass->m_vkDepthBaseLayer = view->baseLayer(); + pass->m_vkDepthLayerCount = view->layerCount(); // Depth-only pass: no color attachments contributed dimensions. if (passWidth == 0) { @@ -1304,7 +1310,10 @@ fbCI.width = passWidth; fbCI.height = passHeight; fbCI.layers = 1; - m_vk.CreateFramebuffer(m_vkDevice, &fbCI, nullptr, &pass.m_vkFramebuffer); + m_vk->CreateFramebuffer(m_vk->device, + &fbCI, + nullptr, + &pass->m_vkFramebuffer); // Clear values — must match the attachment ordering that // `getOrCreateRenderPass` builds: [color × N][resolve × R][depth?]. @@ -1335,15 +1344,15 @@ VkRenderPassBeginInfo rpBI{}; rpBI.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO; rpBI.renderPass = renderPass; - rpBI.framebuffer = pass.m_vkFramebuffer; + rpBI.framebuffer = pass->m_vkFramebuffer; rpBI.renderArea.offset = {0, 0}; rpBI.renderArea.extent = {passWidth, passHeight}; rpBI.clearValueCount = attachCount; rpBI.pClearValues = clearValues; - m_vk.CmdBeginRenderPass(m_vkCommandBuffer, - &rpBI, - VK_SUBPASS_CONTENTS_INLINE); + m_vk->CmdBeginRenderPass(m_vkCommandBuffer, + &rpBI, + VK_SUBPASS_CONTENTS_INLINE); return pass; } @@ -1395,7 +1404,7 @@ texDesc.sampleCount = 1; // Borrow the VkImage — the RenderCanvas owns it. - auto texture = rcp<Texture>(new Texture(texDesc)); + auto texture = rcp<TextureVulkan>(new TextureVulkan(texDesc)); texture->m_vkImage = image; // Mark as not VMA-owned so onRefCntReachedZero skips the VMA free. texture->m_vmaAllocation = VK_NULL_HANDLE; @@ -1410,7 +1419,8 @@ viewDesc.baseLayer = 0; viewDesc.layerCount = 1; - auto view = rcp<TextureView>(new TextureView(std::move(texture), viewDesc)); + auto view = rcp<TextureViewVulkan>( + new TextureViewVulkan(std::move(texture), viewDesc)); view->m_vkImageView = imageView; view->m_vkOreContext = this; // No destroy pointer — caller owns the image view lifetime. @@ -1454,7 +1464,7 @@ "wrapRiveTexture requires an open frame: call beginFrame() first"); vkTex->prepareForFragmentShaderRead(m_vkCommandBuffer); - auto texture = rcp<Texture>(new Texture(texDesc)); + auto texture = rcp<TextureVulkan>(new TextureVulkan(texDesc)); texture->m_vkImage = image; texture->m_vmaAllocation = VK_NULL_HANDLE; // Borrowed, not VMA-owned. texture->m_vkLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; @@ -1467,7 +1477,8 @@ viewDesc.baseLayer = 0; viewDesc.layerCount = 1; - auto view = rcp<TextureView>(new TextureView(std::move(texture), viewDesc)); + auto view = rcp<TextureViewVulkan>( + new TextureViewVulkan(std::move(texture), viewDesc)); view->m_vkImageView = imageView; view->m_vkOreContext = this; return view;
diff --git a/renderer/src/ore/vulkan/ore_pipeline_vulkan.cpp b/renderer/src/ore/vulkan/ore_pipeline_vulkan.cpp index d9a9e7e..4fa7fd9 100644 --- a/renderer/src/ore/vulkan/ore_pipeline_vulkan.cpp +++ b/renderer/src/ore/vulkan/ore_pipeline_vulkan.cpp
@@ -2,9 +2,11 @@ * Copyright 2025 Rive */ -#include "rive/renderer/ore/ore_pipeline.hpp" #include "rive/renderer/ore/ore_context_vulkan.hpp" -#include "rive/renderer/ore/ore_shader_module.hpp" +#include "ore_pipeline_vulkan.hpp" +#include "ore_bind_group_vulkan.hpp" +#include "ore_bind_group_layout_vulkan.hpp" +#include "ore_shader_module_vulkan.hpp" #include "rive/rive_types.hpp" #include "ore_vulkan_dsl.hpp" @@ -246,9 +248,7 @@ // BindGroupLayout::onRefCntReachedZero when its rcp drops. // ============================================================================ -#if !defined(ORE_BACKEND_GL) - -void Pipeline::onRefCntReachedZero() const +void PipelineVulkan::onRefCntReachedZero() const { VkDevice dev = m_vkDevice; VkPipeline pipe = m_vkPipeline; @@ -276,7 +276,7 @@ // BindGroupLayout::onRefCntReachedZero (Vulkan) // ============================================================================ -void BindGroupLayout::onRefCntReachedZero() const +void BindGroupLayoutVulkan::onRefCntReachedZero() const { VkDevice dev = m_vkDevice; VkDescriptorSetLayout dsl = m_vkDSL; @@ -296,8 +296,6 @@ destroy(); } -#endif // !ORE_BACKEND_GL — resource onRefCntReachedZero defs - // ============================================================================ // ContextVulkan::makePipeline — called from ore_context_vulkan.cpp. // Always compiled when ORE_BACKEND_VK is defined (regardless of GL coexist), @@ -307,8 +305,8 @@ rcp<Pipeline> ContextVulkan::makePipeline(const PipelineDesc& desc, std::string* outError) { - auto pipeline = rcp<Pipeline>(new Pipeline(desc)); - pipeline->m_vkDevice = m_vkDevice; + auto pipeline = rcp<PipelineVulkan>(new PipelineVulkan(desc)); + pipeline->m_vkDevice = m_vk->device; pipeline->m_vkOreContext = this; pipeline->m_vkTopology = oreTopologyToVk(desc.topology); @@ -341,7 +339,9 @@ { if (desc.bindGroupLayouts[g] != nullptr) { - dsls[g] = desc.bindGroupLayouts[g]->m_vkDSL; + auto layout = lite_rtti_cast<BindGroupLayoutVulkan*>( + desc.bindGroupLayouts[g]); + dsls[g] = layout->m_vkDSL; } else { @@ -354,17 +354,19 @@ layoutCI.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO; layoutCI.setLayoutCount = desc.bindGroupLayoutCount; layoutCI.pSetLayouts = desc.bindGroupLayoutCount > 0 ? dsls : nullptr; - m_vk.CreatePipelineLayout(m_vkDevice, - &layoutCI, - nullptr, - &pipeline->m_vkPipelineLayout); - pipeline->m_vkDestroyPipelineLayout = m_vk.DestroyPipelineLayout; + m_vk->CreatePipelineLayout(m_vk->device, + &layoutCI, + nullptr, + &pipeline->m_vkPipelineLayout); + pipeline->m_vkDestroyPipelineLayout = m_vk->DestroyPipelineLayout; // --- Shader stages --- (depth-only pipelines omit the fragment stage) VkPipelineShaderStageCreateInfo stages[2]{}; stages[0].sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO; stages[0].stage = VK_SHADER_STAGE_VERTEX_BIT; - stages[0].module = desc.vertexModule->m_vkShaderModule; + auto vertexModule = lite_rtti_cast<ShaderModuleVulkan*>(desc.vertexModule); + assert(vertexModule); + stages[0].module = vertexModule->m_vkShaderModule; stages[0].pName = desc.vertexEntryPoint; uint32_t stageCount = 1; @@ -372,7 +374,10 @@ { stages[1].sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO; stages[1].stage = VK_SHADER_STAGE_FRAGMENT_BIT; - stages[1].module = desc.fragmentModule->m_vkShaderModule; + auto fragmentModule = + lite_rtti_cast<ShaderModuleVulkan*>(desc.fragmentModule); + assert(fragmentModule); + stages[1].module = fragmentModule->m_vkShaderModule; stages[1].pName = desc.fragmentEntryPoint; stageCount = 2; } @@ -558,12 +563,12 @@ pipelineCI.renderPass = compatRenderPass; pipelineCI.subpass = 0; - VkResult vkr = m_vk.CreateGraphicsPipelines(m_vkDevice, - VK_NULL_HANDLE, - 1, - &pipelineCI, - nullptr, - &pipeline->m_vkPipeline); + VkResult vkr = m_vk->CreateGraphicsPipelines(m_vk->device, + VK_NULL_HANDLE, + 1, + &pipelineCI, + nullptr, + &pipeline->m_vkPipeline); if (vkr != VK_SUCCESS) { setLastError("Ore Vulkan: vkCreateGraphicsPipelines failed (%d)", vkr); @@ -571,7 +576,7 @@ *outError = m_lastError; return nullptr; } - pipeline->m_vkDestroyPipeline = m_vk.DestroyPipeline; + pipeline->m_vkDestroyPipeline = m_vk->DestroyPipeline; return pipeline; }
diff --git a/renderer/src/ore/vulkan/ore_pipeline_vulkan.hpp b/renderer/src/ore/vulkan/ore_pipeline_vulkan.hpp new file mode 100644 index 0000000..93667ef --- /dev/null +++ b/renderer/src/ore/vulkan/ore_pipeline_vulkan.hpp
@@ -0,0 +1,31 @@ +#pragma once +#include "rive/renderer/ore/ore_pipeline.hpp" +#include <vulkan/vulkan.h> + +namespace rive::ore +{ +class ContextVulkan; + +class PipelineVulkan : public LITE_RTTI_OVERRIDE(Pipeline, PipelineVulkan) +{ +public: + PipelineVulkan(const PipelineDesc& desc) : lite_rtti_override(desc) {} + ~PipelineVulkan() override = default; + // Defers vkDestroyPipeline and vkDestroyPipelineLayout through + // ContextVulkan::vkDeferDestroy(). + void onRefCntReachedZero() const override; + +private: + friend class ContextVulkan; + friend class RenderPassVulkan; + VkDevice m_vkDevice = VK_NULL_HANDLE; // Weak ref. + VkPipeline m_vkPipeline = VK_NULL_HANDLE; + VkPipelineLayout m_vkPipelineLayout = VK_NULL_HANDLE; + VkPrimitiveTopology m_vkTopology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST; + // Function pointers for cleanup (loaded by Context::makePipeline). + PFN_vkDestroyPipeline m_vkDestroyPipeline = nullptr; + PFN_vkDestroyPipelineLayout m_vkDestroyPipelineLayout = nullptr; + // Back-ref for deferred destruction. Weak ref. + ContextVulkan* m_vkOreContext = nullptr; +}; +} // namespace rive::ore
diff --git a/renderer/src/ore/vulkan/ore_render_pass_vk_gl.cpp b/renderer/src/ore/vulkan/ore_render_pass_vk_gl.cpp deleted file mode 100644 index 466e40d..0000000 --- a/renderer/src/ore/vulkan/ore_render_pass_vk_gl.cpp +++ /dev/null
@@ -1,796 +0,0 @@ -/* - * Copyright 2025 Rive - */ - -// Combined VK + GL RenderPass implementation for dual-backend builds. -// Compiled when both ORE_BACKEND_VK and ORE_BACKEND_GL are active. -// Provides all RenderPass method definitions with runtime dispatch: -// passes initialized via the Vulkan context path (m_vkContext != nullptr) use -// Vulkan; passes initialized via the GL context path (m_context != nullptr) -// use GL. - -#if defined(ORE_BACKEND_VK) && defined(ORE_BACKEND_GL) - -// Pull in VK static helpers (layout transitions, etc.). -// The !defined(ORE_BACKEND_GL) guard in ore_render_pass_vulkan.cpp excludes -// RenderPass method bodies, so we get only the static helper functions. -#include "ore_render_pass_vulkan.cpp" - -// Pull in GL static helpers (oreTopologyToGL, oreBlendFactorToGL, etc.). -// The !defined(ORE_BACKEND_METAL) && !defined(ORE_BACKEND_VK) guard in -// ore_render_pass_gl.cpp excludes RenderPass method bodies, so we get only -// the static helper functions. -#include "../gl/ore_render_pass_gl.cpp" - -#include "rive/renderer/gl/load_gles_extensions.hpp" -#include "rive/renderer/ore/ore_render_pass.hpp" -#include "rive/renderer/ore/ore_bind_group.hpp" -#include "rive/renderer/ore/ore_buffer.hpp" -#include "rive/renderer/ore/ore_texture.hpp" -#include "rive/renderer/ore/ore_sampler.hpp" -#include "rive/renderer/ore/ore_pipeline.hpp" -#include "rive/renderer/ore/ore_context_vulkan.hpp" // for RenderPass inline bodies - -namespace rive::ore -{ - -RenderPass::~RenderPass() -{ - if (!m_finished) - { - if (m_vkContext != nullptr || m_context != nullptr) - finish(); - } -} - -RenderPass::RenderPass(RenderPass&& other) noexcept : - m_currentPipeline(std::move(other.m_currentPipeline)), - // VK members - m_vkContext(other.m_vkContext), - m_vkCmdBuf(other.m_vkCmdBuf), - m_vkFramebuffer(other.m_vkFramebuffer), - m_vkIndexBuffer(other.m_vkIndexBuffer), - m_vkIndexType(other.m_vkIndexType), - m_vkIndexOffset(other.m_vkIndexOffset), - m_vkColorCount(other.m_vkColorCount), - m_vkDepthImage(other.m_vkDepthImage), - m_vkDepthBaseLayer(other.m_vkDepthBaseLayer), - m_vkDepthLayerCount(other.m_vkDepthLayerCount), - // GL members - m_glFBO(other.m_glFBO), - m_glVAO(other.m_glVAO), - m_prevVAO(other.m_prevVAO), - m_prevFBO(other.m_prevFBO), - m_ownsFBO(other.m_ownsFBO), - m_ownsVAO(other.m_ownsVAO), - m_viewportWidth(other.m_viewportWidth), - m_viewportHeight(other.m_viewportHeight), - m_maxSamplerSlot(other.m_maxSamplerSlot), - m_maxAttribSlot(other.m_maxAttribSlot), - m_usedSamplers(other.m_usedSamplers), - m_usedAttribs(other.m_usedAttribs), - m_glIndexFormat(other.m_glIndexFormat), - m_glResolveCount(other.m_glResolveCount) -{ - moveCrossBackendFieldsFrom(other); - // VK arrays - memcpy(m_vkColorImages, other.m_vkColorImages, sizeof(m_vkColorImages)); - memcpy(m_vkColorBaseLayer, - other.m_vkColorBaseLayer, - sizeof(m_vkColorBaseLayer)); - memcpy(m_vkColorLayerCount, - other.m_vkColorLayerCount, - sizeof(m_vkColorLayerCount)); - memcpy(m_vkColorRenderTargets, - other.m_vkColorRenderTargets, - sizeof(m_vkColorRenderTargets)); - // GL resolve array - for (uint32_t i = 0; i < m_glResolveCount; ++i) - m_glResolves[i] = other.m_glResolves[i]; - other.m_vkContext = nullptr; - other.m_vkFramebuffer = VK_NULL_HANDLE; - other.m_ownsFBO = false; - other.m_ownsVAO = false; - other.m_glResolveCount = 0; -} - -RenderPass& RenderPass::operator=(RenderPass&& other) noexcept -{ - if (this != &other) - { - if (!m_finished && (m_vkContext != nullptr || m_context != nullptr)) - finish(); - moveCrossBackendFieldsFrom(other); - m_currentPipeline = std::move(other.m_currentPipeline); - // VK members - m_vkContext = other.m_vkContext; - m_vkCmdBuf = other.m_vkCmdBuf; - m_vkFramebuffer = other.m_vkFramebuffer; - m_vkIndexBuffer = other.m_vkIndexBuffer; - m_vkIndexType = other.m_vkIndexType; - m_vkIndexOffset = other.m_vkIndexOffset; - memcpy(m_vkColorImages, other.m_vkColorImages, sizeof(m_vkColorImages)); - memcpy(m_vkColorBaseLayer, - other.m_vkColorBaseLayer, - sizeof(m_vkColorBaseLayer)); - memcpy(m_vkColorLayerCount, - other.m_vkColorLayerCount, - sizeof(m_vkColorLayerCount)); - m_vkColorCount = other.m_vkColorCount; - memcpy(m_vkColorRenderTargets, - other.m_vkColorRenderTargets, - sizeof(m_vkColorRenderTargets)); - m_vkDepthImage = other.m_vkDepthImage; - m_vkDepthBaseLayer = other.m_vkDepthBaseLayer; - m_vkDepthLayerCount = other.m_vkDepthLayerCount; - // GL members - m_glFBO = other.m_glFBO; - m_glVAO = other.m_glVAO; - m_prevVAO = other.m_prevVAO; - m_prevFBO = other.m_prevFBO; - m_ownsFBO = other.m_ownsFBO; - m_ownsVAO = other.m_ownsVAO; - m_viewportWidth = other.m_viewportWidth; - m_viewportHeight = other.m_viewportHeight; - m_maxSamplerSlot = other.m_maxSamplerSlot; - m_maxAttribSlot = other.m_maxAttribSlot; - m_usedSamplers = other.m_usedSamplers; - m_usedAttribs = other.m_usedAttribs; - m_glIndexFormat = other.m_glIndexFormat; - m_glResolveCount = other.m_glResolveCount; - for (uint32_t i = 0; i < m_glResolveCount; ++i) - m_glResolves[i] = other.m_glResolves[i]; - other.m_vkContext = nullptr; - other.m_vkFramebuffer = VK_NULL_HANDLE; - other.m_ownsFBO = false; - other.m_ownsVAO = false; - other.m_glResolveCount = 0; - } - return *this; -} - -void RenderPass::validate() const -{ - assert(!m_finished && "RenderPass already finished"); - assert(m_vkContext != nullptr || m_context != nullptr); -} - -void RenderPass::setPipeline(Pipeline* pipeline) -{ - validate(); - if (!checkPipelineCompat(pipeline)) - return; - if (m_vkContext != nullptr) - { - m_currentPipeline = ref_rcp(pipeline); - m_vkContext->m_vk.CmdBindPipeline(m_vkCmdBuf, - VK_PIPELINE_BIND_POINT_GRAPHICS, - pipeline->m_vkPipeline); - return; - } - - // GL path. - m_currentPipeline = ref_rcp(pipeline); - const auto& desc = pipeline->desc(); - glUseProgram(pipeline->m_glProgram); - - if (desc.cullMode == CullMode::none) - { - glDisable(GL_CULL_FACE); - } - else - { - glEnable(GL_CULL_FACE); - glCullFace(desc.cullMode == CullMode::front ? GL_FRONT : GL_BACK); - } - - glFrontFace(desc.winding == FaceWinding::counterClockwise ? GL_CCW : GL_CW); - - if (desc.depthStencil.depthCompare != CompareFunction::always || - desc.depthStencil.depthWriteEnabled) - { - glEnable(GL_DEPTH_TEST); - glDepthFunc(oreCompareFunctionToGL(desc.depthStencil.depthCompare)); - glDepthMask(desc.depthStencil.depthWriteEnabled ? GL_TRUE : GL_FALSE); - } - else - { - glDisable(GL_DEPTH_TEST); - } - - if (desc.depthStencil.depthBias != 0 || - desc.depthStencil.depthBiasSlopeScale != 0.0f) - { - glEnable(GL_POLYGON_OFFSET_FILL); - glPolygonOffset(desc.depthStencil.depthBiasSlopeScale, - static_cast<float>(desc.depthStencil.depthBias)); - } - else - { - glDisable(GL_POLYGON_OFFSET_FILL); - } - - bool hasStencil = (desc.stencilFront.compare != CompareFunction::always || - desc.stencilFront.failOp != StencilOp::keep || - desc.stencilFront.depthFailOp != StencilOp::keep || - desc.stencilFront.passOp != StencilOp::keep || - desc.stencilBack.compare != CompareFunction::always || - desc.stencilBack.failOp != StencilOp::keep || - desc.stencilBack.depthFailOp != StencilOp::keep || - desc.stencilBack.passOp != StencilOp::keep); - - if (hasStencil) - { - glEnable(GL_STENCIL_TEST); - glStencilMaskSeparate(GL_FRONT, desc.stencilWriteMask); - glStencilMaskSeparate(GL_BACK, desc.stencilWriteMask); - glStencilFuncSeparate(GL_FRONT, - oreCompareFunctionToGL(desc.stencilFront.compare), - static_cast<GLint>(m_glStencilRef), - desc.stencilReadMask); - glStencilFuncSeparate(GL_BACK, - oreCompareFunctionToGL(desc.stencilBack.compare), - static_cast<GLint>(m_glStencilRef), - desc.stencilReadMask); - glStencilOpSeparate(GL_FRONT, - oreStencilOpToGL(desc.stencilFront.failOp), - oreStencilOpToGL(desc.stencilFront.depthFailOp), - oreStencilOpToGL(desc.stencilFront.passOp)); - glStencilOpSeparate(GL_BACK, - oreStencilOpToGL(desc.stencilBack.failOp), - oreStencilOpToGL(desc.stencilBack.depthFailOp), - oreStencilOpToGL(desc.stencilBack.passOp)); - } - else - { - glDisable(GL_STENCIL_TEST); - } - - if (desc.colorCount > 0 && desc.colorTargets[0].blendEnabled) - { - glEnable(GL_BLEND); - const auto& b = desc.colorTargets[0].blend; - glBlendFuncSeparate(oreBlendFactorToGL(b.srcColor), - oreBlendFactorToGL(b.dstColor), - oreBlendFactorToGL(b.srcAlpha), - oreBlendFactorToGL(b.dstAlpha)); - glBlendEquationSeparate(oreBlendOpToGL(b.colorOp), - oreBlendOpToGL(b.alphaOp)); - } - else - { - glDisable(GL_BLEND); - } - - if (desc.colorCount > 0) - { - auto mask = desc.colorTargets[0].writeMask; - glColorMask((mask & ColorWriteMask::red) != ColorWriteMask::none, - (mask & ColorWriteMask::green) != ColorWriteMask::none, - (mask & ColorWriteMask::blue) != ColorWriteMask::none, - (mask & ColorWriteMask::alpha) != ColorWriteMask::none); - } -} - -void RenderPass::setVertexBuffer(uint32_t slot, Buffer* buffer, uint32_t offset) -{ - validate(); - if (m_vkContext != nullptr) - { - VkDeviceSize vkOffset = offset; - m_vkContext->m_vk.CmdBindVertexBuffers(m_vkCmdBuf, - slot, - 1, - &buffer->m_vkBuffer, - &vkOffset); - return; - } - - // GL path. - assert(m_currentPipeline != nullptr && "setPipeline must be called first"); - assert(slot < m_currentPipeline->desc().vertexBufferCount); - - const auto& layout = m_currentPipeline->desc().vertexBuffers[slot]; - glBindBuffer(GL_ARRAY_BUFFER, buffer->m_glBuffer); - - for (uint32_t i = 0; i < layout.attributeCount; ++i) - { - const auto& attr = layout.attributes[i]; - GLVertexInfo info = oreVertexFormatToGL(attr.format); - glEnableVertexAttribArray(attr.shaderSlot); - - bool isIntType = - (info.type == GL_UNSIGNED_INT || info.type == GL_INT || - info.type == GL_UNSIGNED_BYTE || info.type == GL_BYTE || - info.type == GL_UNSIGNED_SHORT || info.type == GL_SHORT) && - !info.normalized; - - if (isIntType) - { - glVertexAttribIPointer( - attr.shaderSlot, - info.count, - info.type, - layout.stride, - reinterpret_cast<const void*>( - static_cast<uintptr_t>(attr.offset + offset))); - } - else - { - glVertexAttribPointer( - attr.shaderSlot, - info.count, - info.type, - info.normalized, - layout.stride, - reinterpret_cast<const void*>( - static_cast<uintptr_t>(attr.offset + offset))); - } - - if (layout.stepMode == VertexStepMode::instance) - glVertexAttribDivisor(attr.shaderSlot, 1); - else - glVertexAttribDivisor(attr.shaderSlot, 0); - - if (!m_usedAttribs || attr.shaderSlot > m_maxAttribSlot) - m_maxAttribSlot = attr.shaderSlot; - m_usedAttribs = true; - } -} - -void RenderPass::setIndexBuffer(Buffer* buffer, - IndexFormat format, - uint32_t offset) -{ - validate(); - if (m_vkContext != nullptr) - { - m_vkIndexBuffer = buffer->m_vkBuffer; - m_vkIndexType = (format == IndexFormat::uint32) ? VK_INDEX_TYPE_UINT32 - : VK_INDEX_TYPE_UINT16; - m_vkIndexOffset = offset; - m_vkContext->m_vk.CmdBindIndexBuffer(m_vkCmdBuf, - buffer->m_vkBuffer, - offset, - m_vkIndexType); - return; - } - - // GL path. - glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, buffer->m_glBuffer); - m_glIndexFormat = format; - (void)offset; -} - -void RenderPass::setBindGroup(uint32_t groupIndex, - BindGroup* bg, - const uint32_t* dynamicOffsets, - uint32_t dynamicOffsetCount) -{ - validate(); - m_boundGroups[groupIndex] = ref_rcp(bg); - - if (m_vkContext != nullptr) - { - assert(bg != nullptr); - assert(m_currentPipeline != nullptr && - "setPipeline must be called before setBindGroup"); - - m_vkContext->m_vk.CmdBindDescriptorSets( - m_vkCmdBuf, - VK_PIPELINE_BIND_POINT_GRAPHICS, - m_currentPipeline->m_vkPipelineLayout, - groupIndex, - 1, - &bg->m_vkDescriptorSet, - dynamicOffsetCount, - dynamicOffsets); - return; - } - - // GL path. - (void)groupIndex; - uint32_t dynIdx = 0; - for (auto& b : bg->m_glUBOs) - { - uint32_t offset = b.offset; - if (b.hasDynamicOffset && dynIdx < dynamicOffsetCount) - offset += dynamicOffsets[dynIdx++]; - glBindBufferRange(GL_UNIFORM_BUFFER, b.slot, b.buffer, offset, b.size); - } - for (auto& t : bg->m_glTextures) - { - glActiveTexture(GL_TEXTURE0 + t.slot); - glBindTexture(t.target, t.texture); - if (!m_usedSamplers || t.slot > m_maxSamplerSlot) - m_maxSamplerSlot = t.slot; - m_usedSamplers = true; - } - for (auto& s : bg->m_glSamplers) - { - glBindSampler(s.slot, s.sampler); - } -} - -void RenderPass::setViewport(float x, - float y, - float width, - float height, - float minDepth, - float maxDepth) -{ - validate(); - if (m_vkContext != nullptr) - { - // Ore NDC convention: Y-up clip space, depth in [0, 1]. - // Vulkan's clip space is Y-down, so we flip the viewport with a - // negative height (VK_KHR_maintenance1). - VkViewport vp{}; - vp.x = x; - vp.y = y + height; // Start at the bottom. - vp.width = width; - vp.height = -height; // Negative height flips Y. - vp.minDepth = minDepth; - vp.maxDepth = maxDepth; - m_vkContext->m_vk.CmdSetViewport(m_vkCmdBuf, 0, 1, &vp); - - // Match the other backends' implicit behaviour: scissor defaults - // to the full viewport rectangle. `VkRect2D` is integer-typed, - // so floor the corner / ceil the far edge to avoid clipping - // fractional sub-rects, and clamp negative origins to 0 - // (`static_cast<uint32_t>` of a negative float is UB). - const float x0 = std::floor(x); - const float y0 = std::floor(y); - const float x1 = std::ceil(x + width); - const float y1 = std::ceil(y + height); - VkRect2D scissor{}; - scissor.offset = {static_cast<int32_t>(std::max(0.0f, x0)), - static_cast<int32_t>(std::max(0.0f, y0))}; - scissor.extent = {static_cast<uint32_t>(std::max(0.0f, x1 - x0)), - static_cast<uint32_t>(std::max(0.0f, y1 - y0))}; - m_vkContext->m_vk.CmdSetScissor(m_vkCmdBuf, 0, 1, &scissor); - return; - } - - // GL path. - m_viewportWidth = static_cast<uint32_t>(width); - m_viewportHeight = static_cast<uint32_t>(height); - glViewport(static_cast<GLint>(x), - static_cast<GLint>(y), - static_cast<GLsizei>(width), - static_cast<GLsizei>(height)); - glDepthRangef(minDepth, maxDepth); -} - -void RenderPass::setScissorRect(uint32_t x, - uint32_t y, - uint32_t width, - uint32_t height) -{ - validate(); - if (m_vkContext != nullptr) - { - VkRect2D scissor{}; - scissor.offset = {static_cast<int32_t>(x), static_cast<int32_t>(y)}; - scissor.extent = {width, height}; - m_vkContext->m_vk.CmdSetScissor(m_vkCmdBuf, 0, 1, &scissor); - return; - } - - // GL path. - glEnable(GL_SCISSOR_TEST); - glScissor(x, y, width, height); -} - -void RenderPass::setStencilReference(uint32_t ref) -{ - validate(); - if (m_vkContext != nullptr) - { - m_vkContext->m_vk.CmdSetStencilReference(m_vkCmdBuf, - VK_STENCIL_FACE_FRONT_AND_BACK, - ref); - return; - } - - // GL path. Cache the ref so a subsequent `setPipeline` re-applies - // it — WebGPU semantics make `setStencilReference` pass-state, so - // calling it before the first `setPipeline` must not be a no-op. - m_glStencilRef = ref; - if (m_currentPipeline) - { - const auto& desc = m_currentPipeline->desc(); - glStencilFuncSeparate(GL_FRONT, - oreCompareFunctionToGL(desc.stencilFront.compare), - static_cast<GLint>(ref), - desc.stencilReadMask); - glStencilFuncSeparate(GL_BACK, - oreCompareFunctionToGL(desc.stencilBack.compare), - static_cast<GLint>(ref), - desc.stencilReadMask); - } -} - -void RenderPass::setBlendColor(float r, float g, float b, float a) -{ - validate(); - if (m_vkContext != nullptr) - { - float constants[4] = {r, g, b, a}; - m_vkContext->m_vk.CmdSetBlendConstants(m_vkCmdBuf, constants); - return; - } - - // GL path. - glBlendColor(r, g, b, a); -} - -void RenderPass::draw(uint32_t vertexCount, - uint32_t instanceCount, - uint32_t firstVertex, - uint32_t firstInstance) -{ - validate(); - if (m_vkContext != nullptr) - { - m_vkContext->m_vk.CmdDraw(m_vkCmdBuf, - vertexCount, - instanceCount, - firstVertex, - firstInstance); - return; - } - - // GL path. - assert(m_currentPipeline != nullptr); - GLenum mode = oreTopologyToGL(m_currentPipeline->desc().topology); - (void)firstInstance; - if (instanceCount > 1) - glDrawArraysInstanced(mode, firstVertex, vertexCount, instanceCount); - else - glDrawArrays(mode, firstVertex, vertexCount); -} - -void RenderPass::drawIndexed(uint32_t indexCount, - uint32_t instanceCount, - uint32_t firstIndex, - int32_t baseVertex, - uint32_t firstInstance) -{ - validate(); - if (m_vkContext != nullptr) - { - m_vkContext->m_vk.CmdDrawIndexed(m_vkCmdBuf, - indexCount, - instanceCount, - firstIndex, - baseVertex, - firstInstance); - return; - } - - // GL path. - assert(m_currentPipeline != nullptr); - GLenum mode = oreTopologyToGL(m_currentPipeline->desc().topology); - GLenum indexType = (m_glIndexFormat == IndexFormat::uint32) - ? GL_UNSIGNED_INT - : GL_UNSIGNED_SHORT; - uint32_t indexSize = - (indexType == GL_UNSIGNED_INT) ? sizeof(uint32_t) : sizeof(uint16_t); - const void* offset = reinterpret_cast<const void*>( - static_cast<uintptr_t>(firstIndex * indexSize)); - (void)baseVertex; - (void)firstInstance; - if (instanceCount > 1) - glDrawElementsInstanced(mode, - indexCount, - indexType, - offset, - instanceCount); - else - glDrawElements(mode, indexCount, indexType, offset); -} - -void RenderPass::finish() -{ - if (m_finished) - return; - m_finished = true; - - // Release bound BindGroup refs. - for (auto& bg : m_boundGroups) - bg.reset(); - - if (m_vkContext != nullptr) - { - m_vkContext->m_vk.CmdEndRenderPass(m_vkCmdBuf); - - // Transition color attachments COLOR_ATTACHMENT_OPTIMAL -> - // SHADER_READ_ONLY_OPTIMAL so callers (e.g. Rive drawImage) can - // sample. - constexpr gpu::vkutil::ImageAccess kColorAttachmentWriteAccess = { - VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, - VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT, - VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, - }; - for (uint32_t i = 0; i < m_vkColorCount; ++i) - { - if (m_vkColorImages[i] == VK_NULL_HANDLE) - continue; - VkImageMemoryBarrier barrier{}; - barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER; - barrier.oldLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL; - barrier.newLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; - barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; - barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; - barrier.image = m_vkColorImages[i]; - barrier.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, - 0, - 1, - m_vkColorBaseLayer[i], - m_vkColorLayerCount[i]}; - barrier.srcAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT; - barrier.dstAccessMask = 0; // visibility established in Rive's CB - m_vkContext->m_vk.CmdPipelineBarrier( - m_vkCmdBuf, - VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, - VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, - 0, - 0, - nullptr, - 0, - nullptr, - 1, - &barrier); - if (m_vkColorRenderTargets[i] != nullptr) - m_vkColorRenderTargets[i]->updateLastAccess( - kColorAttachmentWriteAccess); - } - - // Transition depth attachment DEPTH_STENCIL_ATTACHMENT_OPTIMAL -> - // SHADER_READ_ONLY_OPTIMAL. - if (m_vkDepthImage != VK_NULL_HANDLE) - { - // Aspect mask must cover stencil when format contains one, else - // strict drivers / validation layer fault on a missing-aspect - // transition for depth+stencil-combined formats. - VkImageAspectFlags depthAspect = VK_IMAGE_ASPECT_DEPTH_BIT; - if (m_depthFormat == TextureFormat::depth24plusStencil8 || - m_depthFormat == TextureFormat::depth32floatStencil8) - { - depthAspect |= VK_IMAGE_ASPECT_STENCIL_BIT; - } - - VkImageMemoryBarrier depthBarrier{}; - depthBarrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER; - depthBarrier.oldLayout = - VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL; - depthBarrier.newLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; - depthBarrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; - depthBarrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; - depthBarrier.image = m_vkDepthImage; - depthBarrier.subresourceRange = {depthAspect, - 0, - 1, - m_vkDepthBaseLayer, - m_vkDepthLayerCount}; - depthBarrier.srcAccessMask = - VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT; - depthBarrier.dstAccessMask = 0; - m_vkContext->m_vk.CmdPipelineBarrier( - m_vkCmdBuf, - VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT | - VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT, - VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, - 0, - 0, - nullptr, - 0, - nullptr, - 1, - &depthBarrier); - } - - if (m_vkFramebuffer != VK_NULL_HANDLE) - { - // Defer destruction -- the command buffer still references this - // framebuffer until endFrame() submits and waits. - m_vkContext->m_vkDeferredFramebuffers.push_back(m_vkFramebuffer); - m_vkFramebuffer = VK_NULL_HANDLE; - } - return; - } - - // GL path. - glDisable(GL_SCISSOR_TEST); - glDisable(GL_BLEND); - glDisable(GL_DEPTH_TEST); - glDisable(GL_STENCIL_TEST); - glDisable(GL_CULL_FACE); - glDisable(GL_POLYGON_OFFSET_FILL); - glDepthMask(GL_TRUE); - glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE); - - // Unbind sampler objects and textures so they don't override texture - // parameters in subsequent draws by the host renderer (e.g. Rive's MSAA - // path). - if (m_usedSamplers) - { - for (uint32_t i = 0; i <= m_maxSamplerSlot; ++i) - { - glActiveTexture(GL_TEXTURE0 + i); - glBindTexture(GL_TEXTURE_2D, 0); - glBindTexture(GL_TEXTURE_CUBE_MAP, 0); - glBindSampler(i, 0); - } - glActiveTexture(GL_TEXTURE0); - } - - if (m_usedAttribs) - { - for (uint32_t i = 0; i <= m_maxAttribSlot; ++i) - glDisableVertexAttribArray(i); - } - - // Unbind the global array buffer. (GL_ELEMENT_ARRAY_BUFFER is VAO state - // and will be cleaned up when the per-pass VAO is deleted below — we must - // NOT unbind it here because on some WebGL2 implementations the EBO=0 - // can leak through the VAO delete/restore and corrupt the host VAO.) - glBindBuffer(GL_ARRAY_BUFFER, 0); - - // Delete the per-pass VAO and restore the host renderer's VAO so its - // element-array-buffer binding (and other attrib state) is intact. - if (m_ownsVAO && m_glVAO != 0) - { - glDeleteVertexArrays(1, &m_glVAO); - m_glVAO = 0; - } - glBindVertexArray(m_prevVAO); - - // Resolve MSAA renderbuffers → single-sample resolve targets. - if (m_glResolveCount > 0) - { - GLuint resolveFBO; - glGenFramebuffers(1, &resolveFBO); - for (uint32_t i = 0; i < m_glResolveCount; ++i) - { - const auto& r = m_glResolves[i]; - // Read from the render pass FBO (MSAA renderbuffer attached). - glBindFramebuffer(GL_READ_FRAMEBUFFER, m_glFBO); - glReadBuffer(GL_COLOR_ATTACHMENT0 + r.colorIndex); - - // Write to a temp FBO with the single-sample resolve texture. - glBindFramebuffer(GL_DRAW_FRAMEBUFFER, resolveFBO); - glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, - GL_COLOR_ATTACHMENT0, - r.resolveTarget, - r.resolveTex, - 0); - - glBlitFramebuffer(0, - 0, - r.width, - r.height, - 0, - 0, - r.width, - r.height, - GL_COLOR_BUFFER_BIT, - GL_NEAREST); - } - glDeleteFramebuffers(1, &resolveFBO); - } - - // Delete our FBO and restore the host renderer's FBO. - if (m_ownsFBO && m_glFBO != 0) - { - glDeleteFramebuffers(1, &m_glFBO); - } - glBindFramebuffer(GL_FRAMEBUFFER, m_prevFBO); - - m_context = nullptr; -} - -} // namespace rive::ore - -#endif // ORE_BACKEND_VK && ORE_BACKEND_GL
diff --git a/renderer/src/ore/vulkan/ore_render_pass_vulkan.cpp b/renderer/src/ore/vulkan/ore_render_pass_vulkan.cpp index a2cf4c8..b2ba11c 100644 --- a/renderer/src/ore/vulkan/ore_render_pass_vulkan.cpp +++ b/renderer/src/ore/vulkan/ore_render_pass_vulkan.cpp
@@ -2,13 +2,13 @@ * Copyright 2025 Rive */ -#include "rive/renderer/ore/ore_render_pass.hpp" -#include "rive/renderer/ore/ore_bind_group.hpp" #include "rive/renderer/ore/ore_context_vulkan.hpp" -#include "rive/renderer/ore/ore_buffer.hpp" -#include "rive/renderer/ore/ore_texture.hpp" -#include "rive/renderer/ore/ore_sampler.hpp" -#include "rive/renderer/ore/ore_pipeline.hpp" +#include "ore_render_pass_vulkan.hpp" +#include "ore_bind_group_vulkan.hpp" +#include "ore_buffer_vulkan.hpp" +#include "ore_texture_vulkan.hpp" +#include "ore_sampler_vulkan.hpp" +#include "ore_pipeline_vulkan.hpp" #include "rive/renderer/vulkan/render_target_vulkan.hpp" #include "rive/rive_types.hpp" @@ -24,52 +24,60 @@ // RenderPass methods // ============================================================================ -#if !defined(ORE_BACKEND_GL) - -void RenderPass::setPipeline(Pipeline* pipeline) +void RenderPassVulkan::setPipeline(Pipeline* inPipeline) { - if (!checkPipelineCompat(pipeline)) + if (!checkPipelineCompat(inPipeline)) return; + auto pipeline = lite_rtti_cast<PipelineVulkan*>(inPipeline); + assert(pipeline != nullptr); m_currentPipeline = ref_rcp(pipeline); - m_vkContext->m_vk.CmdBindPipeline(m_vkCmdBuf, - VK_PIPELINE_BIND_POINT_GRAPHICS, - pipeline->m_vkPipeline); + m_vkContext->m_vk->CmdBindPipeline(m_vkCmdBuf, + VK_PIPELINE_BIND_POINT_GRAPHICS, + pipeline->m_vkPipeline); } -void RenderPass::setVertexBuffer(uint32_t slot, Buffer* buffer, uint32_t offset) +void RenderPassVulkan::setVertexBuffer(uint32_t slot, + Buffer* inBuffer, + uint32_t offset) { VkDeviceSize vkOffset = offset; - m_vkContext->m_vk.CmdBindVertexBuffers(m_vkCmdBuf, - slot, - 1, - &buffer->m_vkBuffer, - &vkOffset); + auto buffer = lite_rtti_cast<BufferVulkan*>(inBuffer); + assert(buffer != nullptr); + m_vkContext->m_vk->CmdBindVertexBuffers(m_vkCmdBuf, + slot, + 1, + &buffer->m_vkBuffer, + &vkOffset); } -void RenderPass::setIndexBuffer(Buffer* buffer, - IndexFormat format, - uint32_t offset) +void RenderPassVulkan::setIndexBuffer(Buffer* inBuffer, + IndexFormat format, + uint32_t offset) { + auto buffer = lite_rtti_cast<BufferVulkan*>(inBuffer); + assert(buffer != nullptr); m_vkIndexBuffer = buffer->m_vkBuffer; m_vkIndexType = (format == IndexFormat::uint32) ? VK_INDEX_TYPE_UINT32 : VK_INDEX_TYPE_UINT16; m_vkIndexOffset = offset; - m_vkContext->m_vk.CmdBindIndexBuffer(m_vkCmdBuf, - buffer->m_vkBuffer, - offset, - m_vkIndexType); + m_vkContext->m_vk->CmdBindIndexBuffer(m_vkCmdBuf, + buffer->m_vkBuffer, + offset, + m_vkIndexType); } -void RenderPass::setBindGroup(uint32_t groupIndex, - BindGroup* bg, - const uint32_t* dynamicOffsets, - uint32_t dynamicOffsetCount) +void RenderPassVulkan::setBindGroup(uint32_t groupIndex, + BindGroup* inBg, + const uint32_t* dynamicOffsets, + uint32_t dynamicOffsetCount) { - assert(bg != nullptr); + assert(inBg != nullptr); assert(m_currentPipeline != nullptr && "setPipeline must be called before setBindGroup"); - m_vkContext->m_vk.CmdBindDescriptorSets( + auto bg = lite_rtti_cast<BindGroupVulkan*>(inBg); + assert(bg != nullptr); + m_vkContext->m_vk->CmdBindDescriptorSets( m_vkCmdBuf, VK_PIPELINE_BIND_POINT_GRAPHICS, m_currentPipeline->m_vkPipelineLayout, @@ -84,12 +92,12 @@ m_boundGroups[groupIndex] = ref_rcp(bg); } -void RenderPass::setViewport(float x, - float y, - float width, - float height, - float minDepth, - float maxDepth) +void RenderPassVulkan::setViewport(float x, + float y, + float width, + float height, + float minDepth, + float maxDepth) { // Ore NDC convention: Y-up clip space, depth in [0, 1]. // Vulkan's clip space is Y-down, so we flip the viewport with a negative @@ -103,7 +111,7 @@ vp.height = -height; // Negative height flips Y. vp.minDepth = minDepth; vp.maxDepth = maxDepth; - m_vkContext->m_vk.CmdSetViewport(m_vkCmdBuf, 0, 1, &vp); + m_vkContext->m_vk->CmdSetViewport(m_vkCmdBuf, 0, 1, &vp); // Match the other backends' implicit behaviour: scissor defaults to the // full viewport rectangle. Callers can override with setScissorRect(). @@ -123,66 +131,66 @@ static_cast<int32_t>(std::max(0.0f, y0))}; scissor.extent = {static_cast<uint32_t>(std::max(0.0f, x1 - x0)), static_cast<uint32_t>(std::max(0.0f, y1 - y0))}; - m_vkContext->m_vk.CmdSetScissor(m_vkCmdBuf, 0, 1, &scissor); + m_vkContext->m_vk->CmdSetScissor(m_vkCmdBuf, 0, 1, &scissor); } -void RenderPass::setScissorRect(uint32_t x, - uint32_t y, - uint32_t width, - uint32_t height) +void RenderPassVulkan::setScissorRect(uint32_t x, + uint32_t y, + uint32_t width, + uint32_t height) { VkRect2D scissor{}; scissor.offset = {static_cast<int32_t>(x), static_cast<int32_t>(y)}; scissor.extent = {width, height}; - m_vkContext->m_vk.CmdSetScissor(m_vkCmdBuf, 0, 1, &scissor); + m_vkContext->m_vk->CmdSetScissor(m_vkCmdBuf, 0, 1, &scissor); } -void RenderPass::setStencilReference(uint32_t ref) +void RenderPassVulkan::setStencilReference(uint32_t ref) { - m_vkContext->m_vk.CmdSetStencilReference(m_vkCmdBuf, - VK_STENCIL_FACE_FRONT_AND_BACK, - ref); + m_vkContext->m_vk->CmdSetStencilReference(m_vkCmdBuf, + VK_STENCIL_FACE_FRONT_AND_BACK, + ref); } -void RenderPass::setBlendColor(float r, float g, float b, float a) +void RenderPassVulkan::setBlendColor(float r, float g, float b, float a) { float constants[4] = {r, g, b, a}; - m_vkContext->m_vk.CmdSetBlendConstants(m_vkCmdBuf, constants); + m_vkContext->m_vk->CmdSetBlendConstants(m_vkCmdBuf, constants); } -void RenderPass::draw(uint32_t vertexCount, - uint32_t instanceCount, - uint32_t firstVertex, - uint32_t firstInstance) +void RenderPassVulkan::draw(uint32_t vertexCount, + uint32_t instanceCount, + uint32_t firstVertex, + uint32_t firstInstance) { - m_vkContext->m_vk.CmdDraw(m_vkCmdBuf, - vertexCount, - instanceCount, - firstVertex, - firstInstance); + m_vkContext->m_vk->CmdDraw(m_vkCmdBuf, + vertexCount, + instanceCount, + firstVertex, + firstInstance); } -void RenderPass::drawIndexed(uint32_t indexCount, - uint32_t instanceCount, - uint32_t firstIndex, - int32_t baseVertex, - uint32_t firstInstance) +void RenderPassVulkan::drawIndexed(uint32_t indexCount, + uint32_t instanceCount, + uint32_t firstIndex, + int32_t baseVertex, + uint32_t firstInstance) { - m_vkContext->m_vk.CmdDrawIndexed(m_vkCmdBuf, - indexCount, - instanceCount, - firstIndex, - baseVertex, - firstInstance); + m_vkContext->m_vk->CmdDrawIndexed(m_vkCmdBuf, + indexCount, + instanceCount, + firstIndex, + baseVertex, + firstInstance); } -void RenderPass::finish() +void RenderPassVulkan::finish() { if (m_finished) return; m_finished = true; - m_vkContext->m_vk.CmdEndRenderPass(m_vkCmdBuf); + m_vkContext->m_vk->CmdEndRenderPass(m_vkCmdBuf); // Transition color attachments COLOR_ATTACHMENT_OPTIMAL → // SHADER_READ_ONLY_OPTIMAL so callers (e.g. Rive drawImage) can sample. @@ -218,7 +226,7 @@ m_vkColorLayerCount[i]}; barrier.srcAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT; barrier.dstAccessMask = 0; // visibility established in Rive's CB - m_vkContext->m_vk.CmdPipelineBarrier( + m_vkContext->m_vk->CmdPipelineBarrier( m_vkCmdBuf, VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, // just the layout transition @@ -269,7 +277,7 @@ depthBarrier.srcAccessMask = VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT; depthBarrier.dstAccessMask = 0; - m_vkContext->m_vk.CmdPipelineBarrier( + m_vkContext->m_vk->CmdPipelineBarrier( m_vkCmdBuf, VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT | VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT, @@ -292,12 +300,11 @@ } } -RenderPass::~RenderPass() { finish(); } +RenderPassVulkan::~RenderPassVulkan() { finish(); } -RenderPass::RenderPass(RenderPass&& other) noexcept +RenderPassVulkan::RenderPassVulkan(RenderPassVulkan&& other) noexcept { #if defined(ORE_BACKEND_VK) - moveCrossBackendFieldsFrom(other); m_vkContext = other.m_vkContext; m_currentPipeline = std::move(other.m_currentPipeline); m_vkCmdBuf = other.m_vkCmdBuf; @@ -320,21 +327,19 @@ #endif } -RenderPass& RenderPass::operator=(RenderPass&& other) noexcept +RenderPassVulkan& RenderPassVulkan::operator=(RenderPassVulkan&& other) noexcept { if (this != &other) { finish(); - new (this) RenderPass(std::move(other)); + new (this) RenderPassVulkan(std::move(other)); } return *this; } -void RenderPass::validate() const +void RenderPassVulkan::validate() const { assert(!m_finished && "RenderPass has already been finished"); } -#endif // !ORE_BACKEND_GL - } // namespace rive::ore
diff --git a/renderer/src/ore/vulkan/ore_render_pass_vulkan.hpp b/renderer/src/ore/vulkan/ore_render_pass_vulkan.hpp new file mode 100644 index 0000000..ebbbc47 --- /dev/null +++ b/renderer/src/ore/vulkan/ore_render_pass_vulkan.hpp
@@ -0,0 +1,81 @@ +#pragma once +#include "rive/renderer/ore/ore_render_pass.hpp" +#include "ore_pipeline_vulkan.hpp" +#include "rive/refcnt.hpp" +#include <vulkan/vulkan.h> +#include <cstdint> + +namespace rive::gpu +{ +class RenderTargetVulkan; +} + +namespace rive::ore +{ +class ContextVulkan; + +class RenderPassVulkan : public RenderPass +{ +public: + void setPipeline(Pipeline* pipeline) override; + void setVertexBuffer(uint32_t slot, + Buffer* buffer, + uint32_t offset = 0) override; + void setIndexBuffer(Buffer* buffer, + IndexFormat format, + uint32_t offset = 0) override; + void setBindGroup(uint32_t groupIndex, + BindGroup* bg, + const uint32_t* dynamicOffsets = nullptr, + uint32_t dynamicOffsetCount = 0) override; + void setViewport(float x, + float y, + float width, + float height, + float minDepth = 0.0f, + float maxDepth = 1.0f) override; + void setScissorRect(uint32_t x, + uint32_t y, + uint32_t width, + uint32_t height) override; + void setStencilReference(uint32_t ref) override; + void setBlendColor(float r, float g, float b, float a) override; + void draw(uint32_t vertexCount, + uint32_t instanceCount = 1, + uint32_t firstVertex = 0, + uint32_t firstInstance = 0) override; + void drawIndexed(uint32_t indexCount, + uint32_t instanceCount = 1, + uint32_t firstIndex = 0, + int32_t baseVertex = 0, + uint32_t firstInstance = 0) override; + void finish() override; + + void validate() const override; + + RenderPassVulkan() = default; + RenderPassVulkan(Context* context) : RenderPass(context) {} + ~RenderPassVulkan() override; + RenderPassVulkan(RenderPassVulkan&& other) noexcept; + RenderPassVulkan& operator=(RenderPassVulkan&&) noexcept; + +private: + friend class ContextVulkan; + + ContextVulkan* m_vkContext = nullptr; // weak ref + rcp<PipelineVulkan> m_currentPipeline; + VkCommandBuffer m_vkCmdBuf = VK_NULL_HANDLE; + VkFramebuffer m_vkFramebuffer = VK_NULL_HANDLE; + VkBuffer m_vkIndexBuffer = VK_NULL_HANDLE; + VkIndexType m_vkIndexType = VK_INDEX_TYPE_UINT16; + uint32_t m_vkIndexOffset = 0; + VkImage m_vkColorImages[4] = {}; + uint32_t m_vkColorBaseLayer[4] = {}; + uint32_t m_vkColorLayerCount[4] = {}; + uint32_t m_vkColorCount = 0; + gpu::RenderTargetVulkan* m_vkColorRenderTargets[4] = {}; // weak refs + VkImage m_vkDepthImage = VK_NULL_HANDLE; + uint32_t m_vkDepthBaseLayer = 0; + uint32_t m_vkDepthLayerCount = 1; +}; +} // namespace rive::ore
diff --git a/renderer/src/ore/vulkan/ore_resources_vk_gl.cpp b/renderer/src/ore/vulkan/ore_resources_vk_gl.cpp deleted file mode 100644 index eafc764..0000000 --- a/renderer/src/ore/vulkan/ore_resources_vk_gl.cpp +++ /dev/null
@@ -1,691 +0,0 @@ -/* - * Copyright 2025 Rive - */ - -// Unified resource method implementations for VK+GL dual-backend builds. -// Each resource knows which backend created it by which handle is non-null. -// No dispatch abstraction -- just direct handle checks. - -#if defined(ORE_BACKEND_VK) && defined(ORE_BACKEND_GL) - -#include "rive/renderer/gl/load_gles_extensions.hpp" -#include "rive/renderer/ore/ore_buffer.hpp" -#include "rive/renderer/ore/ore_texture.hpp" -#include "rive/renderer/ore/ore_pipeline.hpp" -#include "rive/renderer/ore/ore_sampler.hpp" -#include "rive/renderer/ore/ore_shader_module.hpp" -#include "rive/renderer/ore/ore_bind_group.hpp" -#include "rive/renderer/ore/ore_context_vulkan.hpp" - -#include "ore_vulkan_dsl.hpp" // for kVkMaxGroups - -#include <vk_mem_alloc.h> -#include <cassert> -#include <cstring> - -namespace rive::ore -{ - -// ============================================================================ -// Buffer -// ============================================================================ - -void Buffer::update(const void* data, uint32_t size, uint32_t offset) -{ - assert(offset + size <= m_size); - - if (m_glBuffer != 0) - { - if (m_usage == BufferUsage::index) - { - // WebGL forbids binding a buffer to GL_ELEMENT_ARRAY_BUFFER if it - // was ever bound to a different target, so index buffers must use - // their native target. GL_ELEMENT_ARRAY_BUFFER is VAO state, so we - // save/restore the current binding to avoid clobbering the host - // renderer's VAO. - GLint prevEBO; - glGetIntegerv(GL_ELEMENT_ARRAY_BUFFER_BINDING, &prevEBO); - glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_glBuffer); - glBufferSubData(GL_ELEMENT_ARRAY_BUFFER, offset, size, data); - glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, prevEBO); - } - else - { - // Non-index buffers use GL_COPY_WRITE_BUFFER to avoid disturbing - // the host renderer's VAO element-buffer binding. - glBindBuffer(GL_COPY_WRITE_BUFFER, m_glBuffer); - glBufferSubData(GL_COPY_WRITE_BUFFER, offset, size, data); - glBindBuffer(GL_COPY_WRITE_BUFFER, 0); - } - return; - } - - assert(m_vkMappedPtr != nullptr); - memcpy(static_cast<uint8_t*>(m_vkMappedPtr) + offset, data, size); -} - -void Buffer::onRefCntReachedZero() const -{ - if (m_glBuffer != 0) - { - GLuint buf = m_glBuffer; - glDeleteBuffers(1, &buf); - delete this; - return; - } - - VmaAllocator allocator = m_vmaAllocator; - VkBuffer vkBuf = m_vkBuffer; - VmaAllocation alloc = m_vmaAllocation; - ContextVulkan* ctx = m_vkOreContext; - - auto destroy = [=]() { - if (vkBuf != VK_NULL_HANDLE) - vmaDestroyBuffer(allocator, vkBuf, alloc); - }; - - delete this; - - if (ctx != nullptr) - ctx->vkDeferDestroy(std::move(destroy)); - else - destroy(); -} - -// ============================================================================ -// Texture -- local helpers -// ============================================================================ - -// GL format + type for upload (local to this TU). -static GLenum oreFormatToGLFormat(TextureFormat fmt) -{ - switch (fmt) - { - case TextureFormat::r8unorm: - case TextureFormat::r16float: - case TextureFormat::r32float: - return GL_RED; - case TextureFormat::rg8unorm: - case TextureFormat::rg16float: - case TextureFormat::rg32float: - return GL_RG; - case TextureFormat::rgba8unorm: - case TextureFormat::rgba8snorm: - case TextureFormat::bgra8unorm: - case TextureFormat::rgba16float: - case TextureFormat::rgba32float: - return GL_RGBA; - case TextureFormat::rgb10a2unorm: - return GL_RGBA; - case TextureFormat::r11g11b10float: - return GL_RGB; - case TextureFormat::depth16unorm: - case TextureFormat::depth32float: - return GL_DEPTH_COMPONENT; - case TextureFormat::depth24plusStencil8: - case TextureFormat::depth32floatStencil8: - return GL_DEPTH_STENCIL; - default: - RIVE_UNREACHABLE(); - } -} - -static GLenum oreFormatToGLType(TextureFormat fmt) -{ - switch (fmt) - { - case TextureFormat::r8unorm: - case TextureFormat::rg8unorm: - case TextureFormat::rgba8unorm: - case TextureFormat::bgra8unorm: - return GL_UNSIGNED_BYTE; - case TextureFormat::rgba8snorm: - return GL_BYTE; - case TextureFormat::rgba16float: - case TextureFormat::rg16float: - case TextureFormat::r16float: - return GL_HALF_FLOAT; - case TextureFormat::rgba32float: - case TextureFormat::rg32float: - case TextureFormat::r32float: - case TextureFormat::depth32float: - return GL_FLOAT; - case TextureFormat::rgb10a2unorm: - return GL_UNSIGNED_INT_2_10_10_10_REV; - case TextureFormat::r11g11b10float: - return GL_UNSIGNED_INT_10F_11F_11F_REV; - case TextureFormat::depth16unorm: - return GL_UNSIGNED_SHORT; - case TextureFormat::depth24plusStencil8: - return GL_UNSIGNED_INT_24_8; - case TextureFormat::depth32floatStencil8: - return GL_FLOAT_32_UNSIGNED_INT_24_8_REV; - default: - RIVE_UNREACHABLE(); - } -} - -// VK helpers (local to this TU). -static bool isDepthStencilFormat(TextureFormat fmt) -{ - switch (fmt) - { - case TextureFormat::depth16unorm: - case TextureFormat::depth24plusStencil8: - case TextureFormat::depth32float: - case TextureFormat::depth32floatStencil8: - return true; - default: - return false; - } -} - -static bool hasStencil(TextureFormat fmt) -{ - return fmt == TextureFormat::depth24plusStencil8 || - fmt == TextureFormat::depth32floatStencil8; -} - -static VkImageAspectFlags aspectMask(TextureFormat fmt) -{ - if (isDepthStencilFormat(fmt)) - { - VkImageAspectFlags flags = VK_IMAGE_ASPECT_DEPTH_BIT; - if (hasStencil(fmt)) - flags |= VK_IMAGE_ASPECT_STENCIL_BIT; - return flags; - } - return VK_IMAGE_ASPECT_COLOR_BIT; -} - -// Transition an image from one layout to another using a pipeline barrier. -static void transitionLayout(PFN_vkCmdPipelineBarrier pfnCmdPipelineBarrier, - VkCommandBuffer cmdBuf, - VkImage image, - VkImageAspectFlags aspect, - VkImageLayout oldLayout, - VkImageLayout newLayout, - uint32_t mipCount = 1, - uint32_t layerCount = 1) -{ - VkImageMemoryBarrier barrier{}; - barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER; - barrier.oldLayout = oldLayout; - barrier.newLayout = newLayout; - barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; - barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; - barrier.image = image; - barrier.subresourceRange.aspectMask = aspect; - barrier.subresourceRange.baseMipLevel = 0; - barrier.subresourceRange.levelCount = mipCount; - barrier.subresourceRange.baseArrayLayer = 0; - barrier.subresourceRange.layerCount = layerCount; - - VkPipelineStageFlags srcStage = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT; - VkPipelineStageFlags dstStage = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT; - - if (oldLayout == VK_IMAGE_LAYOUT_UNDEFINED && - newLayout == VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL) - { - barrier.srcAccessMask = 0; - barrier.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; - srcStage = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT; - dstStage = VK_PIPELINE_STAGE_TRANSFER_BIT; - } - else if (oldLayout == VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL && - newLayout == VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL) - { - barrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; - barrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT; - srcStage = VK_PIPELINE_STAGE_TRANSFER_BIT; - dstStage = VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT; - } - else if (oldLayout == VK_IMAGE_LAYOUT_UNDEFINED && - newLayout == VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL) - { - barrier.srcAccessMask = 0; - barrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT; - srcStage = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT; - dstStage = VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT; - } - else if (oldLayout == VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL && - newLayout == VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL) - { - barrier.srcAccessMask = VK_ACCESS_SHADER_READ_BIT; - barrier.dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT; - srcStage = VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT; - dstStage = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT; - } - else if (oldLayout == VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL && - newLayout == VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL) - { - barrier.srcAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT; - barrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT; - srcStage = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT; - dstStage = VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT; - } - else if (oldLayout == VK_IMAGE_LAYOUT_UNDEFINED && - newLayout == VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL) - { - barrier.srcAccessMask = 0; - barrier.dstAccessMask = VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | - VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT; - srcStage = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT; - dstStage = VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT; - } - else - { - // Generic fallback -- conservative but correct. - barrier.srcAccessMask = VK_ACCESS_MEMORY_WRITE_BIT; - barrier.dstAccessMask = - VK_ACCESS_MEMORY_READ_BIT | VK_ACCESS_MEMORY_WRITE_BIT; - srcStage = VK_PIPELINE_STAGE_ALL_COMMANDS_BIT; - dstStage = VK_PIPELINE_STAGE_ALL_COMMANDS_BIT; - } - - pfnCmdPipelineBarrier(cmdBuf, - srcStage, - dstStage, - 0, - 0, - nullptr, - 0, - nullptr, - 1, - &barrier); -} - -// ============================================================================ -// Texture -// ============================================================================ - -void Texture::upload(const TextureDataDesc& data) -{ - if (m_glTexture != 0) - { - // GL path. - assert(data.data != nullptr); - - glBindTexture(m_glTarget, m_glTexture); - - GLenum format = oreFormatToGLFormat(m_format); - GLenum type = oreFormatToGLType(m_format); - - // Honor `bytesPerRow` / `rowsPerImage` for non-tightly-packed - // source data via `GL_UNPACK_ROW_LENGTH` / `GL_UNPACK_IMAGE_HEIGHT`. - // Save + restore so we don't trash the host's pixel-store state. - // Pre-fix the combined VK+GL backend ignored these fields entirely - // — uploads from a sub-rect of a larger source buffer (or from a - // layout that pads rows) read garbage bytes between rows. The - // standalone GL TU (`ore_texture_gl.cpp`) had this from the - // Phase 3 GL fix, but this combined-backend TU was never - // updated and silently shipped the broken behaviour on every - // build that compiles both VK and GL (e.g. Android). - GLint savedRowLength = 0, savedImageHeight = 0; - glGetIntegerv(GL_UNPACK_ROW_LENGTH, &savedRowLength); - glGetIntegerv(GL_UNPACK_IMAGE_HEIGHT, &savedImageHeight); - const uint32_t bpt = textureFormatBytesPerTexel(m_format); - if (data.bytesPerRow != 0 && bpt != 0 && (data.bytesPerRow % bpt) == 0) - { - glPixelStorei(GL_UNPACK_ROW_LENGTH, - static_cast<GLint>(data.bytesPerRow / bpt)); - } - if (data.rowsPerImage != 0) - { - glPixelStorei(GL_UNPACK_IMAGE_HEIGHT, - static_cast<GLint>(data.rowsPerImage)); - } - - if (m_glTarget == GL_TEXTURE_3D || m_glTarget == GL_TEXTURE_2D_ARRAY) - { - glTexSubImage3D(m_glTarget, - data.mipLevel, - data.x, - data.y, - data.layer, - data.width, - data.height, - data.depth, - format, - type, - data.data); - } - else if (m_glTarget == GL_TEXTURE_CUBE_MAP) - { - glTexSubImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + data.layer, - data.mipLevel, - data.x, - data.y, - data.width, - data.height, - format, - type, - data.data); - } - else - { - glTexSubImage2D(m_glTarget, - data.mipLevel, - data.x, - data.y, - data.width, - data.height, - format, - type, - data.data); - } - - glPixelStorei(GL_UNPACK_ROW_LENGTH, savedRowLength); - glPixelStorei(GL_UNPACK_IMAGE_HEIGHT, savedImageHeight); - - glBindTexture(m_glTarget, 0); - return; - } - - // VK staging upload path — resolve the current frame CB and VK - // dispatch table from the owning Context (owned or host-external). - assert(m_vkOreContext != nullptr); - VkCommandBuffer cmdBuf = m_vkOreContext->m_vkCommandBuffer; - auto pfnCmdPipelineBarrier = m_vkOreContext->m_vk.CmdPipelineBarrier; - auto pfnCmdCopyBufferToImage = m_vkOreContext->m_vk.CmdCopyBufferToImage; - assert(cmdBuf != VK_NULL_HANDLE); - assert(m_vkImage != VK_NULL_HANDLE); - - // Determine byte size of the upload region. - uint32_t bytesPerRow = data.bytesPerRow; - uint32_t height = data.height > 0 ? data.height : m_height; - uint32_t depth = data.depth > 0 ? data.depth : m_depthOrArrayLayers; - VkDeviceSize uploadSize = - static_cast<VkDeviceSize>(bytesPerRow) * height * depth; - - // Create a transient host-visible staging buffer. - VkBufferCreateInfo bufCI{}; - bufCI.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO; - bufCI.size = uploadSize; - bufCI.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT; - - VmaAllocationCreateInfo allocCI{}; - allocCI.usage = VMA_MEMORY_USAGE_CPU_ONLY; - allocCI.flags = VMA_ALLOCATION_CREATE_MAPPED_BIT; - - VmaAllocationInfo allocInfo{}; - VkBuffer stagingBuf = VK_NULL_HANDLE; - VmaAllocation stagingAlloc = VK_NULL_HANDLE; - vmaCreateBuffer(m_vmaAllocator, - &bufCI, - &allocCI, - &stagingBuf, - &stagingAlloc, - &allocInfo); - - memcpy(allocInfo.pMappedData, data.data, static_cast<size_t>(uploadSize)); - - // Transition to TRANSFER_DST. - transitionLayout(pfnCmdPipelineBarrier, - cmdBuf, - m_vkImage, - aspectMask(m_format), - m_vkLayout, - VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, - m_numMipmaps, - m_depthOrArrayLayers); - m_vkLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL; - - // Copy staging buffer -> image. `bufferRowLength` and - // `bufferImageHeight` are in texels — 0 means "tightly packed at - // imageExtent". When the caller's source has padding (e.g. a - // sub-rect of a larger image, or `bytesPerRow > width * - // bytesPerTexel`), the staging copy must honour that pitch or the - // image comes back with the padding bytes interleaved into every - // other row. Pre-fix this was hardcoded to 0 — the - // `ore_array_upload` GM (Phase 4 witness) caught it on every - // Android Vulkan target by uploading with a 2× row stride filled - // with `0xCC` sentinel bytes that then leaked into the rendered - // texture as alternating colour/grey stripes. - const uint32_t bptVK = textureFormatBytesPerTexel(m_format); - VkBufferImageCopy region{}; - region.bufferOffset = 0; - region.bufferRowLength = - (data.bytesPerRow != 0 && bptVK != 0 && (data.bytesPerRow % bptVK) == 0) - ? data.bytesPerRow / bptVK - : 0; - region.bufferImageHeight = data.rowsPerImage; - region.imageSubresource.aspectMask = aspectMask(m_format); - region.imageSubresource.mipLevel = data.mipLevel; - region.imageSubresource.baseArrayLayer = data.layer; - region.imageSubresource.layerCount = 1; - region.imageOffset = {static_cast<int32_t>(data.x), - static_cast<int32_t>(data.y), - static_cast<int32_t>(data.z)}; - region.imageExtent = {data.width > 0 ? data.width : m_width, height, depth}; - - pfnCmdCopyBufferToImage(cmdBuf, - stagingBuf, - m_vkImage, - VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, - 1, - ®ion); - - // Transition back to SHADER_READ_ONLY. - transitionLayout(pfnCmdPipelineBarrier, - cmdBuf, - m_vkImage, - aspectMask(m_format), - VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, - VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, - m_numMipmaps, - m_depthOrArrayLayers); - m_vkLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; - - // Defer staging buffer destruction to Context::endFrame(), which - // submits the command buffer and waits on the fence before cleaning up. - m_vkOreContext->m_vkDeferredStagingBuffers.push_back( - {stagingBuf, stagingAlloc}); -} - -void Texture::onRefCntReachedZero() const -{ - if (m_glTexture != 0 || m_glRenderbuffer != 0) - { - // GL path. - if (m_glRenderbuffer != 0 && m_glOwnsTexture) - { - GLuint rb = m_glRenderbuffer; - glDeleteRenderbuffers(1, &rb); - } - if (m_glTexture != 0 && m_glOwnsTexture) - { - GLuint tex = m_glTexture; - glDeleteTextures(1, &tex); - } - delete this; - return; - } - - // VK path — only destroy VMA-owned images (borrowed textures have - // m_vmaAllocation==null). - VmaAllocator allocator = m_vmaAllocator; - VkImage image = m_vkImage; - VmaAllocation alloc = m_vmaAllocation; - ContextVulkan* ctx = m_vkOreContext; - - auto destroy = [=]() { - if (image != VK_NULL_HANDLE && alloc != VK_NULL_HANDLE) - vmaDestroyImage(allocator, image, alloc); - }; - - delete this; - - if (ctx != nullptr) - ctx->vkDeferDestroy(std::move(destroy)); - else - destroy(); -} - -// ============================================================================ -// TextureView -// ============================================================================ - -void TextureView::onRefCntReachedZero() const -{ - if (m_glTextureView != 0) - { - GLuint tex = m_glTextureView; - glDeleteTextures(1, &tex); - delete this; - return; - } - - VkDevice dev = m_vkDevice; - VkImageView view = m_vkImageView; - auto destroyFn = m_vkDestroyImageView; - ContextVulkan* ctx = m_vkOreContext; - - auto destroy = [=]() { - if (view != VK_NULL_HANDLE && destroyFn != nullptr) - destroyFn(dev, view, nullptr); - }; - - delete this; - - if (ctx != nullptr) - ctx->vkDeferDestroy(std::move(destroy)); - else - destroy(); -} - -// ============================================================================ -// Pipeline -// ============================================================================ - -void Pipeline::onRefCntReachedZero() const -{ - if (m_glProgram != 0) - { - glDeleteProgram(m_glProgram); - delete this; - return; - } - - // VK path: per-group VkDescriptorSetLayouts are owned by BindGroupLayout - // (m_layouts[]) — Pipeline only destroys its own VkPipeline + Layout. - VkDevice dev = m_vkDevice; - VkPipeline pipe = m_vkPipeline; - VkPipelineLayout layout = m_vkPipelineLayout; - auto destroyPipe = m_vkDestroyPipeline; - auto destroyLayout = m_vkDestroyPipelineLayout; - ContextVulkan* ctx = m_vkOreContext; - - auto destroy = [=]() { - if (pipe != VK_NULL_HANDLE && destroyPipe != nullptr) - destroyPipe(dev, pipe, nullptr); - if (layout != VK_NULL_HANDLE && destroyLayout != nullptr) - destroyLayout(dev, layout, nullptr); - }; - - delete this; - - if (ctx != nullptr) - ctx->vkDeferDestroy(std::move(destroy)); - else - destroy(); -} - -// ============================================================================ -// BindGroupLayout -// ============================================================================ - -void BindGroupLayout::onRefCntReachedZero() const -{ - VkDevice dev = m_vkDevice; - VkDescriptorSetLayout dsl = m_vkDSL; - auto destroyDSL = m_vkDestroyDescriptorSetLayout; - // In VK+GL builds m_context can point at either a ContextVulkan (set by - // ContextVulkan::makeBindGroupLayout) or a ContextGL (set by - // ContextGL::makeBindGroupLayout). m_vkDSL is the unambiguous signal that - // this is a VK-created layout — GL layouts leave it VK_NULL_HANDLE — so we - // only downcast and defer when there is actually a Vulkan handle to - // destroy. - ContextVulkan* ctx = (dsl != VK_NULL_HANDLE) - ? static_cast<ContextVulkan*>(m_context) - : nullptr; - - auto destroy = [=]() { - if (dsl != VK_NULL_HANDLE && destroyDSL != nullptr) - destroyDSL(dev, dsl, nullptr); - }; - - delete this; - - if (ctx != nullptr) - ctx->vkDeferDestroy(std::move(destroy)); - else - destroy(); -} - -// ============================================================================ -// Sampler -// ============================================================================ - -void Sampler::onRefCntReachedZero() const -{ - if (m_glSampler != 0) - { - GLuint samp = m_glSampler; - glDeleteSamplers(1, &samp); - delete this; - return; - } - - VkDevice dev = m_vkDevice; - VkSampler samp = m_vkSampler; - auto destroyFn = m_vkDestroySampler; - ContextVulkan* ctx = m_vkOreContext; - - auto destroy = [=]() { - if (samp != VK_NULL_HANDLE && destroyFn != nullptr) - destroyFn(dev, samp, nullptr); - }; - - delete this; - - if (ctx != nullptr) - ctx->vkDeferDestroy(std::move(destroy)); - else - destroy(); -} - -// ============================================================================ -// ShaderModule -// ============================================================================ - -void ShaderModule::onRefCntReachedZero() const -{ - if (m_glShader != 0) - { - glDeleteShader(m_glShader); - } - else if (m_vkShaderModule != VK_NULL_HANDLE && - m_vkDestroyShaderModule != nullptr) - { - m_vkDestroyShaderModule(m_vkDevice, m_vkShaderModule, nullptr); - } - delete this; -} - -// ============================================================================ -// BindGroup -// ============================================================================ - -void BindGroup::onRefCntReachedZero() const -{ - // Deferred destruction is handled at the Lua GC level via - // Context::deferBindGroupDestroy(), which keeps the rcp<> alive - // until after endFrame(). By the time refcount reaches zero here, - // the GPU is guaranteed to be done. - delete this; -} - -} // namespace rive::ore - -#endif // ORE_BACKEND_VK && ORE_BACKEND_GL
diff --git a/renderer/src/ore/vulkan/ore_sampler_vulkan.cpp b/renderer/src/ore/vulkan/ore_sampler_vulkan.cpp index 31ce9d7..fef97e9 100644 --- a/renderer/src/ore/vulkan/ore_sampler_vulkan.cpp +++ b/renderer/src/ore/vulkan/ore_sampler_vulkan.cpp
@@ -2,15 +2,13 @@ * Copyright 2025 Rive */ -#include "rive/renderer/ore/ore_sampler.hpp" +#include "ore_sampler_vulkan.hpp" #include "rive/renderer/ore/ore_context_vulkan.hpp" namespace rive::ore { -#if !defined(ORE_BACKEND_GL) - -void Sampler::onRefCntReachedZero() const +void SamplerVulkan::onRefCntReachedZero() const { VkDevice dev = m_vkDevice; VkSampler samp = m_vkSampler; @@ -30,6 +28,4 @@ destroy(); } -#endif // !ORE_BACKEND_GL - } // namespace rive::ore
diff --git a/renderer/src/ore/vulkan/ore_sampler_vulkan.hpp b/renderer/src/ore/vulkan/ore_sampler_vulkan.hpp new file mode 100644 index 0000000..ebfa0d1 --- /dev/null +++ b/renderer/src/ore/vulkan/ore_sampler_vulkan.hpp
@@ -0,0 +1,26 @@ +#pragma once +#include "rive/renderer/ore/ore_sampler.hpp" +#include <vulkan/vulkan.h> + +namespace rive::ore +{ +class ContextVulkan; + +class SamplerVulkan : public LITE_RTTI_OVERRIDE(Sampler, SamplerVulkan) +{ +public: + SamplerVulkan() = default; + ~SamplerVulkan() override = default; + // Defers vkDestroySampler through ContextVulkan::vkDeferDestroy(). + void onRefCntReachedZero() const override; + +private: + friend class ContextVulkan; + friend class RenderPassVulkan; + VkDevice m_vkDevice = VK_NULL_HANDLE; // Weak ref. + VkSampler m_vkSampler = VK_NULL_HANDLE; + PFN_vkDestroySampler m_vkDestroySampler = nullptr; + // Back-ref for deferred destruction. Weak ref. + ContextVulkan* m_vkOreContext = nullptr; +}; +} // namespace rive::ore
diff --git a/renderer/src/ore/vulkan/ore_shader_module_vulkan.cpp b/renderer/src/ore/vulkan/ore_shader_module_vulkan.cpp index 4eb8fb8..f0e467b 100644 --- a/renderer/src/ore/vulkan/ore_shader_module_vulkan.cpp +++ b/renderer/src/ore/vulkan/ore_shader_module_vulkan.cpp
@@ -2,15 +2,13 @@ * Copyright 2025 Rive */ -#include "rive/renderer/ore/ore_shader_module.hpp" +#include "ore_shader_module_vulkan.hpp" #include "rive/renderer/ore/ore_context_vulkan.hpp" namespace rive::ore { -#if !defined(ORE_BACKEND_GL) - -void ShaderModule::onRefCntReachedZero() const +void ShaderModuleVulkan::onRefCntReachedZero() const { if (m_vkShaderModule != VK_NULL_HANDLE && m_vkDestroyShaderModule != nullptr) @@ -20,6 +18,4 @@ delete this; } -#endif // !ORE_BACKEND_GL - } // namespace rive::ore
diff --git a/renderer/src/ore/vulkan/ore_shader_module_vulkan.hpp b/renderer/src/ore/vulkan/ore_shader_module_vulkan.hpp new file mode 100644 index 0000000..01dec7e --- /dev/null +++ b/renderer/src/ore/vulkan/ore_shader_module_vulkan.hpp
@@ -0,0 +1,24 @@ +#pragma once +#include "rive/renderer/ore/ore_shader_module.hpp" +#include <vulkan/vulkan.h> + +namespace rive::ore +{ +class ContextVulkan; + +class ShaderModuleVulkan + : public LITE_RTTI_OVERRIDE(ShaderModule, ShaderModuleVulkan) +{ +public: + ShaderModuleVulkan() = default; + ~ShaderModuleVulkan() override = default; + void onRefCntReachedZero() const override; + +private: + friend class ContextVulkan; + friend class RenderPassVulkan; + VkDevice m_vkDevice = VK_NULL_HANDLE; // Weak ref. + VkShaderModule m_vkShaderModule = VK_NULL_HANDLE; + PFN_vkDestroyShaderModule m_vkDestroyShaderModule = nullptr; +}; +} // namespace rive::ore
diff --git a/renderer/src/ore/vulkan/ore_texture_vulkan.cpp b/renderer/src/ore/vulkan/ore_texture_vulkan.cpp index d132b2b..7ee870a 100644 --- a/renderer/src/ore/vulkan/ore_texture_vulkan.cpp +++ b/renderer/src/ore/vulkan/ore_texture_vulkan.cpp
@@ -2,7 +2,7 @@ * Copyright 2025 Rive */ -#include "rive/renderer/ore/ore_texture.hpp" +#include "ore_texture_vulkan.hpp" #include "rive/renderer/ore/ore_context_vulkan.hpp" #include <vk_mem_alloc.h> @@ -16,65 +16,6 @@ // Helpers // ============================================================================ -static VkFormat oreFormatToVk(TextureFormat fmt) -{ - switch (fmt) - { - case TextureFormat::r8unorm: - return VK_FORMAT_R8_UNORM; - case TextureFormat::rg8unorm: - return VK_FORMAT_R8G8_UNORM; - case TextureFormat::rgba8unorm: - return VK_FORMAT_R8G8B8A8_UNORM; - case TextureFormat::rgba8snorm: - return VK_FORMAT_R8G8B8A8_SNORM; - case TextureFormat::bgra8unorm: - return VK_FORMAT_B8G8R8A8_UNORM; - case TextureFormat::rgba16float: - return VK_FORMAT_R16G16B16A16_SFLOAT; - case TextureFormat::rg16float: - return VK_FORMAT_R16G16_SFLOAT; - case TextureFormat::r16float: - return VK_FORMAT_R16_SFLOAT; - case TextureFormat::rgba32float: - return VK_FORMAT_R32G32B32A32_SFLOAT; - case TextureFormat::rg32float: - return VK_FORMAT_R32G32_SFLOAT; - case TextureFormat::r32float: - return VK_FORMAT_R32_SFLOAT; - case TextureFormat::rgb10a2unorm: - return VK_FORMAT_A2B10G10R10_UNORM_PACK32; - case TextureFormat::r11g11b10float: - return VK_FORMAT_B10G11R11_UFLOAT_PACK32; - case TextureFormat::depth16unorm: - return VK_FORMAT_D16_UNORM; - case TextureFormat::depth24plusStencil8: - return VK_FORMAT_D24_UNORM_S8_UINT; - case TextureFormat::depth32float: - return VK_FORMAT_D32_SFLOAT; - case TextureFormat::depth32floatStencil8: - return VK_FORMAT_D32_SFLOAT_S8_UINT; - case TextureFormat::bc1unorm: - return VK_FORMAT_BC1_RGBA_UNORM_BLOCK; - case TextureFormat::bc3unorm: - return VK_FORMAT_BC3_UNORM_BLOCK; - case TextureFormat::bc7unorm: - return VK_FORMAT_BC7_UNORM_BLOCK; - case TextureFormat::etc2rgb8: - return VK_FORMAT_ETC2_R8G8B8_UNORM_BLOCK; - case TextureFormat::etc2rgba8: - return VK_FORMAT_ETC2_R8G8B8A8_UNORM_BLOCK; - case TextureFormat::astc4x4: - return VK_FORMAT_ASTC_4x4_UNORM_BLOCK; - case TextureFormat::astc6x6: - return VK_FORMAT_ASTC_6x6_UNORM_BLOCK; - case TextureFormat::astc8x8: - return VK_FORMAT_ASTC_8x8_UNORM_BLOCK; - } - assert(false && "Unhandled TextureFormat"); - return VK_FORMAT_UNDEFINED; -} - static bool isDepthStencilFormat(TextureFormat fmt) { switch (fmt) @@ -107,40 +48,6 @@ return VK_IMAGE_ASPECT_COLOR_BIT; } -static VkImageAspectFlags oreAspectToVk(TextureAspect aspect, TextureFormat fmt) -{ - switch (aspect) - { - case TextureAspect::all: - return aspectMask(fmt); - case TextureAspect::depthOnly: - return VK_IMAGE_ASPECT_DEPTH_BIT; - case TextureAspect::stencilOnly: - return VK_IMAGE_ASPECT_STENCIL_BIT; - } - assert(false); - return VK_IMAGE_ASPECT_COLOR_BIT; -} - -static VkImageViewType oreViewDimToVk(TextureViewDimension dim) -{ - switch (dim) - { - case TextureViewDimension::texture2D: - return VK_IMAGE_VIEW_TYPE_2D; - case TextureViewDimension::cube: - return VK_IMAGE_VIEW_TYPE_CUBE; - case TextureViewDimension::texture3D: - return VK_IMAGE_VIEW_TYPE_3D; - case TextureViewDimension::array2D: - return VK_IMAGE_VIEW_TYPE_2D_ARRAY; - case TextureViewDimension::cubeArray: - return VK_IMAGE_VIEW_TYPE_CUBE_ARRAY; - } - assert(false); - return VK_IMAGE_VIEW_TYPE_2D; -} - // Transition an image from one layout to another using a pipeline barrier // on the given command buffer. static void transitionLayout(PFN_vkCmdPipelineBarrier pfnCmdPipelineBarrier, @@ -243,9 +150,7 @@ // Texture // ============================================================================ -#if !defined(ORE_BACKEND_GL) - -void Texture::upload(const TextureDataDesc& data) +void TextureVulkan::upload(const TextureDataDesc& data) { // Staging upload records into whichever command buffer the owning // Context currently has open — either Ore's own CB (owned-CB mode) or @@ -253,8 +158,8 @@ // Texture can span both modes across its lifetime. assert(m_vkOreContext != nullptr); VkCommandBuffer cmdBuf = m_vkOreContext->m_vkCommandBuffer; - auto pfnCmdPipelineBarrier = m_vkOreContext->m_vk.CmdPipelineBarrier; - auto pfnCmdCopyBufferToImage = m_vkOreContext->m_vk.CmdCopyBufferToImage; + auto pfnCmdPipelineBarrier = m_vkOreContext->m_vk->CmdPipelineBarrier; + auto pfnCmdCopyBufferToImage = m_vkOreContext->m_vk->CmdCopyBufferToImage; assert(cmdBuf != VK_NULL_HANDLE); assert(m_vkImage != VK_NULL_HANDLE); @@ -350,7 +255,7 @@ {stagingBuf, stagingAlloc}); } -void Texture::onRefCntReachedZero() const +void TextureVulkan::onRefCntReachedZero() const { // Only destroy VMA-owned images (borrowed textures have // m_vmaAllocation==null). @@ -376,7 +281,7 @@ // TextureView // ============================================================================ -void TextureView::onRefCntReachedZero() const +void TextureViewVulkan::onRefCntReachedZero() const { VkDevice dev = m_vkDevice; VkImageView view = m_vkImageView; @@ -396,6 +301,4 @@ destroy(); } -#endif // !ORE_BACKEND_GL - } // namespace rive::ore
diff --git a/renderer/src/ore/vulkan/ore_texture_vulkan.hpp b/renderer/src/ore/vulkan/ore_texture_vulkan.hpp new file mode 100644 index 0000000..98b9811 --- /dev/null +++ b/renderer/src/ore/vulkan/ore_texture_vulkan.hpp
@@ -0,0 +1,55 @@ +#pragma once +#include "rive/renderer/ore/ore_texture.hpp" +#include "rive/renderer/vulkan/render_target_vulkan.hpp" +#include <vulkan/vulkan.h> +VK_DEFINE_HANDLE(VmaAllocator); +VK_DEFINE_HANDLE(VmaAllocation); + +namespace rive::ore +{ +class ContextVulkan; + +class TextureVulkan : public LITE_RTTI_OVERRIDE(Texture, TextureVulkan) +{ +public: + TextureVulkan(const TextureDesc& desc) : lite_rtti_override(desc) {} + // Destructor defers GPU image destruction via ContextVulkan. + ~TextureVulkan() override = default; + void upload(const TextureDataDesc& data) override; + // Defers vmaDestroyImage through ContextVulkan::vkDeferDestroy(). + void onRefCntReachedZero() const override; + +private: + friend class ContextVulkan; + friend class RenderPassVulkan; + VkImage m_vkImage = VK_NULL_HANDLE; + VmaAllocation m_vmaAllocation = VK_NULL_HANDLE; + VkImageLayout m_vkLayout = VK_IMAGE_LAYOUT_UNDEFINED; + VkDevice m_vkDevice = VK_NULL_HANDLE; // Weak ref. + VmaAllocator m_vmaAllocator = VK_NULL_HANDLE; // Weak ref. + // Back-ref so upload() and onRefCntReachedZero() can route through + // ContextVulkan. Weak ref. + ContextVulkan* m_vkOreContext = nullptr; +}; + +class TextureViewVulkan + : public LITE_RTTI_OVERRIDE(TextureView, TextureViewVulkan) +{ +public: + TextureViewVulkan(rcp<Texture> texture, const TextureViewDesc& desc) : + lite_rtti_override(std::move(texture), desc) + {} + ~TextureViewVulkan() override = default; + // Defers vkDestroyImageView through ContextVulkan::vkDeferDestroy(). + void onRefCntReachedZero() const override; + +private: + friend class ContextVulkan; + VkDevice m_vkDevice = VK_NULL_HANDLE; // Weak ref. + VkImageView m_vkImageView = VK_NULL_HANDLE; + PFN_vkDestroyImageView m_vkDestroyImageView = nullptr; + rive::gpu::RenderTargetVulkan* m_vkRenderTarget = nullptr; + // Back-ref for deferred destruction. Weak ref. + ContextVulkan* m_vkOreContext = nullptr; +}; +} // namespace rive::ore
diff --git a/renderer/src/ore/wgpu/ore_bind_group_layout_wgpu.hpp b/renderer/src/ore/wgpu/ore_bind_group_layout_wgpu.hpp new file mode 100644 index 0000000..2eec85e --- /dev/null +++ b/renderer/src/ore/wgpu/ore_bind_group_layout_wgpu.hpp
@@ -0,0 +1,21 @@ +#pragma once +#include "rive/renderer/ore/ore_bind_group_layout.hpp" +#include <webgpu/webgpu_cpp.h> + +namespace rive::ore +{ +class ContextWGPU; + +class BindGroupLayoutWGPU + : public LITE_RTTI_OVERRIDE(BindGroupLayout, BindGroupLayoutWGPU) +{ +public: + BindGroupLayoutWGPU() = default; + ~BindGroupLayoutWGPU() override = + default; // wgpu::BindGroupLayout RAII destructor releases + +private: + friend class ContextWGPU; + wgpu::BindGroupLayout m_wgpuBGL; +}; +} // namespace rive::ore
diff --git a/renderer/src/ore/wgpu/ore_bind_group_wgpu.cpp b/renderer/src/ore/wgpu/ore_bind_group_wgpu.cpp index 6d8d58a..3907694 100644 --- a/renderer/src/ore/wgpu/ore_bind_group_wgpu.cpp +++ b/renderer/src/ore/wgpu/ore_bind_group_wgpu.cpp
@@ -2,18 +2,4 @@ * Copyright 2025 Rive */ -#include "rive/renderer/ore/ore_bind_group.hpp" - -namespace rive::ore -{ - -void BindGroup::onRefCntReachedZero() const -{ - // Deferred destruction is handled at the Lua GC level via - // Context::deferBindGroupDestroy(), which keeps the rcp<> alive - // until after endFrame(). By the time refcount reaches zero here, - // the GPU is guaranteed to be done. - delete this; -} - -} // namespace rive::ore +#include "ore_bind_group_wgpu.hpp"
diff --git a/renderer/src/ore/wgpu/ore_bind_group_wgpu.hpp b/renderer/src/ore/wgpu/ore_bind_group_wgpu.hpp new file mode 100644 index 0000000..f0a540e --- /dev/null +++ b/renderer/src/ore/wgpu/ore_bind_group_wgpu.hpp
@@ -0,0 +1,21 @@ +#pragma once +#include "rive/renderer/ore/ore_bind_group.hpp" +#include <webgpu/webgpu_cpp.h> + +namespace rive::ore +{ +class ContextWGPU; + +class BindGroupWGPU : public LITE_RTTI_OVERRIDE(BindGroup, BindGroupWGPU) +{ +public: + BindGroupWGPU() = default; + ~BindGroupWGPU() override = + default; // wgpu::BindGroup RAII destructor releases + +private: + friend class ContextWGPU; + friend class RenderPassWGPU; + wgpu::BindGroup m_wgpuBindGroup; +}; +} // namespace rive::ore
diff --git a/renderer/src/ore/wgpu/ore_buffer_wgpu.cpp b/renderer/src/ore/wgpu/ore_buffer_wgpu.cpp index 0ddcfc4..5f32966 100644 --- a/renderer/src/ore/wgpu/ore_buffer_wgpu.cpp +++ b/renderer/src/ore/wgpu/ore_buffer_wgpu.cpp
@@ -2,23 +2,17 @@ * Copyright 2025 Rive */ -#include "rive/renderer/ore/ore_buffer.hpp" +#include "ore_buffer_wgpu.hpp" #include "rive/rive_types.hpp" namespace rive::ore { -void Buffer::update(const void* data, uint32_t size, uint32_t offset) +void BufferWGPU::update(const void* data, uint32_t size, uint32_t offset) { assert(offset + size <= m_size); assert(m_wgpuBuffer != nullptr); m_wgpuQueue.WriteBuffer(m_wgpuBuffer, offset, data, size); } -void Buffer::onRefCntReachedZero() const -{ - // wgpu::Buffer RAII destructor releases the GPU resource. - delete this; -} - } // namespace rive::ore
diff --git a/renderer/src/ore/wgpu/ore_buffer_wgpu.hpp b/renderer/src/ore/wgpu/ore_buffer_wgpu.hpp new file mode 100644 index 0000000..2cba374 --- /dev/null +++ b/renderer/src/ore/wgpu/ore_buffer_wgpu.hpp
@@ -0,0 +1,24 @@ +#pragma once +#include "rive/renderer/ore/ore_buffer.hpp" +#include <webgpu/webgpu_cpp.h> + +namespace rive::ore +{ +class ContextWGPU; + +class BufferWGPU : public LITE_RTTI_OVERRIDE(Buffer, BufferWGPU) +{ +public: + BufferWGPU(uint32_t size, BufferUsage usage) : + lite_rtti_override(size, usage) + {} + ~BufferWGPU() override = default; // wgpu::Buffer RAII destructor releases + void update(const void* data, uint32_t size, uint32_t offset) override; + +private: + friend class ContextWGPU; + friend class RenderPassWGPU; + wgpu::Buffer m_wgpuBuffer; + wgpu::Queue m_wgpuQueue; // Weak ref (addref'd copy). +}; +} // namespace rive::ore
diff --git a/renderer/src/ore/wgpu/ore_context_wgpu.cpp b/renderer/src/ore/wgpu/ore_context_wgpu.cpp index 9ce9aa8..2bfaed4 100644 --- a/renderer/src/ore/wgpu/ore_context_wgpu.cpp +++ b/renderer/src/ore/wgpu/ore_context_wgpu.cpp
@@ -3,12 +3,14 @@ */ #include "rive/renderer/ore/ore_context_wgpu.hpp" -#include "rive/renderer/ore/ore_buffer.hpp" -#include "rive/renderer/ore/ore_texture.hpp" -#include "rive/renderer/ore/ore_sampler.hpp" -#include "rive/renderer/ore/ore_shader_module.hpp" -#include "rive/renderer/ore/ore_pipeline.hpp" -#include "rive/renderer/ore/ore_render_pass.hpp" +#include "ore_buffer_wgpu.hpp" +#include "ore_texture_wgpu.hpp" +#include "ore_bind_group_wgpu.hpp" +#include "ore_bind_group_layout_wgpu.hpp" +#include "ore_sampler_wgpu.hpp" +#include "ore_shader_module_wgpu.hpp" +#include "ore_pipeline_wgpu.hpp" +#include "ore_render_pass_wgpu.hpp" #include "rive/renderer/render_canvas.hpp" #include "rive/renderer/webgpu/render_context_webgpu_impl.hpp" #include "rive/rive_types.hpp" @@ -413,7 +415,7 @@ return wgpu::ShaderModule::Acquire( wgpuDeviceCreateShaderModule(device.Get(), &descriptor)); } -#else +#elif RIVE_WAGYU static wgpu::ShaderModule compileWagyuShader(wgpu::Device device, const char* source, uint32_t codeSize, @@ -524,7 +526,7 @@ rcp<Buffer> ContextWGPU::makeBuffer(const BufferDesc& desc) { - auto buffer = rcp<Buffer>(new Buffer(desc.size, desc.usage)); + auto buffer = rcp<BufferWGPU>(new BufferWGPU(desc.size, desc.usage)); buffer->m_wgpuQueue = m_wgpuQueue; // addref'd copy for WriteBuffer wgpu::BufferUsage usage = wgpu::BufferUsage::CopyDst; @@ -563,7 +565,7 @@ rcp<Texture> ContextWGPU::makeTexture(const TextureDesc& desc) { - auto texture = rcp<Texture>(new Texture(desc)); + auto texture = rcp<TextureWGPU>(new TextureWGPU(desc)); texture->m_wgpuQueue = m_wgpuQueue; wgpu::TextureUsage usage = @@ -591,11 +593,11 @@ rcp<TextureView> ContextWGPU::makeTextureView(const TextureViewDesc& desc) { - Texture* tex = desc.texture; + auto tex = lite_rtti_cast<TextureWGPU*>(desc.texture); if (!tex) return nullptr; - auto view = rcp<TextureView>(new TextureView(ref_rcp(tex), desc)); + auto view = rcp<TextureViewWGPU>(new TextureViewWGPU(ref_rcp(tex), desc)); wgpu::TextureViewDescriptor wDesc{}; wDesc.dimension = oreViewDimToWGPU(desc.dimension); @@ -617,7 +619,7 @@ rcp<Sampler> ContextWGPU::makeSampler(const SamplerDesc& desc) { - auto sampler = rcp<Sampler>(new Sampler()); + auto sampler = rcp<SamplerWGPU>(new SamplerWGPU()); wgpu::SamplerDescriptor wDesc{}; wDesc.label = desc.label; @@ -647,7 +649,7 @@ rcp<ShaderModule> ContextWGPU::makeShaderModule(const ShaderModuleDesc& desc) { - auto module = rcp<ShaderModule>(new ShaderModule()); + auto module = rcp<ShaderModuleWGPU>(new ShaderModuleWGPU()); const char* source = static_cast<const char*>(desc.code); uint32_t codeSize = desc.codeSize > 0 @@ -661,7 +663,7 @@ compileDawnWGSLShader(m_wgpuDevice, source, codeSize); assert(module->m_wgpuShaderModule != nullptr && "Ore Dawn WGSL shader compilation failed"); -#else +#elif RIVE_WAGYU WGPUWagyuShaderLanguage language; if (desc.language == ShaderLanguage::wgsl) { @@ -694,7 +696,7 @@ rcp<Pipeline> ContextWGPU::makePipeline(const PipelineDesc& desc, std::string* outError) { - auto pipeline = rcp<Pipeline>(new Pipeline(desc)); + auto pipeline = rcp<PipelineWGPU>(new PipelineWGPU(desc)); // --- Vertex state --- // Flatten attribute arrays per buffer slot. @@ -729,7 +731,9 @@ } wgpu::VertexState vertexState{}; - vertexState.module = desc.vertexModule->m_wgpuShaderModule; + auto vertexModule = lite_rtti_cast<ShaderModuleWGPU*>(desc.vertexModule); + assert(vertexModule != nullptr); + vertexState.module = vertexModule->m_wgpuShaderModule; vertexState.entryPoint = desc.vertexEntryPoint; vertexState.bufferCount = desc.vertexBufferCount; vertexState.buffers = wBuffers; @@ -838,7 +842,10 @@ wgpu::FragmentState fragmentState{}; if (desc.fragmentModule != nullptr) { - fragmentState.module = desc.fragmentModule->m_wgpuShaderModule; + auto fragmentModule = + lite_rtti_cast<ShaderModuleWGPU*>(desc.fragmentModule); + assert(fragmentModule != nullptr); + fragmentState.module = fragmentModule->m_wgpuShaderModule; fragmentState.entryPoint = desc.fragmentEntryPoint; fragmentState.targetCount = desc.colorCount; fragmentState.targets = colorTargets; @@ -872,8 +879,12 @@ for (uint32_t g = 0; g < desc.bindGroupLayoutCount && g < kWGPUMaxGroups; ++g) { - if (desc.bindGroupLayouts[g] != nullptr) - rawBGLs[g] = desc.bindGroupLayouts[g]->m_wgpuBGL; + if (auto bindGroupLayouts = + lite_rtti_cast<BindGroupLayoutWGPU*>(desc.bindGroupLayouts[g]); + bindGroupLayouts != nullptr) + { + rawBGLs[g] = bindGroupLayouts->m_wgpuBGL; + } } wgpu::PipelineLayoutDescriptor plDesc{}; plDesc.label = desc.label ? desc.label : ""; @@ -918,7 +929,7 @@ kMaxBindGroups); return nullptr; } - auto layout = rcp<BindGroupLayout>(new BindGroupLayout()); + auto layout = rcp<BindGroupLayoutWGPU>(new BindGroupLayoutWGPU()); layout->m_context = this; layout->m_groupIndex = desc.groupIndex; layout->m_entries.reserve(desc.entryCount); @@ -947,7 +958,8 @@ setLastError("makeBindGroup: BindGroupDesc::layout is null"); return nullptr; } - BindGroupLayout* layout = desc.layout; + auto layout = lite_rtti_cast<BindGroupLayoutWGPU*>(desc.layout); + assert(layout != nullptr); if (layout->groupIndex() >= kMaxBindGroups) { setLastError("makeBindGroup: layout->groupIndex %u out of range [0, " @@ -957,7 +969,7 @@ return nullptr; } - auto bg = rcp<BindGroup>(new BindGroup()); + auto bg = rcp<BindGroupWGPU>(new BindGroupWGPU()); bg->m_context = this; bg->m_layoutRef = ref_rcp(layout); @@ -1013,10 +1025,12 @@ wgpu::BindGroupEntry& e = entries[idx++]; e = {}; e.binding = ubo.slot; - e.buffer = ubo.buffer->m_wgpuBuffer; + auto buffer = lite_rtti_cast<BufferWGPU*>(ubo.buffer); + assert(buffer != nullptr); + e.buffer = buffer->m_wgpuBuffer; e.offset = ubo.offset; - e.size = (ubo.size > 0) ? ubo.size : ubo.buffer->size(); - bg->m_retainedBuffers.push_back(ref_rcp(ubo.buffer)); + e.size = (ubo.size > 0) ? ubo.size : buffer->size(); + bg->m_retainedBuffers.push_back(ref_rcp(buffer)); } for (uint32_t i = 0; i < desc.textureCount; ++i) @@ -1027,8 +1041,10 @@ wgpu::BindGroupEntry& e = entries[idx++]; e = {}; e.binding = tex.slot; - e.textureView = tex.view->m_wgpuTextureView; - bg->m_retainedViews.push_back(ref_rcp(tex.view)); + auto view = lite_rtti_cast<TextureViewWGPU*>(tex.view); + assert(view != nullptr); + e.textureView = view->m_wgpuTextureView; + bg->m_retainedViews.push_back(ref_rcp(view)); } for (uint32_t i = 0; i < desc.samplerCount; ++i) @@ -1039,8 +1055,10 @@ wgpu::BindGroupEntry& e = entries[idx++]; e = {}; e.binding = samp.slot; - e.sampler = samp.sampler->m_wgpuSampler; - bg->m_retainedSamplers.push_back(ref_rcp(samp.sampler)); + auto sampler = lite_rtti_cast<SamplerWGPU*>(samp.sampler); + assert(sampler != nullptr); + e.sampler = sampler->m_wgpuSampler; + bg->m_retainedSamplers.push_back(ref_rcp(sampler)); } wgpu::BindGroupDescriptor bgDesc{}; @@ -1060,18 +1078,19 @@ // beginRenderPass // ============================================================================ -RenderPass ContextWGPU::beginRenderPass(const RenderPassDesc& desc, - std::string* outError) +std::unique_ptr<RenderPass> ContextWGPU::beginRenderPass( + const RenderPassDesc& desc, + std::string* outError) { finishActiveRenderPass(); assert(m_wgpuCommandEncoder != nullptr && "beginFrame must be called before beginRenderPass"); - RenderPass pass; - pass.m_context = this; - pass.m_wgpuContext = this; - pass.populateAttachmentMetadata(desc); + std::unique_ptr<RenderPassWGPU> pass = std::make_unique<RenderPassWGPU>(); + pass->m_context = this; + pass->m_wgpuContext = this; + pass->populateAttachmentMetadata(desc); // Color attachments. wgpu::RenderPassColorAttachment colorAttachments[4]; @@ -1079,9 +1098,15 @@ { const auto& ca = desc.colorAttachments[i]; wgpu::RenderPassColorAttachment& wca = colorAttachments[i]; - wca.view = ca.view ? ca.view->m_wgpuTextureView : nullptr; - wca.resolveTarget = - ca.resolveTarget ? ca.resolveTarget->m_wgpuTextureView : nullptr; + if (auto view = lite_rtti_cast<TextureViewWGPU*>(ca.view)) + { + wca.view = view->m_wgpuTextureView; + } + if (auto resolveTarget = + lite_rtti_cast<TextureViewWGPU*>(ca.resolveTarget)) + { + wca.resolveTarget = resolveTarget->m_wgpuTextureView; + } wca.loadOp = (ca.loadOp == LoadOp::clear) ? wgpu::LoadOp::Clear : wgpu::LoadOp::Load; wca.storeOp = (ca.storeOp == StoreOp::store) ? wgpu::StoreOp::Store @@ -1098,7 +1123,9 @@ if (desc.depthStencil.view) { const auto& ds = desc.depthStencil; - depthStencilAttachment.view = ds.view->m_wgpuTextureView; + auto view = lite_rtti_cast<TextureViewWGPU*>(ds.view); + assert(view != nullptr); + depthStencilAttachment.view = view->m_wgpuTextureView; depthStencilAttachment.depthLoadOp = (ds.depthLoadOp == LoadOp::clear) ? wgpu::LoadOp::Clear : wgpu::LoadOp::Load; @@ -1135,7 +1162,7 @@ passDesc.colorAttachments = colorAttachments; passDesc.depthStencilAttachment = pDepthStencil; - pass.m_wgpuPassEncoder = m_wgpuCommandEncoder.BeginRenderPass(&passDesc); + pass->m_wgpuPassEncoder = m_wgpuCommandEncoder.BeginRenderPass(&passDesc); return pass; } @@ -1181,7 +1208,7 @@ texDesc.sampleCount = 1; // Borrow the WebGPU texture — the RenderCanvas owns it. - auto texture = rcp<Texture>(new Texture(texDesc)); + auto texture = rcp<TextureWGPU>(new TextureWGPU(texDesc)); texture->m_wgpuTexture = wgpuTarget->targetTexture(); TextureViewDesc viewDesc{}; @@ -1192,7 +1219,8 @@ viewDesc.baseLayer = 0; viewDesc.layerCount = 1; - auto view = rcp<TextureView>(new TextureView(std::move(texture), viewDesc)); + auto view = + rcp<TextureViewWGPU>(new TextureViewWGPU(std::move(texture), viewDesc)); view->m_wgpuTextureView = wgpuTarget->targetTextureView(); return view; @@ -1213,7 +1241,8 @@ // Acquire takes ownership (will release on destruction). Since we're // borrowing, AddRef/Reference first so the original owner's ref is // preserved. Use the same version guard as the rest of the codebase. -#if (defined(RIVE_WEBGPU) && RIVE_WEBGPU > 1) || defined(RIVE_DAWN) +#if (defined(RIVE_WEBGPU) && RIVE_WEBGPU > 1) || \ + (defined(RIVE_DAWN) && !defined(RIVE_WAGYU)) wgpuTextureAddRef(rawTex); #else wgpuTextureReference(rawTex); @@ -1229,7 +1258,7 @@ texDesc.numMipmaps = 1; texDesc.sampleCount = 1; - auto texture = rcp<Texture>(new Texture(texDesc)); + auto texture = rcp<TextureWGPU>(new TextureWGPU(texDesc)); texture->m_wgpuTexture = wgpuTex; // Borrow. TextureViewDesc viewDesc{}; @@ -1240,7 +1269,8 @@ viewDesc.baseLayer = 0; viewDesc.layerCount = 1; - auto view = rcp<TextureView>(new TextureView(std::move(texture), viewDesc)); + auto view = + rcp<TextureViewWGPU>(new TextureViewWGPU(std::move(texture), viewDesc)); // Create a wgpu::TextureView for sampling. wgpu::TextureViewDescriptor tvd{}; tvd.format = wgpu::TextureFormat::RGBA8Unorm;
diff --git a/renderer/src/ore/wgpu/ore_pipeline_wgpu.cpp b/renderer/src/ore/wgpu/ore_pipeline_wgpu.cpp index 229d021..d36b0bb 100644 --- a/renderer/src/ore/wgpu/ore_pipeline_wgpu.cpp +++ b/renderer/src/ore/wgpu/ore_pipeline_wgpu.cpp
@@ -2,24 +2,5 @@ * Copyright 2025 Rive */ -#include "rive/renderer/ore/ore_pipeline.hpp" -#include "rive/renderer/ore/ore_bind_group_layout.hpp" - -namespace rive::ore -{ - -void Pipeline::onRefCntReachedZero() const -{ - // wgpu::RenderPipeline and wgpu::PipelineLayout RAII destructors release - // the GPU resources. Per-group BGLs are owned by `m_layouts[g]` and freed - // when those rcps drop. - delete this; -} - -void BindGroupLayout::onRefCntReachedZero() const -{ - // wgpu::BindGroupLayout RAII destructor releases the GPU resource. - delete this; -} - -} // namespace rive::ore +#include "ore_pipeline_wgpu.hpp" +#include "ore_bind_group_layout_wgpu.hpp"
diff --git a/renderer/src/ore/wgpu/ore_pipeline_wgpu.hpp b/renderer/src/ore/wgpu/ore_pipeline_wgpu.hpp new file mode 100644 index 0000000..03fb066 --- /dev/null +++ b/renderer/src/ore/wgpu/ore_pipeline_wgpu.hpp
@@ -0,0 +1,22 @@ +#pragma once +#include "rive/renderer/ore/ore_pipeline.hpp" +#include <webgpu/webgpu_cpp.h> + +namespace rive::ore +{ +class ContextWGPU; + +class PipelineWGPU : public LITE_RTTI_OVERRIDE(Pipeline, PipelineWGPU) +{ +public: + PipelineWGPU(const PipelineDesc& desc) : lite_rtti_override(desc) {} + ~PipelineWGPU() override = default; // RAII destructors release wgpu objects + +private: + friend class ContextWGPU; + friend class RenderPassWGPU; + wgpu::Device m_wgpuDevice; + wgpu::RenderPipeline m_wgpuPipeline; + wgpu::PipelineLayout m_wgpuPipelineLayout; +}; +} // namespace rive::ore
diff --git a/renderer/src/ore/wgpu/ore_render_pass_wgpu.cpp b/renderer/src/ore/wgpu/ore_render_pass_wgpu.cpp index a319b4e..fb8b20b 100644 --- a/renderer/src/ore/wgpu/ore_render_pass_wgpu.cpp +++ b/renderer/src/ore/wgpu/ore_render_pass_wgpu.cpp
@@ -2,13 +2,13 @@ * Copyright 2025 Rive */ -#include "rive/renderer/ore/ore_render_pass.hpp" -#include "rive/renderer/ore/ore_bind_group.hpp" #include "rive/renderer/ore/ore_context_wgpu.hpp" -#include "rive/renderer/ore/ore_buffer.hpp" -#include "rive/renderer/ore/ore_texture.hpp" -#include "rive/renderer/ore/ore_sampler.hpp" -#include "rive/renderer/ore/ore_pipeline.hpp" +#include "ore_render_pass_wgpu.hpp" +#include "ore_bind_group_wgpu.hpp" +#include "ore_buffer_wgpu.hpp" +#include "ore_texture_wgpu.hpp" +#include "ore_sampler_wgpu.hpp" +#include "ore_pipeline_wgpu.hpp" #include "rive/rive_types.hpp" namespace rive::ore @@ -18,7 +18,7 @@ // RenderPass // ============================================================================ -RenderPass::~RenderPass() +RenderPassWGPU::~RenderPassWGPU() { if (!m_finished && m_wgpuPassEncoder != nullptr) { @@ -26,26 +26,24 @@ } } -RenderPass::RenderPass(RenderPass&& other) noexcept : - m_currentPipeline(std::move(other.m_currentPipeline)), +RenderPassWGPU::RenderPassWGPU(RenderPassWGPU&& other) noexcept : m_wgpuContext(other.m_wgpuContext), + m_currentPipeline(std::move(other.m_currentPipeline)), m_wgpuPassEncoder(std::move(other.m_wgpuPassEncoder)), m_wgpuIndexBuffer(std::move(other.m_wgpuIndexBuffer)), m_wgpuIndexFormat(other.m_wgpuIndexFormat), m_wgpuIndexOffset(other.m_wgpuIndexOffset) { - moveCrossBackendFieldsFrom(other); other.m_wgpuContext = nullptr; } -RenderPass& RenderPass::operator=(RenderPass&& other) noexcept +RenderPassWGPU& RenderPassWGPU::operator=(RenderPassWGPU&& other) noexcept { if (this != &other) { if (!m_finished && m_wgpuPassEncoder != nullptr) finish(); - moveCrossBackendFieldsFrom(other); m_wgpuContext = other.m_wgpuContext; m_currentPipeline = std::move(other.m_currentPipeline); m_wgpuPassEncoder = std::move(other.m_wgpuPassEncoder); @@ -58,35 +56,43 @@ return *this; } -void RenderPass::validate() const +void RenderPassWGPU::validate() const { assert(!m_finished && "RenderPass already finished"); assert(m_wgpuPassEncoder != nullptr); } -void RenderPass::setPipeline(Pipeline* pipeline) +void RenderPassWGPU::setPipeline(Pipeline* inPipeline) { validate(); - if (!checkPipelineCompat(pipeline)) + if (!checkPipelineCompat(inPipeline)) return; + auto pipeline = lite_rtti_cast<PipelineWGPU*>(inPipeline); + assert(pipeline); m_currentPipeline = ref_rcp(pipeline); m_wgpuPassEncoder.SetPipeline(pipeline->m_wgpuPipeline); } -void RenderPass::setVertexBuffer(uint32_t slot, Buffer* buffer, uint32_t offset) +void RenderPassWGPU::setVertexBuffer(uint32_t slot, + Buffer* inBuffer, + uint32_t offset) { validate(); + auto buffer = lite_rtti_cast<BufferWGPU*>(inBuffer); + assert(buffer); m_wgpuPassEncoder.SetVertexBuffer(slot, buffer->m_wgpuBuffer, offset, buffer->size() - offset); } -void RenderPass::setIndexBuffer(Buffer* buffer, - IndexFormat format, - uint32_t offset) +void RenderPassWGPU::setIndexBuffer(Buffer* inBuffer, + IndexFormat format, + uint32_t offset) { validate(); + auto buffer = lite_rtti_cast<BufferWGPU*>(inBuffer); + assert(buffer); wgpu::IndexFormat wFmt = (format == IndexFormat::uint32) ? wgpu::IndexFormat::Uint32 : wgpu::IndexFormat::Uint16; @@ -99,14 +105,14 @@ buffer->size() - offset); } -void RenderPass::setBindGroup(uint32_t groupIndex, - BindGroup* bg, - const uint32_t* dynamicOffsets, - uint32_t dynamicOffsetCount) +void RenderPassWGPU::setBindGroup(uint32_t groupIndex, + BindGroup* inBg, + const uint32_t* dynamicOffsets, + uint32_t dynamicOffsetCount) { validate(); + auto bg = lite_rtti_cast<BindGroupWGPU*>(inBg); assert(bg != nullptr); - m_wgpuPassEncoder.SetBindGroup(groupIndex, bg->m_wgpuBindGroup, dynamicOffsetCount, @@ -117,43 +123,43 @@ m_boundGroups[groupIndex] = ref_rcp(bg); } -void RenderPass::setViewport(float x, - float y, - float width, - float height, - float minDepth, - float maxDepth) +void RenderPassWGPU::setViewport(float x, + float y, + float width, + float height, + float minDepth, + float maxDepth) { validate(); m_wgpuPassEncoder.SetViewport(x, y, width, height, minDepth, maxDepth); } -void RenderPass::setScissorRect(uint32_t x, - uint32_t y, - uint32_t width, - uint32_t height) +void RenderPassWGPU::setScissorRect(uint32_t x, + uint32_t y, + uint32_t width, + uint32_t height) { validate(); m_wgpuPassEncoder.SetScissorRect(x, y, width, height); } -void RenderPass::setStencilReference(uint32_t ref) +void RenderPassWGPU::setStencilReference(uint32_t ref) { validate(); m_wgpuPassEncoder.SetStencilReference(ref); } -void RenderPass::setBlendColor(float r, float g, float b, float a) +void RenderPassWGPU::setBlendColor(float r, float g, float b, float a) { validate(); wgpu::Color color{r, g, b, a}; m_wgpuPassEncoder.SetBlendConstant(&color); } -void RenderPass::draw(uint32_t vertexCount, - uint32_t instanceCount, - uint32_t firstVertex, - uint32_t firstInstance) +void RenderPassWGPU::draw(uint32_t vertexCount, + uint32_t instanceCount, + uint32_t firstVertex, + uint32_t firstInstance) { validate(); assert(m_currentPipeline != nullptr && "setPipeline must be called first"); @@ -164,11 +170,11 @@ firstInstance); } -void RenderPass::drawIndexed(uint32_t indexCount, - uint32_t instanceCount, - uint32_t firstIndex, - int32_t baseVertex, - uint32_t firstInstance) +void RenderPassWGPU::drawIndexed(uint32_t indexCount, + uint32_t instanceCount, + uint32_t firstIndex, + int32_t baseVertex, + uint32_t firstInstance) { validate(); assert(m_currentPipeline != nullptr && "setPipeline must be called first"); @@ -180,7 +186,7 @@ firstInstance); } -void RenderPass::finish() +void RenderPassWGPU::finish() { if (m_finished) return;
diff --git a/renderer/src/ore/wgpu/ore_render_pass_wgpu.hpp b/renderer/src/ore/wgpu/ore_render_pass_wgpu.hpp new file mode 100644 index 0000000..0da0bd3 --- /dev/null +++ b/renderer/src/ore/wgpu/ore_render_pass_wgpu.hpp
@@ -0,0 +1,66 @@ +#pragma once +#include "rive/renderer/ore/ore_render_pass.hpp" +#include "rive/renderer/ore/ore_pipeline.hpp" +#include "rive/refcnt.hpp" +#include <webgpu/webgpu_cpp.h> +#include <cstdint> + +namespace rive::ore +{ +class ContextWGPU; + +class RenderPassWGPU : public RenderPass +{ +public: + void setPipeline(Pipeline* pipeline) override; + void setVertexBuffer(uint32_t slot, + Buffer* buffer, + uint32_t offset = 0) override; + void setIndexBuffer(Buffer* buffer, + IndexFormat format, + uint32_t offset = 0) override; + void setBindGroup(uint32_t groupIndex, + BindGroup* bg, + const uint32_t* dynamicOffsets = nullptr, + uint32_t dynamicOffsetCount = 0) override; + void setViewport(float x, + float y, + float width, + float height, + float minDepth = 0.0f, + float maxDepth = 1.0f) override; + void setScissorRect(uint32_t x, + uint32_t y, + uint32_t width, + uint32_t height) override; + void setStencilReference(uint32_t ref) override; + void setBlendColor(float r, float g, float b, float a) override; + void draw(uint32_t vertexCount, + uint32_t instanceCount = 1, + uint32_t firstVertex = 0, + uint32_t firstInstance = 0) override; + void drawIndexed(uint32_t indexCount, + uint32_t instanceCount = 1, + uint32_t firstIndex = 0, + int32_t baseVertex = 0, + uint32_t firstInstance = 0) override; + void finish() override; + void validate() const override; + + RenderPassWGPU() = default; + RenderPassWGPU(Context* context) : RenderPass(context) {} + ~RenderPassWGPU() override; + RenderPassWGPU(RenderPassWGPU&& other) noexcept; + RenderPassWGPU& operator=(RenderPassWGPU&&) noexcept; + +private: + friend class ContextWGPU; + + ContextWGPU* m_wgpuContext = nullptr; // weak ref + rcp<Pipeline> m_currentPipeline; + wgpu::RenderPassEncoder m_wgpuPassEncoder; + wgpu::Buffer m_wgpuIndexBuffer; + wgpu::IndexFormat m_wgpuIndexFormat = wgpu::IndexFormat::Uint16; + uint32_t m_wgpuIndexOffset = 0; +}; +} // namespace rive::ore
diff --git a/renderer/src/ore/wgpu/ore_sampler_wgpu.cpp b/renderer/src/ore/wgpu/ore_sampler_wgpu.cpp index 468e393..7d439c0 100644 --- a/renderer/src/ore/wgpu/ore_sampler_wgpu.cpp +++ b/renderer/src/ore/wgpu/ore_sampler_wgpu.cpp
@@ -2,15 +2,4 @@ * Copyright 2025 Rive */ -#include "rive/renderer/ore/ore_sampler.hpp" - -namespace rive::ore -{ - -void Sampler::onRefCntReachedZero() const -{ - // wgpu::Sampler RAII destructor releases the GPU resource. - delete this; -} - -} // namespace rive::ore +#include "ore_sampler_wgpu.hpp"
diff --git a/renderer/src/ore/wgpu/ore_sampler_wgpu.hpp b/renderer/src/ore/wgpu/ore_sampler_wgpu.hpp new file mode 100644 index 0000000..23c302b --- /dev/null +++ b/renderer/src/ore/wgpu/ore_sampler_wgpu.hpp
@@ -0,0 +1,19 @@ +#pragma once +#include "rive/renderer/ore/ore_sampler.hpp" +#include <webgpu/webgpu_cpp.h> + +namespace rive::ore +{ +class ContextWGPU; + +class SamplerWGPU : public LITE_RTTI_OVERRIDE(Sampler, SamplerWGPU) +{ +public: + SamplerWGPU() = default; + ~SamplerWGPU() override = default; // wgpu::Sampler RAII destructor releases + +private: + friend class ContextWGPU; + wgpu::Sampler m_wgpuSampler; +}; +} // namespace rive::ore
diff --git a/renderer/src/ore/wgpu/ore_shader_module_wgpu.cpp b/renderer/src/ore/wgpu/ore_shader_module_wgpu.cpp index ffde7f8..745b5b2 100644 --- a/renderer/src/ore/wgpu/ore_shader_module_wgpu.cpp +++ b/renderer/src/ore/wgpu/ore_shader_module_wgpu.cpp
@@ -2,15 +2,4 @@ * Copyright 2025 Rive */ -#include "rive/renderer/ore/ore_shader_module.hpp" - -namespace rive::ore -{ - -void ShaderModule::onRefCntReachedZero() const -{ - // wgpu::ShaderModule RAII destructor releases the GPU resource. - delete this; -} - -} // namespace rive::ore +#include "ore_shader_module_wgpu.hpp"
diff --git a/renderer/src/ore/wgpu/ore_shader_module_wgpu.hpp b/renderer/src/ore/wgpu/ore_shader_module_wgpu.hpp new file mode 100644 index 0000000..b4af8e2 --- /dev/null +++ b/renderer/src/ore/wgpu/ore_shader_module_wgpu.hpp
@@ -0,0 +1,21 @@ +#pragma once +#include "rive/renderer/ore/ore_shader_module.hpp" +#include <webgpu/webgpu_cpp.h> + +namespace rive::ore +{ +class ContextWGPU; + +class ShaderModuleWGPU + : public LITE_RTTI_OVERRIDE(ShaderModule, ShaderModuleWGPU) +{ +public: + ShaderModuleWGPU() = default; + ~ShaderModuleWGPU() override = + default; // wgpu::ShaderModule RAII destructor releases + +private: + friend class ContextWGPU; + wgpu::ShaderModule m_wgpuShaderModule; +}; +} // namespace rive::ore
diff --git a/renderer/src/ore/wgpu/ore_texture_wgpu.cpp b/renderer/src/ore/wgpu/ore_texture_wgpu.cpp index bdd42c8..c11e55e 100644 --- a/renderer/src/ore/wgpu/ore_texture_wgpu.cpp +++ b/renderer/src/ore/wgpu/ore_texture_wgpu.cpp
@@ -2,19 +2,29 @@ * Copyright 2025 Rive */ -#include "rive/renderer/ore/ore_texture.hpp" +#include "ore_texture_wgpu.hpp" #include "rive/renderer/ore/ore_types.hpp" #include "rive/rive_types.hpp" +#if RIVE_WEBGPU == 1 +namespace wgpu +{ +using TexelCopyBufferInfo = ImageCopyBuffer; +using TexelCopyTextureInfo = ImageCopyTexture; +using TexelCopyBufferLayout = TextureDataLayout; +using ShaderSourceWGSL = ShaderModuleWGSLDescriptor; +}; // namespace wgpu +#endif + namespace rive::ore { -void Texture::upload(const TextureDataDesc& data) +void TextureWGPU::upload(const TextureDataDesc& data) { assert(m_wgpuTexture != nullptr); assert(data.data != nullptr); - wgpu::TexelCopyTextureInfo dst{}; + dst.texture = m_wgpuTexture; dst.mipLevel = data.mipLevel; dst.origin = {data.x, data.y, data.layer}; @@ -53,6 +63,7 @@ // any caller-provided row padding is correctly skipped. uint32_t packedRowBytes = data.width * bpt; wgpu::TexelCopyBufferLayout rowLayout{}; + rowLayout.bytesPerRow = WGPU_COPY_STRIDE_UNDEFINED; rowLayout.rowsPerImage = WGPU_COPY_STRIDE_UNDEFINED; wgpu::Extent3D rowExtent{data.width, 1, 1}; @@ -80,16 +91,4 @@ m_wgpuQueue.WriteTexture(&dst, data.data, dataSize, &layout, &extent); } -void Texture::onRefCntReachedZero() const -{ - // wgpu::Texture RAII destructor releases the GPU resource. - delete this; -} - -void TextureView::onRefCntReachedZero() const -{ - // wgpu::TextureView RAII destructor releases the GPU resource. - delete this; -} - } // namespace rive::ore
diff --git a/renderer/src/ore/wgpu/ore_texture_wgpu.hpp b/renderer/src/ore/wgpu/ore_texture_wgpu.hpp new file mode 100644 index 0000000..97ea47f --- /dev/null +++ b/renderer/src/ore/wgpu/ore_texture_wgpu.hpp
@@ -0,0 +1,35 @@ +#pragma once +#include "rive/renderer/ore/ore_texture.hpp" +#include <webgpu/webgpu_cpp.h> + +namespace rive::ore +{ +class ContextWGPU; + +class TextureWGPU : public LITE_RTTI_OVERRIDE(Texture, TextureWGPU) +{ +public: + TextureWGPU(const TextureDesc& desc) : lite_rtti_override(desc) {} + ~TextureWGPU() override = default; // wgpu::Texture RAII destructor releases + void upload(const TextureDataDesc& data) override; + +private: + friend class ContextWGPU; + wgpu::Texture m_wgpuTexture; + wgpu::Queue m_wgpuQueue; // Weak ref (addref'd copy). +}; + +class TextureViewWGPU : public LITE_RTTI_OVERRIDE(TextureView, TextureViewWGPU) +{ +public: + TextureViewWGPU(rcp<Texture> texture, const TextureViewDesc& desc) : + lite_rtti_override(std::move(texture), desc) + {} + ~TextureViewWGPU() override = + default; // wgpu::TextureView RAII destructor releases + +private: + friend class ContextWGPU; + wgpu::TextureView m_wgpuTextureView; +}; +} // namespace rive::ore
diff --git a/renderer/src/vulkan/render_context_vulkan_impl.cpp b/renderer/src/vulkan/render_context_vulkan_impl.cpp index 1678a0c..3e6773a 100644 --- a/renderer/src/vulkan/render_context_vulkan_impl.cpp +++ b/renderer/src/vulkan/render_context_vulkan_impl.cpp
@@ -7,6 +7,7 @@ #include "vulkan_shaders.hpp" #ifdef RIVE_CANVAS #include "rive/renderer/render_canvas.hpp" +#include "rive/renderer/ore/ore_context_vulkan.hpp" #endif #include "rive/renderer/stack_vector.hpp" #include "rive/renderer/texture.hpp" @@ -187,6 +188,13 @@ return make_rcp<RenderCanvas>(std::move(renderImage), std::move(renderTarget)); } +std::unique_ptr<rive::ore::Context> RenderContextVulkanImpl::makeOreContext() +{ + assert(m_canvasQueue != VK_NULL_HANDLE); + return rive::ore::ContextVulkan::Make(m_vk, + m_canvasQueue, + m_canvasQueueFamilyIndex); +} #endif // Common base class for a pipeline that renders a texture resource at the
diff --git a/renderer/src/webgpu/render_context_webgpu_impl.cpp b/renderer/src/webgpu/render_context_webgpu_impl.cpp index b4be806..57a6031 100644 --- a/renderer/src/webgpu/render_context_webgpu_impl.cpp +++ b/renderer/src/webgpu/render_context_webgpu_impl.cpp
@@ -7,6 +7,7 @@ #include "rive/renderer/draw.hpp" #ifdef RIVE_CANVAS #include "rive/renderer/render_canvas.hpp" +#include "rive/renderer/ore/ore_context_wgpu.hpp" #endif #include "rive/renderer/stack_vector.hpp" #include "rive/gpu_texture_format.hpp" @@ -1948,6 +1949,12 @@ return make_rcp<RenderCanvas>(std::move(renderImage), std::move(renderTarget)); } +std::unique_ptr<rive::ore::Context> RenderContextWebGPUImpl::makeOreContext() +{ + return rive::ore::ContextWGPU::Make(m_device, + m_queue, + m_capabilities.backendType); +} #endif class RenderBufferWebGPUImpl : public RenderBuffer
diff --git a/src/lua/renderer/lua_gpu.cpp b/src/lua/renderer/lua_gpu.cpp index adf628f..6af2392 100644 --- a/src/lua/renderer/lua_gpu.cpp +++ b/src/lua/renderer/lua_gpu.cpp
@@ -2863,10 +2863,8 @@ oreCtx->setActiveRenderPass(nullptr); } - ore::RenderPass raw = oreCtx->beginRenderPass(passDesc); - auto* rp = lua_newrive<ScriptedGPURenderPass>(L); - rp->pass = std::make_unique<ore::RenderPass>(std::move(raw)); + rp->pass = oreCtx->beginRenderPass(passDesc); rp->m_context = oreCtx; rp->m_finished = false; rp->sampleCount =
diff --git a/tests/common/render_context_null.hpp b/tests/common/render_context_null.hpp index b4341c2..9db3f89 100644 --- a/tests/common/render_context_null.hpp +++ b/tests/common/render_context_null.hpp
@@ -7,6 +7,10 @@ #include "rive/renderer/render_context_helper_impl.hpp" #include "rive/gpu_texture_format.hpp" +#ifdef RIVE_CANVAS +#include "rive/renderer/ore/ore_context.hpp" +#endif + class RenderContextNULL : public rive::gpu::RenderContextHelperImpl { public: @@ -14,6 +18,13 @@ RenderContextNULL(); +#ifdef RIVE_CANVAS + std::unique_ptr<rive::ore::Context> makeOreContext() override + { + return nullptr; + } +#endif + rive::rcp<rive::gpu::RenderTarget> makeRenderTarget(uint32_t width, uint32_t height);
diff --git a/tests/gm/ore_array_upload.cpp b/tests/gm/ore_array_upload.cpp index 2eb8d6a..a648b4b 100644 --- a/tests/gm/ore_array_upload.cpp +++ b/tests/gm/ore_array_upload.cpp
@@ -258,12 +258,12 @@ rpDesc.label = "ore_array_upload_pass"; auto pass = ctx.beginRenderPass(rpDesc); - pass.setPipeline(pipeline.get()); - pass.setBindGroup(1, texBG.get()); - pass.setBindGroup(2, sampBG.get()); - pass.setViewport(0, 0, 256, 256); - pass.draw(3); // big-triangle fullscreen — covers entire NDC. - pass.finish(); + pass->setPipeline(pipeline.get()); + pass->setBindGroup(1, texBG.get()); + pass->setBindGroup(2, sampBG.get()); + pass->setViewport(0, 0, 256, 256); + pass->draw(3); // big-triangle fullscreen — covers entire NDC. + pass->finish(); m_ore.endFrame(); ore_gm::invalidateGLStateAfterOre(renderContext);
diff --git a/tests/gm/ore_binding_dynamic_ubo.cpp b/tests/gm/ore_binding_dynamic_ubo.cpp index 19366dc..d0f5606 100644 --- a/tests/gm/ore_binding_dynamic_ubo.cpp +++ b/tests/gm/ore_binding_dynamic_ubo.cpp
@@ -193,11 +193,11 @@ rpDesc.label = "ore_binding_dynamic_ubo_pass"; auto pass = ctx.beginRenderPass(rpDesc); - pass.setPipeline(pipeline.get()); - pass.setBindGroup(0, bg.get(), dynamicOffsets, 2); - pass.setViewport(0, 0, 128, 128); - pass.draw(3); // fullscreen triangle - pass.finish(); + pass->setPipeline(pipeline.get()); + pass->setBindGroup(0, bg.get(), dynamicOffsets, 2); + pass->setViewport(0, 0, 128, 128); + pass->draw(3); // fullscreen triangle + pass->finish(); m_ore.endFrame(); ore_gm::invalidateGLStateAfterOre(renderContext);
diff --git a/tests/gm/ore_binding_mixed_kind.cpp b/tests/gm/ore_binding_mixed_kind.cpp index b5ea566..4f93b49 100644 --- a/tests/gm/ore_binding_mixed_kind.cpp +++ b/tests/gm/ore_binding_mixed_kind.cpp
@@ -242,11 +242,11 @@ rpDesc.label = "ore_binding_mixed_kind_pass"; auto pass = ctx.beginRenderPass(rpDesc); - pass.setPipeline(pipeline.get()); - pass.setBindGroup(0, bg.get()); - pass.setViewport(0, 0, 128, 128); - pass.draw(3); // fullscreen triangle - pass.finish(); + pass->setPipeline(pipeline.get()); + pass->setBindGroup(0, bg.get()); + pass->setViewport(0, 0, 128, 128); + pass->draw(3); // fullscreen triangle + pass->finish(); m_ore.endFrame(); ore_gm::invalidateGLStateAfterOre(renderContext);
diff --git a/tests/gm/ore_binding_multi_group.cpp b/tests/gm/ore_binding_multi_group.cpp index 1a11234..efadb3e 100644 --- a/tests/gm/ore_binding_multi_group.cpp +++ b/tests/gm/ore_binding_multi_group.cpp
@@ -196,12 +196,12 @@ rpDesc.label = "ore_binding_multi_group_pass"; auto pass = ctx.beginRenderPass(rpDesc); - pass.setPipeline(pipeline.get()); - pass.setBindGroup(0, bgA.get()); - pass.setBindGroup(1, bgB.get()); - pass.setViewport(0, 0, 128, 128); - pass.draw(3); // fullscreen triangle - pass.finish(); + pass->setPipeline(pipeline.get()); + pass->setBindGroup(0, bgA.get()); + pass->setBindGroup(1, bgB.get()); + pass->setViewport(0, 0, 128, 128); + pass->draw(3); // fullscreen triangle + pass->finish(); m_ore.endFrame(); ore_gm::invalidateGLStateAfterOre(renderContext);
diff --git a/tests/gm/ore_binding_shadow_sampler.cpp b/tests/gm/ore_binding_shadow_sampler.cpp index 19a2168..fff7d59 100644 --- a/tests/gm/ore_binding_shadow_sampler.cpp +++ b/tests/gm/ore_binding_shadow_sampler.cpp
@@ -289,12 +289,12 @@ rpDesc.colorCount = 1; rpDesc.label = "ore_binding_shadow_sampler_pass"; auto pass = ctx.beginRenderPass(rpDesc); - pass.setPipeline(pipeline.get()); - pass.setBindGroup(0, bg0.get()); - pass.setBindGroup(1, bg1.get()); - pass.setViewport(0, 0, 128, 128); - pass.draw(3); - pass.finish(); + pass->setPipeline(pipeline.get()); + pass->setBindGroup(0, bg0.get()); + pass->setBindGroup(1, bg1.get()); + pass->setViewport(0, 0, 128, 128); + pass->draw(3); + pass->finish(); m_ore.endFrame(); ore_gm::invalidateGLStateAfterOre(renderContext);
diff --git a/tests/gm/ore_binding_shadow_sampler_d32.cpp b/tests/gm/ore_binding_shadow_sampler_d32.cpp index cef38dd..7441efd 100644 --- a/tests/gm/ore_binding_shadow_sampler_d32.cpp +++ b/tests/gm/ore_binding_shadow_sampler_d32.cpp
@@ -370,12 +370,12 @@ rpDesc.colorCount = 1; rpDesc.label = "ore_binding_shadow_sampler_d32_pass"; auto pass = ctx.beginRenderPass(rpDesc); - pass.setPipeline(pipeline.get()); - pass.setBindGroup(0, bg0.get()); - pass.setBindGroup(1, bg1.get()); - pass.setViewport(0, 0, 128, 128); - pass.draw(3); - pass.finish(); + pass->setPipeline(pipeline.get()); + pass->setBindGroup(0, bg0.get()); + pass->setBindGroup(1, bg1.get()); + pass->setViewport(0, 0, 128, 128); + pass->draw(3); + pass->finish(); m_ore.endFrame(); ore_gm::invalidateGLStateAfterOre(renderContext);
diff --git a/tests/gm/ore_binding_vs_texture.cpp b/tests/gm/ore_binding_vs_texture.cpp index 558e065..c874381 100644 --- a/tests/gm/ore_binding_vs_texture.cpp +++ b/tests/gm/ore_binding_vs_texture.cpp
@@ -223,11 +223,11 @@ rpDesc.label = "ore_binding_vs_texture_pass"; auto pass = ctx.beginRenderPass(rpDesc); - pass.setPipeline(pipeline.get()); - pass.setBindGroup(0, bg.get()); - pass.setViewport(0, 0, 128, 128); - pass.draw(3); // fullscreen triangle - pass.finish(); + pass->setPipeline(pipeline.get()); + pass->setBindGroup(0, bg.get()); + pass->setViewport(0, 0, 128, 128); + pass->draw(3); // fullscreen triangle + pass->finish(); m_ore.endFrame(); ore_gm::invalidateGLStateAfterOre(renderContext);
diff --git a/tests/gm/ore_binding_witness.cpp b/tests/gm/ore_binding_witness.cpp index d2948b0..8662959 100644 --- a/tests/gm/ore_binding_witness.cpp +++ b/tests/gm/ore_binding_witness.cpp
@@ -174,11 +174,11 @@ rpDesc.label = "ore_binding_witness_pass"; auto pass = ctx.beginRenderPass(rpDesc); - pass.setPipeline(pipeline.get()); - pass.setBindGroup(0, bg.get()); - pass.setViewport(0, 0, 128, 128); - pass.draw(3); // fullscreen triangle - pass.finish(); + pass->setPipeline(pipeline.get()); + pass->setBindGroup(0, bg.get()); + pass->setViewport(0, 0, 128, 128); + pass->draw(3); // fullscreen triangle + pass->finish(); m_ore.endFrame(); ore_gm::invalidateGLStateAfterOre(renderContext);
diff --git a/tests/gm/ore_blend_stencil.cpp b/tests/gm/ore_blend_stencil.cpp index e5b51ca..5cc25e1 100644 --- a/tests/gm/ore_blend_stencil.cpp +++ b/tests/gm/ore_blend_stencil.cpp
@@ -289,21 +289,21 @@ auto pass = ctx.beginRenderPass(rpDesc); // Reference value 1 carries across both pipelines — set once. - pass.setStencilReference(1); + pass->setStencilReference(1); // Prepass: stencil-only, mask written by the centered triangle. - pass.setPipeline(prepass.get()); - pass.setVertexBuffer(0, vbStencil.get()); - pass.setViewport(0, 0, 256, 256); - pass.draw(3); + pass->setPipeline(prepass.get()); + pass->setVertexBuffer(0, vbStencil.get()); + pass->setViewport(0, 0, 256, 256); + pass->draw(3); // Overlay: full-screen alpha-blended tint, masked to the // stencil region. - pass.setPipeline(overlay.get()); - pass.setVertexBuffer(0, vbOverlay.get()); - pass.draw(3); + pass->setPipeline(overlay.get()); + pass->setVertexBuffer(0, vbOverlay.get()); + pass->draw(3); - pass.finish(); + pass->finish(); m_ore.endFrame(); ore_gm::invalidateGLStateAfterOre(renderContext);
diff --git a/tests/gm/ore_canvas_import.cpp b/tests/gm/ore_canvas_import.cpp index 2838c56..e6f80fa 100644 --- a/tests/gm/ore_canvas_import.cpp +++ b/tests/gm/ore_canvas_import.cpp
@@ -288,12 +288,12 @@ rpDesc.label = "ore_canvas_import_pass"; auto pass = ctx.beginRenderPass(rpDesc); - pass.setPipeline(pipeline.get()); - pass.setBindGroup(1, texBG.get()); - pass.setBindGroup(2, sampBG.get()); - pass.setViewport(0, 0, kSize, kSize); - pass.draw(6); // fullscreen quad - pass.finish(); + pass->setPipeline(pipeline.get()); + pass->setBindGroup(1, texBG.get()); + pass->setBindGroup(2, sampBG.get()); + pass->setViewport(0, 0, kSize, kSize); + pass->draw(6); // fullscreen quad + pass->finish(); m_ore.endFrame(); ore_gm::invalidateGLStateAfterOre(renderContext);
diff --git a/tests/gm/ore_cubemap.cpp b/tests/gm/ore_cubemap.cpp index 8d63da5..6a8e67c 100644 --- a/tests/gm/ore_cubemap.cpp +++ b/tests/gm/ore_cubemap.cpp
@@ -118,7 +118,7 @@ rpDesc.label = "cube_face_pass"; auto pass = ctx.beginRenderPass(rpDesc); - pass.finish(); + pass->finish(); } // Now sample the cubemap and render a 3x2 grid showing all faces. @@ -187,12 +187,12 @@ auto sampBG = ctx.makeBindGroup(sampBGDesc); auto samplePass = ctx.beginRenderPass(samplePassDesc); - samplePass.setPipeline(cubeSamplePipeline.get()); - samplePass.setBindGroup(1, texBG.get()); - samplePass.setBindGroup(2, sampBG.get()); - samplePass.setViewport(0, 0, 192, 128); - samplePass.draw(3); - samplePass.finish(); + samplePass->setPipeline(cubeSamplePipeline.get()); + samplePass->setBindGroup(1, texBG.get()); + samplePass->setBindGroup(2, sampBG.get()); + samplePass->setViewport(0, 0, 192, 128); + samplePass->draw(3); + samplePass->finish(); m_ore.endFrame(); ore_gm::invalidateGLStateAfterOre(renderContext);
diff --git a/tests/gm/ore_depth.cpp b/tests/gm/ore_depth.cpp index 70ffe59..a56b9d9 100644 --- a/tests/gm/ore_depth.cpp +++ b/tests/gm/ore_depth.cpp
@@ -182,12 +182,12 @@ rpDesc.label = "ore_depth_pass"; auto pass = ctx.beginRenderPass(rpDesc); - pass.setPipeline(pipeline.get()); - pass.setVertexBuffer(0, vbo.get()); - pass.setViewport(0, 0, kSize, kSize); + pass->setPipeline(pipeline.get()); + pass->setVertexBuffer(0, vbo.get()); + pass->setViewport(0, 0, kSize, kSize); // Draw all 18 vertices (3 quads x 6 vertices each). - pass.draw(18); - pass.finish(); + pass->draw(18); + pass->finish(); m_ore.endFrame(); ore_gm::invalidateGLStateAfterOre(renderContext);
diff --git a/tests/gm/ore_depth_only_pipeline.cpp b/tests/gm/ore_depth_only_pipeline.cpp index b69ae2f..8797277 100644 --- a/tests/gm/ore_depth_only_pipeline.cpp +++ b/tests/gm/ore_depth_only_pipeline.cpp
@@ -193,11 +193,11 @@ ctx.clearLastError(); auto pass = ctx.beginRenderPass(rp); - pass.setPipeline(depthOnlyPipeline.get()); - pass.setVertexBuffer(0, vbuf.get()); - pass.setViewport(0, 0, 64, 64); - pass.draw(3); - pass.finish(); + pass->setPipeline(depthOnlyPipeline.get()); + pass->setVertexBuffer(0, vbuf.get()); + pass->setViewport(0, 0, 64, 64); + pass->draw(3); + pass->finish(); if (!ctx.lastError().empty()) { @@ -233,8 +233,8 @@ rpDesc.label = "ore_depth_only_pipeline_result"; auto resultPass = ctx.beginRenderPass(rpDesc); - resultPass.setViewport(0, 0, 128, 128); - resultPass.finish(); + resultPass->setViewport(0, 0, 128, 128); + resultPass->finish(); m_ore.endFrame(); ore_gm::invalidateGLStateAfterOre(renderContext);
diff --git a/tests/gm/ore_gm_helper.hpp b/tests/gm/ore_gm_helper.hpp index de2f346..ce9ca3c 100644 --- a/tests/gm/ore_gm_helper.hpp +++ b/tests/gm/ore_gm_helper.hpp
@@ -157,7 +157,8 @@ auto queue = (__bridge id<MTLCommandQueue>)TestingWindow::Get() ->metalQueue(); assert(queue != nil); - oreContext = rive::ore::ContextMetal::Make(impl->gpu(), queue); + impl->setCommandQueue(queue); + oreContext = impl->makeOreContext(); return true; } #endif @@ -165,29 +166,21 @@ if (b == TestingWindow::Backend::gl || b == TestingWindow::Backend::angle) { - oreContext = rive::ore::ContextGL::Make(); + oreContext = renderContext->impl()->makeOreContext(); return true; } #endif #if defined(ORE_BACKEND_D3D11) if (b == TestingWindow::Backend::d3d) { - auto* impl = - renderContext - ->static_impl_cast<rive::gpu::RenderContextD3DImpl>(); - oreContext = - rive::ore::ContextD3D11::Make(impl->gpu(), impl->gpuContext()); + oreContext = renderContext->impl()->makeOreContext(); return true; } #endif #if defined(ORE_BACKEND_D3D12) if (b == TestingWindow::Backend::d3d12) { - auto* impl = - renderContext - ->static_impl_cast<rive::gpu::RenderContextD3D12Impl>(); - oreContext = rive::ore::ContextD3D12::Make(impl->device().Get(), - impl->commandQueue()); + oreContext = renderContext->impl()->makeOreContext(); return true; } #endif @@ -195,13 +188,7 @@ if (b == TestingWindow::Backend::wgpu || b == TestingWindow::Backend::dawn) { - auto* impl = - renderContext - ->static_impl_cast<rive::gpu::RenderContextWebGPUImpl>(); - oreContext = - rive::ore::ContextWGPU::Make(impl->device(), - impl->queue(), - impl->capabilities().backendType); + oreContext = renderContext->impl()->makeOreContext(); return true; } #endif @@ -213,22 +200,13 @@ auto* impl = renderContext ->static_impl_cast<rive::gpu::RenderContextVulkanImpl>(); - rive::gpu::VulkanContext* vkCtx = impl->vulkanContext(); auto* win = TestingWindow::Get(); VkQueue queue = static_cast<VkQueue>(win->vulkanGraphicsQueue()); uint32_t queueFamily = win->vulkanGraphicsQueueFamilyIndex(); - auto pfnGetInstanceProcAddr = - reinterpret_cast<PFN_vkGetInstanceProcAddr>( - win->vulkanGetInstanceProcAddr()); - if (queue == VK_NULL_HANDLE || pfnGetInstanceProcAddr == nullptr) + if (queue == VK_NULL_HANDLE) return false; - oreContext = rive::ore::ContextVulkan::Make(vkCtx->instance, - vkCtx->physicalDevice, - vkCtx->device, - queue, - queueFamily, - vkCtx->allocator(), - pfnGetInstanceProcAddr); + impl->setCanvasQueue(queue, queueFamily); + oreContext = impl->makeOreContext(); return true; } #endif
diff --git a/tests/gm/ore_image_view.cpp b/tests/gm/ore_image_view.cpp index 5a115bc..fa2767b 100644 --- a/tests/gm/ore_image_view.cpp +++ b/tests/gm/ore_image_view.cpp
@@ -199,12 +199,12 @@ rpDesc.label = "ore_image_view_pass"; auto pass = ctx.beginRenderPass(rpDesc); - pass.setPipeline(pipeline.get()); - pass.setBindGroup(1, texBG.get()); - pass.setBindGroup(2, sampBG.get()); - pass.setViewport(0, 0, 256, 256); - pass.draw(6); // fullscreen quad — 2 triangles - pass.finish(); + pass->setPipeline(pipeline.get()); + pass->setBindGroup(1, texBG.get()); + pass->setBindGroup(2, sampBG.get()); + pass->setViewport(0, 0, 256, 256); + pass->draw(6); // fullscreen quad — 2 triangles + pass->finish(); m_ore.endFrame(); ore_gm::invalidateGLStateAfterOre(renderContext);
diff --git a/tests/gm/ore_layout_mismatch.cpp b/tests/gm/ore_layout_mismatch.cpp index 4268fbc..bf05746 100644 --- a/tests/gm/ore_layout_mismatch.cpp +++ b/tests/gm/ore_layout_mismatch.cpp
@@ -201,8 +201,8 @@ rpDesc.label = "ore_layout_mismatch_pass"; auto pass = ctx.beginRenderPass(rpDesc); - pass.setViewport(0, 0, 128, 128); - pass.finish(); + pass->setViewport(0, 0, 128, 128); + pass->finish(); m_ore.endFrame(); ore_gm::invalidateGLStateAfterOre(renderContext);
diff --git a/tests/gm/ore_layout_reuse.cpp b/tests/gm/ore_layout_reuse.cpp index 43e3539..69202d9 100644 --- a/tests/gm/ore_layout_reuse.cpp +++ b/tests/gm/ore_layout_reuse.cpp
@@ -185,19 +185,19 @@ // Left half: pipe A (full RGBA) — should produce olive (0.3, 0.6, 0, // 1). - pass.setPipeline(pipeA.get()); - pass.setBindGroup(0, sharedBG.get()); - pass.setViewport(0, 0, 64, 128); - pass.draw(3); + pass->setPipeline(pipeA.get()); + pass->setBindGroup(0, sharedBG.get()); + pass->setViewport(0, 0, 64, 128); + pass->draw(3); // Right half: pipe B (red-only mask) — same shared bind group. // Output: dark red (0.3, 0, 0, 1). - pass.setPipeline(pipeB.get()); - pass.setBindGroup(0, sharedBG.get()); - pass.setViewport(64, 0, 64, 128); - pass.draw(3); + pass->setPipeline(pipeB.get()); + pass->setBindGroup(0, sharedBG.get()); + pass->setViewport(64, 0, 64, 128); + pass->draw(3); - pass.finish(); + pass->finish(); m_ore.endFrame(); ore_gm::invalidateGLStateAfterOre(renderContext);
diff --git a/tests/gm/ore_mrt.cpp b/tests/gm/ore_mrt.cpp index 7905cd2..03f12bb 100644 --- a/tests/gm/ore_mrt.cpp +++ b/tests/gm/ore_mrt.cpp
@@ -108,10 +108,10 @@ rpDesc.label = "mrt_pass"; auto pass = ctx.beginRenderPass(rpDesc); - pass.setPipeline(mrtPipeline.get()); - pass.setViewport(0, 0, kSize, kSize); - pass.draw(3); // Fullscreen triangle, no VBO needed. - pass.finish(); + pass->setPipeline(mrtPipeline.get()); + pass->setViewport(0, 0, kSize, kSize); + pass->draw(3); // Fullscreen triangle, no VBO needed. + pass->finish(); // Now blit each target to a RenderCanvas for compositing. // Load blit shader from the pre-compiled RSTB. @@ -189,12 +189,12 @@ auto blitTexBG = ctx.makeBindGroup(blitTexBGDesc); auto blitPass = ctx.beginRenderPass(blitPassDesc); - blitPass.setPipeline(blitPipeline.get()); - blitPass.setBindGroup(1, blitTexBG.get()); - blitPass.setBindGroup(2, blitSampBG.get()); - blitPass.setViewport(i * kSize, 0, kSize, kSize); - blitPass.draw(3); - blitPass.finish(); + blitPass->setPipeline(blitPipeline.get()); + blitPass->setBindGroup(1, blitTexBG.get()); + blitPass->setBindGroup(2, blitSampBG.get()); + blitPass->setViewport(i * kSize, 0, kSize, kSize); + blitPass->draw(3); + blitPass->finish(); } m_ore.endFrame();
diff --git a/tests/gm/ore_msaa_resolve.cpp b/tests/gm/ore_msaa_resolve.cpp index ebb036c..f9aca9f 100644 --- a/tests/gm/ore_msaa_resolve.cpp +++ b/tests/gm/ore_msaa_resolve.cpp
@@ -215,11 +215,11 @@ rpDesc.label = "ore_msaa_resolve_pass"; auto pass = ctx.beginRenderPass(rpDesc); - pass.setPipeline(pipeline.get()); - pass.setVertexBuffer(0, vbo.get()); - pass.setViewport(0, 0, 256, 256); - pass.draw(3); - pass.finish(); + pass->setPipeline(pipeline.get()); + pass->setVertexBuffer(0, vbo.get()); + pass->setViewport(0, 0, 256, 256); + pass->draw(3); + pass->finish(); m_ore.endFrame(); ore_gm::invalidateGLStateAfterOre(renderContext);
diff --git a/tests/gm/ore_triangle.cpp b/tests/gm/ore_triangle.cpp index 01d8537..c3ccc1e 100644 --- a/tests/gm/ore_triangle.cpp +++ b/tests/gm/ore_triangle.cpp
@@ -135,11 +135,11 @@ rpDesc.label = "ore_triangle_pass"; auto pass = ctx.beginRenderPass(rpDesc); - pass.setPipeline(pipeline.get()); - pass.setVertexBuffer(0, vbo.get()); - pass.setViewport(0, 0, 256, 256); - pass.draw(3); - pass.finish(); + pass->setPipeline(pipeline.get()); + pass->setVertexBuffer(0, vbo.get()); + pass->setViewport(0, 0, 256, 256); + pass->draw(3); + pass->finish(); m_ore.endFrame(); ore_gm::invalidateGLStateAfterOre(renderContext);
diff --git a/tests/rive_tools_project.lua b/tests/rive_tools_project.lua index fa08790..08cbd3b 100644 --- a/tests/rive_tools_project.lua +++ b/tests/rive_tools_project.lua
@@ -59,6 +59,13 @@ fatalwarnings { "All" } + -- Solves link order issue on linux + filter({ 'system:linux'}) + do + linkgroups("On") + end + filter({ }) + defines({ 'SK_GL', 'GL_SILENCE_DEPRECATION', -- For glReadPixels()