mirror of
https://github.com/MobileGL-Dev/MobileGL
synced 2026-11-26 19:22:16 +09:00
Compare commits
7
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
94d729c493 | ||
|
|
926e54e28c | ||
|
|
c025f9c4e8 | ||
|
|
99afafd7cf | ||
|
|
b897556750 | ||
|
|
639ae0f636 | ||
|
|
10deb9cea4 |
No files matched your search
@@ -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<MG_State::GLState::ProgramObject>& 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
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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<MG_State::GLState::ProgramObject>& 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<MG_State::GLState::ProgramObject>& currentProgram);
|
||||
|
||||
@@ -504,8 +504,8 @@ namespace MobileGL::MG_Backend::DirectGLES {
|
||||
void BindCurrentTextures();
|
||||
|
||||
void BindCurrentProgramWithResources(const SharedPtr<MG_State::GLState::ProgramObject>& 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();
|
||||
|
||||
|
||||
@@ -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
|
||||
@@ -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;
|
||||
@@ -639,6 +641,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<std::mutex> lock(g_nativeRegistryMutex);
|
||||
@@ -653,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<Uint32>(kFrameFenceRingDepth) &&
|
||||
g_GLESFuncs.glClientWaitSync && presentedSerial + 1 > framesInFlight) {
|
||||
@@ -660,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.
|
||||
|
||||
@@ -7,9 +7,50 @@
|
||||
// End of Source File Header
|
||||
|
||||
#include "DirectGLESInternal.h"
|
||||
#include "DrawTextureReads.h"
|
||||
|
||||
namespace MobileGL::MG_Backend::DirectGLES {
|
||||
namespace TextureImpl {
|
||||
namespace {
|
||||
PerNativeContext<DrawTextureReads> 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<SizeT>(static_cast<SizeT>(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
|
||||
|
||||
@@ -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 <cstdint>
|
||||
#include <vector>
|
||||
|
||||
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<std::size_t>(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<std::uint64_t> m_reads;
|
||||
};
|
||||
} // namespace MobileGL::MG_Backend::DirectGLES::TextureImpl
|
||||
@@ -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 <typename IssueDraw>
|
||||
inline void ForEachViewportRoutingPass(IssueDraw&& issue) {
|
||||
TextureImpl::NoteDrawTextureReads();
|
||||
const Uint passCount = BeginViewportRoutingPasses();
|
||||
for (Uint pass = 0; pass < passCount; ++pass) {
|
||||
if (passCount > 1) {
|
||||
@@ -1878,15 +1883,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
|
||||
@@ -2106,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();
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -7,6 +7,9 @@
|
||||
// End of Source File Header
|
||||
|
||||
#include "ManagersInternal.h"
|
||||
#include "DirectGLESInternal.h"
|
||||
#include <MG_Util/Texture/PackedTextureUpload.h>
|
||||
#include <MG_Util/Texture/TextureUploadBoxes.h>
|
||||
|
||||
namespace MobileGL::MG_Backend::DirectGLES {
|
||||
namespace TextureImpl {
|
||||
@@ -97,6 +100,149 @@ namespace MobileGL::MG_Backend::DirectGLES {
|
||||
return reinterpret_cast<const void*>(static_cast<std::uintptr_t>(offset));
|
||||
}
|
||||
|
||||
namespace {
|
||||
static Bool SplitMipUpload(const MG_Pipe::MGPipeResourceRecord::PendingUpload& pending,
|
||||
const IntVec3& levelSize, MG_State::GLState::MipmapDirtyRegion* boxes) {
|
||||
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<Uint>(levelSize.x() - bounds.X) ||
|
||||
bounds.H > static_cast<Uint>(levelSize.y() - bounds.Y)) {
|
||||
return false;
|
||||
}
|
||||
const Box unionBox{bounds.X, bounds.Y, bounds.X + static_cast<Int>(bounds.W),
|
||||
bounds.Y + static_cast<Int>(bounds.H)};
|
||||
if (!WorthSearching(unionBox, pending.Regions.size())) return false;
|
||||
std::array<Box, MaxRegions> 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<Uint>(unionBox.right - region.X) ||
|
||||
region.H > static_cast<Uint>(unionBox.bottom - region.Y)) {
|
||||
return false;
|
||||
}
|
||||
regions[i] = {region.X, region.Y, region.X + static_cast<Int>(region.W),
|
||||
region.Y + static_cast<Int>(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<PackedUploadPage, 4> pages;
|
||||
|
||||
void ForgetContext(Uint64 context) override {
|
||||
const std::lock_guard<std::mutex> 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 MG_Util::PackedTextureUpload::Batch& batch,
|
||||
GLuint destination, Uint64 unionTexels) {
|
||||
const Uint64 context = CurrentNativeContextSerial();
|
||||
if (context == 0) return PackedUploadResult::Unavailable;
|
||||
static PackedUploadPages pool;
|
||||
const std::unique_lock<std::mutex> 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<Uint8*>(BufferImpl::UnpackRingMappedPtr());
|
||||
MG_Util::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, 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) {
|
||||
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<unsigned long long>(unionTexels * MG_Util::PackedTextureUpload::BytesPerTexel));
|
||||
return PackedUploadResult::Committed;
|
||||
}
|
||||
} // namespace
|
||||
|
||||
static Uint GetNormFallbackComponentCount(TextureInternalFormat format) {
|
||||
switch (format) {
|
||||
case TextureInternalFormat::R8Snorm:
|
||||
@@ -755,6 +901,69 @@ namespace MobileGL::MG_Backend::DirectGLES {
|
||||
(pushedStorage != nullptr ? static_cast<TextureStorageType>(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 MG_Util::PackedTextureUpload;
|
||||
Batch batch;
|
||||
Uint64 unionTexels = 0;
|
||||
const auto targetCode = static_cast<Uint16>(uploadTarget);
|
||||
for (SizeT level = 0; level < mipmapCount; ++level) {
|
||||
const auto levelCode = static_cast<Uint16>(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<Uint64>(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<const Uint8*>(
|
||||
MGB_LEVEL_TEXELS(textureMipmapObject, uploadTarget, level, "packed-dirty-level"));
|
||||
if (pixels == nullptr) return PackedUploadResult::Unavailable;
|
||||
const SizeT pitch = static_cast<SizeT>(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<Uint>(size.x() - region.X) ||
|
||||
region.H > static_cast<Uint>(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<int>(level),
|
||||
region.X,
|
||||
region.Y,
|
||||
static_cast<int>(region.W),
|
||||
static_cast<int>(region.H)};
|
||||
}
|
||||
unionTexels += static_cast<Uint64>(pending->UnionBox.W) * pending->UnionBox.H;
|
||||
}
|
||||
|
||||
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<Uint16>(level)) != nullptr) {
|
||||
MGB_LEVEL_UPLOAD_DONE(textureMipmapObject, uploadTarget, level);
|
||||
}
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
void BackendTextureObject::SyncMipmapsToBackend(
|
||||
const SharedPtr<MG_State::GLState::ITextureObject>& stateTextureObject) {
|
||||
// P5e (tx2): null IS the by-handle arm once a handle has been noted on this twin;
|
||||
@@ -1038,7 +1247,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 +1650,26 @@ 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. 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()) {
|
||||
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<MG_State::GLState::MipmapDirtyRegion> dirtyFootprint;
|
||||
Vector<UnpackStagingBlock> stagingBlockOverflow;
|
||||
@@ -1707,7 +1938,9 @@ 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();
|
||||
// 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
|
||||
@@ -1751,23 +1984,26 @@ 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;
|
||||
}
|
||||
}
|
||||
// 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.
|
||||
// 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 && !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<SizeT>(texelSize.x()) * bpp &&
|
||||
levelSliceBytes == static_cast<SizeT>(texelSize.y()) * levelRowBytes &&
|
||||
pendingUpload != nullptr &&
|
||||
(!MGB_STAGED_TEXTURE_LIVE ||
|
||||
MG_Record::ServerStagedTexture().IsCovered(
|
||||
MG_Record::StagedTextureStore::KeyForHandle(pushedRes),
|
||||
static_cast<Uint16>(uploadTarget), static_cast<Uint16>(level))) &&
|
||||
SplitMipUpload(*pendingUpload, texelSize, dirtyRects);
|
||||
if (splitBoxUpload) dirtyRectCount = 2;
|
||||
// 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) {
|
||||
@@ -1816,19 +2052,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<SizeT>(idx) < pendingUpload->Regions.size()) \
|
||||
? static_cast<const Uint8*>(uploadData) + \
|
||||
static_cast<SizeT>(pendingUpload->Regions[static_cast<SizeT>(idx)].SrcOffset) \
|
||||
@@ -1864,8 +2096,7 @@ 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) {
|
||||
if (!ringUsable || useClientUnpack) {
|
||||
// Nothing to plan: every branch below keeps the client
|
||||
// pointer and its ROW_LENGTH striding, unchanged.
|
||||
} else if (perRectUpload) {
|
||||
@@ -1925,11 +2156,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<Uint64>(rect.hi.x() - rect.lo.x()) *
|
||||
static_cast<Uint64>(rect.hi.y() - rect.lo.y()) *
|
||||
static_cast<Uint64>(std::max(rect.hi.z() - rect.lo.z(), 1)) *
|
||||
@@ -1940,7 +2171,7 @@ namespace MobileGL::MG_Backend::DirectGLES {
|
||||
static_cast<Uint64>(regionSize.x()) * static_cast<Uint64>(regionSize.y()) *
|
||||
static_cast<Uint64>(std::max(regionSize.z(), 1)) * static_cast<Uint64>(bpp);
|
||||
} else {
|
||||
shippedBytes = static_cast<Uint64>(byteSize);
|
||||
shippedBytes = static_cast<Uint64>(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 +2180,7 @@ namespace MobileGL::MG_Backend::DirectGLES {
|
||||
: MG_Util::PipeStats::CallClass::TextureUploadBoxEmissions,
|
||||
1);
|
||||
MG_Util::PipeStats::AddCalls(MG_Util::PipeStats::CallClass::TextureUploadJobs,
|
||||
rectShape ? static_cast<Uint64>(dirtyRectCount) : 1u);
|
||||
rectShape ? static_cast<Uint64>(uploadRectCount) : 1u);
|
||||
}
|
||||
switch (MapToBackendTextureTarget(MGB_TEXTURE_TARGET(stateTextureObject))) {
|
||||
case TextureTarget::Texture2D:
|
||||
|
||||
@@ -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<VaoMemo> m_vaoMemo;
|
||||
SizeT m_vaoMemoUsed = 0;
|
||||
SizeT m_lastMemoIndex = ~SizeT{0};
|
||||
|
||||
public:
|
||||
// The VAO died (MGPipeEmitVertexElementsDestroyAndFree): its entry goes, by backward-shift
|
||||
|
||||
@@ -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<VertexAttribute, MAX_VERTEX_ATTRIBS> m_attributes;
|
||||
Array<VertexAttributeVersion, MAX_VERTEX_ATTRIBS> m_attributeVersions;
|
||||
BindingSlot<BufferObject> m_indexBufferBindingSlot;
|
||||
|
||||
@@ -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).
|
||||
|
||||
@@ -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 <gtest/gtest.h>
|
||||
#include <MG_Backend/DirectGLES/DrawTextureReads.h>
|
||||
|
||||
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
|
||||
@@ -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)
|
||||
@@ -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 <gtest/gtest.h>
|
||||
#include <MG_Util/Texture/PackedTextureUpload.h>
|
||||
#include <MG_Util/Texture/TextureUploadBoxes.h>
|
||||
|
||||
#include <array>
|
||||
#include <cstdint>
|
||||
#include <initializer_list>
|
||||
#include <vector>
|
||||
|
||||
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<std::uint8_t> texels;
|
||||
|
||||
Level(int w, int h) : width(w), height(h), texels(static_cast<std::size_t>(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<std::uint8_t>(x);
|
||||
texel[1] = static_cast<std::uint8_t>(y);
|
||||
texel[2] = static_cast<std::uint8_t>(x >> 8);
|
||||
texel[3] = static_cast<std::uint8_t>(y >> 8);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
std::uint8_t* Texel(int x, int y) {
|
||||
return texels.data() + (static_cast<std::size_t>(y) * width + x) * Packed::BytesPerTexel;
|
||||
}
|
||||
|
||||
Packed::Region Region(int level, int x, int y, int w, int h) {
|
||||
return {Texel(x, y), static_cast<std::size_t>(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<std::uint8_t> page(batch.ByteSize(), 0xCD);
|
||||
Packed::WritePage(batch, page.data());
|
||||
const std::size_t pitch = static_cast<std::size_t>(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<std::uint8_t>(region.x + x)) << "region " << i;
|
||||
ASSERT_EQ(texel[1], static_cast<std::uint8_t>(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<int>(i % 4) * 4;
|
||||
AddRegion(batch, mip0.Region(0, static_cast<int>(i) * 15, static_cast<int>(i) * 15, size, size));
|
||||
}
|
||||
ASSERT_TRUE(Packed::Pack(batch, 512ull * 512));
|
||||
ExpectValidLayout(batch);
|
||||
}
|
||||
|
||||
std::array<Boxes::Box, Boxes::MaxRegions> Regions(std::initializer_list<Boxes::Box> boxes) {
|
||||
std::array<Boxes::Box, Boxes::MaxRegions> 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
|
||||
@@ -0,0 +1,147 @@
|
||||
// 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
|
||||
// https://www.gnu.org/licenses/lgpl-3.0.txt
|
||||
// SPDX-License-Identifier: LGPL-3.0-only
|
||||
// End of Source File Header
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <algorithm>
|
||||
#include <array>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <cstring>
|
||||
|
||||
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;
|
||||
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<Region, MaxRegions> regions;
|
||||
std::array<Point, MaxRegions> 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<Rect, MaxRegions + 1> 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_Util::PackedTextureUpload
|
||||
@@ -0,0 +1,68 @@
|
||||
// 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
|
||||
// https://www.gnu.org/licenses/lgpl-3.0.txt
|
||||
// SPDX-License-Identifier: LGPL-3.0-only
|
||||
// End of Source File Header
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <algorithm>
|
||||
#include <array>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <optional>
|
||||
|
||||
namespace MobileGL::MG_Util::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<std::uint64_t>(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 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;
|
||||
}
|
||||
|
||||
// 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<std::array<Box, 2>> Split(Box bounds, std::array<Box, MaxRegions>& 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<std::array<Box, 2>> best;
|
||||
std::array<Box, MaxRegions> 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<Box, 2>{prefix, rest};
|
||||
}
|
||||
prefix = Union(prefix, regions[i]);
|
||||
}
|
||||
}
|
||||
return best;
|
||||
}
|
||||
} // namespace MobileGL::MG_Util::TextureUploadBoxes
|
||||
Reference in new issue
Block a user