Refactor PLS uniform buffers to support multiple draws Currently, PLS renders every path in a single draw call. In order to support some indispensable optmizations, in addition to non-raster-ordered rendering, we need to be able to support a draw list with multiple draws. This change adds a uniform buffer that can support per-draw parameters. Diffs= beab8bab0 Refactor PLS uniform buffers to support multiple draws (#5416) Co-authored-by: Chris Dalton <99840794+csmartdalton@users.noreply.github.com>
diff --git a/.rive_head b/.rive_head index 5f63853..9faf631 100644 --- a/.rive_head +++ b/.rive_head
@@ -1 +1 @@ -ffa49c5b9c08c0f9c86ab901bc987e96a0eee794 +beab8bab0c8748c652dc07ca8f6e11d5ad22a9af
diff --git a/include/rive/pls/buffer_ring.hpp b/include/rive/pls/buffer_ring.hpp index 589a7f1..dbd6516 100644 --- a/include/rive/pls/buffer_ring.hpp +++ b/include/rive/pls/buffer_ring.hpp
@@ -88,19 +88,7 @@ void* m_shadowBuffer = nullptr; }; -// Buffer ring implementation that attaches to a uniform binding and only supports one single item. -class UniformBufferRing : public BufferRingShadowImpl -{ -public: - UniformBufferRing(size_t itemSizeInBytes) : BufferRingShadowImpl(1, itemSizeInBytes) {} - - bool contentMatches(const void* data) const - { - return shadowBuffer() != nullptr && memcmp(shadowBuffer(), data, itemSizeInBytes()) == 0; - } -}; - -// BufferRingShadowImpl whose backing store is a 2D array of texels. +// BufferRingShadowImpl whose backing store is a 2D texture. class TexelBufferRing : public BufferRingShadowImpl { public:
diff --git a/include/rive/pls/gl/pls_render_context_gl.hpp b/include/rive/pls/gl/pls_render_context_gl.hpp index 1f83b65..8905035 100644 --- a/include/rive/pls/gl/pls_render_context_gl.hpp +++ b/include/rive/pls/gl/pls_render_context_gl.hpp
@@ -84,6 +84,9 @@ class DrawProgram { public: + constexpr static int kUniformsBlockIdx = 0; + constexpr static int kDrawParametersBlockIdx = 1; + DrawProgram(const DrawProgram&) = delete; DrawProgram& operator=(const DrawProgram&) = delete; DrawProgram(PLSRenderContextGL* context, const ShaderFeatures& shaderFeatures); @@ -110,9 +113,6 @@ bool QCOM_shader_framebuffer_fetch_noncoherent = false; } m_extensions; - // We only use one uniform buffer per shader, so for now, we bind them all to block 0. - constexpr static int kUniformBlockIdx = 0; - PLSRenderContextGL(const PlatformFeatures&, const Extensions& extensions, std::unique_ptr<PLSImpl>); @@ -122,7 +122,8 @@ return static_cast<const PLSRenderTargetGL*>(frameDescriptor().renderTarget.get()); } - std::unique_ptr<UniformBufferRing> makeUniformBufferRing(size_t sizeInBytes) override; + std::unique_ptr<BufferRingImpl> makeVertexBufferRing(size_t capacity, + size_t itemSizeInBytes) override; std::unique_ptr<TexelBufferRing> makeTexelBufferRing(TexelBufferRing::Format, size_t widthInItems, @@ -131,8 +132,8 @@ int textureIdx, TexelBufferRing::Filter) override; - std::unique_ptr<BufferRingImpl> makeVertexBufferRing(size_t capacity, - size_t itemSizeInBytes) override; + std::unique_ptr<BufferRingImpl> makeUniformBufferRing(size_t capacity, + size_t sizeInBytes) override; void allocateTessellationTexture(size_t height) override;
diff --git a/include/rive/pls/metal/pls_render_context_metal.h b/include/rive/pls/metal/pls_render_context_metal.h index e0c1d97..dda24cc 100644 --- a/include/rive/pls/metal/pls_render_context_metal.h +++ b/include/rive/pls/metal/pls_render_context_metal.h
@@ -30,7 +30,8 @@ private: PLSRenderContextMetal(const PlatformFeatures&, id<MTLDevice>, id<MTLCommandQueue>); - std::unique_ptr<UniformBufferRing> makeUniformBufferRing(size_t sizeInBytes) override; + std::unique_ptr<BufferRingImpl> makeVertexBufferRing(size_t capacity, + size_t itemSizeInBytes) override; std::unique_ptr<TexelBufferRing> makeTexelBufferRing(TexelBufferRing::Format, size_t widthInItems, @@ -39,8 +40,8 @@ int textureIdx, TexelBufferRing::Filter) override; - std::unique_ptr<BufferRingImpl> makeVertexBufferRing(size_t capacity, - size_t itemSizeInBytes) override; + std::unique_ptr<BufferRingImpl> makeUniformBufferRing(size_t capacity, + size_t itemSizeInBytes) override; void allocateTessellationTexture(size_t height) override;
diff --git a/include/rive/pls/pls.hpp b/include/rive/pls/pls.hpp index 9636ec8..9bcbfd9 100644 --- a/include/rive/pls/pls.hpp +++ b/include/rive/pls/pls.hpp
@@ -164,7 +164,7 @@ float viewportHeight; }; -// Uniform buffer layout for draw shaders. +// Per-flush uniforms used by the draw shader. struct DrawUniforms { DrawUniforms(float viewportWidth_, @@ -179,7 +179,7 @@ float viewportWidth; float viewportHeight; float gradTextureInverseHeight; - uint32_t pathIDGranularity; + uint32_t pathIDGranularity; // Spacing between adjacent path IDs (1 if IEEE compliant). float vertexDiscardValue = std::numeric_limits<float>::quiet_NaN(); uint32_t pad0 = 0; uint32_t pad1 = 0; @@ -187,6 +187,19 @@ }; static_assert(sizeof(DrawUniforms) == 8 * sizeof(uint32_t)); +// Per-draw uniforms that specify how to draw which tessellation vertices. +struct DrawParameters +{ + DrawParameters(int32_t wedgeSize_, int32_t baseTessellationVertex_) : + wedgeSize(wedgeSize_), baseTessellationVertex(baseTessellationVertex_) + {} + int32_t wedgeSize; + int32_t baseTessellationVertex; + uint32_t pad0 = 0; + uint32_t pad1 = 0; +}; +static_assert(sizeof(DrawParameters) == 4 * sizeof(int32_t)); + // Gradient color stops are implemented as a horizontal span of pixels in a global gradient texture. // They are rendered by "GradientSpan" instances. struct GradientSpan
diff --git a/include/rive/pls/pls_render_context.hpp b/include/rive/pls/pls_render_context.hpp index 6eb01d6..dddbec4 100644 --- a/include/rive/pls/pls_render_context.hpp +++ b/include/rive/pls/pls_render_context.hpp
@@ -217,7 +217,8 @@ protected: PLSRenderContext(const PlatformFeatures&); - virtual std::unique_ptr<UniformBufferRing> makeUniformBufferRing(size_t sizeInBytes) = 0; + virtual std::unique_ptr<BufferRingImpl> makeVertexBufferRing(size_t capacity, + size_t itemSizeInBytes) = 0; virtual std::unique_ptr<TexelBufferRing> makeTexelBufferRing(TexelBufferRing::Format, size_t widthInItems, @@ -226,22 +227,26 @@ int textureIdx, TexelBufferRing::Filter) = 0; - virtual std::unique_ptr<BufferRingImpl> makeVertexBufferRing(size_t capacity, - size_t itemSizeInBytes) = 0; + virtual std::unique_ptr<BufferRingImpl> makeUniformBufferRing(size_t capacity, + size_t sizeInBytes) = 0; virtual void allocateTessellationTexture(size_t height) = 0; - const UniformBufferRing* gradUniformBufferRing() const + const BufferRingImpl* colorRampUniforms() const { - return static_cast<const UniformBufferRing*>(m_gradUniformBuffer.impl()); + return static_cast<const BufferRingImpl*>(m_colorRampUniforms.impl()); } - const UniformBufferRing* tessellateUniformBufferRing() + const BufferRingImpl* tessellateUniforms() { - return static_cast<const UniformBufferRing*>(m_tessellateUniformBuffer.impl()); + return static_cast<const BufferRingImpl*>(m_tessellateUniforms.impl()); } - const UniformBufferRing* drawUniformBufferRing() + const BufferRingImpl* drawUniforms() { - return static_cast<const UniformBufferRing*>(m_drawUniformBuffer.impl()); + return static_cast<const BufferRingImpl*>(m_drawUniforms.impl()); + } + const BufferRingImpl* drawParametersBufferRing() + { + return static_cast<const BufferRingImpl*>(m_drawParametersBuffer.impl()); } const TexelBufferRing* pathBufferRing() { @@ -333,6 +338,7 @@ size_t maxComplexGradientSpans; size_t maxTessellationSpans; size_t maxTessellationVertices; + size_t maxDrawParameters; // "*this = max(*this, other)" void accumulateMax(const GPUResourceLimits& other) @@ -346,7 +352,8 @@ maxTessellationSpans = std::max(maxTessellationSpans, other.maxTessellationSpans); maxTessellationVertices = std::max(maxTessellationVertices, other.maxTessellationVertices); - static_assert(sizeof(*this) == sizeof(size_t) * 7); // Make sure we got every field. + maxDrawParameters = std::max(maxDrawParameters, other.maxDrawParameters); + static_assert(sizeof(*this) == sizeof(size_t) * 8); // Make sure we got every field. } // Scale each limit > threshold by a factor of "scaleFactor". @@ -371,7 +378,9 @@ if (maxTessellationVertices > threshold.maxTessellationVertices) scaled.maxTessellationVertices = static_cast<double>(maxTessellationVertices) * scaleFactor; - static_assert(sizeof(*this) == sizeof(size_t) * 7); // Make sure we got every field. + if (maxDrawParameters > threshold.maxDrawParameters) + scaled.maxDrawParameters = static_cast<double>(maxDrawParameters) * scaleFactor; + static_assert(sizeof(*this) == sizeof(size_t) * 8); // Make sure we got every field. return scaled; } @@ -398,6 +407,13 @@ GPUResourceLimits m_currentFrameResourceUsage = {}; GPUResourceLimits m_maxRecentResourceUsage = {}; + // Here we cache the contents of the uniform buffers that only have one item (and are therefore + // constant throughout an entire flush). We use these cached values to determine whether the + // buffers need to be updated at the beginning of a flush. + ColorRampUniforms m_cachedColorRampUniformData{}; + TessellateUniforms m_cachedTessUniformData{}; + DrawUniforms m_cachedDrawUniformData{0, 0, 0, m_platformFeatures}; + // Simple gradients only have 2 texels, so we write them to mapped texture memory from the CPU // instead of rendering them. struct TwoTexelRamp @@ -415,9 +431,10 @@ BufferRing<TwoTexelRamp> m_gradTexelBuffer; // Simple gradients get written by the CPU. BufferRing<GradientSpan> m_gradSpanBuffer; // Complex gradients get rendered by the GPU. BufferRing<TessVertexSpan> m_tessSpanBuffer; - BufferRing<ColorRampUniforms> m_gradUniformBuffer; - BufferRing<TessellateUniforms> m_tessellateUniformBuffer; - BufferRing<DrawUniforms> m_drawUniformBuffer; + BufferRing<DrawParameters> m_drawParametersBuffer; + BufferRing<ColorRampUniforms> m_colorRampUniforms; + BufferRing<TessellateUniforms> m_tessellateUniforms; + BufferRing<DrawUniforms> m_drawUniforms; // How many rows of the gradient texture are dedicated to simple (two-texel) ramps? // This is also the y-coordinate at which the complex color ramps begin.
diff --git a/renderer/gl/buffer_ring_gl.cpp b/renderer/gl/buffer_ring_gl.cpp index 7c01a61..cc962dd 100644 --- a/renderer/gl/buffer_ring_gl.cpp +++ b/renderer/gl/buffer_ring_gl.cpp
@@ -8,52 +8,23 @@ namespace rive::pls { -VertexBufferGL::VertexBufferGL(size_t capacity, size_t itemSizeInBytes) : - BufferRingShadowImpl(capacity, itemSizeInBytes) +BufferGL::BufferGL(GLenum target, size_t capacity, size_t itemSizeInBytes) : + BufferRingShadowImpl(capacity, itemSizeInBytes), m_target(target) { glGenBuffers(kBufferRingSize, m_ids); for (int i = 0; i < kBufferRingSize; ++i) { - glBindBuffer(GL_ARRAY_BUFFER, m_ids[i]); - glBufferData(GL_ARRAY_BUFFER, capacity * itemSizeInBytes, nullptr, GL_DYNAMIC_DRAW); + glBindBuffer(m_target, m_ids[i]); + glBufferData(m_target, capacity * itemSizeInBytes, nullptr, GL_DYNAMIC_DRAW); } } -VertexBufferGL::~VertexBufferGL() { glDeleteBuffers(kBufferRingSize, m_ids); } +BufferGL::~BufferGL() { glDeleteBuffers(kBufferRingSize, m_ids); } -void VertexBufferGL::bindCurrentBuffer() const +void BufferGL::onUnmapAndSubmitBuffer(int bufferIdx, size_t bytesWritten) { - glBindBuffer(GL_ARRAY_BUFFER, m_ids[submittedBufferIdx()]); -} - -void VertexBufferGL::onUnmapAndSubmitBuffer(int bufferIdx, size_t bytesWritten) -{ - glBindBuffer(GL_UNIFORM_BUFFER, m_ids[bufferIdx]); - glBufferSubData(GL_UNIFORM_BUFFER, 0, bytesWritten, shadowBuffer()); -} - -UniformBufferGL::UniformBufferGL(size_t itemSizeInBytes) : UniformBufferRing(itemSizeInBytes) -{ - glGenBuffers(kBufferRingSize, m_ids); - for (int i = 0; i < kBufferRingSize; ++i) - { - glBindBuffer(GL_UNIFORM_BUFFER, m_ids[i]); - glBufferData(GL_UNIFORM_BUFFER, itemSizeInBytes, nullptr, GL_DYNAMIC_DRAW); - } -} - -UniformBufferGL::~UniformBufferGL() { glDeleteBuffers(kBufferRingSize, m_ids); } - -void UniformBufferGL::bindToUniformBlock(GLuint blockIndex) const -{ - glBindBufferBase(GL_UNIFORM_BUFFER, blockIndex, m_ids[submittedBufferIdx()]); -} - -void UniformBufferGL::onUnmapAndSubmitBuffer(int bufferIdx, size_t bytesWritten) -{ - assert(bytesWritten == itemSizeInBytes()); - glBindBuffer(GL_UNIFORM_BUFFER, m_ids[bufferIdx]); - glBufferSubData(GL_UNIFORM_BUFFER, 0, bytesWritten, shadowBuffer()); + glBindBuffer(m_target, m_ids[bufferIdx]); + glBufferSubData(m_target, 0, bytesWritten, shadowBuffer()); } static GLenum internalformat_gl(TexelBufferRing::Format format)
diff --git a/renderer/gl/buffer_ring_gl.hpp b/renderer/gl/buffer_ring_gl.hpp index 8406715..5b5fc8a 100644 --- a/renderer/gl/buffer_ring_gl.hpp +++ b/renderer/gl/buffer_ring_gl.hpp
@@ -9,35 +9,21 @@ namespace rive::pls { -// BufferRingImpl of a GL_ARRAY_BUFFER. In order to support WebGL2, we don't support mapping. -class VertexBufferGL : public BufferRingShadowImpl +// BufferRingImpl in GL on a given buffer target. In order to support WebGL2, we don't do hardware +// mapping. +class BufferGL : public BufferRingShadowImpl { public: - VertexBufferGL(size_t capacity, size_t itemSizeInBytes); - ~VertexBufferGL() override; + BufferGL(GLenum target, size_t capacity, size_t itemSizeInBytes); + ~BufferGL() override; - void bindCurrentBuffer() const; + GLuint submittedBufferID() const { return m_ids[submittedBufferIdx()]; } protected: void onUnmapAndSubmitBuffer(int bufferIdx, size_t bytesWritten) override; private: - GLuint m_ids[kBufferRingSize]; -}; - -// BufferRingImpl of a GL_UNIFORM_BUFFER. -class UniformBufferGL : public UniformBufferRing -{ -public: - UniformBufferGL(size_t itemSizeInBytes); - ~UniformBufferGL() override; - - void bindToUniformBlock(GLuint blockIndex) const; - -protected: - void onUnmapAndSubmitBuffer(int bufferIdx, size_t bytesWritten) override; - -private: + const GLenum m_target; GLuint m_ids[kBufferRingSize]; };
diff --git a/renderer/gl/pls_render_context_gl.cpp b/renderer/gl/pls_render_context_gl.cpp index 06e212c..8a1c49f 100644 --- a/renderer/gl/pls_render_context_gl.cpp +++ b/renderer/gl/pls_render_context_gl.cpp
@@ -51,7 +51,7 @@ glutils::LinkProgram(m_colorRampProgram); glUniformBlockBinding(m_colorRampProgram, glGetUniformBlockIndex(m_colorRampProgram, GLSL_Uniforms), - kUniformBlockIdx); + 0); glGenVertexArrays(1, &m_colorRampVAO); glBindVertexArray(m_colorRampVAO); @@ -77,7 +77,7 @@ glutils::LinkProgram(m_tessellateProgram); glUniformBlockBinding(m_tessellateProgram, glGetUniformBlockIndex(m_tessellateProgram, GLSL_Uniforms), - kUniformBlockIdx); + 0); glGenVertexArrays(1, &m_tessellateVAO); glBindVertexArray(m_tessellateVAO); @@ -144,9 +144,10 @@ glDeleteBuffers(1, &m_pathWedgeIndexBuffer); } -std::unique_ptr<UniformBufferRing> PLSRenderContextGL::makeUniformBufferRing(size_t sizeInBytes) +std::unique_ptr<BufferRingImpl> PLSRenderContextGL::makeVertexBufferRing(size_t capacity, + size_t itemSizeInBytes) { - return std::make_unique<UniformBufferGL>(sizeInBytes); + return std::make_unique<BufferGL>(GL_ARRAY_BUFFER, capacity, itemSizeInBytes); } std::unique_ptr<TexelBufferRing> PLSRenderContextGL::makeTexelBufferRing( @@ -165,10 +166,10 @@ filter); } -std::unique_ptr<BufferRingImpl> PLSRenderContextGL::makeVertexBufferRing(size_t capacity, - size_t itemSizeInBytes) +std::unique_ptr<BufferRingImpl> PLSRenderContextGL::makeUniformBufferRing(size_t capacity, + size_t sizeInBytes) { - return std::make_unique<VertexBufferGL>(capacity, itemSizeInBytes); + return std::make_unique<BufferGL>(GL_UNIFORM_BUFFER, capacity, sizeInBytes); } void PLSRenderContextGL::allocateTessellationTexture(size_t height) @@ -289,7 +290,10 @@ glutils::LinkProgram(m_id); glUseProgram(m_id); - glUniformBlockBinding(m_id, glGetUniformBlockIndex(m_id, GLSL_Uniforms), kUniformBlockIdx); + glUniformBlockBinding(m_id, glGetUniformBlockIndex(m_id, GLSL_Uniforms), kUniformsBlockIdx); + glUniformBlockBinding(m_id, + glGetUniformBlockIndex(m_id, GLSL_DrawParameters), + kDrawParametersBlockIdx); glUniform1i(glGetUniformLocation(m_id, GLSL_tessVertexTexture), kGLTexIdxOffset + kTessVertexTextureIdx); glUniform1i(glGetUniformLocation(m_id, GLSL_pathTexture), kGLTexIdxOffset + kPathTextureIdx); @@ -300,11 +304,22 @@ PLSRenderContextGL::DrawProgram::~DrawProgram() { glDeleteProgram(m_id); } +static GLuint gl_buffer_id(const BufferRingImpl* bufferRing) +{ + return static_cast<const BufferGL*>(bufferRing)->submittedBufferID(); +} + +static GLuint gl_texture_id(const TexelBufferRing* texelBufferRing) +{ + return static_cast<const TexelBufferGL*>(texelBufferRing)->submittedTextureID(); +} + void PLSRenderContextGL::bindDrawProgram(const DrawProgram& drawProgram) { glBindVertexArray(m_drawVAO); - static_cast<const UniformBufferGL*>(drawUniformBufferRing()) - ->bindToUniformBlock(kUniformBlockIdx); + glBindBufferBase(GL_UNIFORM_BUFFER, + DrawProgram::kUniformsBlockIdx, + gl_buffer_id(drawUniforms())); glUseProgram(drawProgram.id()); } @@ -320,19 +335,17 @@ // Render the complex color ramps to the gradient texture. if (gradSpanCount > 0) { - static_cast<const VertexBufferGL*>(gradSpanBufferRing())->bindCurrentBuffer(); + glBindBuffer(GL_ARRAY_BUFFER, gl_buffer_id(gradSpanBufferRing())); glBindVertexArray(m_colorRampVAO); glVertexAttribIPointer(0, 4, GL_UNSIGNED_INT, sizeof(GradientSpan), nullptr); glViewport(0, gradTextureRowsForSimpleRamps(), kGradTextureWidth, gradSpansHeight); glBindFramebuffer(GL_FRAMEBUFFER, m_colorRampFBO); - glFramebufferTexture2D( - GL_FRAMEBUFFER, - GL_COLOR_ATTACHMENT0, - GL_TEXTURE_2D, - static_cast<const TexelBufferGL*>(gradTexelBufferRing())->submittedTextureID(), - 0); - static_cast<const UniformBufferGL*>(gradUniformBufferRing()) - ->bindToUniformBlock(kUniformBlockIdx); + glFramebufferTexture2D(GL_FRAMEBUFFER, + GL_COLOR_ATTACHMENT0, + GL_TEXTURE_2D, + gl_texture_id(gradTexelBufferRing()), + 0); + glBindBufferBase(GL_UNIFORM_BUFFER, 0, gl_buffer_id(colorRampUniforms())); glUseProgram(m_colorRampProgram); glDrawArraysInstanced(GL_TRIANGLE_STRIP, 0, 4, gradSpanCount); } @@ -340,7 +353,7 @@ // Tessellate all curves into vertices in the tessellation texture. if (tessVertexSpanCount > 0) { - static_cast<const VertexBufferGL*>(tessSpanBufferRing())->bindCurrentBuffer(); + glBindBuffer(GL_ARRAY_BUFFER, gl_buffer_id(tessSpanBufferRing())); glBindVertexArray(m_tessellateVAO); for (int i = 0; i < 3; ++i) { @@ -359,8 +372,7 @@ glViewport(0, 0, kTessTextureWidth, tessDataHeight); glBindFramebuffer(GL_FRAMEBUFFER, m_tessellateFBO); glUseProgram(m_tessellateProgram); - static_cast<const UniformBufferGL*>(tessellateUniformBufferRing()) - ->bindToUniformBlock(kUniformBlockIdx); + glBindBufferBase(GL_UNIFORM_BUFFER, 0, gl_buffer_id(tessellateUniforms())); glDrawArraysInstanced(GL_TRIANGLE_STRIP, 0, 4, tessVertexSpanCount); } @@ -387,6 +399,11 @@ if (wedgeInstanceCount > 0) { // Draw wedges connecting all tessellated vertices. + glBindBufferRange(GL_UNIFORM_BUFFER, + DrawProgram::kDrawParametersBlockIdx, + gl_buffer_id(drawParametersBufferRing()), + 0 * sizeof(DrawUniforms), + sizeof(DrawUniforms)); glDrawElementsInstanced(GL_TRIANGLES, kOuterStrokeWedgeIndexCount, GL_UNSIGNED_SHORT,
diff --git a/renderer/metal/buffer_ring_metal.h b/renderer/metal/buffer_ring_metal.h index 1f60e8b..ac51158 100644 --- a/renderer/metal/buffer_ring_metal.h +++ b/renderer/metal/buffer_ring_metal.h
@@ -12,11 +12,11 @@ namespace rive::pls { -class VertexBufferMetal : public BufferRingImpl +class BufferMetal : public BufferRingImpl { public: - VertexBufferMetal(id<MTLDevice>, size_t capacity, size_t itemSizeInBytes); - ~VertexBufferMetal() override {} + BufferMetal(id<MTLDevice>, size_t capacity, size_t itemSizeInBytes); + ~BufferMetal() override {} id<MTLBuffer> submittedBuffer() const { return m_buffers[submittedBufferIdx()]; } @@ -28,21 +28,6 @@ id<MTLBuffer> m_buffers[kBufferRingSize]; }; -class UniformBufferMetal : public UniformBufferRing -{ -public: - UniformBufferMetal(id<MTLDevice>, size_t itemSizeInBytes); - ~UniformBufferMetal() override {} - - id<MTLBuffer> submittedBuffer() const { return m_buffers[submittedBufferIdx()]; } - -protected: - void onUnmapAndSubmitBuffer(int bufferIdx, size_t bytesWritten) override; - -private: - id<MTLBuffer> m_buffers[kBufferRingSize]; -}; - class TexelBufferMetal : public TexelBufferRing { public:
diff --git a/renderer/metal/buffer_ring_metal.mm b/renderer/metal/buffer_ring_metal.mm index 040296e..bc53b27 100644 --- a/renderer/metal/buffer_ring_metal.mm +++ b/renderer/metal/buffer_ring_metal.mm
@@ -8,7 +8,7 @@ namespace rive::pls { -VertexBufferMetal::VertexBufferMetal(id<MTLDevice> gpu, size_t capacity, size_t itemSizeInBytes) : +BufferMetal::BufferMetal(id<MTLDevice> gpu, size_t capacity, size_t itemSizeInBytes) : BufferRingImpl(capacity, itemSizeInBytes) { for (int i = 0; i < kBufferRingSize; ++i) @@ -18,23 +18,7 @@ } } -void* VertexBufferMetal::onMapBuffer(int bufferIdx) { return m_buffers[bufferIdx].contents; } - -UniformBufferMetal::UniformBufferMetal(id<MTLDevice> gpu, size_t itemSizeInBytes) : - UniformBufferRing(itemSizeInBytes) -{ - for (int i = 0; i < kBufferRingSize; ++i) - { - m_buffers[i] = [gpu newBufferWithLength:itemSizeInBytes - options:MTLResourceStorageModeShared]; - } -} - -void UniformBufferMetal::onUnmapAndSubmitBuffer(int bufferIdx, size_t bytesWritten) -{ - assert(bytesWritten == itemSizeInBytes()); - memcpy(m_buffers[bufferIdx].contents, shadowBuffer(), bytesWritten); -} +void* BufferMetal::onMapBuffer(int bufferIdx) { return m_buffers[bufferIdx].contents; } TexelBufferMetal::TexelBufferMetal(id<MTLDevice> gpu, Format format,
diff --git a/renderer/metal/pls_render_context_metal.mm b/renderer/metal/pls_render_context_metal.mm index 889ee94..e23091f 100644 --- a/renderer/metal/pls_render_context_metal.mm +++ b/renderer/metal/pls_render_context_metal.mm
@@ -230,9 +230,10 @@ new PLSRenderTargetMetal(m_gpu, pixelFormat, width, height, m_platformFeatures)); } -std::unique_ptr<UniformBufferRing> PLSRenderContextMetal::makeUniformBufferRing(size_t sizeInBytes) +std::unique_ptr<BufferRingImpl> PLSRenderContextMetal::makeVertexBufferRing(size_t capacity, + size_t itemSizeInBytes) { - return std::make_unique<UniformBufferMetal>(m_gpu, sizeInBytes); + return std::make_unique<BufferMetal>(m_gpu, capacity, itemSizeInBytes); } std::unique_ptr<TexelBufferRing> PLSRenderContextMetal::makeTexelBufferRing( @@ -246,10 +247,10 @@ return std::make_unique<TexelBufferMetal>(m_gpu, format, widthInItems, height, texelsPerItem); } -std::unique_ptr<BufferRingImpl> PLSRenderContextMetal::makeVertexBufferRing(size_t capacity, - size_t itemSizeInBytes) +std::unique_ptr<BufferRingImpl> PLSRenderContextMetal::makeUniformBufferRing(size_t capacity, + size_t itemSizeInBytes) { - return std::make_unique<VertexBufferMetal>(m_gpu, capacity, itemSizeInBytes); + return std::make_unique<BufferMetal>(m_gpu, capacity, itemSizeInBytes); } void PLSRenderContextMetal::allocateTessellationTexture(size_t height) @@ -273,6 +274,16 @@ m_bufferRingLocks[m_bufferRingIdx].lock(); } +static id<MTLBuffer> mtl_buffer(const BufferRingImpl* bufferRing) +{ + return static_cast<const BufferMetal*>(bufferRing)->submittedBuffer(); +} + +static id<MTLTexture> mtl_texture(const TexelBufferRing* texelBufferRing) +{ + return static_cast<const TexelBufferMetal*>(texelBufferRing)->submittedTexture(); +} + void PLSRenderContextMetal::onFlush(FlushType flushType, LoadAction loadAction, size_t gradSpanCount, @@ -304,8 +315,7 @@ // gradPass.colorAttachments[0].loadAction = MTLLoadActionLoad; gradPass.colorAttachments[0].storeAction = MTLStoreActionStore; - gradPass.colorAttachments[0].texture = - static_cast<const TexelBufferMetal*>(gradTexelBufferRing())->submittedTexture(); + gradPass.colorAttachments[0].texture = mtl_texture(gradTexelBufferRing()); id<MTLRenderCommandEncoder> gradEncoder = [commandBuffer renderCommandEncoderWithDescriptor:gradPass]; @@ -316,14 +326,8 @@ 0.0, 1.0}]; [gradEncoder setRenderPipelineState:m_colorRampPipeline->pipelineState()]; - [gradEncoder setVertexBuffer:static_cast<const UniformBufferMetal*>(gradUniformBufferRing()) - ->submittedBuffer() - offset:0 - atIndex:0]; - [gradEncoder setVertexBuffer:static_cast<const VertexBufferMetal*>(gradSpanBufferRing()) - ->submittedBuffer() - offset:0 - atIndex:1]; + [gradEncoder setVertexBuffer:mtl_buffer(colorRampUniforms()) offset:0 atIndex:0]; + [gradEncoder setVertexBuffer:mtl_buffer(gradSpanBufferRing()) offset:0 atIndex:1]; [gradEncoder drawPrimitives:MTLPrimitiveTypeTriangleStrip vertexStart:0 vertexCount:4 @@ -350,15 +354,8 @@ 0.0, 1.0}]; [tessEncoder setRenderPipelineState:m_tessPipeline->pipelineState()]; - [tessEncoder - setVertexBuffer:static_cast<const UniformBufferMetal*>(tessellateUniformBufferRing()) - ->submittedBuffer() - offset:0 - atIndex:0]; - [tessEncoder setVertexBuffer:static_cast<const VertexBufferMetal*>(tessSpanBufferRing()) - ->submittedBuffer() - offset:0 - atIndex:1]; + [tessEncoder setVertexBuffer:mtl_buffer(tessellateUniforms()) offset:0 atIndex:0]; + [tessEncoder setVertexBuffer:mtl_buffer(tessSpanBufferRing()) offset:0 atIndex:1]; [tessEncoder drawPrimitives:MTLPrimitiveTypeTriangleStrip vertexStart:0 vertexCount:4 @@ -413,21 +410,13 @@ 0.0, 1.0}]; [encoder setRenderPipelineState:drawPipeline.pipelineState(renderTarget->pixelFormat())]; - [encoder setVertexBuffer:static_cast<const UniformBufferMetal*>(drawUniformBufferRing()) - ->submittedBuffer() - offset:0 - atIndex:0]; - [encoder setVertexBuffer:m_pathWedgeVertexBuffer offset:0 atIndex:1]; + [encoder setVertexBuffer:mtl_buffer(drawUniforms()) offset:0 atIndex:0]; + [encoder setVertexBuffer:mtl_buffer(drawParametersBufferRing()) offset:0 atIndex:1]; + [encoder setVertexBuffer:m_pathWedgeVertexBuffer offset:0 atIndex:2]; [encoder setVertexTexture:m_tessVertexTexture atIndex:kTessVertexTextureIdx]; - [encoder setVertexTexture:static_cast<const TexelBufferMetal*>(pathBufferRing()) - ->submittedTexture() - atIndex:kPathTextureIdx]; - [encoder setVertexTexture:static_cast<const TexelBufferMetal*>(contourBufferRing()) - ->submittedTexture() - atIndex:kContourTextureIdx]; - [encoder setFragmentTexture:static_cast<const TexelBufferMetal*>(gradTexelBufferRing()) - ->submittedTexture() - atIndex:kGradTextureIdx]; + [encoder setVertexTexture:mtl_texture(pathBufferRing()) atIndex:kPathTextureIdx]; + [encoder setVertexTexture:mtl_texture(contourBufferRing()) atIndex:kContourTextureIdx]; + [encoder setFragmentTexture:mtl_texture(gradTexelBufferRing()) atIndex:kGradTextureIdx]; if (frameDescriptor().wireframe) { [encoder setTriangleFillMode:MTLTriangleFillModeLines];
diff --git a/renderer/pls_render_context.cpp b/renderer/pls_render_context.cpp index 1c79982..18557ef 100644 --- a/renderer/pls_render_context.cpp +++ b/renderer/pls_render_context.cpp
@@ -204,27 +204,6 @@ #define COUNT_RESOURCE_SIZE(SIZE_IN_BYTES) #endif - // One-time allocation of the gradient uniform buffer ring. - if (m_gradUniformBuffer.impl() == nullptr) - { - m_gradUniformBuffer.reset(makeUniformBufferRing(sizeof(ColorRampUniforms))); - } - COUNT_RESOURCE_SIZE(m_gradUniformBuffer.totalSizeInBytes()); - - // One-time allocation of the tessellation uniform buffer ring. - if (m_tessellateUniformBuffer.impl() == nullptr) - { - m_tessellateUniformBuffer.reset(makeUniformBufferRing(sizeof(TessellateUniforms))); - } - COUNT_RESOURCE_SIZE(m_tessellateUniformBuffer.totalSizeInBytes()); - - // One-time allocation of the draw uniform buffer ring. - if (m_drawUniformBuffer.impl() == nullptr) - { - m_drawUniformBuffer.reset(makeUniformBufferRing(sizeof(DrawUniforms))); - } - COUNT_RESOURCE_SIZE(m_drawUniformBuffer.totalSizeInBytes()); - // Path data texture ring. constexpr size_t kMinPathIDCount = kPathTextureWidthInItems * 32; // 32 texels tall. size_t targetMaxPathID = resource_texture_height(kPathTextureWidthInItems, targets.maxPathID) * @@ -375,6 +354,45 @@ targetTessTextureHeight * kTessTextureWidth; } COUNT_RESOURCE_SIZE(targetTessTextureHeight * kTessTextureWidth * 4 * sizeof(uint32_t)); + + // Draw parameters uniform buffer ring. + constexpr size_t kMinDrawParameters = 2048; // 96 KiB + size_t maxDrawParameters = m_maxPathID; // Can't have more draws than paths. + size_t targetDrawParameters = targets.maxDrawParameters; + targetDrawParameters = std::clamp(targetDrawParameters, kMinDrawParameters, maxDrawParameters); + if (shouldReallocate(targetDrawParameters, m_currentResourceLimits.maxDrawParameters)) + { + assert(!m_drawParametersBuffer.mapped()); + m_drawParametersBuffer.reset( + makeUniformBufferRing(targetDrawParameters, sizeof(DrawParameters))); + LOG_CHANGED_SIZE("draw uniform buffer count", + m_currentResourceLimits.maxDrawParameters, + targetDrawParameters, + m_drawParametersBuffer.totalSizeInBytes()); + m_currentResourceLimits.maxDrawParameters = targetDrawParameters; + } + COUNT_RESOURCE_SIZE(m_drawParametersBuffer.totalSizeInBytes()); + + // One-time allocation of the gradient uniform buffer ring. + if (m_colorRampUniforms.impl() == nullptr) + { + m_colorRampUniforms.reset(makeUniformBufferRing(1, sizeof(ColorRampUniforms))); + } + COUNT_RESOURCE_SIZE(m_colorRampUniforms.totalSizeInBytes()); + + // One-time allocation of the tessellation uniform buffer ring. + if (m_tessellateUniforms.impl() == nullptr) + { + m_tessellateUniforms.reset(makeUniformBufferRing(1, sizeof(TessellateUniforms))); + } + COUNT_RESOURCE_SIZE(m_tessellateUniforms.totalSizeInBytes()); + + // One-time allocation of the draw uniform buffer ring. + if (m_drawUniforms.impl() == nullptr) + { + m_drawUniforms.reset(makeUniformBufferRing(1, sizeof(DrawUniforms))); + } + COUNT_RESOURCE_SIZE(m_drawUniforms.totalSizeInBytes()); } void PLSRenderContext::beginFrame(FrameDescriptor&& frameDescriptor) @@ -732,81 +750,93 @@ assert(m_tessVertexCount <= m_currentResourceLimits.maxTessellationVertices); } +template <typename T> bool bits_equal(const T* a, const T* b) +{ + return memcmp(a, b, sizeof(T)) == 0; +} + void PLSRenderContext::flush(FlushType flushType) { assert(m_didBeginFrame); + // The first tessellated vertex in every contour gets the kFirstVertexOfContour flag, and when + // emitting wedges, this flag is how the GPU detects when it has crossed past the end of the + // current contour. When this happens, the GPU knows to no not connect those two vertices, and + // instead, either wraps back around to the beginning of the contour to close it, or else + // handles the endcap if it's an open stroke. + // + // The final wedge of the final contour in our buffer also needs to see that + // kFirstVertexOfContour flag in order to render properly, so so we tessellate (and don't draw) + // one more empty line at the end of the buffer as an end-of-previous-contour marker. + // + // TODO: This is a little kludgey. Maybe we can find a cleaner way to accomplish this? if (!m_tessSpanBuffer.empty()) { - // The first tessellated vertex in every contour gets the kFirstVertexOfContour flag, and - // when emitting wedges, this flag is how the GPU detects when it has crossed past the end - // of the current contour. When this happens, the GPU knows to no not connect those two - // vertices, and instead, either wraps back around to the beginning of the contour to close - // it, or else handles the endcap if it's an open stroke. - // - // The final wedge of the final contour in our buffer also needs to see that - // kFirstVertexOfContour flag in order to render properly, so so we tessellate (and don't - // draw) one more empty line at the end of the buffer as an end-of-previous-contour marker. - // - // TODO: This is a little kludgey. Maybe we can find a cleaner way to accomplish this? Vec2D emptyLine[4]{}; // Make sure this empty line gets the kFirstVertexOfContour flag. m_currentContourIDWithFlags = ~0; this->pushCubic(emptyLine, Vec2D{}, 0, 1, 1, 1); } - // Upload all data before flushing. - m_pathBuffer.submit(); - m_contourBuffer.submit(); + // For now, there is only one draw per flush. + assert(m_drawParametersBuffer.empty()); + m_drawParametersBuffer.ensureMapped(); + m_drawParametersBuffer.emplace_back(kWedgeSize, 0); - // Upload texels for simple (two-texel) gradient color ramps. - m_gradTexelBuffer.submit(); - - // Submit the instance buffer for rendering complex color ramps. + // Determine how much to draw. size_t gradSpanCount = m_gradSpanBuffer.bytesWritten() / sizeof(GradientSpan); - assert(m_complexGradients.empty() == (gradSpanCount == 0)); - m_gradSpanBuffer.submit(); - - if (gradSpanCount) - { - // Submit the uniform buffer for rendering complex color ramps. - ColorRampUniforms uniformData = {static_cast<float>(m_complexGradients.size())}; - if (!gradUniformBufferRing()->contentMatches(&uniformData)) - { - m_gradUniformBuffer.ensureMapped(); - m_gradUniformBuffer.emplace_back(uniformData); - m_gradUniformBuffer.submit(); - } - } - size_t tessVertexSpanCount = m_tessSpanBuffer.bytesWritten() / sizeof(TessVertexSpan); - m_tessSpanBuffer.submit(); - size_t tessDataHeight = (m_tessVertexCount + kTessTextureWidth - 1) / kTessTextureWidth; - TessellateUniforms tessUniformData{kTessTextureWidth, static_cast<float>(tessDataHeight)}; - if (!tessellateUniformBufferRing()->contentMatches(&tessUniformData)) - { - m_tessellateUniformBuffer.ensureMapped(); - m_tessellateUniformBuffer.emplace_back(tessUniformData); - m_tessellateUniformBuffer.submit(); - } - - DrawUniforms drawUniformData(m_frameDescriptor.renderTarget->width(), - m_frameDescriptor.renderTarget->height(), - gradTexelBufferRing()->height(), - m_platformFeatures); - if (!drawUniformBufferRing()->contentMatches(&drawUniformData)) - { - m_drawUniformBuffer.ensureMapped(); - m_drawUniformBuffer.emplace_back(drawUniformData); - m_drawUniformBuffer.submit(); - } - // Don't draw the empty "end-of-contour" marker's vertices. size_t tessVertexCountToDraw = std::max<size_t>(m_tessVertexCount, 2) - 2; // PLSRenderer should have padded the vertex count of each contour to a multiple of kWedgeSize. assert(tessVertexCountToDraw % kWedgeSize == 0); size_t wedgeInstanceCount = tessVertexCountToDraw / kWedgeSize; + size_t drawParametersCount = m_drawParametersBuffer.bytesWritten() / sizeof(DrawParameters); + + // Upload all non-empty buffers before flushing. + m_pathBuffer.submit(); + m_contourBuffer.submit(); + m_gradTexelBuffer.submit(); + m_gradSpanBuffer.submit(); + m_tessSpanBuffer.submit(); + m_drawParametersBuffer.submit(); + + if (gradSpanCount) + { + // Update the uniform buffer for rendering complex color ramps if needed. + ColorRampUniforms uniformData = {static_cast<float>(m_complexGradients.size())}; + if (!bits_equal(&m_cachedColorRampUniformData, &uniformData)) + { + m_colorRampUniforms.ensureMapped(); + m_colorRampUniforms.emplace_back(uniformData); + m_colorRampUniforms.submit(); + m_cachedColorRampUniformData = uniformData; + } + } + + // Update the uniform buffer for rendering tessellations if needed. + TessellateUniforms tessUniformData = {kTessTextureWidth, static_cast<float>(tessDataHeight)}; + if (!bits_equal(&m_cachedTessUniformData, &tessUniformData)) + { + m_tessellateUniforms.ensureMapped(); + m_tessellateUniforms.emplace_back(tessUniformData); + m_tessellateUniforms.submit(); + m_cachedTessUniformData = tessUniformData; + } + + // Update the uniform buffer for drawing if needed. + DrawUniforms drawUniformData(m_frameDescriptor.renderTarget->width(), + m_frameDescriptor.renderTarget->height(), + gradTexelBufferRing()->height(), + m_platformFeatures); + if (!bits_equal(&m_cachedDrawUniformData, &drawUniformData)) + { + m_drawUniforms.ensureMapped(); + m_drawUniforms.emplace_back(drawUniformData); + m_drawUniforms.submit(); + m_cachedDrawUniformData = drawUniformData; + } onFlush(flushType, m_isFirstFlushOfFrame ? frameDescriptor().loadAction : LoadAction::preserveRenderTarget, @@ -824,8 +854,9 @@ m_currentFrameResourceUsage.maxComplexGradientSpans += gradSpanCount; m_currentFrameResourceUsage.maxTessellationSpans += tessVertexSpanCount; m_currentFrameResourceUsage.maxTessellationVertices += m_tessVertexCount; + m_currentFrameResourceUsage.maxDrawParameters += drawParametersCount; static_assert(sizeof(m_currentFrameResourceUsage) == - sizeof(size_t) * 7); // Make sure we got every field. + sizeof(size_t) * 8); // Make sure we got every field. m_lastGeneratedClipID = 0; m_clipContentID = 0;
diff --git a/renderer/shaders/draw.glsl b/renderer/shaders/draw.glsl index ea61fc3..ef7b421 100644 --- a/renderer/shaders/draw.glsl +++ b/renderer/shaders/draw.glsl
@@ -2,8 +2,6 @@ * Copyright 2022 Rive */ -#define WEDGE_SIZE 8 - #define AA_RADIUS .5 #define STROKE_VERTEX .0 @@ -64,6 +62,13 @@ uint pad2; UNIFORM_BLOCK_END(uniforms) +UNIFORM_BLOCK_BEGIN(@DrawParameters) +int wedgeSize; +int baseTessellationVertex; +int pad0; +int pad1; +UNIFORM_BLOCK_END(drawParameters) + VERTEX_TEXTURE_BLOCK_BEGIN(VertexTextures) TEXTURE_RGBA32UI(0) @tessVertexTexture; TEXTURE_RGBA32UI(1) @pathTexture; @@ -95,7 +100,8 @@ uint GLSL_VERTEX_ID [[vertex_id]], uint GLSL_INSTANCE_ID [[instance_id]], constant @Uniforms& uniforms [[buffer(0)]], - constant Attrs* attrs [[buffer(1)]], + constant @DrawParameters& drawParameters [[buffer(1)]], + constant Attrs* attrs [[buffer(2)]], VertexTextures textures #endif ) @@ -108,12 +114,13 @@ float vertexType = wedgeVertexData.w; // Fetch the tessellation vertex we belong to. - int vertexIdx = GLSL_INSTANCE_ID * WEDGE_SIZE + localVertexID; + int vertexIdx = GLSL_INSTANCE_ID * drawParameters.wedgeSize + + drawParameters.baseTessellationVertex + localVertexID; int2 tessVertexTexelCoord = tessTexelCoord(vertexIdx); uint4 tessVertexData = TEXEL_FETCH(textures, @tessVertexTexture, tessVertexTexelCoord, 0); uint contourIDWithFlags = tessVertexData.w; - bool isClosingVertexOfContour = - localVertexID == WEDGE_SIZE && (contourIDWithFlags & FIRST_VERTEX_OF_CONTOUR_FLAG) != 0u; + bool isClosingVertexOfContour = localVertexID == drawParameters.wedgeSize && + (contourIDWithFlags & FIRST_VERTEX_OF_CONTOUR_FLAG) != 0u; if (isClosingVertexOfContour) { // The right vertex crossed over into a new contour. Fetch the previous vertex, which will