From c6af33ac9df3ef44f8551a58be2e29bbb13e1780 Mon Sep 17 00:00:00 2001 From: Engineer Date: Thu, 22 Oct 2026 14:49:34 +0800 Subject: [PATCH] fix(2d): allocate Graphics GPU buffers on demand Every Graphics sub-model pre-allocated a 65536-vertex / 131072-index buffer, which is about 2.25 MiB with the 32-byte graphics vertex, while a rect or ellipse mask only needs a few hundred bytes. The cost accumulates with every mask that draws its own geometry. Allocate the buffers from the chunk data when the sub-model is created, grow them by powers of two when the geometry outgrows them, and never shrink, so a dynamic graphic no longer re-creates its GPU buffer every frame. Keep the ceiling at the uint16 addressable limit of 65536 vertices. The assembler does not split a single fill()/stroke() batch, so a batch of exactly 65536 vertices has to fit; capping the buffer at 65535 would upload 32 bytes past its end. UIModelProxy used to resize the buffers to the exact data size on every upload, which re-created them whenever the geometry changed, and on Metal/Vulkan the old buffer stays alive until the GPU is done with it. It now follows the same grow-only policy and passes the valid size to update() explicitly. Refs: cocos/cocos4#371 --- cocos/2d/assembler/graphics/constants.ts | 32 ++++++++++ .../graphics/webgl/graphics-assembler.ts | 8 +-- cocos/2d/components/graphics.ts | 45 ++++++++++++-- native/cocos/2d/renderer/UIModelProxy.cpp | 61 ++++++++++++++----- 4 files changed, 122 insertions(+), 24 deletions(-) create mode 100644 cocos/2d/assembler/graphics/constants.ts diff --git a/cocos/2d/assembler/graphics/constants.ts b/cocos/2d/assembler/graphics/constants.ts new file mode 100644 index 0000000000..776ebbe647 --- /dev/null +++ b/cocos/2d/assembler/graphics/constants.ts @@ -0,0 +1,32 @@ +/* + Copyright (c) 2017-2023 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights to + use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies + of the Software, and to permit persons to whom the Software is furnished to do so, + subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +*/ + +// Vertex/index capacity limits of the graphics geometry. + +// Uint16 can address 65536 vertices (indices 0-65535), and a single fill()/stroke() batch is not +// split, so the buffers have to cover this count. +export const MAX_VERTEX_COUNT = 65536; +// Fill and stroke both emit at most 3 indices per vertex, see GraphicsAssembler. +export const INDICES_PER_VERTEX = 3; +export const MAX_INDEX_COUNT = MAX_VERTEX_COUNT * INDICES_PER_VERTEX; diff --git a/cocos/2d/assembler/graphics/webgl/graphics-assembler.ts b/cocos/2d/assembler/graphics/webgl/graphics-assembler.ts index 024648c21e..5ff3ee5712 100644 --- a/cocos/2d/assembler/graphics/webgl/graphics-assembler.ts +++ b/cocos/2d/assembler/graphics/webgl/graphics-assembler.ts @@ -28,12 +28,10 @@ import { MeshRenderData } from '../../../renderer/render-data'; import { IBatcher } from '../../../renderer/i-batcher'; import { Graphics } from '../../../components/graphics'; import { LineCap, LineJoin, PointFlags } from '../types'; +import { MAX_VERTEX_COUNT, INDICES_PER_VERTEX } from '../constants'; import { earcut as Earcut } from './earcut'; import { Impl, Point } from './impl'; -const MAX_VERTEX = 65535; -const MAX_INDICES = MAX_VERTEX * 2; - const PI = Math.PI; const min = Math.min; const max = Math.max; @@ -95,7 +93,7 @@ export class GraphicsAssembler implements IAssembler { let meshBuffer = renderData; const maxVertexCount = meshBuffer ? meshBuffer.vertexStart + vertexCount : 0; - if (maxVertexCount > MAX_VERTEX || maxVertexCount * 3 > MAX_INDICES) { + if (maxVertexCount > MAX_VERTEX_COUNT) { ++_impl.dataOffset; if (_impl.dataOffset < renderDataList.length) { @@ -109,7 +107,7 @@ export class GraphicsAssembler implements IAssembler { } if (meshBuffer && meshBuffer.vertexCount < maxVertexCount) { - meshBuffer.request(vertexCount, vertexCount * 3); + meshBuffer.request(vertexCount, vertexCount * INDICES_PER_VERTEX); } return renderData; diff --git a/cocos/2d/components/graphics.ts b/cocos/2d/components/graphics.ts index 664a0ccae8..3dbc3f469e 100644 --- a/cocos/2d/components/graphics.ts +++ b/cocos/2d/components/graphics.ts @@ -32,6 +32,7 @@ import { Color, warnID, cclegacy } from '../../core'; import { scene } from '../../render-scene'; import type { IBatcher } from '../renderer/i-batcher'; import { LineCap, LineJoin } from '../assembler/graphics/types'; +import { MAX_VERTEX_COUNT, MAX_INDEX_COUNT } from '../assembler/graphics/constants'; import { Impl } from '../assembler/graphics/webgl/impl'; import { Material, RenderingSubMesh } from '../../asset/assets'; import { Format, PrimitiveMode, Attribute, Device, BufferUsageBit, BufferInfo, MemoryUsageBit, deviceManager } from '../../gfx'; @@ -39,6 +40,8 @@ import { vfmtPosColor, getAttributeStride, getComponentPerVertex } from '../rend import { NativeUIModelProxy } from '../renderer/native-2d'; import { RenderEntity, RenderEntityType } from '../renderer/render-entity'; import type { GraphicsAssembler } from '../assembler/graphics/webgl/graphics-assembler'; +import type { MeshRenderData } from '../renderer/render-data'; +import type { InputAssembler } from '../../gfx'; const attributes = vfmtPosColor.concat([ new Attribute('a_dist', Format.R32F), @@ -48,6 +51,15 @@ const componentPerVertex = getComponentPerVertex(attributes); const stride = getAttributeStride(attributes); +// Grow only, by powers of two, so a changing geometry does not re-create the GPU buffer every frame. +function growCapacity (needed: number, current: number, max: number): number { + let cap = Math.max(current, 1); + while (cap < needed) { + cap *= 2; + } + return Math.min(cap, max); +} + /** * @en * Graphics component. @@ -635,7 +647,7 @@ export class Graphics extends UIRenderer { /** * @deprecated since v3.7.0, this is an engine private interface that will be removed in the future. */ - public activeSubModel (idx: number): void { + public activeSubModel (idx: number, vertexCount = 1, indexCount = 1): void { if (!this.model) { warnID(4500, this.node.name); return; @@ -646,13 +658,13 @@ export class Graphics extends UIRenderer { const vertexBuffer = gfxDevice.createBuffer(new BufferInfo( BufferUsageBit.VERTEX | BufferUsageBit.TRANSFER_DST, MemoryUsageBit.DEVICE, - 65536 * stride, // Uint16 can address 65536 vertices (indices 0–65535) + growCapacity(vertexCount, 0, MAX_VERTEX_COUNT) * stride, stride, )); const indexBuffer = gfxDevice.createBuffer(new BufferInfo( BufferUsageBit.INDEX | BufferUsageBit.TRANSFER_DST, MemoryUsageBit.DEVICE, - 65536 * Uint16Array.BYTES_PER_ELEMENT * 2, // Uint16 can address 65536 vertices (indices 0–65535) + growCapacity(indexCount, 0, MAX_INDEX_COUNT) * Uint16Array.BYTES_PER_ELEMENT, Uint16Array.BYTES_PER_ELEMENT, )); @@ -683,6 +695,9 @@ export class Graphics extends UIRenderer { continue; } + // Buffer.update() does not grow the buffer on WebGL, reserve the capacity first. + this._ensureCapacity(renderData, ia); + const vb = new Float32Array(renderData.vData.buffer, 0, renderData.vertexStart * componentPerVertex); ia.vertexBuffers[0].update(vb); ia.vertexCount = renderData.vertexStart; @@ -696,6 +711,27 @@ export class Graphics extends UIRenderer { this._isNeedUploadData = false; } + /** + * Grow only, never shrink: the capacity is reused after clear(). + */ + private _ensureCapacity (renderData: MeshRenderData, ia: InputAssembler): void { + const vb = ia.vertexBuffers[0]; + const vbStride = vb.stride; + if (renderData.vertexStart * vbStride > vb.size) { + const count = growCapacity(renderData.vertexStart, vb.size / vbStride, MAX_VERTEX_COUNT); + vb.resize(count * vbStride); + } + + const ib = ia.indexBuffer; + if (!ib) { + return; + } + if (renderData.indexStart * Uint16Array.BYTES_PER_ELEMENT > ib.size) { + const count = growCapacity(renderData.indexStart, ib.size / Uint16Array.BYTES_PER_ELEMENT, MAX_INDEX_COUNT); + ib.resize(count * Uint16Array.BYTES_PER_ELEMENT); + } + } + protected _render (render: IBatcher): void { if (this._isNeedUploadData) { if (this.impl) { @@ -703,7 +739,8 @@ export class Graphics extends UIRenderer { const len = this.model!.subModels.length; if (renderDataList.length > len) { for (let i = len; i < renderDataList.length; i++) { - this.activeSubModel(i); + const renderData = renderDataList[i]; + this.activeSubModel(i, renderData.vertexStart, renderData.indexStart); } } } diff --git a/native/cocos/2d/renderer/UIModelProxy.cpp b/native/cocos/2d/renderer/UIModelProxy.cpp index e7c57f8d0c..6fb81cd912 100644 --- a/native/cocos/2d/renderer/UIModelProxy.cpp +++ b/native/cocos/2d/renderer/UIModelProxy.cpp @@ -27,6 +27,25 @@ #include "core/assets/RenderingSubMesh.h" namespace cc { + +namespace { + +// GPU buffers are allocated on demand, in vertex/index counts, keep in sync with +// cocos/2d/assembler/graphics/constants.ts. Grow only: doResize re-creates the GPU buffer. +constexpr uint32_t MAX_VERTEX_COUNT = 65536; +constexpr uint32_t INDICES_PER_VERTEX = 3; +constexpr uint32_t MAX_INDEX_COUNT = MAX_VERTEX_COUNT * INDICES_PER_VERTEX; + +inline uint32_t growCapacity(uint32_t needed, uint32_t current, uint32_t maxCap) { + uint32_t cap = current > 1U ? current : 1U; + while (cap < needed) { + cap *= 2; + } + return cap < maxCap ? cap : maxCap; +} + +} // namespace + UIModelProxy::UIModelProxy() { _device = Root::getInstance()->getDevice(); } @@ -55,16 +74,20 @@ void UIModelProxy::activeSubModels() { return; } + // Allocate exactly for the data of this chunk, rounded up to a power of two. + const uint32_t vertexCapacity = growCapacity(drawInfo->getVertexOffset(), 0, MAX_VERTEX_COUNT); + const uint32_t indexCapacity = growCapacity(drawInfo->getIndexOffset(), 0, MAX_INDEX_COUNT); + auto* vertexBuffer = _device->createBuffer({ gfx::BufferUsageBit::VERTEX | gfx::BufferUsageBit::TRANSFER_DST, gfx::MemoryUsageBit::DEVICE, - 65536 * _stride, // Uint16 can address 65536 vertices (indices 0–65535) + vertexCapacity * _stride, _stride, }); auto* indexBuffer = _device->createBuffer({ gfx::BufferUsageBit::INDEX | gfx::BufferUsageBit::TRANSFER_DST, gfx::MemoryUsageBit::DEVICE, - 65536 * sizeof(uint16_t) * 2, // Uint16 can address 65536 vertices (indices 0–65535) + static_cast(indexCapacity * sizeof(uint16_t)), sizeof(uint16_t), }); gfx::BufferList vbReference; @@ -87,24 +110,32 @@ void UIModelProxy::uploadData() { for (size_t i = 0; i < drawInfos.size(); i++) { auto* drawInfo = drawInfos[i]; auto* ia = subModelList.at(i)->getInputAssembler(); - if (drawInfo->getVertexOffset() <= 0 || drawInfo->getIndexOffset() <= 0) continue; + const uint32_t vertexCount = drawInfo->getVertexOffset(); + const uint32_t indexCount = drawInfo->getIndexOffset(); + if (vertexCount == 0 || indexCount == 0) continue; + gfx::BufferList vBuffers = ia->getVertexBuffers(); if (!vBuffers.empty()) { - auto size = drawInfo->getVertexOffset() * _stride; - // if (size > vBuffers[0]->getSize()) { - vBuffers[0]->resize(size); - // } - vBuffers[0]->update(drawInfo->getVDataBuffer()); // vdata + gfx::Buffer* vBuffer = vBuffers[0]; + const uint32_t neededVBytes = vertexCount * _stride; + if (neededVBytes > vBuffer->getSize()) { + const uint32_t capacity = growCapacity(vertexCount, vBuffer->getSize() / _stride, MAX_VERTEX_COUNT); + vBuffer->resize(capacity * _stride); + } + // pass the valid size explicitly, update(ptr) uploads the whole capacity + vBuffer->update(drawInfo->getVDataBuffer(), neededVBytes); // vdata } - ia->setVertexCount(drawInfo->getVertexOffset()); // count + ia->setVertexCount(vertexCount); // count gfx::Buffer* iBuffer = ia->getIndexBuffer(); - auto size = drawInfo->getIndexOffset() * 2; - // if (size > iBuffer->getSize()) { - iBuffer->resize(size); - // } - iBuffer->update(drawInfo->getIDataBuffer()); // idata - ia->setIndexCount(drawInfo->getIndexOffset()); // indexCount + const auto neededIBytes = static_cast(indexCount * sizeof(uint16_t)); + if (neededIBytes > iBuffer->getSize()) { + const uint32_t capacity = growCapacity(indexCount, static_cast(iBuffer->getSize() / sizeof(uint16_t)), + MAX_INDEX_COUNT); + iBuffer->resize(static_cast(capacity * sizeof(uint16_t))); + } + iBuffer->update(drawInfo->getIDataBuffer(), neededIBytes); // idata + ia->setIndexCount(indexCount); // indexCount // drawInfo->setModel(_model); // hack, render by model }