Compare commits

..
10 Commits
Author SHA1 Message Date
swung0x48 4322427e78 [Fix] (DirectGLES): lower gl_ClipDistance for Adreno's ESSL compiler - shadow the builtin in a Private array with constant-index flushes before EmitVertex/return, loop-copy gl_in clip distances through dynamic indices (whole-array reads segfault the Qualcomm compiler, constant-index element reads miscompile), strip the SPIRV-Cross redeclaration Adreno rejects, and split const struct-array LUT initializers so they stay dynamically indexable; quirk-gated to Qualcomm with MOBILEGL_QUIRK_CLIP_DISTANCE override 2026-07-26 19:56:45 -04:00
swung0x48 203d4bce5e [Fix] (DirectGLES): piglit fixes batch 1 - keep enabled-but-unsourceable vertex attribs disabled on the backend VAO (Adreno memcpy-from-NULL SIGSEGV on gl-3.1-vao-broken-attrib), content-sync READ-framebuffer texture attachments before blits, clamp out-of-bounds access-chain indices via GraphicsRobustAccessPass before ESSL transpile (Adreno poisons whole-shader output on constant OOB), and fold ConstOffset into the coordinate for 1D texelFetch (SPIRV-Cross emulates 1D as 2D but leaves the scalar offset, which ESSL rejects) 2026-07-26 19:17:25 -04:00
swung0x48 761114d022 Merge remote-tracking branch 'origin/cts-gl33' into dev 2026-07-26 18:29:02 -04:00
swung0x48 9caf34d5b1 [Fix] (Logging): rank WARN/ERROR above INFO so release builds keep them - the old ordering (DEBUG=0, WARN=1, ERROR=2, INFO=3) compiled every MGLOG_W/MGLOG_E out of the default MOBILEGL_LOG_LEVEL_INFO build, silently hiding backend shader-compile failures, unsupported-path skips, and enum-conversion fallbacks during the piglit runs 2026-07-26 18:14:56 -04:00
swung0x48 5e676b338b [Fix] (DirectVulkan): back legacy low-bit formats (RGB565/RGB5A1/RGBA4/R3G3B2/RGB4/RGBA2/RGB10/12) with their UNorm8/16 canonical shadow layouts and add capability fallbacks - they mapped to VK_FORMAT_UNDEFINED and crashed or wedged the GPU on upload; also admit 2DMSArray/CubeMap/3D color attachment targets in the render pass 2026-07-26 13:28:30 -04:00
swung0x48 db01bfa3e8 [Fix] (DirectVulkan): general (format,type) readback conversion - hoist the CTS-verified StoreWideRowsToClient into shared ReadbackImpl and decode any color VkFormat to wide RGBA rows; readback previously supported only RGB/BGR/RGBA/BGRA x UNSIGNED_BYTE/FLOAT and silently returned zeros for everything else 2026-07-26 13:28:30 -04:00
swung0x48 cc3dcfd80e [Fix] (DirectVulkan): support UBO instance arrays as arrayed descriptors - uniform Block{...}b[N] reflected as one binding with descriptorCount=N, per-element GL block mapping, per-element buffer infos and dynamic offsets; non-UBO descriptor arrays now fail program creation cleanly instead of continuing corrupt 2026-07-26 12:25:24 -04:00
swung0x48 d9556ff041 [Fix] (DirectVulkan): implement color renderbuffer attachments - render pass/pipeline/blit/copy/readback/clear paths treated color renderbuffers as absent (writes masked to VK_ATTACHMENT_UNUSED, glClear dropped, readback zeros) 2026-07-26 11:30:54 -04:00
swung0x48 39f21e52ea [Test] (CTS): isolate the DirectVulkan renderbuffer-FBO readback defect so the rest of KHR-GL33 can be measured 2026-07-26 10:43:48 -04:00
swung0x48 0e933b8f2f [Test] (CTS): run VK-GL-CTS KHR-GL33 against MobileGL on Android via a standalone glcts binary 2026-07-26 08:05:02 -04:00
58 changed files with 1379 additions and 1426 deletions
+3 -14
View File
@@ -194,6 +194,9 @@ set(SOURCE_FILES
MobileGL/MG_Util/ShaderTranspiler/SpirvPasses/StripUboMemberRelaxedPrecisionPass.cpp
MobileGL/MG_Util/ShaderTranspiler/SpirvPasses/StripNoPerspectivePass.cpp
MobileGL/MG_Util/ShaderTranspiler/SpirvPasses/EmulateNoPerspectivePass.cpp
MobileGL/MG_Util/ShaderTranspiler/SpirvPasses/FoldConstOffsetFor1DFetchPass.cpp
MobileGL/MG_Util/ShaderTranspiler/SpirvPasses/LowerClipDistanceForEsslPass.cpp
MobileGL/MG_Util/ShaderTranspiler/SpirvPasses/DefeatConstStructArrayLutPass.cpp
MobileGL/MG_Util/BackendLoaders/OpenGL/Loader.cpp
MobileGL/MG_Util/BackendLoaders/Vulkan/Loader.cpp
@@ -455,21 +458,8 @@ if (ANDROID)
endif()
if (APPLE AND NOT MOBILEGL_IOS)
# MobileGL statically embeds glslang, SPIRV-Tools, and SPIRV-Cross. When
# this dylib is injected with DYLD_INSERT_LIBRARIES, exporting those C++
# symbols interposes incompatible copies embedded by host libraries such
# as shaderc. Keep only the public GL/EGL/CGL loader surface globally
# visible; GetProcAddress can still return pointers to hidden internals.
set(MOBILEGL_MACOS_EXPORTED_SYMBOLS
"${CMAKE_CURRENT_SOURCE_DIR}/MobileGL/MG_Impl/DyldInterpose/ExportedSymbols.txt")
target_link_options(${CMAKE_PROJECT_NAME} PRIVATE
"LINKER:-exported_symbols_list,${MOBILEGL_MACOS_EXPORTED_SYMBOLS}")
set_property(TARGET ${CMAKE_PROJECT_NAME} APPEND PROPERTY
LINK_DEPENDS "${MOBILEGL_MACOS_EXPORTED_SYMBOLS}")
target_link_libraries(${CMAKE_PROJECT_NAME} PUBLIC
"-framework Cocoa"
"-framework CoreVideo"
"-framework QuartzCore"
"-framework Foundation"
"-framework OpenGL"
@@ -477,7 +467,6 @@ if (APPLE AND NOT MOBILEGL_IOS)
if(TARGET ${CMAKE_PROJECT_NAME}_s)
target_link_libraries(${CMAKE_PROJECT_NAME}_s PUBLIC
"-framework Cocoa"
"-framework CoreVideo"
"-framework QuartzCore"
"-framework Foundation"
"-framework OpenGL"
+5
View File
@@ -80,6 +80,11 @@ namespace MobileGL::MG_Config {
// rewrites the recognized workgroup prefix-scan template on Qualcomm devices with
// subgroups wider than 32 lanes (see ShaderSourceProcessor's quirk registry).
QuirkOverride SubgroupPrefixScanQuirk = QuirkOverride::Auto;
// MOBILEGL_QUIRK_CLIP_DISTANCE: overrides the DirectGLES quirk that lowers
// gl_ClipDistance for Adreno's ESSL compiler (shadow Private arrays with
// constant-index builtin flushes, dynamic-index gl_in copy loop, redeclaration
// strip, and const struct-array LUT splitting). Auto detects Qualcomm.
QuirkOverride ClipDistanceQuirk = QuirkOverride::Auto;
// MOBILEGL_MAGMA_DISABLE_BLENDED_DEPTH_WRITE: overrides the DirectVulkan quirk that
// strips depth writes from accumulation-blended pipelines (MIN/MAX or additive
// ONE+ONE - the multi-pass depth-equality signature) on drivers without
+1
View File
@@ -135,6 +135,7 @@ namespace MobileGL::MG_ConfigLoader {
features.DisableUboRing = QueryEnvFlag("MOBILEGL_DISABLE_UBO_RING");
features.RelaxedSemantics = QueryEnvFlag("MOBILEGL_RELAXED_SEMANTICS");
features.SubgroupPrefixScanQuirk = QueryEnvQuirkOverride("MOBILEGL_QUIRK_SUBGROUP_PREFIX_SCAN");
features.ClipDistanceQuirk = QueryEnvQuirkOverride("MOBILEGL_QUIRK_CLIP_DISTANCE");
features.MagmaDisableBlendedDepthWriteQuirk =
QueryEnvQuirkOverride("MOBILEGL_MAGMA_DISABLE_BLENDED_DEPTH_WRITE");
features.DisableRobustBufferAccess = QueryEnvFlag("MOBILEGL_DISABLE_ROBUST_BUFFER_ACCESS");
+4 -13
View File
@@ -14,7 +14,6 @@
#include <MG_State/EGLState/Core.h>
#include <MG_Impl/GLImpl/Texture/ProxyTexture.h>
#include <MG_Impl/GLImpl/Framebuffer/GL_Framebuffer.h>
#include <MG_Impl/GLImpl/Sync/GL_Sync.h>
#include <atomic>
#include <mutex>
@@ -38,12 +37,6 @@ namespace MobileGL {
MGLOG_I("MobileGL closing...");
}
glslang::FinalizeProcess();
// GL syncs die with their contexts, and every context is gone by the
// time full teardown runs: drain the live-sync registry while the
// backend function table can still release the backend handles (and
// before a re-initialized library could pair them with the wrong
// backend's DeleteSync).
MG_Impl::GLImpl::DestroyAllSyncObjects();
MG_Backend::pActiveBackendObject.reset();
MG_State::pGLContext.reset();
MG_State::pEGLContext.reset();
@@ -107,11 +100,9 @@ namespace MobileGL {
// (EGL/WGL/CGL): initialization happens lazily on the first entry point
// via EnsureInitialized(), and full teardown happens deterministically
// when the last EGL display is terminated with nothing current (EGLImpl
// calls Destroy()). There is intentionally no backend-initializing static
// constructor, no static destructor, and no DllMain: the global singletons
// use leak-at-exit storage (see GlobalObjects.cpp), so a process that exits
// calls Destroy()). There is intentionally no static constructor, no
// static destructor, and no DllMain: the global singletons use
// leak-at-exit storage (see GlobalObjects.cpp), so a process that exits
// without eglTerminate simply leaks them to the OS instead of running
// backend destructors during static teardown. macOS has a lightweight
// dyld constructor that installs NSOpenGL dispatch hooks only; full backend
// initialization still enters here from the first hooked CGL context.
// backend destructors during static teardown.
} // namespace MobileGL
+3 -4
View File
@@ -13,10 +13,9 @@ namespace MobileGL {
void Initialize();
// Thread-safe, idempotent, and re-entrant wrapper around Initialize().
// Host layers (EGL/WGL/CGL entry points) call this lazily on first use so
// full backend initialization never depends on ELF/DLL static constructors,
// and so a fresh init can follow a full Destroy() (e.g. after the last
// eglTerminate). The macOS dyld bootstrap installs only lightweight
// NSOpenGL method hooks.
// MobileGL's lifecycle never depends on ELF/DLL static constructors, and
// so a fresh init can follow a full Destroy() (e.g. after the last
// eglTerminate).
void EnsureInitialized();
void Destroy();
@@ -449,6 +449,20 @@ namespace MobileGL::MG_Backend::DirectGLES {
}
}
}
// Textures attached only to the READ framebuffer (blit / ReadPixels sources) need
// their content synced too, or the backend reads stale texel data.
const auto& readFBO =
MG_State::pGLContext->GetFramebufferBindingSlot(FramebufferTarget::Read).GetBoundObject();
if (readFBO && readFBO != currentFBO) {
for (const auto& attachment : readFBO->GetAllAttachmentObjects()) {
if (!attachment.IsTexture()) continue;
auto& textureObject = attachment.GetTexture();
if (textureObject) {
SyncTextureObjectToBackend(textureObject);
}
}
}
}
static Bool SupportsLayeredImageBinding(TextureTarget target) {
+104 -2
View File
@@ -1262,15 +1262,31 @@ namespace MobileGL::MG_Backend::DirectGLES {
const auto& allAttributes = stateVAOObject->GetAllAttributes();
for (Uint attribIndex = 0; attribIndex < allAttributes.size(); ++attribIndex) {
const auto& attrib = allAttributes[attribIndex];
const Uint32 attribBit = 1u << attribIndex;
// An enabled attrib with neither a buffer object nor a client pointer has no
// source; GL tolerates the state (only draws consuming it are undefined), but
// Adreno's ES driver memcpys the "client array" from address 0 at draw time
// (SIGSEGV). Keep such attribs disabled on the backend VAO and re-enable them
// the moment they gain a source - the mask-vs-current compare below triggers
// the enable even when only the Buffer/Format versions changed.
const Bool unsourceable = attrib.Enabled && !attrib.Buffer && attrib.Offset == 0;
const Bool wasForceDisabled = (m_forceDisabledAttribsMask & attribBit) != 0;
Bool needsSyncSwitch = allAttributeVersions[attribIndex].SwitchVersion !=
m_syncedAttributeVersions[attribIndex].SwitchVersion;
if (needsSyncSwitch) {
if (attrib.Enabled) {
if (needsSyncSwitch || unsourceable != wasForceDisabled) {
if (attrib.Enabled && !unsourceable) {
g_GLESFuncs.glEnableVertexAttribArray(attribIndex);
} else {
g_GLESFuncs.glDisableVertexAttribArray(attribIndex);
}
}
if (unsourceable) {
m_forceDisabledAttribsMask |= attribBit;
} else {
m_forceDisabledAttribsMask &= ~attribBit;
}
Bool needsSyncFormat = allAttributeVersions[attribIndex].FormatVersion !=
m_syncedAttributeVersions[attribIndex].FormatVersion;
@@ -1278,7 +1294,17 @@ namespace MobileGL::MG_Backend::DirectGLES {
m_syncedAttributeVersions[attribIndex].BufferVersion;
if (!needsSyncFormat && !needsSyncBuffer) continue;
if (unsourceable) continue;
// Client-side array with a non-null pointer: the pointer is uploaded and applied
// per draw by SyncClientSideAttributesForDrawArrays.
if (!attrib.Buffer) continue;
if (!BindAttributeBuffer(attrib)) {
if (attrib.Enabled) {
g_GLESFuncs.glDisableVertexAttribArray(attribIndex);
m_forceDisabledAttribsMask |= attribBit;
}
continue;
}
@@ -3265,6 +3291,19 @@ namespace MobileGL::MG_Backend::DirectGLES {
}
auto& shaderSpirvs = stateProgramObject->GetGeneratedSpirv();
// Adreno's ESSL compiler mishandles gl_ClipDistance (rejects redeclarations,
// miscompiles non-constant-index writes and constant-index gl_in element reads,
// crashes on whole-array gl_in reads) and cannot dynamically index the global
// const struct[] LUTs SPIRV-Cross likes to emit. Gate the workarounds to
// Qualcomm; MOBILEGL_QUIRK_CLIP_DISTANCE overrides the device detection.
const MG_Config::QuirkOverride clipDistanceQuirkOverride =
MG_Config::Features.ClipDistanceQuirk;
const Bool applyClipDistanceQuirk =
clipDistanceQuirkOverride == MG_Config::QuirkOverride::ForceOn ||
(clipDistanceQuirkOverride == MG_Config::QuirkOverride::Auto &&
pActiveBackendObject &&
pActiveBackendObject->GetDynamicParameters().GpuVendor == GpuVendorKind::Qualcomm);
for (int index = 0; index < attachedShaders.size(); ++index) {
auto& shader = attachedShaders[index];
GLenum glShaderType = MG_Util::ConvertShaderStageToGLEnum(shader->GetShaderStage());
@@ -3287,6 +3326,63 @@ namespace MobileGL::MG_Backend::DirectGLES {
effectiveSpirv = &loweredSpirv;
}
// GL 3.3 only promises undefined *values* for out-of-bounds array indexing, but
// Adreno's ESSL compiler constant-folds a provably out-of-bounds local-array
// index into poison that corrupts the whole shader's output. Clamp every
// access-chain index to its declared bounds before transpiling.
Vector<unsigned int> clampedSpirv;
if (MG_Util::ShaderTranspiler::ShaderCompiler::ClampAccessChainIndicesForEssl(*effectiveSpirv,
clampedSpirv) &&
!clampedSpirv.empty()) {
effectiveSpirv = &clampedSpirv;
} else {
MGLOG_W("ClampAccessChainIndicesForEssl failed, continuing with unclamped SPIR-V.");
}
// SPIRV-Cross emulates 1D samplers as 2D for ES: it widens texelFetch coordinates
// to ivec2 but keeps the ConstOffset operand scalar, which is not a valid ESSL
// texelFetchOffset overload (Adreno rejects it). Fold the constant offset into the
// coordinate instead (texelFetchOffset(t,P,l,o) == texelFetch(t,P+o,l)).
Vector<unsigned int> foldedOffsetSpirv;
if (MG_Util::ShaderTranspiler::ShaderCompiler::FoldConstOffsetFor1DFetchForEssl(
*effectiveSpirv, foldedOffsetSpirv) &&
!foldedOffsetSpirv.empty()) {
effectiveSpirv = &foldedOffsetSpirv;
} else {
MGLOG_W("FoldConstOffsetFor1DFetchForEssl failed, continuing with unfolded SPIR-V.");
}
// Adreno quirk: shadow gl_ClipDistance in Private arrays so the transpiled
// ESSL only writes the builtin with literal constant indices (flushed before
// EmitVertex/return) and only reads gl_in clip distances through dynamic loop
// indices - the shapes this driver compiles correctly. Must run after the
// access-chain clamp above so the flush indices stay literal constants.
Vector<unsigned int> clipDistanceSpirv;
if (applyClipDistanceQuirk &&
(glShaderType == GL_VERTEX_SHADER || glShaderType == GL_GEOMETRY_SHADER)) {
if (MG_Util::ShaderTranspiler::ShaderCompiler::LowerClipDistanceForEssl(
*effectiveSpirv, clipDistanceSpirv) &&
!clipDistanceSpirv.empty()) {
effectiveSpirv = &clipDistanceSpirv;
} else {
MGLOG_W("LowerClipDistanceForEssl failed, continuing with unlowered SPIR-V.");
}
}
// Adreno quirk: split single constant-composite stores of struct arrays so
// SPIRV-Cross does not promote them to global const struct[] LUTs, which this
// driver cannot dynamically index ("Cannot offset into the structure").
Vector<unsigned int> structLutSpirv;
if (applyClipDistanceQuirk) {
if (MG_Util::ShaderTranspiler::ShaderCompiler::DefeatConstStructArrayLutForEssl(
*effectiveSpirv, structLutSpirv) &&
!structLutSpirv.empty()) {
effectiveSpirv = &structLutSpirv;
} else {
MGLOG_W("DefeatConstStructArrayLutForEssl failed, continuing with unsplit SPIR-V.");
}
}
// ESSL stage-matches uniform blocks by member precision, but SPIRV-Cross prints
// a RelaxedPrecision member as explicit "mediump" in the vertex stage and as
// UNQUALIFIED (mediump-by-default) in the fragment stage; after
@@ -3345,6 +3441,12 @@ namespace MobileGL::MG_Backend::DirectGLES {
source = RebindImageUniformsToFrontendUnits(std::move(source), stateProgramObject);
source = RemoveLayoutBinding(source);
if (applyClipDistanceQuirk) {
// Adreno rejects the gl_ClipDistance redeclaration SPIRV-Cross still emits
// ("reserved built-in name") but accepts plain usage with
// GL_EXT_clip_cull_distance required; drop the line, keep the #extension.
source = RemoveClipDistanceRedeclaration(source);
}
source = ProcessOutColorLocations(source);
source = ForceFlatIntegerVaryings(source, glShaderType);
source = EmulateBaseInstanceInVertexShader(std::move(source), glShaderType);
@@ -258,6 +258,11 @@ namespace MobileGL::MG_Backend::DirectGLES {
private:
Uint m_backendVAOId = 0;
Array<Uint, MG_State::GLState::VertexArrayObject::MAX_VERTEX_ATTRIBS> m_clientAttributeBufferIds;
// Attribs the frontend has Enabled but that have no source at all (no buffer object
// and NULL client pointer). GL keeps such attribs latently enabled, but Adreno's ES
// driver treats them as client arrays and memcpys from address 0 at draw time
// (SIGSEGV), so they are kept disabled on the backend VAO until they gain a source.
Uint32 m_forceDisabledAttribsMask = 0;
Bool m_isInitialized = false;
Uint16 m_syncedIndexBufferVersion = 0;
Array<MG_State::GLState::VertexAttributeVersion, MG_State::GLState::VertexArrayObject::MAX_VERTEX_ATTRIBS>
+35
View File
@@ -342,6 +342,41 @@ namespace MobileGL::MG_Backend::DirectGLES {
}
return result;
}
String RemoveClipDistanceRedeclaration(const String& glslCode) {
#ifdef TRACY_ENABLE
ZoneScopedC(TRACY_ZONECOLOR_BACKEND);
#endif
// Adreno rejects any redeclaration of gl_ClipDistance/gl_CullDistance ("reserved
// built-in name") even with GL_EXT_clip_cull_distance required, but accepts plain
// usage of the builtin. Drop the desktop-style redeclaration line SPIRV-Cross
// prints; the "#extension GL_EXT_clip_cull_distance : require" line stays.
static const std::regex redeclarationRegex(
R"(^\s*(?:out|in)\s+(?:(?:high|medium|low)p\s+)?float\s+gl_(?:Clip|Cull)Distance\[[0-9]+\];\s*$)");
String result;
result.reserve(glslCode.size());
SizeT lineStart = 0;
Bool firstLine = true;
while (lineStart <= glslCode.size()) {
SizeT lineEnd = glslCode.find('\n', lineStart);
const Bool lastLine = lineEnd == String::npos;
String line = glslCode.substr(lineStart, lastLine ? String::npos : lineEnd - lineStart);
if (!std::regex_match(line, redeclarationRegex)) {
if (!firstLine) {
result += '\n';
}
result += line;
firstLine = false;
}
if (lastLine) {
break;
}
lineStart = lineEnd + 1;
}
return result;
}
} // namespace PrgramImpl
namespace Utils {
+1
View File
@@ -105,6 +105,7 @@ namespace MobileGL::MG_Backend::DirectGLES {
Uint32 unormOutputMask);
String ForceFlatIntegerVaryings(const String& glslCode, GLenum shaderType);
String RemoveLayoutBinding(const String& glslCode);
String RemoveClipDistanceRedeclaration(const String& glslCode);
} // namespace PrgramImpl
namespace Utils {
@@ -469,9 +469,6 @@ namespace MobileGL::MG_Backend::DirectVulkan {
// treat them as signaled/available with zero results from here on.
BumpRendererGeneration();
pVulkanRenderer.reset();
// The reflection cache is file-scope, not renderer-owned; without this the
// deleted programs' reflection strings survive full context teardown.
ClearProgramResourceCaches();
BackendObject::ReleaseEGLResources();
}
@@ -481,9 +478,6 @@ namespace MobileGL::MG_Backend::DirectVulkan {
// treat them as signaled/available with zero results from here on.
BumpRendererGeneration();
pVulkanRenderer.reset();
// The reflection cache is file-scope, not renderer-owned; without this the
// deleted programs' reflection strings survive full context teardown.
ClearProgramResourceCaches();
}
const RendererInfo& BackendObject_DirectVulkan::GetRendererInfo() const {
@@ -61,12 +61,6 @@ namespace MobileGL::MG_Backend::DirectVulkan {
};
struct ProgramResourceCache {
// Lifetime id of the program the cached reflection belongs to. GL names are
// recycled (IndexGenerator hands freed indices straight back), and a
// recreated program's backendStateVersion restarts at the same small values,
// so the version alone can collide; the never-reused lifetime id makes the
// slot's ownership unambiguous.
Uint64 programLifetimeId = 0;
Uint32 backendStateVersion = 0;
Vector<StorageBlockResource> storageBlocks;
Vector<BufferVariableResource> bufferVariables;
@@ -88,11 +82,6 @@ namespace MobileGL::MG_Backend::DirectVulkan {
Uint32 baseInstance = 0;
};
// Keyed by GL program name so the freed-name reuse in IndexGenerator bounds the
// map at the peak-simultaneous-program high-water mark; each slot's ownership is
// checked against the program's lifetime id before it is served (see
// GetProgramResourceCache). Cleared wholesale at EGL teardown via
// ClearProgramResourceCaches.
UnorderedMap<GLuint, ProgramResourceCache> g_programResourceCaches;
void ClearReadPixelsOutput(GLsizei width, GLsizei height, GLenum format, GLenum type, void* pixels) {
@@ -153,19 +142,13 @@ namespace MobileGL::MG_Backend::DirectVulkan {
ProgramResourceCache& GetProgramResourceCache(const MG_State::GLState::ProgramObject& program) {
auto& cache = g_programResourceCaches[program.GetExternalIndex()];
const Uint64 programLifetimeId = program.GetLifetimeId();
const Uint32 backendStateVersion = program.GetBackendStateVersion();
// The lifetime id must match too: a new program that reuses a deleted
// program's name and happens to land on the same backendStateVersion (both
// count from zero) would otherwise be served the dead program's reflection.
if (cache.programLifetimeId == programLifetimeId &&
cache.backendStateVersion == backendStateVersion &&
if (cache.backendStateVersion == backendStateVersion &&
(!cache.storageBlocks.empty() || !cache.bufferVariables.empty())) {
return cache;
}
cache = {};
cache.programLifetimeId = programLifetimeId;
cache.backendStateVersion = backendStateVersion;
Vector<SpvReflectShaderModule> modules;
@@ -383,15 +366,6 @@ namespace MobileGL::MG_Backend::DirectVulkan {
}
} // namespace
void ClearProgramResourceCaches() {
// Called from EGL teardown while the backend's m_eglStateMutex is held; GL
// calls are serialized in this codebase (contexts migrate threads but never
// run concurrently), so no other thread can be inside the unsynchronized map.
// Live programs in another context self-heal: their entry rebuilds from the
// retained generated SPIR-V on the next resource query.
g_programResourceCaches.clear();
}
GLuint GetShaderStorageBlockIndex(const MG_State::GLState::ProgramObject& program, const String& name) {
auto& cache = GetProgramResourceCache(program);
const auto it = std::find_if(cache.storageBlocks.begin(), cache.storageBlocks.end(),
@@ -23,12 +23,6 @@ namespace MobileGL::MG_Backend::DirectVulkan {
Uint64 GetRendererGeneration();
void BumpRendererGeneration();
// Drops every cached program-resource reflection entry (CPU-side strings/vectors
// only, no Vulkan handles). Called at EGL teardown next to the renderer reset;
// safe because GL calls are serialized in this codebase, and any still-live
// program rebuilds its entry from the retained generated SPIR-V on demand.
void ClearProgramResourceCaches();
void ClearBufferfi(GLenum buffer, GLint drawbuffer, GLfloat depth, GLint stencil);
void ClearBufferfv(GLenum buffer, GLint drawbuffer, const GLfloat* value);
void ClearBufferuiv(GLenum buffer, GLint drawbuffer, const GLuint* value);
@@ -150,30 +150,12 @@ namespace MobileGL::MG_Backend::DirectVulkan {
Bool FrameContext::TransitionToPresent(VkImage image, VkImageLayout oldLayout, VkImageLayout presentLayout) {
auto& frame = GetCurrent();
if (oldLayout == presentLayout || oldLayout == VK_IMAGE_LAYOUT_SHARED_PRESENT_KHR) {
if (frame.hasCommandBufferRecorded || frame.isCommandRecording || oldLayout == presentLayout ||
oldLayout == VK_IMAGE_LAYOUT_SHARED_PRESENT_KHR) {
return false;
}
// The barrier belongs in the frame's own recording. Bailing out because
// something was already recorded (the previous behaviour) dropped the
// transition entirely for every frame that never ran a default-framebuffer
// render pass - the only other thing that carries the image to
// PRESENT_SRC_KHR, via that pass's finalLayout - so the swapchain image was
// handed to the WSI still in the layout it was acquired in.
// A closed-but-unsubmitted buffer can only come from a submit that already
// failed (SubmitPendingCommandBuffer leaves the flag set on error), and
// appending to it is illegal while reopening would reset the frame's own
// commands away. The device is gone on that path anyway - stay silent-safe
// rather than trade a lost device for a barrier into a closed buffer.
if (frame.hasCommandBufferRecorded) {
MGLOG_E("TransitionToPresent: command buffer already closed; skipping the present barrier");
return false;
}
// Reopening a recording here would vkResetCommandBuffer this frame's own
// commands away, so append to the open one and let the caller close it.
const Bool openedRecording = !frame.isCommandRecording;
VkCommandBuffer commandBuffer = openedRecording ? BeginCommandRecording() : frame.commandBuffer;
auto& commandBuffer = BeginCommandRecording();
VkImageMemoryBarrier presentBarrier{};
presentBarrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
@@ -192,9 +174,7 @@ namespace MobileGL::MG_Backend::DirectVulkan {
vkCmdPipelineBarrier(commandBuffer, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, 0, 0,
nullptr, 0, nullptr, 1, &presentBarrier);
if (openedRecording) {
EndCommandRecording();
}
EndCommandRecording();
return true;
}
@@ -247,21 +227,12 @@ namespace MobileGL::MG_Backend::DirectVulkan {
result = vkAcquireNextImageKHR(device, swapchain, timeout, frame.imageAvailableSemaphore, acquireFence,
&outImageIndex);
// VK_SUBOPTIMAL_KHR is a success code: an image *was* acquired and
// imageAvailableSemaphore *will* be signaled. Bailing out on it skipped both
// the consumed-flag reset (leaving a stale "already consumed", so the next
// submit never waited on the pending signal) and the fence reset (leaving
// the slot's fence signaled for the next submit to reuse). Only a genuine
// failure - VK_ERROR_OUT_OF_DATE_KHR and friends, where nothing is acquired
// and nothing is signaled - skips the bookkeeping.
if (result != VK_SUCCESS && result != VK_SUBOPTIMAL_KHR) {
if (result != VK_SUCCESS) {
return result;
}
frame.imageAvailableSemaphoreConsumed = false;
const VkResult resetResult = vkResetFences(device, 1, &frame.imageInFlightFence);
// Hand the acquire's own code back so the caller can schedule a rebuild.
return resetResult == VK_SUCCESS ? result : resetResult;
return vkResetFences(device, 1, &frame.imageInFlightFence);
}
Uint32 FrameContext::GetCurrentFrameIndex() const {
@@ -293,9 +264,7 @@ namespace MobileGL::MG_Backend::DirectVulkan {
if (result != VK_SUCCESS) {
return result;
}
// lastSubmitIndex was just written by the renderer for the submission
// that carried this command buffer.
frame.retiredCommandBuffers.push_back({frame.commandBuffer, frame.lastSubmitIndex});
frame.retiredCommandBuffers.push_back(frame.commandBuffer);
frame.commandBuffer = replacement;
return VK_SUCCESS;
}
@@ -305,40 +274,12 @@ namespace MobileGL::MG_Backend::DirectVulkan {
return;
}
if (m_device != VK_NULL_HANDLE && m_commandPool != VK_NULL_HANDLE) {
for (const auto& retired : frame.retiredCommandBuffers) {
vkFreeCommandBuffers(m_device, m_commandPool, 1, &retired.commandBuffer);
}
vkFreeCommandBuffers(m_device, m_commandPool, static_cast<Uint32>(frame.retiredCommandBuffers.size()),
frame.retiredCommandBuffers.data());
}
frame.retiredCommandBuffers.clear();
}
void FrameContext::FreeRetiredCommandBuffersCompletedUpTo(Uint64 completedSubmitIndex) {
if (m_device == VK_NULL_HANDLE || m_commandPool == VK_NULL_HANDLE) {
return;
}
for (auto& frame : m_frames) {
// Retired buffers are appended in submit order, so the completed
// ones form a prefix.
SizeT completedCount = 0;
while (completedCount < frame.retiredCommandBuffers.size() &&
frame.retiredCommandBuffers[completedCount].submitIndex <= completedSubmitIndex) {
vkFreeCommandBuffers(m_device, m_commandPool, 1,
&frame.retiredCommandBuffers[completedCount].commandBuffer);
++completedCount;
}
if (completedCount > 0) {
frame.retiredCommandBuffers.erase(frame.retiredCommandBuffers.begin(),
frame.retiredCommandBuffers.begin() + completedCount);
}
}
}
void FrameContext::FreeAllRetiredCommandBuffers() {
for (auto& frame : m_frames) {
FreeRetiredCommandBuffers(frame);
}
}
void FrameContext::AssertValidFrameIndex(Uint32 frameIndex) const {
MOBILEGL_ASSERT(frameIndex < m_frames.size(), "FrameContext index out of range");
}
@@ -40,16 +40,6 @@ namespace MobileGL::MG_Backend::DirectVulkan {
VkPresentInfoKHR presentInfo{VK_STRUCTURE_TYPE_PRESENT_INFO_KHR};
};
// A command buffer submitted mid-frame (FlushPendingCommands), tagged
// with the submit-tracker index it was submitted under so it can be
// freed as soon as that submission is observed complete - without
// waiting for the slot's fence to be waited again (present-less flush
// loops never wait it).
struct RetiredCommandBuffer {
VkCommandBuffer commandBuffer = VK_NULL_HANDLE;
Uint64 submitIndex = 0;
};
struct FrameData {
VkCommandBuffer commandBuffer = VK_NULL_HANDLE;
VkSemaphore imageAvailableSemaphore = VK_NULL_HANDLE;
@@ -57,10 +47,10 @@ namespace MobileGL::MG_Backend::DirectVulkan {
Bool isCommandRecording = false;
Bool hasCommandBufferRecorded = false;
Bool imageAvailableSemaphoreConsumed = false;
// Command buffers submitted mid-frame (FlushPendingCommands),
// appended in submit order; freed once their submission is known
// complete (fence wait or completion poll).
Vector<RetiredCommandBuffer> retiredCommandBuffers;
// Command buffers submitted mid-frame (FlushPendingCommands) whose
// execution is only known complete once this slot's fence has been
// waited again; freed at that point.
Vector<VkCommandBuffer> retiredCommandBuffers;
// Submit-tracker index of this slot's most recent queue submission
// (written by the renderer at submit time).
Uint64 lastSubmitIndex = 0;
@@ -89,19 +79,9 @@ namespace MobileGL::MG_Backend::DirectVulkan {
// Parks the current (already ended and submitted) command buffer on the
// slot's retired list and installs a freshly allocated one, so recording
// can restart while the submitted buffer is still executing. Retired
// buffers are freed after the slot's fence is next waited, or as soon
// as their submission is observed complete.
// buffers are freed after the slot's fence is next waited.
VkResult RetireCurrentCommandBuffer();
// Frees every retired command buffer whose tagged submission index is
// known complete. Driven by the renderer's submit tracker on completion
// events (fence waits and non-blocking polls), so present-less flush
// loops reclaim their buffers without any extra wait.
void FreeRetiredCommandBuffersCompletedUpTo(Uint64 completedSubmitIndex);
// Frees every slot's retired command buffers. Only valid when the
// caller has proven every queue submission complete.
void FreeAllRetiredCommandBuffers();
Uint32 GetCurrentFrameIndex() const;
Uint32 GetFrameCount() const;
@@ -8,7 +8,6 @@
#include "PipelineFactory.h"
#include <algorithm>
namespace MobileGL::MG_Backend::DirectVulkan {
static const char* PrimitiveTopologyToString(VkPrimitiveTopology topology) {
@@ -244,108 +243,23 @@ namespace MobileGL::MG_Backend::DirectVulkan {
const HashType hash = ComputeHash(payload);
auto it = m_cache.find(hash);
if (it != m_cache.end()) {
it->second.lastUsedFrame = m_frameCounter;
return it->second.pipeline;
return it->second;
}
VkPipeline pipeline = CreatePipeline(payload);
m_cache.emplace(hash, PipelineCacheEntry{pipeline, payload.programHash, payload.renderPass,
m_frameCounter});
m_cache.emplace(hash, pipeline);
return pipeline;
}
void PipelineFactory::DestroyAll() {
for (auto& pair : m_cache) {
if (pair.second.pipeline != VK_NULL_HANDLE) {
vkDestroyPipeline(m_device, pair.second.pipeline, nullptr);
if (pair.second != VK_NULL_HANDLE) {
vkDestroyPipeline(m_device, pair.second, nullptr);
}
}
m_cache.clear();
}
Uint32 PipelineFactory::OnFrameBoundary() {
++m_frameCounter;
// Sweep cadence and retire age mirror VkRenderPassManager::OnPresent: an entry
// idle for more than kRetireAgeFrames frame boundaries cannot be referenced by
// any in-flight command buffer (frames-in-flight <= MOBILEGL_MAGMA_FRAMESINFLIGHT),
// so immediate vkDestroyPipeline is safe. The caller must drop its "last
// pipeline" memo when this returns non-zero: the memo can return a cached
// handle without touching this cache, so an evicted pipeline may still be
// memoized (present-less flush loops never reset the memo per frame).
constexpr Uint64 kSweepInterval = 256;
constexpr Uint64 kRetireAgeFrames = 1024;
if ((m_frameCounter % kSweepInterval) != 0) {
return 0;
}
Uint32 evicted = 0;
for (auto it = m_cache.begin(); it != m_cache.end();) {
if (m_frameCounter - it->second.lastUsedFrame > kRetireAgeFrames) {
if (it->second.pipeline != VK_NULL_HANDLE) {
vkDestroyPipeline(m_device, it->second.pipeline, nullptr);
}
it = m_cache.erase(it);
++evicted;
} else {
++it;
}
}
if (evicted > 0) {
MGLOG_D("PipelineFactory::OnFrameBoundary: evicted %u idle pipelines (%zu remain)", evicted,
m_cache.size());
}
return evicted;
}
Uint32 PipelineFactory::EvictByRenderPasses(const Vector<VkRenderPass>& renderPasses) {
if (renderPasses.empty() || m_cache.empty()) {
return 0;
}
// Sorted-batch membership test keeps a mass eviction (shader-pack switch,
// dimension exit) at one O(cache * log batch) scan instead of one full scan
// per dying pass.
Vector<VkRenderPass> sortedPasses = renderPasses;
std::sort(sortedPasses.begin(), sortedPasses.end());
Uint32 evicted = 0;
for (auto it = m_cache.begin(); it != m_cache.end();) {
if (std::binary_search(sortedPasses.begin(), sortedPasses.end(), it->second.renderPass)) {
if (it->second.pipeline != VK_NULL_HANDLE) {
vkDestroyPipeline(m_device, it->second.pipeline, nullptr);
}
it = m_cache.erase(it);
++evicted;
} else {
++it;
}
}
if (evicted > 0) {
MGLOG_D("PipelineFactory::EvictByRenderPasses: evicted %u pipelines for %zu destroyed render passes",
evicted, sortedPasses.size());
}
return evicted;
}
Uint32 PipelineFactory::EvictByProgramHash(HashType programHash) {
Uint32 evicted = 0;
for (auto it = m_cache.begin(); it != m_cache.end();) {
if (it->second.programHash == programHash) {
if (it->second.pipeline != VK_NULL_HANDLE) {
vkDestroyPipeline(m_device, it->second.pipeline, nullptr);
}
it = m_cache.erase(it);
++evicted;
} else {
++it;
}
}
if (evicted > 0) {
MGLOG_D("PipelineFactory::EvictByProgramHash: evicted %u pipelines for program hash 0x%llx",
evicted, static_cast<unsigned long long>(programHash));
}
return evicted;
}
VkPipeline PipelineFactory::CreatePipeline(const PipelineCreatePayload& payload) const {
MOBILEGL_ASSERT(payload.stages != nullptr && !payload.stages->empty(), "PipelineFactory: stages are empty");
MOBILEGL_ASSERT(payload.vertexInputState != nullptr, "PipelineFactory: vertexInputState is null");
@@ -65,26 +65,6 @@ namespace MobileGL::MG_Backend::DirectVulkan {
VkPipeline GetOrCreatePipeline(const PipelineCreatePayload& payload);
void DestroyAll();
// Frame boundary hook: ages the pipeline cache and destroys long-unused entries
// (their command buffers retired many frames ago), mirroring
// VkRenderPassManager::OnPresent's sweep. Returns the number of pipelines
// destroyed so the caller can drop any memoized VkPipeline handle.
Uint32 OnFrameBoundary();
// Destroys every cached pipeline hashed on one of `renderPasses`. Only safe
// when the caller guarantees GPU idleness for them - the render-pass manager
// calls this (via the renderer) for passes its own >1024-boundary-idle sweep
// just evicted, and a pipeline hashed on those handles is only ever bound by
// draws that also hit the render-pass entries. Also closes the handle-recycling
// hazard: a recycled VkRenderPass value must never serve a stale pipeline.
// Batched: one cache scan regardless of how many passes died in the sweep.
// Returns the number destroyed (callers invalidate memos when non-zero).
Uint32 EvictByRenderPasses(const Vector<VkRenderPass>& renderPasses);
// Destroys every cached pipeline built from the program with content hash
// `programHash`. Called from the ProgramFactory eviction path, which proves the
// same >1024-boundary idleness (the program's pipelines are only bound by draws
// that stamp its factory entry). Returns the number destroyed.
Uint32 EvictByProgramHash(HashType programHash);
// Driver quirk: suppress depth writes on accumulation-blended pipelines. Multi-pass
// depth-equality rendering (a blended prepass writes depth that later passes re-test
// with an equality-inclusive compare on the re-rasterized geometry) requires
@@ -107,26 +87,12 @@ namespace MobileGL::MG_Backend::DirectVulkan {
static Bool ShouldSuppressDepthWrite(const PipelineCreatePayload& payload);
private:
struct PipelineCacheEntry {
VkPipeline pipeline = VK_NULL_HANDLE;
// The hashed inputs the eviction paths key on: programHash ties the entry to
// its ProgramFactory entry, renderPass records the exact handle the hash
// folded in (the hash is one-way, so targeted eviction needs them verbatim).
HashType programHash = 0;
VkRenderPass renderPass = VK_NULL_HANDLE;
// Frame-boundary counter value of the last GetOrCreatePipeline hit; drives
// cache eviction (see OnFrameBoundary).
Uint64 lastUsedFrame = 0;
};
VkPipeline CreatePipeline(const PipelineCreatePayload& payload) const;
VkDevice m_device = VK_NULL_HANDLE;
const VulkanRendererConfig& m_config;
VkPipelineCache m_pipelineCache = VK_NULL_HANDLE;
UnorderedMap<HashType, PipelineCacheEntry> m_cache;
// Monotonic frame-boundary counter (bumped in OnFrameBoundary) for cache aging.
Uint64 m_frameCounter = 0;
UnorderedMap<HashType, VkPipeline> m_cache;
static inline XXH64_state_t* m_hashState = XXH64_createState();
static inline Bool s_suppressBlendedDepthWrite = false;
};
@@ -1950,17 +1950,11 @@ namespace MobileGL::MG_Backend::DirectVulkan {
}
auto it = m_cache.find(hash);
if (it != m_cache.end()) {
// Every draw/dispatch funnels through this lookup (the renderer memos only
// skip re-hashing, never the factory lookup), so an actively-used entry is
// stamped at least once per frame boundary and can never be aged out while
// any in-flight command buffer still references it.
it->second.lastUsedFrame = m_frameCounter;
return it->second;
}
auto& entry = m_cache[hash];
entry.hash = hash;
entry.lastUsedFrame = m_frameCounter;
auto& shaders = program.GetAttachedShaders();
auto& spirv = program.GetGeneratedSpirv();
Vector<Vector<Uint>> moduleSpirvs(spirv.size());
@@ -2074,42 +2068,4 @@ namespace MobileGL::MG_Backend::DirectVulkan {
return entry;
}
void ProgramFactory::OnFrameBoundary() {
++m_frameCounter;
// Sweep cadence and retire age mirror VkRenderPassManager::OnPresent: an entry
// idle for more than kRetireAgeFrames frame boundaries cannot be referenced by
// any in-flight command buffer (frames-in-flight <= MOBILEGL_MAGMA_FRAMESINFLIGHT),
// so its shader modules and layouts are destroyed immediately - no deferred-
// destroy machinery needed. Eviction is content-based, never tied to
// glDeleteProgram: the cache is content-hash-shared across GL programs, so a
// delete-driven erase could free an entry another live program still resolves.
// An evicted entry self-heals - the frontend program keeps its generated
// SPIR-V, so the next GetOrCreateProgram rebuilds it (this also covers the
// renderer's internal blit/depth-mipmap programs).
constexpr Uint64 kSweepInterval = 256;
constexpr Uint64 kRetireAgeFrames = 1024;
if ((m_frameCounter % kSweepInterval) != 0) {
return;
}
for (auto it = m_cache.begin(); it != m_cache.end();) {
if (m_frameCounter - it->second.lastUsedFrame > kRetireAgeFrames) {
const HashType hash = it->first;
const VkDescriptorSetLayout descriptorSetLayout = it->second.descriptorSetLayout;
MGLOG_D("ProgramFactory::OnFrameBoundary: evicting idle program entry hash=0x%llx",
static_cast<unsigned long long>(hash));
// erase runs ~VkProgramObject (modules/layouts destroyed); notify after
// so an observer never observes a half-destroyed entry through a lookup.
// Observers only need the handle values to purge their keyed caches.
it = m_cache.erase(it);
if (m_evictionObserver != nullptr) {
m_evictionObserver->OnProgramEvicted(hash, descriptorSetLayout);
}
} else {
++it;
}
}
}
} // namespace MobileGL::MG_Backend::DirectVulkan
@@ -88,9 +88,6 @@ namespace MobileGL::MG_Backend::DirectVulkan {
// gl_FragDepth); shader-computed depth is immune to the cross-pipeline
// position-invariance quirk (see PipelineFactory::ShouldSuppressDepthWrite).
Bool fragmentReplacesDepth = false;
// Frame-boundary counter value of the last GetOrCreateProgram hit; drives
// cache eviction (see OnFrameBoundary).
Uint64 lastUsedFrame = 0;
static inline VkDevice s_device = VK_NULL_HANDLE;
@@ -127,7 +124,6 @@ namespace MobileGL::MG_Backend::DirectVulkan {
producerOutputComponentCount = other.producerOutputComponentCount;
fragmentInputComponentCount = other.fragmentInputComponentCount;
fragmentReplacesDepth = other.fragmentReplacesDepth;
lastUsedFrame = other.lastUsedFrame;
other.hash = 0;
other.descriptorSetLayout = VK_NULL_HANDLE;
other.pipelineLayout = VK_NULL_HANDLE;
@@ -139,7 +135,6 @@ namespace MobileGL::MG_Backend::DirectVulkan {
other.producerOutputComponentCount = 0;
other.fragmentInputComponentCount = 0;
other.fragmentReplacesDepth = false;
other.lastUsedFrame = 0;
}
VkProgramObject& operator=(VkProgramObject&& other) noexcept {
if (this == &other) {
@@ -175,7 +170,6 @@ namespace MobileGL::MG_Backend::DirectVulkan {
producerOutputComponentCount = other.producerOutputComponentCount;
fragmentInputComponentCount = other.fragmentInputComponentCount;
fragmentReplacesDepth = other.fragmentReplacesDepth;
lastUsedFrame = other.lastUsedFrame;
other.hash = 0;
other.descriptorSetLayout = VK_NULL_HANDLE;
other.pipelineLayout = VK_NULL_HANDLE;
@@ -187,7 +181,6 @@ namespace MobileGL::MG_Backend::DirectVulkan {
other.producerOutputComponentCount = 0;
other.fragmentInputComponentCount = 0;
other.fragmentReplacesDepth = false;
other.lastUsedFrame = 0;
return *this;
}
@@ -217,18 +210,6 @@ namespace MobileGL::MG_Backend::DirectVulkan {
}
};
// Notified when the OnFrameBoundary sweep destroys an aged-out cache entry,
// carrying the entry's content hash and the VkDescriptorSetLayout it owned.
// Dependent caches (compute pipelines, PipelineFactory entries, UniformManager's
// per-layout descriptor sets) must purge in the same step: after vkDestroy the
// layout handle value may be recycled for an unrelated layout, and the program
// hash may be re-inserted by a later rebuild of the same content.
class IEvictionObserver {
public:
virtual ~IEvictionObserver() = default;
virtual void OnProgramEvicted(HashType programHash, VkDescriptorSetLayout descriptorSetLayout) = 0;
};
explicit ProgramFactory(VkDevice device, const VulkanRendererConfig& config, Uint32 maxBindings = 16,
Bool shaderDrawParametersEnabled = false,
Bool unformattedFloatStorageImagesEnabled = false)
@@ -244,13 +225,6 @@ namespace MobileGL::MG_Backend::DirectVulkan {
const VkProgramObject& GetOrCreateProgram(
const MG_State::GLState::ProgramObject& program, CompileOptionFlags flags);
// Observer may be null (no notifications). Not owned.
void SetEvictionObserver(IEvictionObserver* observer) { m_evictionObserver = observer; }
// Frame boundary hook: ages the program cache and evicts long-unused entries
// (their command buffers retired many frames ago), mirroring
// VkRenderPassManager::OnPresent's sweep.
void OnFrameBoundary();
static VkShaderStageFlagBits ToVkStage(ShaderStage stage);
static VkFormat ConvertSpirvImageFormatToVkFormat(SpvImageFormat format);
static SamplerNumericDomain UniformTypeToSamplerNumericDomain(GLenum glType);
@@ -292,9 +266,6 @@ namespace MobileGL::MG_Backend::DirectVulkan {
// shaderStorageImageReadWithoutFormat and shaderStorageImageWriteWithoutFormat.
Bool m_unformattedFloatStorageImagesEnabled = false;
mutable ProgramLookupCache m_lastLookup;
// Monotonic frame-boundary counter (bumped in OnFrameBoundary) for cache aging.
Uint64 m_frameCounter = 0;
IEvictionObserver* m_evictionObserver = nullptr;
static inline XXH64_state_t* m_hashState = XXH64_createState();
};
} // namespace MobileGL::MG_Backend::DirectVulkan
@@ -247,11 +247,6 @@ namespace MobileGL::MG_Backend::DirectVulkan {
m_surfaceFormat = {createInfo.imageFormat, createInfo.imageColorSpace};
m_extent = createInfo.imageExtent;
// The surface-space extent this swapchain was built from, i.e. before the
// quarter-turn swap above. Out-of-date checks must compare in THIS space: comparing a
// freshly queried currentExtent against the swapped m_extent flips axes every rotation
// and makes the comparison alternate forever.
m_surfaceExtent = defaultFramebufferExtent;
m_preTransform = createInfo.preTransform;
VK_VERIFY(vkCreateSwapchainKHR(device, &createInfo, nullptr, &m_swapchain));
@@ -35,9 +35,6 @@ namespace MobileGL::MG_Backend::DirectVulkan {
VkSwapchainKHR GetHandle() const { return m_swapchain; }
const VkSurfaceFormatKHR& GetSurfaceFormat() const { return m_surfaceFormat; }
VkExtent2D GetExtent() const { return m_extent; }
// Surface-space extent (before the pre-rotation quarter-turn swap) this swapchain was
// created from - the value to compare a freshly queried currentExtent against.
VkExtent2D GetSurfaceExtent() const { return m_surfaceExtent; }
VkSurfaceTransformFlagBitsKHR GetPreTransform() const { return m_preTransform; }
const Vector<VkImage>& GetImages() const { return m_images; }
const Vector<VkImageView>& GetImageViews() const { return m_imageViews; }
@@ -66,7 +63,6 @@ namespace MobileGL::MG_Backend::DirectVulkan {
VkSwapchainKHR m_swapchain = VK_NULL_HANDLE;
VkSurfaceFormatKHR m_surfaceFormat{};
VkExtent2D m_extent{};
VkExtent2D m_surfaceExtent{};
VkSurfaceTransformFlagBitsKHR m_preTransform = VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR;
Vector<VkImage> m_images;
Vector<VkImageView> m_imageViews;
@@ -211,40 +211,6 @@ namespace MobileGL::MG_Backend::DirectVulkan {
}
}
void UniformManager::OnDescriptorSetLayoutDestroyed(VkDescriptorSetLayout descriptorSetLayout) {
SizeT purgedSets = 0;
for (auto& frame : m_frames) {
const auto it = frame.descriptorSetCacheByLayout.find(descriptorSetLayout);
if (it == frame.descriptorSetCacheByLayout.end()) {
continue;
}
// Free the sets back to their pools and credit the bucket accounting, so
// program churn recycles pool capacity instead of abandoning the slots.
// GPU-safe: the layout only dies after >1024 idle frame boundaries, so no
// in-flight command buffer references these sets.
for (const auto& cached : it->second.sets) {
if (cached.set == VK_NULL_HANDLE) {
continue;
}
vkFreeDescriptorSets(m_device, cached.pool, 1, &cached.set);
const auto bucket = std::find_if(
frame.descriptorPools.begin(), frame.descriptorPools.end(),
[&cached](const DescriptorPoolBucket& candidate) { return candidate.handle == cached.pool; });
if (bucket != frame.descriptorPools.end() && bucket->allocatedSets > 0) {
--bucket->allocatedSets;
}
}
purgedSets += it->second.sets.size();
frame.descriptorSetCacheByLayout.erase(it);
}
if (purgedSets > 0) {
// The per-draw reuse memo folds the layout handle into its signature; drop
// it so a recycled handle value cannot revive a purged set mid-frame.
m_hasLastDescriptor = false;
MGLOG_D("UniformDescriptorBinder: freed %zu descriptor sets for destroyed layout", purgedSets);
}
}
Bool UniformManager::ResolveSamplerDescriptor(VkCommandBuffer commandBuffer,
const MG_State::GLState::ProgramObject& program,
const ProgramFactory::VkProgramObject& programObj,
@@ -945,11 +911,6 @@ namespace MobileGL::MG_Backend::DirectVulkan {
VkDescriptorPoolCreateInfo poolInfo{};
poolInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO;
// FREE_DESCRIPTOR_SET_BIT lets a destroyed layout's cached sets be freed back
// (OnDescriptorSetLayoutDestroyed) so program churn recycles pool capacity.
// The cost is on set allocation only, which happens when a layout's per-frame
// cache grows - never on the per-draw reuse path.
poolInfo.flags = VK_DESCRIPTOR_POOL_CREATE_FREE_DESCRIPTOR_SET_BIT;
poolInfo.maxSets = maxSets;
poolInfo.poolSizeCount = static_cast<Uint32>(std::size(poolSizes));
poolInfo.pPoolSizes = poolSizes;
@@ -1029,7 +990,7 @@ namespace MobileGL::MG_Backend::DirectVulkan {
auto& frame = m_frames[frameIndex];
auto& cache = frame.descriptorSetCacheByLayout[programObj.descriptorSetLayout];
if (cache.cursor < cache.sets.size()) {
outDescriptorSet = cache.sets[cache.cursor++].set;
outDescriptorSet = cache.sets[cache.cursor++];
} else {
VkResult allocResult = AllocateDescriptorSetsFromActivePool(frameIndex, programObj, outDescriptorSet);
if (allocResult == VK_ERROR_OUT_OF_POOL_MEMORY || allocResult == VK_ERROR_FRAGMENTED_POOL) {
@@ -1043,9 +1004,7 @@ namespace MobileGL::MG_Backend::DirectVulkan {
return allocResult;
}
// The successful allocation came from the bucket the alloc helper left
// active; record it so a layout-destroyed purge can free the set back.
cache.sets.push_back({outDescriptorSet, frame.descriptorPools[frame.activeDescriptorPoolIndex].handle});
cache.sets.push_back(outDescriptorSet);
++cache.cursor;
MGLOG_D("UniformDescriptorBinder: cached descriptor set count for frame=%u grew to %zu", frameIndex,
cache.sets.size());
@@ -39,17 +39,6 @@ namespace MobileGL::MG_Backend::DirectVulkan {
void Shutdown();
void BeginFrame(Uint32 frameIndex);
// A ProgramFactory eviction just destroyed this layout: purge every frame
// slot's cached descriptor sets for it, so a recycled handle value can never
// stale-hit sets written for the dead layout's bindings. The sets are
// vkFreeDescriptorSets'd back to their pools (created with
// FREE_DESCRIPTOR_SET_BIT) and the pool accounting is credited, so program
// churn recycles pool capacity instead of abandoning it. GPU-safe: the layout
// only dies after >1024 idle frame boundaries, so no in-flight command buffer
// references its sets. This is the only eviction path for the per-layout
// caches - a live layout's entry must never be purged (its sets would be
// unreachable pool slots), so there is deliberately no age-based sweep here.
void OnDescriptorSetLayoutDestroyed(VkDescriptorSetLayout descriptorSetLayout);
Bool CollectSampledTextures(const MG_State::GLState::ProgramObject& program,
const ProgramFactory::VkProgramObject& programObj,
Vector<MG_State::GLState::ITextureObject*>& outTextures);
@@ -76,16 +65,8 @@ namespace MobileGL::MG_Backend::DirectVulkan {
Uint32 allocatedSets = 0;
};
// A cached descriptor set together with the pool it was allocated from, so a
// layout-destroyed purge can vkFreeDescriptorSets it back and credit the
// owning bucket's accounting.
struct CachedDescriptorSet {
VkDescriptorSet set = VK_NULL_HANDLE;
VkDescriptorPool pool = VK_NULL_HANDLE;
};
struct DescriptorSetCacheEntry {
Vector<CachedDescriptorSet> sets;
Vector<VkDescriptorSet> sets;
Uint32 cursor = 0;
};
@@ -32,13 +32,6 @@ namespace MobileGL::MG_Backend::DirectVulkan {
XXHASH_VERIFY(XXH64_update(m_hashState, &attr.IsBgra, sizeof(attr.IsBgra)));
XXHASH_VERIFY(XXH64_update(m_hashState, &attr.Divisor, sizeof(attr.Divisor)));
// The buffer's heap address is an identity component of the key: a freed
// buffer's reused address can alias an old cache entry, but only under a
// byte-identical attribute layout - and the entry payload is a pure function
// of the hashed inputs, with the draw path re-resolving bindingBufferKeys
// against the live VAO attribute pointers, so an aliased hit returns exactly
// what a rebuild would. Address drift only grows the map; the OnFrameBoundary
// aging sweep bounds that.
const SizeT bufferKey = reinterpret_cast<SizeT>(attr.Buffer.get());
XXHASH_VERIFY(XXH64_update(m_hashState, &bufferKey, sizeof(bufferKey)));
}
@@ -65,7 +58,6 @@ namespace MobileGL::MG_Backend::DirectVulkan {
const MG_State::GLState::VertexArrayObject& vao, HashType hash) {
auto it = m_cache.find(hash);
if (it != m_cache.end()) {
it->second.lastUsedFrameBoundary = m_frameBoundaryCounter;
return it->second;
}
@@ -174,7 +166,6 @@ namespace MobileGL::MG_Backend::DirectVulkan {
auto& entry = m_cache[hash];
entry.hash = hash;
entry.lastUsedFrameBoundary = m_frameBoundaryCounter;
entry.bindings = builder.GetBindings();
entry.attributes = builder.GetAttributes();
entry.bindingBufferKeys = std::move(bindingBufferKeys);
@@ -189,30 +180,6 @@ namespace MobileGL::MG_Backend::DirectVulkan {
return entry;
}
void VertexInputStateFactory::OnFrameBoundary() {
++m_frameBoundaryCounter;
// Sweep occasionally; evict entries whose last hit is far in the past.
// Erasure happens only here, never mid-frame: the draw path holds a
// reference into the current entry across its setup, and unordered_map
// erase would invalidate it. Entries are CPU-side only, so no GPU-idle
// proof is needed; an evicted entry that is used again is simply rebuilt
// from the VAO state (same hash, same content).
constexpr Uint64 kSweepInterval = 256;
constexpr Uint64 kRetireAgeBoundaries = 1024;
if ((m_frameBoundaryCounter % kSweepInterval) != 0) {
return;
}
for (auto it = m_cache.begin(); it != m_cache.end();) {
if (m_frameBoundaryCounter - it->second.lastUsedFrameBoundary > kRetireAgeBoundaries) {
it = m_cache.erase(it);
} else {
++it;
}
}
}
VkFormat VertexInputStateFactory::ToVkVertexFormat(DataType type, Int size, Bool normalized, Bool isInteger,
Bool isBgra) {
if (isBgra) {
@@ -27,9 +27,6 @@ namespace MobileGL::MG_Backend::DirectVulkan {
struct BackendVertexInputState {
HashType hash = 0;
// Frame boundary of the last cache hit; entries idle past the
// OnFrameBoundary retirement age are evicted (CPU heap only).
Uint64 lastUsedFrameBoundary = 0;
Vector<VkVertexInputBindingDescription> bindings;
Vector<VkVertexInputAttributeDescription> attributes;
Vector<SizeT> bindingBufferKeys;
@@ -58,14 +55,6 @@ namespace MobileGL::MG_Backend::DirectVulkan {
const BackendVertexInputState& GetOrCreateVertexInputState(
const MG_State::GLState::VertexArrayObject& vao, HashType hash);
const BackendVertexInputState& GetOrCreateVertexInputState(const MG_State::GLState::VertexArrayObject& vao);
// Frame boundary hook: ages the cache and evicts entries not hit for many
// frames. The key mixes buffer heap addresses, so buffer/VAO churn keeps
// minting fresh keys; without eviction the map grows for the whole session.
// Entries hold no Vulkan handles (pipeline creation copies the descriptions)
// and the draw path's entry reference never spans a frame boundary, so
// eviction here needs no GPU-idle proof. Self-gated: one counter bump and
// compare except on sweep boundaries.
void OnFrameBoundary();
static SizeT GetComponentSize(DataType type);
// Tightly-packed byte size of one vertex element for this attribute: componentSize * size for
// normal types, and 4 (one packed word) for the 2_10_10_10 types and GL_BGRA. Returns 0 for
@@ -81,8 +70,6 @@ namespace MobileGL::MG_Backend::DirectVulkan {
const VulkanRendererConfig& m_config;
VkPhysicalDevice m_physicalDevice = VK_NULL_HANDLE;
UnorderedMap<HashType, BackendVertexInputState> m_cache;
// Monotonic frame-boundary counter (bumped in OnFrameBoundary) for cache aging.
Uint64 m_frameBoundaryCounter = 0;
static inline XXH64_state_t* m_hashState = XXH64_createState();
};
} // namespace MobileGL::MG_Backend::DirectVulkan
@@ -141,15 +141,6 @@ namespace MobileGL::MG_Backend::DirectVulkan {
m_transientUploadArena.BeginFrame(frameIndex);
}
void VkBufferManager::CollectAllDeferredReleases() {
for (Uint32 frameIndex = 0; frameIndex < m_deferredBufferReleases.size(); ++frameIndex) {
CollectDeferredReleases(frameIndex);
}
for (Uint32 frameIndex = 0; frameIndex < m_transientUploadArena.GetFrameCount(); ++frameIndex) {
m_transientUploadArena.CollectDeferredReleases(frameIndex);
}
}
void VkBufferManager::NotifyDeviceIdle() {
// Everything submitted so far has completed. Work recorded for the
// current frame has not been submitted yet, so the current serial
@@ -77,11 +77,6 @@ namespace MobileGL::MG_Backend::DirectVulkan {
// Recreate all per-frame transient arenas
Bool RecreateTransientArenas(Uint32 frameCount);
void BeginFrame(Uint32 frameIndex);
// Drains every frame slot's deferred buffer/resource releases (and the
// transient arena's parked superseded blocks). Only valid when the
// caller has proven every queue submission complete; used by the
// present-less frame-boundary drain.
void CollectAllDeferredReleases();
// All previously submitted GPU work has completed (vkDeviceWaitIdle).
void NotifyDeviceIdle();
// A frame slot's submission fence has been waited: every serial up to
@@ -180,7 +180,6 @@ namespace MobileGL::MG_Backend::DirectVulkan {
sampleCount = VK_SAMPLE_COUNT_1_BIT;
internalFormat = TextureInternalFormat::Unknown;
samples = 0;
deadSinceFrame = kNeverObservedDead;
}
VkRenderPassManager::VkRenderPassManager(VkDevice device,
@@ -207,7 +206,6 @@ namespace MobileGL::MG_Backend::DirectVulkan {
resource.Destroy(m_device, m_allocator);
}
m_renderbufferResources.clear();
CollectDeferredRenderbufferReleases(/*destroyAll=*/true); // caller guarantees device idle
m_pendingRenderbufferClears.clear();
RenderPassEntry::s_textureResourcesScratch.clear();
s_activeRenderPass = {};
@@ -215,75 +213,22 @@ namespace MobileGL::MG_Backend::DirectVulkan {
m_rpFastValid = false;
}
Uint64 VkRenderPassManager::RetireAgeFrames() const {
// MaxFramesInFlight + 2 covers the frame ring plus one boundary for the
// recording-to-submit gap and one because OnPresent runs ahead of Present's
// fence wait; the floor of 8 keeps a margin over the default ring of 3 while
// still releasing multi-MB attachment memory promptly (the render-pass cache's
// 1024-frame retirement would pin it for no additional safety).
return std::max<Uint64>(8, static_cast<Uint64>(m_config.MaxFramesInFlight) + 2);
}
void VkRenderPassManager::DeferRenderbufferBackingRelease(RenderbufferResource& resource) {
// The superseded backing may still be referenced by in-flight command buffers
// (glRenderbufferStorage can respecify a renderbuffer drawn this very frame),
// so it is parked and destroyed only after RetireAgeFrames() boundaries.
if (resource.image == VK_NULL_HANDLE && resource.view == VK_NULL_HANDLE) {
return;
}
m_deferredRenderbufferReleases.push_back({resource.image, resource.allocation, resource.view, m_frameCounter});
resource.image = VK_NULL_HANDLE;
resource.allocation = nullptr;
resource.view = VK_NULL_HANDLE;
}
void VkRenderPassManager::CollectDeferredRenderbufferReleases(Bool destroyAll) {
if (m_deferredRenderbufferReleases.empty()) {
return;
}
const Uint64 retireAgeFrames = RetireAgeFrames();
std::erase_if(m_deferredRenderbufferReleases, [&](DeferredRenderbufferRelease& release) {
if (!destroyAll && m_frameCounter - release.deferredAtFrame < retireAgeFrames) {
return false;
}
if (release.view != VK_NULL_HANDLE) {
vkDestroyImageView(m_device, release.view, nullptr);
}
if (release.image != VK_NULL_HANDLE) {
vmaDestroyImage(m_allocator, release.image, release.allocation);
}
return true;
});
}
void VkRenderPassManager::CollectRenderbufferGarbage() {
// Two-phase reclamation: a dead renderbuffer's VkImage may still be referenced by
// command buffers submitted up to frames-in-flight frames ago (it was legally
// attached and drawn right up to its deletion), so the first observation of an
// expired weak reference only stamps the current frame counter; Destroy runs once
// enough frame boundaries have passed that the stamping frame's submission fence
// has provably been waited (see RetireAgeFrames).
const Uint64 retireAgeFrames = RetireAgeFrames();
for (auto it = m_renderbufferResources.begin(); it != m_renderbufferResources.end();) {
auto& resource = it->second;
Vector<MG_State::GLState::RenderbufferObject*> deadRenderbuffers;
deadRenderbuffers.reserve(m_renderbufferResources.size());
for (auto& [renderbuffer, resource] : m_renderbufferResources) {
const auto liveRenderbuffer = resource.renderbuffer.lock();
if (liveRenderbuffer && liveRenderbuffer.get() == it->first) {
resource.deadSinceFrame = RenderbufferResource::kNeverObservedDead;
++it;
continue;
if (!liveRenderbuffer || liveRenderbuffer.get() != renderbuffer) {
deadRenderbuffers.emplace_back(renderbuffer);
}
if (resource.deadSinceFrame == RenderbufferResource::kNeverObservedDead) {
resource.deadSinceFrame = m_frameCounter;
++it;
continue;
}
for (auto* renderbuffer : deadRenderbuffers) {
auto resourceIt = m_renderbufferResources.find(renderbuffer);
if (resourceIt != m_renderbufferResources.end()) {
resourceIt->second.Destroy(m_device, m_allocator);
m_renderbufferResources.erase(resourceIt);
}
if (m_frameCounter - resource.deadSinceFrame < retireAgeFrames) {
++it;
continue;
}
m_pendingRenderbufferClears.erase(it->first);
resource.Destroy(m_device, m_allocator);
it = m_renderbufferResources.erase(it);
m_pendingRenderbufferClears.erase(renderbuffer);
}
}
@@ -325,15 +270,9 @@ namespace MobileGL::MG_Backend::DirectVulkan {
resource.samples != renderbuffer->GetSamples();
if (!needsCreate) {
resource.renderbuffer = renderbuffer;
// A new renderbuffer at a recycled address may adopt a compatible entry that
// was already stamped dead; it is alive again, so cancel the aging.
resource.deadSinceFrame = RenderbufferResource::kNeverObservedDead;
return &resource;
}
// Respecify: park the old backing for aged destruction instead of destroying
// inline - it may still be referenced by in-flight command buffers.
DeferRenderbufferBackingRelease(resource);
resource.Destroy(m_device, m_allocator);
resource.renderbuffer = renderbuffer;
@@ -1239,14 +1178,6 @@ namespace MobileGL::MG_Backend::DirectVulkan {
void VkRenderPassManager::OnPresent() {
++m_frameCounter;
// Runs every frame boundary, ahead of the render-pass sweep gate below: the walk
// is O(#renderbuffer resources) — single digits in practice — and per-frame
// invocation keeps dead-resource reclaim latency at the aging bound instead of
// coupling it to renderbuffer *use* (the GetOrCreateRenderbufferResource call
// site never runs again once an app stops using renderbuffers).
CollectRenderbufferGarbage();
CollectDeferredRenderbufferReleases(/*destroyAll=*/false);
// Sweep occasionally; evict entries whose last use is far past every
// in-flight frame so their VkRenderPass/VkFramebuffer can be destroyed
// safely (RenderPassEntry's destructor releases the handles).
@@ -1256,12 +1187,6 @@ namespace MobileGL::MG_Backend::DirectVulkan {
return;
}
// Collect the dying handles and notify once after the loop: pipelines hashed
// on them share the entries' >kRetireAgeFrames idleness (they are only bound
// by draws that hit those entries), so the observer may destroy them
// immediately - and a single batched notification costs one pipeline-cache
// scan instead of one per evicted pass.
Vector<VkRenderPass> destroyedRenderPasses;
const Uint64 activeHash = s_hasActiveRenderPass ? s_activeRenderPass.hash : 0;
for (auto it = m_renderPasses.begin(); it != m_renderPasses.end();) {
const Bool isActive = s_hasActiveRenderPass && it->first == activeHash;
@@ -1269,15 +1194,11 @@ namespace MobileGL::MG_Backend::DirectVulkan {
if (m_rpFastValid && m_rpFastRenderPassHash == it->first) {
m_rpFastValid = false;
}
destroyedRenderPasses.push_back(it->second.renderPass);
it = m_renderPasses.erase(it);
} else {
++it;
}
}
if (!destroyedRenderPasses.empty() && m_evictionObserver != nullptr) {
m_evictionObserver->OnRenderPassesDestroyed(destroyedRenderPasses);
}
}
Bool VkRenderPassManager::BeginRenderPass(VkCommandBuffer commandBuffer, RenderPassEntry& renderPassEntry) {
@@ -157,31 +157,11 @@ namespace MobileGL::MG_Backend::DirectVulkan {
class VkRenderPassManager {
public:
using HashType = Uint64;
// Notified once per OnPresent sweep with every aged-out entry's VkRenderPass
// value: pipelines are hashed on the raw handle, and once destroyed the value
// may be recycled for an incompatible pass, so dependent caches must purge
// everything keyed on them before any new pass can be created (the sweep and
// the notification run back-to-back with no creation in between; observers
// compare the values, never dereference them). Batched so a mass-idle cohort
// (shader-pack switch, dimension exit) costs the observer one pipeline-cache
// scan, not one per dying pass. The wholesale paths
// (Shutdown/RecreateSwapchain) do not notify - their callers already drop
// every pipeline outright.
class IEvictionObserver {
public:
virtual ~IEvictionObserver() = default;
virtual void OnRenderPassesDestroyed(const Vector<VkRenderPass>& renderPasses) = 0;
};
VkRenderPassManager(VkDevice device,
VkPhysicalDevice physicalDevice, VmaAllocator allocator, const VulkanRendererConfig& config,
VkClearManager& clearManager, VkTextureManager& textureManager, SwapchainObject& swapchainObject);
~VkRenderPassManager();
// Observer may be null (no notifications). Not owned.
void SetEvictionObserver(IEvictionObserver* observer) { m_evictionObserver = observer; }
Bool Initialize();
void Shutdown();
@@ -212,7 +192,6 @@ namespace MobileGL::MG_Backend::DirectVulkan {
UnorderedMap<Uint64, RenderPassEntry> m_renderPasses;
// Monotonic frame counter (bumped in OnPresent) for render-pass cache aging.
Uint64 m_frameCounter = 0;
IEvictionObserver* m_evictionObserver = nullptr;
// Bumped whenever a renderbuffer VkImage is (re)created; together with the texture
// manager's image epoch this invalidates the render-pass fast path on any attachment
@@ -234,12 +213,6 @@ namespace MobileGL::MG_Backend::DirectVulkan {
public:
struct RenderbufferResource {
// deadSinceFrame sentinel: the owning weak reference has not been observed
// expired. Dead resources age past every in-flight frame before Destroy
// (see CollectRenderbufferGarbage); the GPU may still reference the image
// for frames-in-flight frames after the GL object dies.
static constexpr Uint64 kNeverObservedDead = UINT64_MAX;
WeakPtr<MG_State::GLState::RenderbufferObject> renderbuffer;
VkImage image = VK_NULL_HANDLE;
VmaAllocation allocation = nullptr;
@@ -251,8 +224,6 @@ namespace MobileGL::MG_Backend::DirectVulkan {
VkSampleCountFlagBits sampleCount = VK_SAMPLE_COUNT_1_BIT;
TextureInternalFormat internalFormat = TextureInternalFormat::Unknown;
Int samples = 0;
// m_frameCounter value at which the weak reference was first seen expired.
Uint64 deadSinceFrame = kNeverObservedDead;
void Destroy(VkDevice device, VmaAllocator allocator);
};
@@ -270,28 +241,12 @@ namespace MobileGL::MG_Backend::DirectVulkan {
ClearAttachmentPayload payload{};
};
// A superseded renderbuffer backing (glRenderbufferStorage respecify) parked
// until enough frame boundaries have passed that no in-flight command buffer
// can still reference it; destroyed in OnPresent (see RetireAgeFrames).
struct DeferredRenderbufferRelease {
VkImage image = VK_NULL_HANDLE;
VmaAllocation allocation = nullptr;
VkImageView view = VK_NULL_HANDLE;
Uint64 deferredAtFrame = 0;
};
UnorderedMap<MG_State::GLState::RenderbufferObject*, RenderbufferResource> m_renderbufferResources;
UnorderedMap<MG_State::GLState::RenderbufferObject*, PendingRenderbufferClear> m_pendingRenderbufferClears;
Vector<DeferredRenderbufferRelease> m_deferredRenderbufferReleases;
Bool HasPendingRenderbufferClear(
const MG_State::GLState::FramebufferAttachmentObject& attachment) const;
void CollectRenderbufferGarbage();
// Frame-boundary margin after which a resource last referenced by a retired
// GL object (or superseded backing) is provably past every in-flight frame.
Uint64 RetireAgeFrames() const;
void DeferRenderbufferBackingRelease(RenderbufferResource& resource);
void CollectDeferredRenderbufferReleases(Bool destroyAll);
static inline XXH64_state_t* m_hashState = XXH64_createState();
static inline ActiveRenderPassInfo s_activeRenderPass{};
@@ -89,33 +89,6 @@ namespace MobileGL::MG_Backend::DirectVulkan {
m_device = VK_NULL_HANDLE;
m_config = nullptr;
m_frameBoundaryCounter = 0;
}
void VkSamplerManager::OnFrameBoundary() {
++m_frameBoundaryCounter;
// Sweep occasionally; destroy samplers whose last use is far past every
// in-flight frame. Destroy and erase must stay atomic, or Shutdown would
// double-free the handle; an evicted key that recurs simply re-creates
// its sampler on the next miss.
constexpr Uint64 kSweepInterval = 256;
constexpr Uint64 kRetireAgeBoundaries = 1024;
if ((m_frameBoundaryCounter % kSweepInterval) != 0) {
return;
}
for (auto it = m_samplers.begin(); it != m_samplers.end();) {
auto& entry = it->second;
if (m_frameBoundaryCounter - entry.lastUsedFrameBoundary > kRetireAgeBoundaries) {
if (m_device != VK_NULL_HANDLE && entry.handle != VK_NULL_HANDLE) {
vkDestroySampler(m_device, entry.handle, nullptr);
}
it = m_samplers.erase(it);
} else {
++it;
}
}
}
Uint64 VkSamplerManager::BuildSamplerKey(const MG_State::GLState::SamplerObject& sampler,
@@ -164,7 +137,6 @@ namespace MobileGL::MG_Backend::DirectVulkan {
const Uint64 key = BuildSamplerKey(sampler, texture, forceNearestFiltering);
auto it = m_samplers.find(key);
if (it != m_samplers.end()) {
it->second.lastUsedFrameBoundary = m_frameBoundaryCounter;
return it->second.handle;
}
@@ -197,7 +169,6 @@ namespace MobileGL::MG_Backend::DirectVulkan {
entry.handle = vkSampler;
entry.externalIndex = sampler.GetExternalIndex();
entry.version = sampler.GetVersion();
entry.lastUsedFrameBoundary = m_frameBoundaryCounter;
m_samplers[key] = entry;
return vkSampler;
}
@@ -36,27 +36,12 @@ public:
VkSampler GetOrCreateSampler(const MG_State::GLState::SamplerObject& sampler,
const MG_State::GLState::ITextureObject& texture,
Bool forceNearestFiltering = false);
// Frame boundary hook: ages the sampler cache and destroys samplers not used
// for many frames. The key hashes continuous float state (lodBias, LOD clamps,
// anisotropy), so an app animating those would otherwise mint an unbounded
// stream of never-destroyed VkSamplers and eventually exhaust the device's
// maxSamplerAllocationCount. A sampler idle for over a thousand frame
// boundaries cannot be referenced by any in-flight command buffer (frames in
// flight are single digits), and every descriptor set the GPU consumes is
// written that same frame with live handles (the per-binding resolve memo and
// descriptor-set reuse are both frame-reset), so destruction here needs no
// fence wait. Self-gated: one counter bump and compare except on sweep
// boundaries.
void OnFrameBoundary();
private:
struct SamplerCacheEntry {
VkSampler handle = VK_NULL_HANDLE;
Uint externalIndex = 0;
Uint16 version = 0;
// Frame boundary of the last cache hit; entries idle past the
// OnFrameBoundary retirement age have their VkSampler destroyed.
Uint64 lastUsedFrameBoundary = 0;
};
Uint64 BuildSamplerKey(const MG_State::GLState::SamplerObject& sampler,
@@ -82,8 +67,6 @@ private:
Bool m_samplerAnisotropySupported = false;
Float m_maxSamplerAnisotropy = 1.0f;
UnorderedMap<Uint64, SamplerCacheEntry> m_samplers;
// Monotonic frame-boundary counter (bumped in OnFrameBoundary) for cache aging.
Uint64 m_frameBoundaryCounter = 0;
static inline XXH64_state_t* m_hashState = XXH64_createState();
};
} // namespace MobileGL::MG_Backend::DirectVulkan
@@ -627,26 +627,6 @@ namespace MobileGL::MG_Backend::DirectVulkan {
frameIndex, m_deferredViewReleases.size());
m_currentFrameIndex = frameIndex;
CollectDeferredReleases(frameIndex);
// Frame-boundary GC: every 64 frame boundaries (~1 s at 60 fps) bounds the reclaim
// latency for dead textures regardless of draw traffic — workloads that churn
// textures through clears/readbacks alone never reach the draw-gated
// CollectGarbage. Must run after CollectDeferredReleases above: the prune defers
// its releases into this frame's slot, which was just drained, so they are
// destroyed only after the slot's fence has been waited again one full frame-ring
// cycle from now (never while an in-flight frame may still reference them).
constexpr Uint32 kGcFrameInterval = 64;
++m_gcFrameCounter;
if (m_gcFrameCounter % kGcFrameInterval == 0) {
PruneDeadTextures();
}
}
void VkTextureManager::CollectAllDeferredReleases() {
const SizeT frameCount = std::min(m_deferredReleases.size(), m_deferredViewReleases.size());
for (SizeT frameIndex = 0; frameIndex < frameCount; ++frameIndex) {
CollectDeferredReleases(static_cast<Uint32>(frameIndex));
}
}
void VkTextureManager::EraseTrackedTexture(const TextureIdentity& identity) {
@@ -722,22 +702,9 @@ namespace MobileGL::MG_Backend::DirectVulkan {
// construction introduces a new identity. Doing this unconditionally made every
// sampled-texture sync scan the entire alive-texture map per draw.
if (aliveIt == m_aliveObjects.end()) {
WeakPtr<MG_State::GLState::ITextureObject> aliveTexture;
const auto& liveTexture = MG_State::pGLContext->GetTextureObject(texture.GetExternalIndex());
if (liveTexture && liveTexture.get() == &texture) {
aliveTexture = liveTexture;
} else {
// The name lookup legally fails while the object is alive: the name was
// deleted with the texture still attached to an FBO (the attachment's
// SharedPtr keeps it alive), or the name was reused by a new texture, or
// this is a default texture object (name 0 lives outside the name map).
// Register through the object's own control block so the resource created
// below still participates in weak-expiry GC instead of becoming an
// orphan no reclamation path can reach until Shutdown.
aliveTexture = texture.weak_from_this();
}
if (!aliveTexture.expired()) {
m_aliveObjects[identity] = Move(aliveTexture);
m_aliveObjects[identity] = WeakPtr<MG_State::GLState::ITextureObject>(liveTexture);
PruneStaleTextureAliases(&texture);
}
}
@@ -1245,22 +1212,10 @@ namespace MobileGL::MG_Backend::DirectVulkan {
}
SizeT VkTextureManager::CollectGarbage() {
// Draw-gated stagger (1 in 256 calls): keeps the per-draw cost at one counter
// bump. The guaranteed reclaim path is the frame-boundary prune in BeginFrame;
// this remains as a cheap assist so draw-heavy workloads reclaim sooner.
m_gcCounter++;
if (m_gcCounter != 0) {
return 0;
}
return PruneDeadTextures();
}
SizeT VkTextureManager::PruneDeadTextures() {
// Erasing entries would dangle the raw TextureResource pointers memoized for the
// current draw; every call path (BeginFrame, and CollectGarbage at the top of a
// freshly opened draw-sync scope) runs before any memo entry is recorded.
MOBILEGL_ASSERT(m_drawSyncedThisDraw.empty(),
"PruneDeadTextures: draw-sync memo holds raw resource pointers an erase would dangle");
Vector<MG_State::GLState::ITextureObject*> expiredTextures;
expiredTextures.reserve(m_aliveObjects.size());
@@ -1272,25 +1227,7 @@ namespace MobileGL::MG_Backend::DirectVulkan {
for (auto* texture : expiredTextures) {
PruneStaleTextureAliases(texture);
}
SizeT prunedCount = expiredTextures.size();
// Orphan sweep: after the pass above, m_aliveObjects holds only live entries.
// Registration in SyncTextureAndGetDescriptor cannot fail for a SharedPtr-owned
// texture (weak_from_this fallback), so a resource whose identity has no alive
// entry has no trackable owner: its GL-side object is gone, or was never
// shared-owned, in which case recreation on a later sync is the safe fallback.
// Destruction goes through the per-frame deferred queues, never immediate.
Vector<TextureIdentity> orphanIdentities;
for (auto it = m_textureResources.begin(); it != m_textureResources.end(); ++it) {
if (m_aliveObjects.find(it->first) == m_aliveObjects.end()) {
orphanIdentities.emplace_back(it->first);
}
}
for (const auto& identity : orphanIdentities) {
EraseTrackedTexture(identity);
}
prunedCount += orphanIdentities.size();
return prunedCount;
return expiredTextures.size();
}
Bool VkTextureManager::SyncTexture(MG_State::GLState::ITextureObject &texture,
@@ -267,10 +267,6 @@ public:
Bool Initialize(const InitInfo& initInfo);
void Shutdown();
void BeginFrame(Uint32 frameIndex);
// Drains every frame slot's deferred image/view releases. Only valid when
// the caller has proven every queue submission complete; used by the
// present-less frame-boundary drain.
void CollectAllDeferredReleases();
TextureResource* SyncTextureAndGetDescriptor(
MG_State::GLState::ITextureObject& texture);
@@ -368,7 +364,6 @@ private:
static TextureIdentity MakeTextureIdentity(MG_State::GLState::ITextureObject* texture);
void EraseTrackedTexture(const TextureIdentity& identity);
void PruneStaleTextureAliases(MG_State::GLState::ITextureObject* texture);
SizeT PruneDeadTextures();
VkDevice m_device = VK_NULL_HANDLE;
VkPhysicalDevice m_physicalDevice = VK_NULL_HANDLE;
@@ -378,9 +373,6 @@ private:
Uint32 m_currentFrameIndex = 0;
Uint8 m_gcCounter = 0;
// Frame-boundary GC gate: counts BeginFrame calls, not draws, so texture churn
// through non-draw paths (FBO clears, readbacks) still reaches the prune.
Uint32 m_gcFrameCounter = 0;
// Active only between BeginDrawSyncScope/EndDrawSyncScope; identities of
// textures already fully synced in the current draw (small N -> flat scan).
Bool m_drawSyncScopeActive = false;
@@ -1016,18 +1016,7 @@ layout(location = 0) in vec2 vTexCoord;
layout(location = 0) out vec4 outColor;
void main() {
// Explicit LOD, not texture(): a blit reads exactly the selected level, so
// derivative-based mip selection has no business here. It is also load-bearing:
// on Adreno 650 (driver 512.502) an implicit-LOD sample of this single-mip
// UBWC render target through the pre-rotation (ROTATE_90) mapping reads past
// the image's allocation - despite the sampler's maxLod=0 and a nominal 1:1
// texel mapping whose LOD is 0, so the driver's implicit-LOD path itself is at
// fault - and page-faults the GPU once the neighbouring memory is returned to
// the kernel (frame 2 of Minecraft 26.2's resource reload; the kernel then
// invalidates the context and the next submit dies with EDEADLK ->
// VK_ERROR_DEVICE_LOST at Present). Verified on device: texture() faults on
// the second frame every run, textureLod survives with identical state.
outColor = textureLod(uSource, vTexCoord, 0.0);
outColor = texture(uSource, vTexCoord);
}
)";
@@ -1921,10 +1910,8 @@ void main() {
case VK_FORMAT_R16G16_UNORM: out = {ReadbackSourceClass::Float, 2, 16}; return true;
case VK_FORMAT_R16G16B16A16_UNORM: out = {ReadbackSourceClass::Float, 4, 16}; return true;
// --- SRGB (decode to linear like GL readback of sRGB textures) ---
// GL GetTexImage/ReadPixels of sRGB textures return the raw sRGB-encoded
// bytes (GL 3.3 has no FRAMEBUFFER_SRGB read decode) - do NOT linearize.
case VK_FORMAT_R8G8B8A8_SRGB: out = {ReadbackSourceClass::Float, 4, 8}; return true;
case VK_FORMAT_B8G8R8A8_SRGB: out = {ReadbackSourceClass::Float, 4, 8, false, false, true}; return true;
case VK_FORMAT_R8G8B8A8_SRGB: out = {ReadbackSourceClass::Float, 4, 8, false, true}; return true;
case VK_FORMAT_B8G8R8A8_SRGB: out = {ReadbackSourceClass::Float, 4, 8, false, true, true}; return true;
// --- SNORM ---
case VK_FORMAT_R8_SNORM: out = {ReadbackSourceClass::Float, 1, 8, true}; return true;
case VK_FORMAT_R8G8_SNORM: out = {ReadbackSourceClass::Float, 2, 8, true}; return true;
@@ -1962,8 +1949,6 @@ void main() {
// --- packed / special ---
case VK_FORMAT_A2B10G10R10_UNORM_PACK32:
case VK_FORMAT_A2B10G10R10_UINT_PACK32:
case VK_FORMAT_A2R10G10B10_UNORM_PACK32:
case VK_FORMAT_A2R10G10B10_UINT_PACK32:
case VK_FORMAT_B10G11R11_UFLOAT_PACK32:
case VK_FORMAT_E5B9G9R9_UFLOAT_PACK32:
case VK_FORMAT_R5G6B5_UNORM_PACK16:
@@ -1973,8 +1958,7 @@ void main() {
case VK_FORMAT_B5G5R5A1_UNORM_PACK16:
case VK_FORMAT_R4G4B4A4_UNORM_PACK16:
case VK_FORMAT_B4G4R4A4_UNORM_PACK16:
out.sourceClass = (format == VK_FORMAT_A2B10G10R10_UINT_PACK32 ||
format == VK_FORMAT_A2R10G10B10_UINT_PACK32) ?
out.sourceClass = format == VK_FORMAT_A2B10G10R10_UINT_PACK32 ?
ReadbackSourceClass::UnsignedInt : ReadbackSourceClass::Float;
out.special = format;
return true;
@@ -2050,15 +2034,6 @@ void main() {
rgba[3] = static_cast<Float>((word >> 30) & 0x3u) / 3.0f;
return;
}
case VK_FORMAT_A2R10G10B10_UNORM_PACK32: {
Uint32 word = 0;
Memcpy(&word, source, sizeof(word));
rgba[2] = static_cast<Float>(word & 0x3FFu) / 1023.0f;
rgba[1] = static_cast<Float>((word >> 10) & 0x3FFu) / 1023.0f;
rgba[0] = static_cast<Float>((word >> 20) & 0x3FFu) / 1023.0f;
rgba[3] = static_cast<Float>((word >> 30) & 0x3u) / 3.0f;
return;
}
case VK_FORMAT_B10G11R11_UFLOAT_PACK32: {
Uint32 word = 0;
Memcpy(&word, source, sizeof(word));
@@ -2210,13 +2185,6 @@ void main() {
rgba[1] = (word >> 10) & 0x3FFu;
rgba[2] = (word >> 20) & 0x3FFu;
rgba[3] = (word >> 30) & 0x3u;
} else if (srcFormat == VK_FORMAT_A2R10G10B10_UINT_PACK32) {
Uint32 word = 0;
Memcpy(&word, source, sizeof(word));
rgba[2] = word & 0x3FFu;
rgba[1] = (word >> 10) & 0x3FFu;
rgba[0] = (word >> 20) & 0x3FFu;
rgba[3] = (word >> 30) & 0x3u;
} else {
for (Int c = 0; c < desc.channels; ++c) {
if (desc.componentBits == 8) {
@@ -2248,9 +2216,8 @@ void main() {
}
static Bool PackReadbackToClientOrPbo(const Uint8* srcPixels, VkFormat srcFormat, GLsizei width,
GLsizei sliceHeight, GLsizei sliceCount, GLenum format, GLenum type,
void* pixels, Bool applyPackImageParams) {
if (width <= 0 || sliceHeight <= 0 || sliceCount <= 0) {
GLsizei height, GLenum format, GLenum type, void* pixels) {
if (width <= 0 || height <= 0) {
return true;
}
@@ -2263,8 +2230,7 @@ void main() {
Vector<Uint8> wide;
GLenum wideType = GL_FLOAT;
if (!DecodeReadbackRowsToWide(srcPixels, srcFormat, width,
sliceHeight * sliceCount, wide, wideType)) {
if (!DecodeReadbackRowsToWide(srcPixels, srcFormat, width, height, wide, wideType)) {
MGLOG_E("DirectVulkan readback skipped: unsupported source format=%d",
static_cast<Int>(srcFormat));
return false;
@@ -2277,9 +2243,9 @@ void main() {
return false;
}
return DirectGLES::ReadbackImpl::StoreWideRowsToClient(wide.data(), wideType, width, sliceHeight,
sliceCount, mapping, type, pixels,
applyPackImageParams);
return DirectGLES::ReadbackImpl::StoreWideRowsToClient(wide.data(), wideType, width, height,
/*sliceCount=*/1, mapping, type, pixels,
/*applyPackImageParams=*/false);
}
} // namespace
@@ -2540,11 +2506,6 @@ void main() {
m_shaderDrawParametersFeatureEnabled,
m_unformattedFloatStorageImagesEnabled);
MOBILEGL_ASSERT(m_programFactory != nullptr, "ProgramFactory creation failed.");
// Aging evictions (render passes and program entries) must purge the dependent
// pipeline / compute-pipeline / descriptor-set caches in the same step; both
// sweeps only run from the frame-boundary seams, long after initialization.
m_renderPassManager->SetEvictionObserver(this);
m_programFactory->SetEvictionObserver(this);
m_samplerManager = MakeUnique<VkSamplerManager>();
MOBILEGL_ASSERT(m_samplerManager != nullptr, "VkSamplerManager creation failed.");
@@ -2574,20 +2535,11 @@ void main() {
if (m_swapchainObject.GetHandle() != VK_NULL_HANDLE) {
VkResult acquireResult =
m_frameContext.WaitAndAcquireNextImage(m_device, m_swapchainObject.GetHandle(), m_imageIndexAcquired);
if (acquireResult == VK_ERROR_OUT_OF_DATE_KHR) {
// Nothing was acquired and no semaphore signal was armed, so
// rebuilding and re-acquiring on the same semaphore is safe.
if (acquireResult == VK_ERROR_OUT_OF_DATE_KHR || acquireResult == VK_SUBOPTIMAL_KHR) {
MGLOG_D("Initialize, vkAcquireNextImageKHR got %d, recreating swapchain", acquireResult);
RecreateSwapchain();
acquireResult =
m_frameContext.WaitAndAcquireNextImage(m_device, m_swapchainObject.GetHandle(), m_imageIndexAcquired);
} else if (acquireResult == VK_SUBOPTIMAL_KHR) {
// The image is usable, and its acquire signal is already armed on
// imageAvailableSemaphore. Re-acquiring here would arm a second signal on a
// binary semaphore whose first one nobody has waited on yet; keep the image.
// Only a real surface change schedules a rebuild.
m_swapchainResizeRequested = m_swapchainResizeRequested || SwapchainIsOutOfDate();
acquireResult = VK_SUCCESS;
}
VK_VERIFY(acquireResult, "Initialize, WaitAndAcquireNextImage");
} else {
@@ -2614,15 +2566,6 @@ void main() {
DestroyDeferredDepthMipmapCleanup();
DestroyComputePipelines();
// No sweep runs during teardown, but the observers point at this renderer
// and the factories die at different times below; disconnect them first.
if (m_renderPassManager) {
m_renderPassManager->SetEvictionObserver(nullptr);
}
if (m_programFactory) {
m_programFactory->SetEvictionObserver(nullptr);
}
m_pipelineFactory.reset();
ShutdownBlitResources();
ShutdownDepthMipmapResources();
@@ -2713,7 +2656,6 @@ void main() {
DestroyDebugMessenger();
m_debugMessenger = VK_NULL_HANDLE;
}
DestroyDebugReportCallback();
if (m_instance != VK_NULL_HANDLE) {
vkDestroyInstance(m_instance, nullptr);
@@ -6239,12 +6181,12 @@ void main() {
frame.hasCommandBufferRecorded = false;
frame.isCommandRecording = false;
// The wait proved every submission complete, so the full frame-boundary
// drain applies: descriptor cursors, transient arenas, deferred
// texture/buffer releases, retired command buffers and the converted
// vertex-stream cache all rewind here, keeping present-less readback
// loops bounded (Present is the only other drain point).
TryDrainFrameTransients();
// The wait proved every descriptor set this slot has in flight idle;
// rewind the reuse cursors so present-less readback loops stay
// bounded (Present is the only other rewind point).
if (m_uniformManager) {
m_uniformManager->BeginFrame(m_frameContext.GetCurrentFrameIndex());
}
return true;
}
@@ -6391,8 +6333,7 @@ void main() {
if (RemapDefaultFboReadbackToGLOrientation(mapped, swapchainExtent, preTransform,
sourceTexelSize,
remapped.data())) {
PackReadbackToClientOrPbo(remapped.data(), srcFormat, width, height, 1, format, type, pixels,
/*applyPackImageParams=*/false);
PackReadbackToClientOrPbo(remapped.data(), srcFormat, width, height, format, type, pixels);
return;
}
}
@@ -6401,8 +6342,7 @@ void main() {
width, height, swapchainExtent.width, swapchainExtent.height,
static_cast<Int>(preTransform));
}
PackReadbackToClientOrPbo(mapped, srcFormat, width, height, 1, format, type, pixels,
/*applyPackImageParams=*/false);
PackReadbackToClientOrPbo(mapped, srcFormat, width, height, format, type, pixels);
}
void VulkanRenderer::GetTexImage(GLenum target, GLint level, GLenum format, GLenum type, GLvoid* pixels) {
@@ -6455,17 +6395,6 @@ void main() {
if (width <= 0 || height <= 0) {
return;
}
// GetTexImage returns every slice of a 3D level and every layer of an array
// level; GL_PACK_IMAGE_HEIGHT / GL_PACK_SKIP_IMAGES apply to the 3D/array
// destination layout (GL 3.3 section 6.1.4).
const auto imageTextureTarget = textureObject->GetTarget();
const Bool is3dImage = imageTextureTarget == TextureTarget::Texture3D;
const Bool isArrayImage = imageTextureTarget == TextureTarget::Texture1DArray ||
imageTextureTarget == TextureTarget::Texture2DArray ||
imageTextureTarget == TextureTarget::TextureCubeMapArray;
const GLsizei depthSlices = is3dImage ? std::max<GLsizei>(texelSize.z(), 1) : 1;
const GLsizei arrayLayers = isArrayImage ? static_cast<GLsizei>(resource->arrayLayers) : 1;
const GLsizei sliceCount = std::max<GLsizei>(depthSlices * arrayLayers, 1);
if (bufSize >= 0) {
const Int dstChannels = GetReadbackChannelCount(format);
if ((type == GL_UNSIGNED_BYTE || type == GL_FLOAT) && dstChannels > 0) {
@@ -6486,8 +6415,7 @@ void main() {
return;
}
const VkDeviceSize readbackSize = static_cast<VkDeviceSize>(width) *
static_cast<VkDeviceSize>(height) *
static_cast<VkDeviceSize>(sliceCount) * sourceTexelSize;
static_cast<VkDeviceSize>(height) * sourceTexelSize;
VkBufferObject readback;
if (!readback.Create({
.allocator = m_allocator,
@@ -6515,9 +6443,8 @@ void main() {
copyRegion.imageSubresource.aspectMask = resource->aspect;
copyRegion.imageSubresource.mipLevel = static_cast<Uint32>(level);
copyRegion.imageSubresource.baseArrayLayer = 0;
copyRegion.imageSubresource.layerCount = static_cast<Uint32>(arrayLayers);
copyRegion.imageExtent = {static_cast<Uint32>(width), static_cast<Uint32>(height),
static_cast<Uint32>(depthSlices)};
copyRegion.imageSubresource.layerCount = 1;
copyRegion.imageExtent = {static_cast<Uint32>(width), static_cast<Uint32>(height), 1};
vkCmdCopyImageToBuffer(frame.commandBuffer, resource->image, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
readback.GetHandle(), 1, &copyRegion);
@@ -6543,8 +6470,7 @@ void main() {
MGLOG_E("DirectVulkan::GetTextureImage skipped: failed to invalidate readback buffer");
return;
}
PackReadbackToClientOrPbo(mapped, resource->format, width, height, sliceCount, format, type, pixels,
/*applyPackImageParams=*/is3dImage || isArrayImage);
PackReadbackToClientOrPbo(mapped, resource->format, width, height, format, type, pixels);
}
void VulkanRenderer::GenerateMipmap(GLenum target) {
@@ -7158,9 +7084,6 @@ void main() {
}
m_bufferManager.NotifyDeviceIdle();
OnSubmitsCompletedUpTo(m_submitCounter);
// The queue was just drained; take the free frame-boundary drain when
// nothing is recorded (present-less timer-query loops). No-op otherwise.
TryDrainFrameTransients();
return true;
}
@@ -7229,85 +7152,6 @@ void main() {
vkDestroyFence(m_device, record.fence, nullptr);
}
}
// Mid-frame-flushed command buffers whose submission just completed can
// be freed now; present-less flush loops have no other reclaim point.
m_frameContext.FreeRetiredCommandBuffersCompletedUpTo(m_completedSubmitCounter);
}
Bool VulkanRenderer::TryDrainFrameTransients() {
if (m_device == VK_NULL_HANDLE || m_frameContext.GetFrameCount() == 0) {
return false;
}
if (m_completedSubmitCounter != m_submitCounter) {
RefreshCompletedSubmits();
if (m_completedSubmitCounter != m_submitCounter) {
return false;
}
}
if (HasPendingRecordedWork()) {
return false;
}
// Every submission is complete and nothing recorded references the
// per-frame transients. Pure-reclaim work runs on every drain: it only
// releases memory that is provably dead, never invalidates anything a
// later draw would have to rebuild. Raise the buffer manager's
// completed floor first so busy-tracking reflects the proven idleness.
m_bufferManager.NotifyDeviceIdle();
const Uint32 frameIndex = m_frameContext.GetCurrentFrameIndex();
m_frameContext.FreeAllRetiredCommandBuffers();
for (Uint32 slot = 0; slot < m_deferredDepthMipmapCleanup.size(); ++slot) {
CollectDeferredDepthMipmapCleanup(slot);
}
if (m_textureManager) {
m_textureManager->CollectAllDeferredReleases();
}
m_bufferManager.CollectAllDeferredReleases();
// Descriptor cursors rewind on every drain (the pre-drain readback path
// already did exactly this), keeping fence/readback loops' set usage bounded.
if (m_uniformManager) {
m_uniformManager->BeginFrame(frameIndex);
}
// Frame-boundary-equivalent work - transient arena rewind (which invalidates
// the conversion cache) and the cache-aging clocks - is gated to every 8th
// drain since the last Present: a presenting app's mid-frame readbacks/waits
// must neither force re-conversion/re-upload churn for the rest of the frame
// nor multiply the aging rate (which would shrink the 1024-boundary retire
// window and thrash periodically-used pipelines/programs), while present-less
// loops still rewind the arena and age their caches every 8 iterations -
// bounded by 8 iterations' transient usage.
++m_drainsSinceLastPresent;
if ((m_drainsSinceLastPresent % 8) != 0) {
return true;
}
if (m_textureManager) {
m_textureManager->BeginFrame(frameIndex);
}
m_bufferManager.BeginFrame(frameIndex);
// The cached conversion slices point into the transient arena the
// BeginFrame above just rewound; drop them together.
m_convertedVertexStreams.clear();
if (m_renderPassManager) {
m_renderPassManager->OnPresent();
}
// The pipeline memo can survive across these boundaries (no per-frame reset
// on this path), so it must drop whenever the sweep destroys anything.
if (m_programFactory) {
m_programFactory->OnFrameBoundary();
}
if (m_pipelineFactory && m_pipelineFactory->OnFrameBoundary() > 0) {
m_lastPipelineValid = false;
m_lastPipelineResult = VK_NULL_HANDLE;
}
if (m_vertexInputStateFactory) {
m_vertexInputStateFactory->OnFrameBoundary();
}
if (m_samplerManager) {
m_samplerManager->OnFrameBoundary();
}
return true;
}
VkFence VulkanRenderer::AcquirePooledSubmitFence() {
@@ -7370,10 +7214,6 @@ void main() {
if (m_device == VK_NULL_HANDLE || m_graphicsQueue == VK_NULL_HANDLE || m_frameContext.GetFrameCount() == 0) {
return false;
}
// Non-blocking completion poll: gives flush-only workloads (no sync
// objects, no present) a point where finished submissions retire their
// pooled fences and mid-frame command buffers.
RefreshCompletedSubmits();
auto& frame = m_frameContext.GetCurrent();
if (!frame.isCommandRecording && !frame.hasCommandBufferRecorded) {
return false;
@@ -7398,14 +7238,6 @@ void main() {
return false;
}
// Command-buffer boundary: the pipeline memo must not survive it, or a
// pipeline bound only through memo hits is never re-stamped in the factory
// cache and the aging sweep could destroy it while the flushed submission
// still references it. Mirrors the drops at the readback and Present
// boundaries; costs one full pipeline lookup on the next draw.
m_lastPipelineValid = false;
m_lastPipelineResult = VK_NULL_HANDLE;
// The submitted command buffer may still be executing; recording must
// restart on a fresh one. If none can be allocated, fall back to
// draining this submission so reusing the buffer stays legal.
@@ -7457,10 +7289,6 @@ void main() {
const VkResult result = vkWaitForFences(m_device, 1, &record.fence, VK_TRUE, timeoutNs);
if (result == VK_SUCCESS) {
OnSubmitsCompletedUpTo(record.submitIndex);
// The wait already stalled the pipeline; if it happens to
// have drained everything (present-less fence loops), take
// the free frame-boundary drain. No-op otherwise.
TryDrainFrameTransients();
return true;
}
if (result != VK_TIMEOUT) {
@@ -7550,69 +7378,34 @@ void main() {
suspendedFrame.isCommandRecording = false;
suspendedFrame.hasCommandBufferRecorded = false;
m_lastPipelineValid = false;
// The dropped recording is never submitted, so once the fence
// poll shows the pre-suspension submissions complete the frame
// transients (descriptor sets, transient arenas, deferred
// releases, conversion caches) can rewind; without this a
// minimized-window app accumulates them for the whole
// suspension.
TryDrainFrameTransients();
MGLOG_D("Present skipped: no usable swapchain (zero-area window)");
return;
}
m_presentSuspended = false;
const VkResult acquireResult =
m_frameContext.WaitAndAcquireNextImage(m_device, m_swapchainObject.GetHandle(), m_imageIndexAcquired);
if (acquireResult == VK_SUBOPTIMAL_KHR) {
// Usable image with its acquire signal already armed; a rebuild is scheduled
// only if the surface genuinely no longer matches (see step 4 of Present).
m_swapchainResizeRequested = m_swapchainResizeRequested || SwapchainIsOutOfDate();
} else {
if (acquireResult != VK_SUBOPTIMAL_KHR) {
VK_VERIFY(acquireResult, "Present, deferred first WaitAndAcquireNextImage");
}
}
MOBILEGL_ASSERT(m_imageIndexAcquired < m_swapchainObject.GetImageCount(),
"Present, acquired image index out of range");
m_renderPassManager->OnPresent();
// A real presented frame is the canonical aging cadence; mid-frame drains
// count against this and only age when presents stop coming.
m_drainsSinceLastPresent = 0;
// Age the content-addressed caches on the same frame-boundary cadence. Each
// keeps its own internal 256-sweep gate, so the per-frame cost is one counter
// increment and compare per cache; entries used by this frame's still-
// unsubmitted recording were stamped this boundary (every command-buffer
// boundary drops the pipeline memo, so the first draw of each recording
// performs a real, stamping lookup) and can never age out.
m_programFactory->OnFrameBoundary();
if (m_pipelineFactory->OnFrameBoundary() > 0) {
m_lastPipelineValid = false; // an aged-out pipeline may still be memoized
m_lastPipelineResult = VK_NULL_HANDLE;
}
m_vertexInputStateFactory->OnFrameBoundary();
m_samplerManager->OnFrameBoundary();
auto& frame = m_frameContext.GetCurrent();
auto* activeRenderPass = VkRenderPassManager::GetActiveRenderPass();
if (activeRenderPass)
VkRenderPassManager::EndRenderPass(frame.commandBuffer);
// Transition while this frame's recording is still open. A frame that
// rendered only into FBOs has no default-framebuffer render pass, and that
// pass's finalLayout is the only other thing that carries the swapchain
// image to PRESENT_SRC_KHR - so closing the buffer first, which made
// TransitionToPresent refuse to record, handed the image to
// vkQueuePresentKHR in the layout it was acquired in (UNDEFINED on a fresh
// swapchain). The SetImageLayout below then made the tracker's
// disagreement with reality permanent for that image index.
const auto acquiredImageLayout = m_swapchainObject.GetImageLayout(m_imageIndexAcquired);
m_frameContext.TransitionToPresent(m_swapchainObject.GetImage(m_imageIndexAcquired), acquiredImageLayout);
if (frame.isCommandRecording) {
m_frameContext.EndCommandRecording();
frame.hasCommandBufferRecorded = true;
m_lastPipelineValid = false; // command-buffer boundary: drop the pipeline memo
}
const Bool shouldSubmitCommandBuffer = frame.hasCommandBufferRecorded;
const auto acquiredImageLayout = m_swapchainObject.GetImageLayout(m_imageIndexAcquired);
const Bool needsLayoutTransitionForPresent =
m_frameContext.TransitionToPresent(m_swapchainObject.GetImage(m_imageIndexAcquired), acquiredImageLayout);
const Bool shouldSubmitCommandBuffer = frame.hasCommandBufferRecorded || needsLayoutTransitionForPresent;
// 1) Submit current frame work.
auto submitPacket = m_frameContext.GetSubmitInfo(shouldSubmitCommandBuffer, m_imageIndexAcquired);
@@ -7626,15 +7419,7 @@ void main() {
// 2) Present current frame.
auto presentPacket = m_frameContext.GetPresentInfo(m_swapchainObject.GetHandle(), m_imageIndexAcquired);
auto result = vkQueuePresentKHR(m_presentQueue, &presentPacket.presentInfo);
if (result == VK_SUBOPTIMAL_KHR) {
// Suboptimal is not a reason to rebuild on its own: a driver may report it for a
// surface whose size and orientation still match what we built from (Android does
// this routinely), and rebuilding on it alone destroys every pipeline and
// reallocates the default framebuffer once per frame - flicker, then garbage.
// Defer to the surface-capabilities comparison below.
result = VK_SUCCESS;
}
if (result == VK_ERROR_OUT_OF_DATE_KHR) {
if (result == VK_ERROR_OUT_OF_DATE_KHR || result == VK_SUBOPTIMAL_KHR) {
MGLOG_D("Present, vkQueuePresentKHR got %d, recreating swapchain", result);
if (!RecreateSwapchain()) {
// Window went zero-area (minimize) with the swapchain out of date:
@@ -7648,13 +7433,6 @@ void main() {
result = VK_SUCCESS;
}
VK_VERIFY(result, "Present, vkQueuePresentKHR");
// The authoritative check, done here - after the frame is presented, before the next
// acquire. This is what makes a launcher-side resolution change take effect: shrinking
// the window's buffer (SurfaceHolder.setFixedSize) moves currentExtent, the swapchain
// follows, and the compositor scales the smaller image up to the view for free.
if (!m_swapchainResizeRequested && SwapchainIsOutOfDate()) {
m_swapchainResizeRequested = true;
}
if (m_swapchainResizeRequested) {
MGLOG_D("Present, processing requested swapchain resize");
if (!RecreateSwapchain()) {
@@ -7671,16 +7449,7 @@ void main() {
// 4) Wait/reset/acquire for next frame.
result = m_frameContext.WaitAndAcquireNextImage(m_device, m_swapchainObject.GetHandle(), m_imageIndexAcquired);
if (result == VK_SUBOPTIMAL_KHR) {
// An image WAS acquired and its signal is armed on this slot's
// imageAvailableSemaphore, so the frame proceeds normally. Whether a rebuild is
// actually needed is decided by the surface-capabilities comparison at the next
// Present - suboptimal alone must not schedule one, or a driver that reports it
// every frame would rebuild every frame.
m_swapchainResizeRequested = m_swapchainResizeRequested || SwapchainIsOutOfDate();
result = VK_SUCCESS;
} else if (result == VK_ERROR_OUT_OF_DATE_KHR) {
// Nothing acquired, nothing signaled: safe to rebuild and re-acquire.
if (result == VK_ERROR_OUT_OF_DATE_KHR || result == VK_SUBOPTIMAL_KHR) {
MGLOG_D("Present, vkAcquireNextImageKHR got %d, recreating swapchain", result);
if (!RecreateSwapchain()) {
m_presentSuspended = true;
@@ -7728,24 +7497,6 @@ void main() {
m_validationLayersEnabled = m_config.EnableValidationLayers && validationLayerAvailable;
// The debug messenger is a VK_EXT_debug_utils object, but a driver can ship
// the validation layers while exposing only the older VK_EXT_debug_report
// (Adreno 650 / Vulkan 1.1.128 does exactly that). Requesting the extension
// unconditionally tripped the required-extension assert below, aborting every
// validation-enabled build in CreateInstance. Keep the layers - they still
// validate, and on Android they report to logcat on their own - and drop only
// the messenger.
const Bool debugUtilsAvailable =
m_validationLayersEnabled && IsExtensionSupported(m_extensions, VK_EXT_DEBUG_UTILS_EXTENSION_NAME);
// Without a reporting channel the layers validate but say nothing, so fall
// back to VK_EXT_debug_report when debug_utils is missing.
const Bool debugReportAvailable = m_validationLayersEnabled && !debugUtilsAvailable &&
IsExtensionSupported(m_extensions, VK_EXT_DEBUG_REPORT_EXTENSION_NAME);
if (m_validationLayersEnabled && !debugUtilsAvailable) {
MGLOG_I("%s not available; validation reports via %s instead.", VK_EXT_DEBUG_UTILS_EXTENSION_NAME,
debugReportAvailable ? VK_EXT_DEBUG_REPORT_EXTENSION_NAME : "(no channel)");
}
// ---------------- App info -------------------
VkApplicationInfo appInfo = {};
appInfo.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO;
@@ -7796,10 +7547,8 @@ void main() {
}
#endif
if (debugUtilsAvailable) {
if (m_validationLayersEnabled) {
exts.push_back(VK_EXT_DEBUG_UTILS_EXTENSION_NAME);
} else if (debugReportAvailable) {
exts.push_back(VK_EXT_DEBUG_REPORT_EXTENSION_NAME);
}
MGLOG_I("Enabling %d Vulkan instance extensions:", exts.size());
@@ -7824,8 +7573,7 @@ void main() {
MGLOG_I("Enabling validation layer...");
instanceInfo.enabledLayerCount = static_cast<uint32_t>(std::size(s_validationLayerNames));
instanceInfo.ppEnabledLayerNames = s_validationLayerNames;
// Chaining the messenger create-info is only legal with the extension on.
instanceInfo.pNext = debugUtilsAvailable ? &debugMessengerCreateInfo : nullptr;
instanceInfo.pNext = &debugMessengerCreateInfo;
} else {
instanceInfo.enabledLayerCount = 0;
instanceInfo.pNext = nullptr;
@@ -7833,40 +7581,7 @@ void main() {
VK_VERIFY(vkCreateInstance(&instanceInfo, nullptr, &m_instance), "vkCreateInstance failed");
if (debugUtilsAvailable) {
VK_VERIFY(SetupDebugMessenger());
} else if (debugReportAvailable) {
VK_VERIFY(SetupDebugReportCallback());
}
}
static VKAPI_ATTR VkBool32 VKAPI_CALL DebugReportCallback(VkDebugReportFlagsEXT flags, VkDebugReportObjectTypeEXT,
Uint64, size_t, Int32 messageCode, const char* pLayerPrefix,
const char* pMessage, void*) {
if ((flags & (VK_DEBUG_REPORT_ERROR_BIT_EXT | VK_DEBUG_REPORT_WARNING_BIT_EXT |
VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT)) != 0) {
MGLOG_F("[Vulkan %s %d] %s", pLayerPrefix ? pLayerPrefix : "?", messageCode, pMessage ? pMessage : "");
}
return VK_FALSE;
}
VkResult VulkanRenderer::SetupDebugReportCallback() {
auto vkCreateDebugReportCallbackEXT =
(PFN_vkCreateDebugReportCallbackEXT)vkGetInstanceProcAddr(m_instance, "vkCreateDebugReportCallbackEXT");
if (!vkCreateDebugReportCallbackEXT) return VK_ERROR_EXTENSION_NOT_PRESENT;
VkDebugReportCallbackCreateInfoEXT createInfo{VK_STRUCTURE_TYPE_DEBUG_REPORT_CALLBACK_CREATE_INFO_EXT};
createInfo.flags = VK_DEBUG_REPORT_ERROR_BIT_EXT | VK_DEBUG_REPORT_WARNING_BIT_EXT |
VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT;
createInfo.pfnCallback = &DebugReportCallback;
return vkCreateDebugReportCallbackEXT(m_instance, &createInfo, nullptr, &m_debugReportCallback);
}
void VulkanRenderer::DestroyDebugReportCallback() {
if (m_debugReportCallback == VK_NULL_HANDLE) return;
auto func = (PFN_vkDestroyDebugReportCallbackEXT)vkGetInstanceProcAddr(m_instance,
"vkDestroyDebugReportCallbackEXT");
if (func != nullptr) func(m_instance, m_debugReportCallback, nullptr);
m_debugReportCallback = VK_NULL_HANDLE;
if (m_validationLayersEnabled) VK_VERIFY(SetupDebugMessenger());
}
VkResult VulkanRenderer::SetupDebugMessenger() {
@@ -8612,38 +8327,6 @@ void main() {
return m_physicalDevice;
}
Bool VulkanRenderer::SwapchainIsOutOfDate() {
if (m_surface == VK_NULL_HANDLE || m_swapchainObject.GetHandle() == VK_NULL_HANDLE) {
return false;
}
VkSurfaceCapabilitiesKHR surfaceCaps{};
if (vkGetPhysicalDeviceSurfaceCapabilitiesKHR(m_physicalDevice.handle, m_surface, &surfaceCaps) !=
VK_SUCCESS) {
return false;
}
// A driver-defined currentExtent (UINT32_MAX) means the surface takes its size from the
// swapchain, so there is nothing to compare against - the app's requested size wins and
// only an explicit RequestSwapchainResize can change it.
if (surfaceCaps.currentExtent.width == UINT32_MAX || surfaceCaps.currentExtent.height == UINT32_MAX) {
return false;
}
// Compare in SURFACE space against the extent the live swapchain was created from. Using
// the swapchain's own (quarter-turn swapped) extent here would report a difference on
// every rotated frame and rebuild forever.
const VkExtent2D builtFrom = m_swapchainObject.GetSurfaceExtent();
const Bool extentChanged = surfaceCaps.currentExtent.width != builtFrom.width ||
surfaceCaps.currentExtent.height != builtFrom.height;
const Bool transformChanged = surfaceCaps.currentTransform != m_swapchainObject.GetPreTransform();
if (!extentChanged && !transformChanged) {
return false;
}
MGLOG_I("Swapchain out of date: surface %ux%u transform %u -> %ux%u transform %u",
builtFrom.width, builtFrom.height, static_cast<Uint32>(m_swapchainObject.GetPreTransform()),
surfaceCaps.currentExtent.width, surfaceCaps.currentExtent.height,
static_cast<Uint32>(surfaceCaps.currentTransform));
return true;
}
void VulkanRenderer::RequestSwapchainResize(Uint32 width, Uint32 height) {
width = std::max<Uint32>(width, 1);
height = std::max<Uint32>(height, 1);
@@ -8740,43 +8423,6 @@ void main() {
m_computePipelines.clear();
}
void VulkanRenderer::OnRenderPassesDestroyed(const Vector<VkRenderPass>& renderPasses) {
if (m_pipelineFactory == nullptr) {
return;
}
// The render-pass sweep's >1024-boundary idle guarantee covers these pipelines
// too (they are only bound by draws that hit the dying entries), so the factory
// destroys them immediately. The memo must drop as well: it can hand out a
// cached handle without touching the factory.
if (m_pipelineFactory->EvictByRenderPasses(renderPasses) > 0) {
m_lastPipelineValid = false;
m_lastPipelineResult = VK_NULL_HANDLE;
}
}
void VulkanRenderer::OnProgramEvicted(ProgramFactory::HashType programHash,
VkDescriptorSetLayout descriptorSetLayout) {
// Same >1024-boundary idleness as the program entry: its compute pipeline is
// only dispatched, and its graphics pipelines only bound, through paths that
// stamp the entry, so immediate destruction is GPU-safe. (The graphics memo
// never holds compute pipelines; it only needs invalidating for the factory
// eviction below.)
const auto computeIt = m_computePipelines.find(programHash);
if (computeIt != m_computePipelines.end()) {
if (computeIt->second != VK_NULL_HANDLE && m_device != VK_NULL_HANDLE) {
vkDestroyPipeline(m_device, computeIt->second, nullptr);
}
m_computePipelines.erase(computeIt);
}
if (m_pipelineFactory != nullptr && m_pipelineFactory->EvictByProgramHash(programHash) > 0) {
m_lastPipelineValid = false;
m_lastPipelineResult = VK_NULL_HANDLE;
}
if (m_uniformManager != nullptr) {
m_uniformManager->OnDescriptorSetLayoutDestroyed(descriptorSetLayout);
}
}
VkPipeline VulkanRenderer::GetOrCreateComputePipeline(const ProgramFactory::VkProgramObject& programObj) {
const auto it = m_computePipelines.find(programObj.hash);
if (it != m_computePipelines.end()) {
@@ -114,10 +114,7 @@ namespace MobileGL::MG_Backend::DirectVulkan {
}
};
class VulkanRenderer : public IBufferCopyCommandProvider,
public FrameContext::IRecordingObserver,
public VkRenderPassManager::IEvictionObserver,
public ProgramFactory::IEvictionObserver {
class VulkanRenderer : public IBufferCopyCommandProvider, public FrameContext::IRecordingObserver {
public:
VulkanRenderer(NativeWindowType window, const VulkanRendererConfig& cfg = {});
~VulkanRenderer();
@@ -134,20 +131,6 @@ namespace MobileGL::MG_Backend::DirectVulkan {
// recording, before any render pass.
void OnFrameCommandRecordingBegan(VkCommandBuffer commandBuffer) override;
// VkRenderPassManager::IEvictionObserver: the render-pass aging sweep just
// destroyed these VkRenderPasses; evict every graphics pipeline hashed on a
// dying handle (they share its >1024-boundary idleness, so immediate
// destruction is safe) and drop the last-pipeline memo if any went.
void OnRenderPassesDestroyed(const Vector<VkRenderPass>& renderPasses) override;
// ProgramFactory::IEvictionObserver: an aged-out program entry was
// destroyed; evict its compute pipeline and graphics pipelines (same
// idleness guarantee - they are only bound through draws/dispatches that
// stamp the program entry) and purge the descriptor-set cache entries
// keyed by its now-recyclable VkDescriptorSetLayout handle.
void OnProgramEvicted(ProgramFactory::HashType programHash,
VkDescriptorSetLayout descriptorSetLayout) override;
Bool SetupDraw(FrameContext::FrameData& frame, GLenum mode, Flags<DrawSetupAspect> aspects,
const DrawCmdParam& drawParams,
const IndexBufferView* pIndexBufferView = nullptr);
@@ -274,10 +257,6 @@ namespace MobileGL::MG_Backend::DirectVulkan {
Uint64 GetTimerQueryTimestampNs(const VkTimerQueryManager::TimestampRecord& record) const;
void RequestSwapchainResize(Uint32 width, Uint32 height);
// Re-query the surface and report whether the live swapchain no longer matches it
// (size or orientation). This - not a VK_SUBOPTIMAL_KHR result - is what decides a
// rebuild, so a surface the driver merely considers suboptimal cannot thrash.
Bool SwapchainIsOutOfDate();
// Returns false when the surface is zero-area (minimized/hidden window):
// no new swapchain is installed and presentation must stay suspended.
Bool RecreateSwapchain();
@@ -366,26 +345,11 @@ namespace MobileGL::MG_Backend::DirectVulkan {
VkFence AcquirePooledSubmitFence();
void DestroySubmitFencePool();
Bool HasPendingRecordedWork() const;
// Frame-boundary housekeeping for paths that never reach Present's
// tail (present-less readback loops, suspended presentation, blocking
// sync waits): runs the same per-frame drains Present performs, but
// only when every queue submission has been observed complete AND no
// recorded-but-unsubmitted commands exist - i.e. when CPU-GPU overlap
// is provably already zero. Never blocks (non-blocking fence poll
// only), so the presenting path's frames-in-flight pipelining is
// untouched. Returns true when the drain ran.
Bool TryDrainFrameTransients();
Vector<SubmitRecord> m_inFlightSubmits;
Vector<VkFence> m_freeSubmitFences;
Uint64 m_submitCounter = 0;
Uint64 m_completedSubmitCounter = 0;
// Drains since the last Present, gating the drain's frame-boundary-equivalent
// work (arena rewind + cache aging): a presenting app's mid-frame
// readbacks/waits must neither churn the transient caches nor accelerate the
// aging clocks, while present-less loops still cross a boundary every few
// iterations. Reset in Present.
Uint32 m_drainsSinceLastPresent = 0;
NativeWindowType m_window = 0;
void* m_platformDisplay = nullptr;
@@ -403,9 +367,6 @@ namespace MobileGL::MG_Backend::DirectVulkan {
Vector<VkExtensionProperties> m_extensions;
VkInstance m_instance = VK_NULL_HANDLE;
VkDebugUtilsMessengerEXT m_debugMessenger = VK_NULL_HANDLE;
// Fallback reporting channel for drivers that ship the validation layers but
// only expose the older VK_EXT_debug_report (Adreno 650 / Vulkan 1.1.128).
VkDebugReportCallbackEXT m_debugReportCallback = VK_NULL_HANDLE;
PhysicalDevice m_physicalDevice;
VkDevice m_device = VK_NULL_HANDLE;
VmaAllocator m_allocator = nullptr;
@@ -556,8 +517,6 @@ namespace MobileGL::MG_Backend::DirectVulkan {
void CreateInstance();
VkResult SetupDebugMessenger();
VkResult DestroyDebugMessenger();
VkResult SetupDebugReportCallback();
void DestroyDebugReportCallback();
VkDebugUtilsMessengerCreateInfoEXT PopulateDebugMessengerCreateInfo();
void CreateSurface();
void PickPhysicalDevice();
-33
View File
@@ -24,7 +24,6 @@ namespace MobileGL::MG_Impl::CGLImpl {
GLint Samples = 0;
GLint Profile = kCGLOGLPVersion_3_2_Core;
GLint RendererId = 0x4d474c;
GLint DisplayMask = 0;
};
struct ContextObject {
@@ -135,9 +134,6 @@ namespace MobileGL::MG_Impl::CGLImpl {
case kCGLPFARendererID:
pixelFormat.RendererId = value;
break;
case kCGLPFADisplayMask:
pixelFormat.DisplayMask = value;
break;
default:
break;
}
@@ -347,9 +343,6 @@ namespace MobileGL::MG_Impl::CGLImpl {
case kCGLPFARendererID:
*value = pixelFormat->RendererId;
return kCGLNoError;
case kCGLPFADisplayMask:
*value = pixelFormat->DisplayMask;
return kCGLNoError;
case kCGLPFAOpenGLProfile:
*value = pixelFormat->Profile;
return kCGLNoError;
@@ -488,32 +481,6 @@ namespace MobileGL::MG_Impl::CGLImpl {
return it == currentContexts.end() ? nullptr : it->second;
}
CGLError SetVirtualScreen(CGLContextObj ctx, GLint screen) {
const std::lock_guard<std::recursive_mutex> lock(RegistryMutex());
auto* object = TryGetContext(ctx);
if (!object) {
return kCGLBadContext;
}
if (screen != 0) {
return kCGLBadValue;
}
object->VirtualScreen = screen;
return kCGLNoError;
}
CGLError GetVirtualScreen(CGLContextObj ctx, GLint* screen) {
const std::lock_guard<std::recursive_mutex> lock(RegistryMutex());
auto* object = TryGetContext(ctx);
if (!object) {
return kCGLBadContext;
}
if (!screen) {
return kCGLBadAddress;
}
*screen = object->VirtualScreen;
return kCGLNoError;
}
CGLError SetParameter(CGLContextObj ctx, CGLContextParameter pname, const GLint* params) {
const std::lock_guard<std::recursive_mutex> lock(RegistryMutex());
auto* object = TryGetContext(ctx);
-2
View File
@@ -32,8 +32,6 @@ namespace MobileGL::MG_Impl::CGLImpl {
CGLError SetCurrentContext(CGLContextObj ctx);
CGLContextObj GetCurrentContext();
CGLError SetVirtualScreen(CGLContextObj ctx, GLint screen);
CGLError GetVirtualScreen(CGLContextObj ctx, GLint* screen);
CGLError SetParameter(CGLContextObj ctx, CGLContextParameter pname, const GLint* params);
CGLError GetParameter(CGLContextObj ctx, CGLContextParameter pname, GLint* params);
CGLError UpdateContext(CGLContextObj ctx);
@@ -71,14 +71,6 @@ MOBILEGL_CGL_API CGLContextObj CGLGetCurrentContext(void) {
return MobileGL::MG_Impl::CGLImpl::GetCurrentContext();
}
MOBILEGL_CGL_API CGLError CGLSetVirtualScreen(CGLContextObj ctx, GLint screen) {
return MobileGL::MG_Impl::CGLImpl::SetVirtualScreen(ctx, screen);
}
MOBILEGL_CGL_API CGLError CGLGetVirtualScreen(CGLContextObj ctx, GLint* screen) {
return MobileGL::MG_Impl::CGLImpl::GetVirtualScreen(ctx, screen);
}
MOBILEGL_CGL_API CGLError CGLSetParameter(CGLContextObj ctx, CGLContextParameter pname, const GLint* params) {
return MobileGL::MG_Impl::CGLImpl::SetParameter(ctx, pname, params);
}
@@ -10,12 +10,8 @@
#if defined(__APPLE__)
#include "MG_Impl/CGLImpl/CGLImpl.h"
#include "MG_Impl/GetProcAddress.h"
#include <CoreGraphics/CoreGraphics.h>
#include <CoreVideo/CVDisplayLink.h>
#include <cstdint>
#include <dlfcn.h>
namespace {
@@ -51,52 +47,10 @@ namespace {
return dlsym(handle, symbol);
}
CGDirectDisplayID DisplayForMask(GLint displayMask) {
constexpr std::uint32_t MaxDisplays = sizeof(CGOpenGLDisplayMask) * 8;
CGDirectDisplayID displays[MaxDisplays] = {};
std::uint32_t displayCount = 0;
if (displayMask != 0 &&
CGGetActiveDisplayList(MaxDisplays, displays, &displayCount) == kCGErrorSuccess) {
const auto mask = static_cast<CGOpenGLDisplayMask>(displayMask);
for (std::uint32_t i = 0; i < displayCount; ++i) {
if ((CGDisplayIDToOpenGLDisplayMask(displays[i]) & mask) != 0) {
return displays[i];
}
}
}
return CGMainDisplayID();
}
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
CVReturn MobileGLCVDisplayLinkSetCurrentCGDisplayFromOpenGLContext(
CVDisplayLinkRef displayLink,
CGLContextObj context,
CGLPixelFormatObj pixelFormat) {
GLint virtualScreen = 0;
if (MobileGL::MG_Impl::CGLImpl::GetVirtualScreen(context, &virtualScreen) == kCGLNoError) {
GLint displayMask = 0;
if (!displayLink ||
MobileGL::MG_Impl::CGLImpl::DescribePixelFormat(
pixelFormat, virtualScreen, kCGLPFADisplayMask, &displayMask) != kCGLNoError) {
return kCVReturnInvalidArgument;
}
return CVDisplayLinkSetCurrentCGDisplay(displayLink, DisplayForMask(displayMask));
}
using OriginalFunction = CVReturn (*)(CVDisplayLinkRef, CGLContextObj, CGLPixelFormatObj);
static const auto original = reinterpret_cast<OriginalFunction>(
dlsym(RTLD_NEXT, "CVDisplayLinkSetCurrentCGDisplayFromOpenGLContext"));
return original ? original(displayLink, context, pixelFormat) : kCVReturnError;
}
__attribute__((used)) static const DyldInterposeEntry kMobileGLDyldInterpose[]
__attribute__((section("__DATA,__interpose"))) = {
{reinterpret_cast<const void*>(MobileGLDlsym), reinterpret_cast<const void*>(dlsym)},
{reinterpret_cast<const void*>(MobileGLCVDisplayLinkSetCurrentCGDisplayFromOpenGLContext),
reinterpret_cast<const void*>(CVDisplayLinkSetCurrentCGDisplayFromOpenGLContext)},
};
#pragma clang diagnostic pop
} // namespace
#endif
@@ -1,10 +0,0 @@
# Public CGL entry points.
_CGL*
# Public EGL entry points.
_egl*
# Public OpenGL and GLX entry points. OpenGL function names always use an
# uppercase letter or digit after the "gl" prefix; excluding lowercase here
# deliberately prevents glslang_* from matching this pattern.
_gl[A-Z0-9]*
-29
View File
@@ -133,33 +133,4 @@ namespace MobileGL::MG_Impl::GLImpl {
values[0] = value;
}
}
void DestroyAllSyncObjects() {
// Detach the registry under the lock, release outside it. Entries the app
// already deleted were erased by DeleteSync, so nothing here double-frees;
// a DeleteSync racing this sweep finds an empty registry and returns. A
// thread still blocked inside ClientWaitSync/GetSynciv during teardown
// holds a raw SyncObject* these deletes invalidate - the same undefined
// race an app-driven DeleteSync already has.
UnorderedMap<GLsync, SyncObject*> orphans;
{
const std::lock_guard<std::mutex> lock(g_syncObjectsMutex);
orphans.swap(g_liveSyncObjects);
}
if (orphans.empty()) {
return;
}
// Both backends' DeleteSync only free the heap wrapper once their GL
// context/renderer is gone (generation/current-thread guards), so this is
// safe after the backend has released its EGL resources - but not after
// the function table itself is cleared.
const auto backendDeleteSync = MG_Backend::gBackendFunctionsTable.GL.DeleteSync;
for (const auto& [_, syncObject] : orphans) {
if (backendDeleteSync && syncObject->backendHandle) {
backendDeleteSync(syncObject->backendHandle);
}
delete syncObject;
}
MGLOG_D("DestroyAllSyncObjects: reclaimed %zu sync object(s) the app left undeleted", orphans.size());
}
} // namespace MobileGL::MG_Impl::GLImpl
-8
View File
@@ -16,12 +16,4 @@ namespace MobileGL::MG_Impl::GLImpl {
void WaitSync(GLsync sync, GLbitfield flags, GLuint64 timeout);
void DeleteSync(GLsync sync);
void GetSynciv(GLsync sync, GLenum pname, GLsizei bufSize, GLsizei* length, GLint* values);
// Destroys every still-registered sync object exactly as DeleteSync would.
// GL requires syncs to die with their context; called only from full library
// teardown (DestroyImpl), where no context survives on any thread, so the
// process-global registry can be drained wholesale. Must run while the
// backend function table is still populated: each backend handle has to be
// released by the backend that created it, never by a later re-initialized
// one.
void DestroyAllSyncObjects();
} // namespace MobileGL::MG_Impl::GLImpl
-2
View File
@@ -85,8 +85,6 @@ namespace MobileGL::MG_Impl {
GETPROC(CGLGetPixelFormat, name);
GETPROC(CGLSetCurrentContext, name);
GETPROC(CGLGetCurrentContext, name);
GETPROC(CGLSetVirtualScreen, name);
GETPROC(CGLGetVirtualScreen, name);
GETPROC(CGLSetParameter, name);
GETPROC(CGLGetParameter, name);
GETPROC(CGLUpdateContext, name);
+4 -36
View File
@@ -29,19 +29,10 @@ namespace MobileGL::MG_Impl::NSOpenGLImpl {
char kContextViewKey;
char kContextLayerKey;
std::once_flag g_installOnce;
IMP g_pixelFormatDealloc = nullptr;
IMP g_contextDealloc = nullptr;
std::mutex& HookInstallMutex() {
static auto* mutex = new std::mutex();
return *mutex;
}
Bool& HooksInstalled() {
static auto* installed = new Bool(false);
return *installed;
}
template <typename Fn>
Fn ObjcMsgSend() {
return reinterpret_cast<Fn>(objc_msgSend);
@@ -440,12 +431,12 @@ namespace MobileGL::MG_Impl::NSOpenGLImpl {
method_setImplementation(method, replacement);
}
Bool InstallHooksOnce() {
void InstallHooksOnce() {
Class pixelFormatClass = objc_getClass("NSOpenGLPixelFormat");
Class contextClass = objc_getClass("NSOpenGLContext");
if (!pixelFormatClass || !contextClass) {
MGLOG_W("NSOpenGLImpl: NSOpenGL classes are not loaded; hooks not installed");
return false;
return;
}
ReplaceInstanceMethod(pixelFormatClass, "initWithAttributes:",
@@ -480,34 +471,11 @@ namespace MobileGL::MG_Impl::NSOpenGLImpl {
ReplaceInstanceMethod(contextClass, "dealloc", reinterpret_cast<IMP>(ContextDealloc), &g_contextDealloc);
MGLOG_I("NSOpenGLImpl hooks installed");
return true;
}
} // namespace
void InstallHooks() {
const std::lock_guard<std::mutex> lock(HookInstallMutex());
if (!HooksInstalled()) {
// Do not permanently consume the install attempt when the OpenGL
// framework has not registered its Objective-C classes yet. The
// dyld bootstrap normally runs after framework dependencies, but
// an explicitly loaded/static-linked MobileGL can arrive earlier.
HooksInstalled() = InstallHooksOnce();
}
std::call_once(g_installOnce, InstallHooksOnce);
}
} // namespace MobileGL::MG_Impl::NSOpenGLImpl
namespace {
// SDL's Cocoa backend creates NSOpenGLPixelFormat/NSOpenGLContext before
// its first dlsym("glGetString") or other MobileGL host-API call. Install
// only the lightweight Objective-C dispatch hooks while the injected dylib
// is loading so those first Cocoa objects are routed through CGLImpl. The
// hooked context constructor reaches EGLImpl::GetDisplay(), which performs
// the full, thread-safe MobileGL initialization outside this bootstrap.
//
// There is intentionally no matching destructor: backend teardown remains
// owned by the EGL lifecycle and process-exit globals remain leak-at-exit.
__attribute__((constructor)) void BootstrapNSOpenGLHooks() {
MobileGL::MG_Impl::NSOpenGLImpl::InstallHooks();
}
} // namespace
#endif
@@ -15,11 +15,7 @@
#include <MG_Util/Math/VectorTypes.h>
namespace MobileGL::MG_State::GLState {
// Texture objects are always SharedPtr-owned (TextureState creates every instance via
// MakeShared, including the per-target default objects). enable_shared_from_this lets
// backends that only receive a reference (e.g. syncing a name-deleted texture kept
// alive by an FBO attachment) still register a weak liveness reference for GC.
class ITextureObject : public std::enable_shared_from_this<ITextureObject> {
class ITextureObject {
public:
using TargetEnum = TextureTarget;
virtual ~ITextureObject() = default;
-59
View File
@@ -33,7 +33,6 @@
#include <MG_Util/ShaderTranspiler/ShaderCompiler.h>
#include <MG_Util/ShaderTranspiler/ShaderSourceProcessor.h>
#include <MG_Util/Debug/Log.h>
#include <FastSTL/UnorderedMap.h>
namespace {
class DynamicParameterBackend final : public MobileGL::MG_Backend::BackendObject {
@@ -1737,61 +1736,3 @@ TEST(DirectGLESStateGuards, DefaultFramebufferBindGoesThroughShadow) {
FramebufferImpl::BindFramebufferId(GL_DRAW_FRAMEBUFFER, 7); // must reach the driver again
EXPECT_EQ(mocks.log.Count("BindFramebuffer:"), 3u);
}
// FastSTL::unordered_map::erase(iterator) regression coverage. The open-addressing
// iterator constructor snaps forward from a tombstoned slot to the successor, so
// erase must NOT advance the rebuilt iterator again: the old double-advance skipped
// one live element per erase, and erasing the element in the highest occupied
// bucket pushed the returned index past bucket_count where it never compared equal
// to end() again - erase-while-iterating sweeps (pipeline/program cache eviction)
// then ran off the bucket array and fed garbage handles to vkDestroyPipeline
// (device crash on first mass eviction during world load).
TEST(FastSTLSanity, EraseWhileIteratingVisitsEveryElementExactlyOnce) {
FastSTL::unordered_map<MobileGL::Uint64, MobileGL::Uint64> map;
constexpr MobileGL::Uint64 kCount = 1000;
for (MobileGL::Uint64 key = 0; key < kCount; ++key) {
map.emplace(key * 0x9e3779b97f4a7c15ull, key);
}
ASSERT_EQ(map.size(), kCount);
MobileGL::SizeT visited = 0;
for (auto it = map.begin(); it != map.end();) {
it = map.erase(it);
++visited;
ASSERT_LE(visited, kCount); // old code: runaway past end / skipped entries
}
EXPECT_EQ(visited, kCount);
EXPECT_EQ(map.size(), 0u);
}
TEST(FastSTLSanity, EraseReturnsTheSuccessorElement) {
FastSTL::unordered_map<MobileGL::Uint32, MobileGL::Uint32> map;
for (MobileGL::Uint32 key = 1; key <= 64; ++key) {
map.emplace(key, key);
}
// Erasing every other visited element must still visit all 64 exactly once:
// the iterator returned by erase names the very next element, not one past it.
MobileGL::SizeT visited = 0;
MobileGL::SizeT erased = 0;
for (auto it = map.begin(); it != map.end();) {
++visited;
if ((visited & 1) != 0) {
it = map.erase(it);
++erased;
} else {
++it;
}
ASSERT_LE(visited, 64u);
}
EXPECT_EQ(visited, 64u);
EXPECT_EQ(map.size(), 64u - erased);
}
TEST(FastSTLSanity, ErasingTheOnlyElementReturnsEnd) {
FastSTL::unordered_map<MobileGL::Uint32, MobileGL::Uint32> map;
map.emplace(42u, 1u);
auto next = map.erase(map.begin());
EXPECT_EQ(next, map.end());
EXPECT_TRUE(map.empty());
}
@@ -133,11 +133,9 @@ namespace MobileGL {
case TextureInternalFormat::RGBA8Snorm:
return VK_FORMAT_R8G8B8A8_SNORM;
case TextureInternalFormat::RGB10A2:
// GL_UNSIGNED_INT_2_10_10_10_REV puts R in bits 0-9, which is Vulkan's
// A2B10G10R10 layout - A2R10G10B10 silently swaps R and B on upload.
return VK_FORMAT_A2B10G10R10_UNORM_PACK32;
return VK_FORMAT_A2R10G10B10_UNORM_PACK32;
case TextureInternalFormat::RGB10A2UI:
return VK_FORMAT_A2B10G10R10_UINT_PACK32;
return VK_FORMAT_A2R10G10B10_UINT_PACK32;
case TextureInternalFormat::RGBA16:
return VK_FORMAT_R16G16B16A16_UNORM;
case TextureInternalFormat::RGBA16Snorm:
+7 -3
View File
@@ -9,10 +9,14 @@
#pragma once
#include <Includes.h>
// Severity-ordered: a build compiled at level X keeps X and everything MORE
// severe. INFO builds must keep WARN/ERROR/FATAL — the old ordering
// (WARN=1/ERROR=2 below INFO=3) compiled every warning and error out of
// release builds and hid real backend failures.
#define MOBILEGL_LOG_LEVEL_DEBUG 0
#define MOBILEGL_LOG_LEVEL_WARN 1
#define MOBILEGL_LOG_LEVEL_ERROR 2
#define MOBILEGL_LOG_LEVEL_INFO 3
#define MOBILEGL_LOG_LEVEL_INFO 1
#define MOBILEGL_LOG_LEVEL_WARN 2
#define MOBILEGL_LOG_LEVEL_ERROR 3
#define MOBILEGL_LOG_LEVEL_FATAL 4
#define MOBILEGL_LOG_INTERNAL(levelTag, androidLogLevel, fmt, ...) \
@@ -22,6 +22,9 @@
#include "SpirvPasses/StripUboMemberRelaxedPrecisionPass.h"
#include "SpirvPasses/StripNoPerspectivePass.h"
#include "SpirvPasses/EmulateNoPerspectivePass.h"
#include "SpirvPasses/FoldConstOffsetFor1DFetchPass.h"
#include "SpirvPasses/LowerClipDistanceForEsslPass.h"
#include "SpirvPasses/DefeatConstStructArrayLutPass.h"
#include "spirv-tools/libspirv.h"
#include "spirv-tools/optimizer.hpp"
@@ -323,6 +326,55 @@ namespace MobileGL {
return optimizer.Run(inputBinary.data(), inputBinary.size(), &outputBinary, options);
}
bool ShaderCompiler::ClampAccessChainIndicesForEssl(const Vector<Uint32>& inputBinary,
Vector<uint32_t>& outputBinary) {
using namespace spvtools;
OptimizerOptions options;
options.set_run_validator(false);
Optimizer optimizer(SPV_ENV_VULKAN_1_1);
optimizer.RegisterPass(CreateGraphicsRobustAccessPass());
return optimizer.Run(inputBinary.data(), inputBinary.size(), &outputBinary, options);
}
bool ShaderCompiler::FoldConstOffsetFor1DFetchForEssl(const Vector<Uint32>& inputBinary,
Vector<uint32_t>& outputBinary) {
using namespace spvtools;
OptimizerOptions options;
options.set_run_validator(false);
Optimizer optimizer(SPV_ENV_VULKAN_1_1);
optimizer.RegisterPass(FoldConstOffsetFor1DFetchPass::CreateFoldConstOffsetFor1DFetchPass());
return optimizer.Run(inputBinary.data(), inputBinary.size(), &outputBinary, options);
}
bool ShaderCompiler::LowerClipDistanceForEssl(const Vector<Uint32>& inputBinary,
Vector<uint32_t>& outputBinary) {
using namespace spvtools;
OptimizerOptions options;
options.set_run_validator(false);
Optimizer optimizer(SPV_ENV_VULKAN_1_1);
optimizer.RegisterPass(LowerClipDistanceForEsslPass::CreateLowerClipDistanceForEsslPass());
return optimizer.Run(inputBinary.data(), inputBinary.size(), &outputBinary, options);
}
bool ShaderCompiler::DefeatConstStructArrayLutForEssl(const Vector<Uint32>& inputBinary,
Vector<uint32_t>& outputBinary) {
using namespace spvtools;
OptimizerOptions options;
options.set_run_validator(false);
Optimizer optimizer(SPV_ENV_VULKAN_1_1);
optimizer.RegisterPass(
DefeatConstStructArrayLutPass::CreateDefeatConstStructArrayLutPass());
return optimizer.Run(inputBinary.data(), inputBinary.size(), &outputBinary, options);
}
bool ShaderCompiler::StripUboMemberRelaxedPrecisionForEssl(const Vector<Uint32>& inputBinary,
Vector<uint32_t>& outputBinary) {
using namespace spvtools;
@@ -27,6 +27,36 @@ namespace MobileGL {
// Only for backends without native draw-parameter support (DirectGLES).
static bool LowerDrawParametersForEssl(const Vector<Uint32>& inputBinary,
Vector<uint32_t>& outputBinary);
// Clamps every access-chain index to its declared bounds (spirv-tools
// GraphicsRobustAccessPass). GL 3.3 only promises undefined *values* for
// out-of-bounds indexing, but Adreno's ESSL compiler constant-folds a provably
// out-of-bounds local-array index into poison that corrupts the whole shader's
// output; clamping restores the "some value from the array" contract. Only for
// the DirectGLES transpile path.
static bool ClampAccessChainIndicesForEssl(const Vector<Uint32>& inputBinary,
Vector<uint32_t>& outputBinary);
// Folds the ConstOffset image operand of Dim1D OpImageFetch into the integer
// coordinate (texelFetchOffset(t,P,l,o) == texelFetch(t,P+o,l)). SPIRV-Cross
// emulates 1D samplers as 2D for ES: it widens the coordinate to ivec2 but keeps
// the scalar offset, and ESSL has no texelFetchOffset(sampler2D, ivec2, int,
// scalar) overload, so Adreno rejects the shader. Only for the DirectGLES
// transpile path.
static bool FoldConstOffsetFor1DFetchForEssl(const Vector<Uint32>& inputBinary,
Vector<uint32_t>& outputBinary);
// Shadows gl_ClipDistance in Private mg_ClipDistance/mg_ClipDistanceIn arrays so
// the decompiled ESSL only writes the builtin with literal constant indices
// (flush before EmitVertex/return) and only reads gl_in clip distances with
// dynamic loop indices (copy loop): the other shapes miscompile or crash
// Adreno's ESSL compiler. Vertex/geometry stages; DirectGLES transpile path on
// Qualcomm only (quirk-gated). See LowerClipDistanceForEsslPass.
static bool LowerClipDistanceForEssl(const Vector<Uint32>& inputBinary,
Vector<uint32_t>& outputBinary);
// Splits a Function-storage array-of-structs variable's single constant-composite
// store into per-element stores so SPIRV-Cross does not hoist it into a global
// const struct[] LUT, which Adreno cannot dynamically index. DirectGLES
// transpile path on Qualcomm only (quirk-gated). See DefeatConstStructArrayLutPass.
static bool DefeatConstStructArrayLutForEssl(const Vector<Uint32>& inputBinary,
Vector<uint32_t>& outputBinary);
// Drops RelaxedPrecision member decorations from uniform-block structs so
// SPIRV-Cross prints the same (highp) member precision in every stage; ES
// drivers reject cross-stage uniform blocks whose member precisions differ.
@@ -0,0 +1,175 @@
// MobileGL - MobileGL/MG_Util/ShaderTranspiler/SpirvPasses/DefeatConstStructArrayLutPass.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
#include "DefeatConstStructArrayLutPass.h"
#include "spirv.hpp"
#include "source/opt/constants.h"
#include "source/opt/def_use_manager.h"
#include "source/opt/instruction.h"
#include "source/opt/ir_context.h"
#include "source/opt/module.h"
#include "source/opt/type_manager.h"
#include "source/opt/types.h"
#include "source/util/make_unique.h"
#include <vector>
namespace MobileGL {
namespace MG_Util {
namespace ShaderTranspiler {
namespace {
using spvtools::opt::BasicBlock;
using spvtools::opt::Function;
using spvtools::opt::Instruction;
using spvtools::opt::IRContext;
using spvtools::opt::Operand;
namespace analysis = spvtools::opt::analysis;
uint32_t PointerTypeTo(IRContext* ctx, uint32_t pointeeId, spv::StorageClass sc) {
analysis::Type* pointee = ctx->get_type_mgr()->GetType(pointeeId);
analysis::Pointer ptr(pointee, sc);
return ctx->get_type_mgr()->GetTypeInstruction(&ptr);
}
uint32_t SignedIntConstant(IRContext* ctx, uint32_t value) {
analysis::Integer i(32, true);
analysis::Type* reg = ctx->get_type_mgr()->GetRegisteredType(&i);
const analysis::Constant* c = ctx->get_constant_mgr()->GetConstant(reg, {value});
return ctx->get_constant_mgr()->GetDefiningInstruction(c)->result_id();
}
// True when |var| (a Function-storage OpVariable) points to an array of structs.
// Reports the struct type id on success.
bool IsArrayOfStructsVariable(IRContext* ctx, Instruction* var, uint32_t& structTypeId) {
auto* defUse = ctx->get_def_use_mgr();
Instruction* ptrType = defUse->GetDef(var->type_id());
if (ptrType == nullptr || ptrType->opcode() != spv::Op::OpTypePointer) return false;
Instruction* pointee = defUse->GetDef(ptrType->GetSingleWordInOperand(1));
if (pointee == nullptr || pointee->opcode() != spv::Op::OpTypeArray) return false;
Instruction* element = defUse->GetDef(pointee->GetSingleWordInOperand(0));
if (element == nullptr || element->opcode() != spv::Op::OpTypeStruct) return false;
structTypeId = element->result_id();
return true;
}
} // namespace
spvtools::opt::Pass::Status DefeatConstStructArrayLutPass::Process() {
auto* ctx = context();
auto* defUse = ctx->get_def_use_mgr();
bool modified = false;
for (Function& function : *get_module()) {
if (function.begin() == function.end()) continue;
BasicBlock* entryBlock = &*function.begin();
// Candidate variables: Function-storage arrays of structs declared in this
// function's entry block (where OpVariables must live).
struct Candidate {
Instruction* var;
uint32_t structTypeId;
};
std::vector<Candidate> candidates;
for (Instruction& inst : *entryBlock) {
if (inst.opcode() != spv::Op::OpVariable) break;
// Variables with initializers keep SPIRV-Cross's initializer path; the
// glslang pattern under attack is initializer-free with one OpStore.
if (inst.NumInOperands() > 1) continue;
uint32_t structTypeId = 0;
if (IsArrayOfStructsVariable(ctx, &inst, structTypeId)) {
candidates.push_back({&inst, structTypeId});
}
}
for (const Candidate& candidate : candidates) {
Instruction* var = candidate.var;
// The variable qualifies only when its single write is one direct
// OpStore of an OpConstantComposite; any other write shape already
// defeats SPIRV-Cross's LUT promotion, so it is left untouched.
Instruction* singleStore = nullptr;
bool disqualified = false;
defUse->ForEachUser(var, [&](Instruction* user) {
if (user->opcode() == spv::Op::OpStore &&
user->GetSingleWordInOperand(0) == var->result_id()) {
if (singleStore != nullptr) {
disqualified = true;
} else {
singleStore = user;
}
} else if (user->opcode() == spv::Op::OpCopyMemory) {
disqualified = true;
} else if (user->opcode() == spv::Op::OpAccessChain ||
user->opcode() == spv::Op::OpInBoundsAccessChain) {
defUse->ForEachUser(user, [&](Instruction* chainUser) {
if (chainUser->opcode() == spv::Op::OpStore ||
chainUser->opcode() == spv::Op::OpCopyMemory) {
disqualified = true;
}
});
}
});
if (disqualified || singleStore == nullptr) continue;
Instruction* composite = defUse->GetDef(singleStore->GetSingleWordInOperand(1));
if (composite == nullptr ||
composite->opcode() != spv::Op::OpConstantComposite) {
continue;
}
// The store must sit in the entry block: that is the only placement
// SPIRV-Cross treats as a LUT initializer.
bool storeInEntryBlock = false;
for (Instruction& inst : *entryBlock) {
if (&inst == singleStore) {
storeInEntryBlock = true;
break;
}
}
if (!storeInEntryBlock) continue;
// Split the composite store into one constant-index store per element.
const uint32_t ptrFnStruct =
PointerTypeTo(ctx, candidate.structTypeId, spv::StorageClass::Function);
for (uint32_t element = 0; element < composite->NumInOperands(); ++element) {
const uint32_t elementConstId = composite->GetSingleWordInOperand(element);
const uint32_t chainId = ctx->TakeNextId();
Instruction* chain =
singleStore->InsertBefore(spvtools::MakeUnique<Instruction>(
ctx, spv::Op::OpAccessChain, ptrFnStruct, chainId,
std::initializer_list<Operand>{
{SPV_OPERAND_TYPE_ID, {var->result_id()}},
{SPV_OPERAND_TYPE_ID, {SignedIntConstant(ctx, element)}}}));
ctx->AnalyzeDefUse(chain);
Instruction* store =
singleStore->InsertBefore(spvtools::MakeUnique<Instruction>(
ctx, spv::Op::OpStore, 0, 0,
std::initializer_list<Operand>{
{SPV_OPERAND_TYPE_ID, {chainId}},
{SPV_OPERAND_TYPE_ID, {elementConstId}}}));
ctx->AnalyzeDefUse(store);
}
ctx->KillInst(singleStore);
modified = true;
}
}
if (!modified) {
return Status::SuccessWithoutChange;
}
ctx->InvalidateAnalysesExceptFor(spvtools::opt::IRContext::kAnalysisNone);
return Status::SuccessWithChange;
}
spvtools::Optimizer::PassToken
DefeatConstStructArrayLutPass::CreateDefeatConstStructArrayLutPass() {
return spvtools::Optimizer::PassToken(MakeUnique<DefeatConstStructArrayLutPass>());
}
} // namespace ShaderTranspiler
} // namespace MG_Util
} // namespace MobileGL
@@ -0,0 +1,36 @@
// MobileGL - MobileGL/MG_Util/ShaderTranspiler/SpirvPasses/DefeatConstStructArrayLutPass.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 "source/opt/pass.h"
#include "spirv-tools/optimizer.hpp"
#include <Includes.h>
namespace MobileGL {
namespace MG_Util {
namespace ShaderTranspiler {
// SPIRV-Cross hoists a Function-storage array variable whose only write is a single
// constant-composite store into a global `const struct[]` LUT (variable_is_lut).
// Adreno's ESSL compiler cannot dynamically index such a global const struct array
// ("Cannot offset into the structure" - device-verified on Adreno 750). Splitting
// the one composite store into per-element constant-index stores makes
// variable_is_lut fail, so SPIRV-Cross keeps the array as an ordinary local that
// Adreno indexes fine. Scalar/vector const arrays are unaffected on Adreno and are
// left alone - only arrays OF STRUCTS are rewritten. Only meant for the DirectGLES
// transpile path on Qualcomm devices.
class DefeatConstStructArrayLutPass : public spvtools::opt::Pass {
public:
const char* name() const override { return "defeat-const-struct-array-lut"; }
Status Process() override;
static spvtools::Optimizer::PassToken CreateDefeatConstStructArrayLutPass();
};
} // namespace ShaderTranspiler
} // namespace MG_Util
} // namespace MobileGL
@@ -0,0 +1,131 @@
// MobileGL - MobileGL/MG_Util/ShaderTranspiler/SpirvPasses/FoldConstOffsetFor1DFetchPass.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
#include "FoldConstOffsetFor1DFetchPass.h"
#include "spirv.hpp"
#include "source/opt/def_use_manager.h"
#include "source/opt/instruction.h"
#include "source/opt/ir_builder.h"
#include "source/opt/ir_context.h"
#include "source/opt/module.h"
#include "source/util/make_unique.h"
#include <vector>
namespace MobileGL {
namespace MG_Util {
namespace ShaderTranspiler {
namespace {
using spvtools::opt::Instruction;
using spvtools::opt::InstructionBuilder;
using spvtools::opt::IRContext;
using spvtools::opt::Operand;
// Number of ImageOperands ids that precede the ConstOffset id: one per
// lower-order bit set in the mask, except Grad which carries two ids.
uint32_t CountIdsBeforeConstOffset(uint32_t mask) {
uint32_t count = 0;
if (mask & static_cast<uint32_t>(spv::ImageOperandsMask::Bias)) count += 1;
if (mask & static_cast<uint32_t>(spv::ImageOperandsMask::Lod)) count += 1;
if (mask & static_cast<uint32_t>(spv::ImageOperandsMask::Grad)) count += 2;
return count;
}
} // namespace
spvtools::opt::Pass::Status FoldConstOffsetFor1DFetchPass::Process() {
auto* irContext = context();
auto* defUseMgr = irContext->get_def_use_mgr();
Bool modified = false;
constexpr uint32_t kConstOffsetBit =
static_cast<uint32_t>(spv::ImageOperandsMask::ConstOffset);
for (auto& function : *get_module()) {
for (auto& block : function) {
for (auto& inst : block) {
if (inst.opcode() != spv::Op::OpImageFetch) continue;
// In-operands: image, coordinate, [ImageOperands mask, ids...].
if (inst.NumInOperands() < 3) continue;
const uint32_t operandsMask = inst.GetSingleWordInOperand(2);
if ((operandsMask & kConstOffsetBit) == 0) continue;
Instruction* imageInst = defUseMgr->GetDef(inst.GetSingleWordInOperand(0));
if (imageInst == nullptr) continue;
Instruction* imageType = defUseMgr->GetDef(imageInst->type_id());
if (imageType == nullptr || imageType->opcode() != spv::Op::OpTypeImage ||
static_cast<spv::Dim>(imageType->GetSingleWordInOperand(1)) != spv::Dim::Dim1D) {
continue;
}
const uint32_t offsetOperandIndex = 3 + CountIdsBeforeConstOffset(operandsMask);
const uint32_t offsetId = inst.GetSingleWordInOperand(offsetOperandIndex);
const uint32_t coordId = inst.GetSingleWordInOperand(1);
Instruction* coordType = defUseMgr->GetDef(defUseMgr->GetDef(coordId)->type_id());
InstructionBuilder builder(
irContext, &inst,
IRContext::kAnalysisDefUse | IRContext::kAnalysisInstrToBlockMapping);
uint32_t newCoordId = 0;
if (coordType->opcode() == spv::Op::OpTypeVector) {
// Arrayed 1D fetch: component 0 is the texel coordinate,
// component 1 the layer - only component 0 takes the offset.
const uint32_t componentTypeId = coordType->GetSingleWordInOperand(0);
Instruction* extracted = builder.AddCompositeExtract(componentTypeId, coordId, {0});
Instruction* sum =
builder.AddIAdd(componentTypeId, extracted->result_id(), offsetId);
Instruction* inserted = builder.AddInstruction(spvtools::MakeUnique<Instruction>(
irContext, spv::Op::OpCompositeInsert, coordType->result_id(),
irContext->TakeNextId(),
std::initializer_list<Operand>{
{SPV_OPERAND_TYPE_ID, {sum->result_id()}},
{SPV_OPERAND_TYPE_ID, {coordId}},
{SPV_OPERAND_TYPE_LITERAL_INTEGER, {0}}}));
newCoordId = inserted->result_id();
} else {
Instruction* sum = builder.AddIAdd(coordType->result_id(), coordId, offsetId);
newCoordId = sum->result_id();
}
const uint32_t newMask = operandsMask & ~kConstOffsetBit;
// 3 fixed operands + the offset id: anything beyond that is another
// image-operand id that must keep the mask word alive.
const Bool otherOperandIdsRemain = inst.NumInOperands() > 4;
irContext->ForgetUses(&inst);
std::vector<Operand> newOperands;
newOperands.push_back(inst.GetInOperand(0));
newOperands.push_back({SPV_OPERAND_TYPE_ID, {newCoordId}});
if (newMask != 0 || otherOperandIdsRemain) {
Operand maskOperand = inst.GetInOperand(2);
maskOperand.words[0] = newMask;
newOperands.push_back(maskOperand);
for (uint32_t i = 3; i < inst.NumInOperands(); ++i) {
if (i == offsetOperandIndex) continue;
newOperands.push_back(inst.GetInOperand(i));
}
}
inst.SetInOperands(std::move(newOperands));
irContext->AnalyzeUses(&inst);
modified = true;
}
}
}
return modified ? Status::SuccessWithChange : Status::SuccessWithoutChange;
}
spvtools::Optimizer::PassToken FoldConstOffsetFor1DFetchPass::CreateFoldConstOffsetFor1DFetchPass() {
return spvtools::Optimizer::PassToken(MakeUnique<FoldConstOffsetFor1DFetchPass>());
}
} // namespace ShaderTranspiler
} // namespace MG_Util
} // namespace MobileGL
@@ -0,0 +1,36 @@
// MobileGL - MobileGL/MG_Util/ShaderTranspiler/SpirvPasses/FoldConstOffsetFor1DFetchPass.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 "source/opt/pass.h"
#include "spirv-tools/optimizer.hpp"
#include <Includes.h>
namespace MobileGL {
namespace MG_Util {
namespace ShaderTranspiler {
// SPIRV-Cross emulates 1D textures as 2D for ES targets: it widens the texelFetch
// coordinate to ivec2 but keeps the ConstOffset image operand scalar, and ESSL has
// no texelFetchOffset(sampler2D, ivec2, int, scalar-offset) overload, so drivers
// (Adreno) reject the transpiled shader. This pass folds the constant offset into
// the integer coordinate before the fetch - texelFetchOffset(t, P, l, o) ==
// texelFetch(t, P + o, l) per the GLSL spec - and drops the ConstOffset operand,
// so SPIRV-Cross emits a plain texelFetch. For arrayed 1D fetches only coordinate
// component 0 is offset (component 1 is the layer). Only meant for the DirectGLES
// transpile path.
class FoldConstOffsetFor1DFetchPass : public spvtools::opt::Pass {
public:
const char* name() const override { return "fold-const-offset-for-1d-fetch"; }
Status Process() override;
static spvtools::Optimizer::PassToken CreateFoldConstOffsetFor1DFetchPass();
};
} // namespace ShaderTranspiler
} // namespace MG_Util
} // namespace MobileGL
@@ -0,0 +1,613 @@
// MobileGL - MobileGL/MG_Util/ShaderTranspiler/SpirvPasses/LowerClipDistanceForEsslPass.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
#include "LowerClipDistanceForEsslPass.h"
#include "spirv.hpp"
#include "source/opt/basic_block.h"
#include "source/opt/constants.h"
#include "source/opt/def_use_manager.h"
#include "source/opt/instruction.h"
#include "source/opt/ir_context.h"
#include "source/opt/module.h"
#include "source/opt/type_manager.h"
#include "source/opt/types.h"
#include "source/util/make_unique.h"
#include <memory>
#include <vector>
namespace MobileGL {
namespace MG_Util {
namespace ShaderTranspiler {
namespace {
using spvtools::opt::BasicBlock;
using spvtools::opt::Function;
using spvtools::opt::Instruction;
using spvtools::opt::IRContext;
using spvtools::opt::Operand;
namespace analysis = spvtools::opt::analysis;
spv::ExecutionModel EntryExecutionModel(IRContext* ctx) {
for (Instruction& ep : ctx->module()->entry_points()) {
return static_cast<spv::ExecutionModel>(ep.GetSingleWordInOperand(0));
}
return spv::ExecutionModel::Max;
}
uint32_t EntryFunctionId(IRContext* ctx) {
for (Instruction& ep : ctx->module()->entry_points()) {
// OpEntryPoint <model> <function> "name" <interface...>
return ep.GetSingleWordInOperand(1);
}
return 0;
}
uint32_t VariablePointeeType(IRContext* ctx, Instruction* var) {
Instruction* ptrType = ctx->get_def_use_mgr()->GetDef(var->type_id());
// OpTypePointer <storage-class> <pointee>
return ptrType->GetSingleWordInOperand(1);
}
uint32_t PointerTypeTo(IRContext* ctx, uint32_t pointeeId, spv::StorageClass sc) {
analysis::Type* pointee = ctx->get_type_mgr()->GetType(pointeeId);
analysis::Pointer ptr(pointee, sc);
return ctx->get_type_mgr()->GetTypeInstruction(&ptr);
}
uint32_t IntConstant(IRContext* ctx, bool isSigned, uint32_t value) {
analysis::Integer i(32, isSigned);
analysis::Type* reg = ctx->get_type_mgr()->GetRegisteredType(&i);
const analysis::Constant* c = ctx->get_constant_mgr()->GetConstant(reg, {value});
return ctx->get_constant_mgr()->GetDefiningInstruction(c)->result_id();
}
uint32_t UintType(IRContext* ctx) {
analysis::Integer i(32, false);
return ctx->get_type_mgr()->GetTypeInstruction(&i);
}
uint32_t BoolType(IRContext* ctx) {
analysis::Bool b;
return ctx->get_type_mgr()->GetTypeInstruction(&b);
}
// Constant length of OpTypeArray |arrayTypeId| (0 when not a sized constant).
uint32_t ArrayLength(IRContext* ctx, uint32_t arrayTypeId) {
Instruction* arrayType = ctx->get_def_use_mgr()->GetDef(arrayTypeId);
if (arrayType == nullptr || arrayType->opcode() != spv::Op::OpTypeArray) {
return 0;
}
Instruction* length = ctx->get_def_use_mgr()->GetDef(arrayType->GetSingleWordInOperand(1));
if (length == nullptr || length->opcode() != spv::Op::OpConstant) {
return 0;
}
return length->GetSingleWordInOperand(0);
}
bool IsConstantWithValue(IRContext* ctx, uint32_t id, uint32_t value) {
Instruction* def = ctx->get_def_use_mgr()->GetDef(id);
return def != nullptr && def->opcode() == spv::Op::OpConstant &&
def->GetSingleWordInOperand(0) == value;
}
bool IsAccessChain(const Instruction* inst) {
return inst->opcode() == spv::Op::OpAccessChain ||
inst->opcode() == spv::Op::OpInBoundsAccessChain;
}
Instruction* AddPrivateVariable(IRContext* ctx, uint32_t pointeeTypeId, const char* name) {
const uint32_t ptrType = PointerTypeTo(ctx, pointeeTypeId, spv::StorageClass::Private);
const uint32_t varId = ctx->TakeNextId();
ctx->AddGlobalValue(spvtools::MakeUnique<Instruction>(
ctx, spv::Op::OpVariable, ptrType, varId,
std::initializer_list<Operand>{
{SPV_OPERAND_TYPE_STORAGE_CLASS,
{static_cast<uint32_t>(spv::StorageClass::Private)}}}));
ctx->AddDebug2Inst(spvtools::MakeUnique<Instruction>(
ctx, spv::Op::OpName, 0, 0,
std::initializer_list<Operand>{
{SPV_OPERAND_TYPE_ID, {varId}},
{SPV_OPERAND_TYPE_LITERAL_STRING, spvtools::utils::MakeVector(name)}}));
return ctx->get_def_use_mgr()->GetDef(varId);
}
// Retargets |chain| onto |newBaseId|, dropping the first |dropIndexCount| index
// operands and switching the result pointer's storage class to Private.
void RetargetChainToPrivate(IRContext* ctx, Instruction* chain, uint32_t newBaseId,
uint32_t dropIndexCount) {
Instruction* chainPtrType = ctx->get_def_use_mgr()->GetDef(chain->type_id());
const uint32_t pointeeId = chainPtrType->GetSingleWordInOperand(1);
const uint32_t newPtrType = PointerTypeTo(ctx, pointeeId, spv::StorageClass::Private);
ctx->ForgetUses(chain);
std::vector<Operand> newOperands;
newOperands.push_back({SPV_OPERAND_TYPE_ID, {newBaseId}});
for (uint32_t i = 1 + dropIndexCount; i < chain->NumInOperands(); ++i) {
newOperands.push_back(chain->GetInOperand(i));
}
chain->SetResultType(newPtrType);
chain->SetInOperands(std::move(newOperands));
ctx->AnalyzeUses(chain);
}
// ---- Output side --------------------------------------------------------------
struct OutputTarget {
Instruction* var = nullptr; // Output gl_PerVertex block or standalone builtin
bool isBlockMember = false;
uint32_t memberIndex = 0; // valid when isBlockMember
uint32_t arrayTypeId = 0; // float[N]
uint32_t elemTypeId = 0; // float
uint32_t arrayLen = 0; // N
};
// Inserts "gl_ClipDistance[k] = mg_ClipDistance[k]" for every literal k before
// |before|. Constant-index writes are the only write shape Adreno links correctly.
void InsertFlushBefore(IRContext* ctx, Instruction* before, const OutputTarget& target,
uint32_t mgVarId) {
const uint32_t ptrPrivElem =
PointerTypeTo(ctx, target.elemTypeId, spv::StorageClass::Private);
const uint32_t ptrOutElem =
PointerTypeTo(ctx, target.elemTypeId, spv::StorageClass::Output);
for (uint32_t k = 0; k < target.arrayLen; ++k) {
const uint32_t kConst = IntConstant(ctx, true, k);
const uint32_t srcChainId = ctx->TakeNextId();
before->InsertBefore(spvtools::MakeUnique<Instruction>(
ctx, spv::Op::OpAccessChain, ptrPrivElem, srcChainId,
std::initializer_list<Operand>{{SPV_OPERAND_TYPE_ID, {mgVarId}},
{SPV_OPERAND_TYPE_ID, {kConst}}}));
const uint32_t valId = ctx->TakeNextId();
before->InsertBefore(spvtools::MakeUnique<Instruction>(
ctx, spv::Op::OpLoad, target.elemTypeId, valId,
std::initializer_list<Operand>{{SPV_OPERAND_TYPE_ID, {srcChainId}}}));
const uint32_t dstChainId = ctx->TakeNextId();
std::vector<Operand> dstOperands;
dstOperands.push_back({SPV_OPERAND_TYPE_ID, {target.var->result_id()}});
if (target.isBlockMember) {
dstOperands.push_back(
{SPV_OPERAND_TYPE_ID, {IntConstant(ctx, true, target.memberIndex)}});
}
dstOperands.push_back({SPV_OPERAND_TYPE_ID, {kConst}});
before->InsertBefore(spvtools::MakeUnique<Instruction>(
ctx, spv::Op::OpAccessChain, ptrOutElem, dstChainId, dstOperands));
before->InsertBefore(spvtools::MakeUnique<Instruction>(
ctx, spv::Op::OpStore, 0, 0,
std::initializer_list<Operand>{{SPV_OPERAND_TYPE_ID, {dstChainId}},
{SPV_OPERAND_TYPE_ID, {valId}}}));
}
}
bool LowerOutputClipDistance(IRContext* ctx, bool isGeometry) {
auto* defUse = ctx->get_def_use_mgr();
// Collect (struct type, member) pairs decorated BuiltIn ClipDistance and
// standalone variables decorated BuiltIn ClipDistance.
std::vector<std::pair<uint32_t, uint32_t>> memberTargets; // (structId, member)
std::vector<uint32_t> plainTargets; // variable ids
for (Instruction& ann : ctx->annotations()) {
if (ann.opcode() == spv::Op::OpMemberDecorate && ann.NumInOperands() >= 4 &&
static_cast<spv::Decoration>(ann.GetSingleWordInOperand(2)) ==
spv::Decoration::BuiltIn &&
static_cast<spv::BuiltIn>(ann.GetSingleWordInOperand(3)) ==
spv::BuiltIn::ClipDistance) {
memberTargets.emplace_back(ann.GetSingleWordInOperand(0),
ann.GetSingleWordInOperand(1));
} else if (ann.opcode() == spv::Op::OpDecorate && ann.NumInOperands() >= 3 &&
static_cast<spv::Decoration>(ann.GetSingleWordInOperand(1)) ==
spv::Decoration::BuiltIn &&
static_cast<spv::BuiltIn>(ann.GetSingleWordInOperand(2)) ==
spv::BuiltIn::ClipDistance) {
plainTargets.push_back(ann.GetSingleWordInOperand(0));
}
}
std::vector<OutputTarget> targets;
for (Instruction& inst : ctx->module()->types_values()) {
if (inst.opcode() != spv::Op::OpVariable ||
static_cast<spv::StorageClass>(inst.GetSingleWordInOperand(0)) !=
spv::StorageClass::Output) {
continue;
}
const uint32_t pointee = VariablePointeeType(ctx, &inst);
for (const auto& [structId, member] : memberTargets) {
if (pointee != structId) continue;
Instruction* structType = defUse->GetDef(structId);
if (structType == nullptr || member >= structType->NumInOperands()) continue;
OutputTarget target;
target.var = &inst;
target.isBlockMember = true;
target.memberIndex = member;
target.arrayTypeId = structType->GetSingleWordInOperand(member);
target.arrayLen = ArrayLength(ctx, target.arrayTypeId);
targets.push_back(target);
}
for (const uint32_t varId : plainTargets) {
if (inst.result_id() != varId) continue;
OutputTarget target;
target.var = &inst;
target.isBlockMember = false;
target.arrayTypeId = pointee;
target.arrayLen = ArrayLength(ctx, target.arrayTypeId);
targets.push_back(target);
}
}
bool changed = false;
for (OutputTarget& target : targets) {
if (target.arrayLen == 0) continue;
Instruction* arrayType = defUse->GetDef(target.arrayTypeId);
target.elemTypeId = arrayType->GetSingleWordInOperand(0);
// Collect the accesses to redirect. For the block form only chains whose
// leading index selects the ClipDistance member count; for the standalone
// form every chain plus whole-variable loads/stores.
std::vector<Instruction*> chains;
std::vector<Instruction*> directAccesses;
bool unsupportedUse = false;
defUse->ForEachUser(target.var, [&](Instruction* user) {
if (IsAccessChain(user) &&
user->GetSingleWordInOperand(0) == target.var->result_id()) {
if (target.isBlockMember) {
if (user->NumInOperands() >= 2 &&
IsConstantWithValue(ctx, user->GetSingleWordInOperand(1),
target.memberIndex)) {
chains.push_back(user);
}
} else {
chains.push_back(user);
}
} else if (!target.isBlockMember) {
if (user->opcode() == spv::Op::OpLoad ||
(user->opcode() == spv::Op::OpStore &&
user->GetSingleWordInOperand(0) == target.var->result_id())) {
directAccesses.push_back(user);
} else if (user->opcode() == spv::Op::OpCopyMemory) {
unsupportedUse = true;
}
}
});
if (unsupportedUse || (chains.empty() && directAccesses.empty())) {
continue;
}
Instruction* mgVar = AddPrivateVariable(ctx, target.arrayTypeId, "mg_ClipDistance");
const uint32_t mgVarId = mgVar->result_id();
for (Instruction* chain : chains) {
const uint32_t dropCount = target.isBlockMember ? 1u : 0u;
if (chain->NumInOperands() == 1 + dropCount) {
// Pointer to the whole float[N]: reuse the private variable itself.
ctx->ReplaceAllUsesWith(chain->result_id(), mgVarId);
ctx->KillInst(chain);
} else {
RetargetChainToPrivate(ctx, chain, mgVarId, dropCount);
}
}
for (Instruction* access : directAccesses) {
ctx->ForgetUses(access);
access->SetInOperand(0, {mgVarId});
ctx->AnalyzeUses(access);
}
// Flush the shadow into the real builtin: geometry right before every
// EmitVertex, vertex before every return of the entry point. The flush is
// also what keeps the builtin statically used for cross-stage IO matching.
std::vector<Instruction*> flushSites;
if (isGeometry) {
for (Function& function : *ctx->module()) {
function.ForEachInst([&](Instruction* inst) {
if (inst->opcode() == spv::Op::OpEmitVertex) {
flushSites.push_back(inst);
}
});
}
} else {
const uint32_t entryFuncId = EntryFunctionId(ctx);
for (Function& function : *ctx->module()) {
if (function.result_id() != entryFuncId) continue;
function.ForEachInst([&](Instruction* inst) {
if (inst->opcode() == spv::Op::OpReturn ||
inst->opcode() == spv::Op::OpReturnValue) {
flushSites.push_back(inst);
}
});
}
}
for (Instruction* site : flushSites) {
InsertFlushBefore(ctx, site, target, mgVarId);
}
changed = true;
}
return changed;
}
// ---- Input side (geometry gl_in) ----------------------------------------------
bool LowerInputClipDistance(IRContext* ctx) {
auto* defUse = ctx->get_def_use_mgr();
auto* typeMgr = ctx->get_type_mgr();
// Locate the gl_in block member decorated ClipDistance.
Instruction* glInVar = nullptr;
uint32_t memberIndex = 0;
uint32_t arrayTypeId = 0; // float[N]
for (Instruction& ann : ctx->annotations()) {
if (ann.opcode() != spv::Op::OpMemberDecorate || ann.NumInOperands() < 4 ||
static_cast<spv::Decoration>(ann.GetSingleWordInOperand(2)) !=
spv::Decoration::BuiltIn ||
static_cast<spv::BuiltIn>(ann.GetSingleWordInOperand(3)) !=
spv::BuiltIn::ClipDistance) {
continue;
}
const uint32_t structId = ann.GetSingleWordInOperand(0);
const uint32_t member = ann.GetSingleWordInOperand(1);
for (Instruction& inst : ctx->module()->types_values()) {
if (inst.opcode() != spv::Op::OpVariable ||
static_cast<spv::StorageClass>(inst.GetSingleWordInOperand(0)) !=
spv::StorageClass::Input) {
continue;
}
const uint32_t pointee = VariablePointeeType(ctx, &inst);
Instruction* pointeeType = defUse->GetDef(pointee);
if (pointeeType == nullptr || pointeeType->opcode() != spv::Op::OpTypeArray ||
pointeeType->GetSingleWordInOperand(0) != structId) {
continue;
}
Instruction* structType = defUse->GetDef(structId);
if (structType == nullptr || member >= structType->NumInOperands()) continue;
glInVar = &inst;
memberIndex = member;
arrayTypeId = structType->GetSingleWordInOperand(member);
break;
}
if (glInVar != nullptr) break;
}
if (glInVar == nullptr) {
return false;
}
const uint32_t clipCount = ArrayLength(ctx, arrayTypeId);
const uint32_t vertexCount = ArrayLength(ctx, VariablePointeeType(ctx, glInVar));
if (clipCount == 0 || vertexCount == 0) {
return false;
}
// Every gl_in chain that selects the ClipDistance member:
// (vertex, member) yields a whole float[N], (vertex, member, k) an element.
std::vector<Instruction*> chains;
defUse->ForEachUser(glInVar, [&](Instruction* user) {
if (IsAccessChain(user) && user->GetSingleWordInOperand(0) == glInVar->result_id() &&
user->NumInOperands() >= 3 &&
IsConstantWithValue(ctx, user->GetSingleWordInOperand(2), memberIndex)) {
chains.push_back(user);
}
});
if (chains.empty()) {
return false;
}
Instruction* arrayTypeInst = defUse->GetDef(arrayTypeId);
const uint32_t elemTypeId = arrayTypeInst->GetSingleWordInOperand(0);
// Private mg_ClipDistanceIn = float[vertexCount][clipCount].
const uint32_t vertexCountConst = IntConstant(ctx, false, vertexCount);
analysis::Type* innerType = typeMgr->GetType(arrayTypeId);
analysis::Array outerArray(
innerType, analysis::Array::LengthInfo{
vertexCountConst,
{analysis::Array::LengthInfo::kConstant, vertexCount}});
const uint32_t outerArrayTypeId = typeMgr->GetTypeInstruction(&outerArray);
Instruction* mgInVar = AddPrivateVariable(ctx, outerArrayTypeId, "mg_ClipDistanceIn");
const uint32_t mgInVarId = mgInVar->result_id();
// Copy loop at the top of the entry point:
// for (uint t = 0; t < vertexCount * clipCount; ++t)
// mg_ClipDistanceIn[t / clipCount][t % clipCount] =
// gl_in[t / clipCount].gl_ClipDistance[t % clipCount];
// Both gl_in indices are loop-derived (dynamic): constant-index element reads
// miscompile and whole-array reads crash the Adreno compiler.
const uint32_t entryFuncId = EntryFunctionId(ctx);
Function* entryFn = nullptr;
for (Function& function : *ctx->module()) {
if (function.result_id() == entryFuncId) {
entryFn = &function;
break;
}
}
if (entryFn == nullptr || entryFn->begin() == entryFn->end()) {
return false;
}
const uint32_t uintTypeId = UintType(ctx);
const uint32_t boolTypeId = BoolType(ctx);
const uint32_t ptrFnUint = PointerTypeTo(ctx, uintTypeId, spv::StorageClass::Function);
const uint32_t ptrInElem = PointerTypeTo(ctx, elemTypeId, spv::StorageClass::Input);
const uint32_t ptrPrivElem = PointerTypeTo(ctx, elemTypeId, spv::StorageClass::Private);
const uint32_t uint0 = IntConstant(ctx, false, 0);
const uint32_t uint1 = IntConstant(ctx, false, 1);
const uint32_t uintN = IntConstant(ctx, false, clipCount);
const uint32_t uintTotal = IntConstant(ctx, false, vertexCount * clipCount);
const uint32_t memberConst = IntConstant(ctx, true, memberIndex);
BasicBlock* entryBlock = &*entryFn->begin();
auto splitPoint = entryBlock->begin();
while (splitPoint != entryBlock->end() &&
splitPoint->opcode() == spv::Op::OpVariable) {
++splitPoint;
}
// Loop counter lives with the other function-local variables.
const uint32_t counterVarId = ctx->TakeNextId();
splitPoint->InsertBefore(spvtools::MakeUnique<Instruction>(
ctx, spv::Op::OpVariable, ptrFnUint, counterVarId,
std::initializer_list<Operand>{
{SPV_OPERAND_TYPE_STORAGE_CLASS,
{static_cast<uint32_t>(spv::StorageClass::Function)}}}));
const uint32_t restLabelId = ctx->TakeNextId();
BasicBlock* restBlock = entryBlock->SplitBasicBlock(ctx, restLabelId, splitPoint);
const uint32_t headerLabelId = ctx->TakeNextId();
const uint32_t checkLabelId = ctx->TakeNextId();
const uint32_t bodyLabelId = ctx->TakeNextId();
const uint32_t continueLabelId = ctx->TakeNextId();
auto makeBlock = [&](uint32_t labelId) {
return spvtools::MakeUnique<BasicBlock>(spvtools::MakeUnique<Instruction>(
ctx, spv::Op::OpLabel, 0, labelId, std::initializer_list<Operand>{}));
};
auto addInst = [&](BasicBlock* block, spv::Op opcode, uint32_t typeId,
uint32_t resultId, std::vector<Operand> operands) {
block->AddInstruction(spvtools::MakeUnique<Instruction>(
ctx, opcode, typeId, resultId, std::move(operands)));
};
// entry: t = 0; branch header
addInst(entryBlock, spv::Op::OpStore, 0, 0,
{{SPV_OPERAND_TYPE_ID, {counterVarId}}, {SPV_OPERAND_TYPE_ID, {uint0}}});
addInst(entryBlock, spv::Op::OpBranch, 0, 0, {{SPV_OPERAND_TYPE_ID, {headerLabelId}}});
// header: structured loop header
auto headerBlock = makeBlock(headerLabelId);
addInst(headerBlock.get(), spv::Op::OpLoopMerge, 0, 0,
{{SPV_OPERAND_TYPE_ID, {restLabelId}},
{SPV_OPERAND_TYPE_ID, {continueLabelId}},
{SPV_OPERAND_TYPE_LOOP_CONTROL,
{static_cast<uint32_t>(spv::LoopControlMask::MaskNone)}}});
addInst(headerBlock.get(), spv::Op::OpBranch, 0, 0,
{{SPV_OPERAND_TYPE_ID, {checkLabelId}}});
// check: t < vertexCount * clipCount ?
auto checkBlock = makeBlock(checkLabelId);
const uint32_t tCheckId = ctx->TakeNextId();
addInst(checkBlock.get(), spv::Op::OpLoad, uintTypeId, tCheckId,
{{SPV_OPERAND_TYPE_ID, {counterVarId}}});
const uint32_t condId = ctx->TakeNextId();
addInst(checkBlock.get(), spv::Op::OpULessThan, boolTypeId, condId,
{{SPV_OPERAND_TYPE_ID, {tCheckId}}, {SPV_OPERAND_TYPE_ID, {uintTotal}}});
addInst(checkBlock.get(), spv::Op::OpBranchConditional, 0, 0,
{{SPV_OPERAND_TYPE_ID, {condId}},
{SPV_OPERAND_TYPE_ID, {bodyLabelId}},
{SPV_OPERAND_TYPE_ID, {restLabelId}}});
// body: mg_ClipDistanceIn[t / N][t % N] = gl_in[t / N].gl_ClipDistance[t % N]
auto bodyBlock = makeBlock(bodyLabelId);
const uint32_t tBodyId = ctx->TakeNextId();
addInst(bodyBlock.get(), spv::Op::OpLoad, uintTypeId, tBodyId,
{{SPV_OPERAND_TYPE_ID, {counterVarId}}});
const uint32_t vertexIdxId = ctx->TakeNextId();
addInst(bodyBlock.get(), spv::Op::OpUDiv, uintTypeId, vertexIdxId,
{{SPV_OPERAND_TYPE_ID, {tBodyId}}, {SPV_OPERAND_TYPE_ID, {uintN}}});
const uint32_t clipIdxId = ctx->TakeNextId();
addInst(bodyBlock.get(), spv::Op::OpUMod, uintTypeId, clipIdxId,
{{SPV_OPERAND_TYPE_ID, {tBodyId}}, {SPV_OPERAND_TYPE_ID, {uintN}}});
const uint32_t srcChainId = ctx->TakeNextId();
addInst(bodyBlock.get(), spv::Op::OpAccessChain, ptrInElem, srcChainId,
{{SPV_OPERAND_TYPE_ID, {glInVar->result_id()}},
{SPV_OPERAND_TYPE_ID, {vertexIdxId}},
{SPV_OPERAND_TYPE_ID, {memberConst}},
{SPV_OPERAND_TYPE_ID, {clipIdxId}}});
const uint32_t valId = ctx->TakeNextId();
addInst(bodyBlock.get(), spv::Op::OpLoad, elemTypeId, valId,
{{SPV_OPERAND_TYPE_ID, {srcChainId}}});
const uint32_t dstChainId = ctx->TakeNextId();
addInst(bodyBlock.get(), spv::Op::OpAccessChain, ptrPrivElem, dstChainId,
{{SPV_OPERAND_TYPE_ID, {mgInVarId}},
{SPV_OPERAND_TYPE_ID, {vertexIdxId}},
{SPV_OPERAND_TYPE_ID, {clipIdxId}}});
addInst(bodyBlock.get(), spv::Op::OpStore, 0, 0,
{{SPV_OPERAND_TYPE_ID, {dstChainId}}, {SPV_OPERAND_TYPE_ID, {valId}}});
addInst(bodyBlock.get(), spv::Op::OpBranch, 0, 0,
{{SPV_OPERAND_TYPE_ID, {continueLabelId}}});
// continue: ++t
auto continueBlock = makeBlock(continueLabelId);
const uint32_t tContinueId = ctx->TakeNextId();
addInst(continueBlock.get(), spv::Op::OpLoad, uintTypeId, tContinueId,
{{SPV_OPERAND_TYPE_ID, {counterVarId}}});
const uint32_t tIncId = ctx->TakeNextId();
addInst(continueBlock.get(), spv::Op::OpIAdd, uintTypeId, tIncId,
{{SPV_OPERAND_TYPE_ID, {tContinueId}}, {SPV_OPERAND_TYPE_ID, {uint1}}});
addInst(continueBlock.get(), spv::Op::OpStore, 0, 0,
{{SPV_OPERAND_TYPE_ID, {counterVarId}}, {SPV_OPERAND_TYPE_ID, {tIncId}}});
addInst(continueBlock.get(), spv::Op::OpBranch, 0, 0,
{{SPV_OPERAND_TYPE_ID, {headerLabelId}}});
BasicBlock* headerPtr = entryFn->InsertBasicBlockBefore(std::move(headerBlock), restBlock);
BasicBlock* checkPtr = entryFn->InsertBasicBlockAfter(std::move(checkBlock), headerPtr);
BasicBlock* bodyPtr = entryFn->InsertBasicBlockAfter(std::move(bodyBlock), checkPtr);
entryFn->InsertBasicBlockAfter(std::move(continueBlock), bodyPtr);
// Redirect the pre-existing accesses to the shadow copy.
for (Instruction* chain : chains) {
if (chain->NumInOperands() == 3) {
// (vertex, member): whole float[N] of one vertex.
Instruction* chainPtrType = defUse->GetDef(chain->type_id());
const uint32_t pointeeId = chainPtrType->GetSingleWordInOperand(1);
const uint32_t newPtrType =
PointerTypeTo(ctx, pointeeId, spv::StorageClass::Private);
ctx->ForgetUses(chain);
std::vector<Operand> newOperands;
newOperands.push_back({SPV_OPERAND_TYPE_ID, {mgInVarId}});
newOperands.push_back(chain->GetInOperand(1));
chain->SetResultType(newPtrType);
chain->SetInOperands(std::move(newOperands));
ctx->AnalyzeUses(chain);
} else {
// (vertex, member, k, ...): drop the member index.
Instruction* chainPtrType = defUse->GetDef(chain->type_id());
const uint32_t pointeeId = chainPtrType->GetSingleWordInOperand(1);
const uint32_t newPtrType =
PointerTypeTo(ctx, pointeeId, spv::StorageClass::Private);
ctx->ForgetUses(chain);
std::vector<Operand> newOperands;
newOperands.push_back({SPV_OPERAND_TYPE_ID, {mgInVarId}});
newOperands.push_back(chain->GetInOperand(1));
for (uint32_t i = 3; i < chain->NumInOperands(); ++i) {
newOperands.push_back(chain->GetInOperand(i));
}
chain->SetResultType(newPtrType);
chain->SetInOperands(std::move(newOperands));
ctx->AnalyzeUses(chain);
}
}
return true;
}
} // namespace
spvtools::opt::Pass::Status LowerClipDistanceForEsslPass::Process() {
auto* ctx = context();
const spv::ExecutionModel model = EntryExecutionModel(ctx);
const bool isVertex = model == spv::ExecutionModel::Vertex;
const bool isGeometry = model == spv::ExecutionModel::Geometry;
if (!isVertex && !isGeometry) {
return Status::SuccessWithoutChange;
}
bool changed = LowerOutputClipDistance(ctx, isGeometry);
if (isGeometry) {
changed |= LowerInputClipDistance(ctx);
}
if (!changed) {
return Status::SuccessWithoutChange;
}
ctx->InvalidateAnalysesExceptFor(spvtools::opt::IRContext::kAnalysisNone);
return Status::SuccessWithChange;
}
spvtools::Optimizer::PassToken
LowerClipDistanceForEsslPass::CreateLowerClipDistanceForEsslPass() {
return spvtools::Optimizer::PassToken(MakeUnique<LowerClipDistanceForEsslPass>());
}
} // namespace ShaderTranspiler
} // namespace MG_Util
} // namespace MobileGL
@@ -0,0 +1,44 @@
// MobileGL - MobileGL/MG_Util/ShaderTranspiler/SpirvPasses/LowerClipDistanceForEsslPass.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 "source/opt/pass.h"
#include "spirv-tools/optimizer.hpp"
#include <Includes.h>
namespace MobileGL {
namespace MG_Util {
namespace ShaderTranspiler {
// Adreno's ESSL compiler mishandles gl_ClipDistance (device-verified on Adreno 750):
// - writes through non-constant indices silently fail to link,
// - reads of gl_in[i].gl_ClipDistance[k] with a CONSTANT k >= 1 fail to compile
// ("array indexing out of boundary") while dynamic-index reads work,
// - compiling a whole-array read of gl_in[i].gl_ClipDistance segfaults the
// compiler backend (libllvm-qgl.so).
// This pass shadows the builtin so the decompiled ESSL only ever touches it in the
// shapes Adreno accepts. Output side (vertex + geometry): all accesses to the
// Output ClipDistance (gl_PerVertex member or standalone variable) are redirected
// to a Private mg_ClipDistance array, and a flush writing the real builtin with
// literal constant indices is inserted before every OpEmitVertex (geometry) or
// every return of the entry point (vertex). Input side (geometry): accesses to
// gl_in[...].gl_ClipDistance are redirected to a Private mg_ClipDistanceIn
// array-of-arrays filled once at the top of the entry point by a structured loop
// whose gl_in reads use dynamic (loop-variable) indices. The builtin members stay
// statically referenced by the flush/copy so cross-stage IO matching is intact.
// Only meant for the DirectGLES transpile path on Qualcomm devices.
class LowerClipDistanceForEsslPass : public spvtools::opt::Pass {
public:
const char* name() const override { return "lower-clip-distance-for-essl"; }
Status Process() override;
static spvtools::Optimizer::PassToken CreateLowerClipDistanceForEsslPass();
};
} // namespace ShaderTranspiler
} // namespace MG_Util
} // namespace MobileGL
+1 -1
View File
@@ -87,7 +87,7 @@ def main():
ap.add_argument("--device-dir", default="/data/local/tmp/mgcts")
ap.add_argument("--surface", default="fbo", help="--deqp-surface-type value")
ap.add_argument("--max-rounds", type=int, default=4000)
ap.add_argument("--max-empty-streak", type=int, default=64,
ap.add_argument("--max-empty-streak", type=int, default=8,
help="abort after this many consecutive chunks that produce no log at all")
ap.add_argument("--min-mem-kb", type=int, default=400000,
help="pause when the device drops below this much available memory")