From bba64c17960c370cc833805b4f5e9f2f5fbccd1a Mon Sep 17 00:00:00 2001 From: cosmonaut Date: Fri, 15 Dec 2023 09:23:46 -0800 Subject: [PATCH] make text batches use less memory by defualt --- src/Graphics/Font/TextBatch.cs | 28 +++++++++++++++++++++------- 1 file changed, 21 insertions(+), 7 deletions(-) diff --git a/src/Graphics/Font/TextBatch.cs b/src/Graphics/Font/TextBatch.cs index cccbd59..7aef845 100644 --- a/src/Graphics/Font/TextBatch.cs +++ b/src/Graphics/Font/TextBatch.cs @@ -6,9 +6,9 @@ namespace MoonWorks.Graphics.Font { public unsafe class TextBatch : GraphicsResource { - public const int MAX_CHARS = 4096; - public const int MAX_VERTICES = MAX_CHARS * 4; - public const int MAX_INDICES = MAX_CHARS * 6; + public const int INITIAL_CHAR_COUNT = 64; + public const int INITIAL_VERTEX_COUNT = INITIAL_CHAR_COUNT * 4; + public const int INITIAL_INDEX_COUNT = INITIAL_CHAR_COUNT * 6; private GraphicsDevice GraphicsDevice { get; } public IntPtr Handle { get; } @@ -30,10 +30,11 @@ namespace MoonWorks.Graphics.Font StringBytesLength = 128; StringBytes = (byte*) NativeMemory.Alloc((nuint) StringBytesLength); - VertexBuffer = Buffer.Create(GraphicsDevice, BufferUsageFlags.Vertex, MAX_VERTICES); - IndexBuffer = Buffer.Create(GraphicsDevice, BufferUsageFlags.Index, MAX_INDICES); + VertexBuffer = Buffer.Create(GraphicsDevice, BufferUsageFlags.Vertex, INITIAL_VERTEX_COUNT); + IndexBuffer = Buffer.Create(GraphicsDevice, BufferUsageFlags.Index, INITIAL_INDEX_COUNT); } + // Call this to initialize or reset the batch. public void Start(Font font) { Wellspring.Wellspring_StartTextBatch(Handle, font.Handle); @@ -41,6 +42,7 @@ namespace MoonWorks.Graphics.Font PrimitiveCount = 0; } + // Add text with size and color to the batch public unsafe bool Add( string text, int pixelSize, @@ -79,7 +81,7 @@ namespace MoonWorks.Graphics.Font return true; } - // Call this after you have made all the Draw calls you want. + // Call this after you have made all the Add calls you want, but before beginning a render pass. public unsafe void UploadBufferData(CommandBuffer commandBuffer) { Wellspring.Wellspring_GetBufferData( @@ -91,13 +93,25 @@ namespace MoonWorks.Graphics.Font out uint indexDataLengthInBytes ); + if (VertexBuffer.Size < vertexDataLengthInBytes) + { + VertexBuffer.Dispose(); + VertexBuffer = new Buffer(GraphicsDevice, BufferUsageFlags.Vertex, vertexDataLengthInBytes); + } + + if (IndexBuffer.Size < indexDataLengthInBytes) + { + IndexBuffer.Dispose(); + IndexBuffer = new Buffer(GraphicsDevice, BufferUsageFlags.Vertex, vertexDataLengthInBytes); + } + if (vertexDataLengthInBytes > 0 && indexDataLengthInBytes > 0) { commandBuffer.SetBufferData(VertexBuffer, vertexDataPointer, 0, vertexDataLengthInBytes); commandBuffer.SetBufferData(IndexBuffer, indexDataPointer, 0, indexDataLengthInBytes); } - PrimitiveCount = vertexCount / 2; // FIXME: is this jank? + PrimitiveCount = vertexCount / 2; } // Call this AFTER binding your text pipeline!