From 10deb9cea450704cfbddb38f14b213647fd7ddc6 Mon Sep 17 00:00:00 2001 From: Eurya0x13 Date: Thu, 26 Nov 2026 14:10:37 +0800 Subject: [PATCH 1/9] [Perf] (MG_Backend/DirectGLES): batch sparse texture uploads on Mali - Pack dirty rectangles across mip levels into a shared staging texture. - Keep a bounded fallback when mapped unpack space is busy. - https://bugzilla.mozilla.org/show_bug.cgi?id=1661528 - https://searchfox.org/firefox-main/source/gfx/wr/webrender/src/renderer/upload.rs#474 --- MobileGL/MG_Backend/DirectGLES/Managers.h | 12 +- .../MG_Backend/DirectGLES/ManagersBuffers.cpp | 24 +- .../MG_Backend/DirectGLES/ManagersInternal.h | 4 + .../DirectGLES/ManagersTextureSync.cpp | 277 ++++++++++++++++-- .../DirectGLES/PackedTextureUpload.h | 147 ++++++++++ .../DirectGLES/TextureUploadBoxes.h | 68 +++++ 6 files changed, 489 insertions(+), 43 deletions(-) create mode 100644 MobileGL/MG_Backend/DirectGLES/PackedTextureUpload.h create mode 100644 MobileGL/MG_Backend/DirectGLES/TextureUploadBoxes.h diff --git a/MobileGL/MG_Backend/DirectGLES/Managers.h b/MobileGL/MG_Backend/DirectGLES/Managers.h index b36b3121..9037ce9e 100644 --- a/MobileGL/MG_Backend/DirectGLES/Managers.h +++ b/MobileGL/MG_Backend/DirectGLES/Managers.h @@ -1878,15 +1878,11 @@ namespace MobileGL::MG_Backend::DirectGLES { Uint64 m_sharedImageId = 0; SharedImageImpl::EglImageRef m_sharedImage; #endif - // Whether the driver texture may hold texels the shadow never saw. Set the first time - // anything other than a texel upload can write it - an application framebuffer - // attachment, a writable image binding, a copy or blit into it, a driver-side mipmap - // generation - and never cleared. Until then the driver holds, outside a level's - // pending writes, exactly the shadow bytes it was last sent, so those writes may go up - // as their union box (one unpack-ring job, which is what Mali needs); from then on - // only the texels the client wrote may go up, since the shadow is stale everywhere - // else. See SyncMipmapsToBackend. + // Once a framebuffer, image binding, copy, or mipmap generation may write this texture, + // the CPU shadow can be stale. Upload only the texels the client wrote from then on. Bool m_driverMayHoldGpuWrites = false; + // Retry the packed path when the texture's storage changes. + Bool m_packedUploadRejected = false; // Latches the "this driver has no buffer textures" report to once per texture. The // report is emitted from the respecify path, which bails before recording the state // it was asked to apply - so without the latch the texture stays permanently dirty diff --git a/MobileGL/MG_Backend/DirectGLES/ManagersBuffers.cpp b/MobileGL/MG_Backend/DirectGLES/ManagersBuffers.cpp index 0be68182..2bb2f9c1 100644 --- a/MobileGL/MG_Backend/DirectGLES/ManagersBuffers.cpp +++ b/MobileGL/MG_Backend/DirectGLES/ManagersBuffers.cpp @@ -2741,16 +2741,9 @@ namespace MobileGL::MG_Backend::DirectGLES { } } // namespace - // Bump-allocate `size` bytes out of `ring`. - // - // Fast path: a live store under the current context with room before both - // the wrap boundary and the in-flight tail. Touches no GL and probes no - // frame marks - callers sit behind the ring's availability gate, so the - // context checks have already run for this draw/upload. `tail` may be stale - // here (marks are only retired on Present and on the slow path); staleness - // is conservative - the in-flight span reads too large, the check fails, - // and the slow path retires marks and re-tries. - Bool RingAllocate(PersistentRing& ring, SizeT size, SizeT& outOffset) { + // Allocate within the mapped ring without GL calls or polling fences. A stale tail + // accounts for extra bytes in flight, so it can only make this check more conservative. + static Bool TryAllocateMappedRing(PersistentRing& ring, SizeT size, SizeT& outOffset) { if (size == 0) return false; auto& store = ring.store; if (store.id != 0 && store.contextGeneration == g_bufferContextGeneration) { @@ -2770,7 +2763,12 @@ namespace MobileGL::MG_Backend::DirectGLES { return true; } } - return RingAllocateSlow(ring, size, outOffset); + return false; + } + + Bool RingAllocate(PersistentRing& ring, SizeT size, SizeT& outOffset) { + return TryAllocateMappedRing(ring, size, outOffset) || + (size != 0 && RingAllocateSlow(ring, size, outOffset)); } Bool RingAllocateSlow(PersistentRing& ring, SizeT size, SizeT& outOffset) { @@ -2969,6 +2967,10 @@ namespace MobileGL::MG_Backend::DirectGLES { return RingAllocate(UnpackRing(), size, outOffset); } + Bool TryAllocateMappedUnpackRing(SizeT size, SizeT& outOffset) { + return size <= kUnpackRingMaxBytes && TryAllocateMappedRing(UnpackRing(), size, outOffset); + } + void* UnpackRingMappedPtr() { return UnpackRing().store.mappedPtr; } diff --git a/MobileGL/MG_Backend/DirectGLES/ManagersInternal.h b/MobileGL/MG_Backend/DirectGLES/ManagersInternal.h index c6df6820..74bedb8a 100644 --- a/MobileGL/MG_Backend/DirectGLES/ManagersInternal.h +++ b/MobileGL/MG_Backend/DirectGLES/ManagersInternal.h @@ -382,6 +382,10 @@ namespace MobileGL::MG_Backend::DirectGLES { Bool UnpackRingAllocate(SizeT size, SizeT& outOffset); + // Only use space in the current mapping. Optional uploads can fall back + // immediately when the ring would have to grow or wait. + Bool TryAllocateMappedUnpackRing(SizeT size, SizeT& outOffset); + void* UnpackRingMappedPtr(); Uint UnpackRingBufferId(); diff --git a/MobileGL/MG_Backend/DirectGLES/ManagersTextureSync.cpp b/MobileGL/MG_Backend/DirectGLES/ManagersTextureSync.cpp index 057a75b3..26842f69 100644 --- a/MobileGL/MG_Backend/DirectGLES/ManagersTextureSync.cpp +++ b/MobileGL/MG_Backend/DirectGLES/ManagersTextureSync.cpp @@ -7,6 +7,9 @@ // End of Source File Header #include "ManagersInternal.h" +#include "DirectGLESInternal.h" +#include "PackedTextureUpload.h" +#include "TextureUploadBoxes.h" namespace MobileGL::MG_Backend::DirectGLES { namespace TextureImpl { @@ -97,6 +100,148 @@ namespace MobileGL::MG_Backend::DirectGLES { return reinterpret_cast(static_cast(offset)); } + namespace { + static Bool SplitMipUpload(const MG_Pipe::MGPipeResourceRecord::PendingUpload& pending, + const IntVec3& levelSize, MG_State::GLState::MipmapDirtyRegion* boxes) { + using namespace TextureUploadBoxes; + const auto& bounds = pending.UnionBox; + if (bounds.X < 0 || bounds.Y < 0 || bounds.Z != 0 || bounds.D != 1 || bounds.X >= levelSize.x() || + bounds.Y >= levelSize.y() || bounds.W > static_cast(levelSize.x() - bounds.X) || + bounds.H > static_cast(levelSize.y() - bounds.Y)) { + return false; + } + const Box unionBox{bounds.X, bounds.Y, bounds.X + static_cast(bounds.W), + bounds.Y + static_cast(bounds.H)}; + if (!WorthSearching(unionBox, pending.Regions.size())) return false; + std::array regions; + for (SizeT i = 0; i < pending.Regions.size(); ++i) { + const auto& region = pending.Regions[i]; + if (region.X < unionBox.left || region.X >= unionBox.right || region.Y < unionBox.top || + region.Y >= unionBox.bottom || region.Z != 0 || region.D != 1 || region.W == 0 || + region.H == 0 || region.W > static_cast(unionBox.right - region.X) || + region.H > static_cast(unionBox.bottom - region.Y)) { + return false; + } + regions[i] = {region.X, region.Y, region.X + static_cast(region.W), + region.Y + static_cast(region.H)}; + } + const auto split = Split(unionBox, regions, pending.Regions.size()); + if (!split) return false; + for (SizeT i = 0; i < split->size(); ++i) { + const auto& box = (*split)[i]; + boxes[i] = {IntVec3{box.left, box.top, 0}, IntVec3{box.right, box.bottom, 1}}; + } + return true; + } + + struct PackedUploadPage { + GLuint texture = 0; + Uint generation = 0; + Uint64 context = 0; + Uint64 retireSerial = 0; + }; + + // The names live in the share group, while reuse is restricted to the + // EGL context that submitted the copies. Any retired context's page + // can be deleted the next time a shared context acquires its slot. + struct PackedUploadPages final : PerNativeContextBase { + std::mutex mutex; + std::array pages; + + void ForgetContext(Uint64 context) override { + const std::lock_guard lock(mutex); + for (auto& page : pages) { + if (page.context == context) page.context = 0; + } + } + + PackedUploadPage* FindIdle(Uint64 context) { + const Uint64 completed = CompletedFrameSerial(); + PackedUploadPage* vacant = nullptr; + for (auto& page : pages) { + if (page.generation != g_backendContextGeneration) page = {}; + if (page.context == context && page.retireSerial <= completed) return &page; + if (page.context == 0 && vacant == nullptr) vacant = &page; + } + return vacant; + } + }; + + enum class PackedUploadResult { + Unavailable, + Rejected, + Committed + }; + + static PackedUploadResult SubmitPackedUpload(const PackedTextureUpload::Batch& batch, GLuint destination, + Uint64 unionTexels) { + const Uint64 context = CurrentNativeContextSerial(); + if (context == 0) return PackedUploadResult::Unavailable; + static PackedUploadPages pool; + const std::unique_lock lock(pool.mutex, std::try_to_lock); + if (!lock.owns_lock()) return PackedUploadResult::Unavailable; + auto* page = pool.FindIdle(context); + if (page == nullptr) return PackedUploadResult::Unavailable; + + SizeT offset = 0; + if (!BufferImpl::TryAllocateMappedUnpackRing(batch.ByteSize(), offset)) { + return PackedUploadResult::Unavailable; + } + auto* mapping = static_cast(BufferImpl::UnpackRingMappedPtr()); + PackedTextureUpload::WritePage(batch, mapping + offset); + + DrainDriverErrors("packed texture upload"); + if (page->context != context) { + if (page->texture != 0) g_GLESFuncs.glDeleteTextures(1, &page->texture); + *page = {0, g_backendContextGeneration, context, 0}; + g_GLESFuncs.glGenTextures(1, &page->texture); + if (page->texture == 0) { + *page = {}; + return PackedUploadResult::Rejected; + } + g_GLESFuncs.glBindTexture(GL_TEXTURE_2D, page->texture); + g_GLESFuncs.glTexStorage2D(GL_TEXTURE_2D, 1, GL_RGBA8, PackedTextureUpload::PageSide, + PackedTextureUpload::PageSide); + g_GLESFuncs.glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); + g_GLESFuncs.glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); + if (g_GLESFuncs.glGetError() != GL_NO_ERROR) { + g_GLESFuncs.glBindTexture(GL_TEXTURE_2D, destination); + g_GLESFuncs.glDeleteTextures(1, &page->texture); + *page = {}; + return PackedUploadResult::Rejected; + } + } else { + g_GLESFuncs.glBindTexture(GL_TEXTURE_2D, page->texture); + } + + // SyncMipmapsToBackend has the destination bound on the temp unit. + // Restore that raw binding before returning to the cached GL state. + BufferImpl::BindPixelUnpackBufferId(BufferImpl::UnpackRingBufferId()); + g_GLESFuncs.glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, batch.width, batch.height, GL_RGBA, + GL_UNSIGNED_BYTE, UnpackRingPixelOffset(offset)); + BufferImpl::BindPixelUnpackBufferId(0); + g_GLESFuncs.glBindTexture(GL_TEXTURE_2D, destination); + page->retireSerial = CurrentFrameSerial() + 1; + if (g_GLESFuncs.glGetError() != GL_NO_ERROR) return PackedUploadResult::Rejected; + if (MG_Util::PipeStats::Enabled()) { + MG_Util::PipeStats::AddBytes(MG_Util::PipeStats::ByteClass::StageTexture, batch.ByteSize()); + } + + for (SizeT i = 0; i < batch.count; ++i) { + const auto& region = batch.regions[i]; + const auto& source = batch.offsets[i]; + g_GLESFuncs.glCopyImageSubData(page->texture, GL_TEXTURE_2D, 0, source.x, source.y, 0, destination, + GL_TEXTURE_2D, region.level, region.x, region.y, 0, region.width, + region.height, 1); + } + if (g_GLESFuncs.glGetError() != GL_NO_ERROR) return PackedUploadResult::Rejected; + MGLOG_I_ONCE("Packed texture upload: %zu regions, %zu packed bytes, %llu bounding-box bytes", + batch.count, batch.ByteSize(), + static_cast(unionTexels * PackedTextureUpload::BytesPerTexel)); + return PackedUploadResult::Committed; + } + } // namespace + static Uint GetNormFallbackComponentCount(TextureInternalFormat format) { switch (format) { case TextureInternalFormat::R8Snorm: @@ -755,6 +900,67 @@ namespace MobileGL::MG_Backend::DirectGLES { (pushedStorage != nullptr ? static_cast(pushedStorage->Desc.StorageKind) \ : (obj)->GetStorageType()) + static PackedUploadResult TryPackedMipUpload(MG_State::GLState::TextureObjectMipmap* textureMipmapObject, + const MG_Pipe::MGPipeResourceRecord* pushedStorage, + MG_Pipe::MGPipeHandle pushedRes, TextureUploadTarget uploadTarget, + SizeT mipmapCount, GLuint destination) { + using namespace PackedTextureUpload; + Batch batch; + Uint64 unionTexels = 0; + const auto targetCode = static_cast(uploadTarget); + for (SizeT level = 0; level < mipmapCount; ++level) { + const auto levelCode = static_cast(level); + const auto* pending = FindPipeTextureUpload(*pushedStorage, targetCode, levelCode); + if (pending == nullptr) continue; + if (pending->Regions.empty() || pending->Regions.size() > MaxRegions - batch.count) { + return PackedUploadResult::Unavailable; + } + const auto size = MGB_LEVEL_TEXEL_SIZE(textureMipmapObject, uploadTarget, level); + if (size.x() <= 0 || size.y() <= 0 || size.z() > 1 || + MGB_LEVEL_BYTE_SIZE(textureMipmapObject, uploadTarget, level) != + static_cast(size.x()) * size.y() * BytesPerTexel) { + return PackedUploadResult::Unavailable; + } + if (MGB_STAGED_TEXTURE_LIVE && + !MG_Record::ServerStagedTexture().IsCovered(MG_Record::StagedTextureStore::KeyForHandle(pushedRes), + targetCode, levelCode)) { + return PackedUploadResult::Unavailable; + } + const auto* pixels = static_cast( + MGB_LEVEL_TEXELS(textureMipmapObject, uploadTarget, level, "packed-dirty-level")); + if (pixels == nullptr) return PackedUploadResult::Unavailable; + const SizeT pitch = static_cast(size.x()) * BytesPerTexel; + for (const auto& region : pending->Regions) { + if (region.Z != 0 || region.D != 1 || region.W == 0 || region.H == 0 || region.W > PageSide || + region.H > PageSide || region.X < 0 || region.Y < 0 || region.X >= size.x() || + region.Y >= size.y() || region.W > static_cast(size.x() - region.X) || + region.H > static_cast(size.y() - region.Y)) { + return PackedUploadResult::Unavailable; + } + // Read the final shadow using level coordinates. Carried offsets can address smaller slabs. + batch.regions[batch.count++] = {pixels + region.Y * pitch + region.X * BytesPerTexel, + pitch, + static_cast(level), + region.X, + region.Y, + static_cast(region.W), + static_cast(region.H)}; + } + unionTexels += static_cast(pending->UnionBox.W) * pending->UnionBox.H; + } + + if (!Pack(batch, unionTexels)) return PackedUploadResult::Unavailable; + const auto result = SubmitPackedUpload(batch, destination, unionTexels); + if (result == PackedUploadResult::Committed) { + for (SizeT level = 0; level < mipmapCount; ++level) { + if (FindPipeTextureUpload(*pushedStorage, targetCode, static_cast(level)) != nullptr) { + MGB_LEVEL_UPLOAD_DONE(textureMipmapObject, uploadTarget, level); + } + } + } + return result; + } + void BackendTextureObject::SyncMipmapsToBackend( const SharedPtr& stateTextureObject) { // P5e (tx2): null IS the by-handle arm once a handle has been noted on this twin; @@ -1038,7 +1244,9 @@ namespace MobileGL::MG_Backend::DirectGLES { const auto mipmapCount = MGB_STORAGE_LEVELS(textureMipmapObject); currentTextureInfo.mipmapLevels = mipmapCount; - Bool needsRegeneration = !m_isInitialized || (currentTextureInfo != m_prevTextureInfo); + const Bool stableStorage = m_isInitialized && currentTextureInfo == m_prevTextureInfo; + Bool needsRegeneration = !stableStorage; + if (needsRegeneration) m_packedUploadRejected = false; if (needsRegeneration && m_backendStorageImmutable) { RecreateBackendTexture(); Bind(target); @@ -1439,6 +1647,24 @@ namespace MobileGL::MG_Backend::DirectGLES { ApplyImageBindableStorageWidening(imageWidening, &glInternalFormat, &glFormat, &glType); const auto& uploadTargets = MGB_UPLOAD_TARGETS(textureMipmapObject); ScopedDefaultUnpackState unpackState; + // Pack the small writes across all dirty mip levels before their + // per-level union boxes can pull in untouched atlas texels. + if (stableStorage && !m_driverMayHoldGpuWrites && !m_packedUploadRejected && + !m_imageBindableStorageRequired && target == GL_TEXTURE_2D && + (glInternalFormat == GL_RGBA8 || glInternalFormat == GL_RGBA) && glFormat == GL_RGBA && + glType == GL_UNSIGNED_BYTE && pushedStorage != nullptr && uploadTargets.size() == 1 && + g_GLESFuncs.glCopyImageSubData && g_GLESFuncs.glTexStorage2D && + g_GLESCapabilities.GLESRendererString.find("Mali") != String::npos && + BufferImpl::UnpackRingAvailable()) { + const auto result = TryPackedMipUpload(textureMipmapObject, pushedStorage, pushedRes, + uploadTargets.front(), mipmapCount, m_backendTextureId); + if (result == PackedUploadResult::Rejected) { + // Replay all regions from the shadow after a rejected copy. + DrainDriverErrors("packed texture upload fallback"); + m_packedUploadRejected = true; + MGLOG_D("Packed texture upload rejected for texture %u", m_backendTextureId); + } + } // Per-level scratch of the exact-footprint path, hoisted to reuse capacity. Vector dirtyFootprint; Vector stagingBlockOverflow; @@ -1707,7 +1933,8 @@ namespace MobileGL::MG_Backend::DirectGLES { MG_State::GLState::MipmapDirtyRegion dirtyRects[MG_State::GLState::MipmapStorage::kMaxDirtyRects]; SizeT dirtyRectCount = 0; - if (subRectEligible) { + const Bool ringUsable = BufferImpl::UnpackRingAvailable(); + if (subRectEligible && !ringUsable) { if (pendingUpload != nullptr) { // RegionCount == 0 is LEGAL and means "the union box is the // whole story" (D-D3), which is the same statement the @@ -1751,16 +1978,23 @@ namespace MobileGL::MG_Backend::DirectGLES { dirtyRectCount = textureMipmapObject->GetStorageDirtyRects( uploadTarget, level, dirtyRects, MG_State::GLState::MipmapStorage::kMaxDirtyRects); - // The scatter refinement pays only on the client-pointer path, - // where fewer bytes mean less driver-side copying. Through the - // unpack ring every glTexSubImage is a GPU copy job (Mali), so - // ~100 sprite rects become ~100 jobs whose fixed cost dwarfs - // the union box's extra bytes - measured +6 ms/frame of GPU - // time in MC's animated-atlas ticks. One box, one job. - if (BufferImpl::UnpackRingAvailable()) { - dirtyRectCount = 0; - } } + // Bound the unpack-ring fallback to two jobs per level. The + // boxes may include gaps, so require an authoritative CPU shadow. + const Bool splitBoxUpload = + ringUsable && regionsAddressable && stableStorage && !m_driverMayHoldGpuWrites && + !m_imageBindableStorageRequired && target == GL_TEXTURE_2D && + (glInternalFormat == GL_RGBA8 || glInternalFormat == GL_RGBA) && glFormat == GL_RGBA && + glType == GL_UNSIGNED_BYTE && bpp == 4 && texelSize.z() == 1 && mipData != nullptr && + uploadData == mipData && levelRowBytes == static_cast(texelSize.x()) * bpp && + levelSliceBytes == static_cast(texelSize.y()) * levelRowBytes && + pendingUpload != nullptr && + (!MGB_STAGED_TEXTURE_LIVE || + MG_Record::ServerStagedTexture().IsCovered( + MG_Record::StagedTextureStore::KeyForHandle(pushedRes), + static_cast(uploadTarget), static_cast(level))) && + SplitMipUpload(*pendingUpload, texelSize, dirtyRects); + if (splitBoxUpload) dirtyRectCount = 2; // Everything above - the union box, the ring's one-box rule, the rect // list with its merges, fold and 3/4 cut-off - may upload shadow texels // the client did not write, which is only harmless while the driver @@ -1816,19 +2050,15 @@ namespace MobileGL::MG_Backend::DirectGLES { // is the level shadow itself and never a conversion buffer: since dev's 8966d5c2 a converted // level is sub-rect eligible too, and its rects are cut at the conversion's bpp (rectUploadPtr). // -// THREE USE SITES, AND THE FIRST OF THEM IS UNREACHABLE (N-5's second half, and the correction -// to what esprytobj-v2.md m-1 claimed): dirtyRectCount is forced to 0 whenever -// UnpackRingAvailable(), and the staging-block loop that takes MGB_RECT_SRC_PTR(r, rect) first -// requires `ringUsable && dirtyRectCount >= 2`. The two conditions cannot both hold. That shape -// is pre-existing (the ring/scatter decision, not this package's), so the loop is left as it -// stands and the count is corrected here instead of the loop being deleted underneath it. +// A pair of bounding boxes need not start at the corresponding recorded region's origin. +// Read those boxes by coordinate, including when ring staging falls back to a client pointer. // // A MACRO AND NOT A SECOND LAMBDA, for DV-9's measured reason: this function's nine ErrorLopper // lambdas are mangled ...::$_N BY POSITION, so one more renumbers every one of them and moves // the PULL build's symbol set, whose admitted-change set is EMPTY. The pull expansion is the // pre-P4a call with one pair of parentheses. #undef'd with the rest. #define MGB_RECT_SRC_PTR(idx, rect) \ - ((pendingUpload != nullptr && pendingOffsetsAgree && carriedLayoutApplies && \ + ((!splitBoxUpload && pendingUpload != nullptr && pendingOffsetsAgree && carriedLayoutApplies && \ static_cast(idx) < pendingUpload->Regions.size()) \ ? static_cast(uploadData) + \ static_cast(pendingUpload->Regions[static_cast(idx)].SrcOffset) \ @@ -1864,7 +2094,6 @@ namespace MobileGL::MG_Backend::DirectGLES { UnpackStagingBlock stagingBlockArray[MG_State::GLState::MipmapStorage::kMaxDirtyRects]; UnpackStagingBlock* stagingBlocks = stagingBlockArray; SizeT stagingBlockCount = 0; - const Bool ringUsable = BufferImpl::UnpackRingAvailable(); if (!ringUsable) { // Nothing to plan: every branch below keeps the client // pointer and its ROW_LENGTH striding, unchanged. @@ -1925,11 +2154,11 @@ namespace MobileGL::MG_Backend::DirectGLES { // separately from the bytes on purpose: SSIM is blind to it // and the +6 ms/frame Mali cliff was a shape regression, not // a byte regression (plan section 7.3). - const Bool rectShape = subRectEligible && dirtyRectCount >= 2; + const Bool rectShape = perRectUpload; Uint64 shippedBytes = 0; if (rectShape) { - for (SizeT r = 0; r < dirtyRectCount; ++r) { - const auto& rect = dirtyRects[r]; + for (SizeT r = 0; r < uploadRectCount; ++r) { + const auto& rect = uploadRects[r]; shippedBytes += static_cast(rect.hi.x() - rect.lo.x()) * static_cast(rect.hi.y() - rect.lo.y()) * static_cast(std::max(rect.hi.z() - rect.lo.z(), 1)) * @@ -1940,7 +2169,7 @@ namespace MobileGL::MG_Backend::DirectGLES { static_cast(regionSize.x()) * static_cast(regionSize.y()) * static_cast(std::max(regionSize.z(), 1)) * static_cast(bpp); } else { - shippedBytes = static_cast(byteSize); + shippedBytes = static_cast(uploadBytes == 0 ? byteSize : uploadBytes); } MG_Util::PipeStats::AddBytes(MG_Util::PipeStats::ByteClass::StageTexture, shippedBytes); MG_Util::PipeStats::AddCalls(MG_Util::PipeStats::CallClass::TextureUploadEmissions, 1); @@ -1949,7 +2178,7 @@ namespace MobileGL::MG_Backend::DirectGLES { : MG_Util::PipeStats::CallClass::TextureUploadBoxEmissions, 1); MG_Util::PipeStats::AddCalls(MG_Util::PipeStats::CallClass::TextureUploadJobs, - rectShape ? static_cast(dirtyRectCount) : 1u); + rectShape ? static_cast(uploadRectCount) : 1u); } switch (MapToBackendTextureTarget(MGB_TEXTURE_TARGET(stateTextureObject))) { case TextureTarget::Texture2D: diff --git a/MobileGL/MG_Backend/DirectGLES/PackedTextureUpload.h b/MobileGL/MG_Backend/DirectGLES/PackedTextureUpload.h new file mode 100644 index 00000000..b2b19c25 --- /dev/null +++ b/MobileGL/MG_Backend/DirectGLES/PackedTextureUpload.h @@ -0,0 +1,147 @@ +// MobileGL - MobileGL/MG_Backend/DirectGLES/PackedTextureUpload.h +// Copyright (c) 2025-2026 MobileGL-Dev +// Licensed under the GNU Lesser General Public License v3.0: +// https://www.gnu.org/licenses/gpl-3.0.txt +// https://www.gnu.org/licenses/lgpl-3.0.txt +// SPDX-License-Identifier: LGPL-3.0-only +// End of Source File Header + +#pragma once + +#include +#include +#include +#include +#include + +namespace MobileGL::MG_Backend::DirectGLES::TextureImpl::PackedTextureUpload { + // A small RGBA8 page bounds both temporary storage and the packing search. + constexpr int PageSide = 128; + constexpr std::size_t MaxRegions = 32; + constexpr std::size_t BytesPerTexel = 4; + + struct Region { + const std::uint8_t* source; + std::size_t sourcePitch; + int level, x, y, width, height; + }; + + struct Point { + int x, y; + }; + + struct Batch { + std::array regions; + std::array offsets; + std::size_t count = 0; + int width = 0; + int height = 0; + + std::size_t ByteSize() const { return BytesPerTexel * width * height; } + }; + + namespace Detail { + struct Rect { + int x, y, width, height; + int Area() const { return width * height; } + }; + + // Best-area-fit guillotine packing. Splitting on the shorter remainder + // leaves the larger free rectangle available for the next sprite. + inline bool TryWidth(const Batch& batch, int width, Batch& result) { + std::array free; + std::size_t freeCount = 1; + free[0] = {0, 0, width, PageSide}; + int usedWidth = 0, usedHeight = 0; + + for (std::size_t i = 0; i < batch.count; ++i) { + const Region& region = batch.regions[i]; + std::size_t best = freeCount; + for (std::size_t j = 0; j < freeCount; ++j) { + const Rect& rect = free[j]; + if (region.width <= rect.width && region.height <= rect.height && + (best == freeCount || rect.Area() < free[best].Area())) { + best = j; + } + } + if (best == freeCount) return false; + + const Rect rect = free[best]; + free[best] = free[--freeCount]; + result.offsets[i] = {rect.x, rect.y}; + usedWidth = std::max(usedWidth, rect.x + region.width); + usedHeight = std::max(usedHeight, rect.y + region.height); + + const int right = rect.width - region.width; + const int below = rect.height - region.height; + if (right > 0) { + free[freeCount++] = {rect.x + region.width, rect.y, right, + right <= below ? region.height : rect.height}; + } + if (below > 0) { + free[freeCount++] = {rect.x, rect.y + region.height, right <= below ? rect.width : region.width, + below}; + } + } + + result.width = usedWidth; + result.height = usedHeight; + return true; + } + } // namespace Detail + + inline bool Pack(Batch& batch, std::uint64_t unionTexels) { + batch.width = 0; + batch.height = 0; + if (batch.count < 2 || batch.count > batch.regions.size()) return false; + // Require a full page of traffic savings before taking on extra GPU copy + // commands. Dense or single-region uploads already cost little. + constexpr int PageTexels = PageSide * PageSide; + if (unionTexels <= PageTexels) return false; + + int widest = 1, dirtyTexels = 0; + for (std::size_t i = 0; i < batch.count; ++i) { + const Region& region = batch.regions[i]; + if (region.source == nullptr || region.width <= 0 || region.width > PageSide || region.height <= 0 || + region.height > PageSide) { + return false; + } + widest = std::max(widest, region.width); + dirtyTexels += region.width * region.height; + } + if (dirtyTexels > PageTexels) return false; + + std::sort(batch.regions.begin(), batch.regions.begin() + batch.count, [](const Region& a, const Region& b) { + const int aArea = a.width * a.height; + const int bArea = b.width * b.height; + if (aArea != bArea) return aArea > bArea; + return std::max(a.width, a.height) > std::max(b.width, b.height); + }); + + int width = 1; + while (width < widest) + width *= 2; + Batch layout; + for (; width <= PageSide; width *= 2) { + if (!Detail::TryWidth(batch, width, layout)) continue; + if (batch.width > 0 && layout.ByteSize() >= batch.ByteSize()) continue; + std::copy_n(layout.offsets.begin(), batch.count, batch.offsets.begin()); + batch.width = layout.width; + batch.height = layout.height; + } + return batch.width > 0 && unionTexels >= std::uint64_t(PageTexels + dirtyTexels + batch.width * batch.height); + } + + inline void WritePage(const Batch& batch, std::uint8_t* page) { + std::memset(page, 0, batch.ByteSize()); + const std::size_t pitch = batch.width * BytesPerTexel; + for (std::size_t i = 0; i < batch.count; ++i) { + const Region& region = batch.regions[i]; + const Point offset = batch.offsets[i]; + auto* dest = page + offset.y * pitch + offset.x * BytesPerTexel; + for (int y = 0; y < region.height; ++y) { + std::memcpy(dest + y * pitch, region.source + y * region.sourcePitch, region.width * BytesPerTexel); + } + } + } +} // namespace MobileGL::MG_Backend::DirectGLES::TextureImpl::PackedTextureUpload diff --git a/MobileGL/MG_Backend/DirectGLES/TextureUploadBoxes.h b/MobileGL/MG_Backend/DirectGLES/TextureUploadBoxes.h new file mode 100644 index 00000000..7e3513e3 --- /dev/null +++ b/MobileGL/MG_Backend/DirectGLES/TextureUploadBoxes.h @@ -0,0 +1,68 @@ +// MobileGL - MobileGL/MG_Backend/DirectGLES/TextureUploadBoxes.h +// Copyright (c) 2025-2026 MobileGL-Dev +// Licensed under the GNU Lesser General Public License v3.0: +// https://www.gnu.org/licenses/gpl-3.0.txt +// https://www.gnu.org/licenses/lgpl-3.0.txt +// SPDX-License-Identifier: LGPL-3.0-only +// End of Source File Header + +#pragma once + +#include +#include +#include +#include +#include + +namespace MobileGL::MG_Backend::DirectGLES::TextureImpl::TextureUploadBoxes { + constexpr std::size_t MaxRegions = 64; + constexpr std::uint64_t MinSavedTexels = 16 * 1024 / 4; + + struct Box { + int left, top, right, bottom; + + std::uint64_t Texels() const { return static_cast(right - left) * (bottom - top); } + }; + + inline Box Union(Box a, Box b) { + return {std::min(a.left, b.left), std::min(a.top, b.top), std::max(a.right, b.right), + std::max(a.bottom, b.bottom)}; + } + + // A second GLES upload is worth taking only for separated groups with a + // substantial absolute and relative reduction. Small mip levels keep one job. + inline bool WorthSearching(Box bounds, std::size_t count) { + return count >= 2 && count <= MaxRegions && bounds.Texels() > MinSavedTexels; + } + + // Every input rectangle belongs to one group. Try cuts on both axes and + // keep the least expensive pair of non-overlapping bounding boxes. + inline std::optional> Split(Box bounds, std::array& regions, + std::size_t count) { + if (!WorthSearching(bounds, count)) return std::nullopt; + const auto totalTexels = bounds.Texels(); + auto bestTexels = std::min(totalTexels / 2, totalTexels - MinSavedTexels); + std::optional> best; + std::array suffix; + for (bool horizontal : {true, false}) { + std::sort(regions.begin(), regions.begin() + count, + [horizontal](Box a, Box b) { return horizontal ? a.left < b.left : a.top < b.top; }); + suffix[count - 1] = regions[count - 1]; + for (std::size_t i = count - 1; i > 1; --i) { + suffix[i - 1] = Union(regions[i - 1], suffix[i]); + } + Box prefix = regions[0]; + for (std::size_t i = 1; i < count; ++i) { + const Box rest = suffix[i]; + const bool separated = horizontal ? prefix.right < rest.left : prefix.bottom < rest.top; + const auto texels = prefix.Texels() + rest.Texels(); + if (separated && texels <= bestTexels) { + bestTexels = texels; + best = std::array{prefix, rest}; + } + prefix = Union(prefix, regions[i]); + } + } + return best; + } +} // namespace MobileGL::MG_Backend::DirectGLES::TextureImpl::TextureUploadBoxes From 639ae0f636b6d2609d1943d0f15012a57b4724c0 Mon Sep 17 00:00:00 2001 From: Eurya0x13 Date: Thu, 26 Nov 2026 14:12:28 +0800 Subject: [PATCH 2/9] [Fix] (MG_Backend/DirectGLES): avoid PBO updates to sampled offscreen textures - Track sampled storage by native context and draw batch. - Use the existing client upload for in-place edits to sampled storage. --- .../MG_Backend/DirectGLES/DirectGLESSync.cpp | 1 + .../DirectGLES/DirectGLESTextures.cpp | 41 ++++++++++++ .../MG_Backend/DirectGLES/DrawTextureReads.h | 66 +++++++++++++++++++ MobileGL/MG_Backend/DirectGLES/Managers.h | 9 +++ .../DirectGLES/ManagersFramebuffers.cpp | 2 + .../DirectGLES/ManagersTextureSync.cpp | 13 ++-- 6 files changed, 124 insertions(+), 8 deletions(-) create mode 100644 MobileGL/MG_Backend/DirectGLES/DrawTextureReads.h diff --git a/MobileGL/MG_Backend/DirectGLES/DirectGLESSync.cpp b/MobileGL/MG_Backend/DirectGLES/DirectGLESSync.cpp index 622a1084..560efb8c 100644 --- a/MobileGL/MG_Backend/DirectGLES/DirectGLESSync.cpp +++ b/MobileGL/MG_Backend/DirectGLES/DirectGLESSync.cpp @@ -639,6 +639,7 @@ namespace MobileGL::MG_Backend::DirectGLES { } else if (g_EGLFuncs.eglSwapBuffers != nullptr) { mglSwapped = g_EGLFuncs.eglSwapBuffers(g_Display, drawSurface); } + if (mglSwapped == EGL_TRUE) TextureImpl::EndDrawTextureBatch(); NoteDrawSurfaceMoved(); // a window surface takes a new size at its swap if (drawSurface != EGL_NO_SURFACE) { const std::lock_guard lock(g_nativeRegistryMutex); diff --git a/MobileGL/MG_Backend/DirectGLES/DirectGLESTextures.cpp b/MobileGL/MG_Backend/DirectGLES/DirectGLESTextures.cpp index 3cd3be8c..6fd14071 100644 --- a/MobileGL/MG_Backend/DirectGLES/DirectGLESTextures.cpp +++ b/MobileGL/MG_Backend/DirectGLES/DirectGLESTextures.cpp @@ -7,9 +7,50 @@ // End of Source File Header #include "DirectGLESInternal.h" +#include "DrawTextureReads.h" namespace MobileGL::MG_Backend::DirectGLES { namespace TextureImpl { + namespace { + PerNativeContext g_drawTextureReads; + } // namespace + + void NoteDrawTextureFramebuffer(Uint framebuffer) { + if (CurrentNativeContextSerial() != 0) g_drawTextureReads.Current().BindFramebuffer(framebuffer); + } + + void DeleteDrawTextureFramebuffer(Uint framebuffer) { + if (CurrentNativeContextSerial() != 0) g_drawTextureReads.Current().DeleteFramebuffer(framebuffer); + } + + void EndDrawTextureBatch() { + if (CurrentNativeContextSerial() != 0) g_drawTextureReads.Current().EndBatch(); + } + + Bool WasTextureReadInDrawBatch(MG_Pipe::MGPipeHandle storage) { + return CurrentNativeContextSerial() != 0 && g_drawTextureReads.Current().WasRead(storage.Slot, storage.Gen); + } + + void NoteDrawTextureReads() { + if (CurrentNativeContextSerial() == 0) return; + auto& reads = g_drawTextureReads.Current(); + const auto& state = MG_Pipe::MGPipeApplier(); + if (!reads.NeedsSamplerWalk(state.ContextSerial, state.SamplerViewsSerial)) return; + + const SizeT end = std::min(static_cast(state.SamplerViewStart) + state.SamplerViewCount, + state.BoundSamplerViews.size()); + for (SizeT unit = state.SamplerViewStart; unit < end; ++unit) { + const auto* texture = PipeTextureRecordForHandle(state.BoundSamplerViews[unit].Texture); + if (!texture) continue; + // A sampler view and an update to its parent address the same texture storage. + if (const auto* storage = PipeTextureStorageRecordForRecord(*texture)) { + const auto handle = storage->Desc.Resource; + reads.NoteRead(handle.Slot, handle.Gen); + } + } + reads.RecordSamplerWalk(state.ContextSerial, state.SamplerViewsSerial); + } + // Identity snapshot of what one texture unit has bound: the object in every binding // slot plus the unit's sampler object. This - not the context's texture bind // generation - is what the per-draw texture memos key on: the generation also bumps diff --git a/MobileGL/MG_Backend/DirectGLES/DrawTextureReads.h b/MobileGL/MG_Backend/DirectGLES/DrawTextureReads.h new file mode 100644 index 00000000..ed695f17 --- /dev/null +++ b/MobileGL/MG_Backend/DirectGLES/DrawTextureReads.h @@ -0,0 +1,66 @@ +// MobileGL - MobileGL/MG_Backend/DirectGLES/DrawTextureReads.h +// Copyright (c) 2025-2026 MobileGL-Dev +// Licensed under the GNU Lesser General Public License v3.0: +// https://www.gnu.org/licenses/gpl-3.0.txt +// https://www.gnu.org/licenses/lgpl-3.0.txt +// SPDX-License-Identifier: LGPL-3.0-only +// End of Source File Header + +#pragma once + +#include +#include + +namespace MobileGL::MG_Backend::DirectGLES::TextureImpl { + // One instance per native context. Slot generations distinguish reused texture names, + // and batch stamps let us discard a batch without walking its texture slots. + class DrawTextureReads { + public: + void BindFramebuffer(std::uint32_t framebuffer) { + if (m_drawFramebuffer == framebuffer) return; + m_drawFramebuffer = framebuffer; + EndBatch(); + } + + void DeleteFramebuffer(std::uint32_t framebuffer) { + if (framebuffer == m_drawFramebuffer) BindFramebuffer(0); + } + + void EndBatch() { + m_recordedSamplers = false; + if (++m_batch == 0) { + m_reads.clear(); + m_batch = 1; + } + } + + bool NeedsSamplerWalk(std::uint64_t context, std::uint64_t views) const { + return m_drawFramebuffer != 0 && (!m_recordedSamplers || context != m_context || views != m_views); + } + + void RecordSamplerWalk(std::uint64_t context, std::uint64_t views) { + m_recordedSamplers = true; + m_context = context; + m_views = views; + } + + void NoteRead(std::uint32_t slot, std::uint32_t generation) { + if (slot >= m_reads.size()) m_reads.resize(static_cast(slot) + 1); + m_reads[slot] = Stamp(generation); + } + + bool WasRead(std::uint32_t slot, std::uint32_t generation) const { + return m_drawFramebuffer != 0 && slot < m_reads.size() && m_reads[slot] == Stamp(generation); + } + + private: + std::uint64_t Stamp(std::uint32_t generation) const { return (std::uint64_t{m_batch} << 32) | generation; } + + std::uint32_t m_drawFramebuffer = 0; + std::uint32_t m_batch = 1; + bool m_recordedSamplers = false; + std::uint64_t m_context = 0; + std::uint64_t m_views = 0; + std::vector m_reads; + }; +} // namespace MobileGL::MG_Backend::DirectGLES::TextureImpl diff --git a/MobileGL/MG_Backend/DirectGLES/Managers.h b/MobileGL/MG_Backend/DirectGLES/Managers.h index 9037ce9e..142cc0ef 100644 --- a/MobileGL/MG_Backend/DirectGLES/Managers.h +++ b/MobileGL/MG_Backend/DirectGLES/Managers.h @@ -272,11 +272,16 @@ namespace MobileGL::MG_Backend::DirectGLES { // re-pushes index 0's state. Takes the count so it can do nothing at all in the common case. void EndViewportRoutingPasses(Uint passCount); + namespace TextureImpl { + void NoteDrawTextureReads(); + } // namespace TextureImpl + // Issue one draw, replayed once per viewport-routing pass. Every application-visible draw // entry point wraps its native glDraw* call in this; the internal blit and clear helpers // deliberately do not, because they bind their own programs, which never route. template inline void ForEachViewportRoutingPass(IssueDraw&& issue) { + TextureImpl::NoteDrawTextureReads(); const Uint passCount = BeginViewportRoutingPasses(); for (Uint pass = 0; pass < passCount; ++pass) { if (passCount > 1) { @@ -2102,6 +2107,10 @@ namespace MobileGL::MG_Backend::DirectGLES { // issued since the last one. Sampled access from a draw does not take it: that is the // order every driver keeps on its own, and it is the per-draw hot path. void NoteInPlaceTextureUpload(); + void NoteDrawTextureFramebuffer(Uint framebuffer); + void DeleteDrawTextureFramebuffer(Uint framebuffer); + void EndDrawTextureBatch(); + Bool WasTextureReadInDrawBatch(MG_Pipe::MGPipeHandle storage); // The barrier bits owed for the uploads noted since the last call (0 when none), and // the note cleared: the caller issues them, folded into any barrier of its own. GLbitfield TakeInPlaceTextureUploadBarrierBits(); diff --git a/MobileGL/MG_Backend/DirectGLES/ManagersFramebuffers.cpp b/MobileGL/MG_Backend/DirectGLES/ManagersFramebuffers.cpp index 1a0a4692..fa21e820 100644 --- a/MobileGL/MG_Backend/DirectGLES/ManagersFramebuffers.cpp +++ b/MobileGL/MG_Backend/DirectGLES/ManagersFramebuffers.cpp @@ -46,6 +46,7 @@ namespace MobileGL::MG_Backend::DirectGLES { NoteFramebufferIdDeleted(m_backendFBOId); if (m_contextGeneration == g_backendContextGeneration && g_GLESFuncs.glDeleteFramebuffers) { g_GLESFuncs.glDeleteFramebuffers(1, &m_backendFBOId); + TextureImpl::DeleteDrawTextureFramebuffer(m_backendFBOId); } m_backendFBOId = 0; } @@ -83,6 +84,7 @@ namespace MobileGL::MG_Backend::DirectGLES { if (bindsDraw) { g_driverFBOBindings[drawIdx] = id; g_driverFBOBindingKnown[drawIdx] = true; + if (!drawMatches) TextureImpl::NoteDrawTextureFramebuffer(id); } if (bindsRead) { g_driverFBOBindings[readIdx] = id; diff --git a/MobileGL/MG_Backend/DirectGLES/ManagersTextureSync.cpp b/MobileGL/MG_Backend/DirectGLES/ManagersTextureSync.cpp index 26842f69..0381cdbc 100644 --- a/MobileGL/MG_Backend/DirectGLES/ManagersTextureSync.cpp +++ b/MobileGL/MG_Backend/DirectGLES/ManagersTextureSync.cpp @@ -1665,6 +1665,8 @@ namespace MobileGL::MG_Backend::DirectGLES { MGLOG_D("Packed texture upload rejected for texture %u", m_backendTextureId); } } + // Update sampled storage directly to avoid stalling the current offscreen batch on a PBO. + const Bool useClientUnpack = stableStorage && WasTextureReadInDrawBatch(pushedRes); // Per-level scratch of the exact-footprint path, hoisted to reuse capacity. Vector dirtyFootprint; Vector stagingBlockOverflow; @@ -1995,13 +1997,8 @@ namespace MobileGL::MG_Backend::DirectGLES { static_cast(uploadTarget), static_cast(level))) && SplitMipUpload(*pendingUpload, texelSize, dirtyRects); if (splitBoxUpload) dirtyRectCount = 2; - // Everything above - the union box, the ring's one-box rule, the rect - // list with its merges, fold and 3/4 cut-off - may upload shadow texels - // the client did not write, which is only harmless while the driver - // still holds those texels as they were last uploaded. Once it may hold - // GPU writes, the level goes up as exactly the texels written, one box - // (one ring job) each, whatever that costs: more boxes, and a union box - // that spans the whole level no longer means a whole-level upload. + // A union or split can include untouched texels while the shadow is authoritative. + // Once the GPU may have written the texture, upload only the exact client footprint. const MG_State::GLState::MipmapDirtyRegion* uploadRects = dirtyRects; SizeT uploadRectCount = dirtyRectCount; if (m_driverMayHoldGpuWrites && regionsAddressable) { @@ -2094,7 +2091,7 @@ namespace MobileGL::MG_Backend::DirectGLES { UnpackStagingBlock stagingBlockArray[MG_State::GLState::MipmapStorage::kMaxDirtyRects]; UnpackStagingBlock* stagingBlocks = stagingBlockArray; SizeT stagingBlockCount = 0; - if (!ringUsable) { + if (!ringUsable || useClientUnpack) { // Nothing to plan: every branch below keeps the client // pointer and its ROW_LENGTH striding, unchanged. } else if (perRectUpload) { From b89755675011ef06123602f55513b80e5c9a67a8 Mon Sep 17 00:00:00 2001 From: Eurya0x13 Date: Thu, 26 Nov 2026 14:13:37 +0800 Subject: [PATCH 3/9] [Perf] (MG_Backend/DirectGLES, MG_Impl/Pipe, MG_State/GLState): reuse draw state - Reuse the resolved shader record during draw preparation and copies. - Read the tracked draw framebuffer when preparing a clear. - Keep one memo slot hint per VAO and validate it by identity and epoch. --- .../MG_Backend/DirectGLES/DirectGLESBind.cpp | 29 +++++++------------ .../MG_Backend/DirectGLES/DirectGLESCopy.cpp | 14 ++------- .../MG_Backend/DirectGLES/DirectGLESDraw.cpp | 6 ++-- .../DirectGLES/DirectGLESInternal.h | 14 ++++----- .../MG_Backend/DirectGLES/DirectGLESState.cpp | 8 +++-- MobileGL/MG_Impl/Pipe/VertexInputEmit.h | 14 ++++----- .../VertexArrayState/VertexArrayObject.h | 3 ++ 7 files changed, 39 insertions(+), 49 deletions(-) diff --git a/MobileGL/MG_Backend/DirectGLES/DirectGLESBind.cpp b/MobileGL/MG_Backend/DirectGLES/DirectGLESBind.cpp index c741f7b3..320511c2 100644 --- a/MobileGL/MG_Backend/DirectGLES/DirectGLESBind.cpp +++ b/MobileGL/MG_Backend/DirectGLES/DirectGLESBind.cpp @@ -911,7 +911,8 @@ namespace MobileGL::MG_Backend::DirectGLES { BufferImpl::SyncNeccessaryBuffers(currentVAO, vaoTwin, vaoConfigVersion, syncBit & DrawSyncBit::IndexBuffer, syncBit & DrawSyncBit::IndirectBuffer); // The draw's integer arrays and the program's narrow-integer seeds (NarrowIntegerSeeds.h). - IntegerAttributePlan integerPlan = ResolveIntegerAttributePlanForDraw(MG_Pipe::MGPipeApplier().DrawProgram); + const MG_Pipe::MGPipeHandle programCso = MG_Pipe::MGPipeApplier().DrawProgram; + IntegerAttributePlan integerPlan = ResolveIntegerAttributePlanForDraw(programCso); VertexArrayImpl::SyncCurrentVAOFromRecords(vaoTwin, integerPlan); TextureImpl::SyncNeccessaryTextures(textureKeys); // A draw reads and writes through its image units too, so the unit bindings have to be @@ -929,8 +930,8 @@ namespace MobileGL::MG_Backend::DirectGLES { // at all; the remaining uses of it below are the two callees' own, and both have a // handle arm of their own. P5e (pa) finished it: the pull itself is gone on that arm and // `currentProgram` is a null SharedPtr there, which this branch never reaches for. - PrgramImpl::SyncCurrentProgramByHandle(MG_Pipe::MGPipeApplier().DrawProgram, true, &integerPlan); - if (DropRefusedNarrowIntegerSeeds(integerPlan, MG_Pipe::MGPipeApplier().DrawProgram)) + const auto* programRecord = PrgramImpl::SyncCurrentProgramByHandle(programCso, true, &integerPlan); + if (DropRefusedNarrowIntegerSeeds(integerPlan, programCso)) VertexArrayImpl::SyncCurrentVAOFromRecords(vaoTwin, integerPlan); RenderStateImpl::SyncRenderState(); @@ -951,11 +952,11 @@ namespace MobileGL::MG_Backend::DirectGLES { // a conjunction over four callees; this one is served by the record whenever the PROGRAM // family is on the handle arm, which includes the mixed A/B where the texture bits are // off and `currentProgram` above is therefore still a real object. - VertexArrayImpl::SyncCurrentVertexAttributeValues(vaoTwin, MG_Pipe::MGPipeApplier().DrawProgram); + VertexArrayImpl::SyncCurrentVertexAttributeValues(vaoTwin, programCso); BindCurrentTextures(textureKeys, currentProgram); - BindCurrentProgramWithResources(currentProgram, textureKeys, MG_Pipe::MGPipeApplier().DrawProgram); - PushNarrowIntegerWidthsForDraw(integerPlan, MG_Pipe::MGPipeApplier().DrawProgram); + BindCurrentProgramWithResources(currentProgram, textureKeys, programCso, programRecord); + PushNarrowIntegerWidthsForDraw(integerPlan, programCso); // Last: opening the capture span needs the program current and the capture // buffers bound, and ES rejects most binding changes once it is open. @@ -1368,19 +1369,9 @@ namespace MobileGL::MG_Backend::DirectGLES { // (its note says so). The parameter stays for the monolith arm, which is ruling ID-81: that // build keeps this function's frontend text token for token. void BindCurrentProgramWithResources(const SharedPtr& currentProgram, - const TextureImpl::DrawTextureSyncKeys& keys, - MG_Pipe::MGPipeHandle programCso) { - // P5e (pg): THE HANDLE ARM'S GATE, from the record rather than from the object. Hoisted - // out of the `if` below because the whole body's entry condition is "the program linked - // and has SPIR-V", and on this arm both answers are fields of the descriptor - // (Desc.LinkStatus is ID-88's, Desc.SpirvStatus P4a's). - const MG_Pipe::MGPipeShaderCsoRecord* programRecord = nullptr; - programRecord = PrgramImpl::FindShaderCsoRecord(programCso); - if (programRecord != nullptr && (programRecord->Desc.LinkStatus == 0 || programRecord->Desc.SpirvStatus == 0)) { - programRecord = nullptr; - } - const Bool programUsable = programRecord != nullptr; - if (programUsable) { + const TextureImpl::DrawTextureSyncKeys& keys, MG_Pipe::MGPipeHandle programCso, + const MG_Pipe::MGPipeShaderCsoRecord* programRecord) { + if (programRecord != nullptr) { #ifdef TRACY_ENABLE ZoneScopedNC("BindCurrentProgram", TRACY_ZONECOLOR_BACKEND); #endif diff --git a/MobileGL/MG_Backend/DirectGLES/DirectGLESCopy.cpp b/MobileGL/MG_Backend/DirectGLES/DirectGLESCopy.cpp index 35f367eb..99d567c2 100644 --- a/MobileGL/MG_Backend/DirectGLES/DirectGLESCopy.cpp +++ b/MobileGL/MG_Backend/DirectGLES/DirectGLESCopy.cpp @@ -107,16 +107,8 @@ namespace MobileGL::MG_Backend::DirectGLES { // MGPipeApplier().DispatchProgram, which set_dispatch_program carried. A compute-only // pipeline has no draw program at all, which is why the two applier fields are separate. const MG_Pipe::MGPipeHandle dispatchCso = MG_Pipe::MGPipeApplier().DispatchProgram; - PrgramImpl::SyncCurrentProgramByHandle(dispatchCso, false); - - // The same gate as the frontend one below, from the record: a dispatch of a program - // the frontend reports unlinked, or one whose SPIR-V never arrived, binds nothing. - const auto* const record = PrgramImpl::FindShaderCsoRecord(dispatchCso); - if (record == nullptr || record->Desc.LinkStatus == 0 || record->Desc.SpirvStatus == 0) { - g_GLESFuncs.glUseProgram(0); - PrgramImpl::g_lastUsedBackendProgramId = 0; - return; - } + const auto* programRecord = PrgramImpl::SyncCurrentProgramByHandle(dispatchCso, false); + if (programRecord == nullptr) return; // Compute shaders sample textures through the same unit bindings as draws // (e.g. Flywheel's depth-pyramid downsample reads the depth attachment on @@ -125,7 +117,7 @@ namespace MobileGL::MG_Backend::DirectGLES { // Compute programs need the same per-program resource sync as draws: // uniform-block bindings and sampler units only exist through the API // because layout(binding) is stripped from the transpiled ESSL. - BindCurrentProgramWithResources(currentProgram, textureKeys, dispatchCso); + BindCurrentProgramWithResources(currentProgram, textureKeys, dispatchCso, programRecord); } Bool UpdateTextureBindingAtTarget(GLenum target) { diff --git a/MobileGL/MG_Backend/DirectGLES/DirectGLESDraw.cpp b/MobileGL/MG_Backend/DirectGLES/DirectGLESDraw.cpp index cf078b79..4cca0bc3 100644 --- a/MobileGL/MG_Backend/DirectGLES/DirectGLESDraw.cpp +++ b/MobileGL/MG_Backend/DirectGLES/DirectGLESDraw.cpp @@ -582,8 +582,10 @@ namespace MobileGL::MG_Backend::DirectGLES { const Bool widenedColorClear = widenedDrawBuffers != 0 && FramebufferImpl::g_integerColorDrawBufferMask == 0; GLint clearDrawFbo = 0; - g_GLESFuncs.glGetIntegerv(GL_DRAW_FRAMEBUFFER_BINDING, &clearDrawFbo); - if ((outOfRange || widenedColorClear) && clearDrawFbo != 0) { + if (outOfRange || widenedColorClear) { + g_GLESFuncs.glGetIntegerv(GL_DRAW_FRAMEBUFFER_BINDING, &clearDrawFbo); + } + if (clearDrawFbo != 0) { GLint maxDrawBuffers = 0; GLint clearedCount = 0; GLint firstDb = -1; diff --git a/MobileGL/MG_Backend/DirectGLES/DirectGLESInternal.h b/MobileGL/MG_Backend/DirectGLES/DirectGLESInternal.h index 6bb55873..22a9fe60 100644 --- a/MobileGL/MG_Backend/DirectGLES/DirectGLESInternal.h +++ b/MobileGL/MG_Backend/DirectGLES/DirectGLESInternal.h @@ -387,9 +387,9 @@ namespace MobileGL::MG_Backend::DirectGLES { const MG_Pipe::MGPipeShaderCsoRecord* ResolveGlobalConstantsRecordForHandle(MG_Pipe::MGPipeHandle handle, Uint uboSize); - // `plan` (a draw's) arms the program's narrow-integer seeds when it needs them. - void SyncCurrentProgramByHandle(MG_Pipe::MGPipeHandle cso, Bool forDraw, - const IntegerAttributePlan* plan = nullptr); + // Returns the validated record for resource binding in the same draw or dispatch. + const MG_Pipe::MGPipeShaderCsoRecord* SyncCurrentProgramByHandle(MG_Pipe::MGPipeHandle cso, Bool forDraw, + const IntegerAttributePlan* plan = nullptr); } // namespace PrgramImpl // Defined with the surface registry, below. @@ -398,8 +398,8 @@ namespace MobileGL::MG_Backend::DirectGLES { void BindCurrentFBO(FramebufferTarget target); void BindCurrentProgramWithResources(const SharedPtr& currentProgram, - const TextureImpl::DrawTextureSyncKeys& keys, - MG_Pipe::MGPipeHandle programCso); + const TextureImpl::DrawTextureSyncKeys& keys, MG_Pipe::MGPipeHandle programCso, + const MG_Pipe::MGPipeShaderCsoRecord* programRecord); void BindCurrentTextures(const TextureImpl::DrawTextureSyncKeys& keys, const SharedPtr& currentProgram); @@ -504,8 +504,8 @@ namespace MobileGL::MG_Backend::DirectGLES { void BindCurrentTextures(); void BindCurrentProgramWithResources(const SharedPtr& currentProgram, - const TextureImpl::DrawTextureSyncKeys& keys, - MG_Pipe::MGPipeHandle programCso); + const TextureImpl::DrawTextureSyncKeys& keys, MG_Pipe::MGPipeHandle programCso, + const MG_Pipe::MGPipeShaderCsoRecord* programRecord); PrgramImpl::BackendProgramObjectImpl* GetCurrentBackendProgram(); diff --git a/MobileGL/MG_Backend/DirectGLES/DirectGLESState.cpp b/MobileGL/MG_Backend/DirectGLES/DirectGLESState.cpp index bd5272d8..cf416f4a 100644 --- a/MobileGL/MG_Backend/DirectGLES/DirectGLESState.cpp +++ b/MobileGL/MG_Backend/DirectGLES/DirectGLESState.cpp @@ -1434,7 +1434,8 @@ namespace MobileGL::MG_Backend::DirectGLES { // and the clamp masks, the broadcast count, ImageUnitFormatsStillMatch and the three // patch clauses are unchanged - they are backend globals, fb's row and VALUE rows of the // residual block, none of which this family owns. - void SyncCurrentProgramByHandle(MG_Pipe::MGPipeHandle cso, Bool forDraw, const IntegerAttributePlan* plan) { + const MG_Pipe::MGPipeShaderCsoRecord* SyncCurrentProgramByHandle(MG_Pipe::MGPipeHandle cso, Bool forDraw, + const IntegerAttributePlan* plan) { #ifdef TRACY_ENABLE ZoneScopedC(TRACY_ZONECOLOR_BACKEND); #endif @@ -1453,7 +1454,7 @@ namespace MobileGL::MG_Backend::DirectGLES { if (record == nullptr || record->Desc.LinkStatus == 0 || record->Desc.SpirvStatus == 0) { g_GLESFuncs.glUseProgram(0); g_lastUsedBackendProgramId = 0; - return; + return nullptr; } // REFUSED at a draw, record-only at a dispatch: see the policy's own note. ResolveFragColorBroadcastCount(forDraw ? BroadcastCountPolicy::RefuseFallback @@ -1466,7 +1467,7 @@ namespace MobileGL::MG_Backend::DirectGLES { // than a draw with somebody else's shader. g_GLESFuncs.glUseProgram(0); g_lastUsedBackendProgramId = 0; - return; + return record; } // Sticky for the twin's lifetime: a draw that needs the seeds rebuilds the program once. if (plan != nullptr && plan->NeedsSeeds()) twin->NarrowIntegerSeeds().wanted = true; @@ -1488,6 +1489,7 @@ namespace MobileGL::MG_Backend::DirectGLES { } g_currentDrawProgramHandle = cso; g_currentDrawBackendProgram = twin; + return record; } } // namespace PrgramImpl } // namespace MobileGL::MG_Backend::DirectGLES diff --git a/MobileGL/MG_Impl/Pipe/VertexInputEmit.h b/MobileGL/MG_Impl/Pipe/VertexInputEmit.h index c63ada98..388178f5 100644 --- a/MobileGL/MG_Impl/Pipe/VertexInputEmit.h +++ b/MobileGL/MG_Impl/Pipe/VertexInputEmit.h @@ -487,18 +487,19 @@ namespace MobileGL::MG_Pipe { VaoMemo& MemoFor(const VertexArrayObject& vao) { const Uint64 lifetimeId = vao.GetLifetimeId(); const Uint64 epoch = MGPipeSlots().ResetEpoch(); - // The three emitters of one validate ask for the same array: the last answer's index, - // believed only while that entry still holds this id (a grow or an erase moves entries). - if (m_lastMemoIndex < m_vaoMemo.size() && m_vaoMemo[m_lastMemoIndex].LifetimeId == lifetimeId && - m_vaoMemo[m_lastMemoIndex].SlotEpoch == epoch) - return m_vaoMemo[m_lastMemoIndex]; + // A per-array hint survives switching arrays. Growth and erasure can move entries, + // so the slot is only a candidate until both identity and the allocator epoch match. + SizeT& hint = vao.PipeVertexInputMemoHint(); + if (hint < m_vaoMemo.size() && m_vaoMemo[hint].LifetimeId == lifetimeId && + m_vaoMemo[hint].SlotEpoch == epoch) + return m_vaoMemo[hint]; if (m_vaoMemo.empty() || (m_vaoMemoUsed + 1) * 2 > m_vaoMemo.size()) GrowVaoMemo(); const SizeT mask = m_vaoMemo.size() - 1; SizeT i = VaoMemoHome(lifetimeId, mask); while (m_vaoMemo[i].LifetimeId != 0 && m_vaoMemo[i].LifetimeId != lifetimeId) i = (i + 1) & mask; VaoMemo& memo = m_vaoMemo[i]; - m_lastMemoIndex = i; + hint = i; if (memo.LifetimeId == 0) ++m_vaoMemoUsed; if (memo.LifetimeId != lifetimeId || memo.SlotEpoch != epoch) { memo = VaoMemo{}; @@ -527,7 +528,6 @@ namespace MobileGL::MG_Pipe { } Vector m_vaoMemo; SizeT m_vaoMemoUsed = 0; - SizeT m_lastMemoIndex = ~SizeT{0}; public: // The VAO died (MGPipeEmitVertexElementsDestroyAndFree): its entry goes, by backward-shift diff --git a/MobileGL/MG_State/GLState/VertexArrayState/VertexArrayObject.h b/MobileGL/MG_State/GLState/VertexArrayState/VertexArrayObject.h index 97b176cb..a6143268 100644 --- a/MobileGL/MG_State/GLState/VertexArrayState/VertexArrayObject.h +++ b/MobileGL/MG_State/GLState/VertexArrayState/VertexArrayObject.h @@ -69,6 +69,8 @@ namespace MobileGL { // DirectVulkan's VulkanRenderer). Uint64 GetLifetimeId() const { return m_lifetimeId; } + SizeT& PipeVertexInputMemoHint() const { return m_pipeVertexInputMemoHint; } + void SetAttributeDivisor(Uint index, Uint divisor); Uint GetAttributeDivisor(Uint index) const; @@ -134,6 +136,7 @@ namespace MobileGL { const Uint m_externalIndex = 0; const Uint64 m_lifetimeId = AllocateLifetimeId(); + mutable SizeT m_pipeVertexInputMemoHint = ~SizeT{0}; Array m_attributes; Array m_attributeVersions; BindingSlot m_indexBufferBindingSlot; From 99afafd7cf5dc6c60985855684bba5a2ce27e626 Mon Sep 17 00:00:00 2001 From: Eurya0x13 Date: Thu, 26 Nov 2026 14:14:38 +0800 Subject: [PATCH 4/9] [Perf] (MG_Backend/DirectGLES): reuse the frame fence wait result - Retire the already signaled slot without querying its status again. - Keep polling the other slots to preserve the completion watermark. --- .../MG_Backend/DirectGLES/DirectGLESSync.cpp | 17 ++++++++++++----- 1 file changed, 12 insertions(+), 5 deletions(-) diff --git a/MobileGL/MG_Backend/DirectGLES/DirectGLESSync.cpp b/MobileGL/MG_Backend/DirectGLES/DirectGLESSync.cpp index 560efb8c..1300d8d3 100644 --- a/MobileGL/MG_Backend/DirectGLES/DirectGLESSync.cpp +++ b/MobileGL/MG_Backend/DirectGLES/DirectGLESSync.cpp @@ -450,7 +450,7 @@ namespace MobileGL::MG_Backend::DirectGLES { // and the serials are handed out to every native context of every session in turn, so the // highest signaled serial says nothing about an older fence of another context still // pending. A serial is complete when no live fence at or below it is pending. - void PollFrameFences() { + void PollFrameFences(const FrameFence* signaled = nullptr) { if (!g_GLESFuncs.glGetSynciv) return; Uint64 lowestPending = ~Uint64{0}; for (FrameFence& slot : g_frameFenceRing) { @@ -460,8 +460,10 @@ namespace MobileGL::MG_Backend::DirectGLES { continue; } GLint status = GL_SIGNALED; - GLsizei length = 0; - g_GLESFuncs.glGetSynciv(slot.sync, GL_SYNC_STATUS, 1, &length, &status); + if (&slot != signaled) { + GLsizei length = 0; + g_GLESFuncs.glGetSynciv(slot.sync, GL_SYNC_STATUS, 1, &length, &status); + } if (status == GL_SIGNALED) { if (g_GLESFuncs.glDeleteSync) g_GLESFuncs.glDeleteSync(slot.sync); slot.sync = nullptr; @@ -654,6 +656,7 @@ namespace MobileGL::MG_Backend::DirectGLES { // the same bound on the ES driver: after presenting S, wait for S+1-N to complete. The // platform's own queueBuffer throttle already waits for S-1, so only N = 1 is stricter // than what Android does by itself; larger N is the same contract stated, not a change. + const FrameFence* signaled = nullptr; const Uint32 framesInFlight = MG_Config::Features.FramesInFlight; if (presentedSerial != 0 && framesInFlight != 0 && framesInFlight < static_cast(kFrameFenceRingDepth) && g_GLESFuncs.glClientWaitSync && presentedSerial + 1 > framesInFlight) { @@ -661,11 +664,15 @@ namespace MobileGL::MG_Backend::DirectGLES { const FrameFence& oldest = g_frameFenceRing[target % kFrameFenceRingDepth]; if (oldest.sync && oldest.serial == target && oldest.contextGeneration == g_syncContextGeneration) { constexpr Uint64 kFramesInFlightWaitNs = 1000ull * 1000 * 1000; - (void)g_GLESFuncs.glClientWaitSync(oldest.sync, GL_SYNC_FLUSH_COMMANDS_BIT, kFramesInFlightWaitNs); + const GLenum status = + g_GLESFuncs.glClientWaitSync(oldest.sync, GL_SYNC_FLUSH_COMMANDS_BIT, kFramesInFlightWaitNs); + if (status == GL_ALREADY_SIGNALED || status == GL_CONDITION_SATISFIED) { + signaled = &oldest; + } } } - if (canFence) PollFrameFences(); + if (canFence) PollFrameFences(signaled); // After the watermark advanced: retire grown-away ring stores and record the // frame's ring high-water marks for slot reclamation. From c025f9c4e895f37305284a04f140d95d039e5533 Mon Sep 17 00:00:00 2001 From: Swung0x48 Date: Thu, 26 Nov 2026 04:56:02 -0400 Subject: [PATCH 5/9] [Fix, Perf] (MG_Backend/DirectGLES): fence packed copies and keep them off sampled storage - Note committed packed copies as in-place uploads for the image barrier. - Skip packed copies and split boxes for storage sampled in the batch. - Keep the scatter rect list on the client-memory path while the ring is up. - Take the packed path on every ES driver that has glCopyImageSubData. --- .../DirectGLES/ManagersTextureSync.cpp | 20 +++++++++++-------- 1 file changed, 12 insertions(+), 8 deletions(-) diff --git a/MobileGL/MG_Backend/DirectGLES/ManagersTextureSync.cpp b/MobileGL/MG_Backend/DirectGLES/ManagersTextureSync.cpp index 0381cdbc..295437a7 100644 --- a/MobileGL/MG_Backend/DirectGLES/ManagersTextureSync.cpp +++ b/MobileGL/MG_Backend/DirectGLES/ManagersTextureSync.cpp @@ -952,6 +952,8 @@ namespace MobileGL::MG_Backend::DirectGLES { if (!Pack(batch, unionTexels)) return PackedUploadResult::Unavailable; const auto result = SubmitPackedUpload(batch, destination, unionTexels); if (result == PackedUploadResult::Committed) { + // The copies rewrite storage the driver already holds, like any in-place level upload. + NoteInPlaceTextureUpload(); for (SizeT level = 0; level < mipmapCount; ++level) { if (FindPipeTextureUpload(*pushedStorage, targetCode, static_cast(level)) != nullptr) { MGB_LEVEL_UPLOAD_DONE(textureMipmapObject, uploadTarget, level); @@ -1647,14 +1649,16 @@ namespace MobileGL::MG_Backend::DirectGLES { ApplyImageBindableStorageWidening(imageWidening, &glInternalFormat, &glFormat, &glType); const auto& uploadTargets = MGB_UPLOAD_TARGETS(textureMipmapObject); ScopedDefaultUnpackState unpackState; + // Update sampled storage directly to avoid stalling the current offscreen batch on a PBO. + const Bool useClientUnpack = stableStorage && WasTextureReadInDrawBatch(pushedRes); // Pack the small writes across all dirty mip levels before their - // per-level union boxes can pull in untouched atlas texels. - if (stableStorage && !m_driverMayHoldGpuWrites && !m_packedUploadRejected && + // per-level union boxes can pull in untouched atlas texels. The packed + // copies write the destination on the GPU too, so sampled storage skips them. + if (stableStorage && !useClientUnpack && !m_driverMayHoldGpuWrites && !m_packedUploadRejected && !m_imageBindableStorageRequired && target == GL_TEXTURE_2D && (glInternalFormat == GL_RGBA8 || glInternalFormat == GL_RGBA) && glFormat == GL_RGBA && glType == GL_UNSIGNED_BYTE && pushedStorage != nullptr && uploadTargets.size() == 1 && g_GLESFuncs.glCopyImageSubData && g_GLESFuncs.glTexStorage2D && - g_GLESCapabilities.GLESRendererString.find("Mali") != String::npos && BufferImpl::UnpackRingAvailable()) { const auto result = TryPackedMipUpload(textureMipmapObject, pushedStorage, pushedRes, uploadTargets.front(), mipmapCount, m_backendTextureId); @@ -1665,8 +1669,6 @@ namespace MobileGL::MG_Backend::DirectGLES { MGLOG_D("Packed texture upload rejected for texture %u", m_backendTextureId); } } - // Update sampled storage directly to avoid stalling the current offscreen batch on a PBO. - const Bool useClientUnpack = stableStorage && WasTextureReadInDrawBatch(pushedRes); // Per-level scratch of the exact-footprint path, hoisted to reuse capacity. Vector dirtyFootprint; Vector stagingBlockOverflow; @@ -1936,7 +1938,8 @@ namespace MobileGL::MG_Backend::DirectGLES { dirtyRects[MG_State::GLState::MipmapStorage::kMaxDirtyRects]; SizeT dirtyRectCount = 0; const Bool ringUsable = BufferImpl::UnpackRingAvailable(); - if (subRectEligible && !ringUsable) { + // A client-memory upload keeps the scatter refinement, ring or not. + if (subRectEligible && (!ringUsable || useClientUnpack)) { if (pendingUpload != nullptr) { // RegionCount == 0 is LEGAL and means "the union box is the // whole story" (D-D3), which is the same statement the @@ -1984,8 +1987,9 @@ namespace MobileGL::MG_Backend::DirectGLES { // Bound the unpack-ring fallback to two jobs per level. The // boxes may include gaps, so require an authoritative CPU shadow. const Bool splitBoxUpload = - ringUsable && regionsAddressable && stableStorage && !m_driverMayHoldGpuWrites && - !m_imageBindableStorageRequired && target == GL_TEXTURE_2D && + ringUsable && !useClientUnpack && regionsAddressable && stableStorage && + !m_driverMayHoldGpuWrites && !m_imageBindableStorageRequired && + target == GL_TEXTURE_2D && (glInternalFormat == GL_RGBA8 || glInternalFormat == GL_RGBA) && glFormat == GL_RGBA && glType == GL_UNSIGNED_BYTE && bpp == 4 && texelSize.z() == 1 && mipData != nullptr && uploadData == mipData && levelRowBytes == static_cast(texelSize.x()) * bpp && From 926e54e28c5b47b1385448b742f7b2c43fcfd58b Mon Sep 17 00:00:00 2001 From: Swung0x48 Date: Thu, 26 Nov 2026 04:56:56 -0400 Subject: [PATCH 6/9] [Refactor] (MG_Backend/DirectGLES, MG_Util/Texture): move the upload packing helpers to MG_Util --- .../DirectGLES/ManagersTextureSync.cpp | 25 ++++++++++--------- .../Texture}/PackedTextureUpload.h | 6 ++--- .../Texture}/TextureUploadBoxes.h | 8 +++--- 3 files changed, 20 insertions(+), 19 deletions(-) rename MobileGL/{MG_Backend/DirectGLES => MG_Util/Texture}/PackedTextureUpload.h (96%) rename MobileGL/{MG_Backend/DirectGLES => MG_Util/Texture}/TextureUploadBoxes.h (89%) diff --git a/MobileGL/MG_Backend/DirectGLES/ManagersTextureSync.cpp b/MobileGL/MG_Backend/DirectGLES/ManagersTextureSync.cpp index 295437a7..3be2ee15 100644 --- a/MobileGL/MG_Backend/DirectGLES/ManagersTextureSync.cpp +++ b/MobileGL/MG_Backend/DirectGLES/ManagersTextureSync.cpp @@ -8,8 +8,8 @@ #include "ManagersInternal.h" #include "DirectGLESInternal.h" -#include "PackedTextureUpload.h" -#include "TextureUploadBoxes.h" +#include +#include namespace MobileGL::MG_Backend::DirectGLES { namespace TextureImpl { @@ -103,7 +103,7 @@ namespace MobileGL::MG_Backend::DirectGLES { namespace { static Bool SplitMipUpload(const MG_Pipe::MGPipeResourceRecord::PendingUpload& pending, const IntVec3& levelSize, MG_State::GLState::MipmapDirtyRegion* boxes) { - using namespace TextureUploadBoxes; + using namespace MG_Util::TextureUploadBoxes; const auto& bounds = pending.UnionBox; if (bounds.X < 0 || bounds.Y < 0 || bounds.Z != 0 || bounds.D != 1 || bounds.X >= levelSize.x() || bounds.Y >= levelSize.y() || bounds.W > static_cast(levelSize.x() - bounds.X) || @@ -173,8 +173,8 @@ namespace MobileGL::MG_Backend::DirectGLES { Committed }; - static PackedUploadResult SubmitPackedUpload(const PackedTextureUpload::Batch& batch, GLuint destination, - Uint64 unionTexels) { + static PackedUploadResult SubmitPackedUpload(const MG_Util::PackedTextureUpload::Batch& batch, + GLuint destination, Uint64 unionTexels) { const Uint64 context = CurrentNativeContextSerial(); if (context == 0) return PackedUploadResult::Unavailable; static PackedUploadPages pool; @@ -188,7 +188,7 @@ namespace MobileGL::MG_Backend::DirectGLES { return PackedUploadResult::Unavailable; } auto* mapping = static_cast(BufferImpl::UnpackRingMappedPtr()); - PackedTextureUpload::WritePage(batch, mapping + offset); + MG_Util::PackedTextureUpload::WritePage(batch, mapping + offset); DrainDriverErrors("packed texture upload"); if (page->context != context) { @@ -200,8 +200,8 @@ namespace MobileGL::MG_Backend::DirectGLES { return PackedUploadResult::Rejected; } g_GLESFuncs.glBindTexture(GL_TEXTURE_2D, page->texture); - g_GLESFuncs.glTexStorage2D(GL_TEXTURE_2D, 1, GL_RGBA8, PackedTextureUpload::PageSide, - PackedTextureUpload::PageSide); + g_GLESFuncs.glTexStorage2D(GL_TEXTURE_2D, 1, GL_RGBA8, MG_Util::PackedTextureUpload::PageSide, + MG_Util::PackedTextureUpload::PageSide); g_GLESFuncs.glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); g_GLESFuncs.glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); if (g_GLESFuncs.glGetError() != GL_NO_ERROR) { @@ -235,9 +235,10 @@ namespace MobileGL::MG_Backend::DirectGLES { region.height, 1); } if (g_GLESFuncs.glGetError() != GL_NO_ERROR) return PackedUploadResult::Rejected; - MGLOG_I_ONCE("Packed texture upload: %zu regions, %zu packed bytes, %llu bounding-box bytes", - batch.count, batch.ByteSize(), - static_cast(unionTexels * PackedTextureUpload::BytesPerTexel)); + MGLOG_I_ONCE( + "Packed texture upload: %zu regions, %zu packed bytes, %llu bounding-box bytes", batch.count, + batch.ByteSize(), + static_cast(unionTexels * MG_Util::PackedTextureUpload::BytesPerTexel)); return PackedUploadResult::Committed; } } // namespace @@ -904,7 +905,7 @@ namespace MobileGL::MG_Backend::DirectGLES { const MG_Pipe::MGPipeResourceRecord* pushedStorage, MG_Pipe::MGPipeHandle pushedRes, TextureUploadTarget uploadTarget, SizeT mipmapCount, GLuint destination) { - using namespace PackedTextureUpload; + using namespace MG_Util::PackedTextureUpload; Batch batch; Uint64 unionTexels = 0; const auto targetCode = static_cast(uploadTarget); diff --git a/MobileGL/MG_Backend/DirectGLES/PackedTextureUpload.h b/MobileGL/MG_Util/Texture/PackedTextureUpload.h similarity index 96% rename from MobileGL/MG_Backend/DirectGLES/PackedTextureUpload.h rename to MobileGL/MG_Util/Texture/PackedTextureUpload.h index b2b19c25..c1c3d6ab 100644 --- a/MobileGL/MG_Backend/DirectGLES/PackedTextureUpload.h +++ b/MobileGL/MG_Util/Texture/PackedTextureUpload.h @@ -1,4 +1,4 @@ -// MobileGL - MobileGL/MG_Backend/DirectGLES/PackedTextureUpload.h +// MobileGL - MobileGL/MG_Util/Texture/PackedTextureUpload.h // Copyright (c) 2025-2026 MobileGL-Dev // Licensed under the GNU Lesser General Public License v3.0: // https://www.gnu.org/licenses/gpl-3.0.txt @@ -14,7 +14,7 @@ #include #include -namespace MobileGL::MG_Backend::DirectGLES::TextureImpl::PackedTextureUpload { +namespace MobileGL::MG_Util::PackedTextureUpload { // A small RGBA8 page bounds both temporary storage and the packing search. constexpr int PageSide = 128; constexpr std::size_t MaxRegions = 32; @@ -144,4 +144,4 @@ namespace MobileGL::MG_Backend::DirectGLES::TextureImpl::PackedTextureUpload { } } } -} // namespace MobileGL::MG_Backend::DirectGLES::TextureImpl::PackedTextureUpload +} // namespace MobileGL::MG_Util::PackedTextureUpload diff --git a/MobileGL/MG_Backend/DirectGLES/TextureUploadBoxes.h b/MobileGL/MG_Util/Texture/TextureUploadBoxes.h similarity index 89% rename from MobileGL/MG_Backend/DirectGLES/TextureUploadBoxes.h rename to MobileGL/MG_Util/Texture/TextureUploadBoxes.h index 7e3513e3..0fa79318 100644 --- a/MobileGL/MG_Backend/DirectGLES/TextureUploadBoxes.h +++ b/MobileGL/MG_Util/Texture/TextureUploadBoxes.h @@ -1,4 +1,4 @@ -// MobileGL - MobileGL/MG_Backend/DirectGLES/TextureUploadBoxes.h +// MobileGL - MobileGL/MG_Util/Texture/TextureUploadBoxes.h // Copyright (c) 2025-2026 MobileGL-Dev // Licensed under the GNU Lesser General Public License v3.0: // https://www.gnu.org/licenses/gpl-3.0.txt @@ -14,7 +14,7 @@ #include #include -namespace MobileGL::MG_Backend::DirectGLES::TextureImpl::TextureUploadBoxes { +namespace MobileGL::MG_Util::TextureUploadBoxes { constexpr std::size_t MaxRegions = 64; constexpr std::uint64_t MinSavedTexels = 16 * 1024 / 4; @@ -29,7 +29,7 @@ namespace MobileGL::MG_Backend::DirectGLES::TextureImpl::TextureUploadBoxes { std::max(a.bottom, b.bottom)}; } - // A second GLES upload is worth taking only for separated groups with a + // A second upload job is worth taking only for separated groups with a // substantial absolute and relative reduction. Small mip levels keep one job. inline bool WorthSearching(Box bounds, std::size_t count) { return count >= 2 && count <= MaxRegions && bounds.Texels() > MinSavedTexels; @@ -65,4 +65,4 @@ namespace MobileGL::MG_Backend::DirectGLES::TextureImpl::TextureUploadBoxes { } return best; } -} // namespace MobileGL::MG_Backend::DirectGLES::TextureImpl::TextureUploadBoxes +} // namespace MobileGL::MG_Util::TextureUploadBoxes From 94d729c493ceb453c3304d68594d003e966b1994 Mon Sep 17 00:00:00 2001 From: Swung0x48 Date: Thu, 26 Nov 2026 04:57:54 -0400 Subject: [PATCH 7/9] [Test] (MG_Test/Backend, MG_Test/Util): cover upload packing, box splits and sampled-storage tracking --- .../MG_Test/Backend/DirectGLES/CMakeLists.txt | 6 + .../DirectGLES/DrawTextureReadsTest.cpp | 61 ++++++ MobileGL/MG_Test/Util/CMakeLists.txt | 6 + .../MG_Test/Util/TextureUploadPackingTest.cpp | 201 ++++++++++++++++++ 4 files changed, 274 insertions(+) create mode 100644 MobileGL/MG_Test/Backend/DirectGLES/DrawTextureReadsTest.cpp create mode 100644 MobileGL/MG_Test/Util/TextureUploadPackingTest.cpp diff --git a/MobileGL/MG_Test/Backend/DirectGLES/CMakeLists.txt b/MobileGL/MG_Test/Backend/DirectGLES/CMakeLists.txt index 1990d78e..c74fa74f 100644 --- a/MobileGL/MG_Test/Backend/DirectGLES/CMakeLists.txt +++ b/MobileGL/MG_Test/Backend/DirectGLES/CMakeLists.txt @@ -67,6 +67,12 @@ target_include_directories(ContextEpochTest PRIVATE ${MGL_ROOT}/include ${MGL_RO target_link_libraries(ContextEpochTest PRIVATE MobileGLTestMain ${LINK_LIBRARIES}) gtest_discover_tests(ContextEpochTest DISCOVERY_TIMEOUT 30 PROPERTIES LABELS unit) +# The record of texture storage sampled in the current offscreen draw batch. +add_executable(DrawTextureReadsTest DrawTextureReadsTest.cpp) +target_include_directories(DrawTextureReadsTest PRIVATE ${MGL_ROOT}/include ${MGL_ROOT}/MobileGL) +target_link_libraries(DrawTextureReadsTest PRIVATE MobileGLTestMain ${LINK_LIBRARIES}) +gtest_discover_tests(DrawTextureReadsTest DISCOVERY_TIMEOUT 30 PROPERTIES LABELS unit) + # P3b/P4b R-5: D-K2's dependency rule had six statements and nothing compared them. This binary # is where the comparison can live, because it is the one that links BOTH the client check # (MG_Impl/Pipe, through MG_Pipe) and the server gate (MG_Backend/DirectGLES's resolvers). diff --git a/MobileGL/MG_Test/Backend/DirectGLES/DrawTextureReadsTest.cpp b/MobileGL/MG_Test/Backend/DirectGLES/DrawTextureReadsTest.cpp new file mode 100644 index 00000000..e6c60482 --- /dev/null +++ b/MobileGL/MG_Test/Backend/DirectGLES/DrawTextureReadsTest.cpp @@ -0,0 +1,61 @@ +// MobileGL - MobileGL/MG_Test/Backend/DirectGLES/DrawTextureReadsTest.cpp +// Copyright (c) 2025-2026 MobileGL-Dev +// Licensed under the GNU Lesser General Public License v3.0: +// https://www.gnu.org/licenses/gpl-3.0.txt +// https://www.gnu.org/licenses/lgpl-3.0.txt +// SPDX-License-Identifier: LGPL-3.0-only +// End of Source File Header + +// The per-context record of texture storage sampled in the current offscreen draw batch. +#include +#include + +namespace { + using MobileGL::MG_Backend::DirectGLES::TextureImpl::DrawTextureReads; + + TEST(DrawTextureReads, RecordsOnlyOffscreenBatches) { + DrawTextureReads reads; + EXPECT_FALSE(reads.NeedsSamplerWalk(1, 1)) << "the window surface is not tracked"; + reads.NoteRead(3, 7); + EXPECT_FALSE(reads.WasRead(3, 7)); + + reads.BindFramebuffer(5); + EXPECT_TRUE(reads.NeedsSamplerWalk(1, 1)); + reads.NoteRead(3, 7); + EXPECT_TRUE(reads.WasRead(3, 7)); + EXPECT_FALSE(reads.WasRead(3, 8)) << "a recycled slot has a new generation"; + EXPECT_FALSE(reads.WasRead(4, 7)); + } + + TEST(DrawTextureReads, FramebufferChangesAndSwapsEndTheBatch) { + DrawTextureReads reads; + reads.BindFramebuffer(5); + reads.NoteRead(2, 1); + reads.BindFramebuffer(5); + EXPECT_TRUE(reads.WasRead(2, 1)) << "rebinding the same framebuffer keeps the batch"; + + reads.BindFramebuffer(6); + EXPECT_FALSE(reads.WasRead(2, 1)); + reads.NoteRead(2, 1); + reads.EndBatch(); + EXPECT_FALSE(reads.WasRead(2, 1)); + + reads.NoteRead(9, 4); + reads.DeleteFramebuffer(7); + EXPECT_TRUE(reads.WasRead(9, 4)) << "deleting another framebuffer changes nothing"; + reads.DeleteFramebuffer(6); + EXPECT_FALSE(reads.WasRead(9, 4)); + EXPECT_FALSE(reads.NeedsSamplerWalk(1, 1)); + } + + TEST(DrawTextureReads, SamplerWalkRepeatsOnlyWhenTheViewsChange) { + DrawTextureReads reads; + reads.BindFramebuffer(5); + reads.RecordSamplerWalk(1, 10); + EXPECT_FALSE(reads.NeedsSamplerWalk(1, 10)); + EXPECT_TRUE(reads.NeedsSamplerWalk(1, 11)); + EXPECT_TRUE(reads.NeedsSamplerWalk(2, 10)); + reads.EndBatch(); + EXPECT_TRUE(reads.NeedsSamplerWalk(1, 10)); + } +} // namespace diff --git a/MobileGL/MG_Test/Util/CMakeLists.txt b/MobileGL/MG_Test/Util/CMakeLists.txt index 0fd253cc..0b6fb635 100644 --- a/MobileGL/MG_Test/Util/CMakeLists.txt +++ b/MobileGL/MG_Test/Util/CMakeLists.txt @@ -142,3 +142,9 @@ gtest_discover_tests(LogLevelTest DISCOVERY_TIMEOUT 30 PROPERTIES LABELS unit) gtest_discover_tests(PipeStatsTest DISCOVERY_TIMEOUT 30 PROPERTIES LABELS unit) gtest_discover_tests(DamageTest DISCOVERY_TIMEOUT 30 PROPERTIES LABELS unit) gtest_discover_tests(ConfigFileTest DISCOVERY_TIMEOUT 30 PROPERTIES LABELS unit) + +# Sparse texture uploads: the packed staging page and the two-box split. +add_executable(TextureUploadPackingTest TextureUploadPackingTest.cpp) +target_include_directories(TextureUploadPackingTest PRIVATE ${MGL_ROOT}/include ${MGL_ROOT}/MobileGL) +target_link_libraries(TextureUploadPackingTest PRIVATE MobileGLTestMain ${LINK_LIBRARIES}) +gtest_discover_tests(TextureUploadPackingTest DISCOVERY_TIMEOUT 30 PROPERTIES LABELS unit) diff --git a/MobileGL/MG_Test/Util/TextureUploadPackingTest.cpp b/MobileGL/MG_Test/Util/TextureUploadPackingTest.cpp new file mode 100644 index 00000000..2674b855 --- /dev/null +++ b/MobileGL/MG_Test/Util/TextureUploadPackingTest.cpp @@ -0,0 +1,201 @@ +// MobileGL - MobileGL/MG_Test/Util/TextureUploadPackingTest.cpp +// Copyright (c) 2025-2026 MobileGL-Dev +// Licensed under the GNU Lesser General Public License v3.0: +// https://www.gnu.org/licenses/gpl-3.0.txt +// https://www.gnu.org/licenses/lgpl-3.0.txt +// SPDX-License-Identifier: LGPL-3.0-only +// End of Source File Header + +// The sparse texture upload helpers: the packed staging page and the two-box split. +#include +#include +#include + +#include +#include +#include +#include + +namespace { + namespace Packed = MobileGL::MG_Util::PackedTextureUpload; + namespace Boxes = MobileGL::MG_Util::TextureUploadBoxes; + + // A level shadow whose every texel names its own coordinates, so a copied row shows where + // it came from. + struct Level { + int width, height; + std::vector texels; + + Level(int w, int h) : width(w), height(h), texels(static_cast(w) * h * Packed::BytesPerTexel) { + for (int y = 0; y < h; ++y) { + for (int x = 0; x < w; ++x) { + std::uint8_t* texel = Texel(x, y); + texel[0] = static_cast(x); + texel[1] = static_cast(y); + texel[2] = static_cast(x >> 8); + texel[3] = static_cast(y >> 8); + } + } + } + + std::uint8_t* Texel(int x, int y) { + return texels.data() + (static_cast(y) * width + x) * Packed::BytesPerTexel; + } + + Packed::Region Region(int level, int x, int y, int w, int h) { + return {Texel(x, y), static_cast(width) * Packed::BytesPerTexel, level, x, y, w, h}; + } + }; + + void AddRegion(Packed::Batch& batch, const Packed::Region& region) { + batch.regions[batch.count++] = region; + } + + bool Overlap(const Packed::Point& a, const Packed::Region& ra, const Packed::Point& b, const Packed::Region& rb) { + return a.x < b.x + rb.width && b.x < a.x + ra.width && a.y < b.y + rb.height && b.y < a.y + ra.height; + } + + void ExpectValidLayout(const Packed::Batch& batch) { + ASSERT_GT(batch.width, 0); + ASSERT_GT(batch.height, 0); + EXPECT_LE(batch.width, Packed::PageSide); + EXPECT_LE(batch.height, Packed::PageSide); + for (std::size_t i = 0; i < batch.count; ++i) { + const auto& region = batch.regions[i]; + const auto& offset = batch.offsets[i]; + EXPECT_GE(offset.x, 0); + EXPECT_GE(offset.y, 0); + EXPECT_LE(offset.x + region.width, batch.width) << "region " << i; + EXPECT_LE(offset.y + region.height, batch.height) << "region " << i; + for (std::size_t j = i + 1; j < batch.count; ++j) { + EXPECT_FALSE(Overlap(offset, region, batch.offsets[j], batch.regions[j])) + << "regions " << i << " and " << j; + } + } + } + + TEST(PackedTextureUpload, PacksScatteredSpritesWithoutOverlap) { + Level mip0(512, 512); + Level mip1(256, 256); + Packed::Batch batch; + AddRegion(batch, mip0.Region(0, 0, 0, 16, 16)); + AddRegion(batch, mip0.Region(0, 480, 32, 32, 16)); + AddRegion(batch, mip0.Region(0, 200, 400, 16, 32)); + AddRegion(batch, mip0.Region(0, 300, 300, 64, 64)); + AddRegion(batch, mip1.Region(1, 8, 8, 8, 8)); + AddRegion(batch, mip1.Region(1, 240, 240, 16, 16)); + + ASSERT_TRUE(Packed::Pack(batch, 512ull * 512 + 256ull * 256)); + ExpectValidLayout(batch); + // Largest first, so the 64x64 sprite takes the page origin. + EXPECT_EQ(batch.regions[0].width * batch.regions[0].height, 64 * 64); + EXPECT_EQ(batch.offsets[0].x, 0); + EXPECT_EQ(batch.offsets[0].y, 0); + } + + TEST(PackedTextureUpload, WritePageCopiesEachRegionToItsOffset) { + Level mip0(512, 512); + Packed::Batch batch; + AddRegion(batch, mip0.Region(0, 3, 5, 7, 9)); + AddRegion(batch, mip0.Region(0, 400, 300, 20, 11)); + AddRegion(batch, mip0.Region(0, 260, 17, 13, 13)); + ASSERT_TRUE(Packed::Pack(batch, 512ull * 512)); + ExpectValidLayout(batch); + + std::vector page(batch.ByteSize(), 0xCD); + Packed::WritePage(batch, page.data()); + const std::size_t pitch = static_cast(batch.width) * Packed::BytesPerTexel; + for (std::size_t i = 0; i < batch.count; ++i) { + const auto& region = batch.regions[i]; + const auto& offset = batch.offsets[i]; + for (int y = 0; y < region.height; ++y) { + for (int x = 0; x < region.width; ++x) { + const std::uint8_t* texel = + page.data() + (offset.y + y) * pitch + (offset.x + x) * Packed::BytesPerTexel; + ASSERT_EQ(texel[0], static_cast(region.x + x)) << "region " << i; + ASSERT_EQ(texel[1], static_cast(region.y + y)) << "region " << i; + } + } + } + } + + TEST(PackedTextureUpload, DeclinesBatchesThatSaveTooLittle) { + Level mip0(512, 512); + Packed::Batch single; + AddRegion(single, mip0.Region(0, 0, 0, 16, 16)); + EXPECT_FALSE(Packed::Pack(single, 512ull * 512)) << "one region already uploads exactly"; + + Packed::Batch dense; + AddRegion(dense, mip0.Region(0, 0, 0, 16, 16)); + AddRegion(dense, mip0.Region(0, 16, 0, 16, 16)); + EXPECT_FALSE(Packed::Pack(dense, 32ull * 16)) << "the union box is already small"; + } + + TEST(PackedTextureUpload, DeclinesRegionsThatCannotFitThePage) { + Level mip0(512, 512); + Packed::Batch wide; + AddRegion(wide, mip0.Region(0, 0, 0, Packed::PageSide + 1, 4)); + AddRegion(wide, mip0.Region(0, 300, 300, 4, 4)); + EXPECT_FALSE(Packed::Pack(wide, 512ull * 512)); + + Packed::Batch full; + AddRegion(full, mip0.Region(0, 0, 0, Packed::PageSide, Packed::PageSide)); + AddRegion(full, mip0.Region(0, 256, 256, Packed::PageSide, Packed::PageSide)); + EXPECT_FALSE(Packed::Pack(full, 512ull * 512)) << "more dirty texels than one page holds"; + } + + TEST(PackedTextureUpload, PacksTheMaximumRegionCount) { + Level mip0(512, 512); + Packed::Batch batch; + for (std::size_t i = 0; i < Packed::MaxRegions; ++i) { + const int size = 8 + static_cast(i % 4) * 4; + AddRegion(batch, mip0.Region(0, static_cast(i) * 15, static_cast(i) * 15, size, size)); + } + ASSERT_TRUE(Packed::Pack(batch, 512ull * 512)); + ExpectValidLayout(batch); + } + + std::array Regions(std::initializer_list boxes) { + std::array regions{}; + std::size_t i = 0; + for (const auto& box : boxes) + regions[i++] = box; + return regions; + } + + bool Contains(const Boxes::Box& outer, const Boxes::Box& inner) { + return outer.left <= inner.left && outer.top <= inner.top && outer.right >= inner.right && + outer.bottom >= inner.bottom; + } + + TEST(TextureUploadBoxes, SplitsTwoSeparatedClusters) { + const Boxes::Box a{0, 0, 16, 16}, b{20, 4, 36, 20}, c{400, 300, 416, 316}, d{420, 330, 436, 346}; + auto regions = Regions({c, a, d, b}); + const Boxes::Box bounds{0, 0, 436, 346}; + const auto split = Boxes::Split(bounds, regions, 4); + ASSERT_TRUE(split.has_value()); + const auto& first = (*split)[0]; + const auto& second = (*split)[1]; + const bool firstHoldsLeft = Contains(first, a); + const auto& left = firstHoldsLeft ? first : second; + const auto& right = firstHoldsLeft ? second : first; + EXPECT_TRUE(Contains(left, a) && Contains(left, b)); + EXPECT_TRUE(Contains(right, c) && Contains(right, d)); + EXPECT_LE(first.Texels() + second.Texels(), bounds.Texels() / 2); + const bool disjoint = left.right <= right.left || left.bottom <= right.top; + EXPECT_TRUE(disjoint); + } + + TEST(TextureUploadBoxes, KeepsOneBoxWhenNoCutSeparatesTheRegions) { + // Overlapping regions along the diagonal: no cut on either axis separates two groups. + auto regions = Regions({{0, 0, 100, 100}, {90, 90, 190, 190}, {180, 180, 280, 280}}); + EXPECT_FALSE(Boxes::Split({0, 0, 280, 280}, regions, 3).has_value()); + } + + TEST(TextureUploadBoxes, SkipsSmallOrSingleRegionLevels) { + EXPECT_FALSE(Boxes::WorthSearching({0, 0, 32, 32}, 4)) << "a small level keeps one job"; + EXPECT_FALSE(Boxes::WorthSearching({0, 0, 512, 512}, 1)); + EXPECT_FALSE(Boxes::WorthSearching({0, 0, 512, 512}, Boxes::MaxRegions + 1)); + EXPECT_TRUE(Boxes::WorthSearching({0, 0, 512, 512}, 2)); + } +} // namespace From 6ad3d3f51950c2dbcf6a67e7540282e95959a358 Mon Sep 17 00:00:00 2001 From: Eurya0x13 Date: Thu, 26 Nov 2026 18:14:18 +0800 Subject: [PATCH 8/9] [Fix] (MG_Backend/DirectGLES): require raw RGBA8 for packed texture uploads - Check the shadow format before copying bytes into the staging texture. - Document the draw-batch scope of sampled-storage tracking. --- .../MG_Backend/DirectGLES/DrawTextureReads.h | 2 ++ .../DirectGLES/ManagersTextureSync.cpp | 18 +++++++++++------- 2 files changed, 13 insertions(+), 7 deletions(-) diff --git a/MobileGL/MG_Backend/DirectGLES/DrawTextureReads.h b/MobileGL/MG_Backend/DirectGLES/DrawTextureReads.h index ed695f17..d3242bb9 100644 --- a/MobileGL/MG_Backend/DirectGLES/DrawTextureReads.h +++ b/MobileGL/MG_Backend/DirectGLES/DrawTextureReads.h @@ -14,6 +14,8 @@ namespace MobileGL::MG_Backend::DirectGLES::TextureImpl { // One instance per native context. Slot generations distinguish reused texture names, // and batch stamps let us discard a batch without walking its texture slots. + // This upload heuristic follows sampler reads from offscreen draws and the framebuffer + // changes observed by BindCurrentFBO. Compute dispatches do not record reads here. class DrawTextureReads { public: void BindFramebuffer(std::uint32_t framebuffer) { diff --git a/MobileGL/MG_Backend/DirectGLES/ManagersTextureSync.cpp b/MobileGL/MG_Backend/DirectGLES/ManagersTextureSync.cpp index 3be2ee15..0c436723 100644 --- a/MobileGL/MG_Backend/DirectGLES/ManagersTextureSync.cpp +++ b/MobileGL/MG_Backend/DirectGLES/ManagersTextureSync.cpp @@ -1640,9 +1640,10 @@ namespace MobileGL::MG_Backend::DirectGLES { } const auto mipmapCount = MGB_STORAGE_LEVELS(textureMipmapObject); + const auto storageFormat = MGB_STORAGE_FORMAT(textureMipmapObject); GLenum glInternalFormat, glType, glFormat; - TextureImpl::GenerateTextureFormatInfo(MGB_STORAGE_FORMAT(textureMipmapObject), &glInternalFormat, - &glFormat, &glType, targetInternal); + TextureImpl::GenerateTextureFormatInfo(storageFormat, &glInternalFormat, &glFormat, &glType, + targetInternal); // The storage this level is being written into was widened when it was minted // (see above), so the transfer pair has to describe the carrier here too - ES // requires glTexSubImage's `format` to match the storage's base internal @@ -1652,15 +1653,18 @@ namespace MobileGL::MG_Backend::DirectGLES { ScopedDefaultUnpackState unpackState; // Update sampled storage directly to avoid stalling the current offscreen batch on a PBO. const Bool useClientUnpack = stableStorage && WasTextureReadInDrawBatch(pushedRes); + // The staging page copies the shadow bytes as-is. Check the shadow and driver + // formats because a driver format can also be used for converted client data. + const Bool rawRgba8Copy = storageFormat == TextureInternalFormat::RGBA8 && + glInternalFormat == GL_RGBA8 && glFormat == GL_RGBA && + glType == GL_UNSIGNED_BYTE; // Pack the small writes across all dirty mip levels before their // per-level union boxes can pull in untouched atlas texels. The packed // copies write the destination on the GPU too, so sampled storage skips them. if (stableStorage && !useClientUnpack && !m_driverMayHoldGpuWrites && !m_packedUploadRejected && - !m_imageBindableStorageRequired && target == GL_TEXTURE_2D && - (glInternalFormat == GL_RGBA8 || glInternalFormat == GL_RGBA) && glFormat == GL_RGBA && - glType == GL_UNSIGNED_BYTE && pushedStorage != nullptr && uploadTargets.size() == 1 && - g_GLESFuncs.glCopyImageSubData && g_GLESFuncs.glTexStorage2D && - BufferImpl::UnpackRingAvailable()) { + !m_imageBindableStorageRequired && target == GL_TEXTURE_2D && rawRgba8Copy && + pushedStorage != nullptr && uploadTargets.size() == 1 && g_GLESFuncs.glCopyImageSubData && + g_GLESFuncs.glTexStorage2D && BufferImpl::UnpackRingAvailable()) { const auto result = TryPackedMipUpload(textureMipmapObject, pushedStorage, pushedRes, uploadTargets.front(), mipmapCount, m_backendTextureId); if (result == PackedUploadResult::Rejected) { From 86471dfb807b11094f54b09353d521cd145fb1b4 Mon Sep 17 00:00:00 2001 From: Eurya0x13 Date: Thu, 26 Nov 2026 18:14:25 +0800 Subject: [PATCH 9/9] [Refactor] (MG_Impl/Pipe, MG_State/GLState): keep vertex-input memo hints in the emitter - Use a bounded slot hint table keyed by array lifetime. - Validate the lifetime and allocator epoch before reusing an entry. --- MobileGL/MG_Impl/Pipe/VertexInputEmit.h | 7 ++++--- .../MG_State/GLState/VertexArrayState/VertexArrayObject.h | 3 --- 2 files changed, 4 insertions(+), 6 deletions(-) diff --git a/MobileGL/MG_Impl/Pipe/VertexInputEmit.h b/MobileGL/MG_Impl/Pipe/VertexInputEmit.h index 388178f5..4960ad5f 100644 --- a/MobileGL/MG_Impl/Pipe/VertexInputEmit.h +++ b/MobileGL/MG_Impl/Pipe/VertexInputEmit.h @@ -487,9 +487,9 @@ namespace MobileGL::MG_Pipe { VaoMemo& MemoFor(const VertexArrayObject& vao) { const Uint64 lifetimeId = vao.GetLifetimeId(); const Uint64 epoch = MGPipeSlots().ResetEpoch(); - // A per-array hint survives switching arrays. Growth and erasure can move entries, - // so the slot is only a candidate until both identity and the allocator epoch match. - SizeT& hint = vao.PipeVertexInputMemoHint(); + // Keep recent slots in the emitter across array switches. Collisions, growth and + // erasure can stale a hint, so check the lifetime and epoch before using it. + SizeT& hint = m_vaoMemoHints[lifetimeId & (m_vaoMemoHints.size() - 1)]; if (hint < m_vaoMemo.size() && m_vaoMemo[hint].LifetimeId == lifetimeId && m_vaoMemo[hint].SlotEpoch == epoch) return m_vaoMemo[hint]; @@ -528,6 +528,7 @@ namespace MobileGL::MG_Pipe { } Vector m_vaoMemo; SizeT m_vaoMemoUsed = 0; + Array m_vaoMemoHints{}; public: // The VAO died (MGPipeEmitVertexElementsDestroyAndFree): its entry goes, by backward-shift diff --git a/MobileGL/MG_State/GLState/VertexArrayState/VertexArrayObject.h b/MobileGL/MG_State/GLState/VertexArrayState/VertexArrayObject.h index a6143268..97b176cb 100644 --- a/MobileGL/MG_State/GLState/VertexArrayState/VertexArrayObject.h +++ b/MobileGL/MG_State/GLState/VertexArrayState/VertexArrayObject.h @@ -69,8 +69,6 @@ namespace MobileGL { // DirectVulkan's VulkanRenderer). Uint64 GetLifetimeId() const { return m_lifetimeId; } - SizeT& PipeVertexInputMemoHint() const { return m_pipeVertexInputMemoHint; } - void SetAttributeDivisor(Uint index, Uint divisor); Uint GetAttributeDivisor(Uint index) const; @@ -136,7 +134,6 @@ namespace MobileGL { const Uint m_externalIndex = 0; const Uint64 m_lifetimeId = AllocateLifetimeId(); - mutable SizeT m_pipeVertexInputMemoHint = ~SizeT{0}; Array m_attributes; Array m_attributeVersions; BindingSlot m_indexBufferBindingSlot;