Compare commits

...
Author SHA1 Message Date
BZLZHH 3025284a6e [Perf, Test] (MG_Util): libfork execution engine for the shader compile pool, runtime-selectable
Adds libfork v3.8.0 (3rdparty submodule, header-only, wired like the asio
precedent) as a second execution engine behind ShaderCompilePool, selected
per process by MOBILEGL_ASYNC_POOL=asio|libfork (default asio; unknown
values warn and fall back). The engine boundary is deliberately tiny: the
queue, the concurrency budget and its clamping, the suspension latch,
cancel request-vs-outcome, the stopped-is-synchronous fallback and the
drain all stay in the shared Impl - an engine only answers how a
budget-cleared job reaches a worker.

The libfork engine runs detached root tasks as CHAINS: a finished body
takes the next queued job in the same coroutine on the same worker, so
the refills a worker posts are absorbed without a scheduler round trip
(the naive dispatch-thread shape measured 4x worse than asio on short
jobs). Absorption is bounded at one job per live chain - unbounded
absorption serialized bursts posted from inside the pool, which is the
shipped shape (one compile settling fans out link jobs via SubmitAfter
and the adoption map), caught by the review and pinned by a permanent
peak-concurrency regression test (pre-fix: libfork peak 1 vs asio peak 4
on a 16-job worker-posted burst). External submissions go through a
round-robin adaptor instead of lf::lazy_pool::schedule, which both
avoids a data race on lazy_pool's unsynchronized xoshiro under
concurrent submits and beats birthday-collision placement by ~1.3x at
budget == thread count.

The measured answer to "does asio scale poorly": no - the executor was
never the bottleneck. On real pack corpora extracted from the trace
fixtures (BSL 61 shaders, Complementary 277), interleaved best-of-5 per
cell, the engines are within noise of each other at every thread count
(complementary: 4965/2506/1376/824 ms at 1/2/4/8 threads for asio;
libfork within 1%), both ~6x at 8 threads. perf counters show the
flattening past 4 threads is machine-level (instructions flat at 22.1e9
from 1 to 16 threads - no added work, no lock spinning - while cycles
and LLC misses double: memory-stall bound), and the separating control
- N fully independent single-threaded processes with no shared
scheduler at all - scales WORSE than the pool (5.27x vs 5.94x at 8).
The pool microbenchmark does favor libfork on pure dispatch (518 vs
530 ns/job at 1 worker, growing with worker count), but a real compile
body is 1-100 ms, so dispatch is under 0.1% either way. asio therefore
stays the default; this branch exists to make the comparison
reproducible (MG_Test/Util/AsyncPoolBench drives either engine over a
corpus directory) and to keep the alternative viable.

613/613 unit tests in all four combos ({asio, libfork} x {async default
on, kill switch}), integration scenarios byte-identical between engines
on both backends.
2026-08-09 17:24:01 -04:00
BZLZHH d8d7530011 [Fix, Test] (MG_Backend/DirectGLES, MG_Util, MG_Impl): widen three-channel render targets wherever the driver refuses them
Complementary Reimagined would not load through Espryt on Mali: Iris got
GL_FRAMEBUFFER_UNSUPPORTED building its composite framebuffer, because
colortex1 is RGB8_SNORM and colortex2 is RGB16F - three-channel formats
that no real ES driver can render to (EXT_render_snorm covers R/RG/RGBA
only, and the float extensions exclude the RGB forms). The frontend's
probe cache diagnosed this correctly and then had nothing to offer: the
NoThreeChannelRenderTarget widening machinery existed but was gated to
multisample targets alone. llvmpipe turns out to refuse most of the same
attachments - CI retrace stayed green only because a replay never
branches on glCheckFramebufferStatus - so this was never a desktop-vs-
device split, just an unlit path.

The widening now applies to every color-attachable image, renderbuffers
included, riding the driver-probe branch so the native format is still
tried first and substituted only on refusal. One ThreeChannelWidening
table owns the widened (internalformat, format, type) triple per source
format - the previous per-case branches disagreed with each other and
could emit an unuploadable (RGBA16F, GL_RGB, GL_BYTE) combination or
widen into another three-channel format the driver refuses just the
same. Uploads repack three-component client data to four with the
format's own one in the alpha channel (127 is not 1 for RGB8I - the
integer arms carry integer ones); readback drops the synthetic alpha,
derived from the actual image being read, not the bound framebuffer,
so glGetTexImage through a scratch FBO cannot be confused by an
unrelated widened attachment.

Stored alpha on a widened attachment is now an invariant 1.0 rather
than an accident: the color-mask sync clears the alpha bit per draw
buffer (glColorMaski for MRT mixes), and clears route through
glClearBufferfv with alpha substituted on widened slots only -
scissored clears inherit the discipline for free, integer color
buffers keep their explicit integer-clear path, and glGet still
answers the application's own mask. GL_DST_ALPHA blending, blits and
readback therefore all see 1.0 without further interception.

DriverPost grows the rows this bug earned: EXT_color_buffer_float
detection (previously unreferenced anywhere) with a FAIL row when
absent, the missing EXT_render_snorm row, and a three-channel-
attachment row that reports one representative per widening class -
graded so a half-float-only driver warns about the 32-bit float gap
instead of being declared unsupported.

Gates: 606/606 unit at default and with the async kill switch; full
retrace, both backends - the complementary fixtures now run with the
widening ACTIVE on llvmpipe and pass with a slightly better SSIM than
before; ext caselist DirectGLES holds 3914/4867 with zero set drift
while 54 cases move from NotSupported to genuinely passing; on the
Mali-G77 device, Complementary Reimagined builds its pipeline and
renders in-world through Espryt (md5-verified build), BSL still green.
A new ThreeChannelAttachmentScenario pins the frontend answer -
COMPLETE where it used to say UNSUPPORTED - on the real driver.
2026-08-09 15:28:34 -04:00
BZLZHH 0f394fa46f [Test] (tools/trace_replay): pin the Iris glyph-death bug with a BSL pause-menu fixture
minecraft-1.21.4-fabric-iris-bsl-esc-menu-854: Minecraft 1.21.4 Fabric +
Sodium + Iris + BSL 10.1.3 through Espryt on Mali-G77, paused at the ESC
menu over the BSL-blurred world, captured at 854x480 through the FCL
trace-capture skill. The trimmed trace keeps the whole session preamble
deliberately: the 107669b3 bug class is triggered while Iris BUILDS the
pipeline (a by-name texture call swapping the active unit's binding under
the sync memo), and the pause menu afterwards is where its damage is
legible - every glyph alpha-discards against the zeroed lightmap while
the button frames survive.

Ablation-proven as a net before landing: against a build with both layers
of 107669b3 reverted the case fails at ssim 0.949284 and the diff image
is text and only text - menu title, all button labels, the tutorial
toast; against the fixed library it matches the golden exactly, and
Magma passes the same golden at 0.998402 with no alternate needed.
Replays in about a minute per backend on llvmpipe/lavapipe (the 1.3M-call
preamble; well under the timeout and smaller than several existing
fixtures). Existing fixtures spot-checked green.
2026-08-09 12:49:10 -04:00
BZLZHH 107669b3db [Fix, Test] (MG_Impl, MG_Backend/DirectGLES): DSA by-name texture calls corrupted borrowed-slot memo pairings - process-wide glyph death under Iris
Field report: on Espryt with a BSL Iris pipeline built, every glyph in the
game died - HUD, menu labels, even the vanilla title screen after leaving
the world - while sprites kept rendering. Captured on-device (FCL apitrace
rig), reproduced headlessly on llvmpipe, and pinned with a three-way replay:
the same trace renders full text on raw Mesa desktop GL and on Magma, so
the stream was intact and the execution was Espryt's.

MECHANISM. WithTemporarilyBoundNamedTexture implements the by-name (DSA)
texture entry points by binding the named texture onto the active unit's
real slot, running the bound-texture code, and restoring - without moving
the texture bind generation on either edge. DirectGLES's per-draw texture
sync memo keys on that generation and BORROWS the slot pointer, so a memo
built for texture A kept passing every key while a by-name call had
texture B sitting in the slot: A's backend twin was driven with B's
frontend object, and SyncMipmapsToBackend re-specified A's storage with
B's shape. In the trace, a by-name upload to a BSL 2048x2048 map while
the 16x16 lightmap was bound re-specified the lightmap's GL texture
2048x2048-NULL and back 16x16-NULL. The lightmap exists only as render
output - no glTexSubImage2D ever touches it - so it stayed zero forever,
and rendertype_text (vertexColor = Color * texelFetch(lightmap, ...)),
alpha-discards every glyph. Background quads never sample the lightmap,
which is why only text died.

FIX, class-level, two layers:
- Frontend (shared, closes the same hole for DirectVulkan's generation-
  keyed memos): the temporary bind and the restore each bump the texture
  bind generation (only when the slot actually changed), and the restore
  is an RAII scope guard so a throwing body can no longer leak the
  temporary binding - a second latent bug of the same class. Deliberately
  a generation bump and not a touched-unit note: the high-water mark must
  not chase by-name calls, and a completed bind/restore pair leaves the
  content epoch unchanged, so the cost is an owner-compare re-walk, not a
  memo rebuild.
- DirectGLES defense in depth: both borrowed-pair memos
  (g_unitTextureSyncList, g_fboTextureSyncList) record which frontend
  texture each backend twin was paired with and re-check it before any
  replay (last in the key conjunction, behind the context-id compare). A
  stale pairing now costs a list rebuild instead of silent cross-texture
  storage corruption.

Tests, both red with their own layer reverted:
TextureTest.NamedTextureCallKeepsUnitBindingAccountingCoherent (the
accounting contract) and DirectGLESTextureSync.UnitMemoRefusesToDriveA-
TwinFromAnotherTexture (the corrupting sequence shape against a mock GLES
table, asserting the resident texture's storage is never re-specified).
595/595 unit at default and with the async kill switch. Replay evidence:
the captured BSL ESC-menu trace renders all text through Espryt post-fix,
byte-comparable to the Mesa-direct and Magma replays; the no-shaderpack
control is unchanged. A trace fixture wiring this scene into CI follows
in a separate commit.
2026-08-09 11:28:24 -04:00
BZLZHH 3e0460e472 [Feat, Fix] (MG_Impl, MG_State, MG_Backend): program interface queries from frontend reflection; Espryt state-shadow reset
Wave 2 of the advertised-extension conformance campaign.

PROGRAM INTERFACE QUERIES (the load-bearing piece). glGetProgramInterfaceiv
and the five glGetProgramResource* entry points were answered by the
BACKENDS - Espryt asked the real driver about SPIRV-Cross-generated ESSL
whose namespace is not the GL one (default-block uniforms live in
MGL_GLOBAL_UBO there), and Magma kept a second, partial reflection that
hardcoded types and diverged from the frontend. Both are now deleted; a new
frontend resource-model layer (ProgramInterface.{h,cpp}) answers every
interface - uniforms, uniform blocks, atomic-counter buffers (recovered
from glslang's synthesized gl_AtomicCounterBlock_<binding> lowering),
buffer variables, shader-storage blocks (classified by TType storage
qualifier since glslang reflects them as uniform blocks), program inputs/
outputs (built-ins' layoutLocationEnd sentinel mapped to -1), and
transform-feedback varyings including the gl_NextBuffer/gl_SkipComponentsN
pseudo-varyings - from the glslang reflection the frontend already trusts
for glGetActiveUniform. Name/index round-tripping, the "[0]" array
spelling, and the GL 4.6 table 7.2 prop/error matrix live in the new layer
only; GetActiveUniform*/GetActiveAttrib* are untouched.

glShaderStorageBlockBinding now takes the interface-layer index (the one
GetProgramResourceIndex returns, with a range check it never had), records
the binding on the program keyed by block NAME - the one coordinate all
three index spaces agree on - and delegates by name across the backend
boundary. Both backends reseed the recorded bindings on their own program
rebuilds, so an unrelated resync can no longer silently revert a rebound
block, and GL_BUFFER_BINDING reports the live binding, not the declared
one. The Espryt delegate applies only to an already-synced twin and can no
longer trigger SyncToBackend from a getter; the sync path's GL query
out-params are initialized and clamped (a load-dependent stack-garbage
Vector size crash caught by the gate, reproduced 3/50 pre-fix, 100/100
post-fix under saturating load).

ESPRYT RENDER-STATE SHADOW RESET (rides along because it shares
DirectGLES.cpp): the render-state shadow is file-static and survives
MobileGL context switches, so GL_FRAMEBUFFER_SRGB (and the whole synced-cap
class) leaked between contexts - the cross-test leakage class the CTS maps
have carried for a week. MakeCurrent now invalidates the shadow like it
already invalidates the program/FBO/buffer caches, and the resync resolves
a never-set scissor box to the current surface instead of pushing the
(0,0,0,0) sentinel verbatim (which scissored everything away - caught by
the retrace gate, bisected to the exact field via a bitmask probe, and
fixed by resolving like the viewport path rather than reverting).

Frontend riders exposed by the layer: glGetUniformLocation resolves
arrays-of-arrays element addressing ("a[2][1]"); transform-feedback capture
accepts element-addressed varying names ("b[1]") and snapshots the request
verbatim for the interface (Magma's decorate pass logs loudly that element
capture is unimplemented there - follow-up).

KNOWN GAPS, documented in code and tests: the 6 subroutines-* cases
(glslang refuses subroutine for SPIR-V; wave 3), the 5 separate-programs-*
cases (glslang's pipe-I/O reflection cannot see a separable non-vertex
stage's own inputs; needs stage-aware output validation first), and
uniform-block-types' per-instance stage masks (not derivable from the
reflection).

Gate: 593/593 unit at default and kill-switch, x10 each, plus the SSB race
case 100/100 under 20-way CPU load; ext caselist Espryt 77.87% -> 80.42%,
Magma 77.58% -> 79.39% (+212 fixed, 0 newly broken); program_interface_query
2/43 -> 31/43 unique on Espryt, 9/43 -> 31/43 on Magma, backends now
byte-identical; KHR-GL45.direct_state_access 370/371 + 371/371 with the 4
sRGB leak victims recovered in cross-test ordering; KHR-GL33 held at
9884/9886; full 39x2 CI retrace with zero wave-attributable failures (the
3 failing newly-added fixtures are bit-identical on the pristine baseline).
2026-08-09 08:12:30 -04:00
BZLZHH 33ff177bb2 [Fix, Test] (MG_Impl, MG_State): advertised-extension conformance wave 1 - uniforms, validators, getters
First wave of the advertised-extension CTS campaign (targeted caselist: the
glcts groups of every extension both backends advertise, 4867 cases across the
KHR-GL41..46 namespaces). All frontend, shared by both backends:

- Non-square float matrix uniforms actually upload: glUniformMatrix{2x3,3x2,
  2x4,4x2,3x4,4x3}fv and the six glProgramUniformMatrix* twins were
  validate-only no-ops; they now write column-at-a-time at the global UBO's
  16-byte std140 column stride, honouring transpose. glUniformMatrix2fv had
  the sibling bug - mat2 written as 4 contiguous floats put column 1 at byte
  8 instead of 16. The readback path only ever un-padded mat3, so
  glGetUniformfv is fixed for mat2, mat3x2 (previously mis-gathered) and
  every non-square shape, with the bounds check widened to the padded span.
- glBindBufferRange validates offset/size at last: size <= 0, offset < 0,
  SSBO and UBO offset alignment, transform-feedback offset AND size
  multiples of 4 - all before any state write (a negative offset used to
  reach Range1D unchecked). glBindBuffersRange inherits per element, with
  the ARB_multi_bind up-front [first, first+count) checks added to the
  BindBuffersBase/Range and BindSamplers prologues.
- BufferSubData's second, wrong mapped-overlap test deleted (it rejected
  every write at or after a mapped range's start, mapped or not); the state
  layer's assert relaxed to the same half-open intersection the frontend
  checks. BufferStorage error precedence fixed: no-bound-buffer now beats
  bad-size/flags.
- glSamplerParameteri accepts the full GL_NEVER..GL_ALWAYS compare-func
  range (NEVER/LESS/EQUAL were rejected by a wrong lower bound).
  glBindSampler's unit gate uses GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS instead
  of the frontend array capacity, shared with glBindSamplers by construction.
- Getters: GL_MAX_SHADER_STORAGE_BLOCK_SIZE in glGetIntegerv; atomic-counter
  buffer limits; all 11 per-unit GL_TEXTURE_BINDING_* plus GL_SAMPLER_BINDING
  in glGetIntegeri_v; GL_VERTEX_ATTRIB_BINDING/_RELATIVE_OFFSET across the
  vertex-attrib query family; glGetFloati_v/glGetDoublei_v implemented (were
  stubs); KHR_debug limits raised to spec floors.
- glCreateShader records INVALID_ENUM for an unknown type (it previously
  handed out a usable name with no error at all); glCreateShaderProgramv
  validates count up front. glDispatchCompute/Indirect validate work-group
  counts, offset alignment and indirect-buffer presence.
- glVertexAttribIFormat & friends take a positive integer-type whitelist -
  GL_FLOAT/GL_HALF_FLOAT/GL_DOUBLE/GL_FIXED no longer slip through as
  integer attributes.

Gate (headless Mesa, default config = async on): 570/570 unit at default and
with the kill switch; ext caselist Espryt 76.29% -> 77.87% (+81 fixed, 6
crashes -> 0, the whole list now runs in one glcts process), Magma 75.94% ->
77.58% (+80 fixed, 0 newly broken); KHR-GL33 full mustpass lost nothing
(9884/9886, the 2 known Mesa-drift failures); retrace smoke clean (the
bsl-GLES miss is the documented golden drift, bit-identical on the pristine
baseline). The 4 DirectGLES direct_state_access.renderbuffers_storage* cases
that turned red are a PRE-EXISTING GL_FRAMEBUFFER_SRGB cross-test leak,
A/B-proven on an unpatched 2e6fc1ff build - wave 1 removed the two accidental
maskers (a crash partition and a failing case whose error path reset the
state). Fixing the leak itself is queued.
2026-08-09 04:39:22 -04:00
BZLZHH 2e6fc1ffc0 [Feat] (MG_Util, MG_Test): enable asynchronous shader compilation by default (P1 stage 7)
kAsyncShaderCompileDefault flips to true, which also advertises
GL_KHR_parallel_shader_compile by default on both backends. Unset
MOBILEGL_ASYNC_SHADER_COMPILE now resolves to ON; =0 remains the complete kill
switch (reverts the threading and withdraws the extension together).

The gate behind the flip (headless Mesa - llvmpipe for Espryt, lavapipe for
Magma - at c6299f75): GL30/31/32/33/40 mustpass plus the
KHR-GL46.parallel_shader_compile group, both backends, async=1 with the
extension advertised. 58,344 case-runs, 8 failures - and every one of the 8
also fails standalone at async=0, in the full async=0 suite arms with an
identical per-case failure set, and under the pre-P1-stage-6 library. Zero
async-attributable deltas; the 8 are Mesa-upgrade drift (4 unique signatures:
Espryt GL40 transform_feedback.draw_xfb{,_feedbackk}_test, Magma
texture_size_promotion.functional + packed_pixels rgb9_e5_format_red on
GL32/33/40), recorded for separate follow-up.

Validation under the flipped default (no env var): 553/553 unit at the default
AND with the kill switch; parallel_shader_compile 3/3 on both backends proving
the default advertises; 44+44 integration scenarios; 71/72 CI trace-replay
fixtures (the one failure is the pre-existing create-indirect lavapipe crash,
identical under the pre-fix library). The lifecycle test's contract updates
with the default: AsyncIsOnByDefaultAndTheOverrideDecidesEitherWay.

Not covered by this gate and deliberately left open: SSO/DSA suites (GL41+,
separate follow-up per review), and real-driver confirmation on NVIDIA/Mali -
the Mali-G77 on-device sweep runs separately as a report-only pass.
2026-08-09 02:04:59 -04:00
BZLZHH c6299f754f [Fix] (MG_Backend/DirectVulkan, MG_State): key per-object memos on lifetime ids, not heap addresses
A destroyed VertexArrayObject's heap address is handed straight back by the
next allocation of its size, and so is a destroyed BufferObject's. DirectVulkan
keyed its per-VAO draw memo on the VAO POINTER and folded the bound buffer's
ADDRESS into the content hash that validates the memoised bindings, so a
delete/recreate pair under a byte-identical attribute layout reproduced both
the key and its validating hash at once. The successor VAO then inherited the
dead one's resolved bindings and the draw fetched from a destroyed VkBuffer.
Both stated defences failed together, because both reduce to the content hash
and the hash's buffer-identity component was itself a recycled address.

VertexArrayObject and BufferObject now carry a globally-unique, never-reused
GetLifetimeId() - the same contract as ProgramObject's, minted from an atomic
starting at 1 so a zero-initialised slot can never name a live object.
VaoDrawMemo matches on (address, lifetime id) and stores the id on recycle,
SetupDrawSnapshot's "the VAO did not move" test compares the id alongside the
config version, and VertexInputStateFactory::ComputeHash hashes the bound
buffer's id instead of its pointer (0 for client memory).

Proven: the use-after-free reproduces at 100% incidence headless on lavapipe,
including a SEGV whose backtrace is the driver dereferencing a destroyed vertex
buffer inside lvp_queue_submit, and it is gone with the fix. New coverage -
MG_Test/State/ObjectLifetimeIdTest (deterministic, GPU-free, no context: it
waits for the real allocator to repeat an address and asserts the id differs,
and skips loudly rather than passing quietly if it never gets the chance), and
MG_IntegrationTest XfbAfterClipDistanceScenario, registered for DirectGLES,
DirectVulkan, and a third DirectVulkan run with async shader compilation pinned
on because that is a second allocation pattern. Gates: 553/553 unit green at
async=0 and async=1; the scenario 5/5 headless at both flag states; 71/72 CI
trace-replay fixtures over both backends, the one failure a pre-existing
lavapipe crash proven not a regression (identical SIGSEGV at the identical
call number under the pre-fix library).

Pending NVIDIA/X11 confirmation: the KHR-GL{32,40} transform_feedback failures
that opened this investigation never reproduced on lavapipe - the -2/-101
pre-fill signature appears in zero pre-fix runs there - so whether this clears
them is UNPROVEN and must be re-measured on the NVIDIA rig against a freshly
re-run pre-fix baseline. The residual suspect is deliberately untouched here:
m_xfbCounterSlotByObject keys its counter slot on the raw GL transform-feedback
name, so a recycled name whose generation check happens to pass would RESUME
instead of BEGIN. That path was never exercised on lavapipe and is neither
confirmed nor exonerated.
2026-08-08 23:56:53 -04:00
BZLZHH dcf918b9ee [Perf] (MG_State): adopt in-flight compile jobs across shader objects (P1 stage 6)
~21% of a shaderpack's glCompileShader calls hand different shader objects
byte-identical source; the P0b cache only helps after one finishes, so under
async two workers would run the whole pipeline twice. Now the GL thread
consults a per-context (stage, hash, length, envFingerprint) -> weak-node
map at enqueue and ADOPTS the in-flight (or completed) node instead of
posting a duplicate - a hit is honored only after a full byte comparison
(the hash never decides), a cancel-requested or settled-cancelled node is
never adopted, and no worker ever waits.

Sharing a node makes the unconditional cancel wrong, so release is now
adopter-counted: a plain GL-thread Int (every mutation site is a GL entry
point; the single-threadedness argument and the terminal-early-out that
keeps the count exact are in the header), and the cancel fires only at
count zero AND with no pending link pinning the node (the stage-4
MarkLinkReferenced precedence). Adoption also re-points the object's source
at the node's snapshot so the layer-1 memo's pointer compare stays armed -
without that, an adopter's next glCompileShader would re-enqueue the very
duplicate this stage removes. Both guards are negative-control-proven: each
removed guard fails exactly its own tests. Count discipline was proven with
a temporary hard-abort on underflow/leak across the full suite and retrace
corpus - zero hits.

18 new tests (13 GL-surface incl. shared-node re-source/delete/orphan-sweep
isolation, shared failure logs, 48-over-6 stress with a deterministic
adoption count, flag-off and KHR-suspended zero-adoption guards; 5 direct
map cases incl. fingerprint mismatch and cancelled/expired pruning).
Gates: 538/538 unit both flag states, async suites x5 no flakes, NVIDIA
DirectGLES retrace identical sets both states. Timing: 2-worker
(Android-shaped) 1-3% faster consistently on complementary and BSL;
4-worker unchanged - the win this stage exists for lands where CPU is
scarce.
2026-08-08 20:17:51 -04:00
BZLZHH d98f72447d [Feat, Test] (MG_Backend/DirectVulkan, MG_Test): Magma advertisement + the parallel-compile test net
Same gated push as the Espryt commit. The tests ride here because they
exercise both backends' advertisement paths and every piece of the
extension: ParallelShaderCompileTest (13 unit cases - the held-job proof
that GL_FALSE is observable and a second poll still shows outstanding work,
program equivalent, untouched objects read TRUE, always-TRUE with async
off, unknown pnames still INVALID_ENUM, zero-count join+inline for compiles
AND links, nonzero restores while Initialize() does not, clamping and
0xFFFFFFFF and KHR/ARB sharing one state, the getter vs the budget, the
string tracking configuration through glGetString AND glGetStringi) and
AsyncCompileScenario (5 real-GPU cases per the design: 64-compile polling,
forced-join correctness, string/thread-count checks against a live driver,
zero-count synchronous settlement, and async-vs-sync frames rendered
byte-identical with quadrant signatures so two identically-wrong images
cannot pass). Verified 5/5 on NVIDIA in the full 2x2 backend x flag matrix
with MOBILEGL_ITEST_REQUIRE_GPU=1.
2026-08-08 13:17:58 -04:00
BZLZHH f15cb8900f [Feat] (MG_Backend/DirectGLES): advertise GL_KHR_parallel_shader_compile when async is enabled
Gated on the configuration flag on purpose: the string is the one change a
retrace can never cover (Iris/Sodium pipeline their submissions differently
once they see it), so the kill switch has to withdraw the app-visible
behaviour along with the threading.
2026-08-08 13:17:58 -04:00
BZLZHH bd0def6133 [Feat] (MG_Impl, MG_State, MG_Util): the GL_KHR_parallel_shader_compile surface (P1 stage 5)
GL_COMPLETION_STATUS_KHR in both object getters, reading the non-joining
node-direct state - the one query that must never block is asserted never
to reach a join gate. glMaxShaderCompilerThreadsKHR/ARB share one
implementation: a zero count suspends async FIRST and then joins every
outstanding compile and link this context owns (suspend-before-join is the
only order whose post-condition is 'nothing in flight'), a nonzero count
restores; the suspension is a process latch the extension controls, kept
distinct from the configuration flag that gates the ADVERTISEMENT - an app
that turned threading off has not made the extension disappear.
GL_MAX_SHADER_COMPILER_THREADS_KHR reports the thread count. DriverPost
gains the MobileGL-side async row (PASS/INFO naming the env knob) and an
informational host-driver row backed by a new GLES capability probe.

The extension string itself lands per backend in the two follow-up
commits, keeping this one green stand-alone.
2026-08-08 13:17:58 -04:00
BZLZHH 6f8b7fbc40 [Feat] (MG_State, MG_Util): async program linking on the job graph (P1 stage 4)
glLinkProgram with the flag on snapshots its inputs in a GL-thread prologue
(stage-sorted shaders with their compile nodes taken without joining, env,
explicit locations/fragdata/xfb, draw-buffer count), then runs the whole
link body - glslang link/mapIO, SPIR-V, reflection, routing tables - as a
ProgramLinkTask that auto-posts when its last compile dependency settles
(+1-guarded countdown; no worker ever waits on another job). The publish is
one move of the LinkArtifacts block at the join, with the second version
bump so nothing memoized during the pending window survives.

The consume-once TShader claim moved onto the shared compile node as a CAS:
two link jobs racing for one shader resolve to winner-takes-the-parse,
loser re-parses the preprocessed source against the node's own env -
identical SPIR-V pinned by test for 2 and for 12 sharing programs.

Two deliberate corrections to the design's cancel matrix, both test-proven:
attach/detach do NOT cancel a pending link (the snapshot isolates it, and
glCreateShaderProgramv's link-then-detach would otherwise discard its own
result before anyone read it); and a compile node a pending link depends on
is pinned against the orphan-name sweep - the ordinary LWJGL teardown
compile/attach/link/detach/delete used to cancel the dependency and turn a
must-pass link into GL_FALSE.

Continuations are now throw-contained per-item (a stage-3 leftover made
load-bearing by the first real continuation), and the review's deadlock
find is fixed: the dispatch loop no longer cancels a node while holding the
pool mutex, since that cancel can run OnDepSettled -> Post -> same mutex.

Explicit joins: the draw path (GetProgramForDraw, both the pipeline stage
loop and the plain-UseProgram half) and the composite-link site; destroy
paths cancel-not-join; COMPLETION_STATUS readers stay non-joining.

Gates: 506/506 unit both flag states; AsyncCompile/AsyncLink/AsyncTeardown
suites x10 repeats clean both states (teardown with 128 jobs in flight,
then re-Initialize); full NVIDIA DirectGLES retrace flag on twice - result
sets identical to flag off, zero new deltas. Compile-phase prefix-diff,
flag on vs off: complementary-reimagined 5.21s -> 2.16s, BSL 1.72s ->
0.90s - past the design's final acceptance targets before the KHR
extension is even advertised. Default remains OFF until stage 5+7.
2026-08-08 11:58:38 -04:00
BZLZHH e5fb57f7eb [Feat] (MG_State, MG_Util): async shader compilation behind the default-off flag (P1 stage 3)
glCompileShader with MOBILEGL_ASYNC_SHADER_COMPILE=1 snapshots its inputs on
the GL thread (source SharedPtr, CompileEnv, cache handle) and runs the whole
pure pipeline - preprocess, validators, extractors, glslang parse - as a
ShaderCompileTask on the worker pool, returning immediately. Every read of
compile-produced state joins through the single Compiled() gate; links stay
synchronous this stage and join their attached shaders at the top of the
body. Flag off, the path is the same code run inline.

Mechanics: the job node owns all its inputs (no back-pointer, no lifetime
tie to the shader object), so re-sourcing or deleting a pending shader is
cancel-and-drop, never a wait; glslang worker hygiene is a TLS-allocator
scope guard plus GL-thread builtin prewarm (gated on the flag, latch reset
on Destroy so re-initialization re-warms); worker-side diagnostics defer
through the job and replay on the GL thread at the join, enforced by
IsPoolThread asserts in RecordError and an empty-deferred-errors tripwire.
A body that throws publishes a COMPLETE failed compile (status false, real
info log) rather than an abandoned node, and never memoizes away the retry;
a failed enqueue (OOM) cancels the node instead of stranding the joiner -
including inside the dispatch loop, where the in-flight slot is repaid.
The pool StopAndDrains from an atexit sentinel too: workers still inside
glslang parse while exit() ran static destructors was a real 2-in-5 SIGSEGV,
reproduced and fixed (15/15 clean after).

Backend-internal shader objects (default FS, DirectVulkan blit/mipmap) are
cache-less and always compile inline - compile-and-read-in-one-breath needs
no round trip.

Gates: unit suite 488/488 with the flag off AND on (x5); AsyncCompileTest
(12 e2e cases: pending re-source/delete/recompile, byte-identical failure
logs across modes, 48-compile cache stress) x10 repeats clean both modes;
full NVIDIA DirectGLES retrace identical result sets flag off/on (zero new
deltas); compile-phase timing flat as designed (links still serial - the
parallel win arrives with stage 4's async link + stage 5's
KHR_parallel_shader_compile).
2026-08-08 10:33:50 -04:00
BZLZHH c93e5fa409 [Refactor] (MG_State, MG_Util): join-by-construction link/compile artifacts (P1 stage 2)
Still fully synchronous - EnsureLinkJoined()/EnsureCompileJoined() are empty
inline no-ops (verified to fold away at every one of the ~1200 call sites;
this project builds without LTO) - but every read of link- or compile-produced
state now goes through a private accessor the compiler enforces, so when
stage 4 moves the bodies onto pool workers, 'which reads must join' is a
type-system fact instead of a 400-line audit.

- ProgramObject: the 31 fields ResetLinkArtifacts clears plus the 5 link
  outputs it forgot (infoLog, linkedFragData{Location,Index}, the geometry
  strip-capture pair) move into a nested LinkArtifacts behind Artifacts().
  ResetLinkArtifacts is now a worker-safe pure clear; the link-observable
  version bumps (backendState/link/uboContent) move to a GL-thread-only
  BumpLinkObservableVersions() called once from Link()'s prologue and from
  glProgramBinary's mandated failure - the link body never writes them, so
  a stage-4 worker cannot lose an invalidation against the draw path.
- ShaderObject: compile artifacts (TShader, preprocessed source, side-channel
  maps, status/log, consume-once flag) behind Compiled(); the P0b layer-1
  memo trio deliberately stays outside as the future non-joining
  COMPLETION_STATUS_KHR fast path.
- CompileEnv (new): a GL-thread snapshot of everything the compile pipeline
  used to read live from the backend mid-parse - compute limits (the
  GetIntegeri_v reach-back is gone from the worker path), advertised
  extensions, device quirks, TBuiltInResource inputs. Captured lazily per
  backend activation; the consume-once re-parse now runs against the same
  env as the original parse.
- The GL-thread prologue / worker-body boundary is marked in Link() where
  the stage sort ends; everything below is a pure function of the snapshot.

Public getter signatures unchanged - MG_Impl and both backends compile
untouched. Unit 476/476, Program suites 117/117, DirectGLES retrace 38/39 on
llvmpipe (the one failure is the known pre-existing non-CI iterationrp case;
the NVIDIA userspace driver was updated out from under the running kernel
module mid-session, so GLX there is down until a reboot).
2026-08-08 07:12:37 -04:00
BZLZHH 8191075133 [Feat] (MG_Util): the async-compile pool skeleton behind a default-off flag (P1 stage 1)
Standalone Asio (submodule, asio-1-38-2 @ 8806a680, ASIO_STANDALONE +
ASIO_NO_DEPRECATED, header-only - no linked artifact) and the job machinery
the async shader pipeline will run on: JobNode (state machine with deferred
errors, continuations firing exactly once, dependency counters, cancel
semantics split into request vs outcome) and ShaderCompilePool
(asio::thread_pool behind a pimpl so no header leaks asio; big-core count
via cpufreq at >=85% of peak clamped to [1,4]; lazily constructed, so with
the flag off no worker thread ever exists; StopAndDrain leads DestroyImpl).

MOBILEGL_ASYNC_SHADER_COMPILE / _THREADS config knobs, default OFF. Nothing
in the GL pipeline references the pool yet - grep-verified; the full
DirectGLES retrace and compile benches are byte- and time-identical. 25
threaded unit tests, clean across 20x gtest_repeat.
2026-08-08 05:28:51 -04:00
BZLZHH d6caed7822 [Fix] (MG_Util, MG_State): five latent frontend bugs the async work made load-bearing
- SpvcSession's move constructor and move assignment dropped the parsed
  metadata, so a moved-to session silently reported empty reflection.
- ParseComputeLocalSize used std::stoull, whose std::out_of_range escaped
  glCompileShader on an oversized local_size literal; now std::from_chars
  saturating to UINT_MAX, pinned by a regression test that reproduced the
  escaping exception.
- The compute local_size std::regex was rebuilt on every compile; hoisted.
- LinkProgram dumped every shader's full source through MGLOG_D per link.
- glslang::FinalizeProcess ran before the GL context tore down, leaving the
  context's live TShaders pointing at freed builtin symbol tables.
2026-08-08 05:28:28 -04:00
BZLZHH 9152e88734 [Perf] (MG_State): dedupe shader compiles by source hash
Iris-style packs hand MobileGL the same source text repeatedly: probed across
three shaderpack traces, 28-32% of all glCompileShader work was redundant -
~9% same-object recompiles with byte-identical source, ~21% distinct shader
objects sharing identical source (the same common GLSL chunk glued into many
program stages). Two layers, both keyed by XXH64 + length with a full byte
compare on every hit (correctness never rides on the hash):

- Per-object: a successful (or failed) compile remembers its source hash;
  glShaderSource with byte-identical text keeps the compiled state and
  glCompileShader on unchanged source returns immediately. Deterministic
  (stage, source) pipeline makes the memo observationally identical to
  recompiling; the consume-once TakeShaderForLink re-parse path is untouched.

- Cross-object: a per-context bounded cache (ProgramState-owned, declared to
  outlive every shader object) shares the preprocessed source, both explicit
  side-channel maps, and the validation verdicts between objects with equal
  source; only the glslang parse stays per-object. Single-GL-thread today;
  flagged for a mutex when compiles go async (P1).

Interleaved A/B on the iterationrp trace (the recompile-heavy pack):
5.65s -> 5.46s median total replay, every round faster; BSL/complementary
stay flat (their duplicate sources are the small common shaders, so calls
drop but wall time is parse-bound on unique sources). Full DirectGLES
retrace, 445-test unit suite, and dedupe-semantics tests (no-op recompile,
invalidation on new source, failed-compile memo, cache bounds) all green.
2026-08-08 04:18:32 -04:00
BZLZHH 2406e2d219 [Perf, Fix] (MG_Util): preprocessing cleanups - dead scanners, quote-mask bug, one version inspection per compile
Three scoped changes to ShaderSourceProcessor, none altering any transform's
output (pinned by a byte-stability test across the legacy-shader anchor path):

- Delete BlankBlockComments and RemoveDefineForIdentifier - dead since their
  callers left; the former's newline-terminated quote handling moves into
  MaskCommentsAndQuotedText (below) together with its rationale comment.

- Fix MaskCommentsAndQuotedText treating a quote as running past end-of-line.
  GLSL has no multi-line literals, but a stray apostrophe in a directive or
  comment tail ("#pragma message can't") blanked the REST OF THE FILE for
  every masked consumer - the tokenizer, the version inspection, and the P0a
  explicit-location/binding extractors silently lost everything after it.

- Inspect the shader language once per PreprocessShaderSource run instead of
  up to five times: NormalizeVersionDirective now takes the already-computed
  ShaderLanguageInfo, and the two after-version injections share one
  AfterVersionAnchor instead of re-running a full masked sweep each
  (FindAfterVersionDirective -> InspectShaderLanguage) to find the same spot.

Compile-phase timings hold (BSL 1.848s, complementary-reimagined ~5.7s);
retraces and the 435-test unit suite unchanged.
2026-08-08 03:43:56 -04:00
BZLZHH b228f813c0 [Perf] (MG_Util): replace the builtin-shadowing string scans with one tokenize and a SPIR-V OpName pass
RenameBuiltinShadowingFunction probed the whole source ten times per compile
(5 names x mask + scan, each a full-text pass) and still had two blind spots:
a 5-name list and single-line-definition-only detection. On Complementary-scale
packs (4.5MB of sources) that was ~68% of the compile phase.

The rename is now split by FAILURE LAYER, both halves sharing one name table
header so they cannot drift:

- A SPIR-V OpName pass in SanitizeAndOptimizeBinary covers the full ESSL 3.20
  builtin set (~146 names). Renaming a function id is safe by construction:
  builtin calls are GLSL.std.450 instructions and can never resolve to a user
  OpFunction, overloads are distinct ids (a helper overload delegating to the
  real builtin keeps working), dead preprocessor branches never reach SPIR-V,
  and macro-expanded definitions are covered. ESSL 3.x is the only consumer
  that forbids the redefinitions, and this pass runs before its transpile.

- A lexical pass covers only the 5 names whose exact-signature redefinitions
  glslang's relaxed parse rejects outright (never producing SPIR-V for the
  backstop): the historical fma/max3/min3/round/tanh. One TokenizeCode pass;
  definition detection requires brace depth 0, a type-identifier previous
  token that is neither a statement keyword nor a directive tail, and skips
  files whose token-level braces do not balance (preprocessor-asymmetric
  arms) - over-detection is unrecoverable, so every ambiguity falls through
  to the backstop.

Measured on the compile phase (prefix-diff, 3-run medians, Espryt/NVIDIA):
complementary-reimagined 20.0s -> 5.5s, BSL 2.14s -> 1.85s. bliss (the pack
that ships from-scratch fma/tanh helpers) stays at SSIM 0.999962.

Tests: end-to-end ESSL assertions for the multiline-definition and
new-overload shapes, the three adversarial-review reproductions (statement-
keyword call under asymmetric braces, dead-#if compat shim, overload
delegating to the shadowed builtin), and a source-level assertion pinning
the lexical half specifically.
2026-08-08 03:11:38 -04:00
BZLZHH 0d0527192a [Perf] (MG_State, MG_Util): compile shaders with a single relaxed parse
glCompileShader used to parse every source twice: once under the GL client
(reflection only) and once under the relaxed Vulkan client (SPIR-V + the
plain-uniform global UBO), with GenerateBinary re-preprocessing, re-parsing
and re-linking every attached shader on every glLinkProgram. The GL-client
pass is gone: Compile() performs the one link-compatible relaxed parse and
the linked TProgram serves reflection and codegen both. Measured on the BSL
shaderpack compile phase: Espryt 2.80s -> 2.14s, Magma 3.78s -> 3.07s.

What the relaxed parse cannot provide is restored explicitly:
- explicit layout(location/binding) qualifiers on default-block uniforms and
  samplers are extracted lexically at Compile() (the relaxed parse strips
  them) and merged per link with cross-stage conflict checks;
- uniforms the relaxed parse sweeps into MGL_GLOBAL_UBO but no stage reads
  are filtered from the GL reflection surface through GL<->TProgram index
  translation maps (dead uniforms stay inactive, the synthesized block stays
  hidden, builtins reflect under their GL spellings);
- SPIR-V is generated BEFORE buildReflection touches the program (its
  live-variable analysis perturbs GlslangToSpv output - generated modules
  stay bit-identical to the old pipeline's), while the glUniform*-to-scratch
  routing tables are built strictly AFTER reflection, whose results size and
  key them;
- a TShader feeds exactly one link (mapIO mutates the intermediate); relinks
  and multi-program attachments re-parse the stored preprocessed source.

Validated: DirectGLES retrace suite green (two pre-existing local-driver
failures unchanged old vs new), KHR-GL30 877/878 on Espryt/NVIDIA (the one
failure pre-exists this change), unit tests green, per-module SPIR-V hashes
identical across a full DirectVulkan replay.
2026-08-08 01:25:54 -04:00
BZLZHH 81bcbd6c14 [Fix] (MG_State): allocate program and shader names from one shared name space
GL 3.3 core 2.11 puts program and shader names in one name space: a shader
name passed where a program is expected must fail with INVALID_OPERATION,
and vice versa. Two independent IndexGenerators handed out colliding names
(shader 2 and program 2 could coexist), so CheckProgramNameValidity resolved
a shader handle to an unrelated linked program and the error checks in
KHR-GL30.get_uniform_tests.get_uniform were silently swallowed - the case
only ever passed because the collided program happened to reject the queried
location. One shared generator keeps the names disjoint; the per-kind object
tables are unchanged.
2026-08-08 01:25:37 -04:00
BZLZHH 867fe3e0ef [Feat] (MG_Util, MG_IntegrationTest): POST rows for the Espryt multi-draw tier, and the scenario that pins it
Three DriverPost rows per the POST rule, since the ladder took on two
new driver dependencies: glDrawElementsBaseVertex (WARN when absent -
every base-vertex draw then costs a CPU index rewrite and an upload) and
compute shaders (INFO - the default tiers never use them). The third
names the tier that will actually run, with the full set the driver
supports, resolved by the same function the backend calls so the two can
not drift. The existing "Multi-draw base vertex" row stopped saying the
fallback is a per-draw loop, which is no longer the whole truth.

Scenario D asserts the one contract every tier shares: a multi-draw
paints exactly what the unrolled single draws paint. The reference side
is a loop of glDrawElementsBaseVertex and never enters the emulation, so
a tier cannot make itself look right by breaking both sides alike, and a
blank-frame pair is rejected outright - drawing nothing is the failure
mode this path actually has.

Nine cases, chosen for the shapes the Minecraft retraces contain none
of: narrow index types, a base vertex past the index type's range,
primitive restart inside a strip on two index types, client-memory index
arrays, and a batch with zero-count sub-draws (whose prefix sums the
flattening tier's binary search has to skip). Each of the six tiers
passes all nine on NVIDIA, and ext/auto/compute also pass on Mesa where
the ext tier is reachable.

The suite is falsifiable, not merely green: rewriting the rebase the way
MobileGlues does it - truncate to the source width, no restart
passthrough - fails exactly three cases on the drawelements tier (both
restart cases and the out-of-range base vertex) and leaves basevertex,
which rewrites nothing, passing. That control is also what turned up the
restart hole in the flattening tier fixed in the previous commit.
2026-08-07 08:16:08 -04:00
BZLZHH 0ec487c993 [Feat] (MG_Backend): port MobileGlues' multi-draw emulation to DirectGLES as a tier ladder
ES has neither glMultiDrawElements nor glMultiDrawElementsBaseVertex, so
both are emulated. DirectGLES had two ways of doing it - one
glMultiDrawElementsBaseVertexEXT where the driver has the extension
interaction, otherwise a per-draw loop. This adds the five MobileGlues
uses (gl/multidraw.cpp), so the ladder is now: one
glMultiDrawElementsBaseVertexEXT; one glMultiDrawElementsIndirectEXT
over a synthesized command buffer; one glDrawElementsIndirect per
command over that same buffer; the base-vertex replay; plain
glDrawElements over a CPU-rewritten index stream, for drivers with no
base-vertex draw at all; and a compute shader that flattens the whole
batch into one rebased index buffer drawn by a single glDrawElements.
They live in their own translation unit that owns the entry point
outright, preparation included - the compute tier has to dispatch BEFORE
PrepareForDraw, or it would have to unpick the program, storage-block
and index bindings the preparation just made, and a dispatch inside an
open transform-feedback span is not legal at all.

The auto ladder is ext -> basevertex -> multiindirect -> indirect ->
drawelements, which is NOT MobileGlues' order (it puts the indirect
tiers first). Measured on mc_sodium_multidraw, ns/op, median of three:
NVIDIA ES 3.2 basevertex 2500 vs multiindirect 5700 and indirect 5800;
Mesa llvmpipe ext 19300, basevertex 25200, multiindirect 27600,
drawelements 28700, indirect 31000. Ring-allocating the command staging
instead of respecifying per batch was tried first and moved the indirect
tiers by less than noise, so the cost is the indirect draw path itself,
not the upload; only a real multi-draw entry point beats replaying the
sub-draws. auto therefore resolves to basevertex on this box - byte for
byte the behaviour that shipped - and the new tiers are what a driver
with the ext interaction, or without base vertex at all, now gets.
compute is never chosen by auto (nor by MobileGlues'): it rewrites the
primitive stream rather than replaying it, and it measured slowest here.

Four places this deliberately does not follow MobileGlues, each a
correctness bug there. A rewritten stream is emitted as GL_UNSIGNED_INT
whatever came in, because GL adds baseVertex at full precision and
folding it into ushort indices wraps. The restart sentinel is carried
across a rebase unrebased, or an enabled primitive restart is lost. The
flattening tier declines strip/loop/fan modes, any sub-draw whose count
is not a whole number of primitives, and any batch at all while
primitive restart is enabled - a restart ends a primitive, so leftover
vertices would find a third vertex in the next sub-draw and become a
triangle GL never draws. And the indirect tiers decline client-memory
index arrays, which have no buffer to address.

gl_DrawID gets better rather than worse: the unrolled tiers now feed
each sub-draw its index (the spec's value, where the old loop left the
uniform untouched), and a program that actually reads it demotes the
batched tiers, which can only hold one value for the whole batch. The
per-batch cost is nil for the programs that do not read it.

Verified: the five DirectGLES retraces are byte-identical (md5) across
all six tiers on NVIDIA and on Mesa, each tier proven to have really
executed rather than silently demoted, via a per-tier announcement in
the log. Unit suite 421/421. The full retrace suite's five failures all
reproduce unchanged on a stashed tree, so none are new.
2026-08-07 08:15:54 -04:00
BZLZHH 23b880c8be [Feat] (MG_Config, MG_Util): a tier knob and two capability flags for Espryt multi-draw
MOBILEGL_ESPRYT_MULTIDRAW_MODE=ext|multiindirect|indirect|basevertex|
drawelements|compute|auto names the DirectGLES emulation tier for
glMultiDrawElements(BaseVertex). Same contract as the Magma knob: a
preference, not a demand, clamped at resolution time to what the driver
actually has, and invalid values keep auto. Nothing reads it yet.

The two capability flags the ladder selects on are new because neither
existed in the shape the choice needs. SupportsDrawElementsBaseVertex is
the weaker sibling of SupportsMultiDrawElementsBaseVertex - ES 3.2 core
or EXT/OES_draw_elements_base_vertex, with no GL_EXT_multi_draw_arrays
requirement - and it decides whether a batch can replay its sub-draws
with their own base vertices or has to fold them into rewritten indices.
SupportsComputeShader is ES 3.1 core plus the dispatch, barrier and
shader-object entry points. Both keep the house rule the multi-draw
flags already follow: the extension/version check is what proves
support, the resolved pointer only confirms it, because
eglGetProcAddress may hand back a live-looking stub for a function the
context does not implement.
2026-08-07 08:15:31 -04:00
BZLZHH ebc5bff9b1 [Fix, Feat] (MG_Backend): make DirectVulkan multi-draw actually draw, then pick its best tier
The bug: DirectVulkan.cpp::MultiDrawElements had its entire body
commented out - plain glMultiDrawElements on Magma recorded NOTHING,
no error, no pixels (readback shows the deferred clear never even
materialized). It now shares the tuned base-vertex implementation, and
both plain entries are pixel-proven by a 4-sub-draw harness.

The feature: every CPU-side multi-draw form dispatches through three
tiers after round-9's contiguous-run merge (restructured to merge into
a span BEFORE dispatch, so every tier consumes the shrunken array):
  1. VK_EXT_multi_draw: one vkCmdDrawMulti(Indexed)EXT, chunked by
     maxMultiDrawCount; per-draw vertexOffset rides in the struct. The
     extension is requested only when enumerated and its feature bit
     confirmed, entry points via vkGetDeviceProcAddr, demoted if
     missing.
  2. multiDrawIndirect: the param span uploads DIRECTLY as a transient
     INDIRECT-usage buffer - DrawIndexedCmdParam is layout-identical
     to VkDrawIndexedIndirectCommand and DrawCmdParam's head is a
     legal 24-byte-stride VkDrawIndirectCommand, both static_asserted,
     so no repacking - then one vkCmdDraw(Indexed)Indirect per
     maxDrawIndirectCount chunk. firstInstance!=0 additionally
     requires drawIndirectFirstInstance or the batch drops a tier.
  3. The byte-identical unroll.
gl_DrawID: tiers 1-2 are spec-correct (0,1,2,3 across a probe's
sub-draws); the unroll tier keeps the pre-existing always-0 contract.
The default tiers strictly improve DrawID correctness.

Adversarially verified: the five real DirectVulkan retrace images are
BIT-IDENTICAL (md5) across auto/ext/indirect/unroll; zero validation
VUIDs on every tier; a simulated no-EXT device resolves to indirect
and renders the same bytes; the known-red create-indirect fixture
crashes at the identical call before and after (not worse, not fixed).
Unit suite 423/423 on the rebased tree, retrace subset 10/10. Bench:
mc_sodium_multidraw's contiguous shape merges 32->1 before dispatch,
so no bench delta - the tiers' beneficiaries are non-contiguous real
streams (the sodium RETRACE pushes ~58-sub-draw batches, in=out
243101 with zero merges) and mobile drivers. A reproducible +3-4%
code-layout drift on mc_use_program (zero shared code, I-cache
displacement from +400 lines) stays under the action gate and is
booked here rather than hidden.
2026-08-07 06:41:21 -04:00
BZLZHH 231d5c90e4 [Feat] (MG_Config, MG_Util): a preference knob and POST rows for Magma's multi-draw tiers
MOBILEGL_MAGMA_MULTIDRAW_MODE=ext|indirect|unroll|auto selects the
DirectVulkan multi-draw dispatch tier, clamped to what the device
supports with one INFO line when it falls back; auto (and unset) picks
the best supported tier. Invalid values keep auto. Magma-only: the
variable has no effect on DirectGLES. Note for the escape hatch:
mode=unroll also forces the GL indirect multi-draw paths onto their
per-command loop, where gl_DrawID reads 0 for every sub-draw -
Flywheel-style content that keys on flw_drawId renders accordingly.

Three DriverPost rows per the POST rule: VK_EXT_multi_draw
(PASS/INFO), the multiDrawIndirect feature (WARN downgraded to INFO -
there is always a fallback tier), and the resolved dispatch tier with
the full chain. drawIndirectFirstInstance gains a row too, since the
indirect tier's legality check now relies on it.
2026-08-07 06:41:21 -04:00
BZLZHH d5f5e6405b [Perf] (MG_Backend): batch DirectGLES multi-draw base-vertex where the driver really has it
When SupportsMultiDrawElementsBaseVertex is true, glMultiDrawElements-
BaseVertex issues one glMultiDrawElementsBaseVertexEXT instead of a
per-draw loop; the fallback loop is byte-identical otherwise.

The local NVIDIA ES driver lacks GL_EXT_multi_draw_arrays, so the
batch cannot engage here and no local win is claimed (counter-proven:
batched=0 / fallback=264329 across a sodium retrace). On Mesa llvmpipe,
which implements the full interaction, the batch engages (batched=4566,
~58 sub-draws per call) and is pixel-identical to a forced-fallback
control (same SSIM to the last digit). The beneficiaries are mobile
drivers advertising the interaction - the Sodium chunk path collapses
32 driver entries into one - and the DriverPost row shows which side
any device falls on. A/B on both backends: every case inside the 5%
bar. Unit suite 423/423, retrace subset 10/10.
2026-08-07 06:00:54 -04:00
BZLZHH ac3a83b207 [Fix] (MG_Util, MG_Test): never take a non-null eglGetProcAddress result as support
On GLVND Linux eglGetProcAddress returns a non-NULL trampoline for ANY
name - including a fabricated one - so pointer-nullness can never
signal driver support. The three EXT multi-draw entry points were
registered as required (spurious error logs on drivers without them)
and their pointers were trusted; the NVIDIA ES driver hands back a
stub for glMultiDrawElementsBaseVertexEXT that SILENTLY DROPS draws,
which once made a "77% faster" multi-draw batch that rendered nothing.

The three entries are optional now, and two extension-derived
capability flags follow the established Supports* pattern - each is an
extension-string check AND a resolved pointer, so a flag alone is
sufficient at a call site:
  SupportsMultiDrawIndirect: GL_EXT_multi_draw_indirect + both entry
  points resolved.
  SupportsMultiDrawElementsBaseVertex: (GL_EXT or
  GL_OES_draw_elements_base_vertex) + GL_EXT_multi_draw_arrays + the
  entry point resolved. The multi_draw_arrays conjunct is the registry
  fact the stub exploited: glMultiDrawElementsBaseVertexEXT exists only
  in interaction with GL_EXT_multi_draw_arrays, and this NVIDIA driver
  advertises everything else EXCEPT that one - so the entry point is
  genuinely unsupported while eglGetProcAddress still "resolves" it.

Two DriverPost rows report both capabilities (INFO when absent - a
fallback always exists). Unit tests pin the stub shape, the exact
NVIDIA shape, the supported shape and extension-without-pointer.

Proven load-bearing: forcing the old pointer-only condition on the
NVIDIA ES driver reproduces the silent drop exactly (sodium retrace
SSIM 1.000000 -> 0.329522, no crash, no GL error); with the gate the
same run is a literal 1.000000. Unit suite 423/423 (two new tests),
retrace subset 10/10, integration suite 52/52.
2026-08-07 06:00:54 -04:00
BZLZHH 335f2decbd [Perf] (MG_Backend): stop DirectVulkan re-proving sampler sets and re-walking render passes
Two per-draw costs from the round-10 profiles. A per-program sampled-set
epoch inside UniformManager skips the per-binding descriptor proof walk
when no texture or sampler API ran since that program's previous draw -
the mc_sampler_churn/mc_tex_param pattern. The pass-switch path stops
re-deriving render-pass state that its own value hash already pins.

Load-gated 6-round order-alternating A/B (medians): magma tex_param
-13.3%, pass_switch -10.9%, state_toggle -5.4%; espryt untouched and
unmoved. The two matrix flags (sodium +7.5%, tex_stream +6.2%) reversed
under 10-pair isolated alternating re-runs (-5.5% and +2.5%) - the same
position-bias artifact every previous round's flags showed. Unit tests
421/421; retrace subset and the 52-entry integration suite pass.

Landing note: this diff was authored by a round-10 agent whose session
died before adjudication; the A/B data survived (r10bmag_ab_raw.csv)
and the flags were adjudicated before landing. Its relink also exposed
the pre-existing exit-teardown SIGSEGV fixed in the previous commit.
2026-08-07 04:13:55 -04:00
BZLZHH fb1ad96c04 [Fix] (MG_Backend): stop DirectGLES twin destructors calling a dead driver at exit
The static twin registries destroy their backend objects from
__run_exit_handlers, and a twin destructor then jumps through
g_GLESFuncs into a driver library that exit() may already have torn
down - a latent SIGSEGV that DriverBench has been dumping core with on
every exit, and that any relink shuffling static destructor order can
hand to the trace-replay binary (a byte-perfect replay then "fails with
status Segmentation fault").

A process-teardown flag now short-circuits the program, VAO and texture
twin destructors: past exit() the driver reclaims every GPU object
anyway, so the skip is a deliberate leak of nothing. The flag is set by
a std::atexit handler registered lazily on first registry use - by then
every static everywhere has finished constructing, so the handler runs
BEFORE any static destructor. A registry-destructor hook was tried
first and is wrong: tests and cache resets destroy temporary registry
instances mid-run, which latched the flag while the process was alive
(caught by DirectGLESBackendTexture.DestructorDeletesIdAndScrubsBindingCache).

421/421 unit tests, the retrace subset exits cleanly on both backends,
and the 52-entry integration suite passes.
2026-08-07 04:13:55 -04:00
BZLZHH 313b75a7c0 [Test] (MG_IntegrationTest): pin the two shipped memo bugs with rendered pixels
Both d7976326 bugs passed every unit test while corrupting real frames -
state-level assertions cannot see them. This module renders and reads
back.

A headless EGL-pbuffer harness (no window, no GLFW) linking MobileGL_s
directly, registered once per backend under the ctest label
integration-gpu, behind the default-OFF option
MOBILEGL_BUILD_INTEGRATION_TEST. The platform pre-flight runs the ENTIRE
bring-up in a forked child first - MobileGL aborts rather than returning
errors on an unusable platform, and the child dying on any signal turns
into a clean GTEST_SKIP instead of taking the test binary down.
MOBILEGL_ITEST_REQUIRE_GPU makes the label falsifiable: with it set, an
unusable harness (or a context that lands on a software rasterizer) is a
FAILURE - without it, a CI runner whose driver pinning silently broke
reports the same green as one that rendered every frame. Configure-time
detection pins the EGL vendor and Vulkan ICD jsons, preferring hardware
vendors and never selecting llvmpipe/lavapipe.

Scenarios assert on glReadPixels with whole-region pixel counts (a
2x2 quadrant pattern whose signature distinguishes all eight square
symmetries; every region predicate reports the first offending pixel):
- OrientationScenario: default -> FBO -> default, pinning the
  transform-flags memo key. Keying GetBaseTransformFlagsRaw on the
  pre-transform alone fails exactly 3 entries.
- StreamedArenaScenario: an untouched streamed vertex buffer must
  survive transient-arena recycling. Re-enabling only the cross-frame
  vertex revalidation fails exactly this entry.
- CrossFrameBufferScenario + ResidentIndexScenario: cross-frame
  mutation matrix (SubData, map/unmap, persistent+flush, coherent
  persistent, orphan, CopyBufferSubData; vertex and index) plus six
  adversarial resident-EBO constructions. Instrumentation showed the
  cross-frame EBO memo cannot be made to serve wrong bytes from GL
  level on this stack (89 entries, 81 accepts, zero divergent slices) -
  these cases are freshness tripwires, documented as such in-file; the
  EBO half of d7976326 remains unpinned by a failing test.

At the buggy commit 72ee7c43 the suite fails 4 entries (3 orientation +
1 streamed-arena); at d7976326 all 52 pass, 5 consecutive runs, zero
flakes, and the default build is bit-for-bit unaffected (unit suite
unchanged). Adversarially verified twice, including hostile-platform
sweeps (26 configurations, all clean skips) and hand-edits of each
production hole in isolation.
2026-08-07 03:30:18 -04:00
BZLZHH d7976326fa [Fix] (MG_Backend): two DirectVulkan draw memos trusted more than they proved
Two correctness holes from the round-7/8 fast-path work, found by
bisecting the retrace matrix after corruption reports on device.

Cross-frame slice trust: the vertex-binding and EBO memos skipped the
acquire - the frame's content-sync point - whenever their recorded
slice epochs still matched, trusting the BumpSliceEpoch inventory to
cover every way a buffer's GPU copy can go stale. At least one mutation
path escapes it: journeymap and common-mods retraces shipped visibly
corrupted, and Sodium on an Adreno device rendered random triangles
from stale vertex data. A memo recorded in an earlier frame now
declines, so the first draw of each (VAO, frame) re-runs the full
acquire; the same-frame paths (layout memo, factory-chase elimination,
one-compare rescue) are untouched. The cross-frame idea can return once
the bump-site inventory is proven complete against exactly these traces.

Transform-flags memo key: GetShaderTransformFlags reads the swapchain
pre-transform AND whether the bound draw framebuffer is the default one
- only a presenting pass gets the Y-flip/rotation bits. The memo
declared it pure in the pre-transform, so after any render-to-texture
pass the next default-framebuffer pass inherited the FBO's unflipped
flags: 1.17-main-menu retraced as a perfectly rendered, perfectly
upside-down frame (SSIM 0.052, deterministic), and cloud passes
flickered on device. The memo now keys on (preTransform, isDefaultFbo).

DirectVulkan retraces for 1.17-main-menu, journeymap, common-mods,
sodium and xaero-world-map all pass on lavapipe; unit tests 421/421.
2026-08-06 21:55:41 -04:00
BZLZHH 72ee7c439c [Perf] (MG_Backend): merge DirectVulkan's contiguous sub-draws, remember four programs
61% of mc_sodium_multidraw's steady-state CPU sat inside the driver
encoding one vkCmdDrawIndexed per sub-draw. MultiDrawElements now
collapses contiguous runs: merge only when the topology is a list
(POINTS/LINES/TRIANGLES), the accumulated count sits on a primitive
boundary, primitive restart is off, baseVertex/instanceCount/
firstInstance are identical and firstIndex is adjacent, with a
count-overflow guard - the bench's 132x32 sub-draws become 132x1.
Dangling-index discard semantics for list topologies are what the GL
spec already mandates per draw. No new Vulkan feature, so no DriverPost
gate; VK_EXT_multi_draw stays a gated follow-up.

The draw fast path's single SetupDraw snapshot died on every program
ping-pong (use_program's A/B pattern sent every other draw down the
full path, CollectSampledTextures alone 6.2% self). A 4-entry
program-keyed snapshot table (MRU by program lifetime id, per-entry
sampled-set copies, per-entry invalidation on decline or full-path
start, all entries still cleared at command-buffer boundary, pipeline
age-out and swapchain recreate) keeps all cycling programs hot.

Load-gated 6-round order-alternating A/B, sha1-fingerprinted pair:
sodium_multidraw -41.3%, use_program -23.9%, pass_switch -12.7%,
tex_param -3.8%, vanilla -2.1%; the one flag (tex_stream +5.4%)
reversed to -0.5% across 10 isolated alternating pairs. Espryt
untouched and unmoved. Unit tests 421/421.
2026-08-06 20:17:19 -04:00
BZLZHH cdea275227 [Perf] (MG_Backend): stage only the rects DirectVulkan actually dirtied
Consume MipmapStorage's new dirty-rect list: pack each rect tightly
into the staging block and issue ONE vkCmdCopyBufferToImage with N
regions instead of staging the whole union box. Offsets are computed
identically in the pack and copy loops; disjoint rects mean no
overlapping copy destinations; the combined depth-stencil and
RGB-expand/depth-convert paths keep their single-box route (gated to
the color-aspect, no-conversion case).

54% of mc_tex_stream's steady-state CPU was the one shadow->staging
memmove of the union box; staged bytes drop to 4.8% (~2MB -> ~95KB per
frame) and the case improves ~-49% (5945 -> 3048 ns/op, ~2.2x native
to ~1.2x). Zero validation-layer findings on the 95-region copy. Unit
tests 421/421.
2026-08-06 20:17:19 -04:00
BZLZHH 6a02c5fea0 [Perf] (MG_Backend): upload only the rects DirectGLES actually dirtied
Consume MipmapStorage's new dirty-rect list: when a level offers a
profitable rect list, the sync path issues one glTexSubImage2D/3D per
rect under a single UNPACK_ROW_LENGTH set/reset instead of one call
covering the union box. Striding is the exact scheme the single-box
path already uses (UNPACK_ALIGNMENT pinned to 1 by
ScopedDefaultUnpackState, so every bpp is stride-exact); levels
without a profitable list take the old path unchanged.

On the atlas-streaming case this trades one ~2MB upload for ~95 small
ones totalling ~95KB - roughly a wash in driver-call overhead on
desktop NVIDIA GL (mc_tex_stream ~-3%), a clear byte-volume win for
tiled/mobile GLES where the driver shadow-copies every upload. Unit
tests 421/421.
2026-08-06 20:17:19 -04:00
BZLZHH 7db5b35a3e [Perf] (MG_State): remember every dirty rect, not just their union
A Minecraft frame updates ~95 scattered 16x16 sprites in a 1024x512
atlas; MipmapStorage's single union dirty box turned ~95KB of changed
texels into a ~2MB upload on every backend. The storage now keeps a
bounded (96-slot) list of pairwise-disjoint dirty rects BEHIND the
untouched union box: rects cascade-merge on touch or overlap, overflow
folds the pair with minimum enlargement and re-cascades, whole-level
dirties and respecifies just clear the list (empty list = "union box
tells all"). GetDirtyRects hands the list out only when it has 2+
rects, fits the caller's capacity, and its summed area is under 75% of
the union box - fewer driver calls beat equal bytes - so consumers can
never stage more than the union box did.

The list is maintained inside the same four mutation funnels every
texel writer already goes through (MarkDirty, MarkDirtyRegion,
AllocateLevel, TruncateToLevelCount - callers enumerated at the
declaration), so list and union box cannot disagree. Backends OPT IN:
the union-box API and its update order are byte-identical, and an
unmodified backend keeps rendering exactly as before.

96 slots is measured, not guessed: on the bench's 95-sprite lattice a
16-slot list collapses to >93% of the union box, 96 slots reach 4.8%
(~2MB -> ~95KB staged per frame). Verified by a 2859-check fuzz run
against a reference dirty bitmap (union exactness, full coverage,
disjointness, bounds, profitability). Unit tests 421/421.
2026-08-06 20:17:19 -04:00
BZLZHH 990e518e33 [Perf] (MG_Backend): give DirectVulkan's draw memo a table that fits in cache lines
The per-VAO resolved-bindings map probe was ~45% of
UploadAndBindVertexBuffers' self time, and the aux-memo pointer chase
was the single hottest instruction left in TrySetupDrawFastPath. Both
die together: a fixed 2048-slot two-probe 64B-aligned VaoDrawMemo table
embeds the VAO key, content-hash-validated layout facts and the
bindings payload reordered hot-to-cold. Layout facts hold exactly while
the slot's content hash equals the live VAO's own config-guarded hash;
a recycled VAO address either misses or reproduces a byte-identical
config, for which the facts are correct by construction. Bindings keep
their full per-draw revalidation; recycled slots zero their frame
serials so half-filled entries can never match.

ComputePipelineStateHash, the depth/stencil probe and the
primitive-restart probe now take one bulk GetRenderStateParameters()
fetch instead of ~17 cross-TU accessor calls (verified pure field
reads, identical bit packing). The EBO slice memo gained the same
manager-wide epoch one-compare rescue the vertex half uses.
GetShaderTransformFlags is memoized on pre-transform. Sodium's
MultiDrawElementsBaseVertex hoists GetGLTypeSize out of the
per-sub-draw loop, replaces the division with a shift, and skips
unsupported index types loudly instead of dividing by zero.

Also verified: a GL_BLEND toggle recompiles nothing in steady state -
the glslang frames in earlier state_toggle profiles were startup
contamination.

Quiet-box load-gated 6-round A/B: sodium_multidraw -8.0%, tex_param
-4.1%, use_program -3.3%; steady-state vanilla_draw CPU -20% ns/op at
4096 frames (the 80-frame matrix compresses CPU wins under GPU boost
clocks; profiles confirm UploadAndBindVertexBuffers 6.3% -> 4.4%
including the table probe, and the aux cold-line load gone). The one
matrix flag (pass_switch +7.5%) reversed to -3.2% in 10-pair isolated
re-runs. Unit tests 421/421.
2026-08-06 14:07:49 -04:00
BZLZHH 25a8f51db5 [Perf] (MG_Backend): make DirectGLES program switches remember their own bindings
mc_use_program cycles programs whose texture bindings never change, yet
every switch re-walked the units. Six fixes, one theme: a switch back to
a known program should find its own state waiting.

Per-program 4-entry resolved-texture-binding memo (round-robin, shadow
memcmp on hit) skips the unit walk when a program returns with its
bindings intact. The whole sampler-uniform pass in
BindCurrentProgramWithResources is memoized per program twin behind
(context, unitBindingsEpoch, samplingGeneration, backendStateVersion,
textureContextGeneration) plus a per-sampled-unit sampler-shadow row
compare, invalidated on relink/backend rebuild; the
BindCurrentUnitSamplers walk sits behind the same keys. Every unit
assignment, sampler-parameter change and bind path was verified to bump
one of those inputs.

UboRingAllocate's common path is now a generation check, a power-of-two
mask, an overrun check and a head bump - the duplicate availability
probe, frame-mark retirement and divisions moved to the wrap slow path.
The per-context framebuffer binding slots (the frontend getter
linear-scans per call) are cached as direct pointers - slots are
by-value members of GLContext, so the pointers are stable by
construction - feeding SyncCurrentFBO, SyncNeccessaryTextures and the
broadcast memo; BindCurrentFBO's per-draw registry hash Find became a
TwinLookupMemo probe. The VAO config-version cold-line load is hoisted
to the top of PrepareForDraw to overlap its miss.

Quiet-box load-gated 6-round order-alternating A/B, all nine cases,
both backends: use_program -27.7%, vanilla_draw -16.2%, ubo_range
-13.4%, pass_switch -11.1%, sampler_churn -10.7%, state_toggle -9.2%,
sodium_multidraw -5.3%, rest flat. No regression on either backend
(magma's one matrix flag disproved by isolated re-runs against
byte-identical DirectVulkan sources). Unit tests 421/421.
2026-08-06 14:07:49 -04:00
BZLZHH 8f2b766b56 [Perf] (MG_Backend): let DirectVulkan trust across frames what it proved once
The draw fast path still paid for its own proofs: the hottest single
load (20% of TrySetupDrawFastPath) was chasing the cold
VertexInputStateFactory heap entry just to answer "same vertex-input
layout?". That answer now comes from the frontend VAO's config-guarded
aux memo (layout hash + attribute masks), and a VAO-cycling stream with
a stable layout skips the pre-flight AND pipeline re-resolution
entirely. The VkProgramObject* is memoized on the snapshot behind a new
ProgramFactory cache-structure epoch (bumped on every insert/erase; use
is re-stamped so the idle sweep can never evict a live entry). A
render-state version move no longer forces the full path: the pipeline
value hash is refreshed in place and the 8-entry memo probed directly
(the GL_BLEND-toggle case).

The resolved-vertex-bindings memo now revalidates all-resident unmapped
entries ACROSS frames via per-binding slice epochs - minted from a
process-lifetime counter so a recycled address can never revalidate,
with every mutation path funnelled through BumpSliceEpoch - while
stamping each resource's GPU-use serial exactly as the skipped acquire
would, preserving the busy-tracking that glBufferSubData's
host-write-vs-staged-copy choice depends on. Resident index buffers get
the same treatment through an EBO slice memo.

The six-part dynamic-state tail (viewport/scissor/blend constants/depth
bias/line width/stencil) is gated behind one render-state-parameters
version + pass-geometry compare per command buffer. GetSlice is inlined;
SampledBindingsUnchanged walks only the program's declared bindings.

Quiet-box 6-round order-alternating A/B (on top of the frontend
VAO-bind commit): vanilla_draw -20.8% (790 -> 626 ns/op, 3.4x native to
2.5x), sampler_churn -28.2%, ubo_range -8.4%, state_toggle -3.8%;
tex_param's matrix flag (+10%) was adjudicated by an isolated
alternating re-run at +1.0% - position bias, not regression. Unit tests
421/421.
2026-08-06 13:18:38 -04:00
BZLZHH b9d8ad0421 [Perf] (MG_Backend): give DirectGLES one epoch that says no buffer moved
Four draw-path costs, one theme: re-proving what nothing invalidated.

A manager-wide buffer-mutation epoch (atomic; bumped with release AFTER
every mutation lands: all six BufferBackendOps via tracking wrappers,
every backend-initiated writeback - XFB readback/scatter, the five
pack-PBO readbacks - registry registration changes, and backend context
destruction; the full site inventory lives in a comment at the accessor)
lets the per-VAO resolved-buffers memo stamp the epoch after one
all-clean probe pass and skip every IsBufferDrawClean probe while it
holds. The IBO keeps its bound-object identity compare - only the probe
is elided. Non-bumping paths are enumerated with why they are safe:
GPU-authoritative writes are ignored by the probe, persistent-mapped
resources are clean by construction, and draws on non-persistent maps
are frontend-rejected GL errors.

GetProgramForDraw is hoisted to one call per PrepareForDraw and handed
to the four consumers that each re-derived it. The enabled-draw-buffers
walk feeding the fragColor broadcast count is memoized on the
(FBO, slot version, object version) trio. The UBO-binding loop probes
IsBufferDrawClean before falling back to EnsureBufferResource.

The texture chain captures (context, maxTouchedUnit, samplingGeneration,
unitBindingsEpoch) once per draw - shared by SyncNeccessaryTextures and
BindCurrentTextures, halving the epoch computations - and an aggregate
gate that is the exact conjunction of the three Sync*ToBackend
early-outs skips the per-texture cross-TU calls.

The t_egl* thread_local verification pair became owner-thread-guarded
atomics reset by MakeCurrent/ReleaseCurrent, removing __tls_get_addr
from the draw loop.

Quiet-box 6-round order-alternating A/B (with the frontend VAO-bind
commit): all NINE Espryt cases improved - sampler_churn -11.0%,
state_toggle -9.3%, ubo_range -9.1%, vanilla_draw -5.4%, pass_switch
-3.5%, the rest -1% to -2.5%. Unit tests 421/421.
2026-08-06 13:16:44 -04:00
BZLZHH f8069c0624 [Perf] (MG_State): stop paying two atomic refcounts for every glBindVertexArray
perf annotate put 94% of VertexArrayState::Bind's 10.5% self time on the
two lock-prefixed shared_ptr refcount RMWs each bind performs. The bound
VAO is now stored as a slot index into m_vertexArrays - no SharedPtr
copy, no atomics on the bind path. The lifetime invariant (the bound
object is kept alive by its slot; any cold path that clobbers a bound
slot - delete-while-bound including slot 0, create-over-bound-slot -
detaches the old object into m_boundDetached so GetBoundVertexArray
keeps answering with it) is enforced in MarkVertexArrayForDeletion /
CreateVertexArrayObject rather than assumed, and documented at the
change. Out-of-range binds and null slots keep their exact old
semantics.

VertexArrayObject also gains two opaque config-version-guarded backend
aux memo words, letting a backend answer "same vertex-input layout?"
from the frontend object instead of chasing its own cold cache entry.

After this change the frontend Bind drops out of the DirectVulkan draw
profile entirely (11.5% -> 0.5%). Measured jointly with the two backend
rounds that land on top: quiet-box 6-round order-alternating A/B,
all nine cases, no case worse than noise on either backend. Unit tests
421/421.
2026-08-06 13:16:02 -04:00
BZLZHH d0aae85da2 [Perf] (MG_Backend): let DirectVulkan's draw fast path survive a VAO swap
TrySetupDrawFastPath declined on its VAO pointer check for every draw of
a 512-VAO cycle - the Blaze3D chunk-render shape - so the fast path was
dead exactly where it mattered: full SetupDraw, per-draw
ResolveSamplerDescriptor, SyncTextureAndGetDescriptor and render-pass
re-fetch, for draws whose only change was the VAO.

Three fixes. A moved VAO now re-runs only the vertex-input pre-flight
and re-resolves the pipeline instead of declining to the full path. That
resolution probes the value-keyed pipeline memo directly off a cached
pipeline-state hash and snapshot render-pass hash, skipping
GetOrCreateRenderPass and its GetPendingRenderbufferClear probes per
draw; a stale cached hash can only miss, never false-hit. And when the
sampler-descriptor hint holds and the program's single dynamic UBO
re-resolves to the same VkBuffer and range - only the dynamic offset
moved, the per-draw glUniform case - the descriptor walk collapses to
one offset recompute and a vkCmdBindDescriptorSets of the same recorded
set with new pDynamicOffsets. The rebind memo is invalidated at
BeginFrame, layout destruction and override walks; the program lifetime
id never repeats, and per-frame descriptor sets are never rewritten
within their frame.

mc_vanilla_draw -36.9% (1260 -> 795 ns/op, 4.6x native to 3.4x),
sodium_multidraw -18.0%, state_toggle -14.9%, sampler_churn -7.8%,
use_program -7.7%, ubo_range -7.3%, tex_param -7.3%. All nine cases on
both backends, interleaved A/B; no attributable regression. Unit tests
421/421.
2026-08-06 12:00:31 -04:00
BZLZHH b904658b10 [Perf] (MG_Backend): stop DirectGLES re-resolving the same VAO's buffers and twins every draw
Four per-draw costs, all lookups that re-answer the same question.

SyncNeccessaryBuffers walked all 32 attribute slots cold and ran
EnsureBufferResource per buffer on every draw. The backend VAO twin now
hosts a resolved-draw-buffers memo: the deduped enabled-attribute buffers
and the index buffer resolve once per VAO config version, and each hit
re-validates every entry with IsBufferDrawClean - a shadow probe mirroring
every no-op branch of EnsureBufferResource (resource identity, context
generation, pending ops, change serial) - falling back to the full path
for just the dirty entries. The IBO entry is checked against the live
bound object each draw, so slot-version wrap cannot false-hit.

The registry hash Finds that resolve state objects to their backend twins
ran several times per draw. TwinLookupMemo - a direct-mapped,
Fibonacci-hashed table (4096 VAO / 256 program slots) with weak-ptr owner
equality against address reuse - answers them in one probe; collisions
fall back to the registry. A live entry's twin is never replaced once
set, so owner equality proves the raw pointer.

SyncCurrentVertexAttributeValues' pending-mask memo was a function-static
single entry that missed every draw once the app cycled VAOs; it now
lives on the twin. CurrentXfb()'s per-draw FastSTL map lookup became a
cached pointer invalidated at every map mutation (open addressing moves
values on any insert/erase/clear).

mc_vanilla_draw -12.6% (3.4x native to 3.0x), ubo_range -9.8%,
sampler_churn -7.5%, pass_switch -6.5%, sodium_multidraw -6.0%,
state_toggle -4.6%. All nine cases measured on both backends, interleaved
A/B; no case regressed. Unit tests 421/421.
2026-08-06 12:00:31 -04:00
BZLZHH 4b3fd11462 [Perf] (MG_Backend): key DirectVulkan's pipeline memo on state values, not a version that never repeats
Two per-draw churn costs, one cause each.

A blend toggle switched pipelines through a memo keyed on a monotonic
pipeline-state version - which never repeats, so flipping GL_BLEND off and back
on produced a "new" key both times, forced the full SetupDraw and rebuilt the
whole pipeline payload for a pipeline the cache already held. The memo now keys
on a value hash of the pipeline-relevant fixed-function state, recomputed only
when the state version moved, and the consecutive-draw fast path re-resolves
just the pipeline through it when nothing but render state changed. Blaze3D
brackets every batch with exactly this toggle; mc_state_toggle drops 36%
(6629 -> 4230 ns/op, 4.8x native to 3.7x).

The sampler-churn cost had the same shape as the Espryt side fixed separately:
glBindSampler bumps the frontend texture-bind generation even when it re-binds
the sampler the unit already holds, so the per-draw fast path died every draw.
The fast path now proves each binding's descriptor inputs unchanged - texture
and sampler lifetime ids, parameter and content sums, the sampling-resolution
generation, image epochs and exact layouts - and reuses the binding's cached
VkDescriptorImageInfo instead of re-running the resolve chain.
mc_sampler_churn drops 30% (1597 -> 1125), and the proof machinery pays for
itself on the uniform-range case too (-17%).

mc_tex_param stays where it is on this backend deliberately: profiling shows its
remaining cost is frontend validation with zero backend work, unreachable from
Renderer/.

All nine cases measured on both backends, interleaved A/B, no case worse than
noise. Unit tests 421/421.
2026-08-06 11:21:26 -04:00
BZLZHH 9be5d95440 [Perf] (MG_Backend): give DirectGLES unit bindings an epoch the sampler churn cannot fake
The texture-binding memos added earlier keyed on the frontend texture-bind
generation, and 26.2-style unit switching defeats them: glBindSampler bumps the
generation even when it re-binds the sampler the unit already carries, so a
frame that cycles active units re-ran the full two-pass, eleven-slot alias
resolution and the unbind walks on every draw. mc_sampler_churn sat at 1674
ns/op against the native driver's 239 - the worst multiplier left on this
backend - with about half the time in two virtual calls per binding slot.

The units now carry an epoch: a snapshot of each touched unit's slot objects and
sampler object, compared by weak_ptr OWNERSHIP rather than raw pointer - a held
weak_ptr pins its control block, so a freed-and-recycled object can never
owner-equal its predecessor, which is the ABA hole a pointer key would have and
the reason version keying was rejected (WithTemporarilyBoundNamedTexture bumps
slot versions without touching the bind generation). The
(context id, bind generation, high-water mark) triple gates the snapshot walk to
at most once per draw; the epoch moves only when a binding really changed. Both
per-draw memos key on the epoch plus the sampling-resolution generation, which
carries what the epoch cannot see: a default texture's image appearing, and
every completeness input. Two smaller memos ride along: the per-unit
sampler-registry lookup (owner-keyed, misses never cached - the backend object
may be created later in the same draw), and the pending-vertex-attribute mask,
whose first version scanned all 32 slots and put +10% on the VAO-cycling case
before being restricted to the program's active locations.

ns per op, DriverBench on a GTX 1660 SUPER, isolated A/B, all nine cases on both
backends: mc_sampler_churn 1673 -> 732, mc_use_program 4513 -> 4279,
mc_state_toggle 2365 -> 2247, everything else within noise and nothing worse.
7.0x native to 3.1x on the churn case.

Unit tests 421/421.
2026-08-06 11:20:52 -04:00
BZLZHH d49d79a64b [Perf] (MG_Backend): pool DirectVulkan's upload staging and batch its submits
Every dirty texture bought itself a fresh staging buffer (vmaCreateBuffer +
vmaMapMemory), a fresh command buffer, a fresh fence, and its own vkQueueSubmit.
A perf profile of the sprite-animation case put 41% of the whole run in the
kernel on the resulting ioctl traffic; the reclaim list already avoided waiting
on the fences, so the cost was the allocation and submission machinery itself,
paid per texture per frame.

Staging now comes from a pool of persistently-mapped blocks (1 MiB minimum,
exact-size beyond that, bump-allocated, 32 MiB idle cap), and uploads record
into one shared batch command buffer from a dedicated command pool, going out as
one submit with one pooled fence per flush. Fences, command buffers and blocks
all recycle through the existing fence-list reclaim instead of being destroyed.
Flush points: before every frame command buffer submission (which is what
preserves the old ordering argument - the batch reaches the queue strictly
before anything that could sample its images), on the glFlush finite-time path,
when a batch would outgrow its staging bound, and eagerly at 128 KiB, which
measured faster because the GPU overlaps the copy with the rest of the frame's
CPU recording. The mid-frame upload-draw-upload-again sequence detects itself
through the batch image list and flushes first, reproducing the old two-submit
granularity exactly; a deferred image release flushes any open batch that still
references the image, because drain proofs only cover submitted work.

ns per op, DriverBench on a GTX 1660 SUPER: mc_tex_stream 9405 -> 5373 (2.3x
the native driver, from 3.9x), atlas_sprite -57%, lightmap -89%, chunk_upload
-10%; draw-path cases unchanged. The suite's sampler-churn number reads a few
percent worse right after the now-much-faster upload case, which was chased to
schedutil downclocking during the newly-blocking-free frames - isolated and
frequency-pinned runs measure parity; noted here so the next person does not
re-chase it.

Unit tests 421/421; Vulkan validation layer clean across draw and upload cases.
2026-08-06 10:36:08 -04:00
BZLZHH f5761ea1f3 [Perf] (MG_Backend): diff only the render-state span that moved, and gate the per-draw walks
Four per-draw costs in DirectGLES, all of the same species: work re-done for an
answer that had not changed.

SyncRenderState was guarded by a single version compare, so one blend toggle -
the way Blaze3D brackets every batch - re-diffed the whole ~40-field render
state block and copied the full struct back into the shadow, every draw. The
parameter struct is now split into three contiguous byte spans, each gated by a
memcmp against the backend shadow; a per-draw blend flip touches only the blend
span. The shadow is byte-cloned after each sync so the span compares stay exact,
padding included. Blocks whose inputs live outside the parameter struct (the
surface-size viewport fallback, the sRGB context capability) stay ungated, and
the dual-source-blend hard-fail still fires every draw because a throwing sync
never stamps the shadow.

SyncMipmapsToBackend gained a first-level clean gate on (context id,
sampling-resolution generation, content version, params version) that skips the
IsComplete walk and the eight-field shape probe outright; every shape mutation
funnels through BumpShapeVersion, which is what makes the gate sound.
SyncToBackend for vertex arrays compares one aggregate config version instead of
three stamps per attribute slot. And SyncNeccessaryTextures memoises the
draw-framebuffer attachment list, keyed the same way the framebuffer sync memo
already is, instead of re-walking attachments per draw.

ns per draw, DriverBench on a GTX 1660 SUPER, isolated A/B: mc_state_toggle
3151 -> 2397, mc_ubo_range 792 -> 579, mc_vanilla_draw 1111 -> 881,
mc_sampler_churn 2019 -> 1676, mc_use_program 5132 -> 4356; every one of the
nine cases improved. Against the native driver Espryt now stands at 3.6x on the
plain draw path, 2.8x on the per-draw uniform-range path and 2.1x on the blend
toggle, from 8.7x / 9.1x / 7.2x when this effort began.

Unit tests 421/421.
2026-08-06 10:35:41 -04:00
BZLZHH b3f774d2c0 [Fix] (CI): name the EGL vendor library the benchmark job runs on
The benchmark job is the only one that brings a real GL context up - DriverBench
dlopens libEGL.so.1 and renders through it - but its apt list only asks for
libegl1, which is glvnd's dispatch layer and nothing more. The vendor library
behind it, libegl-mesa0, has been arriving as a Recommends of libegl1 rather
than because anything asked for it. That is too quiet a dependency for the one
job whose whole purpose is running a driver: a base image change, or
--no-install-recommends turning up anywhere upstream, would leave eglInitialize
with no vendor to dispatch to and fail the job for a reason nothing in the
workflow explains. Name it, next to libgl1-mesa-dri, which is listed for
exactly the same reason.

Verified with a full headless ctest -C Release -L benchmark - no $DISPLAY, no
$EGL_PLATFORM, mesa as the only EGL vendor: SanityBench, ProgramBench,
BufferBench and DriverBench all pass.
2026-08-06 09:44:04 -04:00
BZLZHH d524330032 [Test] (MG_Benchmark, MG_Util): model four more Minecraft frame patterns in the driver bench
The captured traces contain per-frame patterns the bench did not exercise, and
first measurements show two of them are now the worst remaining multipliers -
which is exactly what the missing cases were hiding.

mc_pass_switch: the 26.2 snapshot switches render targets 132 times a frame and
re-declares draw buffers 198 times. Render-target churn is where a Vulkan
backend pays for render-pass breaks and where a tiler pays most on device, and
no case measured it. mc_state_toggle: Blaze3D brackets batches with blend
toggles - 46 enable/disable pairs and 28 blend-func changes per vanilla frame.
mc_tex_param: 26.2 re-sets texture parameters 612 times a frame, almost always
to the value already in place, so this measures redundant-parameter filtering.
mc_use_program: Sodium switches programs 62 times a frame with a mat4 upload on
each, roughly one switch per multi-draw.

All four live in the shared case file at the measured per-frame rates, so the
desktop harness, the on-device harness and the POST screen's Run Bench report
comparable numbers. First desktop measurements (ns/op, native / Espryt / Magma):
pass_switch 8877 / 18502 / 13896, state_toggle 1182 / 8526 / 8305,
tex_param 42 / 102 / 197, use_program 2182 / 10648 / 5096. The state-toggle
multiplier - 7x on both backends - is the largest newly exposed gap and the next
optimization target.

Unit tests 421/421; the Android JNI translation unit compiles against the
extended case set.
2026-08-06 09:39:02 -04:00
BZLZHH f2d210b12d [Perf] (MG_Backend): memoise DirectVulkan's per-draw vertex binding resolution
Every draw re-resolved its whole vertex binding array: for each enabled binding,
look up the buffer, acquire a slice from the buffer manager, apply the binding's
base offset, fill the VkBuffer and offset arrays, bind. In the Minecraft-shaped
benchmark the same few hundred vertex array objects cycle for the whole run and
each one's answer is stable, so UploadAndBindVertexBuffers was the single largest
cost in the backend at 7.9% of the render thread, with AcquireResidentSlice
another 3.8% underneath it.

The resolved array is now kept per vertex array object and revalidated instead of
rebuilt. Validation is two-tier. The vertex array's own configuration version
already invalidates its backend vertex-input state, so a changed attribute,
format, buffer or base offset yields a different state object - the memo compares
both that object's address and its hash, which mixes the bound buffers and the
whole layout. What that does not cover is the slice moving underneath an
unchanged configuration, so the buffer manager now carries a monotonic epoch that
every writer of slice-deciding state bumps: resident storage creation, respecify,
sub-data, flush of a mapped range, the promotion and demotion between streamed
and resident storage, each fresh arena allocation, and bulk release. The counter
is manager-wide and never reset, so a resource created at a recycled address
cannot reproduce a value some memo still holds.

The miss path was the thing to get right, because the previous attempt in this
area regressed the texture-upload and sampler-churn cases by 60-85%: it added a
verification pass that re-ran the resolution work it was trying to skip, so every
miss paid for it twice. Here a miss is one pointer-keyed lookup and a few stores,
and nothing else runs that the full path would not have run anyway.

ns per draw, DriverBench on a GTX 1660 SUPER: mc_ubo_range 924 -> 767,
mc_vanilla_draw 1346 -> 1227, mc_sampler_churn 1397 -> 1279,
mc_sodium_multidraw 3365 -> 3266. Magma is now 4.1x the native driver on the
per-draw uniform-range case, from 5.4x when this round started. No case
regressed on either backend.

Unit tests 421/421.
2026-08-06 09:24:08 -04:00
BZLZHH fd40960f70 [Perf] (MG_Backend): revive DirectGLES's dead framebuffer-sync guard, and stop probing twice
SyncCurrentFBO has an early-out that compares three memos, and it could never
fire. One of the three, g_fboBindVersions, was only ever stamped by
ForceBindCurrentFBO - which runs from glBlitFramebuffer and the DSA
glClearNamedFramebuffer* paths and nowhere else. An application that touches
neither leaves that memo at 0 while the binding slot's version is at least 1 from
its first glBindFramebuffer, so the first term mismatched forever and the guard
was dead code rather than merely too coarse. Every draw therefore re-walked all
40-odd attachment slots and rebuilt the 8-slot snorm/unorm clamp mask for a
framebuffer that had not changed since the previous draw.

SyncCurrentFBO now stamps all three memos itself, through one helper, on every
path that leaves the target synced - including the default-framebuffer
"nothing to do" path, which previously returned without stamping anything. The
memo is renamed to say what it now records (a sync, not a bind). Instrumenting a
throwaway build put it at 539998 hits against 2 misses, the misses being the
first bind of each target; it was 0 hits before.

Skipping the sync also skips the Bind() inside it, so all eleven call sites were
checked: every one issues its own bind afterwards (PrepareForDraw and the
glClearBuffer* paths bind Draw, ReadPixels and the CopyTexSubImage paths bind
Read, BlitFramebuffer binds both, GetTexImage uses its own scoped binder). The
global snorm/unorm clamp masks written inside the sync stay correct because they
can only be stale if a different framebuffer was synced as Draw in between, which
moves the pointer or slot version and forces the re-sync that rewrites them.
InvalidateFramebufferBindingCache now also clears these memos: both its callers
mean the ES context may have been reset, and a live early-out must not survive
that.

Two smaller items in the same pass. StateBackendObjectRegistry kept the backend
twin and its liveness weak_ptr in two maps, so every lookup cost two hash probes
and the draw path does ten to twenty of them; they are one map with one entry
type now, one probe. The weak_ptr check itself is load-bearing and stays -
glDeleteVertexArrays followed by glGenVertexArrays recycles heap addresses
readily. And SyncNeccessaryBuffers ran the full EnsureBufferResource check once
per enabled vertex attribute, which on an interleaved Minecraft-shaped VAO means
four to eight times over the same VBO; it is deduplicated per distinct buffer now.

ns per draw, DriverBench on a GTX 1660 SUPER, A/B against a build differing only
by this diff: mc_vanilla_draw 1403 -> 1113, mc_ubo_range 983 -> 797,
mc_sampler_churn 2309 -> 2003, mc_sodium_multidraw 3232 -> 3023. Against the
native driver Espryt is now 4.3x on both the plain draw and the per-draw
uniform-range case, from 8.7x and 9.1x at the start of this work.

Unit tests 421/421. Also replayed all 38 locally-available DirectGLES trace
fixtures against a baseline library: every one produced bit-identical ssim and
mismatched-pixel counts, including the improved-transparency OIT trace whose
scratch clear framebuffer is exactly the draw-buffer hazard the code comments
warn about.
2026-08-06 09:23:47 -04:00
BZLZHH 49aab57f03 [Perf] (MG_Backend, MG_State): stop re-resolving texture unit bindings on every draw
DirectGLES re-derived the whole texture binding state for every draw: for each
touched unit, two alias-resolution passes over all binding slots, then a third
walk to unbind native targets nothing claimed, then the sampler. With the
Minecraft-shaped bench that was 13.2% of the render thread in BindCurrentTextures
alone, plus 4.6% in SyncNeccessaryTextures deciding which textures to consider.
The answer is identical across a whole terrain batch.

The resolution is now memoised, and what makes replaying it as a no-op legitimate
is that the memo does not merely trust a key: it compares the backend's own bound
texture shadow against the one resolution left behind. Every path that binds a
texture behind this function's back already maintains that shadow - the scratch
bind an upload does on the temp unit, CopyTexSubImage2D and GenerateMipmap
binding on the active unit, the glBindTextures fast path, the scrub a backend
texture performs when it is destroyed or respecified - so a memcmp catches all of
them without having to enumerate them. On top of that the key covers the texture
bind generation, the program that arbitrates aliased targets (pointer, lifetime
id, backend state version, link status), and the ES context generation.

Two invalidation sources had no signal at all and needed one. Mipmap completeness
decides whether a texture is bound in the first place, and it moves with texture
shape and with the effective sampler's filter - so a sampling-resolution
generation now moves with both, routed through single choke points
(TextureObjectBase::BumpShapeVersion, SamplerObject::BumpVersion) so a future
bump site cannot forget it. A texture context id was needed because both
generations restart at zero in a new GLContext, which can land on the old heap
address.

This also closes a pre-existing hole rather than working around it:
glDeleteSamplers unbinds the sampler from every unit straight through
TextureUnit::SetSamplerObject, bypassing the touch bookkeeping, so that setter now
bumps the bind generation on a real change. The sampler bind step itself stays
outside the memo and runs every draw - the program's raw-depth-fetch substitution
rewrites unit samplers immediately afterwards, so a memo there could never hit.

ns per draw, DriverBench on a GTX 1660 SUPER (native / Espryt):
mc_vanilla_draw 253 / 2037->1315, mc_ubo_range 202 / 1684->955,
mc_sodium_multidraw 739 / 3939->3150. Espryt goes from 8.3x to 4.7x the native
driver on the per-draw uniform-range case. Magma is unaffected (the MG_State
additions are counter bumps), and no case regressed.

Unit tests 421/421.
2026-08-06 07:41:10 -04:00
BZLZHH 62dea3bea4 [Perf] (MG_State): answer texture sampling completeness from a memo
Every draw asks, for every bound texture, whether it is mipmap-complete for the
filter in use, and the answer was recomputed from scratch each time: walk the
level chain, read each level's texel size, verify each is half the previous.
With the Minecraft-shaped bench that walk plus the GetTexelSize calls under it
measured about 8% of the render thread on both backends.

The answer depends only on the texture's shape - internal format, stored level
set, level sizes, level range - and never on its texel content, which is the
thing that actually changes between draws. A shape version now moves on exactly
those four mutations (SetInternalFormat, SetBaseLevel/SetMaxLevel, and the
AllocateStorage/TruncateMipmapLevels pair on both mipmap storage classes), and
the completeness answer is memoised against it, one slot for the mipmapped
question and one for the plain one. An upload leaves the memo standing, which is
the whole point; anything that could change the answer invalidates it.

ns per draw, DriverBench on a GTX 1660 SUPER (native / Espryt / Magma):
mc_vanilla_draw 257 / 2201->2037 / 1550->1346, mc_ubo_range 203 / 1832->1684 /
1089->934, mc_sampler_churn 272 / 2349->2325 / 1533->1396. Texture-upload cases
are unchanged, as expected - they were never asking this question in a loop.

Unit tests 421/421.
2026-08-06 06:42:43 -04:00
BZLZHH 57aeeec053 [Perf] (MG_State, MG_Impl, MG_Backend): stop paying per draw and per upload for work already known
A per-draw CPU profile of a real Minecraft frame (perf on the render thread,
which sits at 100% of one core on both backends) said the deficit is translation
overhead, not the GPU, and named where it goes. This removes the largest items
it found, on both backends and in the shared frontend they both feed.

The single biggest one was not translation at all: IsBackendContextCurrentOnThisThread
called eglGetCurrentContext on every invocation, and glvnd answers that with a
getpid() fork check - a real syscall. The predicate sits two and three deep in
every draw (the deferred-release drain, the global-UBO ring availability check,
and the ring allocation), so it accounted for 16.3% of the render thread. EGL is
still the ground truth, but re-verifying it once per thread per frame catches an
external migration at the next frame boundary rather than the next call, which
recovers the same bookkeeping.

Texture uploads now carry a dirty region instead of a per-level flag. Minecraft
animates atlas sprites with 16x16 glTexSubImage2D calls into a 1024x512 atlas
and respecifies the lightmap every frame; a per-level flag turned each of those
into a full-level re-upload - about 3.6 MB a frame of texels nobody changed.
MipmapStorage accumulates the written box, Espryt uploads it with
UNPACK_ROW_LENGTH striding into the level shadow, and Magma stages just that box.
The box is a union, not a range list: repeated writes to one level widen it and
it degrades to exactly the old whole-level upload, which is the honest worst case.

glBufferData(NULL) is the orphaning idiom, and the backend was answering it by
uploading the stale CPU shadow - turning a rename the driver does for free into
a full synchronized upload. BufferObject now records that a NULL respecify leaves
the store undefined, and the upload is skipped until content is actually written.

The rest are smaller and of a kind: the deferred-release queue is probed without
taking its mutex, the UBO ring waits on the frame fence that frees the space it
needs instead of draining the whole pipeline with glFinish at the size cap, VAO
binds go through a shadow so a draw's second bind of the same object does not
reach the driver, the per-draw clean-texture probe short-circuits on the content
version before rebuilding shape info, glUniform drops byte-identical writes
(which otherwise dirty the whole UBO for the next draw), re-binding the texture
or VAO a slot already holds no longer bumps the generation counters a backend
fast path is keyed on, and the texture validators stopped taking shared_ptr by
value.

On Magma: descriptor-set reuse keeps four entries instead of one, because draws
alternating between two programs - the chunk/entity ping-pong - thrashed a single
slot into a full re-allocate and re-write every draw; a DynamicDraw buffer whose
contents survive two frame boundaries is promoted to resident storage instead of
being re-copied into the per-frame arena forever; and sampled-read barriers name
only the shader stages whose device feature is enabled, which also removes a
latent VUID violation (ALL_GRAPHICS names geometry and tessellation stages a
device need not have).

Measured with the Minecraft rig (render distance 32, p50 fps, same machine,
single sample each): vanilla 1.21.1 Espryt 10.8 -> 36.3 and Magma 31.3 -> 44.6;
26.2 snapshot Magma 114.5 -> 210.5. Fabric+Sodium moved inside noise on Magma
(854 -> 766) with the native baseline itself moving 838 -> 1031 between the two
sessions, so treat that cell as unresolved rather than a regression measured.
Unit tests 421/421. The CTS A/B was not run: these numbers and the test suite are
the whole of the evidence, and a conformance regression would not have been
caught here.
2026-08-06 06:24:37 -04:00
BZLZHH 9c0144d24a [Test] (MG_Benchmark, MG_Util, MG_Backend, android-plugin): run the driver benchmark on a phone
The Minecraft-shaped driver benchmark could only be run from a desktop shell
against a desktop driver, which is the wrong machine: MobileGL exists to run on
mobile GPUs, and nothing said what its translation costs there. This puts the
same cases on an Android device, both in the plugin's POST screen and from a
shell, and adds the native-driver baseline they have to be read against.

The cases move into DriverBenchCases.inc so both harnesses run byte-identical
bodies - the desktop program resolving entry points from one EGL provider, and
DriverBenchJni.cpp calling MobileGL's frontend in-process. The JNI file binds
every gl*/egl* name to MG_Impl by macro rather than by linkage: this library
legitimately has the platform libEGL and libGLESv3 in its own lookup scope, and
a benchmark that quietly measured the device driver instead of the translation
layer would have looked like very good news.

Frames are now closed with a fence wait instead of glFinish. MobileGL implements
glFinish and glFlush as no-ops, so the old loop timed submit-plus-GPU on a native
driver and submit-only on a MobileGL backend, and the two numbers did not
describe the same work.

To measure a device's own driver the cases needed to be expressible in GLES:
ESSL 3.20 twins of the four shaders (chosen at runtime from GL_VERSION, since
MobileGL is deliberately still fed desktop GLSL - translating it is the thing
under test), a multi-draw hook that loops DrawElementsBaseVertex where the
multi-draw entry point does not exist, and an EGL bootstrap that falls back from
desktop GL to GLES 3. The binary cross-compiles for arm64 unchanged.

BenchService hosts each run in its own process and exits afterwards. That is not
caution: the backend is latched from MOBILEGL_BACKEND_TYPE at initialization, so
Espryt and Magma can never share a process, and Espryt's teardown terminates the
process-default EGL display, which would take the POST activity's own EGL
objects with it.

Running it found that Magma could not create a windowless context on Mali at
all - CreateInstance required VK_EXT_headless_surface, which no mobile driver
here exposes, and aborted the process. The Xlib path already probes and falls
back to a hidden window for the same reason on NVIDIA; Android now probes too
and hands the WSI an AImageReader's ANativeWindow, a real producer surface
attached to no display whose images are never acquired. DriverPost reports the
extension's absence as a WARN so the fallback is visible rather than silent.

Measured on a Mali-G77 MC9 (native / Espryt / Magma, ns per operation):
5495 chunk draws 14397 / 36934 / 33763, the 26.2 per-draw uniform-range pattern
13710 / 31205 / 21252, sodium-style multi-draw 256956 / 238389 / 209527. The
translation costs about 2.4x per draw here against 5-9x on the desktop, because
the mobile driver's own per-call cost dwarfs it - and both backends beat the
native driver on multi-draw, which it has to emulate.

Desktop unit tests 421/421; the POST screen and both Run Bench buttons verified
on the device.
2026-08-06 06:13:34 -04:00
BZLZHH 1e45958e01 [Test] (MG_Benchmark): measure the driver work a real Minecraft frame asks for
The benchmark tree had nothing that exercised a driver: SanityBench times
std::vector, and the Buffer/Program benches call into MobileGL_s directly, so
neither can say what a backend costs against the native driver. This adds a
headless EGL client that can, and shapes its cases from measured traces rather
than guesses.

DriverBench dlopens exactly one EGL provider - the system libEGL.so.1, or a
libMobileGL.so with MOBILEGL_BACKEND_TYPE selecting Espryt or Magma - so the
same binary measures all three stacks with no LD_LIBRARY_PATH shadowing, which
matters because MobileGL's own loader has to keep finding the real driver
underneath. It renders into its own renderbuffer FBO on a 64x64 pbuffer and
paces frames with glFinish, so it needs no window and no compositor.

The six mc_* cases replay the per-frame call mix of 30-second render-distance-32
captures of three Minecraft versions, at the rates those captures measured:
vanilla 1.21.1 issues 5495 glDrawElements per frame, each preceded by its own
glBindVertexArray and glUniform3fv; Fabric+Sodium collapses the same scene into
132 glMultiDrawElementsBaseVertex; the 26.2 snapshot issues 3401
glDrawElementsBaseVertex, each preceded by glBindBufferRange + glBindBuffer.
The texture case wraps every 16x16 atlas upload in the four glPixelStorei and
two glTexParameteri calls Blaze3D re-sets around it, because that wrapper is a
large part of what an upload costs a translation layer. One bench frame
therefore costs what one real frame of that version costs, and ns_per_op is
directly comparable across renderers.

run_driver_bench.sh pins __EGL_VENDOR_LIBRARY_FILENAMES and VK_ICD_FILENAMES.
Without that, eglGetDisplay(EGL_DEFAULT_DISPLAY) on this glvnd system resolves
to Mesa llvmpipe and the "native" numbers silently describe a software
rasteriser - the first run of this bench reported 11 us per draw before the
pin, versus 250 ns on the real GPU.

Verified against the NVIDIA 610.43.03 driver, Espryt and Magma on a GTX 1660
SUPER; the CMake target builds and runs from a clean configure.
2026-08-06 03:57:52 -04:00
BZLZHH 6e6f5268fb [Fix] (MG_Backend): let a default-visual X11 window match an alpha-free config
ChooseConfigForSurface prefilters candidate configs with eglChooseConfig
requiring EGL_ALPHA_SIZE 8, then tries to match the window's X visual. On
NVIDIA's X11 EGL every alpha-8 config lives on the 32-bit ARGB visual, and the
default depth-24 TrueColor visual only appears on alpha-0 configs - so for any
window created with the default visual the match loop scanned a list that
could not contain its visual, fell through to a 32-bit-visual config, and
eglCreateWindowSurface failed with EGL_BAD_CONFIG.

Keep the alpha-8 list as the first tier and add an alpha-relaxed second tier
used only for the visual match; the sizeless fallbacks below still run on the
alpha-8 list. Mesa is unaffected (its default-visual configs carry alpha), and
a destination-alpha-free default framebuffer is exactly what native GLX hands
out on these visuals anyway.

Found by running Minecraft through the new GLXImpl on Espryt: NVIDIA EGL also
needs EGL_PLATFORM=x11 under a Wayland session or eglGetDisplay itself returns
no display, which is a launcher-environment concern, not a library one.
2026-08-05 23:12:12 -04:00
BZLZHH 08f98ad9ce [Feat] (MG_Impl): implement GLX 1.4 on the EGL layer so GLFW apps run on Linux
Desktop Linux GL apps (GLFW/LWJGL, glxgears, anything X11) create contexts
through GLX, and MobileGL only spoke EGL - the two exported glX symbols were
proc-address stubs that could resolve GL entry points but never produce a
context. GLXImpl is the missing sibling of WGLImpl/CGLImpl: the same
window-system-binding pattern, calling the internal MG_Impl::EGLImpl namespace
directly.

The surface covers exactly what GLFW 3.4 resolves via dlsym plus the legacy
visual API: FBConfig enumeration mirrors the two EGLState configs (stencil-8
first so stencil-wanting choosers land on it), glXGetVisualFromFBConfig answers
with the screen's default visual (falling back to any 24-bit TrueColor one),
and glXCreateContextAttribsARB maps the ARB attribs onto EGL context attribs
the way WGL's Ext_CreateContextAttribsARB does - profile mask only emitted for
3.2+ or an explicit profile request, since that bit is what keys MobileGL's
relaxed-semantics compatibility mode. Legacy glXCreateContext/CreateNewContext
hand out 3.3 compatibility contexts, matching wglCreateContext.

Drawables follow the WGL HWND model: the GLXWindow is the X window itself, the
EGL window surface is created lazily on first MakeCurrent and cached per XID,
and the GLX layer owns size discovery per the platform-layer contract - it
pushes changes through EGLImpl::ResizePlatformWindowSurface, polling
XGetGeometry on MakeCurrent and on swaps throttled to 250ms so a fast-swapping
app is not paying a server round trip per frame. libX11 is dlopen'd at runtime
like everywhere else in the tree; Xlib.h is already in every TU via the vulkan
include, so XVisualInfo gets an ABI mirror struct (Xutil.h needs the Bool and
Status macros that Includes.h deliberately pops) and the caller's XFree pairs
with our malloc.

glXGetProcAddress now resolves glX names from the export table before falling
through to the shared GL resolver, which previously returned nullptr for every
glX extension entry point - GLFW requires glXCreateContextAttribsARB and
glXSwapIntervalEXT to arrive that way.

Verified with a smoke test replaying GLFW's exact call sequence (dlsym-only
resolution, manual FBConfig filtering, 3.2 core forward-compatible context,
glXCreateWindow, 60 swapped frames, clean glGetError) on both backends against
the real NVIDIA driver, then with Minecraft 1.21.1, 1.21.4+Fabric+Sodium and
26.2-snapshot-6 reaching in-world rendering on both Espryt and Magma.
2026-08-05 23:08:29 -04:00
BZLZHH d39a706d57 [Perf] (MG_Backend): stop paying for descriptor slots and mip barriers nobody asked for
Five independent bits of per-draw and per-operation waste in the DirectVulkan
backend, all removing work whose answer was already known.

The per-draw descriptor walk iterated all 256 slots of bindingKinds to find the
one to eight bindings a real GL program declares, because that vector is sized to
the binding cap rather than to the program. Reflection now records the bindings it
actually assigned, and the draw path iterates that. It is built at the end of
ReflectLayout, not where bindingKinds is sized - at that point the vector is only
zero-initialised and the kinds are assigned further down, so a list built there
would be empty. It has to stay ascending: Vulkan consumes pDynamicOffsets in
binding order and the writer pushes them in iteration order, so an unordered list
would silently mis-pair dynamic offsets with their uniform blocks.

Descriptor pools were sized maxSets * the 256-binding cap, declaring 81,920
descriptors per pool and 245,760 across the frames in flight, for sets that hold
what shader reflection found. Sized from eight now; an outlier program is absorbed
by the VK_ERROR_OUT_OF_POOL_MEMORY path that already exists, which works because
pool sizes are aggregate budgets rather than per-set limits.

TrackLiveResource swept the whole live-buffer vector on every insert once it
passed 256 entries, and when the buffers are all live the sweep removes nothing
and the vector grows by one - so creating N live buffers cost about N^2/2
expired() checks. It sweeps on a doubling watermark now, with the same
reclamation semantics.

GenerateMipmap transitioned each destination level individually inside its loop,
but every generated level starts in the same layout and the loop only moves a
level out of TRANSFER_DST after writing it, so the whole range can be prepared in
one barrier - 3(N-1)+1 barrier commands become 2(N-1)+2. Each level is still
transitioned to TRANSFER_SRC before it is read, so the dependency between
consecutive levels is unchanged.

WaitForFrameSerial drained the entire graphics queue, as its own comment admitted.
Every submission records the frame serial it was made under, so it now waits on
the first fence at or past the requested serial. The narrow path deliberately does
not call NotifyDeviceIdle(): that claims every submission has retired, which is
only true after a real drain, so it stays on the fallback.

Verified with an 8213-case A/B (textures, buffers, queries, mipmaps, uniforms and
the whole direct_state_access suite): the Espryt failure list is identical, the
Magma failure list differs by one case, and both crash sets are unchanged on
Magma. That one case, buffer_storage.map_persistent_draw, does not reproduce in
isolation - running the buffer_storage group alone gives byte-identical results on
both builds (the same three failures, not including it), and it reports
NotSupported when run on its own. It is the same ordering-dependent behaviour this
suite shows elsewhere, and the three Espryt crash-set differences are the known
copy_image cluster moving chunk position. Flagging rather than hiding it.

direct_state_access stays at Espryt 370/371 and Magma 371/371; unit tests 421/421.
2026-08-05 15:19:37 -04:00
BZLZHH f3d52faad4 [Perf] (MG_State, MG_Backend): stop glViewport from evicting a cached VkPipeline
RenderState kept one version counter for all render state, and DirectVulkan read
it in three places: the pipeline memo key, the SetupDrawSnapshot fast-path guard,
and that guard's store. So glViewport, glScissor, glBlendColor, glStencilMask,
glClearColor, glPolygonOffset, glLineWidth and the point-size family - none of
which can alter a VkPipeline, all of which an application changes between draws -
knocked the next draw off both fast paths and made it rebuild a pipeline lookup
that was already correct.

The counter is now split. m_version still moves on every state change, because
the draw snapshot really does depend on all of it. m_pipelineStateVersion moves
only for the state a backend bakes into a pipeline object, and it is what the
three DirectVulkan sites read.

The exclusion list is the eight VkDynamicState entries PipelineFactory declares
plus the state that is not pipeline state at all (the clear values, hints, the
point-size family, clamp read colour, the primitive restart index). glStencilFunc
is the one setter that had to be split rather than classified: Func is in the
pipeline payload but Ref and ValueMask are dynamic state, so it bumps the
pipeline version only when Func actually changes.

Capabilities are deliberately NOT in the exclusion list even though several look
like dynamic state: GL_FRAMEBUFFER_SRGB feeds the render-pass hash, depth and
stencil test feed drawUsesDepthStencil, and scissor test, blend, cull face,
polygon offset fill, primitive restart, colour logic op and rasterizer discard
all feed the pipeline payload.

Two smaller draw-path wins ride along, both removing work whose answer was
already in hand. UploadAndBindVertexStreams searched all 32 VAO attribute slots
for the SharedPtr matching a binding's buffer key, once per binding per draw -
but VertexInputStateFactory writes bindingBufferKeys[b] and
bindingAttributeLocations[b] from the same loop iteration, one binding per
attribute with no merging, so the attribute at that location IS the buffer, by
construction. UploadAndBindIndexBuffer round-tripped the element-array buffer's
raw pointer back through the GL name table on every indexed draw, costing a map
lookup and an atomic refcount pair, when the binding slot's SharedPtr was already
in scope forty lines above - where a comment says exactly that about the vertex
path.

Behaviour-neutral by construction and verified as such: a 13355-case subset of
GL30-GL45 covering viewport, scissor, blend, stencil, depth, polygon offset,
clear, multisample, cull, logic op, line width and point state, plus the whole
direct_state_access suite, is identical before and after on both backends - in
the failure list and in the crashed-case set. direct_state_access stays at
Espryt 370/371 and Magma 371/371.
2026-08-05 12:49:54 -04:00
BZLZHH ba81ee114e [Feat] (MG_Backend, MG_Impl, MG_Util): attach one layer of any layered texture on DirectVulkan
Whether a backend can attach a single layer of a texture to a framebuffer was one
Bool, so it could only give the most conservative answer any target needed.
DirectVulkan therefore declined every layer of every target and
direct_state_access.framebuffers_texture_layer_attachment failed with 542
messages across four targets.

The three ways a GL layer maps onto Vulkan are independent capabilities, so the
flag becomes a per-TextureTarget mask. A 2D or 2D multisample array layer IS a
VkImage array layer and needed nothing but the gate opened. A cube map array is
one 2D image with arrayLayers = 6 * cubeCount and CUBE_COMPATIBLE, which is a
shape VkTextureManager simply did not have - it is declined softly when the depth
is not a whole number of cubes or the level is not square, because that function's
Bool return exists for unrepresentable shapes and asserting there would abort on
ordinary input, GL_PROXY_TEXTURE_CUBE_MAP_ARRAY above all. A 3D texture's layer is
a z slice, which needs a 2D-array-compatible image and a per-slice clear, because
vkCmdClearColorImage cannot address a subset of a 3D image's slices - a render
pass whose only content is its LOAD_OP_CLEAR can, since its attachment is a 2D
view over that one slice.

VK_IMAGE_CREATE_2D_ARRAY_COMPATIBLE_BIT is asked for per format and withdrawn per
format, mirroring the MUTABLE_FORMAT pattern already in this file: the capability
is per format+usage, so a single global probe answers a different question than
the one the frontend goes on to ask. Losing it costs per-slice attachment for that
format; failing creation would lose the texture.

Three things found on the way that are not the headline:

glFramebufferTextureLayer, the non-DSA twin, had no gate at all and additionally
refused cube map arrays that GL 4.5 requires it to accept. GL 4.6 core 9.2.8 makes
the two entry points equivalent, so they now decline in the same places - leaving
one ungated is what let an unrepresentable attachment reach the renderer.

ComputeFullMipLevelCount takes max(x, y, z), and for every array shape z is the
layer count rather than a mip-able axis, so a 4x4 array with 192 layers asked for
six mip levels on an image whose legal maximum is three
(VUID-VkImageCreateInfo-mipLevels-00958). Only the image's own extent can bound
it. lavapipe had been letting that through.

A layered GL clear queues layerCount = depth, which is illegal for a
VK_IMAGE_TYPE_3D image (VUID-vkCmdClearColorImage-baseArrayLayer-01472 pins it to
0/1, read as the whole mip level) and the old code passed it straight through.

Takes framebuffers_texture_layer_attachment green on DirectVulkan, so the whole
direct_state_access suite is 371/371 there; Espryt stays 370/371, the remaining
case being the fp64 one it declines by design.

Known and deliberately not fixed here, with a FIXME at the site:
KHR-GL44/45/46.geometry_shader.layered_framebuffer.clear_call_support now fails on
DirectVulkan - a layered clear of a 3D texture reads back zeros. Those cases exist
only in the GL44+ lists, above the 4.0 this backend reports. An A/B of a 6935-case
subset (cube map array, texture storage, framebuffer, 3D, the full DSA suite and
the GL33 texture group) is otherwise clean on both backends: 16 cases fixed and
none broken on Espryt, 15 fixed and those 2 broken on Magma, and zero difference
anywhere at GL 4.0 or below. The FIXME records which causes were already ruled out
by bisection so the next reader does not repeat them.
2026-08-05 12:07:04 -04:00
BZLZHH c8c7b19579 [Feat] (MG_Backend, MG_Util): give DirectVulkan GL's provoking vertex
Vulkan's built-in convention is "provoking vertex first"; GL's default is
LAST_VERTEX_CONVENTION, and GL derives both flat shading and the transform
feedback vertex order from it. DirectVulkan had no way to say so, which is why
direct_state_access.queries_functional failed on a value with nothing in its log
- the primitives came back counted against a strip recorded in the wrong vertex
order.

VK_EXT_provoking_vertex is now enabled when present, and the mode is a hashed
field of the pipeline payload rather than dynamic state, because it is baked into
VkPipelineRasterizationStateCreateInfo: two draws differing only in it must not
collide on one cached VkPipeline, or whichever mode built first would stick for
the rest of the frame. The pNext is chained only when the mode is not Vulkan's
default, so a device without the extension produces a byte-identical
VkGraphicsPipelineCreateInfo to before.

Two carve-outs, both measured rather than reasoned:

A geometry shader already emits its triangles in GL's vertex order, so asking for
LAST rotates them a second time and transform_feedback.geometry reads back the
wrong vertices. The mode is one pipeline bit and the input-assembler path wants
the opposite, so the two cannot both be satisfied: a program that runs a geometry
shader and captures transform feedback keeps Vulkan's own convention. That test
is read off the program's own shader list, not
programObj.rasterizationProducerStage - the latter is filled by the clip-fixup
analysis, which does not run for every program and reads Unknown for exactly the
programs this guard exists to catch. Both halves are link-time facts folded into
programObj.hash, so no pipeline memo can hand back one built for the other mode;
keying on IsTransformFeedbackActive() instead would be a live bug, since neither
memo key moves on glBeginTransformFeedback.

transformFeedbackPreservesProvokingVertex is deliberately not requested. It buys
nothing here - the capture order queries_functional needs comes from
provokingVertexLast alone - and leaving it off keeps
VUID-VkGraphicsPipelineCreateInfo-topology-04884 disarmed, so a TRIANGLE_FAN
pipeline may take LAST on any device.

The blit pipeline routes through the same selector: it has no flat varying and no
capture, but on a device without provokingVertexModePerPipeline a blit left on
FIRST inside a render pass whose draws are LAST is an illegal mix.

Per the POST rule the new extension gets rows for provokingVertexLast and for the
two properties that change what MobileGL can promise.

Fixes queries_functional on Magma (370/371). An A/B over a 976-case transform
feedback / geometry shader / layered rendering subset of GL30-GL45 is otherwise
identical on both backends and additionally takes 14 geometry_shader rendering
and layered_rendering cases from failing to passing on Magma.
2026-08-05 10:04:30 -04:00
BZLZHH 0e7692251d [Feat] (MG_State, MG_Impl, MG_Util): store a compressed texture image and hand it back
glCompressedTexImage2D rejected every internalformat with GL_INVALID_ENUM, so
direct_state_access.textures_get_image threw at its first compressed call and
reported InternalError with nothing in the log at all - the uncompressed half of
the case had already passed.

The compressed bytes are now kept verbatim, in a side-channel beside the texel
shadow rather than in place of it. That placement is the load-bearing decision:
both backends pair MapMipmapData with GetMipmapByteSize while sizing their copy
regions from GetMipmapTexelSize, and DirectGLES additionally divides the byte
size by the texel count to recover bytes-per-texel, so putting 16 bytes where a
4x4 RGBA8 extent says 64 would be an out-of-bounds read on both. The texel
storage therefore stays uncompressed and correctly sized - the image samples as
zeros, which is the same deviation the RGTC/BPTC/ETC2 arms of
ConvertGLEnumToTextureInternalFormat already document - while
glGetCompressedTexImage returns the image *as stored*, which GL 4.6 core 8.11
requires and which no re-encode could satisfy byte for byte. Nothing ever hands
the compressed bytes to GLES or Vulkan, so the shadow is authoritative rather
than potentially stale, which is why the readback never asks a backend.

The accepted set is exactly the RGTC/BPTC/ETC2-EAC formats core GL requires, and
it is deliberately the same set ConvertGLEnumToTextureInternalFormat can back
with uncompressed storage, so the upload can never accept a format whose texel
shadow it cannot allocate. imageSize is checked against the block arithmetic,
which is also what keeps the copy in bounds.

Three things the shape depends on. AllocateStorage clears the compressed tag, so
a glTexImage2D or glTexStorage2D over the level un-compresses it - without that,
textures_compressed_subimage would flip branches and start asking for data
MobileGL cannot produce. GL_TEXTURE_COMPRESSED and
GL_TEXTURE_COMPRESSED_IMAGE_SIZE are answered per level rather than per texture,
because a compressed internalformat handed to glTexImage2D resolves to
uncompressed storage and must keep reading as uncompressed. And
GL_TEXTURE_INTERNAL_FORMAT now reports the compressed token for such a level, or
it would claim GL_RGBA8 while GL_TEXTURE_COMPRESSED said true.

Still rejected on purpose: glCompressedTexImage1D/3D and every
glCompressedTexSubImage*, which caps the blast radius.

Fixes textures_get_image on both backends (Espryt 370/371, Magma 369/371). A/B
over a 1210-case compressed/texture-storage/texture-view/buffer-storage subset of
KHR-GL45 is identical before and after on both backends but for
get_texture_sub_image.errors_test, which stops throwing and fails on a value
instead.
2026-08-05 09:40:29 -04:00
BZLZHH 34f09291da [Feat] (MG_State, MG_Backend, MG_Util): feed a 64-bit vertex attribute on DirectVulkan
glVertexAttribLFormat validated its arguments and then refused unconditionally
with "64-bit vertex attributes are not supported", so
direct_state_access.vertex_arrays_attribute_format failed every GL_DOUBLE
subcase on both backends - the format never landed, the draw fetched whatever
the attribute held before, and the captured values came back as reinterpreted
garbage.

The attribute is now real state. IsLong is its own bit rather than being
inferred from Float64, because glVertexAttribFormat(GL_DOUBLE) also reads
doubles - it just asks for them converted to float - so the type alone cannot
tell the two apart. It participates in the format comparison, so an L-format
call over a plain one still bumps the version, and glVertexAttribPointer clears
it inside the mutation block so the clear and the bump stay atomic.
GL_VERTEX_ATTRIB_ARRAY_LONG stops being hardcoded false, and the pname is now
accepted by the attribute queries at all.

Support is detected, never assumed. SupportsFloat64VertexAttributes comes from
VkPhysicalDeviceFeatures::shaderFloat64 on DirectVulkan and is false on
DirectGLES - not a driver question there and never will be, since ES has no
GL_DOUBLE vertex format and ESSL has no fp64 type to consume one with. A backend
without it declines in the entry point, with the GL error and a log line naming
the reason, rather than accepting state no draw could honour. Both cases get a
DriverPost row so the loss is named at startup instead of at draw setup.

On DirectVulkan the attribute deliberately does not use VK_FORMAT_R64*_SFLOAT:
those are optional and lavapipe advertises zero features for all four of them.
It is fetched as its 32-bit word pair (R32G32_UINT / R32G32B32A32_UINT) and
bitcast back to double in the shader by a new SPIR-V pass, which is bit-exact
and needs no format capability at all. The pass re-declares the input as uvec2 /
uvec4, demotes the original variable to a Private global and seeds it once at
the top of the entry point, so every existing load keeps its id and its double
type and no other instruction is rewritten. Both halves branch on nothing but
"is this attribute long", so they cannot disagree - and if the pass ever fails,
the assertion fires rather than letting a UINT format sit under a double input.
The pointer types are all created before any variable that names them and the
demoted variable is moved after them, since the types-and-variables section may
not forward-reference a type.

dvec3/dvec4 are declined rather than fetched wrong: six or eight uint32
components have no single VkFormat, and GL spreads such an input over two
attribute locations, which the location-per-index model here does not express.

Fixes vertex_arrays_attribute_format on Magma (369/371). On Espryt it stays
failing, now as a detected and explained decline rather than a blanket refusal.
2026-08-05 08:49:23 -04:00
BZLZHH 3b65e646e1 [Fix] (MG_Backend): give every colour attachment its own backend slot on DirectGLES
ES only accepts glDrawBuffers bufs[s] == GL_COLOR_ATTACHMENTs, so a desktop
glDrawBuffer(GL_COLOR_ATTACHMENT3) cannot be expressed directly and DirectGLES
compacts: it physically relocates the draw buffer's image onto backend point 0 so
ES's output-0-to-attachment-0 rule lands on the right image. The clears were
therefore always correct. The read side was not.

GetBackendAttachmentType derived the attachment-to-point map by searching the
draw-buffer array and falling back to the identity point for anything it did not
find. That derivation is not injective against the compaction: after clearing
attachments 0..7 one at a time, every one of them has been relocated onto point 0
in turn, so a later glReadBuffer(GL_COLOR_ATTACHMENT0) - not a draw buffer any
more - takes the identity fallback to point 0 and reads attachment 7's image.
Hence the single mismatch, 0.875 where 0 was expected: 7/8 is attachment 7's clear
colour.

The map is now stored state rather than a re-derivation, and kept a permutation:
a draw buffer takes the point ES forces on it, everything else keeps its identity
point when that point survived, and an attachment evicted from its identity point
is parked on the lowest free one so it stays addressable for glReadBuffer and
blits. With identity draw buffers nothing moves and not one extra GL call is
issued, which is what keeps ordinary rendering untouched.

Two things the permutation depends on. The attachment loop now detaches a colour
point whose frontend owner is empty - SyncAttachmentObject only ever attaches, so
without this a point handed to an empty attachment would still hold the previous
owner's image and hand it back. And QueryReadColorAttachmentInternalFormat asked
GL_COLOR_ATTACHMENT0 for the format it sizes the multisample-resolve scratch
renderbuffer from; it now asks the point the read buffer actually names, since
that is only CA0 when the map happens to be identity.

Fixes framebuffers_read_draw_buffer on Espryt. A 5677-case readback and
framebuffer subset of GL30-33 stays at zero failures on both backends.
2026-08-05 08:24:01 -04:00
BZLZHH 25b9370815 [Fix] (MG_Backend): stop a renderbuffer blit reading a freed image layout
VkRenderPassManager kept m_renderbufferResources on FastSTL's open-addressing
UnorderedMap while BlitFramebuffer caches a raw pointer into one of its elements -
ResolveColorBlitBinding stores &rbResource->layout - and then calls
MaterializePendingClearForRenderbuffer, which looks that same resource up again.
FastSTL's operator[] runs its load-factor check before find_key and reallocates
the whole bucket array when occupancy crosses it, so even a plain lookup relocates
every element; erase only tombstones and never lowers the occupancy, so the
doubling keeps firing. After a relocation the cached pointer names freed storage
still holding the pre-clear VK_IMAGE_LAYOUT_UNDEFINED, BlitFramebuffer takes its
"source image layout is undefined" early return, and the blit is silently dropped
- glReadPixels then returns the zero-filled fresh allocation.

That is why the failures looked arbitrary: which iteration breaks is pure
arithmetic on the table's occupancy, and the observed set (GL_R8 at k=0,1,3,7,
GL_R16 at k=6, GL_RG16 at k=4) is exactly the doubling ladder. Padding the map
with unrelated live renderbuffers moves the failures to the positions the model
predicts and every previously failing format then passes, so nothing else hides
behind it.

Reordering the materialize ahead of the resolves - the fix ReadPixels got, see the
note at its call site - does not cover this, because BlitFramebuffer resolves two
bindings and the second resolve still runs after the first pointer is taken. The
depth blit, GetOrCreateRenderPass's depthRenderbufferResource and
ReadDepthStencilPixels cache the same kind of pointer, so the invariant belongs in
the container rather than in a per-call-site ordering rule. m_textureResources was
already node-based for exactly this reason; this is the map that was left behind.

Fixes renderbuffers_storage_multisample on DirectVulkan.
2026-08-05 08:24:01 -04:00
BZLZHH 4ce808b9f2 [Feat] (MG_State, MG_Impl, MG_Backend): let a bound program pipeline actually draw
The pipeline object bookkeeping landed already - names, stage slots, queries -
but nothing consumed it. Every draw asked the context for the current program,
got null because a pipeline is used with program zero, and drew nothing;
glCreateShaderProgramv was still a stub returning zero, so
direct_state_access.program_pipelines_functional could not even build its stage
programs and reported InternalError on both backends.

glCreateShaderProgramv is written as the exact call sequence the spec defines it
to be, with one deviation that matters: the link goes straight to
ProgramObject::Link(false) rather than through LinkProgram, because LinkProgram
injects a default fragment shader into a program that has none - correct for a
whole program, wrong for a separable vertex-stage one whose fragment stage comes
from the pipeline. glDetachShader defers removal to the next link, so the program
keeps the shader object it was built from while correctly no longer reporting it
attached. GL_PROGRAM_SEPARABLE joins glProgramParameteri and glGetProgramiv.

Everything downstream of a draw - both backends, the uniform plumbing, the draw
validation - is written against one linked program, so rather than teach all of
it about stages, the pipeline is flattened: GetProgramForDraw() composites the
stage programs' shaders into a single hidden program object and caches it against
a signature of each stage program's lifetime id and link generation, so it is
rebuilt exactly when a stage or a stage's link changes. The composite carries no
GL name - it must not answer glIsProgram, and it must not consume a name the
application could be handed.

Uniform entry points get their own resolver rather than sharing that one:
glUniform* addresses the pipeline's active program, not the composited draw
program. GL_CURRENT_PROGRAM still reads the program in use, which is zero here.

Fixes program_pipelines_functional on both backends.
2026-08-05 07:20:42 -04:00
BZLZHH 5545d31c37 [Feat] (MG_Backend, MG_Util): give a cube map array real storage on DirectGLES
TextureCubeMapArray was missing from every storage and upload switch in the
DirectGLES texture sync, so a cube map array reached the driver with no storage
at all - and from the glFramebufferTextureLayer branch, so attaching one of its
layers fell through to glFramebufferTexture2D and raised INVALID_ENUM. Every
GL_TEXTURE_CUBE_MAP_ARRAY colour check in
direct_state_access.framebuffers_texture_layer_attachment read nothing.

ES 3.2 has GL_TEXTURE_CUBE_MAP_ARRAY natively and it stores exactly like a 2D
array whose depth is six times the cube count, so each switch gains the case
beside Texture2DArray and nothing else changes. 1D arrays join the layer branch
for the same reason - their backend image is a 2D array.

Per the POST rule the new GLES dependency gets a capability
(SupportsTextureCubeMapArray, ES 3.2 core or EXT/OES_texture_cube_map_array) and
a DriverPost row saying what a user loses without it.

Takes framebuffers_texture_layer_attachment from failing to passing on Espryt. It
still fails on DirectVulkan, which declines a layered attachment outright.
2026-08-05 06:58:00 -04:00
BZLZHH 588ddba722 [Fix] (MG_Backend): scale a depth blit, keep going after one declines, and mip a 1D texture
Three DirectVulkan gaps found together.

glBlitFramebuffer's depth/stencil path refused any blit whose source and
destination extents differ, because vkCmdCopyImage cannot resize. vkCmdBlitImage
can, and VK_FILTER_NEAREST is the only filter Vulkan allows for depth/stencil
anyway - which is what the GL front end already requires. A same-size pair keeps
the cheaper copy.

Worse, that refusal and four others were `return`, not `continue`, so a
depth/stencil aspect this backend could not handle abandoned the whole function -
including the colour blit that only starts after the aspect loop. The CTS's
scaling blits therefore lost their colour as well, which is why
direct_state_access.framebuffers_blit failed all three of its checks rather than
one.

VulkanRenderer::GenerateMipmap declined GL_TEXTURE_1D. It needed nothing else:
the blit loop derives every offset from the storage extent, and a 1D texture's is
{width, 1, 1}, which is exactly the y and z offsets a 1D image requires.

Also: IsTimerQueryResultReady now asks the query pool before the frame serial.
The pool polls with VK_QUERY_RESULT_WITH_AVAILABILITY_BIT and is the authority;
the frame serial only advances at Present and neither completion notifier will
mark the current serial done, so a timestamp written and fence-waited inside one
GL frame could never be read back within it.

Takes framebuffers_blit and textures_generate_mipmaps from failing to passing on
DirectVulkan. queries_functional still fails there on a value.
2026-08-05 06:50:13 -04:00
BZLZHH 62301b1061 [Fix] (MG_State): let a double-typed varying be captured by transform feedback
ResolveXfbSymbolType accepted only float, int and uint, and its caller reports
anything it rejects as "Transform feedback varying 'x' is not an output of the
vertex stage" - which is a misleading thing to say about a varying that is right
there in the shader, just declared `double`. Program linkage failed outright.

Doubles are now resolved to the GL_DOUBLE* types, in vector and matrix form, and
the per-element size is computed from an 8-byte component rather than a hardcoded
4 (GL 4.6 core 11.1.2.1), so the byte-based limit checks charge a double what GL
says it costs.

direct_state_access.vertex_arrays_attribute_format stops throwing on both
backends and fails on the captured values instead: the capture layout still owes
the 8-byte alignment doubles require, and neither backend feeds a 64-bit vertex
attribute yet - DirectGLES cannot at all, ESSL having no double.
2026-08-05 06:43:41 -04:00
BZLZHH f3a846d336 [Docs] (README): carry the 4.2 short-term target into the status note
The compatibility section already said 4.2; the status note at the top of the
README still said 3.3, so the two disagreed depending on how far a reader got.
2026-08-05 06:10:37 -04:00
BZLZHH 9cdc82fbdd [Fix] (MG_Backend): actually bind the sampler object DirectGLES just synced
BindCurrentTextures' program-driven path synced a bound sampler object's
parameters to its backend object and then never put it on the texture unit, so
every sampler object was inert and the driver kept sampling with the texture's
own parameters - direct_state_access.samplers_functional read black where the
sampler's NEAREST filtering should have given red.

The bind alone is a regression, and the CTS says so loudly: a sampler left on a
unit by an earlier draw keeps being applied, and a multisample texture takes no
sampler object at all, so the next draw against one is rejected and all 27
textures_storage_multisample_3d_* cases fail. The sibling path in the same
function had an empty else branch where the unbind belonged; it now unbinds,
making the two symmetric.

Takes samplers_functional from failing to passing on Espryt, with no other case
moving in either direction.
2026-08-05 06:08:59 -04:00
BZLZHH 4a9d20c49f [Fix] (MG_Backend): resolve a framebuffer attachment's layer in the Vulkan blit bindings
ResolveAttachmentBaseArrayLayer answered zero for everything but a cube map face,
so every blit, copy and glReadPixels against a layered attachment read layer zero
whatever was attached. It reads the attachment's layer now.

A 3D texture needs the other half of the distinction: its image has arrayLayers
== 1 and the GL layer is a z slice, which VkBufferImageCopy will not take as a
base array layer. BlitImageBinding carries it separately as depthOffset, and the
readback copy region uses it as the image offset's z.

Takes textures_copy from failing to passing on DirectVulkan, which is what
glCopyTextureSubImage3D needs to see the slice the CTS attached rather than
slice zero.
2026-08-05 05:56:09 -04:00
BZLZHH 394d1ce748 [Feat] (MG_Impl, MG_Util): copy into 1D and 3D textures, and accept the BPTC and ETC2 enums
Two unrelated texture gaps.

glCopyTextureSubImage1D and 3D validated their arguments and then did nothing:
CopyTexSubImage1D_State and CopyTexSubImage3D_State were empty TODOs and no
backend exposes anything but a 2D blit. But a texture's contents live in its CPU
storage - the backends sync from it - so the copy does not need a blit at all.
CopyReadFramebufferIntoMipmapRegion reads the region out of the read framebuffer
through the existing ReadPixels path, in the destination's own canonical client
layout so the bytes need no second conversion, and writes them straight into the
level. GL 4.6 core 8.6 says the copy ignores pixel-store state and any bound pack
buffer, which the borrowed readback does not, so both are neutralised for the
duration and restored after. A cube map destination addresses its faces as
separate upload targets, so its zoffset picks the target rather than a slice.

ConvertGLEnumToTextureInternalFormat had arms for the six generic compressed
formats and the four RGTC ones, all resolving to uncompressed storage, but none
for BPTC or ETC2/EAC - so glTexImage2D with one of those fourteen enums answered
INVALID_ENUM, which was never a legal reply for formats core GL has required
since 4.2 and 4.3. They follow the same deviation for the same reason: nothing in
this stack can compress them, and uncompressed storage is the trade the RGTC
formats already take.

Takes textures_compressed_subimage from failing to passing on both backends and
textures_copy on Espryt. textures_copy still fails on Magma, where the readback
of a layered attachment does not yet resolve the attached layer.
2026-08-05 05:50:32 -04:00
BZLZHH 300b458132 [Feat] (MG_State, MG_Impl): give program pipelines their object and their state
Every program pipeline entry point was an export stub, and the stub macro's
`return (type)1` made glIsProgramPipeline answer GL_TRUE for anything - including
the names glGenProgramPipelines had never written. All four
direct_state_access.program_pipelines cases failed.

ProgramPipelineObject holds what GL 4.6 core 7.4 says a pipeline is: a program
reference per shader stage, the active program glProgramUniform* addresses, a
validate status and an info log. Its validate status starts false, unlike
ProgramObject's, because a pipeline that has never been validated must report
GL_VALIDATE_STATUS as 0.

The name rules follow the shape queries and transform feedbacks already use, and
which the CTS checks first: glGenProgramPipelines only RESERVES a name and
glIsProgramPipeline answers GL_FALSE for it; the object appears on first bind, or
immediately from glCreateProgramPipelines. Map membership is object existence -
a pipeline, unlike a transform feedback, has no stateful default object zero, so
no everBound flag is needed.

glGet(GL_PROGRAM_PIPELINE_BINDING) reports the real binding now instead of a
hardcoded zero whose comment said the entry points were stubbed.

This is the state half only. program_pipelines_functional needs mixed-stage
rendering - a vertex-only and a fragment-only program drawn together - and stays
failing; glCreateShaderProgramv is deliberately left stubbed until that lands, so
nothing can half-work in between.

Takes program_pipelines_creation, _defaults and _errors from failing to passing
on both backends.
2026-08-05 05:43:13 -04:00
BZLZHH 1f1a331a44 [Feat] (MG_Impl, MG_State): implement the framebuffer parameter getters and setters
glFramebufferParameteri, glGetFramebufferParameteriv and their two by-name
siblings were all export stubs - the GL_ARB_framebuffer_no_attachments entry
points. The stub raises no error and writes nothing, so
direct_state_access.framebuffers_get_parameter_errors saw GL_NO_ERROR for all
three conditions it checks.

FramebufferObject gains the five DEFAULT_* parameters as real state, initialised
to GL 4.6 core table 23.24 and bumping the object version on a write like the
read buffer does. The getter answers those plus the six derived names -
GL_SAMPLES and GL_SAMPLE_BUFFERS from the attachments' sample counts,
GL_IMPLEMENTATION_COLOR_READ_FORMAT/_TYPE from the read buffer's internal format,
GL_DOUBLEBUFFER true only for the window-system framebuffer, GL_STEREO false
because stereo surfaces are not exposed - which is what glGetIntegerv already
reports for the bound framebuffer.

The pname rules live in ValidateFramebufferParameterPname, and their ORDER is
load-bearing: a name outside the table is INVALID_ENUM, and only a name that IS
in the table but that the default framebuffer cannot answer is INVALID_OPERATION.
Testing the framebuffer kind first would answer INVALID_ENUM for
GL_FRAMEBUFFER_DEFAULT_WIDTH on framebuffer zero, which is exactly the third
thing the case checks. The by-name forms take zero as the default framebuffer,
like the other DSA framebuffer entry points.

Rendering to a framebuffer with no attachments is deliberately NOT enabled by
this: CheckCompleteness still reports INCOMPLETE_MISSING_ATTACHMENT, because no
backend can rasterize one. The state is real and the queries are honest; the
draw path is a separate piece of work.

Takes framebuffers_get_parameter_errors from failing to passing on both backends,
with framebuffers_get_parameters - which passed only because both getters were
stubs leaving the CTS's zero-initialised comparands untouched - still passing.
2026-08-05 05:33:31 -04:00
BZLZHH 817091641c [Fix] (MG_Impl): give a cube map the storage and the layered attachment it asks for
direct_state_access.framebuffers_texture_attachment threw on both backends, and
three separate things were wrong on the way to a cube map framebuffer.

glTexStorage1D/2D/3D validated their target by converting it to a single
TextureUploadTarget. GL_TEXTURE_CUBE_MAP has no single upload target - it
allocates all six faces - so the conversion produced Unknown and a legal
glTexStorage2D(GL_TEXTURE_CUBE_MAP, ...) was rejected with INVALID_ENUM, which is
where the case threw. The accepted set for these entry points is the dimension's
storage targets, which IsTextureStorageTargetForDimension already spells out, so
that is what they check now.

TextureStorage2D then allocated only the primary upload target, leaving a cube
map with one face out of six - cube-incomplete, so every framebuffer it was
attached to answered GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT. It allocates every
upload target the object has; for every other 2D target that is the same single
target as before.

ResolveRepresentableFramebufferTextureUploadTarget declined every layered target
but 2D array, so glNamedFramebufferTexture on a cube map reported "not
represented by the current framebuffer attachment model". Cube maps, cube map
arrays, 1D arrays, 2D multisample arrays and 3D textures are all the same shape
as the 2D array that already worked - glFramebufferTexture binds the whole
texture and the attachment records a representative upload target - so they are
all handled now. DirectGLES routes a layered attachment to glFramebufferTexture,
which is exactly this.

Takes framebuffers_texture_attachment from failing to passing on both backends.
2026-08-05 05:24:21 -04:00
BZLZHH e64c7c7e65 [Fix] (MG_Backend): never back a multisample texture with a one-sample Vulkan image
Every one of the sixty direct_state_access.textures_storage_multisample_2d_* and
_3d_* cases failed on DirectVulkan, for every internal format, with no GL error
anywhere - a pure data mismatch.

The CTS asks for glTextureStorage2DMultisample(tex, samples = 1, ...), which is
legal GL, and MobileGL carried the 1 faithfully through to
VkImageCreateInfo::samples = VK_SAMPLE_COUNT_1_BIT. It then binds that image to
the auxiliary program's sampler2DMS, whose SPIR-V is OpTypeImage with MS = 1.
VUID-RuntimeSpirv-samples-08726 forbids exactly that pairing: an MS access must
come from an image created with more than one sample. The texelFetch therefore
read undefined data - which is why it looked format-independent and raised
nothing.

GL only promises "at least the requested number of samples", so a multisample
texture is now floored at two. GL_TEXTURE_SAMPLES still reports what the
application asked for; that is read off the texture object, not off the image.
The device-capability round below it is bounded at two for the same reason -
letting it land back on one sample would recreate the violation silently for any
format whose only supported count is one.

Takes all 60 textures_storage_multisample_* cases from failing to passing on
DirectVulkan, which goes from 296/371 to 356/371. DirectGLES is untouched.
2026-08-05 04:46:15 -04:00
BZLZHH dd60ff39ce [Feat] (MG_State, MG_Impl, MG_Backend, MG_Util): make the border colour real sampler state
glGetSamplerParameterfv(sampler, GL_TEXTURE_BORDER_COLOR) raised INVALID_ENUM,
because MobileGL kept the border colour on the texture object and
GetSamplerParam_State had no case for it at all. That is the first thing
direct_state_access.samplers_defaults asks, so the case threw before reaching
any of the defaults it was written to check.

GL 4.6 core table 23.18 lists TEXTURE_BORDER_COLOR as sampler state, so it moves
to SamplerParameters and TextureObjectBase reaches it through the SamplerObject
it already owns - one source of truth, and a sampler object bound over a texture
now supplies its own border colour, which is what GL says should happen. The
texture params version still moves on a write, because the DirectGLES texture
sync memoises on it. glSamplerParameter{fv,Iiv,Iuiv} and their getters read and
write all four components in whichever representation the caller used, and the
three representations are kept in step so any getter has an answer. The bogus
[0,1] and [0,255] range checks are gone: GL clamps a border colour when a
fixed-point format is sampled, it does not reject it.

DirectVulkan's ResolveVkBorderColor now reads the sampler rather than the
texture. DirectGLES gained a glSamplerParameterfv in its sampler sync, and both
that and the pre-existing glTexParameterfv are gated on a new
SupportsTextureBorderClamp capability - ES 3.2 core, or EXT/OES_texture_border_clamp
before it - since without the extension every such call is INVALID_ENUM on the
driver. DriverPost gains the matching row per the POST rule, saying what a user
actually loses when it is missing.

Takes direct_state_access.samplers_defaults from failing to passing on both
backends.
2026-08-05 04:45:55 -04:00
BZLZHH 96ad7ca0cc [Fix] (MG_Impl): asking a renderbuffer for more samples than it has is INVALID_OPERATION
ValidateRenderbufferStorageSamples_State answered INVALID_VALUE for a sample
count above GL_MAX_SAMPLES. GL 4.6 core 9.2.4 reserves INVALID_VALUE for a
negative count: a count that is well formed but larger than the format can
deliver is INVALID_OPERATION, because the argument is fine and the format is
what cannot honour it.

Takes direct_state_access.renderbuffers_storage_multisample_errors from failing
to passing on both backends.
2026-08-05 04:13:59 -04:00
BZLZHH e80a23eae6 [Fix] (MG_Backend): read a multi-slice glGetTexImage off the GPU instead of the CPU shadow
DirectGLES served every multi-slice glGetTexImage from the CPU shadow copy, on
the grounds that its scratch FBO can only expose one layer at a time. But the
shadow only holds what was uploaded, so any slice that was rendered to rather
than written by glTexSubImage came back stale - and a layered framebuffer
produces exactly that.

The scratch FBO can expose one layer at a time repeatedly. The read now attaches
each layer in turn and takes the slice off the GPU, walking the destination over
GL_PACK_SKIP_IMAGES / GL_PACK_IMAGE_HEIGHT itself so each per-slice call packs a
plain 2D image with the same layout StoreWideRowsToClient computes for the whole
stack. The shadow stays as the fallback for the formats a colour attachment
cannot represent at all, and for any slice whose attachment comes back
incomplete.

Takes all 27 remaining direct_state_access.textures_storage_multisample_3d_*
cases from failing to passing on Espryt - they render into a
TEXTURE_2D_MULTISAMPLE_ARRAY one layer per colour attachment and then read the
whole array back. DirectVulkan is untouched.
2026-08-05 03:55:30 -04:00
BZLZHH 088f263495 [Feat] (MG_Impl): answer the two query parameters the getters were missing
GetQueryObjectValue implemented GL_QUERY_RESULT_AVAILABLE and GL_QUERY_RESULT and
rejected everything else, so direct_state_access.queries_functional threw on its
very first probe - GL_QUERY_TARGET - and never reached any of the checks it was
written for.

GL_QUERY_TARGET is state the object has carried all along; it just had no case.
GL_QUERY_RESULT_NO_WAIT is GL_QUERY_RESULT with the backend asked not to block,
and it brings a wrinkle the shared getter could not express: when the result has
not landed, GL_ARB_query_buffer_object leaves the destination untouched rather
than writing a placeholder. GetQueryObjectValue now reports "succeeded but
produced no value" through an optional out-parameter, and all five callers - the
four buffer forms and the four client-memory forms - skip the write on it.

The switch is deliberately widened by exactly these two names: its default
INVALID_ENUM is what the GL33 and GL40 query error cases rely on.

queries_functional passes on Espryt. On Magma it stops throwing and fails on a
value instead, which is a separate problem in the query results themselves.
2026-08-05 03:48:14 -04:00
BZLZHH 3b3b6e5b8b [Fix] (MG_Backend): read back the stencil half, and clear an sRGB target to the value asked for
Two reasons a framebuffer's contents came back wrong, both on the read/clear
side rather than the write side.

Stencil, on both backends. The CTS reads stencil with glReadPixels(GL_STENCIL_INDEX,
GL_INT), which is as legal as the unsigned widths, and neither backend accepted
it: DirectGLES's ReadPixelsStencilViaNative rejected every signed type, after
which the call fell through to a native ES read the driver refuses and nothing
was written at all, so the caller kept its zeros; DirectVulkan's pack switch had
no GL_INT case, and of the cases it did have only GL_UNSIGNED_INT sourced the
stencil plane - GL_FLOAT and GL_UNSIGNED_SHORT emitted a depth value, which is
meaningless for a stencil-only image. Both now take the signed and float widths,
and DirectVulkan decides "this is a stencil read" once rather than per type.
DirectGLES also gains the GL_FLOAT_32_UNSIGNED_INT_24_8_REV fallback a
DEPTH32F_STENCIL8 attachment needs, which rejects the 24_8 packed type.

sRGB, on DirectVulkan. Every other write path goes through the UNORM twin view
while GL_FRAMEBUFFER_SRGB is off, storing the raw value GL asked for, but a
deferred clear is materialised with vkCmdClearColorImage - which names the image,
so the driver applied the sRGB transfer function and a clear to 0.25 landed at
0.537. PreCompensateSrgbClearColor hands it the linear colour whose encoding is
the requested value instead. It is a no-op for non-sRGB destinations, for integer
clear encodings, and when GL_FRAMEBUFFER_SRGB is on and GL really does want the
encode.

Takes renderbuffers_storage from failing to passing on both backends, plus
renderbuffers_storage_multisample and framebuffers_blit on Espryt.
2026-08-05 03:41:23 -04:00
BZLZHH 9eda2147b1 [Fix] (MG_Impl, MG_Backend): let the backend that can honour a layered attachment have it
NamedFramebufferTextureLayer declined every attachment but layer zero, on both
backends. That was right for DirectVulkan, which maps a GL layer onto a Vulkan
array layer with no notion of a 3D depth slice, but wrong for DirectGLES:
SyncAttachmentObject already routes a layered upload target to
glFramebufferTextureLayer with the attachment's layer passed straight through,
and array storage already carries the real layer count into glTexStorage3D. The
one backend that could render to the layer was being told it could not.

The decision now lives in a DynamicBackendParameters flag, so it is the backend
that answers rather than the entry point guessing. DirectGLES sets it when the
driver resolved glFramebufferTextureLayer; DirectVulkan leaves it false until
VkRenderPassManager tells a depth slice from an array layer.

framebuffers_texture_layer_attachment's colour checks now pass on Espryt for 3D,
2D array and 2D multisample array textures - the case still fails there on cube
map arrays, which DirectGLES gives no storage at all, and on the depth and
stencil halves. No case changes on DirectVulkan, which keeps the old behaviour.
2026-08-05 03:40:59 -04:00
BZLZHH a63699cde6 [Fix] (MG_Impl, MG_Backend): reject incomplete cube maps in mipmap generation instead of crashing on them
Both direct_state_access.textures_generate_mipmap* cases crashed DirectVulkan.
Two causes, neither of them a broken invariant:

glGenerateMipmap and glGenerateTextureMipmap never checked cube completeness, so
an incomplete cube map went straight to the backend, which asserts that the
texture it is handed is complete. GL 4.6 core 8.14.4 makes that call
INVALID_OPERATION - there is no consistent set of faces to filter down - and both
entry points now say so through a shared check.

VulkanRenderer::GenerateMipmap asserted that the target was one of the four it
implements. 1D, 1D array and cube map array are legal GL and the front end passes
them through, so meeting one is a gap in this backend's coverage; it now logs and
declines, leaving the generated levels unwritten rather than aborting.

textures_generate_mipmap_errors passes on both backends now. textures_generate_mipmaps
stops crashing but still fails: DirectVulkan does not generate the 1D mip chain
the case checks - the frontend's storage allocation gives the levels the right
sizes, which is why the case passes when run on its own, but not the descending
content the full-run state leaves it looking for.
2026-08-05 02:55:54 -04:00
BZLZHH 765aaec6dc [Fix] (MG_Impl, MG_Backend): stop the new layer attachment from reaching backends that cannot back it
Implementing NamedFramebufferTextureLayer made layered attachments reachable for
the first time, and direct_state_access.framebuffers_texture_layer_attachment
went from Fail to Crash on DirectVulkan. Two separate gaps sat behind it, both
of them asserted on rather than reported:

- The renderer resolves an attachment's GL layer straight onto a Vulkan array
  layer. A 3D texture's z-slice therefore lands outside its image, which has one
  array layer by construction, and the array texture objects are still the
  one-image stubs in TextureObjectStubs.h, so their image has a single layer
  whatever GL believes. MaterializePendingClearForTexture tripped over a clear
  whose layer span was outside the image it was given.
- A cube map array has no image shape in VkTextureManager at all, so
  SyncTextureAndGetDescriptor returns null for it.

NamedFramebufferTextureLayer now answers the full error set for every target and
layer - which is what took the two error cases green - and then declines to
attach anything but layer zero of a non-cube-array texture, through the same
RecordUnsupportedFramebufferTextureAttachmentError the by-target entry point
already uses. Layer zero of the other targets is the plain first-slice
attachment glFramebufferTextureLayer already backs, so it still goes through.

SyncTextureResource's assertion on an unsupported texture shape is also gone: it
is a gap in this backend's coverage, not a broken invariant, and the code below
it already handles the failure by declining the sync. It logs a warning instead.

framebuffers_texture_layer_attachment goes back to Fail on DirectVulkan rather
than Crash; no case changes in either direction beyond that.
2026-08-05 02:47:27 -04:00
BZLZHH bcd669bd25 [Feat] (MG_Impl): complete the by-name framebuffer attachment and buffer-selection entry points
Four direct_state_access framebuffer cases failed on one shared cause and three
local ones.

The shared cause: every DSA framebuffer entry point resolved its name through
GetNamedFramebufferObject_State, which rejects zero outright. But zero names the
default framebuffer to these functions, so glGetNamedFramebufferAttachmentParameteriv,
glNamedFramebufferDrawBuffer(s) and glNamedFramebufferReadBuffer answered
INVALID_VALUE for every default-framebuffer query the CTS makes. They now resolve
zero to the default framebuffer object and tell the two kinds apart explicitly,
which is what the accepted-name rules key off anyway.

Attachment queries: the accepted attachment names differ between the default
framebuffer (FRONT/BACK variants, DEPTH, STENCIL) and a framebuffer object
(COLOR_ATTACHMENTi, DEPTH/STENCIL/DEPTH_STENCIL_ATTACHMENT), and a name outside
the relevant list is INVALID_ENUM. Both getters share ResolveAttachmentQueryName
for that, so the by-target form no longer aliases GL_FRONT onto a framebuffer
object's colour attachment 0. The TEXTURE_* parameters are also rejected with
INVALID_ENUM when the attached object is a renderbuffer.

Buffer selection: naming a buffer that belongs to the other kind of framebuffer
is INVALID_OPERATION, not INVALID_ENUM - the enum is accepted, the framebuffer
just has no such buffer. glDrawBuffers additionally rejects the multi-buffer
names (FRONT, LEFT, RIGHT, FRONT_AND_BACK) with INVALID_ENUM on both kinds,
takes BACK only when n is one, and glReadBuffer treats the multi-buffer names as
accepted-but-unselectable. Both colour-attachment range checks now go through
ValidateColorAttachmentInRange instead of comparing against MAX_DRAW_BUFFERS with
an off-by-one.

NamedFramebufferTextureLayer was a stub that reported "not represented by the
current framebuffer attachment model" for every call, even though the attachment
model stores a layer and the by-target glFramebufferTextureLayer already uses it.
It is implemented against the same model, with the per-target layer limits and
the INVALID_OPERATION-for-a-bad-name rule that separates it from
NamedFramebufferTexture. NamedFramebufferTexture itself gained the two checks it
lacked: colour attachment range, and a negative level.

Takes framebuffers_get_attachment_parameters, framebuffers_get_attachment_parameter_errors,
framebuffers_texture_attachment_errors and framebuffers_draw_read_buffers_errors
from failing to passing on both backends.
2026-08-05 02:34:12 -04:00
Claude f3405d1d53 [Fix] (CI): narrow the trace fixture Git LFS fallback to the files mirrors lost
The fetch script tries git.hit.moe, then the repo.miawa.cn mirror, and only
then Git LFS, but it bailed out of the mirror loop on the first file no
mirror could serve and then pulled the whole case from GitHub. A case whose
mirrors served every file but one paid GitHub's LFS bandwidth for all of
them.

Collect the files that survived every mirror and every retry instead, and
scope the LFS fallback to just those, matching what the local macOS retrace
helper already does.
2026-08-05 05:59:25 +00:00
BZLZHH 81604d5596 [Feat] (MG_Impl, MG_Test): validate the direct-state-access texture copies
CopyTextureSubImage1D and 3D were do-nothing stubs and the 2D form checked only
its effective target, so all 28 conditions in
direct_state_access.textures_copy_errors went unreported: level and region
bounds, and every read-framebuffer precondition.

The read-framebuffer half lands in FramebufferImpl as ValidateReadFramebufferForCopy -
incomplete read framebuffer (INVALID_FRAMEBUFFER_OPERATION), a read buffer that
names no attachment, and a multisampled read buffer (both INVALID_OPERATION). It
decides multisampledness by attachment kind rather than by sample count alone,
because a TEXTURE_2D_MULTISAMPLE attachment sets SAMPLE_BUFFERS even when its
sample count is one - which is exactly what the CTS attaches, and what a
renderbuffer-only check would have missed.

The texture half is ValidateCopyTextureSubImage, shared by all three forms; 1D
and 3D also get the effective-target rule their form specifies.

NOTE: the copy itself is still not implemented for 1D and 3D - CopyTexSubImage1D_State
and CopyTexSubImage3D_State remain TODOs and no backend exposes anything but a
2D blit - so direct_state_access.textures_copy stays red. Only the errors are
complete, which is what un-stubbing these two entry points buys; both carry a
comment saying so.

CopyTextureSubImage2DUsesNamedObjectAndRestoresBinding had been passing a
storage-less texture and no read framebuffer, which the new validation correctly
rejects. It now sets up a legal copy, so it still measures the by-name plumbing
it was written for.

Takes direct_state_access.textures_copy_errors from failing to passing on both
backends.
2026-08-05 01:54:39 -04:00
BZLZHH 31ea6aa5a3 [Feat] (MG_Impl): give the by-name texture image queries their error set
glGetTextureImage resolved a texture by name and went straight to the read,
skipping every object-level rule glGetTexImage enforces through
GetTexImage_State - and on DirectVulkan it skipped the level checks in
CopyTextureImageToClientOrPBO_State as well, because that backend answers
GetTextureImage itself. Fifteen of the sixteen conditions in
direct_state_access.textures_image_query_errors went unreported.

The object-level half of that error set now lives in ValidateTextureImageQuery
and both entry points run it. Three rules are new rather than merely relocated:

- Multisample and buffer textures are not in the accepted target list; neither
  has a single image to return.
- The destination-size checks (bufSize, and the span written into a bound pixel
  pack buffer) move ahead of the read. They existed, but downstream of it, where
  any early bail-out - an unmapped level, a pack step that declines the format -
  swallowed them. Both measure the tightly packed span summed over the object's
  faces, which is the least a query can produce, so nothing that would have fit
  is rejected.
- IsDepthLikeInternalFormat had no case for StencilIndex8, so a colour client
  format read back against a stencil-only texture looked like a matching pair.

glGetCompressedTextureImage was a do-nothing stub. It validates the name and the
level, then reports INVALID_OPERATION: no format MobileGL can hold is
compressed, and answering GL_NO_ERROR without writing would hand the caller
stale memory - the same reasoning GetCompressedTexImage_State already follows.

Takes direct_state_access.textures_image_query_errors from failing to passing on
both backends.
2026-08-05 01:46:10 -04:00
BZLZHH 7d6f6603c1 [Feat] (MG_Impl): enforce the unpack-buffer rules on texture sub-image uploads
TexSubImage1D/2D/3D_State each carried a TODO for the three INVALID_OPERATION
conditions GL 4.6 core 8.5 attaches to sourcing an upload from a bound
PIXEL_UNPACK_BUFFER: the store being mapped, an offset that is not a multiple of
the size of one datum of `type`, and reads that would run past the end of the
store. None of them was checked, so every such call was quietly accepted.

ValidatePixelUnpackBufferSource now covers all three and returns true when no
unpack buffer is bound, so the callers can run it unconditionally. Persistent
mappings stay legal sources, matching what ReadPixels already does on the pack
side. The overrun check measures the tightly packed span, which is the smallest
the unpack can read - pixel store parameters only ever widen it - so it cannot
reject an upload that would have fit.

TextureSubImage2D needed the call of its own: unlike its 1D and 3D siblings it
does not route through TexSubImage2D_State.

Takes direct_state_access.textures_subimage_errors from failing to passing on
both backends.
2026-08-05 01:32:37 -04:00
BZLZHH 39c17c0b1b [Fix] (MG_Impl): validate the float texture parameter setter and the compressed size query
Two independent gaps in the texture parameter paths, both reported by
direct_state_access:

TexParameterf_State never ran ValidateTextureParameterForTarget. The integer
setter reaches it through TextureParameterObject_State and the scalar float
setter through TextureParameterObjectf_State, but glTexParameterfv and
glTextureParameterfv funnel every non-vector pname straight into
TexParameterf_State - so in float form MobileGL accepted sampler state on a
multisample texture, a mipmapping min filter or a REPEAT wrap on a rectangle
texture, and a negative TEXTURE_BASE_LEVEL/TEXTURE_MAX_LEVEL, all of which the
integer form rejected. It now validates first, passing the same
anisotropy-exempt param the by-object float setter uses so the anisotropy range
check is not run twice.

GL_TEXTURE_COMPRESSED_IMAGE_SIZE answered 0 for every texture. GL 4.6 core 8.11
makes the query INVALID_OPERATION on an image whose internal format is
uncompressed and on any proxy target. TextureInternalFormat has no compressed
enumerator, so that is every texture MobileGL can hold today; the condition is
still written against an IsCompressedTextureFormat predicate so both level
getters answer consistently once compressed formats land, and
GL_TEXTURE_COMPRESSED now reads from the same predicate instead of a hardcoded
false.

Takes textures_parameter_setup_errors and textures_level_parameter_errors from
failing to passing on both backends.
2026-08-05 01:24:29 -04:00
BZLZHH 88138b48ec [Test] (MG_Test): follow the backends to an advertised GL 4.0
Both AdvertisesVoxyRequiredRenderingExtensions cases pinned TargetGLVersion at
3.3, which was the reported version until V_OpenGL40 joined the advertised
extension lists. The version assertion is incidental to what these cases are
for - Voxy needs the individual ARB extensions, not a version - so it just
tracks the new report instead of holding the old one.
2026-08-05 01:24:05 -04:00
BZLZHH c114ce750b [Feat] (MG_Backend): advertise OpenGL 4.0 on both backends
Both backends stopped their advertised version list at V_OpenGL33, so an
application - or the CTS - asking what MobileGL supports was told 3.3 even
though the 4.0 entry points and the KHR-GL40 suite already pass on both.
Adding V_OpenGL40 lets that work be reached through the ordinary version query
instead of only through the individual ARB extension strings.
2026-08-05 13:19:41 +08:00
BZLZHH 1ca2d3c0fe [Docs] (README): move the short-term target to OpenGL 4.2
The 3.3 line is done - GL30 through GL33 conform on both backends - and the
work in flight (GL40, direct state access) is already past it, so the stated
short-term target now reads 4.2 and MG_State/MG_Impl are focused there.
Performance work joins the focus list alongside the two backends.
2026-08-05 01:15:26 -04:00
BZLZHH 58c17f85a5 [Fix] (MG_State, MG_Backend): start TEXTURE_COMPARE_FUNC at LEQUAL
SamplerParameters defaulted compareFunc to ALWAYS, but GL 4.6 core table 23.18
and GLES 3.2 table 21.16 both say the initial value is LEQUAL - for sampler
objects and for the sampler state a texture object carries alike. Every freshly
created texture and sampler therefore answered GL_ALWAYS to
glGetTextureParameteriv(GL_TEXTURE_COMPARE_FUNC).

The Vulkan backend had been papering over it: ResolveCompareFunc substituted
LESS_EQUAL whenever a depth texture was sampled in compare mode and the func
still read ALWAYS, which fixed the rendering but also made an explicitly
requested GL_ALWAYS unreachable. With the default corrected that special case is
both unnecessary and wrong, so it is gone and the compare op is taken straight
from the sampler.

Takes direct_state_access.textures_defaults from failing to passing on both
backends.
2026-08-05 01:13:04 -04:00
BZLZHH 4873da6844 [Fix] (MG_Impl): accept COLOR when invalidating the default framebuffer
The validation added with the invalidation entry points took the default framebuffer's
buffers to be only FRONT_LEFT, FRONT_RIGHT, BACK_LEFT, BACK_RIGHT, DEPTH and STENCIL, so a
call naming COLOR came back INVALID_ENUM. The by-name forms spell the colour buffer the way
glClearNamedFramebuffer does - COLOR, DEPTH, STENCIL - while the target forms use the
individual left/right tokens, and both spellings arrive at the same validation, so both sets
belong there (GL 4.6 core 17.4.4).

Caught by framebuffers_invalidate_data and framebuffers_invalidate_subdata, which had been
passing while the entry points were stubs doing nothing at all. Those two plus
invalidate_data_and_subdata_errors now pass together on both backends.
2026-08-05 00:51:12 -04:00
BZLZHH efeb24ff9b [Fix] (MG_Impl, MG_State): answer the texture parameters the getters were missing
glGetTexParameter and its by-name form rejected several parameters GL 4.6 core table 8.20
lists, with INVALID_ENUM as if the application had made them up. GL_DEPTH_STENCIL_TEXTURE_MODE
was the worst of them: the float setter accepted it, validated it and then threw the value
away, the integer setter did not accept it at all, and neither getter could report it - so
the mode could be set and never read back, and setting it through glTextureParameteri was an
error.

It is real state now, defaulting to DEPTH_COMPONENT, set by both setters and readable from
both getters. GL_TEXTURE_LOD_BIAS was in the same position: settable, not gettable.

The by-name getters reach the target-based ones through a temporary binding rather than the
per-object path, so both had to learn these; the per-object path gained the swizzle
components, the target, the image format compatibility type and the texture-view parameters
at the same time, since they were missing there for the same reason.

direct_state_access.textures_get_set_parameter passes on both backends, and textures_defaults
stops raising an internal error and reports an ordinary failure it can be diagnosed from.
2026-08-05 00:49:12 -04:00
BZLZHH 18c1a4d586 [Feat] (MG_Impl): implement the query getters that write into a buffer object
glGetQueryBufferObjectiv and its three siblings were stubs. They are the ordinary query
getters with the destination changed from client memory to a buffer object, so everything
about the query itself - the name, whether it is still active, the parameter - is already
answered by the shared GetQueryObjectValue, including the errors it raises.

What was left is the destination: a negative offset is INVALID_VALUE, a name that is not a
buffer object is INVALID_OPERATION, and so is a write that would run past the end of the
buffer. The four differ only in the width they store, so they share one template.

direct_state_access.queries_errors passes on both backends, putting the group at 4 of 5.
queries_functional now reaches further into the test and ends in an unrelated InternalError
rather than a plain failure.
2026-08-05 00:36:53 -04:00
BZLZHH 66ac3486e1 [Feat] (MG_Impl): validate the framebuffer invalidation entry points
glInvalidateFramebuffer, glInvalidateSubFramebuffer and their two by-name forms were all
stubs, so every call - including the malformed ones - returned quietly with no error.

These four only grant permission to throw the named attachments' contents away, and keeping
them satisfies "the contents become undefined", so the frontend validates the call and
leaves the contents alone. Actually discarding is a bandwidth optimisation that would need a
backend dependency; it can be added later without changing what any of these promise.

The validation is where the real content is. Which tokens name an attachment depends on
which framebuffer is affected: the default framebuffer has buffers (FRONT_LEFT and company)
and a framebuffer object has attachment points, so a token from the wrong set is
INVALID_ENUM. A COLOR_ATTACHMENTm past GL_MAX_COLOR_ATTACHMENTS is different in kind - a
well-formed enum naming a point that does not exist - and is INVALID_OPERATION, which the
existing colour-attachment range validator already expresses. Negative counts and negative
sub-region extents are INVALID_VALUE.

direct_state_access.invalidate_data_and_subdata_errors passes on both backends.
2026-08-05 00:31:46 -04:00
BZLZHH 764a44f589 [Fix] (MG_Impl): stop treating an empty buffer mapping access mask as a bad enum
glMapBufferRange and glMapNamedBufferRange rejected an access of zero with INVALID_ENUM.
Zero is a perfectly well-formed bitfield value - it contains no invalid flags - and what it
violates is the separate rule that a mapping has to ask for read or write access, which GL
reports as INVALID_OPERATION. Both callers already checked that rule immediately after, so
the validator was reporting the wrong error for a case its callers were about to handle
correctly.

direct_state_access.buffers_errors passes, which puts the whole buffers group at 4 of 4 on
both backends.
2026-08-05 00:13:51 -04:00
BZLZHH d96acb7972 [Fix] (MG_Impl): let a buffer clear name any format the spec allows
glClearBufferData and friends accepted exactly two argument triples - R8UI with
UNSIGNED_BYTE and R32UI with UNSIGNED_INT, both through RED_INTEGER - and raised
INVALID_ENUM for everything else. That is most of the entry point missing rather than a
narrow gap: GL takes any of the sized formats in the buffer-texture table, which is what an
application clearing an RGBA8 or R32F buffer uses.

The wrong error also hid the checks behind it. A test clearing a mapped buffer, or one
passing a misaligned offset, never reached those rules because the format tuple was rejected
first, so INVALID_ENUM came back where INVALID_OPERATION or INVALID_VALUE was due - the
validation was there and correct all along, just unreachable.

internalformat now goes through the same table the buffer textures use (shared rather than
written out twice, since it is the same list for the same reason), and format and type
through the ordinary pixel format converters. The element size comes from the internal
format, which is what offset and size have to be multiples of. Note that a bad format or
type here is INVALID_VALUE, not INVALID_ENUM (GL 4.6 core 6.3) - the odd one out among the
enum arguments, and what the conformance tests check for.

The pattern is still replicated verbatim, which is correct while the client layout matches
the internal format - every real caller, and every conformance case. When they differ it now
says so instead of quietly writing a differently-sized pattern.

direct_state_access.buffers_clear and buffers_functional pass on both backends;
buffers_errors is down to one unrelated complaint about glMapNamedBufferRange.
2026-08-05 00:09:11 -04:00
BZLZHH bd710078fc [Feat] (MG_Impl): implement glGetNamedBufferSubData
The by-name read was a stub, so it left the caller's buffer untouched and a test comparing
it against a reference saw whatever that memory already held. Its by-target sibling
glGetBufferSubData was already implemented, so this is that function with the buffer
resolved by name instead of through a binding: the same non-negative offset and size check,
the same bound-by-the-buffer's-size check, the same refusal to read a buffer mapped without
GL_MAP_PERSISTENT_BIT, and the same SyncGpuWrites before the download so a GPU-side write
that has not landed yet is not missed.

Resolving by name reports INVALID_OPERATION for a name that is not a buffer, which the
by-target form expresses as "target is bound to no buffer object" instead.

direct_state_access.buffers_get_named_buffer_subdata passes on both backends.
2026-08-05 00:01:20 -04:00
BZLZHH 95a7b17d45 [Fix] (DirectVulkan): clear an integer colour buffer with an integer value
glClearBufferiv and glClearBufferuiv flattened their values into the payload's float vector,
and every clear was later written into VkClearColorValue::float32. Vulkan reads that union
according to the destination image's format rather than converting between its members, so
an R8I attachment cleared to -16 received the bit pattern of -16.0f. On top of that,
QueueRenderbufferClear copied only the float vector into the pending clear, so even the
flattened value was dropped and the attachment kept reading zero - which is what the
conformance tests actually observed.

The payload now records which of the three entry points supplied the colour and keeps the
value in that form, and one helper builds the union member the encoding calls for. GL's rule
that a format with no alpha channel reads as one has to be applied in the value's own type,
so the "does this format lack alpha" question is now asked separately from the substitution
and the helper applies it to whichever member is live. glClear is left on the float path
explicitly: ClearFramebufferPayload has no other form.

Takes every integer renderbuffer format in direct_state_access.renderbuffers_storage from
failing to passing on Magma - 115 reported mismatches down to 20, the rest being the stencil
formats Espryt fails too and SRGB8_ALPHA8 - and makes framebuffers_clear pass on both
backends.
2026-08-04 23:55:43 -04:00
BZLZHH 19932f9e49 [Feat] (MG_Impl, MG_Backend): implement the integer direct state access framebuffer clears
glClearNamedFramebufferiv and glClearNamedFramebufferuiv were stubs, so a clear through
them was silently dropped and the attachment kept whatever it held. Their float siblings
were already implemented, which is what made the gap look like a rendering bug rather than
a missing entry point.

Which buffers they accept is narrower than glClearNamedFramebufferfv and differs between
the two: signed values clear COLOR or STENCIL, unsigned only COLOR (GL 4.6 core 17.4.3.1).
Only the colour buffer is indexed, so a stencil clear naming any drawbuffer other than 0 is
INVALID_VALUE rather than merely ignored, and anything else is INVALID_ENUM. Resolving the
framebuffer by name goes through the same helper the float forms use, which is what reports
INVALID_OPERATION for a name that is neither zero nor an existing framebuffer.

Both backends express them the way they already express the float forms: DirectGLES binds
the named framebuffer and forwards to glClearBuffer*, Magma queues the payload against the
named framebuffer rather than the bound one.

direct_state_access.framebuffers_clear_errors passes on both backends, and
framebuffers_clear passes on Espryt. Magma still fails that one, for a separate reason on
the materialization side rather than in these entry points.
2026-08-04 23:41:28 -04:00
BZLZHH 1011d9fea1 [Test] (MG_Test): follow the query-name and incomplete-texture rules the CTS pinned down
Two unit tests asserted behaviour the conformance tests had since contradicted, so they
were testing MobileGL's old answer rather than GL's.

QueryTest expected glIsQuery to report a name straight out of glGenQueries as a query
object. It is not one: GenQueries reserves names, and they "acquire query state only when
they are first used by calling BeginQuery" (GL 4.6 core 4.2.1). The test now checks that a
reserved name reads FALSE, that BeginQuery is what turns it into an object, and that a
sibling name left untouched stays FALSE. A companion case covers the direct state access
half, where glCreateQueries does create the object outright - which is the whole reason the
two entry points both exist.

The DirectGLES binding test built its texture with glGenTextures and glBindTexture and
nothing else, then expected BindCurrentTextures to bind it natively. A texture with no
image is incomplete and samples as (0, 0, 0, 1), which DirectGLES expresses by leaving the
native target unbound, so the setup no longer produced the binding the test then went on to
clear. It now gives the texture a format and a 1x1 level 0 - one level is the entire mip
chain at that size, so it is complete under any filter - and asserts that directly, so a
future completeness change fails on the setup line instead of on the assertion three calls
later.
2026-08-04 23:13:02 -04:00
BZLZHH b5565ae503 [Docs] (tools/cts): refresh the DSA reference tables after the multisample storage fix 2026-08-05 02:50:22 +00:00
BZLZHH b06ad3f877 [Fix] (MG_Impl): make multisample texture storage immutable, and validate it by name
glTexStorage2DMultisample and glTexStorage3DMultisample forwarded straight to the
glTexImage*Multisample allocation and stopped there. The allocation is indeed the same;
what the storage forms add is that it is final - TEXTURE_IMMUTABLE_FORMAT becomes TRUE and
any later call on that texture is INVALID_OPERATION (GL 4.6 core 8.19). MobileGL left the
texture mutable forever, so it reported TEXTURE_IMMUTABLE_FORMAT as FALSE and accepted
being respecified any number of times, silently discarding storage a test or an
application had already rendered into.

The by-name forms had no validation of their own either. The target forms get their target
checked when the binding is resolved; reached by name there is no binding, so
glTextureStorage2DMultisample took any texture, any extent and any sample count. It now
rejects a target that belongs to the other entry point (INVALID_OPERATION), extents
outside 1..GL_MAX_TEXTURE_SIZE and a depth past GL_MAX_ARRAY_TEXTURE_LAYERS
(INVALID_VALUE), and a sample count above GL_MAX_SAMPLES (INVALID_OPERATION) - measured
against the limit the getter reports rather than the backend parameter it is derived from,
since the frontend raises that number.

glTextureStorage1D/2D/3D gained the same treatment: a target belonging to a different one
of the three is INVALID_OPERATION, a zero extent is INVALID_VALUE (immutable storage
describes a real image, unlike glTexImage*D where an empty level is legal), and a level
count longer than the level-zero size admits is INVALID_OPERATION. Which dimensions take
part in that mip chain is per target: a 1D array keeps its layer count in height, so its
height does not halve.

Takes direct_state_access.textures_storage_multisample_2d_* from 0 to 30 of 30 on Espryt,
and the whole group from 74.93% to 82.48%. Magma still fails them for a separate reason.
2026-08-05 02:49:45 +00:00
BZLZHH 3311e6034a [Fix] (MG_Impl): report a buffer texture as the wrong object, not the wrong token
glGetTextureParameter* resolve the texture by name and then hand the work to the
target-based getter, which validates the target it was given. For a buffer texture that
is GL_TEXTURE_BUFFER, and the target form correctly calls that an unaccepted token -
INVALID_ENUM.

By name there is no token to blame. The application named an object that carries none of
the sampler or level state the query reports, which is INVALID_OPERATION (GL 4.6 core
8.11). The four by-name getters check the resolved object before delegating, so the error
describes what the caller actually got wrong.

Fixes direct_state_access.textures_parameter_errors on both backends, taking the group to
74.93% on Espryt and 73.32% on Magma.
2026-08-05 02:36:31 +00:00
BZLZHH 027c1bd4ab [Docs] (tools/cts): add the desktop Linux CTS skill
The Android and Windows paths each have a skill; the desktop Linux one had only
a runner script and a README section, so it was the least discoverable of the
three despite being the one to reach for while iterating - it needs no device
and no GPU, and a single test group takes seconds rather than hours.

Records what the other two skills cannot: that the toolchain has to be GCC 13+
or Clang 20+ (Clang 18 reports __cpp_concepts as 201907L, which switches
libstdc++'s <expected> off and breaks the shader transpiler), that
EGL_PLATFORM=surfaceless is mandatory for DirectGLES and why the symptom points
at the wrong call, and which of this environment's results are MobileGL's own
versus artefacts of software rendering.

Also states the rule the other skills only imply: report Espryt and Magma
separately. They fail different cases, and one combined number hides which
backend a change moved.
2026-08-05 02:31:46 +00:00
BZLZHH da52cc3906 [Docs] (tools/cts): refresh the DSA reference table for the fixes in this branch 2026-08-05 02:29:42 +00:00
BZLZHH ebe4fe133f [Fix] (MG_Impl): apply the buffer texture's own format and range rules
glTextureBuffer and glTextureBufferRange took any internal format the texture enum
converter recognised. A buffer texture accepts a much shorter list than a sampled or a
renderable texture does (GL 4.6 core table 8.16), and it cannot be inferred from either,
so a format like GL_RGB8 was accepted and produced a texture nothing could read.

Two error codes were wrong as well. A texture whose effective target is not
GL_TEXTURE_BUFFER is the wrong object rather than the wrong token, so it is
INVALID_OPERATION. And the range form never checked its range against the buffer it was
attaching, so a size past the end of the buffer was accepted and left the texture
addressing memory the buffer does not own.

Fixes direct_state_access.textures_buffer_errors and textures_buffer_range_errors on both
backends.
2026-08-05 02:29:25 +00:00
BZLZHH 534ec65dda [Fix] (MG_Util): ask the ES driver for the texture buffer offset alignment
The DirectGLES capability probe queried GL_TEXTURE_BUFFER_OFFSET_ALIGNMENT with a bare
glGetIntegerv while every other query in the same function goes through glesFuncs. A bare
call resolves to MobileGL's own exported entry point, which answers that pname out of the
capability table this code is in the middle of filling in, so the value read back was the
default it started from and the driver's real alignment never arrived.

The backend therefore advertised an alignment of 1. An application that trusts that -
which is the only thing it can do - passes glTextureBufferRange an offset the ES driver
cannot honour, and the driver produces a texture that reads as zeros with no error
anywhere. The alignment llvmpipe actually wants is 16.

Takes direct_state_access.textures_buffer_* from 3 to 30 of 30 on DirectGLES, and the
whole DSA group from 66.85% to 74.12%. DirectVulkan was unaffected: its alignment comes
from a Vulkan device limit and was already right.
2026-08-05 02:26:50 +00:00
BZLZHH 35ad1ae7fc [Docs] (tools/cts): document the desktop Linux CTS path and the DSA baseline
run_cts_local.py and the mobilegl-desktop VK-GL-CTS target were both in the tree
with nothing describing how to reach them, so the only documented ways to run the
suite needed either an Android device or a Windows box with a GPU. The desktop
Linux path needs neither: lavapipe gives DirectVulkan a headless surface and
Mesa's surfaceless EGL gives DirectGLES a context, so a single test group can be
measured in seconds while working on it.

Records the two things that cost time to find. EGL_PLATFORM=surfaceless is
mandatory for DirectGLES - without a /dev/dri node Mesa fails eglInitialize on
the default display, and MobileGL surfaces that as EGL_BAD_ALLOC from
eglCreatePbufferSurface, which points at the wrong call entirely. And
DirectVulkan's default-framebuffer readback returns zeros here exactly as it does
on Adreno, so that defect is MobileGL's and reproducible without a phone.

The direct_state_access reference table is the measured baseline for the fixes in
this branch, so a later change has something to be compared against.
2026-08-05 02:22:09 +00:00
BZLZHH 6152ee933f [Fix] (MG_Impl): bound a colour attachment and a vertex binding range by the limit
GL_COLOR_ATTACHMENTn is a token for every n up to 31, but only the first
GL_MAX_COLOR_ATTACHMENTS of them name an attachment point of a framebuffer object. The
enum conversion accepted the whole token range, so attaching a renderbuffer or a texture
to a colour attachment past the limit silently succeeded instead of reporting
INVALID_OPERATION, and the attachment landed in a slot nothing else would ever look at.

glBindVertexBuffers and glVertexArrayVertexBuffers take a range of binding points rather
than one index. A range running past the last binding point is INVALID_OPERATION, which
the per-binding validation could not report: it saw one index at a time and reported the
INVALID_VALUE that a single out-of-range index earns. The range is checked up front now,
before any binding point is touched, so a rejected call also leaves none of them changed.

Takes direct_state_access.vertex_arrays_* to 18 of 19 and fixes
direct_state_access.framebuffers_renderbuffer_attachment_errors on both backends.
2026-08-05 02:21:13 +00:00
BZLZHH dac02ca044 [Feat] (MG_Impl, MG_State): implement the direct state access transform feedback API
glCreateTransformFeedbacks, glTransformFeedbackBufferBase, glTransformFeedbackBufferRange
and the three glGetTransformFeedback* queries were all stubs, so a transform feedback
object could only be configured and inspected by binding it first - the exact thing
direct state access exists to avoid. The queries were the worse half: they returned
nothing and raised no error, so an application could not tell that it had learned
nothing.

glCreateTransformFeedbacks creates the objects outright. glGenTransformFeedbacks only
reserves names, and a reserved name becomes an object when it is first bound
(GL 4.6 core 13.2.1); the DSA form has no bind step to create them from.

The queries and the buffer bindings read and write a named object's state. That state
lives in two places: the context keeps one live copy of the capture bindings and the
active/paused flags for whichever object is bound, and every other object's copy sits in
its saved state until a bind swaps it in. The by-name accessors added to the context
resolve that, so a query for the bound object reads the live copy rather than a stale
save.

GL_TRANSFORM_FEEDBACK_BUFFER_START and _SIZE are answered as zero unless the binding was
made by the range form, matching what the buffer object binding points already do.

Takes direct_state_access.xfb_* from 0 to 4 of 5 on both backends; xfb_functional still
fails on the capture itself, which is a separate defect.
2026-08-05 02:16:48 +00:00
BZLZHH 42fd02d82f [Fix] (MG_Impl, MG_State): give the vertex buffer binding points a real state view
The binding-point half of ARB_vertex_attrib_binding was implemented, but nothing
outside it could see the result. glGetIntegerv answered GL_MAX_VERTEX_ATTRIB_BINDINGS,
GL_MAX_VERTEX_ATTRIB_RELATIVE_OFFSET and GL_MAX_VERTEX_ATTRIB_STRIDE with a hardcoded
0 and a comment saying the entry points were stubs, which they no longer are. An
application that sizes its loops off those limits therefore saw none, and every
"bindingindex must be less than MAX_VERTEX_ATTRIB_BINDINGS" check silently accepted
everything because the limit it validated against was not the one it reported.

The indexed getters answer GL_VERTEX_BINDING_{BUFFER,DIVISOR,OFFSET,STRIDE} from the
bound vertex array now, and the non-indexed getter reports them as indexed-only rather
than returning a fabricated 0.

glVertexAttribPointer is defined in terms of the binding model: it also points the
attribute at its own binding point and gives that point the buffer, the pointer as the
offset and the effective (never zero) stride. MobileGL resolved the pointer form
straight into the flat attribute view and left the binding point untouched, so
GL_VERTEX_BINDING_OFFSET read back 0 for every attribute set up the classic way. The
flat view keeps the raw stride, because GL_VERTEX_ATTRIB_ARRAY_STRIDE reports that
argument verbatim, so the binding point is recorded alongside it rather than resolved
from it. glVertexAttribDivisor likewise now moves the binding point's divisor.

The by-name entry points reject vertex array 0. MobileGL keeps a real object at index 0
for the compatibility paths, so the name validation used to let the default vertex array
through a direct-state-access call that has no such thing.

glVertexAttribFormat and friends validated with the pointer-only subset, which reports
GL_BGRA as an out-of-range size instead of applying the BGRA rules, and never saw
relativeoffset at all. They share the full format validation now, which also grew the
GL_UNSIGNED_INT_10F_11F_11F_REV rules - that type has no DataType of its own, so it has
to be recognised before the conversion turns it into Unknown and reports the wrong error.

glVertexAttribLFormat and glVertexArrayAttribLFormat were stubs. They validate their
arguments now and then report that 64-bit vertex attributes are unsupported, which is
honest; silently accepting a format that can never be used is not.

Takes direct_state_access.vertex_arrays_* from 12 to 17 of 19 on both backends.
2026-08-05 02:16:32 +00:00
BZLZHH 6359b0002b [Feat] (MG_Impl, MG_State): implement the DSA vertex array queries
glGetVertexArrayiv, glGetVertexArrayIndexediv and glGetVertexArrayIndexed64iv
were stubs, so nothing could read a vertex array's state without binding it
first -- the exact thing direct state access exists to avoid.

They read the state the vertex array already holds. Two accessors were needed for
that: the relative offset and the binding points, which are the binding-point
view the flat per-attribute state was resolved from and cannot be reconstructed
from the resolved form.

Note the index means different things by entry point: for the 32-bit indexed
query it is an attribute, but GL_VERTEX_BINDING_OFFSET names a vertex buffer
binding point directly (GL 4.6 core 10.3.1). GL_VERTEX_ATTRIB_ARRAY_LONG is
answered GL_FALSE throughout, which is honest while 64-bit vertex attributes are
unsupported.

Takes direct_state_access.vertex_arrays_* from 8 to 12 of 19 on Espryt.
GL_VERTEX_BINDING_OFFSET still reads back 0: the query is right but the offset is
not reaching the binding point, which is a separate defect further up.
2026-08-04 21:16:59 -04:00
BZLZHH c186f5f255 [Feat] (MG_Impl): implement glCreateQueries and stop treating a reserved name as a query
glGenQueries only reserves names; a name becomes a query object when it is first
used with BeginQuery or QueryCounter (GL 4.6 core 4.2.1). MobileGL created the
live object eagerly at glGenQueries time and glIsQuery reported every reserved
name as an object, with a comment noting the shortcut.

The registry already distinguished the two states -- a target of 0 means the name
has never been used -- so glIsQuery now consults it, and a name that came from
glCreateQueries carries a flag saying it is an object regardless.

glCreateQueries itself was a stub. It creates the objects outright with their
target already fixed, which is the whole point of the DSA form: there is no
binding step to infer the target from later.
2026-08-04 21:07:18 -04:00
BZLZHH 3d97f6fa8f [Fix] (DirectVulkan): decline a draw with no usable fallback instead of aborting
GetFallbackTexture asserted that the target was 2D or rectangle, so a sampler
whose texture could not be resolved took the process down whenever it was any
other kind. A multisample sampler reaches exactly that path: its texture is
reported incomplete, the resolve falls back, and the assert fires. Sixty
direct_state_access multisample cases died that way, and because the abort kills
the whole process the harness lost the rest of its chunk with them -- one run
needed 63 invocations to get through the suite instead of 3.

The fallback is a single-sampled 2D image, so it genuinely cannot stand in for a
multisample sampler: that descriptor demands a multisample view, and binding this
one is invalid usage rather than a degraded picture. So report that no fallback
exists and let the caller decline the draw. An unbound or incomplete sampler is
an application-level mistake with a defined GL meaning; it is never a reason to
abort.

The cases still fail -- multisample textures are not yet complete enough to
sample -- but they fail as one reported case each.
2026-08-04 21:00:13 -04:00
BZLZHH bb582203d9 [Feat] (MG_Impl, MG_State, MG_Util): attach a buffer texture to a range of its buffer
glTexBufferRange, glTextureBuffer and glTextureBufferRange were all stubs, so a
buffer texture could only ever be attached through glTexBuffer -- by binding, and
always to the whole buffer.

Give the buffer texture the window it is supposed to address. The non-range forms
record it as offset 0 with a whole-buffer sentinel rather than the size the buffer
happens to have, so a later respecify keeps being followed instead of freezing the
texture at yesterday's size. All four entry points now share one attach path,
differing only in how they name the texture: by binding for the target forms, by
name for the DSA ones.

Both backends honour the window: DirectVulkan offsets and clamps the buffer view,
DirectGLES uses glTexBufferRange when the texture names a sub-range and keeps
plain glTexBuffer for the whole-buffer case, which also works on a driver without
the range entry point.

GL_TEXTURE_BUFFER_OFFSET_ALIGNMENT reported 0 with a comment explaining that the
range entry points were stubbed. It now reports what the device actually requires
-- minTexelBufferOffsetAlignment on Vulkan, the driver's own value on GLES -- and
the range entry points enforce it. Zero was never a legal answer; the minimum is
1, and an application that trusted it would have built unaligned offsets.
2026-08-04 20:53:53 -04:00
BZLZHH f39e6eb82d [Feat] (MG_Impl): implement glReadnPixels
It was exported as a stub: it logged a warning and returned, leaving the caller's
buffer untouched. Anything reading back through it saw whatever the destination
already held, which for a freshly allocated vector is zeros -- so every
direct_state_access texture test comparing a readback against reference data
failed without a GL error to explain it.

glReadnPixels is glReadPixels with a bound on how much it may write (GL 4.6 core
18.2.8, originally GL_ARB_robustness) and is identical in every other respect, so
it validates and reads through exactly the same path once the destination is
known to be big enough.

Sizing the read honours the GL_PACK_* state: rows are padded to GL_PACK_ALIGNMENT
and laid out GL_PACK_ROW_LENGTH wide, with the skip parameters offsetting the
first texel. The last row is deliberately not padded -- nothing follows it to
align -- which is what makes a tightly-sized destination legal.
2026-08-04 20:33:14 -04:00
BZLZHH cb2ba71feb [Feat] (DirectVulkan): run the tessellation stages
The backend already turned a tessellation control/evaluation shader into the
right VkShaderStage, but nothing downstream knew what to do with it: GL_PATCHES
had no topology, so it fell through to the triangle-list default, and the
pipeline carried no tessellation state at all. A GL_PATCHES draw therefore ran
the vertex and fragment stages over raw triangles.

Map GL_PATCHES to VK_PRIMITIVE_TOPOLOGY_PATCH_LIST, carry GL_PATCH_VERTICES into
the pipeline as patchControlPoints (part of the key, since two patch sizes are
two pipelines), attach VkPipelineTessellationStateCreateInfo for a patch topology
only, and enable the tessellationShader device feature.

POST reports the feature, because without it a program with a tessellation stage
cannot build a pipeline at all and GL_PATCHES draws render nothing.
2026-08-04 20:03:24 -04:00
BZLZHH 6ea7ccdf64 [Feat] (DirectVulkan): support an arbitrary primitive restart index
Vulkan restarts only on the fixed all-ones value of the index type, so
GL_PRIMITIVE_RESTART with a glPrimitiveRestartIndex of anything else used to
hard-fail the draw. GL_PRIMITIVE_RESTART_FIXED_INDEX already matches Vulkan and
is untouched.

Rewrite the indices into a transient copy instead, substituting the fixed value
for the application's. An index that already equals the fixed value would then be
indistinguishable from a restart, so it is nudged down by one: it can only be a
real index, since the application's restart index is a different number, and the
vertex it names is outside any well-defined draw -- whereas leaving it alone would
tear the primitive in two.

The element array buffer is rewritten whole rather than only the drawn range,
because an indirect draw's firstIndex lives in GPU memory and cannot be adjusted
from here; every element therefore keeps its position.
2026-08-04 20:00:17 -04:00
BZLZHH 14605723f0 [Fix] (DirectVulkan): flag a transform feedback capture as a GPU write
A capture is a GPU write like any shader's, so a later CPU read of the buffer has
to wait for it. Only shader storage buffers were flagged, so mapping or reading
back a capture buffer could observe whatever the queue had retired so far.

Nothing needs copying -- the capture writes land in coherent host-visible storage
already -- but coherence only says the writes are visible once they have
happened, which is exactly what MarkGpuWritten arranges through the readback op.
2026-08-04 19:56:28 -04:00
BZLZHH a680611c9f [Fix] (DirectVulkan): never stream a buffer whose storage the application holds
AcquirePersistentMap promises the storage it creates is never recreated, because
the frontend adopts it in place of the shadow and hands out pointers into it.
AcquireStreamedSlice broke that promise: its downgrade path releases the resident
storage unconditionally to avoid keeping a second stale copy, so binding such a
buffer as a vertex or index source freed the memory the application was still
pointing at.

It also fed that draw the wrong bytes. The streaming copy is uploaded from the
shadow, and a persistently mapped buffer can hold bytes the shadow never saw -- a
transform feedback capture writes straight into the resident storage. The next
capture into the same buffer then landed in freshly recreated storage while the
application kept reading the original, which is how the ping-pong in
transform_feedback.draw_xfb_feedbackk_test stalled after its first doubling.

Route a persistently mapped resource to the resident path instead, where its
single piece of storage is bound directly.
2026-08-04 19:56:28 -04:00
BZLZHH 93224ca406 [Fix] (DirectVulkan): make transform feedback writes visible to what reads them
GL makes transform feedback results visible to every later command on their own,
with no glMemoryBarrier in between -- unlike shader storage writes. An
application replaying a capture with glDrawTransformFeedback is therefore
entitled to the captured bytes without asking for them, so the barrier the Vulkan
memory model requires has to come from here.

It cannot be recorded where the write happens: the capturing draw runs inside a
render pass that declares no self-dependency. Flag it there instead and emit the
barrier at the next point that could read the buffer -- the following draw's
setup, or a readback -- ending the render pass first, the same shape
glMemoryBarrier already uses.

The destination covers every way a captured buffer comes back: replayed as vertex
attributes or indices, read through a uniform or storage binding, sourced as an
indirect command, copied out, or mapped.
2026-08-04 19:47:39 -04:00
BZLZHH fbed4485b7 [Fix] (DirectVulkan): key the program cache on the transform feedback capture layout
The program cache is content-hash-shared across GL program names, so its key has
to cover everything that changes the modules it stores. The capture layout did
not: XfbCaptureDecoratePass bakes XfbBuffer/XfbStride/Offset into the SPIR-V from
the frontend's layout, none of which is in the SPIR-V being hashed.

Two programs with identical shaders and different glTransformFeedbackVaryings
therefore shared one entry, and the first one linked decided how both captured.
That is precisely what changing the buffer mode does -- the same varyings
recorded with GL_SEPARATE_ATTRIBS instead of GL_INTERLEAVED_ATTRIBS -- so the
separate-attribs pass of transform_feedback.draw_xfb_test replayed a capture that
was still interleaved into buffer 0.

Hash the captured varyings' names, buffer indices and offsets plus the per-buffer
strides, and only for a capturing compile, so no other program changes key.
2026-08-04 19:47:39 -04:00
BZLZHH 90ae0f048c [Fix] (MG_Impl): answer the GL_UNIFORM program interface from the frontend reflection
The GL_UNIFORM interface queries and glGetActiveUniform(s)iv describe the same
set of resources in two spellings, but they were reading it from two different
places: the latter from the frontend reflection, the former forwarded straight
to the backend program.

The backend program is not a source of truth for this. It does not exist at all
for a program whose types its shading language cannot express -- a
double-precision uniform has no ESSL form, so the program never links there --
and the interface queries then described a program with no uniforms, which is
how gpu_shader_fp64.fp64.state_query failed.

Route GL_ACTIVE_RESOURCES / GL_MAX_NAME_LENGTH, the resource index, the resource
name and the resource properties for GL_UNIFORM through the same reflection that
already answers glGetActiveUniformsiv, so the two spellings can no longer
disagree and neither depends on the backend having linked. The props that
reflection does not model (GL_ATOMIC_COUNTER_BUFFER_INDEX and the
GL_REFERENCED_BY_* stage bits) still come from the backend, looked up by the
uniform's name so the two index spaces do not have to agree.

GL_MAX_NAME_LENGTH counts the terminator; the stored maximum does not, as every
other caller of GetUniformMaxLength() already accounted for.
2026-08-04 19:36:49 -04:00
BZLZHH cff959b2e8 [Feat] (DirectVulkan, MG_Util): honour a glVertexAttribDivisor other than 1
Vulkan's VK_VERTEX_INPUT_RATE_INSTANCE advances an attribute once per instance and has
no way to say anything else, so every non-zero divisor collapsed to 1: an attribute the
application asked to change every three instances changed every one, and
KHR-GL40.draw_indirect.basic-drawArrays-instancing and its elements sibling drew the
wrong colours from instance one onward.

VK_EXT_vertex_attribute_divisor is exactly this state, so it is enabled when the device
has it and the per-binding divisors ride into the pipeline through
VkPipelineVertexInputDivisorStateCreateInfoEXT. Only divisors other than 1 are listed -
1 is what the plain input rate already means - and they join the layout hash, so two
layouts that differ only in a divisor no longer share a pipeline.

POST reports the feature either way, because without it the failure is silent and looks
like a shader bug: the attribute is fetched, just from the wrong instance. The GLES side
gains the two checks this session's other work made load-bearing for the same reason -
glPatchParameteri (without it GL_PATCH_VERTICES stays at the driver's 3 and a patch draw
of any other size renders nothing) and the transform feedback object entry points
(without them a second object cannot open a capture while the first is paused).

KHR-GL40.draw_indirect on Magma: 70/70 but for the arbitrary primitive-restart index,
which Vulkan cannot express at all.
2026-08-04 19:25:32 -04:00
BZLZHH a50b2c422b [Fix] (DirectVulkan): submit a generated mip chain before a later upload can overtake it
Texture uploads go out on a command buffer of their own the moment they happen, while
glGenerateMipmap records its blit chain into the frame's command buffer, which is not
submitted until the frame ends. So a glTexSubImage2D into a level that was just
generated reached the GPU FIRST and the blits then wrote over it.

KHR-GL40.texture_gather.base-level does exactly that - generates the chain, then writes
the texels it is going to sample into level 1 and points TEXTURE_BASE_LEVEL at it - and
read back the generated content instead of what it had written. The image view, the mip
range and the upload itself were all correct; only their order on the GPU was not.

This is the same hazard the mip-chain-growth recreate above already flushes for, from
the other side: there the recorded work had to reach the GPU before an out-of-band copy
read the image, here before an out-of-band copy writes it. Submitting at the end of the
generation orders every upload that can follow.
2026-08-04 19:18:03 -04:00
BZLZHH 9dcda82d71 [Fix] (DirectVulkan): advertise GL_ARB_get_program_binary on Magma too
The extension and its three entry points are frontend state - no binary format is
exposed on either backend - but only DirectGLES listed it, so on Magma dEQP's loader
still left glProgramParameteri null and KHR-GL40.api.coverage called straight through
the null pointer. The entry point is not core before GL 4.1; this is what exposes it.
2026-08-04 19:10:40 -04:00
BZLZHH 28d0af6f04 [Feat] (MG_Util, DirectGLES, DirectVulkan): normalize rectangle coordinates in the module
Neither target API has GL_TEXTURE_RECTANGLE: ESSL has no rectangle sampler, and
Vulkan's SPIR-V environment does not allow Dim::Rect. Both emulate it on a plain 2D
texture, and the two differ in exactly one way - a rectangle lookup addresses texels
where a 2D one addresses [0,1].

That one difference now lives in one SPIR-V pass, so neither backend has to know about
it: every lookup taking normalized coordinates gets its coordinate divided by the size
the texture reports, and the image type is then rewritten to 2D. Magma had no rectangle
handling at all - it fed Dim::Rect straight to Vulkan, which read the texel coordinates
as normalized and sampled the edge, so all fifteen KHR-GL40.texture_gather.*-2drect
cases came back holding the clear colour.

This replaces the ESSL text rewrite that did the same divide for DirectGLES only. Doing
it in the module instead is both shorter and stricter: the pass resolves an operation's
image type through the sampled-image and pointer wrappers rather than matching a
sampler name in generated source, so it cannot be fooled by an expression where it
expected an identifier, and it needs no help from the frontend reflection to know which
samplers were rectangles.

Still declined, as before: the Dref *sample* forms, whose coordinate carries the compare
value in its last component, and the projective ones, where the divide would have to
happen after the perspective divide. texelFetch is deliberately untouched - integer
texel coordinates mean the same thing on both targets.

KHR-GL40.texture_gather: Magma 66 failures -> 2, Espryt stays at 75/75.
2026-08-04 13:25:40 -04:00
BZLZHH 44ee6b66b3 [Fix] (MG_State, DirectVulkan): apply the incomplete-texture rule on Magma too
The completeness rule itself is GL's, not a backend's, so it now reads as one question
both backends ask - SamplesAsIncompleteTexture(texture, effective sampler) - and each
answers in whatever way it already expresses "nothing is bound at this sampler".
DirectGLES leaves the native target unbound; Magma has a fallback texture for exactly
that case and now routes an incomplete texture to it.

The fallback's texel had never been written, so it read whatever its freshly allocated
storage held. GL is specific here: an incomplete texture - and a sampler with nothing
bound - reads (0, 0, 0, 1). It says so now, which is what makes
KHR-GL40.texture_gather.incomplete-texture-last-comp (it gathers the alpha) meaningful
rather than accidentally right.
2026-08-04 13:14:36 -04:00
BZLZHH 28c3cfc1d6 [Fix] (DirectVulkan, MG_State): make a shader-written storage buffer readable on Magma
Reading a buffer a compute shader wrote gave zeros: the frontend shadow that MapBuffer
resolves against is only maintained by uploads, and Magma had no path back. Every
KHR-GL40.texture_gather case ends by dispatching a compute shader into an SSBO and
comparing the mapped result, so 66 of 75 failed on it.

Magma needs no readback: EnsureGpuResidentStorage - the same host-visible coherent
adoption the transform feedback capture already uses - makes the shadow BE the memory
the shader writes, so binding a buffer as a shader storage buffer now adopts it. What
coherence does not give is ordering: the writes are visible once they have happened,
and the CPU was reading before the dispatch had retired. The readback op therefore
submits the recorded work and waits.

That exposed a mistake in the frontend flag this rides on: MarkGpuWritten skipped
GPU-resident buffers, reasoning there was no shadow to refresh. True, but the wait is
still needed - "reconcile with the GPU write" is not always "copy it back", and which
of the two it is belongs to the backend. The flag now only says a write is outstanding;
DirectGLES's readback still skips its persistent-mapped buffers when copying.

KHR-GL40.texture_gather on Magma: 66 failures -> 19 (the rest are rectangle textures,
mipmap completeness and tessellation, all still to do). Espryt stays at 75/75.
2026-08-04 11:55:17 -04:00
BZLZHH 38e04eefae [Fix] (DirectVulkan): size the indirect draw command by GL's struct, not the renderer's
The indirect draw paths bounded their read out of GL_DRAW_INDIRECT_BUFFER - and took
their default stride - from `sizeof(DrawCmdParam)`, this renderer's own draw-parameter
struct. That is not the command GL defines: DrawCmdParam carries two extra members for
bounding vertex-stream conversion and is 24 bytes, where GL's DrawArraysIndirectCommand
is four uint32.

So every glDrawArraysIndirect against a tightly-sized indirect buffer - which is what an
application writes, and what the CTS writes - failed the range check and drew nothing.
It went unnoticed on the elements side only by coincidence: DrawIndexedCmdParam happens
to be exactly the 20 bytes of DrawElementsIndirectCommand.

Both sizes are now named constants of GL's own layout.

KHR-GL40.draw_indirect on Magma: 21 failures -> 3.
2026-08-04 11:47:35 -04:00
BZLZHH fd29cb914e [Fix] (DirectVulkan, MG_State): give each transform feedback object its own capture counters
The frontend half of ARB_transform_feedback2 landed for both backends, but Magma's
capture was still written for the one implicit span GL 3.3 has:

- A paused span kept capturing. VK_EXT_transform_feedback's counter buffers already
  make consecutive draws append, so pausing is simply "do not wrap this draw" - the
  counters keep their values and the next resumed draw carries on where the last
  captured one stopped.
- Those counter buffers were context-wide. Transform feedback objects can each hold an
  open, paused span at the same time - KHR-GL40.transform_feedback.draw_xfb_test keeps
  three - and they were all appending through one set of four slots. Each object now
  gets its own group, handed out on first use; past sixteen objects they share group 0,
  which only matters for concurrently-paused spans.
- The generation that identifies a span is what a backend keys its append state on, so
  it is now part of the per-object state the frontend saves and restores. Without that,
  resuming an object that was paused before another one began looked like a new span
  and restarted its counters at zero.

GL_PRIMITIVES_GENERATED needed one more thing. It counts what the last vertex
processing stage emitted whether or not anything is being captured, but
VK_QUERY_TYPE_TRANSFORM_FEEDBACK_STREAM_EXT only counts what the capture saw - so a
draw made while the span was paused is invisible to it. The frontend now tallies those
draws, and the Vulkan query adds the delta at result time. The correction lives in the
backend that needs it: an ES driver's GL_PRIMITIVES_GENERATED counts them by itself, and
adding it there too would double them.

transform_feedback* on Magma: 4 failures -> 3. Espryt stays at 38/38.
2026-08-04 11:42:44 -04:00
BZLZHH 38497174c8 [Feat] (MG_Impl): implement the double-precision uniform state
glUniform*d, glUniformMatrix*dv, their glProgramUniform twins and glGetUniformdv were
all stubs - 35 entry points - so a GL 4.0 program's double uniforms could be declared
and located but never set or read. Worse, glGetUniformfv on one did reach the storage:
the generic getter memcpy'd the uniform's declared size into the caller's buffer, so a
4-byte float pointer received 8 bytes. That overrun is what took the process down in
KHR-GL40.gpu_shader_fp64.fp64.state_query.

The upload path is already templated on the component type, so the vector forms are
wiring. A matrix is not: the column stride the linker used for a double matrix is not
the 16 bytes a float one gets. It is not guessed - the slot the uniform was given is
exactly `columns` columns wide, so dividing states the stride the rest of the pipeline
already agreed on, for both the upload and the readback.

The four getters now convert instead of reinterpreting when the uniform holds doubles,
following GL 4.6 core 7.6: round to nearest for the integer queries, and clamp into the
queried type's range so a negative double read through glGetUniformuiv is 0 rather than
its two's complement.

The case still fails one step further on, where it queries the same uniforms through
GL_ARB_program_interface_query: those calls are answered by the backend program, and an
fp64 shader has none - ESSL has no doubles, so it never links. Answering them from the
frontend reflection is a separate change.
2026-08-04 11:06:15 -04:00
BZLZHH b95fcb7bca [Feat] (MG_State, MG_Impl, DirectGLES): implement glPatchParameteri
GL_PATCH_VERTICES decides how many vertices one tessellation patch consumes, and
glPatchParameteri was a stub - so the value stayed at the driver's default of 3 no
matter what the application asked for. KHR-GL40.texture_gather.gather-tesselation-shader
sets it to 1 and then draws a single patch: with the request dropped the draw had too
few vertices for one patch, produced nothing at all, and the case read back the clear
colour.

The value is context state on both sides and ES 3.2 spells the entry point exactly the
same way, so it is stored in the render state (where glGetIntegerv(GL_PATCH_VERTICES)
now finds it) and forwarded. Validation needs the real bound, so GL_MAX_PATCH_VERTICES
and GL_MAX_TESS_GEN_LEVEL are probed off the host driver alongside the other limits and
answered from there too; the defaults are the GL 4.0 core minimums.

KHR-GL40.texture_gather is now 75/75.
2026-08-04 10:58:14 -04:00
BZLZHH 5fce287de5 [Fix] (DirectGLES): generate a three-channel float mip chain on the CPU
glGenerateMipmap requires the level-0 format to be colour-renderable, and ES has no
colour-renderable three-channel float format at all - so an ES driver rejects
GL_RGB16F and GL_RGB32F where every desktop driver accepts them, and the error was
forwarded to the application. KHR-GL40.texture_gather.plain-gather-float-2d-rgb and
its offset- sibling build their texture that way and fail on the leftover error alone.

The blit-based emulation already used for GL_R11F_G11F_B10F is no help: it renders
level n from level n-1, so it needs exactly the renderability that is missing. But a
format the driver cannot render into is a format nothing can have rendered into
either, which makes the frontend's own copy of the texels authoritative for precisely
these formats. So the chain is box-filtered there and the levels are marked dirty; the
backend sync that follows uploads them like any other texture data.

Deliberately narrow: only the two formats whose texels are a plain float array, and
only when they are what the texture actually holds. Every other format keeps the
driver's behaviour, error included.
2026-08-04 10:54:17 -04:00
BZLZHH ae6949e459 [Fix] (MG_State, DirectGLES): sample a mipmap-incomplete texture as black
A minification filter that reads the mip chain requires every level from the base down
to hold exactly half the previous one's size; a texture that does not is incomplete and
every lookup on it returns (0, 0, 0, 1) (GL 4.6 core 8.17). Nothing checked it.

The ES driver cannot catch this on MobileGL's behalf, which is why it has to be a
frontend rule here: the backend texture is immutable storage allocated from the level
set as it stood, so a level the application later redefined at a different size never
reaches the driver at all, and the ES texture stays complete. That is exactly what
KHR-GL40.texture_gather.incomplete-texture does - it redefines level 1 of a complete
chain as 1x1 - and it read the original contents back.

The check runs where the sampling bindings are established, and an incomplete texture
simply leaves its native target unbound: an unbound ES target samples as (0, 0, 0, 1),
which is the answer GL asks for, with no scratch texture to keep around.

An array texture's layer count is not one of the dimensions that halves, so the
comparison only shrinks the components that belong to the image itself - getting that
wrong turned eight *-2darray cases black.
2026-08-04 10:49:51 -04:00
BZLZHH 5437947240 [Feat] (DirectGLES, MG_Util): normalize the coordinates of a rectangle lookup
A rectangle texture is emulated on an ES 2D texture, and LowerRectImagesForEssl
rewrites the image type in the SPIR-V to match. That is exact only where the lookup
addresses texels directly, which is why the pass declined any module containing a
lookup that takes normalized coordinates - the whole KHR-GL40.texture_gather 2drect
set among them.

The missing half is one divide: a rectangle lookup's coordinate is in texels and the
2D lookup it becomes wants [0,1], so the coordinate has to be divided by the texture's
size. It goes in on the ESSL the transpiler produces, next to the LOD-bias emulation
that already rewrites lookup arguments there, and reads the size back with
textureSize() rather than plumbing a uniform down - the emulated texture is a real ES
2D texture, so the shader can ask it directly.

Only the forms whose argument 1 is the bare coordinate are rewritten - texture,
textureOffset and the three textureGather flavours, which covers the Dref gathers too
because those carry the compare value in a separate argument. texelFetch is
deliberately left alone: its coordinates are integer texels on both targets. The
SPIR-V pass keeps declining everything else, so a projective lookup or a Dref sample
(where the compare value rides in coord.z) still refuses the module instead of
producing something subtly wrong.

Which samplers were declared rectangle is no longer visible in the transpiled source -
they are plain sampler2D by then - so the names come from the frontend program's
reflection.
2026-08-04 10:38:01 -04:00
BZLZHH f38dbf018d [Fix] (MG_State): give a rectangle texture its own initial sampler state
Every texture object started from the shared defaults, which are the 2D ones:
TEXTURE_MIN_FILTER of NEAREST_MIPMAP_LINEAR and TEXTURE_WRAP_S/T of REPEAT. A
rectangle texture has no mip chain at all, so GL gives it a different initial state -
LINEAR and CLAMP_TO_EDGE (GL 4.6 core table 23.15) - and a mipmapped minification
filter is not even a legal value to set on one.

With the 2D default in place a rectangle texture was mipmap-incomplete the moment it
was created, and an application that (correctly) never touches the filters read
(0, 0, 0, 1) out of every lookup. That is what the eleven
KHR-GL40.texture_gather.*-2drect cases saw: they set only the wrap modes, because the
filters are already what a rectangle texture needs.
2026-08-04 10:37:46 -04:00
BZLZHH 2dcc15bb0e [Feat] (MG_Impl, DirectGLES): advertise GL_ARB_get_program_binary with no binary format
glProgramParameteri is not core before GL 4.1, so in the 4.0 context the CTS runs it
only exists through GL_ARB_get_program_binary or GL_ARB_separate_shader_objects.
MobileGL advertised neither, so dEQP's loader left the entry point null - and
KHR-GL40.api.coverage, which registers glProgramParameteri from GL 3.2 upwards, called
straight through the null pointer and took the process down.

GL_NUM_PROGRAM_BINARY_FORMATS was already 0, and the extension explicitly allows an
implementation to support no binary format at all; that is the honest state of things
here, since a MobileGL program is a glslang link plus a per-backend translation with no
serialised form. So the extension is advertised for what it really provides:
glProgramParameteri stores GL_PROGRAM_BINARY_RETRIEVABLE_HINT (reported back by
glGetProgramiv alongside a GL_PROGRAM_BINARY_LENGTH of zero), glGetProgramBinary is the
INVALID_OPERATION the spec requires when that length is zero, and glProgramBinary
rejects every format with INVALID_ENUM and leaves the program's LINK_STATUS false.

Applications that ask for a binary get the documented "no formats" answer and fall
back, which is what they already had to do - only now they can ask.
2026-08-04 10:27:23 -04:00
BZLZHH ff76af9df7 [Fix] (MG_State, MG_Impl): a transform feedback name is only an object once it is bound
glIsTransformFeedback answered GL_TRUE for any name glGenTransformFeedbacks had handed
out. A generated name is reserved but does not denote an object until the first
glBindTransformFeedback (GL 4.6 core 13.2.1) - the same rule the other object types
follow - and KHR-GL40.api.coverage checks exactly the window in between.

The two questions are now asked separately: whether a name may be bound or deleted
(reserved, which is what the delete and bind paths need) and whether it is an object
(reserved and bound at least once).
2026-08-04 10:27:23 -04:00
BZLZHH 76f37a18e6 [Feat] (MG_State, MG_Impl, DirectGLES): transform feedback objects, pause/resume and the special capture names
GL 4.0 folds ARB_transform_feedback2 and _3 into core, and neither existed:
glGenTransformFeedbacks, glBindTransformFeedback, glDeleteTransformFeedbacks,
glIsTransformFeedback, glPause/ResumeTransformFeedback, the whole
glDrawTransformFeedback family and glBegin/EndQueryIndexed were all stubs, and
gl_NextBuffer / gl_SkipComponents1..4 failed the link as "not an output of the vertex
stage". Seven KHR-GL40.transform_feedback* cases failed on it, three of them by
leaving a capture open at deinit and taking the process down.

Objects. The capture state and the indexed GL_TRANSFORM_FEEDBACK_BUFFER bindings are
object state, but the context keeps one live copy of both, which is what every
existing reader - each backend's per-draw sync, the drawing and getter paths - is
written against. Rather than teach all of them about objects, a bind saves the live
copy into the outgoing object and restores the incoming one's. Object 0 is the
default object and needs no seeding; operator[] materialises the rest on first touch.

Pause. A paused span captures nothing, and three rules key off that: a draw is exempt
from the capture primitive-mode match, it feeds PRIMITIVES_GENERATED but not
TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN, and glUseProgram is allowed again (that last
one was already refused for an active capture, correctly for GL 3.3, which has no
pause).

glDrawTransformFeedback replays the vertices the object captured in its last completed
span, recorded at End. "Has a completed span" is tracked separately from that count,
because a completed empty span draws nothing while an object that never ended one is
INVALID_OPERATION. Drawing from the object whose capture is currently open is
deliberately allowed - feeding a result straight into the next span is the point of
KHR-GL40.transform_feedback.draw_xfb_feedbackk_test.

DirectGLES gets a real driver object per frontend object. That is the only reason the
default one would not do: several objects can be paused at once, and a paused span
lives inside the driver's object. The deferred driver-side Begin (still needed - ES
wants the program current and the buffers bound) now also has to be held back while
the span is paused, or a pause taken before the first draw would open the span on that
draw and subject it to the primitive-mode rule it is exempt from.

Special names. gl_NextBuffer and gl_SkipComponents<n> are consumed during varying
resolution and never become varyings of their own, so they only move where the
following ones land - and stay out of the name list the backend declares on its own
driver. ES cannot express the resulting layout at all: it packs every captured varying
into one gap-free record. So when the layout has holes or spans several buffers,
DirectGLES captures into a scratch buffer bound in place of the application's, and
End distributes the records to the offsets GL asked for. Only the bytes a varying
occupies are written, which is exactly what makes the holes keep the contents the
application left there - the property KHR-GL40.transform_feedback3.skip_components
checks.

glBegin/EndQueryIndexed and glGetQueryIndexediv differ from the plain forms only in the
vertex stream they address, so they validate the index and forward. GL_MAX_VERTEX_STREAMS
stays at 1: multi-stream capture needs ARB_gpu_shader5 stream qualifiers that no ES
driver implements, and the CTS cases that need more than one stream check the limit and
skip.

KHR-GL40.transform_feedback, transform_feedback2 and transform_feedback3: 38/38.
2026-08-04 10:18:53 -04:00
BZLZHH 8d1a734c22 [Fix] (MG_State, MG_Impl): reject a draw mode the geometry stage cannot accept
A geometry shader declares the primitive type it consumes, and a draw may only present
a mode that decomposes into it - points for `points`, the three triangle modes for
`triangles`, and so on (GL 4.6 core 11.3.1). Anything else is GL_INVALID_OPERATION.
Nothing checked it, so KHR-GL40.draw_indirect.negative-gshIncompatible-arrays and
-elements drew points through a `layout(triangles) in` shader and got no error.

The program object had no notion of the geometry input primitive at all: glslang knows
it right after the link, so it is read off the geometry intermediate and kept as the
GL enum (this is also what GL_GEOMETRY_INPUT_TYPE would report). Resolved on every
link rather than only when transform feedback captures the stage, since every draw
consults it, and cleared with the rest of the link artifacts.

The check sits on the shared pre-draw gate next to the transform feedback primitive
rule, which is the same shape of constraint. GL_PATCHES is deliberately exempt: it is
the tessellation pipeline's input and has already become the tessellator's output
primitive by the time the geometry stage sees it.

draw_indirect is now at 70/70.
2026-08-04 09:55:36 -04:00
BZLZHH 7d215028fb [Fix] (MG_Impl): validate the draw mode and the indirect draw's command source
Two classes of draw-time error were never raised, which the KHR-GL40.draw_indirect
negative-* cases check one by one:

- `mode` was passed through unexamined, so glDrawArraysIndirect(GL_FLOAT, ...) reached
  the backend instead of raising GL_INVALID_ENUM. The check belongs on the shared
  pre-draw gate, so it now covers every draw entry point rather than just the indirect
  pair. Nothing that used to render stops rendering: a mode the frontend now rejects is
  a mode the backend driver was rejecting anyway, silently.
- The indirect commands read their arguments out of the buffer bound to
  GL_DRAW_INDIRECT_BUFFER, and all three of that source's preconditions were unchecked
  (GL 4.6 core 10.3.10): a 4-byte-aligned offset, a bound buffer at all, and enough room
  left in it for the whole 16- or 20-byte command. glDrawElementsIndirect also never
  validated its index type, which is the same accepted set as the rest of the
  DrawElements family.

Takes the group from 24 failures to 2 - both of the remaining ones are the geometry
shader input-primitive compatibility rule, which needs reflection the program object
does not keep yet.
2026-08-04 09:52:40 -04:00
BZLZHH 00534d8bbc [Fix] (MG_Impl): report the draw-indirect binding and the buffer access state
Three pieces of queryable buffer state were missing, all of them read by the
KHR-GL40.draw_indirect basic-binding-* and basic-buffer-* cases:

- GL_DRAW_INDIRECT_BUFFER_BINDING had no case in glGetIntegerv, so it raised
  GL_INVALID_ENUM and left the caller's variable untouched (the test read back its own
  -9999 sentinel). GL_DISPATCH_INDIRECT_BUFFER_BINDING right next to it was already
  handled; this is the same two lines against BufferTarget::DrawIndirect. Because
  glGetBooleanv/glGetFloatv/glGetDoublev all widen from the integer path, one case
  fixes all four getters.
- GL_BUFFER_ACCESS answered 0 for an unmapped buffer. Its initial value is
  GL_READ_WRITE and glUnmapBuffer restores it (GL 4.6 core table 6.2); 0 is not a legal
  value of that state at all, and the test threw on the unrecognised enum.
- GL_BUFFER_ACCESS_FLAGS was not implemented, so it fell through to the invalid-pname
  arm. It is the MapBufferRange bitfield verbatim, which the mapping access flags
  already hold in normalised form - glMapBuffer's access enum is converted on the way
  in - so it converts straight back out, and reads zero while unmapped.
2026-08-04 09:52:40 -04:00
BZLZHH d81a6a0998 [Fix] (MG_Impl): silently ignore program and shader name zero on delete
glDeleteProgram and glDeleteShader are the two entry points in the program/shader name
space where 0 is not "a name GL never handed out" but an explicit no-op: "if program is
zero, it is silently ignored" (GL 4.6 core 7.3, and 7.1 for shaders). Both went through
the shared name validator instead and recorded GL_INVALID_VALUE.

Only tests that never got as far as creating a program noticed, because they still run
their cleanup path: the five KHR-GL40.texture_gather.*-cube-array cases bail out of
Init with "GL_ARB_texture_cube_map_array not supported", then Cleanup deletes its
zero-initialised handles and the leftover error fails the case after the fact - the
downstream-error-misattribution shape. Every array-taking delete already skipped 0.
2026-08-04 09:52:40 -04:00
BZLZHH 9bf23d7ffd [Fix] (MG_State, DirectGLES): read a shader-written storage buffer back before mapping it
Buffer contents live in a CPU shadow that every read - MapBuffer, MapBufferRange,
GetBufferSubData, CopyBufferSubData - resolves against, and backend transfer ops only
ever push the shadow outwards. Two paths already knew the GPU can write a buffer on
its own and mirrored the result back by hand (ReadPixels into a pixel-pack buffer,
the transform feedback capture at EndTransformFeedback); a shader storage buffer
written by a draw or a dispatch had no such path at all, so the map handed the
application the bytes from before the dispatch.

Nothing exercised it until now because GL 3.3 has no compute stage. Every
KHR-GL40.texture_gather case ends by dispatching a compute shader that writes its
sampled texel into an SSBO and comparing the mapped result, and all 71 read back the
zero-filled shadow.

Adds the missing direction as a backend op: BufferObject::MarkGpuWritten flags a
buffer the GPU may have moved ahead of the shadow, SyncGpuWrites pulls it back at
every read point, and DirectGLES implements the readback with a plain read map of the
ES buffer. The flag is raised where the storage-buffer points are bound for the
upcoming draw or dispatch, which is the last moment the set of exposed buffers is
known, and cleared by the readback - so a buffer nothing writes costs one bool test
per map. Backends that cannot read their storage back leave the op null and keep
today's behaviour; a GPU-resident (coherent persistent) buffer needs nothing, since
its reads already resolve against the memory the shader wrote.

Drops the texture_gather failures from 71/75 to 25/75 with no crashes left.
2026-08-04 09:40:53 -04:00
BZLZHH 41e45f7d48 [Fix] (MG_Impl): let an indexed buffer bind reach the generic binding point too
BindBufferBase and BindBufferRange bind the buffer to the indexed point AND to the
generic binding point of the same target (GL 4.6 core 6.1.1); only the indexed half
was implemented. Applications lean on the second half constantly, because it is what
makes the set-up idiom work:

    glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 0, ssbo);
    glBufferData(GL_SHADER_STORAGE_BUFFER, size, nullptr, GL_DYNAMIC_DRAW);

With the generic point left at 0 the glBufferData raised GL_INVALID_OPERATION and
the buffer kept its zero size, so the later glMapBufferRange over it failed the
offset+length bound and returned nullptr. The whole KHR-GL40.texture_gather group
verifies its result through exactly that sequence and dereferences the map's return
value without checking it, so 51 of its 75 cases took the process down with a
SIGSEGV inside the test.

Unbinding propagates the same way: buffer 0 clears both points.
2026-08-04 09:40:28 -04:00
BZLZHH 3dc6a1b6db [Fix] (MG_Impl, DirectGLES): answer the texture-gather offset limit queries
glGetIntegerv(GL_MIN_PROGRAM_TEXTURE_GATHER_OFFSET) and its GL_MAX_ counterpart fell
through to the default arm of the getter and raised GL_INVALID_ENUM, leaving the
caller's variable untouched - KHR-GL40.texture_gather.api-enums read back the
uninitialised 32764 that happened to be on its stack and failed on the error alone.

Both are core state from GL 4.0 (table 23.53) and from ES 3.1 (table 20.40), so the
value is simply the host driver's, probed alongside the other limits in
FillInGLESCapabilities and carried to the getter through DynamicBackendParameters.
The probe result is widened to the -8/+7 core minimums rather than trusted blindly:
a driver that leaves the out-parameter alone (no ES 3.1, or an enum it ignores) would
otherwise hand us a range narrower than GL 4.0 requires MobileGL to advertise, and
the shaders the CTS builds assume the guaranteed range regardless.
2026-08-04 09:40:15 -04:00
BZLZHH 598c5497b0 [Fix] (DirectVulkan): submit pending work before growing a texture's mip chain
Sizing backings by their defined mip level count gave every level-0-only texture a
single-level image, and left growing it to the recreate-and-preserve path: the new
image is created and the old contents are carried over by a vkCmdCopyImage that
PreserveTextureContentsOnRecreate submits on its own command buffer and waits on
straight away.

Whatever the frame has already recorded into the old image has not been submitted
yet at that point, so that copy reads the texture as it stood before this frame's
writes. GenerateMipmap then descends the whole chain from a stale level 0, and the
composite pass that samples it renders a washed-out frame -
minecraft-1.21.4-fabric-iris-iterationt-in-world (Iris's mipmapped colour target,
the one texture in the trace that grows 1 -> 10 levels) came back at ssim 0.5699
against a 0.99 threshold.

This is the hazard the storage-usage upgrade already flushes for before its own
preserve-copy; growing the mip chain is simply the second trigger of that same
recreate, and it was added without the same ordering guarantee. Flush there too,
gated on a texture whose live image really does carry a short chain, so the submit
happens once per texture and only when a recreate is actually coming.

Keeps the single-level backing and its memory saving; ssim goes back to 0.9992.
2026-08-02 13:09:48 -04:00
BZLZHH 86c00bdf18 [Test] (MG_Test): catch the unit tests up with three deliberate behaviour changes
ctest -L unit had been failing 13 of its 418 cases, all of them tests left asserting
what the code did before a commit that changed it on purpose:

- "restore target GL version to 3.3" put the advertised target back after the
  experimental 4.6 run, but the two Voxy sanity tests still demanded 4.6. The
  extensions they really care about are all still advertised, so assert 3.3 and drop
  the now-meaningless AtExperimentalCTSVersion from their names.
- "support rectangle textures where the emulation is exact" made every desktop-only
  target supported - rectangle included, stored as a plain 2D - while the texture
  test still expected rectangle to be rejected.
- "keep declared modern GLSL versions strict" changed two things at once: a
  normalized legacy directive now carries a marker on its line, so the ten tests
  matching "#version 330 core\n" whole no longer match; and a version the
  application declared itself is no longer raised to 460, so the sources declaring
  330/400 keep their own number and only MobileGL's own normalization is retargeted.

Test expectations follow, rather than the implementation being bent back: each of
the three changes is the intended behaviour and is argued for where it was made. The
retry test now drives the 460 escalation from a legacy "#version 130" source, which
is the only thing that is still rescued, and gained a case pinning the other half of
that contract - an application-declared "#version 330" stays at 330.

418/418 unit tests pass.
2026-08-02 09:04:16 -04:00
BZLZHH 2f2f95498f [Fix] (MG_State): detach a deleted texture from the framebuffer that is bound
GL 3.3 core 4.4.2: deleting a texture whose image is attached to the framebuffer
currently bound acts as if FramebufferTexture* had been called with texture zero for
every attachment point it occupied there. Framebuffers that are not bound keep the
orphaned attachment, so only the bound ones are touched.

MobileGL unbound a deleted texture from every texture unit and image binding but
left framebuffer attachments alone, so the framebuffer went on holding the dead
texture alive as its attachment and reads through it returned that texture's
contents rather than those of whatever the application put in its place - and since
the deleted name usually comes straight back out of the next glGenTextures, the two
are indistinguishable from the outside.
2026-08-02 07:25:07 -04:00
BZLZHH 7105c2ebdc [Fix] (DirectGLES): never skip a framebuffer bind on a stale version snapshot
BindCurrentFBO returned early when the framebuffer binding slot's version matched
g_fboBindVersions - but nothing on that path ever writes that entry. Only
ForceBindCurrentFBO stamps it, so the comparison was against an arbitrarily old
snapshot, and any later slot version that happened to land on the same 16-bit value
read as "already bound". The driver was then left on whatever framebuffer it had
last been given.

That is how KHR-GL32.packed_pixels.varied_rectangle.rg8i_format_rg_integer read its
gradient back out of the previous subtest's framebuffer, seeing 18 where 127 was
expected. It only shows up after a few thousand cases have gone by - long enough for
the counter to come back around - which is why it reproduced exactly under one
caselist and not at all in isolation.

Drop the fast path. Skipping redundant work is BindFramebufferId's job: it shadows
the driver's own draw and read bindings and drops the glBindFramebuffer when the
target already holds that id, which is where the cost actually is. What is left here
is one registry lookup.

Takes GL32 to 100% conformance; GL30, GL31 and GL33 stay at 100%.
2026-08-02 07:24:59 -04:00
BZLZHH 13bab780f2 [Fix] (DirectGLES): gate the replicate blit's stencil pass on ES 3.1
Reading the stencil half of a packed depth/stencil texture goes through
GL_DEPTH_STENCIL_TEXTURE_MODE, which is ES 3.1 state. On an older driver the pname
would raise GL_INVALID_ENUM and the shader would go on sampling depth bits as if
they were stencil, so decline the emulation instead.
2026-08-02 04:55:05 -04:00
BZLZHH 027310f993 [Fix] (MG_Impl): ask whether a colour format is renderable per target
The framebuffer-completeness check scanned every row of the backend's
format-capability cache and called the format renderable if any target said so. That
was already loose, and it broke outright once DirectGLES started widening
three-channel formats so they stay renderable as multisample storage: the caveat
capability recorded for the multisample target made GL_RGB8_SNORM look renderable
everywhere, so an ordinary 2D GL_RGB8_SNORM texture attachment reported
GL_FRAMEBUFFER_COMPLETE while the driver's own framebuffer was
INCOMPLETE_ATTACHMENT.

KHR-GL3x.packed_pixels stopped skipping those formats and read a framebuffer that
could not be read, so all 18 of its rgb8_snorm cases got back an untouched buffer.

Pass the row the attachment actually lives in - the texture's target, or the
renderbuffer row - and consult only that one; a format is still asked about in
general when the caller has no target.
2026-08-02 04:54:48 -04:00
BZLZHH c741a938bc [Feat] (DirectGLES): emulate a depth/stencil blit into a multisample framebuffer
Desktop GL replicates the source sample into every destination sample when the read
framebuffer is single-sampled and the draw framebuffer is not. ES forbids the call
outright - "an INVALID_OPERATION error is generated if SAMPLE_BUFFERS for the draw
framebuffer is greater than zero" - so the blit did nothing at all, and every one of
KHR-GL3x.packed_depth_stencil.blit's replicate iterations verified a destination
that still held its clear values.

Emulate it by drawing a full-screen triangle into the multisample framebuffer: every
pixel is fully covered, so every sample of it receives the same value, which is
precisely the replicate rule. The source rectangle is first copied into a scratch
texture of its own format (both sides single-sampled, which ES does allow), then
depth is written through gl_FragDepth and stencil - which has no shader output on ES
- one bit plane at a time with REPLACE and a discard for the pixels whose source bit
is clear.

The draw runs inside the caller's framebuffer, so every piece of pipeline state it
touches is read back and restored, including the per-draw-buffer colour masks the
non-indexed glColorMask does not cover: the sync layer's shadow of the driver state
has to stay true across this.

Colour replicate is not emulated (it would need a sampler variant per component
type); it now says so instead of failing silently.
2026-08-02 04:34:25 -04:00
BZLZHH 01d0f01d13 [Fix] (DirectGLES): report the alpha added by the multisample widening as ONE
A three-channel format widened to four for a multisample target gains an alpha
channel the application never asked for, and it holds whatever the draw that filled
the texture happened to write there. GL says a format without alpha reads back as
1.0, so KHR-GL33.texture_swizzle - which fills such a texture by rendering
vec4(r, g, b, 0.0) and then swizzles red from alpha - read 0 where it expected the
maximum.

Fold ONE into the texture's swizzle for exactly those textures, composed with the
swizzle the application set, so the promotion stays invisible.
2026-08-02 04:25:08 -04:00
BZLZHH e45f7ae5d4 [Fix] (DirectGLES, MG_Util): keep 16-bit SNORM precision through the widening
GL_RGB16_SNORM widened to GL_RGBA16F to stay renderable as multisample storage, and
a half float's 11-bit mantissa cannot hold a 16-bit signed-normalized channel:
KHR-GL33.texture_swizzle's blue channel came back several units of 32767 away from
the value the reference computes, well outside its one-unit tolerance.

GL_EXT_render_snorm makes the signed-normalized formats colour-renderable on ES, so
widen to GL_RGBA16_SNORM instead wherever it and EXT_texture_norm16 are both
present, and only fall back to the half float otherwise. Threaded through as its own
normalize option so the capability probe and the runtime pick the same format, the
way every other driver-dependent substitution here is decided.
2026-08-02 04:24:23 -04:00
BZLZHH a687873d32 [Fix] (DirectGLES): probe format capabilities on the target ES stores them on
1D, 1D-array and rectangle textures are emulated on ES 2D and 2D-array targets, but
the capability probe kept asking the driver about the desktop-only target itself.
glTexImage2D(GL_TEXTURE_1D, ...) is not something an ES driver has ever accepted, so
those rows of the cache stayed empty - and an empty row reads as "nothing is known",
not as "the format needs help", so no fallback format was ever selected for them.

GL_DEPTH_COMPONENT32 on a 1D texture therefore went to the driver unchanged instead
of as GL_DEPTH_COMPONENT24, and the texture ended up with no storage
(KHR-GL33.texture_swizzle format_idx_65 on both 1D targets read the wrong value for
every pixel).

Probe the ES target the texture will actually live on, while still recording the
capabilities against the target the frontend asked for.
2026-08-02 04:18:20 -04:00
BZLZHH 43a43c1180 [Fix] (DirectGLES, MG_Util): raw framebuffer writes while GL_FRAMEBUFFER_SRGB is off
GLES core always encodes a fragment written into an sRGB colour attachment, and
offers no switch to stop it. Desktop GL has one, GL_FRAMEBUFFER_SRGB, and it starts
out disabled - so a GL application that never touches it expects its writes to land
raw. The frontend models exactly that (the capability reads as disabled and
DirectVulkan attaches the UNORM twin to honour it), but DirectGLES was passing the
draw straight to a driver that encodes anyway.

The value therefore came back one conversion short of the reference wherever it was
written and then read again: rendering into an sRGB texture and fetching it in a
shader decodes once but had encoded twice, which is how
KHR-GL32.texture_size_promotion read 0.0142 for GL_SRGB8_ALPHA8 where 0.00111 was
expected.

Detect GL_EXT_sRGB_write_control and sync GL_FRAMEBUFFER_SRGB from the frontend
capability alongside the other enables, starting from the driver's enabled state so
the first sync always pushes the disable down.
2026-08-02 04:10:13 -04:00
BZLZHH 65dbfa6f26 [Fix] (DirectGLES, MG_Util): widen three-channel formats for multisample textures
GLES has no colour-renderable three-channel format beyond RGB8, so
glTexStorage2DMultisample rejects GL_RGB16 (and the SNORM variants) with
GL_INVALID_ENUM and the texture is left with no storage at all - every draw into it
then hit GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT and every read came back zero.

The existing fallback machinery could not help: it picks one replacement format per
requested format, from the driver's capabilities, and never re-checks that
replacement against the target it is going to be used with. GL_RGB16's fallback is
GL_RGB32F, which is a perfectly legal ES texture format and a perfectly illegal
multisample storage format, and with EXT_texture_norm16 present no fallback was
selected at all.

Add PixelFormatNormalizeOptionBit::NoThreeChannelRenderTarget, applied only to
multisample targets, mapping GL_RGB16 to GL_RGBA32F and the three-channel SNORM
formats to GL_RGBA16F. Widening the channel count is safe precisely there and
nowhere else: a multisample texture can never be uploaded to, only rendered into, so
no transfer path has to expand three-channel client data, and the alpha a draw
writes for a three-channel source is already the 1.0 the frontend format implies.

The capability probe recomputes its fallback per target for the same reason, so the
probed format and the format the texture is actually created with stay in agreement.
2026-08-02 04:10:01 -04:00
BZLZHH 6de38c666c [Feat] (DirectGLES): support rectangle textures where the emulation is exact
ES has no rectangle target and no rectangle sampler, so DirectGLES declared
GL_TEXTURE_RECTANGLE unsupported outright: the texture was never synced or bound,
and SPIRV-Cross refused the shader ("Rectangle textures are not supported on
OpenGL ES") which left the whole program unlinkable.

A rectangle texture is a single-level, clamped 2D texture whose only real
difference is that its lookups take non-normalized coordinates. Where every use
takes *integer* texel coordinates - texelFetch, textureSize - that difference
does not exist at all, and the two are the same thing. So:

- A new SPIR-V pass rewrites Dim::Rect image types to Dim::2D before
  transpiling, and restates the rectangle capabilities as Shader. It declines
  any module containing a normalized-coordinate lookup rather than emitting
  something subtly wrong; SPIRV-Cross then rejects that module exactly as
  before, so nothing that used to work changes and nothing new renders wrongly.
- The target maps to GL_TEXTURE_2D for storage, uploads and binding, alongside
  the existing 1D and 1D-array emulation.

Fixes KHR-GL31.texture_size_promotion.functional outright, which takes GL31 to
100% conformance. GL32/GL33 advance past their rectangle cases to a separate
GL_RGB16 multisample issue. No regressions across texture_swizzle, shaders30,
texture_lod_*, framebuffer_blit, packed_depth_stencil, transform_feedback,
clip_distance or draw_buffers; DirectVulkan re-verified unaffected.
2026-08-02 01:56:22 -04:00
BZLZHH 9dff24f3e1 [Fix] (DirectGLES): never leave a stale program bound when the new one is broken
When a shader stage fails to transpile or compile, SyncToBackend logs it and
carries on, so the program is linked without that stage - or does not link at
all. Use() then issued glUseProgram for it, which is an INVALID_OPERATION for an
unlinked program and, crucially, leaves the *previous* program current. The draw
went ahead and rendered with an entirely unrelated shader.

That is how KHR-GL3x.texture_size_promotion's GL_TEXTURE_RECTANGLE cases
produced 1.0 for a red channel: SPIRV-Cross refuses sampler2DRect for ESSL
("Rectangle textures are not supported on OpenGL ES"), so every rectangle
program was broken, and the draws kept running the previous case's 1D-array
alpha shader - whose alpha is 1.0. Wrong pixels from a shader the app never
bound are far worse to debug than a blank result.

The program now records whether the last sync produced something usable, and
Use() binds 0 rather than the broken program, making the draw a visible no-op.
The redundancy cache tracks whatever was actually bound, so it stays correct
across the switch.

Does not fix the rectangle cases themselves - those need a SPIR-V pass lowering
Dim::Rect to Dim::2D before SPIRV-Cross runs (plus the coordinate divide for
non-texelFetch lookups), alongside mapping the target to GL_TEXTURE_2D.
2026-08-02 01:40:53 -04:00
BZLZHH 5a400e0297 Merge branch 'dev' of github.com:MobileGL-Dev/MobileGL into dev 2026-08-02 12:21:25 +08:00
BZLZHH b6a2bf08d4 [Fix] (DirectGLES): resolve an aliased texture unit by the sampler's type
Desktop GL_TEXTURE_1D/1D_ARRAY are emulated on ES GL_TEXTURE_2D/2D_ARRAY, so one
native binding serves two of a unit's frontend slots. An earlier fix settled the
real-versus-default case; two REAL textures can collide just as easily, and there
the slot iteration order decided it. KHR-GL3x.texture_size_promotion keeps its 1D
source texture and its 2D destination texture bound to the same unit, so the
shader sampled the render target it was drawing into instead of the source.

GL resolves this from the shader's sampler type, so ask the program: the
frontend's uniform reflection still carries the original GLSL type, which maps
straight back to the target the lookup means. Only consulted when a collision
actually happens, so an ordinary unit costs nothing, and the first binding
placed stands when the program gives no answer rather than being overwritten by
whichever slot happens to come last.

Also adds the read-colour clamp that goes with it: GL clamps a glReadPixels from
a fixed-point colour buffer to [0,1] (GL_CLAMP_READ_COLOR defaults to
GL_FIXED_ONLY), which ES has no equivalent for at all - a GL_R16_SNORM target
holding -0.125 read back unclamped. Applied to the wide rows before they are
repacked, for float, half, short and byte reads alike, and deliberately NOT for
glGetTexImage, which reaches the same helper through a scratch framebuffer but
is not subject to read-colour clamping.

texture_size_promotion now clears every 1D case (it stops at the first failure
and has moved on to GL_TEXTURE_RECTANGLE, which DirectGLES does not emulate at
all yet), and KHR-GL33.texture_swizzle's GL_DEPTH_COMPONENT32 1D cases pass.
DirectVulkan re-verified unchanged.
2026-08-01 16:21:28 -04:00
BZLZHH 6b2a2b5e00 [Fix] (MG_Util): emulate GL_DEPTH_COMPONENT32 with the 24-bit sized format
GL_DEPTH_COMPONENT32 has no ES equivalent. The previous commit routed it to
GL_DEPTH_COMPONENT32F, which gives the attachment storage but changes the
encoding: the transfer type has to become GL_FLOAT for ES to accept the store,
and the upload path hands over the caller's fixed-point GL_UNSIGNED_INT bytes
unchanged, so the texels came out as garbage.

GL_DEPTH_COMPONENT24 is the nearest sized ES format that keeps the same
fixed-point encoding, so GL_UNSIGNED_INT still describes the data and no
conversion is needed. Fixes KHR-GL33.texture_swizzle's GL_DEPTH_COMPONENT32
cases on the 2D and 2D-array targets; framebuffer_blit's GL_DEPTH_COMPONENT32
config still passes, since the depth values it compares are exactly
representable in 24 bits.

(The 1D and 1D-array targets still fail, but for the separate desktop-1D-on-ES
emulation reason that also holds back texture_size_promotion.)
2026-08-01 14:59:19 -04:00
BZLZHH 512c857f18 [Fix] (DirectGLES): emulate a format-converting multisample resolve blit
ES rejects any blit out of a multisample read framebuffer whose format differs
from the draw framebuffer's. Desktop GL only requires identical formats when
BOTH framebuffers are multisampled - a multisample resolve into a single-sample
target is allowed to convert on the way out, and KHR-GL3x.framebuffer_blit
resolves an R8 multisample texture straight into the RGBA8 default framebuffer.
The forwarded blit failed with GL_INVALID_OPERATION, and since the driver's
error never reaches the frontend error queue the caller saw a successful call
that had written nothing.

Retried in two steps when the first blit fails and the read framebuffer really
is the multisampled one: resolve into a scratch renderbuffer of the source's own
format, then run the caller's blit from there - single-sample on both sides,
which is exactly where ES does allow the conversion. The scratch buffer is
cached and grown on demand, keyed on the source format and dropped with its ES
context. Only reached on the failure path, so an ordinary blit is untouched.

KHR-GL3{0,1,2,3}.framebuffer_blit is now 3/3 on all four versions; DirectVulkan
(lavapipe) re-verified at 3/3 as well.
2026-08-01 14:37:58 -04:00
BZLZHH 9f3cac6691 [Fix] (DirectGLES): report distinct depth/stencil framebuffers as unsupported
GL only requires framebuffers whose depth and stencil attachments refer to the
same image; anything else may be answered GL_FRAMEBUFFER_UNSUPPORTED, and both
backends' real targets do exactly that - DirectVulkan cannot form two separate
attachments at all, and the ES drivers behind DirectGLES return UNSUPPORTED for
a separate depth renderbuffer plus stencil renderbuffer.

The frontend already knew how to detect the configuration, but only consulted it
for DirectVulkan. On DirectGLES it answered GL_FRAMEBUFFER_COMPLETE for a
framebuffer the driver had rejected, so every clear and draw against it was
silently dropped and the results read back as zeros - which is what
KHR-GL3x.packed_depth_stencil.verify_mixed_attachments saw. (That test
explicitly tolerates GL_FRAMEBUFFER_UNSUPPORTED; what it cannot survive is being
told the framebuffer works.)

Turned into a backend capability rather than a backend-type check, probed once
at init from a scratch framebuffer the same way the format-capability cache is,
so a driver that does support the configuration keeps using it. Defaults to
supported, leaving any backend that does not set it on the permissive path.

Fixes KHR-GL3{2,3}.packed_depth_stencil.verify_mixed_attachments for both
formats; DirectVulkan re-verified unchanged at 23/25 pass + 2 not-supported.
2026-08-01 14:05:28 -04:00
BZLZHH 4c7332d5e6 [Fix] (DirectGLES): broadcast legacy gl_FragColor to every draw buffer
Legacy GLSL's gl_FragColor goes to every enabled draw buffer (GL 4.6 15.2.3),
but ShaderSourceProcessor lowers it to a single mg_FragColor output, which only
ever reaches draw buffer 0. Everything past the first attachment kept its
pre-draw contents.

Replicated across the enabled draw buffers with copies at the end of main.
Gated on the count so the ordinary single-target shader is byte-for-byte what it
was: the pass is a no-op below two draw buffers, and the count comes from the
frontend draw framebuffer at program-sync time (not from the backend framebuffer
sync, which only runs later in PrepareForDraw - a program compiled against a
stale count would not be relinked until the draw after the one that needed it).
It joins the snorm/unorm clamp masks as framebuffer state the shader is compiled
against, with the same relink-on-change check.

Also advertises GL_ARB_explicit_attrib_location and GL_ARB_texture_multisample,
which DirectGLES implements for every version it advertises but only listed for
DirectVulkan. Both are core from GL 3.2/3.3 on, so an app targeting 3.0/3.1
reaches them only through the extension string - without the former the CTS
picks an entirely different draw_buffers shader, and without the latter
KHR-GL31.texture_size_promotion.functional crashed outright.

KHR-GL3{0,1,2,3}.draw_buffers.draw_buffers_1 now passes on all four versions,
and texture_size_promotion.functional on GL31 downgrades from a crash to a
(still open) comparison failure.
2026-08-01 13:59:11 -04:00
BZLZHH 1c5f6c0986 [Chore] (tools/cts): pick a run config the suite does not contradict
Two harness settings were producing failures that say nothing about the backend:

- dEQP's FboRenderContext picks the first entry of its own depth/stencil format
  list, GL_DEPTH32F_STENCIL8, when the config leaves the bit counts DONT_CARE.
  framebuffer_blit meanwhile hardcodes GL_DEPTH24_STENCIL8 for its own buffers
  as soon as it detects an FBO surface, and then blits depth between the two -
  which the spec forbids for mismatched formats, so a conformant driver has no
  choice but to fail it. Default to --deqp-gl-config-name=rgba8888d24s8 so the
  wrapper framebuffer and the test agree.

- --deqp-watchdog aborts the whole process when one case exceeds a hardcoded 30
  seconds (framework/common/tcuApp.hpp). That is not a hang on a CPU rasterizer:
  several texture_swizzle cases take ~17s each standalone and cross the limit
  once the process is warm, which came back as ten spurious Timeouts. dEQP's own
  default is off, and --chunk-timeout is what actually rescues a genuinely
  wedged case, so default it off too and leave it selectable.
2026-08-01 13:48:58 -04:00
BZLZHH 8b75628dec [Fix] (DirectGLES): depth/stencil clear value and readback gaps
Three separate holes, all of them silent, that KHR-GL3x.framebuffer_blit walks
straight into because it clears and reads back depth and stencil directly:

- glClearStencil was frontend-only. The value was recorded in render state and
  never synced, so the real driver kept its default of 0 and every
  glClear(GL_STENCIL_BUFFER_BIT) wrote zeros. glClearColor and glClearDepthf
  were already synced right next to it.

- Stencil readback assumed GL_STENCIL_INDEX works. It is not part of core ES
  (it needs GL_NV_read_stencil) and a driver without it rejects the read
  outright, which left the caller's buffer untouched. Where the attachment is a
  combined depth-stencil buffer the packed GL_DEPTH_STENCIL read carries the
  same bytes in its low octet, so that is now the fallback; the widening to
  GL_UNSIGNED_SHORT/INT moved into the same helper, since even a byte-for-byte
  read needs it.

- Depth readback always went through GL_UNSIGNED_INT. A floating-point depth
  attachment (GL_DEPTH_COMPONENT32F, GL_DEPTH32F_STENCIL8 - the latter is what
  dEQP's own fbo-surface-type wrapper framebuffer picks) rejects that with
  GL_INVALID_OPERATION and only reads back as GL_FLOAT. Try both.

And one format gap behind the same test: GL_DEPTH_COMPONENT32 has no ES
equivalent and was being normalized to the *unsized* GL_DEPTH_COMPONENT base
format, which is not a legal glTexStorage/glRenderbufferStorage internal format
there - the attachment ended up with no storage and the framebuffer read back as
incomplete. GL_DEPTH_COMPONENT32F is the sized ES format that keeps the
requested 32-bit depth footprint; the transfer type follows it to GL_FLOAT.

Takes KHR-GL3x.framebuffer_blit from 0/3 to 2/3 (the remaining
multisampled_to_singlesampled_blit_color_config_test is a separate
single-channel MSAA resolve issue). Note that scissor_blit additionally needs
the suite to run with a depth/stencil config the test agrees with
(--deqp-gl-config-name=rgba8888d24s8): under FBO surfaces the test hardcodes
GL_DEPTH24_STENCIL8 for its own buffers while dEQP's wrapper framebuffer
defaults to GL_DEPTH32F_STENCIL8, and blitting depth between mismatched formats
is a spec error that any conformant driver has to report.
2026-08-01 13:24:30 -04:00
BZLZHH 8269a1786f [Feat] (DirectGLES): emulate GL_TEXTURE_LOD_BIAS in the transpiled ESSL
ES has no per-texture or per-sampler LOD bias at all - GL_TEXTURE_LOD_BIAS is
desktop only, and Vulkan spells it VkSamplerCreateInfo::mipLodBias, which is why
DirectVulkan already honours it. DirectGLES stored the value in sampler state
and then dropped it, so every lookup sampled at the unbiased level of detail.

The bias now reaches the shader as a uniform: a new SPIRV-Cross post-pass
declares one `uniform highp float mg_lodBias_<sampler>;` per mip-capable sampler
and folds it into the level of detail of every lookup that has somewhere to put
it - appended as the bias argument, added to an existing bias, or added to an
explicit textureLod level (Vulkan applies mipLodBias to explicit-LOD fetches too,
and the CTS reference expects the same). texelFetch/textureGather have no bias
by definition, textureGrad offers no argument to fold one into, and the
array-shadow lookups have no bias overload in GLSL at all, so all of those are
left alone. Draws push the bound texture's (or the bound sampler object's, which
overrides it as in GL) value into the uniform, and only when it changed - a
shader whose samplers all have a zero bias issues no extra call at all.

Fixes KHR-GL3{0,2,3}.texture_lod_bias.texture_lod_bias_all.
2026-08-01 13:24:12 -04:00
BZLZHH 3019c68945 [Fix] (MG_Util): glBindBufferBase must not freeze the buffer's size
BindBufferBase_State stored Range1D(0, bufferObject->GetSize()) as the binding
point's range, so the range reflected whatever size the buffer happened to have
at bind time. Binding an empty buffer and giving it storage afterwards is
ordinary application code - glGenBuffers / glBindBufferBase / glBufferData is
exactly the order KHR-GL3{0,2,3}.clip_distance.coverage uses - and the binding
then stayed frozen at [0, 0).

Every backend consumer reads GetRange() as the range the binding actually
covers, so the stale window meant the capture buffer was bound with
glBindBufferRange(..., 0, 0) instead of glBindBufferBase, transform feedback
captured nothing, and the test read back its pre-draw zeros. The same stale
range also under-counted the CPU-side transform feedback capacity accounting.

GL resolves a whole-buffer binding against the object's size at every use;
only glBindBufferRange pins a fixed window, and the binding point already
tracked which of the two it was for the glGetIntegeri_v START/SIZE queries.
GetRange() now resolves the non-explicit case dynamically.

Fixes KHR-GL3{0,2,3}.clip_distance.coverage on Espryt; transform_feedback stays
21/21 on all four versions, and DirectVulkan (lavapipe) re-verified unaffected.
2026-08-01 12:30:46 -04:00
BZLZHH 800142c104 [Fix] (DirectGLES): stop the default texture clobbering an aliased real binding
Desktop GL_TEXTURE_1D/1D_ARRAY have no ES equivalent and are emulated on
GL_TEXTURE_2D/2D_ARRAY, so one native binding serves two frontend slots of the
same texture unit. BindCurrentTextures walked the slots in enum order and let
the last one win, which is wrong as soon as one of an aliased pair holds a real
texture and the other holds the unit's default (name 0) object: the default
would be bound over the real texture and the shader sampled an empty texture,
which GL resolves to opaque black.

The default is only skipped while it has never been given an image, so this
needed nothing more than some earlier test in the same glcts process defining
one on texture name 0 - after which every later case that sampled a 1D texture
returned black. That is the mechanism behind a whole family of failures that
only reproduced when another case ran first: texture_lod_basic.lod_selection,
packed_pixels.varied_rectangle.rgba4_format_bgra, shaders.arrays.{return,
unnamed_parameter}.float_vertex and clip_distance.functional all pass in the
full-suite ordering now.

Resolved with a second pass, mirroring the intent the unbind half of the
function already had ("a default alias must not clear a real binding"): real
textures are placed first, then defaults fill only the native targets nothing
else claimed.
2026-08-01 12:07:23 -04:00
BZLZHH e9382f5329 [Fix] (DirectGLES): exact transform feedback primitive queries
Two leftovers from the capture passthrough, both only observable with a
geometry shader in the pipeline:

- GL_TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN / GL_PRIMITIVES_GENERATED fell back
  to the frontend's CPU accounting, which counts the primitives the draw call
  assembles and so cannot see a geometry stage's amplification. Both are core ES
  query targets (GL_PRIMITIVES_GENERATED from 3.2 on, gated accordingly so an
  older driver doesn't get a stray GL_INVALID_ENUM), so they now go straight to
  the driver's own counters. Generalized the occlusion-query handle's isOcclusion
  flag into the glBeginQuery target it already had to remember for glEndQuery,
  which is what tells the result read to use the core 32-bit getter.

- FixupGsStripCaptureOrder rewrites captured strip triangles from Vulkan's
  (i, i+1, i+2) order into GL's (i+1, i, i+2). A driver-side capture already
  emits GL order, so the rewrite corrupted it - KHR-GL33.transform_feedback
  .geometry read back the odd triangle rotated one vertex. Skipped when the
  backend owns the capture span.

KHR-GL3{0,1,2,3}.transform_feedback is now 21/21 on Espryt; DirectVulkan
(lavapipe) re-verified at 21/21 for the shared frontend change.
2026-08-01 11:57:18 -04:00
BZLZHH df7d1edeca [Feat] (DirectGLES): implement transform feedback capture
Transform feedback was frontend-only on DirectGLES: glBeginTransformFeedback
just flipped MobileGL's own capture state and the real ES driver was never told
to capture anything, so every capture buffer read back as whatever it held
before the draw (zeros for a fresh glBufferData(NULL)). DirectVulkan drives its
capture from its own draw recording, so the shared GLFunctionsTable had no
entries for the span at all.

Capture now runs on the real driver:

- The backend program declares the capture set with glTransformFeedbackVaryings
  before it links. SPIRV-Cross keeps user output names verbatim in the
  transpiled ESSL, so the frontend's requested names carry over unchanged.
- New GLFunctionsTable Begin/EndTransformFeedback entries hand the span
  boundaries to the backend (null for DirectVulkan, which is unaffected).
- The driver-side begin is deferred to the first draw of the span: ES needs the
  capturing program current and the capture buffers bound, and both only become
  true once PrepareForDraw has run. A span that never draws never touches the
  driver, which is what the GL semantics amount to anyway.
- The end mirrors the captured ranges back into the frontend buffer shadows -
  the GPU wrote them behind the frontend's back, so MapBuffer/GetBufferSubData
  would otherwise still return the pre-draw bytes.

Takes KHR-GL32.transform_feedback from 13/21 to 19/21; the two remaining
failures are the geometry-amplified primitive queries, which still go through
the frontend's CPU accounting.
2026-08-01 11:51:19 -04:00
BZLZHH 8025745fa3 [Chore] (Version): bump version to 26.8 for android plugin 2026-08-01 23:46:58 +08:00
BZLZHH 4a533a215a [Chore] (MG_Backend): fix compiling error. 2026-08-01 23:21:35 +08:00
BZLZHH 0a5d7ceb6c [Feat] (DirectGLES): implement GL_ANY_SAMPLES_PASSED occlusion queries
DirectGLES never registered BeginOcclusionQuery/EndOcclusionQuery, so
the frontend rejected the occlusion query targets entirely; the CTS
tests that use them (e.g. packed_depth_stencil.verify_partial/mixed_
attachments) left a stray GL_INVALID_ENUM that a later, unrelated
glGetError() check would report as its own failure
("Uploading buffer data failed" at gluDrawUtil.cpp:363).

Occlusion queries are core ES3 (glGenQueries/glBeginQuery(GL_ANY_
SAMPLES_PASSED, ...)/glEndQuery/glGetQueryObjectuiv), unlike the timer
queries which need GL_EXT_disjoint_timer_query, so they're wired up
unconditionally (independent of MOBILEGL_DISABLE_TIMERQUERY) using the
same handle-based GetQueryResult64/DeleteBackendQuery plumbing already
shared with timer queries. GetQueryResult64 now reads the 0/1 result
through the core 32-bit glGetQueryObjectuiv getter for occlusion
handles instead of the timer-only 64-bit GL_EXT_disjoint_timer_query
getter, since a driver can fully support core occlusion queries while
lacking that extension entirely.
2026-08-01 11:20:38 -04:00
BZLZHH ac81185968 [Fix] (DirectGLES): implement GL_DEPTH_STENCIL readback for ReadPixels/GetTexImage
Neither ReadPixels nor GetTexImage recognized format=GL_DEPTH_STENCIL
(type GL_UNSIGNED_INT_24_8 / GL_FLOAT_32_UNSIGNED_INT_24_8_REV): it
matched none of the native-passthrough gates nor the color-channel
conversion mapping, so both silently no-op'd (logging a compiled-out
MGLOG_E) and left the caller's buffer untouched. Real GLES/GL drivers
already implement this readback natively, so widen the native-pair
gates to include it.

GetTexImage additionally always attached the source texture to its
scratch FBO as GL_COLOR_ATTACHMENT0, which a depth-stencil texture
cannot be (framebuffer-incomplete) - route it through the existing
EnsureDepthAttachment2D(..., withStencil=true) path instead and skip
the color-only glReadBuffer call for that format.

Fixes KHR-GL3{2,3}.packed_depth_stencil.verify_read_pixels,
verify_get_tex_image, and verify_copy_tex_image (which depends on
GetTexImage internally) for both depth24_stencil8 and
depth32f_stencil8.
2026-08-01 11:14:33 -04:00
BZLZHH 9e861f3f7a [Test] (tools/cts): extend the fbo-harness waiver to the Espryt renderer
Same test-methodology artifact as Magma (dEQP's fbo-surface-type
wrapper FBO being mistaken for the true default framebuffer by
ApiCoverageTestCase's ReadBuffer coverage sub-test) - the waiver's
renderer_list only matched "Magma*", so KHR-GL3{0,1,2}.api.coverage
still reported Fail under the DirectGLES (Espryt) backend. Add
"Espryt*" to the same waiver entry.
2026-08-01 10:48:11 -04:00
BZLZHH da6f75dbd1 [Fix] (DirectGLES): cap advertised GL_MAX_SAMPLE_MASK_WORDS to 1
MobileGL's sample-mask state is a single 32-bit word (RenderState::
SampleMaskValue) and SampleMaski_State() hard-rejects any maskNumber
other than 0. DirectGLES forwarded the real underlying driver's
GL_MAX_SAMPLE_MASK_WORDS unmodified (NVIDIA's GLES driver reports 2),
so dEQP's per-test-case gluStateReset - which always calls
glSampleMaski up to that reported word count - hit GL_INVALID_VALUE on
word 1 after every single case and aborted the whole glcts process.
Each restart only got through one more case before repeating, which
run_cts_local.py recorded as a wall of per-case crashes (63 in
packed_pixels.rectangle alone) and tripped its "many empty chunks"
abort heuristic partway through the GL32 suite. 1 is the spec-required
minimum and is what MobileGL actually implements, so cap to it instead
of forwarding the raw driver limit.
2026-08-01 09:59:26 -04:00
BZLZHH 951da362f7 [Fix] (submodules): point include/FastSTL at the fork's already-pushed fix
Our local-only commit f8567f6 for the erase(iterator) bug was never
pushed to MobileGL-Dev/FastSTL and broke CI's submodule checkout
("not our ref"). The fork's own main branch already carries an
equivalent fix (022211c, same root cause) plus a perf improvement on
erase(key) (34f55f9), so switch to that instead of pushing a redundant
duplicate that would diverge from it.
2026-08-01 09:25:01 -04:00
BZLZHH 4c929b9b3f Merge branch 'dev' of github.com:MobileGL-Dev/MobileGL into dev 2026-08-01 21:03:14 +08:00
BZLZHH 8d5072543a [Test] (tools/cts): waive api.coverage's fbo-surface-type wrapper-FBO artifact
KHR-GL3{0,1,2,3}.api.coverage's ReadBuffer coverage sub-test captures
GL_READ_BUFFER while dEQP's own fbo-surface-type wrapper FBO is bound
(a real, non-zero-named FBO, not framebuffer 0), then later deletes an
unrelated FBO of its own. Per the GL spec, deleting a bound FBO
implicitly rebinds framebuffer target 0 - the true default framebuffer
this time, not the wrapper - and restoring the captured
GL_COLOR_ATTACHMENTn value against it correctly raises GL_INVALID_ENUM
(only FRONT/BACK-style tokens are valid there). This is a spec-correct
response to a --deqp-surface-type=fbo-only test-methodology artifact,
not a MobileGL conformance defect, and cannot occur on a real
window/pbuffer-backed run where framebuffer 0 is genuinely bound
throughout. Add a waiver (dEQP's own mechanism for exactly this kind of
known non-defect) instead of weakening the (correct) validation, and
wire --waiver-file through run_cts_local.py.
2026-08-01 08:53:35 -04:00
BZLZHH 5de2b9e3e9 [Chore] (Version): bump version to 26.8 2026-08-01 20:35:31 +08:00
BZLZHH 9192d156d1 [Fix] (DirectVulkan): ReadPixels materializes pending clears before resolving the blit binding
ResolveColorBlitBinding cached a RenderbufferResource*/TextureResource*
(trackedLayout) before the pending-clear materialization step ran. For an
attachment that had never been part of any render pass yet (e.g. a
GL_NONE draw buffer slot read back via an explicit glReadBuffer), the
materialize call was the first thing to touch its resource, and creating
that entry in the UnorderedMap (FastSTL, open-addressing) can rehash and
invalidate every previously-taken pointer into the map - including the
one just cached. The read then saw a stale VK_IMAGE_LAYOUT_UNDEFINED and
silently bailed (via a compiled-out MGLOG_E in release builds), leaving
the client buffer untouched. Reordering so the clear is materialized
first, then the binding resolved, guarantees the pointer reflects the
final resource state. Fixes KHR-GL3{0,1,2,3}.draw_buffers.draw_buffers_1.
2026-08-01 08:09:49 -04:00
BZLZHH 27cdfbc0ca [Fix] (DirectVulkan): advertise GL_ARB_explicit_attrib_location unconditionally
layout(location=N) out qualifiers are fully supported (glslang parses them,
SPIR-V expresses them natively), but the extension string was never
advertised. KHR-GL3{0,1,2}.draw_buffers.draw_buffers_1 builds its MRT
fragment shader with per-attachment layout(location=i) outputs only when
GL_ARB_explicit_attrib_location is reported or the context is >=3.3; below
that it fell back to a single non-indexed `out vec4`, which only ever
targets location 0, leaving every draw buffer past slot 0 unwritten.
2026-08-01 08:09:35 -04:00
BZLZHH 4567c3b468 [Fix] (DirectVulkan): advertise GL_ARB_texture_multisample unconditionally
GL_ARB_texture_multisample was implemented (glTexImage2D/3DMultisample,
GL_TEXTURE_2D_MULTISAMPLE) but never listed in BuildAdvertisedExtensions.
dEQP's GL 3.1 context loader only binds non-core-until-3.2 entry points
when the extension string is present, so glTexImage2DMultisample stayed
a null function pointer and KHR-GL31.texture_size_promotion.functional
crashed on the null call. GL 3.2+ contexts treat it as core and were
unaffected.
2026-08-01 08:09:20 -04:00
BZLZHH d18c6a1bae [Fix] (DirectVulkan): Xlib surface fallback for ICDs without VK_EXT_headless_surface
Real drivers (NVIDIA proprietary Linux) don't implement VK_EXT_headless_surface,
which the pbuffer path required unconditionally, hard-aborting at CreateInstance.
CreateInstance now detects instance-extension support and requests
VK_KHR_xlib_surface instead when headless is unavailable; CreateSurface creates
an unmapped Xlib window purely to obtain a VkSurfaceKHR, then proceeds through
the existing swapchain path unchanged. Shutdown destroys the window it owns.
Lavapipe and other headless-capable ICDs are unaffected.
2026-08-01 06:38:30 -04:00
BZLZHH dd745d7547 [Fix] (MG_State, MG_Impl): GL-order capture for geometry triangle strips
Vulkan transform feedback captures odd strip triangles as (i, i+2, i+1)
while GL table 10.1 decomposes them as (i+1, i, i+2). When the capture
stage is a triangle-strip geometry shader whose EmitVertex/EndPrimitive
sequence is statically knowable (no emission under control flow), link
time extracts the per-invocation strip lengths from the glslang AST, and
EndTransformFeedback rotates each odd triangle's captured vertex records
into GL order in place (bounded by the binding ranges' whole-triangle
capacity; raw input primitives tracked per Begin/End).
KHR-GL33.transform_feedback.geometry passes - the family is 21/21.
2026-08-01 03:17:30 -04:00
BZLZHH 4407be89cd [Fix] (MG_Impl): count multisample texture attachments in GL_SAMPLE_BUFFERS
The draw-framebuffer sample resolver only looked at renderbuffer
attachments, so framebuffers with multisample texture attachments
reported GL_SAMPLE_BUFFERS == 0 and callers took single-sampled paths
(the CTS blit helpers read multisampled attachments based on it).
2026-08-01 02:50:29 -04:00
BZLZHH 0c1a433af6 [Fix] (DirectVulkan): multisample resolve blits; per-buffer blit skip; RGBA-widened renderbuffers
Color blits from a multisampled source now use vkCmdResolveImage (both
blit resolvers carry the image sample count); a buffer named in the blit
mask but absent from either framebuffer skips just that buffer instead
of cancelling the whole blit (GL 4.6 18.3.1); and three-channel color
renderbuffers widen to their RGBA twin exactly like textures, so
renderbuffer<->texture blits of the same GL format see one VkFormat.
framebuffer_blit.multisampled_to_singlesampled_blit_color_config_test
passes - the whole framebuffer_blit family is green.
2026-08-01 02:46:16 -04:00
BZLZHH a2f3efe22c [Feat] (DirectVulkan): combined and scissored blits; cross-format depth-stencil blits
BlitFramebuffer now serves any GL_COLOR/DEPTH/STENCIL mask combination:
the depth/stencil aspects run as per-aspect image copies before the color
path, renderbuffer attachments materialize their pending clears like
texture ones, and the scissor test clips blit writes (destination rect
intersected, source shrunk proportionally). Depth copies between images
of different depth formats (a D24S8 renderbuffer into a
DEPTH_COMPONENT24 texture riding the D32_SFLOAT fallback) round-trip
through the host with a per-texel re-encode; stencil aspects pass
through raw since every packed format encodes S8. scissor_blit and
packed_depth_stencil.blit.* now pass.
2026-08-01 02:19:07 -04:00
BZLZHH b9a15aed61 [Feat] (DirectVulkan, MG_Impl): GPU transform feedback primitive queries
The TF primitive queries now ride VK_QUERY_TYPE_TRANSFORM_FEEDBACK_STREAM_EXT
pools when the device reports transformFeedbackQueries: each captured draw
is wrapped in a slot (shared between both GL targets when active
together), and results sum the (written, needed) pairs -
GL_TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN from the first,
GL_PRIMITIVES_GENERATED from the second. This is exact through geometry
shaders, so KHR-GL33.transform_feedback.query_geometry_* pass; the CPU
accounting delta remains the fallback for backends without the feature.
2026-08-01 02:02:35 -04:00
BZLZHH f748a06632 [Fix] (3rdparty): glslang evaluates defined() expanded from macros
Pulls the glslang change that downgrades the 'defined in macro
expansion' diagnostic to a portability warning with normal evaluation.
KHR-GL33.shaders.preprocessor.conditional_inclusion.basic_2_* pass; the
whole preprocessor family (482 cases, including every negative
invalid_defined_* case) stays green.
2026-08-01 01:54:48 -04:00
BZLZHH 4532cae175 [Feat] (MG_Impl, MG_Util): STENCIL_INDEX8 renderbuffers; report distinct D/S renderbuffers unsupported
GL_STENCIL_INDEX8 becomes a first-class internal format (VK_FORMAT_S8_UINT
backing, metrics, classifiers, converters), so glRenderbufferStorage
accepts it instead of leaving GL_INVALID_ENUM behind. Framebuffer
completeness now also mirrors the renderer's gate for renderbuffers:
distinct depth/stencil renderbuffer attachments (or a renderbuffer
paired with a texture) report GL_FRAMEBUFFER_UNSUPPORTED - the spec only
requires the same-image case - instead of passing completeness and then
failing at draw/clear (verify_mixed_attachments.* now passes).
2026-08-01 01:50:34 -04:00
BZLZHH 107b56d603 [Feat] (DirectVulkan, MG_Impl): occlusion queries via Vulkan query pools
GL_SAMPLES_PASSED / GL_ANY_SAMPLES_PASSED(_CONSERVATIVE) now work: every
app draw between Begin/EndQuery is wrapped in a slot of a host-reset
occlusion query pool (precise counts when occlusionQueryPrecise is
granted), and the result flush ends any active render pass before
submitting, waits, sums the slots and recycles them. ANY_* targets
report the boolean form; GL_QUERY_COUNTER_BITS and GL_CURRENT_QUERY
answer for the occlusion targets, and deleting an active query releases
its slot. Draw-time depth/stencil state also honors attachment absence:
a framebuffer without a depth (stencil) attachment behaves as if that
test always passes, even when a packed depth-stencil image is attached
through only one half (verify_partial_attachments.*).
2026-08-01 01:50:34 -04:00
BZLZHH 22b749dd37 [Fix] (MG_Util, DirectVulkan): canonical depth shadows with upload conversion
Depth textures previously raw-copied whatever the client handed over
into the Vulkan image, so any client format other than the image's exact
texel layout uploaded garbage (float DEPTH_COMPONENT data read as
16-bit words, GL_TEXTURE_1D/2D alike).

The shadow now has a defined canonical layout - unorm16 for
DEPTH_COMPONENT16, a full-scale unorm32 word for the 24/32-bit fixed
depths, float for DEPTH_COMPONENT32F - produced by the pixel-store
unpack converter (new DepthComponent channel mapping + UNorm32
component). GL_DEPTH_COMPONENT client data may also fill packed
depth-stencil internals (stencil half zero). The Vulkan uploader
converts shadow words to the image texel layout per aspect, and
X8_D24_UNORM falls back to D32_SFLOAT where optimal tiling lacks
support (lavapipe). texture_size_promotion.functional and
packed_depth_stencil.verify_copy_tex_image.* now pass.
2026-08-01 01:15:58 -04:00
BZLZHH f0c0211767 [Fix] (DirectVulkan): raw sRGB attachment writes while FRAMEBUFFER_SRGB is off
GL renders into sRGB color attachments RAW when GL_FRAMEBUFFER_SRGB is
disabled (the core-profile default), but Vulkan sRGB attachments always
encode on write - one decode went missing whenever a rendered-into sRGB
texture was sampled again (multisampled sRGB targets in
texture_size_promotion and texture_swizzle idx27/28 ms cases).

Attachment views (textures and renderbuffers) now reinterpret sRGB
images through their UNORM twin while the capability is off, switching
back when enabled: images get MUTABLE_FORMAT, the attachment-view cache
keys the view format, renderbuffers carry a second view, and the render
pass hash includes the capability state. Sampled views keep decoding.
The VkTextureManager.cpp half of this rides with the next commit.
2026-08-01 01:15:57 -04:00
BZLZHH 9ebbb76df1 [Fix] (DirectVulkan): clamp fixed-point ReadPixels to [0,1]
glReadPixels final conversion honors GL_CLAMP_READ_COLOR (default
GL_FIXED_ONLY): fixed-point normalized color buffers clamp to [0,1] on
read - visible for SNORM attachments, whose negative values previously
leaked through (texture_size_promotion SNORM cases). True float formats
stay unclamped unless the mode is GL_TRUE; GetTexImage is unaffected.
2026-08-01 01:15:57 -04:00
BZLZHH 95547ab9ce [Fix] (MG_Util): map GL adjacency primitives to their Vulkan topologies
GL_LINES_ADJACENCY / GL_LINE_STRIP_ADJACENCY / GL_TRIANGLES_ADJACENCY /
GL_TRIANGLE_STRIP_ADJACENCY fell through to the TRIANGLE_LIST default,
so adjacency draws assembled garbage. They now map to the matching
*_WITH_ADJACENCY topologies (adjacency vertices are discarded by Vulkan
when no geometry shader is active, matching GL semantics);
KHR-GL33.primitive_restart.restart_mode passes.
2026-08-01 00:30:01 -04:00
BZLZHH 8eaf2d0069 [Fix] (MG_Impl): create sampler objects at Gen; guard combined-format CopyTexImage
glGenSamplers creates the sampler objects themselves (unlike texture and
buffer names), so glIsSampler must answer GL_TRUE before any bind - the
names now get their state vectors at Gen time (KHR-GL33.api.coverage).

glCopyTexImage2D with a combined DEPTH_STENCIL internalformat now
requires both halves in the read framebuffer and reports
GL_INVALID_OPERATION when only the depth or only the stencil attachment
point is populated (packed_depth_stencil.validate_errors.*).
2026-08-01 00:27:05 -04:00
BZLZHH 54a8609c64 [Feat] (DirectVulkan): depth-stencil GetTexImage
The depth-stencil ReadPixels core (per-aspect copies + CPU repack) is
now shared, and glGetTexImage serves GL_DEPTH_COMPONENT /
GL_DEPTH_STENCIL / GL_STENCIL_INDEX queries of depth textures with it
instead of rejecting every non-color aspect
(packed_depth_stencil.verify_get_tex_image.* now passes).
2026-07-31 18:45:52 -04:00
BZLZHH 1fb0eb0737 [Fix] (MG_Util): GL_FLOAT_32_UNSIGNED_INT_24_8_REV is 8 bytes per pixel
The packed-type size table listed the D32F+S8 client format at 4 bytes,
so every GL_DEPTH32F_STENCIL8 upload copied only half its client data -
the top half of such textures stayed zero (packed_depth_stencil
verify_read_pixels/clear_buffer.depth32f_stencil8 now pass).
2026-07-31 18:43:30 -04:00
BZLZHH 282dd69230 [Feat] (DirectVulkan, MG_Impl): depth-stencil ReadPixels and combined-attachment queries
glReadPixels now serves GL_DEPTH_COMPONENT, GL_DEPTH_STENCIL and
GL_STENCIL_INDEX from the read framebuffer's depth/stencil attachment:
per-aspect vkCmdCopyImageToBuffer copies (4-byte-aligned stencil region)
with CPU repacking into GL_FLOAT / GL_UNSIGNED_SHORT / GL_UNSIGNED_INT /
GL_UNSIGNED_INT_24_8 / GL_FLOAT_32_UNSIGNED_INT_24_8_REV /
GL_UNSIGNED_BYTE layouts, honoring pack state and pixel-pack buffers.

GL_DEPTH_STENCIL_ATTACHMENT parameter queries follow the spec's combined
rules: differing depth/stencil attachment images (or a lone half) fail
with GL_INVALID_OPERATION, as does GL_FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE
on the combined name. packed_depth_stencil.verify_parameters.* and
verify_read_pixels.depth24_stencil8 now pass.
2026-07-31 18:41:08 -04:00
BZLZHH e6ebe7078d [Fix] (MG_Util, MG_State): reject reserved GLSL identifiers glslang accepts
glslang parses "packed" and "row_major" as plain identifiers outside a
layout(...) list and accepts the reserved image*Shadow names outright.
A comment/preprocessor-aware pre-scan in the compile path now fails such
shaders with a proper info log, while layout(packed)/layout(row_major)
qualifier lists stay legal (uniform_block family still passes).
KHR-GL31/32/33.CommonBugs.CommonBug_ReservedNames now pass.
2026-07-31 18:27:11 -04:00
BZLZHH 30a91023f6 [Chore] (tools/cts): pin local runner surface size to 256x256
Without an explicit size dEQP's FboRenderContext sizes the wrapper FBO
to GL_MAX_RENDERBUFFER_SIZE (16384^2 here) and size-derived test
allocations explode - the multisampled depth blit config test alone
needs a 4 GiB depth texture on such a surface.
2026-07-31 18:21:28 -04:00
BZLZHH 47dd8cdc05 [Feat] (MG_Impl): answer format-derived framebuffer attachment queries
glGetFramebufferAttachmentParameteriv (and the DSA variant) now answer
GL_FRAMEBUFFER_ATTACHMENT_RED/GREEN/BLUE/ALPHA/DEPTH/STENCIL_SIZE,
COMPONENT_TYPE and COLOR_ENCODING from the attached image's internal
format, and accept the default-framebuffer attachment names (GL_DEPTH,
GL_STENCIL, GL_FRONT/GL_BACK variants). Querying them with no image
attached reports GL_INVALID_OPERATION per spec instead of
GL_INVALID_ENUM.
2026-07-31 18:21:28 -04:00
BZLZHH 8b36a15fb3 [Fix] (DirectVulkan): repair VK_VERIFY varargs and soften image-creation OOM
VK_VERIFY appended the caller's context format string to the base format
while the context ARGUMENTS expanded before the base arguments, so any
failing VK_VERIFY with context args formatted every conversion from the
wrong slot - the %s for VkResultToString dereferenced an integer arg and
crashed inside the logger. The context line is now its own log call
(XXHASH_VERIFY had the same defect).

vmaCreateImage failure in SyncTextureResource is now a soft failure like
the unsupported-sample-count path: a driver may pass the
vkGetPhysicalDeviceImageFormatProperties pre-check yet still refuse
creation (a 4-sample 16K depth texture on lavapipe is 4 GiB), and a GL
implementation must not abort on that.
2026-07-31 18:21:28 -04:00
BZLZHH 07fa84fb8d [Fix] (MG_State, MG_Impl): defer deletion of the program in use
glDeleteProgram on the current program now only flags it: the name (and
every glGetProgram* query) stays valid until the program stops being
current, at which point UseProgram frees the slot and releases orphaned
attached shaders. Previously the name died immediately, so a second
glDeleteProgram - as issued by common CTS utility teardown - recorded
GL_INVALID_VALUE that poisoned the next test iteration's build
(KHR-GL33.clip_distance.functional now passes its build phase).

glIsProgram/glIsShader piggyback on the same rule: a flagged name is
still a program/shader while it stays GL-visible, which resolves the
long-standing FIXMEs there.
2026-07-31 18:21:14 -04:00
BZLZHH a03817b4ee [Fix] (FastSTL): bump submodule for erase(iterator) out-of-bounds fix
Pulls the FastSTL fix for erase() iterator advancement: erase loops
(pending-clear GC, render-pass eviction, frame-transient drains) no
longer skip elements or walk past the bucket array. Root cause of the
order-dependent CTS batch segfaults (texture_lod_bias_all,
clip_distance.functional after ReadPixels, batch-order aborts).
2026-07-31 18:21:05 -04:00
BZLZHH 641bc0cdd9 [Feat] (MG_Impl): transform feedback primitive queries
glBeginQuery/glEndQuery now accept GL_TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN
and GL_PRIMITIVES_GENERATED. The result comes from CPU-side accounting:
every captured draw adds the primitives it assembles, clamped by the
capture buffers' remaining capacity in whole primitives (a full buffer
stops recording, which is exactly what PRIMITIVES_WRITTEN reports), with
the captured-vertex cursor resetting on glBeginTransformFeedback.

Draws without a geometry stage write exactly what they assemble, so this
is precise for them (KHR-GL33.transform_feedback.query_vertex_* now pass);
geometry amplification is not modelled yet and the query_geometry_*
variants still fail.
2026-07-31 17:40:42 -04:00
BZLZHH c069890ac7 [Feat] (DirectVulkan): GPU transform feedback capture via VK_EXT_transform_feedback
Second stage of GL 3.0 transform feedback: captured draws now write real
data.

- Device setup enables the VK_EXT_transform_feedback feature when present
  and loads the bind/begin/end entry points.
- Captured draws compile an XfbCapture program variant whose last
  vertex-processing stage gets XfbBuffer/XfbStride/Offset decorations from
  the program's resolved varyings (a new spirv-opt pass). A captured
  gl_Position is mirrored into a dedicated output written before every
  OpReturn - or before every OpEmitVertex in a geometry stage - ahead of
  the position fixup, so the captured value is the shader's own pre-remap
  position.
- DrawArrays/DrawElements wrap the draw in Begin/EndTransformFeedbackEXT;
  a small counter buffer resumes the append position across draws within
  one glBeginTransformFeedback (fresh Begin starts at the bound offsets).
- Capture targets are promoted to persistently-mapped host-coherent GPU
  storage (persistent-map storage now also carries the transform feedback
  usage), so MapBuffer/GetBufferSubData read the captured bytes after the
  fence wait glEndTransformFeedback now performs.
- Draw-mode/feedback-mode validation defers to the geometry shader's
  output primitive when one is present, and glGetBooleanv reports
  GL_TRANSFORM_FEEDBACK_ACTIVE/PAUSED so dEQP's per-case state reset can
  unwind an active capture.

KHR-GL33: transform_feedback capture_vertex_*/capture_geometry_*/
discard_*/draw_xfb and clip_distance.coverage now pass; queries
(PRIMITIVES_WRITTEN) and gl_ClipDistance capture remain.
2026-07-31 17:31:41 -04:00
BZLZHH 48dd1c5956 [Feat] (MG_State, MG_Impl): transform feedback state, validation and reflection
First stage of GL 3.0 transform feedback: glTransformFeedbackVaryings /
glGetTransformFeedbackVarying / glBeginTransformFeedback /
glEndTransformFeedback were unimplemented stubs. This adds

- per-program capture state: requested varyings apply on the next link and
  resolve against the last vertex-processing stage's linker objects (with
  gl_Position/gl_PointSize handled as builtins), failing the link on
  unknown or duplicate names or exceeded interleaved/separate limits, with
  offsets and strides computed per GL rules;
- context Begin/End state with the GL 3.3 error semantics: invalid
  primitive modes, redundant Begin/End, missing program or capture-buffer
  bindings, primitive-mode compatibility at draw time, and the
  while-active prohibitions on rebinding capture buffers, switching
  programs, and relinking the captured program;
- GetProgramiv TRANSFORM_FEEDBACK_* queries and a 4-slot bound on indexed
  GL_TRANSFORM_FEEDBACK_BUFFER binding points.

KHR-GL33.transform_feedback api_errors/linking_errors/get_xfb_varying now
pass; GPU-side capture is the remaining stage.
2026-07-31 17:08:37 -04:00
BZLZHH a389477f78 [Fix] (MG_Impl): report INVALID_OPERATION for shader names in program APIs
Program entry points answered GL_INVALID_VALUE whenever the name did not
resolve to a program, including names that exist but belong to a shader
object. Programs and shaders share one name space, so the spec (and
KHR-GL33.get_uniform_tests.get_uniform) requires GL_INVALID_OPERATION for
the shader-name case and GL_INVALID_VALUE only for names GL never handed
out, matching the interface-query helper's existing behavior.
2026-07-31 16:47:45 -04:00
BZLZHH 94a8f1e3f3 [Fix] (ShaderTranspiler): keep declared modern GLSL versions strict
Normalization rewrote every desktop core #version below 400 to 330 (and
400+ to 460), and a failed parse was retried at 460. Together these erased
the declared version's rules: KHR-GL33 negative-compile cases (reserved
names, parenthesized layout-qualifier values in a declared-420 shader,
GLSL 4.5 mix() overloads at 330, precise in struct members) all compiled.

Explicitly declared core versions >= 330 now keep their number, and the
460 retry only fires for sources whose directive carries the normalizer's
own legacy marker - i.e. shaders that declared 110-150 (or nothing), which
is the shader-pack compatibility case the retry exists for. Replaces the
narrower arrays-of-arrays special case.
2026-07-31 16:43:27 -04:00
BZLZHH 45d506545e [Fix] (MG_Util, DirectVulkan): tolerate storage-less attachments in component-size queries
GetComponentSizesForInternalFormat asserted on TextureInternalFormat::Unknown,
which framebuffer-parameter queries legitimately reach for attachments that
have no storage yet (KHR-GL33.packed_depth_stencil.validate_errors.initial_state
aborted there). Answer with all-zero sizes and keep a warning for genuinely
unhandled formats. Also include the image dimensions in the texture
vmaCreateImage failure report.
2026-07-31 16:35:03 -04:00
BZLZHH d9d63c9496 [Fix] (MG_Impl): answer ARB_transform_feedback3 limit queries
The GL CTS queries GL_MAX_TRANSFORM_FEEDBACK_BUFFERS and
GL_MAX_VERTEX_STREAMS before checking whether the extension is advertised
and requires no GL error (desktop drivers all accept these enums). Answer
with the separate-attrib capacity and a single vertex stream; the
transform_feedback3 tests then report NotSupported instead of failing on
GL_INVALID_ENUM.
2026-07-31 16:25:46 -04:00
BZLZHH 92140405c1 [Feat] (DirectVulkan): emulate GL_LINE_LOOP with closed indexed line strips
Vulkan has no LINE_LOOP topology and the frontend used to reject the mode
with GL_INVALID_OPERATION, which is itself non-conformant (several KHR-GL33
transform_feedback tests draw line loops and expect no error). DrawArrays,
DrawElements and DrawElementsBaseVertex now rewrite the draw into an
indexed GL_LINE_STRIP whose synthesized uint32 index list revisits the
first vertex, delivered through the client-memory index path (a new
forceClientMemory flag keeps a bound element-array buffer from hijacking
the synthesized pointer). Entry points without the rewrite degrade to an
open line strip instead of a triangle list.
2026-07-31 16:25:46 -04:00
BZLZHH b9ecfef0b6 [Fix] (DirectVulkan): handle renderbuffer attachments in color blit clears
BlitFramebuffer's color path asserted that the read framebuffer's source
attachment is a texture; a renderbuffer source (packed_depth_stencil.blit
color checks) aborted the process. Materialize pending clears through the
renderbuffer path for both source and destination, as ReadPixels already
does.
2026-07-31 16:15:50 -04:00
BZLZHH fba26ea169 [Fix] (DirectVulkan): round renderbuffer MSAA requests to supported counts
glRenderbufferStorageMultisample accepts any sample count up to MAX_SAMPLES
(including non-powers-of-two like 3) and promises at-least allocation, but
the renderbuffer path required an exact Vulkan sample-count match and failed
on devices like llvmpipe that expose 1x/4x only. Round the request up to a
power of two and then to the nearest count the device supports for the
format, cached per format so per-draw resolution does not re-query the
physical device.

Un-crashes KHR-GL33.packed_depth_stencil.blit.* (2x/3x MSAA renderbuffers).
2026-07-31 16:15:50 -04:00
BZLZHH 93a3b55907 [Feat] (DirectVulkan): upload combined depth-stencil texture data
UploadDirtyMipLevels used to skip D24S8/D32FS8 textures outright, leaving
glTexImage-supplied depth-stencil data unuploaded (KHR-GL33
texture_repeat_mode depth24_stencil8 and texture_swizzle depth-stencil
cases all sampled zeros). De-interleave the shadow's GL wire format into a
depth plane (X8_D24 word / float) and a stencil byte plane and record one
copy per aspect, with cross-conversion when the device backs the texture
with the other depth-stencil format.

Depth32FStencil8's shadow byte size also claimed 16 bytes/texel while the
stored wire format (GL_FLOAT_32_UNSIGNED_INT_24_8_REV) is 8; that mismatch
truncated every upload of it.

Also route a multisample-texture sample-count request through the device's
supported counts (round up, GL promises at-least semantics).
2026-07-31 16:15:50 -04:00
BZLZHH d1487bedf0 [Fix] (DirectVulkan): address array layers in mip upload copies
UploadDirtyMipLevels encoded a texture's GL depth into VkBufferImageCopy
imageExtent.depth with layerCount = 1. For array textures the layers live in
the image's arrayLayers, and extent.depth > 1 is invalid for 2D images - in
practice every layer past the first never received its data.

Route the third dimension into layerCount for 1D/2D/cube array images and
keep imageExtent.depth for genuine 3D images.

Fixes the KHR-GL33.pixelstoragemodes.teximage3d.* failures (110 cases) on
lavapipe.
2026-07-31 16:01:41 -04:00
BZLZHH 1bb736c57e [Fix] (ShaderTranspiler): keep arrays-of-arrays illegal below GLSL 430
The legacy-shader retry that retargets a failed parse to #version 460 also
re-legalized multidimensional arrays, which every desktop driver rejects
below 430 and KHR-GL33.shaders.arrays.invalid.* requires to fail. Skip the
retry when the original failure is glslang's arrays-of-arrays error; other
legacy rescues (e.g. layout(binding=...)) keep working.

KHR-GL33.shaders.arrays.invalid.multidimensional_array* now report the
required compile failure (4 cases).
2026-07-31 15:51:40 -04:00
BZLZHH eb76686c1e [Fix] (DirectVulkan): stop replaying consumed renderbuffer clears mid-pass
A cached RenderPassEntry bakes renderbuffer clear payloads inline into its
pendingClearAttachments, and that list outlives the clear's consumption at
pass begin (loadOp CLEAR). Every subsequent draw that reused the entry while
its pass was still active replayed the stale clear through
vkCmdClearAttachments, wiping the color and depth of everything drawn so far
in the pass.

Texture-keyed clears already re-checked the clear manager before clearing;
do the same for inline renderbuffer payloads: only clear while the
renderbuffer clear is still actually pending, and take the live payload so a
newer glClear's values win.

On lavapipe this takes KHR-GL33.shaders.fragdepth.* from 0/18 to 18/18; the
same defect hit any renderbuffer-FBO case with several draws per pass.
2026-07-31 15:51:40 -04:00
BZLZHH 1a04fb8c0c [Fix] (DirectVulkan): support client-memory indices in DrawElements
With no GL_ELEMENT_ARRAY_BUFFER bound, the IndexBufferView byte offset is a
raw client pointer (desktop drivers accept client-memory indices and the GL
CTS relies on this even in core contexts). UploadAndBindIndexBuffer used to
assert-crash the process there; it now snapshots the client index data into
a transient per-frame slice and binds that, matching how client-memory
vertex attributes are already streamed.

Fixes the process abort in KHR-GL33.transform_feedback.capture_* and every
other mustpass case that draws with client-side index arrays.
2026-07-31 15:10:01 -04:00
BZLZHH 306790ee7c [Feat] (tools/cts): add crash-resuming local-host glcts runner
Local counterpart of run_cts.py for desktop Linux runs: re-invokes glcts
with the not-yet-measured cases after a crash, quarantines timed-out cases
with the dEQP watchdog enabled, and records crashed/hung/unrun lists so a
partial run cannot read as a complete one.
2026-07-31 14:52:38 -04:00
BZLZHH 170ccda3e7 [Feat] (tools/cts): port dEQP MobileGL platform to desktop Linux
Guard the AImageReader window path behind __ANDROID__ and add a
mobilegl-desktop DEQP target so glcts can run against libMobileGL.so on a
Linux host via pbuffer surfaces (VK_EXT_headless_surface).
2026-07-31 14:50:18 -04:00
BZLZHH e86a9bbec5 [Chore] (MG_Backend): restore target GL version to 3.3 2026-07-31 16:45:19 +08:00
swung0x48 c5569e71b3 [Feat] (tools/cts): automate Windows WGL conformance runs 2026-07-30 23:00:13 -04:00
swung0x48 7e8c32a063 [Feat] (MG_Backend, MG_Impl): expose experimental GL 4.6 CTS limits 2026-07-30 23:00:13 -04:00
swung0x48 77bd03d962 [Chore]: remove unnecessary doc 2026-07-30 21:56:17 -04:00
swung0x48 37111ae992 [Perf] (DirectVulkan): snapshot-gated consecutive-draw fast path skips SetupDraw re-resolution 2026-07-30 09:40:54 -04:00
swung0x48 6b0c2a15ab [Perf] (DirectVulkan): reuse unchanged global-UBO slices and skip identical descriptor binds 2026-07-30 08:18:21 -04:00
swung0x48 e9ffd99313 [Perf] (DirectVulkan): bake the attribute location mask and memoize the explicit-LOD eligibility probe 2026-07-30 08:18:20 -04:00
swung0x48 7c01ddea0c [Perf] (DirectVulkan): drop per-draw weak-ptr locks, re-resolves and rebuilt masks from the sampled-texture and vertex paths 2026-07-30 08:01:07 -04:00
swung0x48 2d4d6e9cfb [Perf] (DirectVulkan): skip pending-clear probes through a lock-free empty check 2026-07-30 07:02:03 -04:00
swung0x48 76b8957b99 [Perf] (DirectVulkan): memoize sampled-texture resources across draws 2026-07-30 07:02:02 -04:00
swung0x48 ec685b9fa7 [Perf] (DirectVulkan): memoize resolved vertex-input state on the VAO and dedupe vertex/index binds 2026-07-30 07:02:01 -04:00
swung0x48 a12068df52 [Perf] (DirectVulkan): reuse pipelines across per-chunk buffers and skip redundant pipeline binds 2026-07-30 05:01:46 -04:00
swung0x48 0b344792cc [Fix] (DirectVulkan): stop fence-waiting out-of-band texture uploads; reclaim transients asynchronously 2026-07-30 05:01:46 -04:00
swung0x48 9fa32bdad0 [Fix] (DirectVulkan): declare only the used colour attachment span per subpass
- every render pass declared colorAttachmentCount=8 (the full GL draw-buffer
  slot span) with trailing VK_ATTACHMENT_UNUSED references, and Adreno
  configures its per-pixel render-backend/export path from the DECLARED
  count - so every fragment of every pass paid an 8-render-target export
  cost; this was the bulk of the 1.5x per-pixel gap against
  MobileGlues+ANGLE on the same Qualcomm driver (their subpasses declare
  exactly the used span)
- measured on Adreno 650 / MC 26.2 / 1440x3044: total GPU frame time
  11.9 -> 7.5 ms (-37%, now below ANGLE's 7.87 ms), the single-quad
  swapchain blit pass alone 1.26 -> 0.40 ms, steady in-world FPS 82.8 -> 123
  under the standard cooled-start protocol, matching the
  MobileGlues+ANGLE+system-Vulkan benchmark of 123.8
- trailing UNUSED references are popped before the subpass is built (the
  entry's colorAttachmentCount and every pipeline's colour-blend span follow
  it); interior GL_NONE holes keep their slots so fragment-output locations
  still line up
- the pipeline-side fragmentOutputMask check downgrades from assert to a
  debug log: an output at a location past the trimmed span is discarded,
  which is GL's defined behaviour for a draw buffer set to GL_NONE
2026-07-30 02:45:39 -04:00
swung0x48 a4980f2b56 [Fix] (DirectVulkan): skip redundant per-draw dynamic-state commands
- viewport, scissor, blend constants, depth bias, line width and the six
  stencil parameters were re-emitted unconditionally for EVERY draw (~1500
  vkCmdSet* per frame in MC 26.2, where ANGLE emits a handful), costing CPU
  record time and GPU command-processor work for values that almost never
  change between draws
- a recording-scoped shadow now drops any vkCmdSet* whose values match what
  the command buffer already holds; valid because every PipelineFactory
  pipeline declares the same eight dynamic states, so set values persist
  across those binds
- the shadow resets at every command-buffer (re)begin (dynamic state does
  not survive the boundary) and after binding the blit or depth-mipmap
  pipelines, whose narrower dynamic sets make the untouched states undefined
  and whose raw viewport/scissor writes bypass the shadow
2026-07-30 02:45:07 -04:00
swung0x48 8ca20e28ca [Fix] (DirectVulkan): size texture backings by their defined mip level count
- every non-MSAA texture was allocated with a full mip chain regardless of
  how many levels the GL texture actually defines, so MC's 3044x1440 main
  colour and depth render targets each carried 12 levels where ANGLE
  allocates one; a level-0-only texture now gets a single-level backing and
  upgrades to the full chain exactly once when a second level is first
  defined, through the existing preserve-copy recreation path
- saves a third of the memory of every mip-less texture and keeps
  single-level render targets off the multi-mip image layout entirely, which
  also removes the surface the Adreno 650 implicit-LOD overread workaround
  (ForceExplicitLod0SamplePass) exists to defend
- measured perf-neutral on Adreno 650 / MC 26.2 (the driver keeps full UBWC
  on multi-mip render targets), so this is a memory/robustness fix, not a
  speed one
2026-07-30 02:43:32 -04:00
swung0x48 c353a2055f [Feat] (DirectVulkan): pre-pass command stream for reorderable out-of-pass work
- a draw whose sampled texture needs out-of-pass work (deferred clear
  materialization or a sampled-layout transition) used to end the active
  render pass - a full-target store+reload on a tiler - even when the only
  ordering the work needs is 'before this draw'; MC 26.2 clears an overlay
  texture every frame and samples it mid-pass, splitting the main scene pass
  once per frame for nothing
- every frame slot now carries a second primary command buffer, submitted
  strictly AHEAD of the frame command buffer in the same vkQueueSubmit; when
  the open recording has not referenced the image yet (tracked via a
  recording-generation stamp on the texture resource, advanced on every
  frame-command-buffer begin and stamped at every recorded reference:
  attachments at BeginRenderPass/attachment-write, sampled reads per draw,
  layout transitions), the clear/transition is recorded there and the active
  pass stays open - ANGLE's outside-render-pass command stream, restricted
  to the provably reorderable case
- mid-frame flushes and readback submits close and carry the pre stream with
  the frame buffer (it must never be submitted later than the recording it
  was paired with), retiring both under the same submit index; dropped
  recordings (present suspension, swapchain recreation) abandon it
- MaterializePendingClearForTexture's no-active-render-pass assert now
  applies only to the frame command buffer, since the pre stream records
  while a pass is open on the frame buffer by design
2026-07-30 02:43:13 -04:00
swung0x48 421c20984e [Fix] (DirectVulkan): stop loading and carrying dead default-framebuffer content
- EGL swap semantics make the presented colour buffer's content undefined at
  its next acquire (EGL_BUFFER_DESTROYED, the implementation default) and
  every ancillary depth/stencil buffer's content undefined after ANY swap,
  yet the default-FBO render pass reloaded both with LOAD_OP_LOAD every
  frame; SwapchainObject now tracks per-image content validity (defined when
  a pass stores into the attachment, invalidated at present) and the
  render-pass manager turns an undefined attachment's tile load into
  LOAD_OP_DONT_CARE with initialLayout=UNDEFINED, keyed into both hashes so
  the cached LOAD variants cannot be hit by mistake
- the default framebuffer's depth attachment is now attached ON DEMAND: a
  draw with depth test and stencil test both disabled (GL: a disabled test
  neither reads nor writes its buffer), and no pending depth/stencil clear,
  resolves to a depth-less pass flavour, dropping the D24S8 tile load AND
  store outright - MC 26.2 renders its GUI into its own FBO and only ever
  blits colour to the default framebuffer, so its swapchain pass carried a
  full-screen depth round-trip for nothing
- the flavour only escalates: an active depth-full pass absorbs depth-less
  draws unchanged, while a depth-using draw against a depth-less pass
  resolves to an incompatible entry and splits, its depth loading DONT_CARE
  (the content was undefined all along); the depth-less flavour is folded
  into ComputeHash and the per-draw fast-path memo so the two flavours can
  never alias
2026-07-30 02:40:47 -04:00
swung0x48 fc4cd980f2 [Fix] (DirectVulkan): bound image mutability so Adreno keeps UBWC compression
- Every storage-capable colour texture was created MUTABLE_FORMAT, and Adreno
  gives up bandwidth compression on an image that may be viewed as any format in
  its compatibility class. MC's main render target therefore ran uncompressed;
  in a fill-bound scene that is the whole frame budget. Measured on Adreno 650,
  MC 26.2, same scene and camera, device cooled to 38-40C before each run:
  65.3 -> 80.9 fps (+23.9%), GPU busy ~93% in both.
- VK_KHR_image_format_list (enabled when present) fixes it without giving up
  mutability: VkImageFormatListCreateInfo names the exact formats a view may
  use, so the driver can keep the image compressed. The set must be exhaustive
  or the result is undefined - for sampled views it is exactly what
  ResolveSampledImageViewFormat can return over the three numeric domains.
- glBindImageTexture may name any compatible format, which cannot be enumerated
  ahead of time, so a texture bound to an image unit gets no format list. That
  is what VK_IMAGE_USAGE_STORAGE_BIT becoming on-demand is for: it makes
  "unmarked" mean "will never receive an arbitrary-format storage view", which
  is what makes the list sound. Removing STORAGE is worth nothing on its own
  (65.4 fps, measured) - only the mutability bound pays.
- MarkStorageImageTexture runs over every collected image-unit texture before
  the probe loop in PrepareStorageImageTextures, because that loop stops at the
  first texture needing work and would leave the rest unmarked. The mark makes
  NeedsStorageImagePreparation report true, which is what ends the render pass,
  so the recreate lands outside it.
- storageUsageResolved separates "not upgraded yet" from "this format can never
  carry STORAGE", so a format whose optimalTilingFeatures lack STORAGE_IMAGE
  cannot ask for a recreate that will never happen. SyncTexture's cross-draw
  early-out also has to break on a pending upgrade or the recreate never runs.
- An upgrade recreates the image and carries its contents forward through
  PreserveTextureContentsOnRecreate, which submits its own command buffer and
  waits. Whatever the frame already recorded into the old image is still
  unsubmitted, so that copy would read pre-frame content and this frame's
  rendering into the texture would be lost - exactly the render-target-then-
  image-unit case. PrepareStorageImageTextures now flushes first; it takes the
  FrameData rather than a command buffer because the flush retires the current
  one, and drops the sampled-descriptor-set memo that described it.
2026-07-29 07:07:50 -04:00
swung0x48 992d16267c [Fix] (DirectVulkan): rewrite implicit-LOD fragment samples to explicit LOD 0 when every bound sampler is pinned to a single mip level - Adreno 650 (driver 512.502) reads outside a full-screen colour render target's allocation on its implicit-LOD sampling path and faults the GPU, which killed MC 26.2 on its own blit shader (texture(InSampler, texCoord)) between frames 344-421 on every run; this is the same driver defect the default-framebuffer blit shader already works around with textureLod, but an application's shader cannot be edited, so ForceExplicitLod0SamplePass converts OpImageSample*ImplicitLod to the explicit form at the SPIR-V level under a new CompileOptionBit that is only requested when the rewrite provably cannot move a texel (every sampler binding on a single-level view, no anisotropy, and either a LOD clamp that already pins lambda at 0 or min and mag filters that agree - an explicit LOD 0 always takes the magnification side of the min/mag decision); a single-level view now also clamps its sampler to mipmapMode NEAREST with maxLod min(maxLod, 0.25) rather than 0, since collapsing the clamp would make every fragment magnify and quietly retire the min filter; and the program's backend hash memo grows from one slot to four so a program resolved under two compile-flag sets in the same frame stops re-hashing every stage's SPIR-V once per draw 2026-07-29 03:26:57 -04:00
swung0x48 0ea9e6de5f [Fix] (DirectVulkan): follow surface resizes instead of rebuilding the swapchain on VK_SUBOPTIMAL_KHR - a per-frame surface-capabilities comparison (ANGLE's model) is now the only thing that schedules a rebuild, so a launcher-side resolution change reaches the swapchain and the compositor scales the smaller image up to the view, while a driver that merely reports the surface as suboptimal can no longer rebuild every frame (each rebuild destroys every pipeline, resets the render-pass manager and reallocates the default framebuffer, which showed as flicker, then corruption, then a crash); the comparison runs in SURFACE space against the extent the live swapchain was created from, since comparing against the swapchain's own quarter-turn-swapped extent reports a difference on every rotated frame 2026-07-28 21:06:57 -04:00
swung0x48 241ed377b4 [Fix] (macOS): harden Cocoa context setup and isolate embedded glslang 2026-07-28 11:54:50 -04:00
swung0x48 bf312a4b67 [Fix] (DirectVulkan): explicit-LOD blit sampling and present-path hardening - the default-framebuffer blit shader now samples with textureLod 0 (a blit reads exactly the selected level; Adreno 650's implicit-LOD path reads past a single-mip UBWC render target's allocation despite maxLod=0, page-faulting the GPU on MC 26.2's second startup frame once the neighbouring startup staging memory is returned - the invalidated context then failed the next Present submit with EDEADLK/DEVICE_LOST), TransitionToPresent appends the present barrier into the frame's open recording instead of silently dropping it whenever anything was recorded (frames without a default-FBO render pass presented images stuck in their acquired layout), VK_SUBOPTIMAL_KHR acquires are treated as the success they are (image acquired, semaphore signal armed - the early return skipped the fence reset and consumed-flag clear, and callers re-acquired on the same binary semaphore; rebuilds now defer to after the signal is consumed), and validation builds report through VK_EXT_debug_report when VK_EXT_debug_utils is absent instead of aborting instance creation 2026-07-28 06:00:20 -04:00
swung0x48 56b31a9587 [Fix] (FastSTL): bump submodule for the erase(iterator) double-advance fix and add erase-while-iterating regression tests - the old semantics skipped one live element per erase and ran past end() when erasing the highest occupied bucket, sending the new mass pipeline-cache eviction sweeps off the bucket array (device crash on first eviction during world load: garbage handles fed to vkDestroyPipeline) 2026-07-27 23:50:25 -04:00
swung0x48 8a0a8a0274 [Fix] (DirectVulkan): harden the leak-fix round after adversarial review - pipeline memo now drops at every command-buffer boundary (a flush-loop-memoized pipeline could age out and be destroyed while its submission was in flight), mid-frame drains no longer rewind the arena or advance the cache-aging clocks in presenting apps (gated to every 8th drain since the last Present, so readback/fence-heavy frames neither churn conversions nor shrink the 1024-boundary retire window), render-pass eviction notifies the pipeline cache once per sweep batch instead of once per dying pass, descriptor pools use FREE_DESCRIPTOR_SET_BIT so a destroyed layout's cached sets are freed back and credited instead of abandoning pool slots (the live-layout age sweep that could orphan slots is removed - layout destruction is the sole purge path), and renderbuffer respecify parks the old backing for aged destruction instead of destroying it while possibly in flight 2026-07-27 22:51:26 -04:00
swung0x48 d076c29146 [Fix] (DirectVulkan): bound the vertex-input and sampler caches and sweep undeleted GL syncs - both caches age out entries idle >1024 frame boundaries (animated LOD bias no longer mints a VkSampler per float value, buffer/VAO churn no longer grows the vertex-input map for the whole session), and library teardown drains the live-sync registry exactly as glDeleteSync would since GL requires syncs to die with their context 2026-07-27 22:16:16 -04:00
swung0x48 930a607bdf [Fix] (DirectVulkan): make texture/renderbuffer GC reach every dead resource - name-deleted textures register via weak_from_this so first-sync-after-delete can no longer orphan a TextureResource, an orphan sweep makes GC authoritative over the resource map, dead-texture pruning moves to a frame-boundary gate (64 frames) so churn through clears/readbacks reclaims without draws, and dead renderbuffers age past frames-in-flight before their VkImage/view is destroyed instead of leaking until shutdown (or being freed while in flight) 2026-07-27 22:16:15 -04:00
swung0x48 34685b4bb0 [Fix] (DirectVulkan): age-based eviction for the content-addressed cache family - ProgramFactory entries (shader modules/layouts), PipelineFactory graphics pipelines, compute pipelines and per-layout descriptor-set tracking now retire after ~1024 idle frame boundaries (render-pass-manager sweep precedent), render-pass eviction purges pipelines hashed on the dying handle (closes a handle-recycling stale-pipeline hazard), and the program reflection cache is lifetime-id-keyed and cleared at EGL teardown - shader/program churn no longer grows Vulkan objects without bound 2026-07-27 22:05:25 -04:00
swung0x48 c540fb88ee [Fix] (DirectVulkan): drain frame transients on present-less paths - readback waits, suspended presentation, blocking sync waits and flush completion polls now run Present's per-frame drains (deferred buffer/texture releases, transient arena rewind, descriptor cursors, retired command buffers, conversion caches) whenever every submission is provably complete, so offscreen/minimized workloads stay bounded; never blocks, frames-in-flight overlap untouched 2026-07-27 21:45:21 -04:00
swung0x48 6ae3245a0d [Test] (CTS): raise the no-output abort threshold - consecutive instant-crash cases are real progress once device liveness is confirmed 2026-07-26 19:23:05 -04:00
swung0x48 7e048fc2bf [Fix] (DirectVulkan): map RGB10_A2(UI) to A2B10G10R10 - GL 2_10_10_10_REV puts R in bits 0-9 so the A2R10G10B10 mapping silently swapped R/B on upload; also decode both 1010102 variants in readback 2026-07-26 19:13:46 -04:00
swung0x48 83cdfd6bdd [Fix] (DirectVulkan): GetTexImage reads all 3D slices/array layers with PACK_IMAGE_HEIGHT/SKIP_IMAGES semantics, and sRGB readback returns raw sRGB-encoded bytes instead of linearizing 2026-07-26 18:30:43 -04:00
swung0x48 1c76f886cf [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 18:30:42 -04:00
swung0x48 a2e109beff [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 18:30:41 -04:00
swung0x48 63f0756644 [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 18:30:41 -04:00
swung0x48 450215d12c [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 18:30:40 -04:00
swung0x48 3a9e520170 [Test] (CTS): isolate the DirectVulkan renderbuffer-FBO readback defect so the rest of KHR-GL33 can be measured 2026-07-26 18:30:39 -04:00
swung0x48 d2996ba1cf [Test] (CTS): run VK-GL-CTS KHR-GL33 against MobileGL on Android via a standalone glcts binary 2026-07-26 18:30:39 -04:00
swung0x48 c8632dfefe [Test] (piglit-android): add on-device piglit harness for MobileGL - patched waffle (WAFFLE_EGL_LIBRARY/WAFFLE_GL_LIBRARY overrides so waffle drives libMobileGL.so directly, AImageReader-backed windows for DirectVulkan since Android ICDs lack VK_EXT_headless_surface, WAFFLE_FORCE_GL_CONTEXT_VERSION to upgrade piglit's low compat context requests to 3.3 core, meson cross fixes) and patched piglit (Android platform support, EGL support decoupled from the X11-dependent EGL tests, and a dispatch-init fix: the waffle resolvers were never installed because gl_fw is NULL during framework construction, so gl* silently bound to the system driver via the DT_NEEDED libEGL's eglGetProcAddress), plus the adb chunked runner with PIGLIT-result parsing, a results comparator, cross-file examples, and the piglit-on-android skill 2026-07-26 11:57:11 -04:00
swung0x48 b8a8a660e1 [Refactor] (Lifecycle): own MobileGL's lifecycle from the EGL layer instead of ELF static ctor/dtor - the first EGL/WGL entry point lazily initializes via a thread-safe, re-init-capable EnsureInitialized (AutoInit is gone), the last eglTerminate with no initialized display and nothing current tears the whole library down deterministically inside the EGL lifecycle, and the global singletons move to leak-at-exit heap storage so process exit runs no backend destructors at all (AutoDestroy and the Windows DllMain abandon hook are gone); fixes the exit-time SIGABRT from undefined static-destruction order - the DirectGLES buffer-pool mutex abort on Android clean exits, and the pre-existing macOS QueryTest/ProgramTest 'Subprocess aborted' gtest failures now pass (ctest 411/411) 2026-07-26 10:59:14 -04:00
swung0x48 7ab83861ca [Fix] (DirectVulkan): suspend presentation while the window is zero-area - a minimized window's out-of-date swapchain used to keep Present submitting on a signaled fence and presenting never-acquired images (adversarial review); also drop logging from the process-detach abandon path 2026-07-26 07:59:40 -04:00
swung0x48 eaeba556a3 [Test] (WGL): add manual Windows smoke tests - hand-rolled WGL bootstrap and GLFW-driven variant covering the zero-area helper-window path 2026-07-26 07:21:36 -04:00
swung0x48 72fa1221a5 [Fix] (DirectVulkan): survive zero-area windows at renderer init - skip the eager first acquire when RecreateSwapchain's minimize guard left no swapchain (GLFW's hidden helper window), and let Present bring the swapchain up once the window has real size 2026-07-26 07:16:11 -04:00
swung0x48 c4254c4bbd [Feat] (WGL): add Windows host layer - drop-in opengl32.dll with WGL over EGLImpl, Win32 window backend plumbing for both backends, ANGLE loader path, and leak-at-exit process teardown 2026-07-26 06:46:29 -04:00
swung0x48 199164c2e0 [Perf] (DirectGLES): route the per-upload GL_PIXEL_UNPACK_BUFFER unbinds through the unpack binding cache - the six texture-upload sites re-issued glBindBuffer(UNPACK, 0) on every upload; with the resting-0 shadow they now no-op after the first 2026-07-21 19:54:55 -04:00
swung0x48 e87063e90c [Fix] (DirectGLES): route default-framebuffer binds through the FBO-binding shadow - the raw glBindFramebuffer(0) in BindCurrentFBO/SyncAndBindFramebufferObject left the shadow claiming the previous user FBO, false-skipping its next re-bind and letting scoped guards restore a stale binding (caught by adversarial review); also scrub buffer-binding shadows when VAO client-attribute staging buffers are deleted, include cube-map arrays in the pack-image-params gate, and make the delete-recording test hook assertion-unwind safe 2026-07-21 19:54:54 -04:00
swung0x48 122da27249 [Fix] (DirectGLES): overhaul readback/copy/blit driver-state handling with shadow-backed RAII guards - pixel-PACK/UNPACK PBO binding caches resting at 0 (the old bind-then-query 'restore' left the user PBO bound forever, capturing later client-memory readbacks), a PACK pixel-store shadow replacing per-readback glGetIntegerv syncs, a driver FBO-binding shadow behind all scoped binders (per-instance prev slots, nest-safe), scratch-FBO attachment shadows that detach cross-aspect residue exactly when present (depth CopyTex* attachments used to wedge later GetTexImage color reads and vice versa), scissor guards around emulation blits (app scissor clipped depth copies), stale-driver-error drains before single-shot glGetError consumers (fallbacks silently dropped readbacks / GenerateMipmap raised phantom app errors in production builds), ClearBufferiv missing BindCurrentFBO(Draw), cube-face glBindTexture INVALID_ENUM cache poisoning, per-slice GL_PACK_IMAGE_HEIGHT/SKIP_IMAGES semantics on 3D GetTexImage, backend texture ids deleted on wrapper destruction with cache/scratch-FBO scrubs (ids used to leak for the context lifetime and dangling cache pointers could false-skip binds), and context-death/MakeCurrent invalidation for all new shadows; regression tests drive the shadows against a recording mock GLES table 2026-07-21 19:54:54 -04:00
swung0x48 bc2d698b3e [Fix] (DirectGLES): apply the read buffer when one FBO is bound as both draw and read
- SyncCurrentFBO skips the READ-target pass when the same GL FBO is bound as
  both draw and read (the common GL_FRAMEBUFFER case), but the read buffer
  (glReadBuffer) is only applied inside SyncToBackend's READ path — so the skip
  silently dropped every glReadBuffer change, leaving the backend read buffer
  stuck at COLOR_ATTACHMENT0.
- Extract the read-buffer application into BackendFramebufferObject::
  SyncReadBufferToBackend and invoke it from the skip branch (target == Read)
  as well as from SyncToBackend, so reads always target the right attachment.
- Bind the backend FBO as READ inside the helper before glReadBuffer, since the
  skip path only bound it as DRAW.
- Fixes KHR-GL3x.draw_buffers.draw_buffers_1 (reading COLOR_ATTACHMENT1 while
  the FBO stays GL_FRAMEBUFFER-bound returned attachment 0's value); the render
  was already correct, only the readback resolved the wrong attachment.
2026-07-21 12:18:55 -04:00
swung0x48 3049c4b82b [Fix] (ShaderTranspiler): stop blanking block comments in the source handed to glslang
- BlankBlockComments replaced comment chars with spaces but preserved interior newlines, so a block comment spanning a newline inside a #define truncated the macro body (VALUE became empty)
- glslang has a conformant preprocessor and collapses a block comment to one space across newlines, so the delivered source now keeps comments intact and lets glslang handle them
- Fixes KHR-GL3x.shaders.preprocessor multiline_comment_define / redefine_object_multiline_comment / function_redefinition_3 (6 cases, both devices)
- FilterUnsupportedGpuShaderInt64 relied on the blanking to skip commented-out #extension lines; it now masks comments locally (MaskCommentsAndQuotedText) like the sibling passes, collecting edits and applying them back-to-front
- conditional_inclusion.basic_2 (defined() via macro expansion) stays failing by design: glslang rejects it as UB and working around it would mean re-running preprocessing MobileGL defers to glslang
2026-07-21 05:27:01 -04:00
swung0x48 2b3850b76b [Fix] (DirectGLES): upload RGB565/RGB5_A1 shadow data as packed 16-bit types
- The 8-bit unorm shadow was uploaded as GL_UNSIGNED_BYTE, leaving the 8->5/6-bit requantization to the driver
- That rounding direction is implementation-defined: Adreno rounds to nearest (lossless round trip), Mali floors
- On Mali mid-range texels drifted one 5-bit step down, failing all 20 KHR-GL33.pixelstoragemodes.teximage3d rgb565/rgb5a1 cases (eps 1/32); layers with exact values (0.125/0.25/1.0-ish) passed, matching the observed 0,1,7-valid pattern
- PreparePackedNormUpload repacks shadow rows to GL_UNSIGNED_SHORT_5_6_5 / 5_5_5_1 with round-to-nearest, which exactly recovers the original 5/6-bit values (the shadow expansion is injective), so the driver stores them verbatim
- Idempotent across each region's level loop (glType is shared); RGBA4 exempt since its 8-bit expansion (v*17) is exact under either rounding
- Wired at all four SyncMipmapsToBackend upload regions (append-mipmaps, immutable TexSubImage, mutable full, dirty-level update)
2026-07-21 04:30:46 -04:00
swung0x48 2a0ae743a0 [Fix] (DirectGLES): glFinish before the glGetTexImage temp-FBO readback
- Mali (tile-based) does not resolve a texture's render into memory when it is read back through a different (temp) FBO than the one it was rendered with
- The cross-FBO glReadPixels raced the deferred tile resolve and returned pre-render clear contents
- Distinct render targets read back byte-identical, so KHR-GLxx.glsl_noperspective failed on Mali-G715 (all four programs read as the clear colour)
- glGetTexImage is already a CPU/GPU sync point so the extra drain is negligible; Adreno resolves eagerly and was unaffected
2026-07-21 03:34:33 -04:00
swung0x48 6839219c10 [Fix] (GLImpl): report GL_NO_ERROR from glGetGraphicsResetStatus
- The generic export stub returned (GLenum)1; dEQP reads any non-zero status as a lost device
- It is polled after every case (gl3cTestPackages.cpp:121) and sets QP_TEST_RESULT_DEVICE_LOST
- Under the default --deqp-terminate-on-device-lost=enable that tears the whole CTS run down
- MobileGL tracks no GPU resets, so GL_NO_ERROR ("no reset detected") is the honest, spec-correct answer
- Routed through GLImpl::GetGraphicsResetStatus like every other entry point, no inline body in Definitions.cpp
2026-07-21 02:40:15 -04:00
swung0x48 52ddb440ca [Feat] (SelfTest/DriverPost): add a noperspective correctness check to the GLES POST - render a strong-perspective quad and read the centre texel to verify the varying interpolates screen-linear (not perspective-correct), carried through the native GL_NV_shader_noperspective_interpolation path when present or MobileGL's exact gl_Position.w/gl_FragCoord.w emulation when absent. PASS = native and correct; WARN = emulated and correct (the fallback path shipping packs hit on such devices); FAIL = interpolation wrong/perspective-correct, or the program will not build. The ESSL header matches the device version because noperspective is rejected at #version 300 es on some drivers even with the extension enabled 2026-07-21 02:09:17 -04:00
swung0x48 79feeffd25 [Feat] (ShaderTranspiler, DirectGLES): emulate noperspective on GLES devices lacking GL_NV_shader_noperspective_interpolation - EmulateNoPerspectivePass pre-multiplies each NoPerspective output by gl_Position.w in the vertex stage and recovers each input via gl_FragCoord.w in the fragment stage (exact screen-linear L = P(a*w)*gl_FragCoord.w, handling whole-variable and component/access-chain reads, scalar and vector varyings), forces highp on emulated varyings, and strips what it cannot emulate; replaces the smooth-strip fallback so no NV extension is ever required. Restricts the vertex pre-multiply to the entry function so a non-inlined helper cannot double-scale 2026-07-20 23:48:48 -04:00
swung0x48 202037b5a3 [Fix] (DirectVulkan): shrink the blended depth-write quirk to MIN/MAX extremum blends only - a fixture-wide trace sweep showed the additive ONE+ONE arm never fires on the 26.3 OIT chain (its accumulation passes disable depth writes themselves) and only hit unrelated additive glow content; also fail reflection toward the gl_FragDepth exemption and zero phantom default-FBO blend slots so stale indexed state cannot trigger the strip 2026-07-20 23:39:28 -04:00
swung0x48 bce9c48c8e [Feat] (ShaderTranspiler, DirectGLES): support noperspective conformantly instead of stripping it - let the qualifier reach glslang as the core SPIR-V NoPerspective decoration (native on DirectVulkan; SPIRV-Cross emits ESSL noperspective + GL_NV_shader_noperspective_interpolation on DirectGLES), and for GLES devices lacking that extension add StripNoPerspectivePass to drop the decoration and fall back to smooth; the old naked substring erase discarded the interpolation shader packs need and mangled identifiers containing the word 2026-07-20 22:59:43 -04:00
swung0x48 b6a7807a3a [Fix] (MG_Util/ShaderTranspiler): reject malformed #version directives instead of legalizing them - an unrecognized version number (329/331), a bad profile keyword, a float or trailing token used to be rewritten to "#version 330 core" (or rescued to 460 by the retry); now InspectShaderLanguage marks such directives invalid so NormalizeVersionDirective and RetargetLegacyVersionDirectiveTo460 leave them for glslang to reject, while every valid version still normalizes as before 2026-07-20 22:03:36 -04:00
swung0x48 48ba622387 [Fix] (MG_Util/ShaderTranspiler): keep #line directives instead of deleting them, dropping only the GLSL-illegal quoted filename and the ones that precede #version, so __LINE__ and compiler diagnostics follow the application's own numbering 2026-07-20 21:06:38 -04:00
swung0x48 05260d1262 [Fix] (MG_Util/ShaderTranspiler): blank block comments lexically instead of erasing them - a '//*** banner ***' line opened a comment the old scanner never closed, so it deleted the rest of the shader, and a commented-out builtin definition renamed every genuine call to a name nothing defines 2026-07-20 21:06:37 -04:00
swung0x48 6eb5ff51c5 [Fix] (MG_Impl/GLImpl): reject the RGTC internal formats on 3D texture targets - RGTC compresses 4x4 blocks of a 2D image and has no 3D form, and the check must run on the raw enum because RGTC now resolves to plain R8/RG8 storage 2026-07-20 21:05:57 -04:00
swung0x48 e526f8e8ac [Fix] (MG_Util/Converters): resolve the GL_COMPRESSED_* internal formats to the uncompressed storage that backs them instead of rejecting them as unknown - GL prescribes this base-format fallback for the six generic formats, and RGTC stores uncompressed because ES exposes no compressor 2026-07-20 21:05:57 -04:00
swung0x48 e724e88eec [Fix] (MG_State, MG_Impl/GLImpl): allocating a mipmap level no longer truncates the chain above it - AllocateLevel now only grows and the callers that genuinely redefine the whole level set (glTexStorage*, mip regeneration, multisample storage, level-0 respecification) drop the tail explicitly 2026-07-20 21:02:54 -04:00
swung0x48 3b175fb88a [Fix] (MG_Impl/GLImpl): a multisample sample count above the format's maximum is INVALID_OPERATION, not INVALID_VALUE - matching both the spec and the native Adreno driver 2026-07-20 21:02:53 -04:00
swung0x48 b5a4e7075a [Fix] (MG_Impl/GLImpl): record a GL error from the unimplemented compressed texture entry points instead of throwing - a C++ exception unwinding through the C GL ABI hard-crashes any caller, and glGetCompressedTexImage reported success while writing nothing 2026-07-20 21:02:53 -04:00
swung0x48 520c2b6750 [Fix] (MG_Backend/DirectGLES): sync GL_TEXTURE_SWIZZLE_* on multisample targets - the early return meant to skip the sampler-only parameters dropped every swizzle write, which the frontend already treats as legal on those targets 2026-07-20 21:02:52 -04:00
swung0x48 57cc652b1d [Fix] (MG_Impl/GLImpl): glIsTransformFeedback reports GL_FALSE instead of claiming every name it is handed is a live transform feedback object 2026-07-20 21:02:52 -04:00
swung0x48 65ea54da9e [Refactor] (ShaderTranspiler, DirectVulkan): replace the hand-rolled SPIR-V word walkers with a DecoratePositionInvariantPass and SPIRV-Reflect-based InstanceIndex detection 2026-07-20 08:35:00 -04:00
swung0x48 c81dd04f08 [Test] (CI, trace_replay): force the blended depth-write quirk on the Linux DirectVulkan OIT retrace lane and tighten that case's SSIM threshold to 0.995 2026-07-20 07:39:25 -04:00
swung0x48 c158bfa584 [Fix] (DirectVulkan): narrow the blended depth-write quirk to order-independent accumulation blends, exempting sorted-transparency, gl_FragDepth writers and fully masked attachments 2026-07-20 07:39:25 -04:00
swung0x48 f9f455144c [Refactor] (MG_Config, DirectVulkan): route the blended depth-write quirk through the FeaturesTable as MOBILEGL_MAGMA_DISABLE_BLENDED_DEPTH_WRITE instead of an ad-hoc getenv 2026-07-20 04:37:23 -04:00
swung0x48 64e4840de2 [Fix] (DirectVulkan): fall back to immutable images when the mutable probe fails, gate robustBufferAccess behind MOBILEGL_DISABLE_ROBUST_BUFFER_ACCESS, decode R32/RG32/R16-class readback formats, and warn when shaderStorageImage*WithoutFormat is unavailable 2026-07-20 02:36:26 -04:00
swung0x48 bf7b5755cc [Refactor] (ShaderTranspiler, MG_Backend, MG_Util): gate the subgroup prefix-scan rewrite behind a generic device-quirk registry with GPU vendor detection and MOBILEGL_QUIRK_SUBGROUP_PREFIX_SCAN override, warn on template mismatch, and block ARB/NV subgroup spellings 2026-07-20 02:36:26 -04:00
swung0x48 293f64b3c2 [Fix] (MG_Impl, DirectGLES): correct ARB_clear_texture error codes, reject cube maps in CopyTextureSubImage2D, advertise the extension on Espryt, and pin the error contracts with tests 2026-07-20 02:36:25 -04:00
swung0x48 f0cc07c937 [Perf] (DirectVulkan): bound vertex-stream conversion by the draw's real fetch range, reuse cached prefixes, pin cached source buffers, and stop repacking client arrays for pointer alignment 2026-07-20 02:36:25 -04:00
swung0x48 4658536652 [Perf] (DirectVulkan): keep the render pass alive for steady-state storage-image draws and skip storage-image collection for programs without them 2026-07-20 02:36:24 -04:00
swung0x48 04b4627c65 [Fix] (DirectVulkan): pass depth/stencil formats through sampled-view resolution so D24S8/D32FS8 samplers stop dropping draws, and memoize per-binding view-format resolution 2026-07-20 02:36:24 -04:00
swung0x48 68e13705c8 [Fix] (MG_Backend/DirectVulkan, ShaderTranspiler, MG_Test, TraceReplay): make iterationRP retrace pass on 64-lane Vulkan devices with subgroup-width emulation and format-aware readback 2026-07-20 02:36:23 -04:00
swung0x48 e5388c0e7e [Fix] (MG_Backend, MG_Impl, ShaderTranspiler, MG_Test): support iterationRP custom images and storage format reinterpretation 2026-07-20 02:35:30 -04:00
swung0x48 8bc4808b1a [Test] (TraceReplay): match the iterationRP fixture name published on the mirror 2026-07-19 23:09:29 -04:00
swung0x48 5d8a5387e2 [Test] (TraceReplay): try the hit.moe mirror before miawa and Git LFS 2026-07-19 22:29:55 -04:00
swung0x48 aa2184e47a [Test] (TraceReplay): register iterationRP in-world fixture (non-CI, fixture files pending LFS) 2026-07-19 21:39:06 -04:00
swung0x48 9152a4a4bc [Test] (TraceReplay): enable improved-transparency fixture in CI and drop unneeded coherent_as_flush 2026-07-19 07:35:34 -04:00
swung0x48 1963b427db [Refactor] (TraceReplay): reorganize trace skills into uniform packages with bundled scripts 2026-07-19 07:00:56 -04:00
swung0x48 f3def150e7 [Fix] (DirectVulkan): suppress blended depth writes on Qualcomm and mark gl_Position invariant to fix MC 26.3 OIT cloud flicker 2026-07-19 05:47:23 -04:00
swung0x48 fc0688c223 [Fix] (CI): stabilize Android retrace jobs 2026-07-18 19:52:04 -04:00
swung0x48 626c7f26fd [Test] (CMake, CI): enable top-level testing and label tests (unit/benchmark/integration) so ctest runs from the build root 2026-07-18 11:37:56 -04:00
swung0x48 1d947d934b [Feat] (TraceReplay): add RenderDoc Android capture tools 2026-07-18 11:25:07 -04:00
swung0x48 4203837648 [Feat] (trace-replay): register improved transparency fixture 2026-07-18 07:28:55 -04:00
swung0x48 f5cba4c2f1 [Docs] (trace-replay): unify Android trace runner docs 2026-07-18 07:06:56 -04:00
swung0x48 c2a1db3fcb [Feat] (trace-replay): add improved transparency fixture 2026-07-18 05:34:01 -04:00
swung0x48 594916850f [Fix] (MG_State, MG_Backend/DirectVulkan): bump the texture bind generation when a context default texture crosses the undefined<->defined boundary so cached sampled sets re-resolve, and collect the fallback texture into the sampled set so its first use transitions outside the render pass 2026-07-17 22:33:31 -04:00
swung0x48 c718d6bad8 [Fix] (MG_Test/Backend/DirectVulkan): link the whole MobileGL_s archive on MSVC so dllimport-declared gl*/egl* references resolve against the in-library entry points 2026-07-17 21:32:17 -04:00
swung0x48 abfda60ff1 [Perf] (MG_Backend/DirectGLES): check the unbind cache before activating the texture unit so the bind-0 sweep stops issuing redundant glActiveTexture per draw 2026-07-17 21:32:16 -04:00
swung0x48 92cced9bcc [Fix] (MG_State, MG_Impl, MG_Test): enforce strict GL 3.3 core rules only on contexts that explicitly request a core profile - texture deleted-name reservation keep and VAO-0 draws relax otherwise or under MOBILEGL_RELAXED_SEMANTICS, and GL_CONTEXT_PROFILE_MASK reports the requested profile 2026-07-17 21:32:16 -04:00
swung0x48 1929a7c546 [Fix] (MG_State, MG_Backend/DirectGLES): preserve legacy texture reuse and clear default backend bindings - keep generated-but-unbound names alive for Minecraft 1.7.10 atlas uploads, synchronize bind-0 to native GLES without 1D/2D alias churn, and cover both paths with BGRA sub-image and binding-cache regressions 2026-07-17 21:32:15 -04:00
swung0x48 df7f5a369d [Fix] (MG_Backend/DirectVulkan): render passes had zero subpass dependencies and same-layout transitions emit no barrier, so tilers could race tile loads against prior passes' stores (flickering artifacts in multi-pass chains like MC 26.3 OIT); add conservative external dependencies both ways 2026-07-17 21:03:52 -04:00
swung0x48 0de9861da4 [Fix] (MG_Backend/DirectVulkan): render-pass cache grew unbounded; age entries per present and evict after 1024 unused frames 2026-07-17 20:03:54 -04:00
swung0x48 6b223e4d23 [Fix] (MG_Backend/DirectVulkan): blendEnable was baked into pipelines without checking VK_FORMAT_FEATURE_COLOR_ATTACHMENT_BLEND_BIT; disable blending on formats that lack it 2026-07-17 20:03:53 -04:00
swung0x48 48568cdb89 [Fix] (MG_Backend/DirectVulkan): deferred glClear/glClearBuffer ignored color/depth/stencil write masks; gate the queued planes like the scissored path 2026-07-17 20:03:53 -04:00
swung0x48 8d83dedc0f [Fix] (MG_Backend/DirectVulkan): pending deferred clears outlived blit/copy writes into the same texture and later stomped them (OIT's cloud_depth copy was erased by its own earlier queued clear); materialize destination pending clears before blit/copy writes 2026-07-17 19:24:55 -04:00
swung0x48 a25d8ee0e7 [Fix] (MG_Backend/DirectGLES): GLES clamps glClearColor to [0,1], zeroing the -FLT_MAX MAX-blend identity; route out-of-range color clears through glClearBufferfv 2026-07-17 11:45:55 -04:00
swung0x48 c30bd0fabb [Fix] (MG_Backend/DirectGLES, MG_Impl/GLImpl): draw/read-buffer state could land on the wrong FBO (glDrawBuffer's static-array latch; SyncToBackend emitting glDrawBuffers/glReadBuffer for the non-bound target; no resync on bound-FBO attachment/drawbuffer edits) leaving MC 26.3's OIT color clears as no-ops; apply per bound target and track the FBO object version 2026-07-17 11:45:54 -04:00
swung0x48 c9fbf79d6a [Fix] (MG_Backend/DirectGLES): blend equations were never synced to the driver (OIT's GL_MAX ran as ADD); diff and emit glBlendEquationSeparate(i) alongside the factor sync 2026-07-17 11:45:53 -04:00
swung0x48 f39e8738da Merge origin/dev (readback overhaul c6d22e6e) into default-texture-objects - true per-target default texture objects supersede the readback branch texture-0 silent no-ops: removed the null-slot early-outs in TexImage1D/2D/3D(Multisample) and TexBuffer plus the DefaultTextureOperationsAreSilentNoOps test so name-0 operations actually (re)specify the default objects; deduped the shared state-reset fixes, keeping upstream std::clamp for GL_MAX_UNIFORM_BUFFER_BINDINGS, the Int-typed ActiveTexture combined-units range check, renderbuffer name-0 unbind, and vertex-attrib-0 current-value writes with the attrib-0 round-trip test 2026-07-16 23:50:47 -04:00
swung0x48 c6d22e6ece Merge branch 'dev' of https://github.com/MobileGL-Dev/MobileGL into dev 2026-07-16 23:38:48 -04:00
swung0x48 981f10e4da [Fix] (MG_Impl/GLImpl): unblock the non-texture sections of GL CTS per-case state reset - clamp advertised GL_MAX_UNIFORM_BUFFER_BINDINGS to the state layer indexed-binding capacity (glBindBufferBase rejected indices past it), let glBindRenderbuffer(0) unbind without recording INVALID_OPERATION (name 0 must never reach the name-table lookup), and allow writes to generic vertex attribute 0 current value (core GL has no attribute-0 restriction; gluStateReset writes vertexAttrib4f(0,...) after every case) - with these plus the default-texture work, multi-case glcts batches complete in one process instead of aborting after the first case 2026-07-16 23:36:58 -04:00
swung0x48 076cd0d19d [Feat] (MG_State, MG_Impl/GLImpl): per-target default texture objects (name 0) - binding 0 binds a real per-context default object (the initial binding of every unit/target slot, rebound on delete of a bound texture), so glTexImage*/glTexParameter*/glGetTex* on it work like any texture while glIsTexture(0)/Gen/Delete keep excluding it and TexStorage* rejects it per spec; backends skip image-less defaults as cheaply as the old null slots (DirectGLES per-draw sync/bind loops, DirectVulkan sampler-fallback resolve); also accept the full advertised GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS range in glActiveTexture, allow zero-layer TexImage3DMultisample, and let glTexBuffer(buffer=0) detach - the texture section of GL CTS per-case state reset (gluStateReset) now runs clean 2026-07-16 23:36:43 -04:00
swung0x48 5cd82f2002 Merge origin/dev (efd7b473) into readback overhaul - unify DirectGLES 2D-array target support under MapToBackendTextureTarget, keep canonical UNorm8 shadows for RGBA4/RGB565 (supersedes packed-word transfer types; GL_RGB565 aliases RGB5), keep upstream GLSL 330 normalization, anisotropy params, error-count semantics and VK clear/scissor fixes 2026-07-16 23:17:37 -04:00
swung0x48 d4922cb0fb [Fix] (MG_Backend, MG_Impl/GLImpl, MG_Util): make anisotropic filtering actually reachable - advertise GL_EXT/ARB_texture_filter_anisotropic only where the host driver or the samplerAnisotropy device feature supports it, answer GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT from the backend limit, and honor the sampler state on DirectVulkan (feature enable, limit clamp, LINEAR-only gate, resolved value in the sampler cache key) 2026-07-16 22:59:11 -04:00
swung0x48 870d882fef [Fix] (MG_Backend/DirectGLES, MG_Impl/GLImpl, MG_Util): GL CTS packed_pixels + texture_swizzle readback overhaul - canonical shadow layouts for legacy sized/unsized/packed internal formats (RGB5->RGB565, RGB10/12->RGB16, RGBA2->RGBA4, RGB10_A2(UI)/RGB9_E5/R11F_G11F_B10F packed-word shadows with per-texel encode/decode incl. 5_9_9_9_REV and 10F_11F_11F_REV client types), GL_UNSIGNED_INT_10_10_10_2 pixel type mapping, conversion-first GetTexImage with CPU-shadow fallback for non-attachable formats and stale-temp-FBO detach, narrow implementation read pairs + SNORM read candidates + 2_10_10_10_REV wide-read decode with RGBA expansion, PACK image/skip and SWAP_BYTES honored on the CPU repack (never in ES), state-reset conformance (default-texture TexParameter/TexImage/TexBuffer no-ops, renderbuffer 0 unbind, vertex attrib 0 current value, ActiveTexture up to combined units, UBO binding count clamp), FramebufferTexture3D/TextureLayer slice attachments via glFramebufferTextureLayer, capability-driven FBO UNSUPPORTED for non-renderable colors, ReadPixels integer-ness mismatch error, single-value texture swizzle validation, and DirectGLES 1D/1D-array/2D-array texture emulation (2D/2D-array backend targets matching SPIRV-Cross ES 1D-as-2D shaders) 2026-07-16 22:41:54 -04:00
swung0x48 e2f873c95c [Fix] (MG_Util/ShaderTranspiler): retry a legacy shader at 460 when it fails to parse as normalized 330 core, so sources using 420-era syntax without the matching #extension line keep compiling as they did on real drivers 2026-07-16 22:33:30 -04:00
swung0x48 efd7b47388 [Chore] (MG_Test): assert exact GL error counts - name-lifecycle regression tests per object family, plus fixtures that drain on setup and fail the test that leaks an unconsumed error 2026-07-16 22:12:12 -04:00
swung0x48 a08669df72 [Fix] (MG_Impl/GLImpl): stop recording GL errors on the delete/query paths of every object family - glDeleteBuffers/VertexArrays/Renderbuffers/Framebuffers must silently ignore unknown names and glIsTexture must never raise, while glBindSampler now reports INVALID_OPERATION like the other bind entry points 2026-07-16 22:11:43 -04:00
swung0x48 b8db509581 [Fix] (MG_Util/ShaderTranspiler): normalize legacy desktop shaders to GLSL 330 2026-07-16 21:39:39 -04:00
swung0x48 5d6b544021 [Fix] (MG_Impl/Texture): support anisotropic sampler parameters 2026-07-16 21:39:38 -04:00
swung0x48 346cd417ca [Fix] (MG_Backend/DirectVulkan): fix ERROR-level vertex stream build 2026-07-16 21:36:22 -04:00
swung0x48 f61675e9ce [Fix] (MG_Impl/Texture): validate the bound texture before dereferencing it in TexSubImage2D, and stop recording an error when glDeleteTextures is handed unknown names 2026-07-16 21:34:40 -04:00
swung0x48 8026838563 [Fix] (MG_Backend/DirectVulkan): honor scissor in glClearBuffer*/glClearNamedFramebuffer* and clamp their depth clear values to [0,1] 2026-07-16 21:18:01 -04:00
swung0x48 5bd8fa8c4e [Perf] (MG_Backend/DirectVulkan): route full-coverage scissored glClear back to the deferred loadOp path, skip render-pass churn for no-op clears, and drop the per-clear heap Vector (extracted PrepareScissoredClear) 2026-07-16 21:18:00 -04:00
swung0x48 37ef2cb600 [Fix] (MG_Backend/DirectVulkan): materialize mid-pass pending color clears at the subpass color slot index, not the compacted description index 2026-07-16 21:18:00 -04:00
swung0x48 5184901a5b [Fix] (MG_Backend/DirectVulkan): clear every layer of layered framebuffers in vkCmdClearAttachments paths (rename the never-read RenderPassEntry::subpass to layers) 2026-07-16 21:17:59 -04:00
swung0x48 4172959e49 [Fix] (MG_Backend/DirectVulkan): honor the front stencil write mask in scissored glClear and drop a redundant compatibility re-check 2026-07-16 21:17:58 -04:00
swung0x48 eb5b4bca3e [Fix] (MG_Backend/DirectVulkan): ignore glClear/glClearBuffer* while GL_RASTERIZER_DISCARD is enabled, and early-out on an empty clear mask 2026-07-16 21:17:58 -04:00
swung0x48 56db115a1a [Fix] (MG_Impl/GLImpl): clamp glClearDepth to [0,1] per GL 3.3 (Vulkan clear values require it) 2026-07-16 21:17:57 -04:00
swung0x48 b14edd515a Merge branch 'worktree-agent-a1381c9e6b342e8d4' into dev 2026-07-16 19:47:52 -04:00
swung0x48 57030b5fb9 [Chore] (MG_Test/Texture): regression tests for 2D-array unpack subcuboid selection and TexStorage3D layer-count semantics, DirectGLES 2D-array target support, packed-format canonical transfer types, and the GL_RGB565 enum round-trip 2026-07-16 19:44:37 -04:00
swung0x48 72532de780 [Fix] (MG_Util/Texture, MG_Util/Converters): canonical packed transfer types for RGBA4/RGB565/RGB10_A2UI - NormalizePixelFormat's default handed backends GL_UNSIGNED_BYTE (and a non-integer GL_RGB transfer format for RGB10_A2UI), so uploads read 4 bytes per texel from 2-byte packed shadow rows (rgba4 layers shifted by 2x slice stride) or were rejected outright; also map GL_RGB565 <-> TextureInternalFormat::RGB5 (the enum had no GL_RGB565 mapping at all, glTexImage* with it failed as unknown) 2026-07-16 19:44:36 -04:00
swung0x48 25323bfb8e [Fix] (MG_Backend/DirectGLES, MG_Impl/GLImpl): sync GL_TEXTURE_2D_ARRAY textures to the ES backend - the target was skipped as unsupported so array textures never uploaded or bound (every KHR-GL33.pixelstoragemodes.teximage3d case failed); also keep array layer counts constant across mip levels in TexStorage3D and generated-mip storage allocation (only true 3D textures halve depth) 2026-07-16 19:44:20 -04:00
swung0x48 9ed5dbf483 [Perf] (MG_Backend/DirectVulkan): return VkBufferResource by raw pointer from GetOrCreateResource to drop per-draw SharedPtr refcounting 2026-07-16 18:34:55 -04:00
swung0x48 3ca57068a8 Merge branch 'worktree-agent-a7bc533bede191e68' into dev 2026-07-16 16:37:58 -04:00
swung0x48 075471cdbd Merge branch 'worktree-agent-a7bc533bede191e68' into dev 2026-07-16 16:37:58 -04:00
swung0x48 62a0ad5639 [Fix] (MG_Backend/DirectGLES, MG_Util/ShaderTranspiler): make the uniform-block cross-stage precision fix surgical - revert the global SPVC ES highp-default options (they changed emission for EVERY fragment shader: sampling code that used to inherit the effective highp default was suddenly printed as explicit mediump, regressing KHR-GL3x.texture_repeat_mode NPOT mip cases on device) and instead strip RelaxedPrecision member decorations from uniform-block-reachable structs in a DirectGLES-only SPIR-V pass, so matched blocks declare identical (highp) member precision in both stages and every other shader keeps its previous emission byte-for-byte 2026-07-16 16:36:28 -04:00
swung0x48 8bf8f6f906 [Fix] (MG_Backend/DirectGLES, MG_Util/ShaderTranspiler): make the uniform-block cross-stage precision fix surgical - revert the global SPVC ES highp-default options (they changed emission for EVERY fragment shader: sampling code that used to inherit the effective highp default was suddenly printed as explicit mediump, regressing KHR-GL3x.texture_repeat_mode NPOT mip cases on device) and instead strip RelaxedPrecision member decorations from uniform-block-reachable structs in a DirectGLES-only SPIR-V pass, so matched blocks declare identical (highp) member precision in both stages and every other shader keeps its previous emission byte-for-byte 2026-07-16 16:36:28 -04:00
swung0x48 249c1ca574 [Fix] (MG_Backend/DirectVulkan): honor scissor in glClear 2026-07-16 12:39:55 -04:00
swung0x48 6a843b3088 [Fix] (MG_Backend/DirectVulkan): honor scissor in glClear 2026-07-16 12:39:55 -04:00
swung0x48 2e94314b78 Merge branch 'worktree-agent-a7bc533bede191e68' into dev 2026-07-16 12:12:47 -04:00
swung0x48 c59c15f66a Merge branch 'worktree-agent-a7bc533bede191e68' into dev 2026-07-16 12:12:47 -04:00
swung0x48 4d1613ba55 [Fix] (MG_Util/ShaderTranspiler, MG_State, MG_Impl/GLImpl, MG_Backend/DirectGLES): GL CTS uniform_block - coerce packed/shared block layouts to std140 at source preprocess (glslang rejects them when targeting SPIR-V; std140 is the only UBO layout the pipeline emits), GL-style block reflection (array "[0]" names, per-element struct-array expansion, unused members and declared-but-unread blocks stay active), vec4-padded GL_UNIFORM_BLOCK_DATA_SIZE, std140 array strides for struct-nested arrays (glslang reflects tight strides there), arrayed-block instances share the first instance member set, glDeleteShader-flagged names stay usable while attached, and backend ESSL emits against highp default precision so relaxed block members match across stages (KHR-GL33.shaders.uniform_block on llvmpipe: 659 Fail -> 828/828 Pass) 2026-07-16 12:09:11 -04:00
swung0x48 254cf1dc21 [Fix] (MG_Util/ShaderTranspiler, MG_State, MG_Impl/GLImpl, MG_Backend/DirectGLES): GL CTS uniform_block - coerce packed/shared block layouts to std140 at source preprocess (glslang rejects them when targeting SPIR-V; std140 is the only UBO layout the pipeline emits), GL-style block reflection (array "[0]" names, per-element struct-array expansion, unused members and declared-but-unread blocks stay active), vec4-padded GL_UNIFORM_BLOCK_DATA_SIZE, std140 array strides for struct-nested arrays (glslang reflects tight strides there), arrayed-block instances share the first instance member set, glDeleteShader-flagged names stay usable while attached, and backend ESSL emits against highp default precision so relaxed block members match across stages (KHR-GL33.shaders.uniform_block on llvmpipe: 659 Fail -> 828/828 Pass) 2026-07-16 12:09:11 -04:00
swung0x48 607e84deed Merge branch 'worktree-agent-af155789372f0003b' into dev 2026-07-16 11:30:03 -04:00
swung0x48 df0e9fca71 Merge branch 'worktree-agent-af155789372f0003b' into dev 2026-07-16 11:30:03 -04:00
swung0x48 b831dae8d5 [Feat] (MG_Backend/DirectGLES): packed-type readback encoding - repack wide RGBA reads into all GL 3.3 packed pixel types (3_3_2/2_3_3_REV, 5_6_5(_REV), 4_4_4_4(_REV), 5_5_5_1/1_5_5_5_REV, 8_8_8_8(_REV), 10_10_10_2/2_10_10_10_REV, packed-float 10F_11F_11F_REV and shared-exponent 5_9_9_9_REV) for ReadPixels/GetTexImage; conversion helpers extracted to context-free ReadbackImpl (Utils.cpp) with unit tests asserting exact packed words against the GL CTS pack_* oracle layouts 2026-07-16 11:08:02 -04:00
swung0x48 0005a50517 [Feat] (MG_Backend/DirectGLES): packed-type readback encoding - repack wide RGBA reads into all GL 3.3 packed pixel types (3_3_2/2_3_3_REV, 5_6_5(_REV), 4_4_4_4(_REV), 5_5_5_1/1_5_5_5_REV, 8_8_8_8(_REV), 10_10_10_2/2_10_10_10_REV, packed-float 10F_11F_11F_REV and shared-exponent 5_9_9_9_REV) for ReadPixels/GetTexImage; conversion helpers extracted to context-free ReadbackImpl (Utils.cpp) with unit tests asserting exact packed words against the GL CTS pack_* oracle layouts 2026-07-16 11:08:02 -04:00
swung0x48 9f302373d6 [Fix] (MG_Impl/GLImpl): TexImage3D - apply ConvertInternalFormatToSized like 2D/1D so unsized-internal 3D uploads get channel/type conversion, skip proxy shadow allocation, auto-generate mipmaps; TexSubImage3D - bound level and region against the target mip 2026-07-16 10:54:48 -04:00
swung0x48 f896c7396f [Fix] (MG_Impl/GLImpl): TexImage3D - apply ConvertInternalFormatToSized like 2D/1D so unsized-internal 3D uploads get channel/type conversion, skip proxy shadow allocation, auto-generate mipmaps; TexSubImage3D - bound level and region against the target mip 2026-07-16 10:54:48 -04:00
swung0x48 6ca48e40fe [Feat] (MG_State, MG_Util, MG_Impl/GLImpl, MG_Backend/DirectGLES): desktop-GL single-channel client formats GL_GREEN/GL_BLUE/GL_ALPHA and _INTEGER variants - validate and readback via wide-RGBA channel extraction (GL CTS packed_pixels rgba8_format_green/blue read with them), unpack GREEN/BLUE(_INTEGER) TexImage uploads into the named channel with 0/1 defaults per table 3.3; GL_ALPHA keeps the legacy Red upload mapping (R8 storage + 000R swizzle), its readback corrected at the backend to source channel 3 2026-07-16 06:47:33 -04:00
swung0x48 1cefb9780b [Feat] (MG_State, MG_Util, MG_Impl/GLImpl, MG_Backend/DirectGLES): desktop-GL single-channel client formats GL_GREEN/GL_BLUE/GL_ALPHA and _INTEGER variants - validate and readback via wide-RGBA channel extraction (GL CTS packed_pixels rgba8_format_green/blue read with them), unpack GREEN/BLUE(_INTEGER) TexImage uploads into the named channel with 0/1 defaults per table 3.3; GL_ALPHA keeps the legacy Red upload mapping (R8 storage + 000R swizzle), its readback corrected at the backend to source channel 3 2026-07-16 06:47:33 -04:00
swung0x48 a1a8a18575 [Fix] (MG_Backend/DirectGLES, MG_Impl/GLImpl): ReadPixels - fall back to wide-format conversion when the ES driver rejects a legacy native read combo (Adreno errors on e.g. GL_RED/GL_UNSIGNED_INT and leaves the buffer untouched), and enforce packed-type/format pairing at the state layer via shared ValidateClientFormatTypePairing (GL_RED + GL_UNSIGNED_SHORT_5_6_5 now raises GL_INVALID_OPERATION) 2026-07-16 06:11:53 -04:00
swung0x48 bae222227a [Fix] (MG_Backend/DirectGLES, MG_Impl/GLImpl): ReadPixels - fall back to wide-format conversion when the ES driver rejects a legacy native read combo (Adreno errors on e.g. GL_RED/GL_UNSIGNED_INT and leaves the buffer untouched), and enforce packed-type/format pairing at the state layer via shared ValidateClientFormatTypePairing (GL_RED + GL_UNSIGNED_SHORT_5_6_5 now raises GL_INVALID_OPERATION) 2026-07-16 06:11:53 -04:00
swung0x48 37a050b106 [Fix] (MG_Backend/DirectGLES): upload shadow mips with UNPACK_ALIGNMENT=1 - shadow rows are tightly packed but uploads ran with alignment 4, shifting every row of non-multiple-of-4-width textures by one pixel (R8 7-wide CTS gradients read back diagonally) 2026-07-16 05:52:01 -04:00
swung0x48 12a67f596c [Fix] (MG_Backend/DirectGLES): upload shadow mips with UNPACK_ALIGNMENT=1 - shadow rows are tightly packed but uploads ran with alignment 4, shifting every row of non-multiple-of-4-width textures by one pixel (R8 7-wide CTS gradients read back diagonally) 2026-07-16 05:52:01 -04:00
swung0x48 164bfd810b [Fix] (MG_State/ErrorState): GL error flags are sticky per error code, not an unbounded queue - repeated same-code errors accumulated and leaked into later unrelated glGetError checks (GL CTS "Texture state reset failed" deinit noise and false "Error during glGetTexImage" failures) 2026-07-16 05:29:46 -04:00
swung0x48 274c234aff [Fix] (MG_State/ErrorState): GL error flags are sticky per error code, not an unbounded queue - repeated same-code errors accumulated and leaked into later unrelated glGetError checks (GL CTS "Texture state reset failed" deinit noise and false "Error during glGetTexImage" failures) 2026-07-16 05:29:46 -04:00
swung0x48 b8dc4a6004 [Fix] (MG_Util/Texture): expand channels and convert component types on texture unpack to the internal shadow layout 2026-07-16 04:39:57 -04:00
swung0x48 20e1b417cc [Fix] (MG_Util/Texture): expand channels and convert component types on texture unpack to the internal shadow layout 2026-07-16 04:39:57 -04:00
swung0x48 3e8c8b756f Merge branch 'worktree-agent-acd555500daee6840' into dev 2026-07-16 04:13:25 -04:00
swung0x48 4dbdbd3bcd Merge branch 'worktree-agent-acd555500daee6840' into dev 2026-07-16 04:13:25 -04:00
swung0x48 763d4c3207 [Fix] (CI): resume interrupted fixture downloads 2026-07-16 04:11:48 -04:00
swung0x48 5eeba29579 [Fix] (CI): resume interrupted fixture downloads 2026-07-16 04:11:48 -04:00
swung0x48 9351d66dbc Merge branch 'worktree-agent-a08726da20d78531a' into dev
# Conflicts:
2026-07-16 03:57:12 -04:00
swung0x48 dae8a40af1 Merge branch 'worktree-agent-a08726da20d78531a' into dev
# Conflicts:
2026-07-16 03:57:12 -04:00
swung0x48 e9bd520d9b [Feat] (MG_Backend/DirectVulkan): implement combined depth-stencil texture upload via per-aspect de-interleaved staging copies 2026-07-16 03:54:33 -04:00
swung0x48 8b78379f6f [Feat] (MG_Backend/DirectVulkan): implement combined depth-stencil texture upload via per-aspect de-interleaved staging copies 2026-07-16 03:54:33 -04:00
swung0x48 1dc217b32c [Fix] (MG_Util/Metrics): correct Depth32FStencil8 shadow texel size (16->8) and FLOAT_32_UNSIGNED_INT_24_8_REV type size (4->8) to the GL client transfer layout 2026-07-16 03:54:33 -04:00
swung0x48 535e9f8b15 [Fix] (MG_Util/Metrics): correct Depth32FStencil8 shadow texel size (16->8) and FLOAT_32_UNSIGNED_INT_24_8_REV type size (4->8) to the GL client transfer layout 2026-07-16 03:54:33 -04:00
swung0x48 35626da5c4 [Fix] (MG_Util/Texture): infer RGBA8 for packed RGBA uploads
(cherry picked from commit 1146188ed4)
2026-07-16 03:41:29 -04:00
swung0x48 b9844ed7c1 [Fix] (MG_Util/Texture): infer RGBA8 for packed RGBA uploads
(cherry picked from commit 1146188ed4)
2026-07-16 03:41:29 -04:00
swung0x48 8496e7c7eb [Fix] (MG_Backend/DirectGLES): convert narrow client formats (RED/RG/RGB/BGR/BGRA + integer variants, byte/short/half/8888 types) in GetTexImage/ReadPixels via wide RGBA readback 2026-07-16 03:40:54 -04:00
swung0x48 f0ed5c1b8e [Fix] (MG_Backend/DirectGLES): convert narrow client formats (RED/RG/RGB/BGR/BGRA + integer variants, byte/short/half/8888 types) in GetTexImage/ReadPixels via wide RGBA readback 2026-07-16 03:40:54 -04:00
swung0x48 c247ad5807 Merge branch 'worktree-agent-aae96e27d8b07e982' into dev 2026-07-16 03:32:39 -04:00
swung0x48 b604188849 Merge branch 'worktree-agent-aae96e27d8b07e982' into dev 2026-07-16 03:32:39 -04:00
swung0x48 7514587b5a [Fix] (MG_Impl/GLImpl, MG_State): fallback UBO backing for optimizer-eliminated uniforms (null-MapUBO SIGSEGV in KHR-GL33 do_while loops) + per-element locations/offsets for array uniforms incl. nested struct arrays (size assert in KHR-GL33 struct.uniform); demote uniform write assert to log-and-clamp 2026-07-16 03:31:32 -04:00
swung0x48 cf8f928db8 [Fix] (MG_Impl/GLImpl, MG_State): fallback UBO backing for optimizer-eliminated uniforms (null-MapUBO SIGSEGV in KHR-GL33 do_while loops) + per-element locations/offsets for array uniforms incl. nested struct arrays (size assert in KHR-GL33 struct.uniform); demote uniform write assert to log-and-clamp 2026-07-16 03:31:32 -04:00
swung0x48 5b38f61961 [Fix] (MG_Backend): GetTexImage level-range check was off-by-one (max level is inclusive; single-level textures asserted on level 0), demoted to logged skip; advertise GL_ARB_texture_storage_multisample (entry points already implemented - unadvertised extension left null glw pointers and CTS framebuffer_blit jumped to address 0) 2026-07-16 03:06:03 -04:00
swung0x48 176d130f09 [Fix] (MG_Backend): GetTexImage level-range check was off-by-one (max level is inclusive; single-level textures asserted on level 0), demoted to logged skip; advertise GL_ARB_texture_storage_multisample (entry points already implemented - unadvertised extension left null glw pointers and CTS framebuffer_blit jumped to address 0) 2026-07-16 03:06:03 -04:00
swung0x48 8bdab8005b [Fix] (MG_Backend/DirectVulkan): skip combined depth-stencil texture data uploads instead of recording invalid single-copy with multi-bit aspect mask (VK_INCOMPLETE at vkEndCommandBuffer killed the process); proper per-aspect de-interleave tracked separately 2026-07-16 02:36:07 -04:00
swung0x48 0b94e02de5 [Fix] (MG_Backend/DirectVulkan): skip combined depth-stencil texture data uploads instead of recording invalid single-copy with multi-bit aspect mask (VK_INCOMPLETE at vkEndCommandBuffer killed the process); proper per-aspect de-interleave tracked separately 2026-07-16 02:36:07 -04:00
swung0x48 273c7ebcf0 [Fix] (MG_Impl/GLImpl, MG_State, MG_Backend/DirectGLES): eliminate packed_pixels SIGTRAPs - complete TexImage format/type/internalformat validation matrix (depth-stencil family, integer-ness, packed-type pairing, 3D depth rejection), fix inverted UpdateSubData assert with clamped copy, demote unimplemented readback asserts to logged no-ops 2026-07-16 02:23:18 -04:00
swung0x48 fe7a5ee1b2 [Fix] (MG_Impl/GLImpl, MG_State, MG_Backend/DirectGLES): eliminate packed_pixels SIGTRAPs - complete TexImage format/type/internalformat validation matrix (depth-stencil family, integer-ness, packed-type pairing, 3D depth rejection), fix inverted UpdateSubData assert with clamped copy, demote unimplemented readback asserts to logged no-ops 2026-07-16 02:23:18 -04:00
swung0x48 3a40778c4b [Fix] (MG_Util/ShaderTranspiler): stop stripping precision qualifiers - the strip corrupted "precision highp float;" into invalid syntax; glslang accepts and ignores them natively in 460 core (unblocks ~2000 GL CTS cases per backend) 2026-07-16 01:50:33 -04:00
swung0x48 5331150cb9 [Fix] (MG_Util/ShaderTranspiler): stop stripping precision qualifiers - the strip corrupted "precision highp float;" into invalid syntax; glslang accepts and ignores them natively in 460 core (unblocks ~2000 GL CTS cases per backend) 2026-07-16 01:50:33 -04:00
swung0x48 37a7f35a27 [Chore] (MG_Backend/DirectGLES): demote UBO ring creation log to debug level 2026-07-16 00:10:14 -04:00
swung0x48 dc2f3a477b [Chore] (MG_Backend/DirectGLES): demote UBO ring creation log to debug level 2026-07-16 00:10:14 -04:00
swung0x48 c6ed9429be [Fix] (MG_Backend/DirectGLES): UBO ring - preserve generation across ES context recreation, retire frame marks at Present to bound growth 2026-07-16 00:10:14 -04:00
swung0x48 21753b0e4c [Fix] (MG_Backend/DirectGLES): UBO ring - preserve generation across ES context recreation, retire frame marks at Present to bound growth 2026-07-16 00:10:14 -04:00
swung0x48 cb6af44984 [Fix] (MG_Backend/DirectGLES): UBO ring review fixes - invalidate array-buffer bind cache on failed ring creation, bump generation on emergency drain, division-based alignment rounding 2026-07-16 00:10:13 -04:00
swung0x48 f509b19b1d [Fix] (MG_Backend/DirectGLES): UBO ring review fixes - invalidate array-buffer bind cache on failed ring creation, bump generation on emergency drain, division-based alignment rounding 2026-07-16 00:10:13 -04:00
swung0x48 7464179249 [Chore] (MG_Backend/DirectGLES): log global-UBO ring creation 2026-07-16 00:10:13 -04:00
swung0x48 c7ac5de28e [Chore] (MG_Backend/DirectGLES): log global-UBO ring creation 2026-07-16 00:10:13 -04:00
swung0x48 315e9cb194 [Perf] (MG_Backend/DirectGLES): replace per-draw global-UBO glBufferSubData with a persistent-mapped ring allocator (fence-watermark reclaimed, MOBILEGL_DISABLE_UBO_RING opt-out); scrub stale indexed-binding shadow on glDeleteBuffers 2026-07-16 00:10:12 -04:00
swung0x48 2e7073a890 [Perf] (MG_Backend/DirectGLES): replace per-draw global-UBO glBufferSubData with a persistent-mapped ring allocator (fence-watermark reclaimed, MOBILEGL_DISABLE_UBO_RING opt-out); scrub stale indexed-binding shadow on glDeleteBuffers 2026-07-16 00:10:12 -04:00
swung0x48 e8d9a913d8 [Fix] (MG_Util/SelfTest): preserve POST checks before format probing 2026-07-16 00:10:12 -04:00
swung0x48 305701326c [Fix] (MG_Util/SelfTest): preserve POST checks before format probing 2026-07-16 00:10:12 -04:00
swung0x48 4453f1910d [Feat] (MG_Backend, android-plugin): show format capability tables in POST 2026-07-16 00:10:11 -04:00
swung0x48 8c89b1618a [Feat] (MG_Backend, android-plugin): show format capability tables in POST 2026-07-16 00:10:11 -04:00
swung0x48 1b0be9a997 [Docs] (android-plugin): specify POST format capability tables 2026-07-15 22:36:56 -04:00
swung0x48 3e4ce5caa7 [Refactor] (MG_Impl/GLImpl): replace Flywheel dispatch sync hack with MOBILEGL_COHERENT_AS_FLUSH 2026-07-15 21:51:20 -04:00
swung0x48 f80f6f4a62 [Fix] (CI): retain fixtures for failed retraces 2026-07-15 04:36:15 -04:00
swung0x48 66caf907fd [Fix] (CI): remove intermediate trace artifacts 2026-07-15 02:52:03 -04:00
swung0x48 d3150399c7 [Fix] (CI): download direct trace APK artifact 2026-07-15 02:01:53 -04:00
swung0x48 f1c6a12c06 [Fix] (CI): use full commit SHAs 2026-07-15 01:33:56 -04:00
swung0x48 947442ec78 [Fix] (CI): resolve trace APK by SHA 2026-07-15 01:27:09 -04:00
swung0x48 165dd003d7 [Chore] (CI): clean intermediate artifacts 2026-07-15 00:53:50 -04:00
swung0x48 b852ced3c1 [Chore] (CI): upgrade GitHub Actions runtimes 2026-07-15 00:36:08 -04:00
swung0x48 4a03d62b91 [Fix] (CI): publish APK artifacts directly 2026-07-15 00:34:52 -04:00
swung0x48 056574eebe [Fix] (CI): name APK artifacts by commit 2026-07-15 00:22:12 -04:00
swung0x48 e61685547a [Fix] (CI): locate unified trace APK 2026-07-15 00:17:08 -04:00
swung0x48 7ebaf43282 [Refactor] (Android plugin): unify renderer APK with Plugin V2 DSL 2026-07-14 23:37:21 -04:00
swung0x48 15580ff6a6 [Fix] (Retrace): preserve bundled ANGLE binaries 2026-07-15 08:46:28 +08:00
swung0x48 fd6f5bca83 [Fix] (Retrace): rely on APK signing for bundled ANGLE 2026-07-15 07:50:40 +08:00
swung0x48 b6d311f20b [Fix] (Retrace): bundle and select signed ANGLE variants 2026-07-15 06:48:10 +08:00
swung0x48 9c0d5517bd [Refactor] (MG_Backend/DirectVulkan): replace null-renderer guards with MOBILEGL_ASSERT
Drops the if (!pVulkanRenderer) { return; } / !MG_State::pGLContext early-return guards across DirectVulkan.cpp in favor of MOBILEGL_ASSERT, matching the pattern already used by the rest of the backend. Legitimate runtime conditions (index bounds, sync/query handle nullness, renderer-generation mismatch, timer-query support) are kept as real checks; only the null-pointer defenses are converted.
2026-07-14 03:55:41 -04:00
swung0x48 3445ab9304 [Refactor] (MG_Backend/DirectVulkan, trace-replay): extract dump-image capture out of MobileGL backend
Moves snapshot capture entirely into the apitrace retrace layer (glReadPixels + PNG encode). Drops the MOBILEGL_PRESENT_DUMP_PATH / MOBILEGL_PRESENT_STATS / MOBILEGL_PRESENT_DUMP_CALL / MOBILEGL_PRESENT_CURRENT_CALL / MOBILEGL_TRACE_CURRENT_CALL_OVERRIDE plumbing from Config, ConfigLoader, VulkanRenderer (GetPresentedDumpPixel/WritePresentedDumpPpm + present-stats readback), the EGL/GLX/Android ws shims, and the Android trace_replay_core PPM reader.

DirectVulkan ReadPixels on the default framebuffer now remaps raw swapchain pixels (top-left origin, preTransform-rotated) to GL orientation (bottom-left origin) so the retrace snapshot matches the golden; SwapchainObject also resizes the default-FBO stencil attachment to the swapchain extent to fix GL_INVALID_FRAMEBUFFER_OPERATION under the glReadPixels completeness check.
2026-07-14 02:40:20 -04:00
swung0x48 533219ede7 [Fix] (Retrace): load ANGLE through LD_LIBRARY_PATH 2026-07-13 21:20:02 -04:00
swung0x48 b1f55026af [Chore] (MobileGL/ConfigLoader): rename/clean up more env var clutter 2026-07-13 20:45:40 -04:00
swung0x48 a26e9aaf25 [Refactor] (MG_Config, MG_Backend, trace-replay): remove unused stats instrumentation 2026-07-13 20:33:31 -04:00
swung0x48 a55a0645e2 [Refactor] (MG_Config, MG_Backend/DirectVulkan, trace-replay): centralize Magma env parsing and rename R11G11B10F fallback 2026-07-13 19:58:06 -04:00
swung0x48 e529e12d27 [Perf] (MG_Backend/DirectVulkan): bind GetBoundObject/GetSamplerObject const-ref returns by reference in BindProgramUniformBuffers resolve paths (UBO/SSBO/texel/sampler override) instead of copying the SharedPtr; ResolveUniformBufferPayload 2.2%->1.6% 2026-07-13 08:27:12 -04:00
swung0x48 e78eee972e [Perf] (MG_Backend/DirectVulkan): store the resolved TextureResource pointer in the per-draw sync memo so repeat SyncTextureAndGetDescriptor calls skip the resource-map lookup 2026-07-13 06:53:37 -04:00
swung0x48 37cd5b42de [Perf] (MG_Backend/DirectVulkan): drop redundant per-draw work in UploadAndBindVertexBuffers - pass programObj from SetupDraw, use the VAO attribute's buffer SharedPtr directly instead of re-resolving by external index; 8.5%->6.2% 2026-07-13 05:21:57 -04:00
swung0x48 7fe5247626 [Fix] (MG_Backend/DirectVulkan): key the sampled-set walk-skip on a program lifetime id, not the recyclable GL name, so a deleted+recreated program can't false-hit the cache 2026-07-13 04:58:05 -04:00
swung0x48 f098983c9f [Perf] (MG_Backend/DirectVulkan): skip the per-draw sampled-texture walk when the bound set is unchanged (texture-bind generation + program state version); CollectSampledTextures 5.0%->0.2%, fps 228->249 2026-07-13 04:41:14 -04:00
swung0x48 516d2a659e [Perf] (MG_Backend/DirectVulkan): cache resolved VkSampler per binding to skip the per-draw sampler key hash, keyed on a new sampler lifetime id 2026-07-13 02:04:57 -04:00
swung0x48 808c5dcc46 [Perf] (MG_Backend/DirectVulkan): re-land content-version texture early-out; bump content version on glGenerateMipmap so cached sampled views re-sync (fixes Iris shader retrace) 2026-07-13 00:50:09 -04:00
swung0x48 ecea8054a6 Revert content-version texture early-out (e8e1521): the SyncTexture cross-draw skip breaks Iris shader retrace validation (correctness regression) 2026-07-12 23:27:54 -04:00
swung0x48 b0076af9bd [Perf] (MG_Backend/DirectVulkan): raw-ptr in ResolveSamplerDescriptor drops the per-draw SharedPtr refcount on the sampler descriptor path 2026-07-12 22:48:05 -04:00
swung0x48 24cf1e3a7f [Perf] (MG_Backend/DirectVulkan): frames-in-flight from MOBILEGL_MAGMA_FRAMESINFLIGHT env (fallback 3), clamped to surface maxImageCount at init 2026-07-12 20:35:05 -04:00
swung0x48 e5ee4cde4f [Perf] (MG_Backend/DirectVulkan): deepen frame pipeline 2->3 to hide GPU-completion latency; cross-frame glClientWaitSync fence stalls -28% 2026-07-12 19:42:35 -04:00
swung0x48 e8e1521972 [Perf] (MG_Backend/DirectVulkan): skip cross-draw re-sync of unchanged textures via a content-version early-out; SyncTextureAndGetDescriptor 8.9%->2.4% 2026-07-12 18:40:48 -04:00
swung0x48 6f53b9a6bb [Perf] (MG_Backend/DirectVulkan): raw-ptr sampled-texture walk skips SharedPtr refcount churn per draw 2026-07-12 10:51:15 -04:00
swung0x48 acaa9f6dc7 [Perf] (MG_Backend/DirectVulkan): zero-copy UBO bind - point descriptor at the app's persistent VkBuffer instead of a per-draw transient copy; fps 127->166 2026-07-12 10:11:49 -04:00
swung0x48 375f2df694 [Perf] (MG_Backend/DirectVulkan): skip per-draw pipeline resolution when pipeline state unchanged; SetupDraw 54%->51%, fps 109->127 2026-07-12 09:28:30 -04:00
swung0x48 542e50be33 [Perf] (MG_Backend/DirectVulkan): skip per-draw render-pass hash when framebuffer state unchanged; SetupDraw 60%->54%, fps 96->109 2026-07-12 08:18:37 -04:00
swung0x48 ad9ee99521 [Perf] (MG_Backend/DirectGLES): dedup per-draw indexed UBO/SSBO binds with a shadow cache; BindCurrentProgramWithResources 5.1% -> 3.1% 2026-07-12 06:32:18 -04:00
swung0x48 25395a9f9a [Docs] (MG_Backend/DirectGLES): TODO for buffer-pool Phase 2 orphan-on-respecify 2026-07-12 05:37:03 -04:00
swung0x48 d7029952bb [Perf] (MG_Backend/DirectGLES): recycle idle GL buffers via a fence-gated size pool instead of glDeleteBuffers; pinned fps 184->220 2026-07-12 05:28:34 -04:00
swung0x48 340449b77e [Perf] (MG_State, MG_Backend/DirectGLES): skip never-touched buffer bind points via high-water mark; SyncNeccessaryBuffers 15.7% -> 4.2% 2026-07-12 04:31:34 -04:00
swung0x48 527e229ac8 [Perf] (MG_Backend/DirectGLES): drop redundant per-draw UBO binding-point sync; BindCurrentProgramWithResources already rebinds them 2026-07-12 04:11:23 -04:00
swung0x48 d5bc753764 [Perf] (MG_Backend/DirectGLES): skip scratch bind + upload for fully-synced mipmap textures 2026-07-12 04:11:22 -04:00
swung0x48 436f7f7e86 [Perf] (DirectGLES): shadow-track unpack state instead of glGetIntegerv
ScopedDefaultUnpackState saved the backend GL unpack state with 6 glGetIntegerv
calls on every construction. glGetIntegerv forces a driver pipeline sync, and
because it ran per dirty texture per frame in the texture upload path, it
dominated the DirectGLES draw path - and stalling the pipeline serialized CPU-GPU
work far beyond its raw CPU cost.

The backend unpack state is set only by MobileGL's own save/restore helpers
(ScopedDefaultUnpackState, TempPixelStoreParameterSync, the R32F copy path), all
of which restore to the resting GL default, so it can be shadow-tracked: read the
previous state from a static shadow (no query), pin the backend to the known
default once up front, and set state with compare-and-set so the paired
glPixelStorei calls also usually no-op.

Device-verified on Adreno 830 (MC 26.3-snapshot3, Espryt, CPU pinned to 1.56/1.96
GHz for a thermally-comparable measurement): rendering correct; fps 105 -> 147
(+40%); render-thread profile: glGetIntegerv ~9% -> below noise, SyncNeccessary-
Textures 25% -> 12%, SyncMipmapsToBackend 23% -> 9%.
2026-07-12 03:11:28 -04:00
swung0x48 009e37ec6f [Perf] (DirectVulkan): reuse descriptor set across draws with identical bindings
BindProgramUniformBuffers rebuilt a fresh descriptor set and called
vkUpdateDescriptorSets on every draw, even when consecutive draws bound the exact
same textures/samplers/buffers (common in MC: many draws share a program + atlas).
Now, after resolving the bindings (still needed for the UBO dynamic offset),
compute a cheap word-wise signature of the resolved descriptor content + layout;
when it matches the previous draw, reuse that descriptor set and skip
AcquireDescriptorSet + vkUpdateDescriptorSets - only the bind-time dynamic offsets
differ.

Correct by construction: bindings are re-resolved every draw so the signature
always reflects current state and reuse only happens on an exact match; the reused
set is never re-acquired within a frame (the acquire cursor only advances); the
descriptor set layout is in the signature so reuse never crosses programs; the
cache resets each frame in BeginFrame when the frame's sets are recycled; sampler
overrides (blits) bypass and invalidate it. The signature hashes 64-bit words (the
Vk*Info payloads are 8-byte-multiple sized and value-initialized) so its own
per-draw cost stays small.

Device-verified on Adreno 830 (MC 26.3-snapshot3, optimized -O2 Magma): rendering
correct, no validation errors. Render-thread wall-clock profile:
BindProgramUniformBuffers 22.85% -> 19.82% (vkUpdateDescriptorSets ~5% dropped below
noise; word-wise signature adds ~0.6% self), SetupDraw 62% -> 60%.
2026-07-12 01:55:31 -04:00
swung0x48andClaude Opus 4.8 b253df881d [Perf] (DirectVulkan): memoize per-draw texture sync in SetupDraw
Each sampled texture was resolved ~3x per draw: SetupDraw's layout-probe
loop, its post-transition loop, and again inside ResolveSamplerDescriptor.
No GL texture mutation happens mid-SetupDraw, and layout is tracked on the
TextureResource independently of SyncTexture, so the repeat SyncTexture work
(mip-completeness / resource+view resync / dirty scan) is pure redundancy.

Add a per-draw memo in VkTextureManager (BeginDrawSyncScope/EndDrawSyncScope
+ RAII DrawSyncScope guard around SetupDraw): after the first successful sync
of a texture in a draw, repeat SyncTextureAndGetDescriptor calls short-circuit
to the already-synced resource.

Device-verified on Adreno 830 (MC 26.3-snapshot3, Magma): rendering correct,
no validation errors; wall-clock profile of the render thread shows
SyncTextureAndGetDescriptor dropping from 15.2% to ~5% and SetupDraw from
43.7% to 28.9%.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-11 22:06:28 -04:00
swung0x48 c1743aa42d [Refactor] (MG_State, MG_Backend): PipeResource storage layer + zero-copy coherent persistent maps
Introduce a Mesa pipe_resource-style PipeResource that owns a GL buffer's bytes
and its backend GPU resource, abstracting WHERE the authoritative bytes live:
 - Shadow mode (non-persistent buffers): a CPU Vector; the backend keeps its own
   GPU copy in sync via BufferBackendOps, exactly as before.
 - Persistent mode (coherent GL_MAP_PERSISTENT maps): the backend's host-visible,
   COHERENT, persistently-mapped GPU memory is the single source of truth. The app
   writes into it directly, every reader resolves against it, and NO per-write
   backend transfer happens. The CPU shadow is released.

BufferObject no longer owns a raw shadow Vector; it holds a PipeResource and
exposes one accessor, MappedData(), that all readers go through. Every buffer-data
consumer (UBO payload, PBO texture upload, indirect draws, resident/streamed
uploads, both backends) was migrated from GetDataReadOnly()->data() to
MappedData(), so a persistent buffer's readers see GPU memory - not a stale
shadow. That stale-shadow inconsistency is what corrupted rendering (wrong UBOs ->
misplaced/"lost" vertices) in the first zero-copy attempt (625c8a6, reverted in
896cafc); routing every consumer through one accessor makes it structurally
impossible.

Backends provide the map via BufferBackendOps::AcquirePersistentMap:
 - DirectVulkan: a HOST_VISIBLE|HOST_COHERENT (required, not just requested),
   persistently mapped resident VkBuffer carrying every usage, seeded from the
   shadow, never recreated; AcquireResidentSlice binds it directly.
 - DirectGLES: EXT_buffer_storage immutable persistent+coherent glMapBufferRange,
   falling back to the shadow when the extension is absent.

Fixes the ~7GB GpuMemory OOM + 100%-CPU/ANR running modern Blaze3D Minecraft on
both Magma and Espryt (per-draw whole-buffer re-upload of the coherent persistent
ring buffer), without the coherency/stale-read hazards of the reverted attempt.

BufferTest: zero-copy stress guard (15,360 draws -> 0 per-draw transfers, and every
reader resolves to GPU memory) + a shadow-fallback test. Host suite: 203/203 pass.
Device verification pending.
2026-07-11 20:18:38 -04:00
swung0x48 0f99d93300 [Feat] (MobileGL): full dual-source blending across state, transpiler, and both backends
Wire GL_SRC1_* dual-source blend factors (glBlendFunc) end to end with the
glBindFragDataLocationIndexed color index, so a fragment shader can drive both
dual-source blend inputs.

State + converters:
  - RenderState BlendFactor gains Src1Color/OneMinusSrc1Color/Src1Alpha/
    OneMinusSrc1Alpha; GLToMG/MGToGL/MGToVk/MGToStr converters map them to
    GL_SRC1_*, VK_BLEND_FACTOR_SRC1_*, and readable names.

Transpiler layout(index = N):
  - ProgramAttrib carries explicitFragmentOutIndices; ProgramObject threads
    m_explicitFragDataIndex into it at both link sites.
  - TMglGlslIoResolver applies the color index as TQualifier.layoutIndex on the
    fragment output, emitting layout(index = 1) via the glslang Index decoration
    -> SPIRV-Cross path. Only the non-zero (dual-source) index is emitted: index 0
    is the GL default and an explicit "index = 0" would demand
    GL_EXT_blend_func_extended on GLES for ordinary single-source outputs.

Feature detection, POST, and hard-fail at use time (no silent fallback):
  - Vulkan: dualSrcBlend is detected at device creation and cached; a draw whose
    enabled blend state uses a SRC1 factor without the feature throws at pipeline
    build with the reason and a pointer to the POST row.
  - GLES: GL_EXT_blend_func_extended detected at load into
    GLESCapabilities.SupportsDualSourceBlend; a draw enabling blend with a SRC1
    factor without it throws in the blend-state sync with the same guidance.
  - DriverPost adds a dual-source-blend row for both backends (Pass/Warn).

Tests:
  - ProgramTest.CompileAndLinkWithExplicitFragmentOut now asserts the transpiled
    fragment shader carries layout(location = 0, index = 1) after a re-link with
    glBindFragDataLocationIndexed(index 1), and still omits any index qualifier
    for the plain index-0 output.
2026-07-11 01:32:07 -04:00
swung0x48 e9fa99e16b [Feat] (MG_Backend): wire primitive restart into both backends; detect dualSrcBlend
Make GL_PRIMITIVE_RESTART[_FIXED_INDEX] actually take effect at draw time,
following the detect-at-init / POST / fallback-or-hard-fail discipline.

DirectVulkan:
- Thread primitiveRestartEnable through the pipeline (payload + hash +
  input-assembly), set from the GL_PRIMITIVE_RESTART / _FIXED_INDEX caps.
- Detect and enable primitiveTopologyListRestart
  (VK_EXT_primitive_topology_list_restart) at device creation; cache it.
  Strip/fan restart needs no feature; a *list* topology with restart and
  no feature hard-fails at the draw with the reason.
- Vulkan only restarts on the fixed all-ones index value, so an arbitrary
  GL_PRIMITIVE_RESTART index that is not that value hard-fails in
  UploadAndBindIndexBuffer (where the index type is known).
- Also detect+enable and cache the dualSrcBlend base feature (groundwork
  for GL_SRC1_* dual-source blending).

DirectGLES:
- Sync GL_PRIMITIVE_RESTART_FIXED_INDEX from either restart cap (GLES core
  has only the fixed-index form); an arbitrary non-fixed index hard-fails
  in the indexed draw paths with the reason.

POST: dualSrcBlend and primitiveTopologyListRestart capability rows (Pass
when supported, Warn with the fallback/hard-fail consequence otherwise).

Library builds clean; SanityTest 31/31. (The actual restart rendering and
the hard-fail paths need a real GPU and are not runtime-testable here.)
2026-07-11 01:11:23 -04:00
swung0x48 e18d369adf [Feat] (MG_Impl/GLImpl, MG_State): implement glPrimitiveRestartIndex
Store the primitive restart index as render state and report it through
glGetIntegerv(GL_PRIMITIVE_RESTART_INDEX), replacing the stub and the
hardcoded 0 in the getter.

- RenderState gains a PrimitiveRestartIndex field (default 0) with
  set/get accessors and GLContext wrappers.
- glPrimitiveRestartIndex accepts any GLuint and generates no error.
- glGetIntegerv(GL_PRIMITIVE_RESTART_INDEX) now reads the stored value.

This is the state layer only. The backends do not yet honor an arbitrary
restart index at draw time -- Vulkan and GLES support only the fixed
all-ones restart value (GL_PRIMITIVE_RESTART_FIXED_INDEX) -- so a non-
default index is tracked and queryable but not yet applied to indexed
draws.

Tests: RenderStateSanity round-trip (default 0, mid value, and the full
32-bit range). Full SanityTest sweep green (31/31).
2026-07-11 00:43:45 -04:00
swung0x48 22ac8a8c10 [Feat] (MG_Impl/GLImpl, MG_State): implement glBindFragDataLocationIndexed
Bind a fragment output to both a color number and a color index (0 or 1
for dual-source blending), and report the bound index back through
glGetFragDataIndex.

- ProgramObject now tracks a per-output color index alongside the
  location: SetExplicitFragmentOutIndex stores it, it is snapshotted into
  the linked map at link time (like the location map), and
  GetFragmentDataIndex returns it (0 by default) for an active output.
- glBindFragDataLocation becomes glBindFragDataLocationIndexed with index
  0, matching the GL definition, so it also resets a previously-bound
  index to 0.
- Validation: index must be 0 or 1 (GL_INVALID_VALUE); colorNumber is
  bounded by GL_MAX_DRAW_BUFFERS for index 0 and GL_MAX_DUAL_SOURCE_DRAW_BUFFERS
  (reported as 1) for index 1 (GL_INVALID_VALUE); a gl_ name is
  GL_INVALID_OPERATION.
- glGetFragDataIndex now returns the real bound index instead of a
  hardcoded 0.

The index is tracked for reflection but is not yet plumbed into dual-source
blend rendering, and shader-side layout(index=) qualifiers are not
reflected -- both documented at the call sites.

Tests: index round-trip through a re-link (bind 1 -> GetFragDataIndex == 1;
glBindFragDataLocation resets to 0), plus the validation error table;
mutation-verified end to end. ProgramTest 24/24.
2026-07-11 00:39:23 -04:00
swung0x48 bebe534bad [Fix] (MG_Impl/GLImpl): stop double-recording GL errors for a bad program handle
glBindFragDataLocation, glGetFragDataLocation and glGetFragDataIndex each
recorded a redundant GL_INVALID_OPERATION on top of the error that
TryToGetProgramObject already recorded (GL_INVALID_VALUE for an unknown
name, GL_INVALID_OPERATION for a non-program object). One bad call thus
queued two errors, so an app calling glGetError twice saw a spurious
second error, and any following code that expects a clean error queue
(e.g. a later test) picked up the stale one.

Drop the second RecordError from all three call sites and rely on the
single error TryToGetProgramObject already reports -- matching the clean
`if (!programObject) return;` pattern the rest of GL_Program.cpp uses. The
first, app-visible error is unchanged; only the redundant second is gone.

ProgramTest's invalid-handle case now asserts exactly one error (mutation-
verified: reintroducing the second record fails it) and keeps a defensive
error-queue drain. ProgramTest 24/24.
2026-07-11 00:19:33 -04:00
swung0x48 9ffcb23877 [Feat] (MG_Impl/GLImpl): implement glGetFragDataIndex
Fill the stubbed GL 3.3 Core glGetFragDataIndex, mirroring its already-
implemented sibling glGetFragDataLocation: validate the program object and
link status, then return the fragment color index the name binds to.

Every active user-defined output uses color index 0. MobileGL does not yet
track dual-source (index 1) bindings -- glBindFragDataLocationIndexed and
the layout(index = 1) qualifier are unsupported -- so the result is exact
for any program that does not use dual-source blending; a name that is not
an active output (including gl_ built-ins) returns -1.

Tests: assertions on the existing linked-program test (valid output -> 0,
unknown name -> -1) plus a standalone invalid-handle case. The invalid-
handle test drains the error queue it produces so no stale error leaks
into a later test (the ProgramTest fixture does not reset it). ProgramTest
24/24.
2026-07-11 00:03:08 -04:00
swung0x48 dc3c2cc5c7 [Feat] (MG_Impl, MG_Backend, MG_State): implement glMultiDrawArrays and glGetBufferSubData
Two previously-stubbed GL 3.3 Core entry points.

glMultiDrawArrays: mirrors the existing glMultiDrawElements(BaseVertex)
architecture end to end -- a new MultiDrawArrays backend function-table
slot dispatched from the frontend after program/primitive-mode validation
(plus a drawcount < 0 -> GL_INVALID_VALUE guard).
- DirectGLES: PrepareForDraw once, then loop native glDrawArrays with the
  same per-range client-side array upload the single DrawArrays does.
- DirectVulkan: build a MultiDrawCmd payload and hand it to a new
  VulkanRenderer::MultiDrawArrays, which does one SetupDraw over the union
  of the sub-draw vertex ranges and then a vkCmdDraw per range (mirrors
  VulkanRenderer::MultiDrawElements).

glGetBufferSubData: reads a range of the bound buffer's CPU shadow into
client memory via a new BufferObject::DownloadSubData, with the same
validation shape as BufferSubData (INVALID_VALUE for negative/overflowing
range, INVALID_OPERATION for no bound buffer or a non-persistent mapped
buffer). The shadow reflects CPU writes and backend write-backs but not
arbitrary GPU-side writes, which is documented on the method.

Tests: 2 BufferTest cases for glGetBufferSubData (round-trip read of a
middle range and the whole buffer, plus out-of-range/negative/no-buffer
errors). BufferTest 32/32, SanityTest 30/30, VertexArrayTest 42/42;
library builds clean. (The glMultiDrawArrays draw paths are not
runtime-testable on this host and are compile-verified against the tested
MultiDrawElements pattern.)
2026-07-10 23:46:14 -04:00
swung0x48 4dd2b2216c [Feat] (MG_Impl, MG_State, MG_Backend, MG_Util): packed 2_10_10_10 and GL_BGRA vertex array formats
glVertexAttribPointer now accepts the GL 3.3 Core packed types
GL_INT_/GL_UNSIGNED_INT_2_10_10_10_REV and the GL_BGRA size, clearing the
two long-standing "// TODO: implement GL_BGRA support" markers. Adds the
format end to end across the frontend, VAO state, and both backends.

- DataType: add Int2101010Rev / Uint2101010Rev with GLToMG / MGToGL /
  MGToStr converter cases.
- Validation (ValidateVertexAttribFormat): the full glVertexAttribPointer /
  glVertexAttribIPointer error table -- size is 1..4 or GL_BGRA (else
  INVALID_VALUE, which takes precedence); a packed type requires size 4 or
  GL_BGRA (else INVALID_OPERATION); GL_BGRA requires GL_UNSIGNED_BYTE or a
  packed type AND normalized == GL_TRUE (else INVALID_OPERATION); the
  integer path rejects packed types (INVALID_ENUM) and GL_BGRA size
  (INVALID_VALUE).
- VAO: store GL_BGRA as size 4 plus a new IsBgra flag (reset on the
  binding-format path).
- DirectVulkan: map the packed/BGRA formats to
  VK_FORMAT_A2B10G10R10_* (normal) and VK_FORMAT_A2R10G10B10_* /
  VK_FORMAT_B8G8R8A8_UNORM (BGRA reversed), fold IsBgra into the pipeline
  hash, and size packed/BGRA elements as one 4-byte word via
  GetAttributeByteSize. (Vulkan *_SNORM decodes with the GL 4.2 symmetric
  rule, a documented deviation from the 3.3 signed formula.)
- DirectGLES: round-trip the packed enum through the loader, pass GL_BGRA
  as the driver size argument, and size client uploads with the packed
  4-byte word.

Tests: 4 VertexArrayTest cases covering packed/BGRA storage and the full
float/integer error table; the packed-size hard-fail is mutation-verified.
VertexArrayTest 42/42, SanityTest 30/30, library builds clean.
2026-07-10 23:25:25 -04:00
swung0x48 0cada09aa7 [Feat] (MG_Impl/GLImpl): implement 8 packed glVertexAttribP*ui current-value setters
glVertexAttribP{1,2,3,4}ui and their *uiv forms set the CURRENT generic
vertex attribute value from a packed 2_10_10_10_REV word (they are the
packed members of the immediate VertexAttrib* family, not the array-format
path), so they funnel into SetCurrentVertexAttributeFloat and reuse the
existing index validation.

- Add DecodePacked2101010: unpacks x=[0..9], y=[10..19], z=[20..29] (10-bit)
  and w=[30..31] (2-bit) from one 32-bit word. Signed fields are two's-
  complement (sign-extended per width); normalized conversion uses the
  GL 3.3 (2c+1)/(2^b-1) form (10-bit /1023, 2-bit /3), matching the
  existing NormalizeSigned* helpers -- NOT the GL 4.2 clamp form.
- type accepts only GL_INT_2_10_10_10_REV / GL_UNSIGNED_INT_2_10_10_10_REV
  (GL_INVALID_ENUM otherwise; the 4.4-era 10F_11F_11F_REV is not legal in
  3.3). P1/P2/P3 consume the first 1/2/3 components; the rest take the
  (0,0,0,1) defaults and are cleared each call. The *uiv forms dereference
  a single packed word, not an array.

Tests: 4 VertexArrayTest cases (unsigned decode, signed GL-3.3 formula,
component-count/defaults, type/index/uiv validation). The signed test is
mutation-verified: z==0 -> 1/1023 fails against the GL 4.2 form.
VertexArrayTest 38/38, SanityTest 30/30.
2026-07-10 23:07:13 -04:00
swung0x48 3ff8cafac6 [Feat] (MG_Util/SelfTest): POST rows for polygon-mode and indexed-color-mask capabilities
Surface the device features that glPolygonMode and glColorMaski depend on,
so a missing capability (and the resulting FILL / draw-buffer-0 fallback)
is visible in the driver POST instead of silently degrading.

- DirectVulkan checklist: fillModeNonSolid (GL_LINE/GL_POINT rasterization)
  and independentBlend (per-draw-buffer color masks) rows, read from the
  physical device features already queried by the probe.
- DirectGLES checklist: "Polygon mode" (GL_NV/ANGLE_polygon_mode) and
  "Indexed color mask" (ES 3.2 core or draw_buffers_indexed) rows, read
  from the cached GLESCapabilities flags.

Each row passes when supported and warns (not fails) when absent, since
the fallback still renders correctly. Builds clean; SanityTest sweep green
(30/30).
2026-07-10 22:31:20 -04:00
swung0x48 041de6cba3 [Feat] (MG_Backend/DirectGLES, MG_Util/Loader): wire glPolygonMode and glColorMaski into GLES sync
Neither entry point exists in unextended OpenGL ES core, so both are
gated on optional extensions detected and cached at init, with a runtime
fallback when absent.

Loader:
- Add glPolygonModeNV/glPolygonModeANGLE and glColorMaskiEXT/glColorMaskiOES
  to the GLES function table, loaded via a new INIT_GLES_FUNC_OPTIONAL
  macro that does not log an error when the driver lacks them.
- Cache GLESCapabilities.SupportsPolygonMode and SupportsIndexedColorMask
  from whether the entry points loaded (glColorMaski is GLES 3.2 core with
  no extension string, so pointer presence is the reliable signal).

Sync (SyncRenderState):
- Color mask: uniform masks keep using the non-indexed glColorMask (works
  everywhere); divergent per-draw-buffer masks use glColorMaski (core /
  EXT / OES, whichever loaded) when SupportsIndexedColorMask, else fall
  back to broadcasting draw buffer 0. Mirrors the existing indexed-blend
  block's all-same-vs-per-buffer structure.
- Polygon mode: new sync block calls glPolygonModeNV/ANGLE(GL_FRONT_AND_BACK,
  mode) when SupportsPolygonMode; without the extension the mode stays FILL
  and non-FILL requests are dropped.

Library builds clean; full SanityTest sweep green (30/30).
2026-07-10 22:27:21 -04:00
swung0x48 aa5c33a42d [Feat] (MG_Backend/DirectVulkan): wire glPolygonMode and glColorMaski into pipeline creation
Consume the polygon mode and per-draw-buffer color write masks that the
frontend already tracks, with runtime fallback for the device features
they require.

glPolygonMode:
- Add ConvertPolygonModeToVkEnum (GL_FILL/LINE/POINT -> VkPolygonMode).
- Thread a polygonMode field through PipelineCreatePayload, fold it into
  the pipeline cache hash (distinct modes need distinct pipelines), and
  apply it in PipelineFactory instead of the hardcoded VK_POLYGON_MODE_FILL.
- LINE/POINT require the fillModeNonSolid device feature: detect and
  enable it at device creation, cache m_fillModeNonSolidFeatureEnabled,
  and fall back to FILL at pipeline-build time when it is absent.

glColorMaski:
- The per-attachment color-blend loop now reads GetColorMaskIndexed(i)
  instead of the broadcast GetColorMask(), so each draw buffer gets its
  own write mask (already covered by the pipeline hash).
- Divergent per-attachment masks require independentBlend: cache
  m_independentBlendFeatureEnabled (was enabled but never recorded) and
  fall back to draw buffer 0's mask for every attachment when it is absent.

The internal depth-mipmap utility pipeline keeps VK_POLYGON_MODE_FILL (not
GL-driven). Library builds clean; full SanityTest sweep green (30/30).
2026-07-10 22:16:47 -04:00
swung0x48 f892f609c2 [Fix] (MG_Backend/DirectVulkan+DirectGLES, MG_State): cap per-stage GL_MAX_TEXTURE_IMAGE_UNITS to 32
Adreno/Qualcomm report a huge maxPerStageDescriptorSampledImages, and the
per-stage texture-unit limits were clamped only to the combined array capacity
(TextureState::MAX_TEXTURE_IMAGE_UNITS = 192). glGetIntegerv thus advertised 192
for GL_MAX_TEXTURE_IMAGE_UNITS, but host code treats it as an array bound:
Minecraft's Blaze3D GlStateManager.TEXTURES[] holds 128 entries and Iris iterates
[0, GL_MAX_TEXTURE_IMAGE_UNITS) over it in CompositeRenderer.renderAll, throwing
ArrayIndexOutOfBoundsException: Index 128 out of bounds for length 128.

Introduce MAX_PER_STAGE_TEXTURE_IMAGE_UNITS = 32 (desktop-driver value) and clamp
the per-stage sampler limits to it in both backends (DirectGLES previously did not
clamp at all), keeping the combined limit at the array capacity. Update SanityTest.
2026-07-10 21:53:04 -04:00
swung0x48 5e8106114f [Feat] (MG_Impl/GLImpl, MG_State, MG_Backend): implement glColorMaski
Promote the color writemask to per-draw-buffer state and implement the
indexed glColorMaski entry point (previously a stub), plus its read-back
through glGetBooleani_v.

- RenderState: replace the single BoolVec4 ColorMask with an array of
  MAX_DRAW_BUFFERS masks, all initialized to true. SetColorMask now
  broadcasts to every draw buffer (glColorMask semantics); GetColorMask
  returns draw buffer 0. Add indexed set/get accessors + GLContext
  wrappers.
- glColorMaski sets only the addressed draw buffer; out-of-range index
  raises GL_INVALID_VALUE (buf is a GLuint, so no GL_INVALID_ENUM path),
  mirroring the indexed blend entry points' MAX_DRAW_BUFFERS bound.
- glGetBooleani_v(GL_COLOR_WRITEMASK, i) reports draw buffer i's four
  booleans; the non-indexed glGetBooleanv still reports draw buffer 0.
- Fix GLboolean coercion in the color-mask path: any nonzero value
  enables the component (was == GL_TRUE, which wrongly rejected e.g. 2).
- DirectGLES sync reads ColorMasks[0] (GLES core has only non-indexed
  glColorMask).

Tests: ColorMaskIndexedStoresAndReadsBack covers the per-buffer vs
broadcast semantics, buffer-0 read-back, out-of-range INVALID_VALUE, and
the GLboolean coercion (mutation-verified: == GL_TRUE fails it). Full
SanityTest sweep green (30/30).
2026-07-10 21:30:57 -04:00
swung0x48 95876d9d8c [Feat] (MG_Impl/GLImpl, MG_State): implement glClampColor and glPolygonMode
Fill the two empty // TODO state handlers with GL 3.3 Core-conformant
behavior, backed by new RenderState fields and glGet* read-back.

glClampColor:
- Accept only GL_CLAMP_READ_COLOR (compat GL_CLAMP_VERTEX/FRAGMENT_COLOR
  rejected); clamp is one of GL_TRUE / GL_FALSE / GL_FIXED_ONLY. Note the
  Khronos man page wrongly omits GL_FIXED_ONLY from the accepted set, but
  it is legal AND the default, so it is accepted here.
- Default GL_FIXED_ONLY; both error paths are GL_INVALID_ENUM with no
  state change. glGetIntegerv returns the raw tri-state enum; GetFloatv/
  GetDoublev widen it and GetBooleanv converts nonzero to GL_TRUE via the
  existing fall-through, so one GetIntegerv case serves every getter.

glPolygonMode:
- Core accepts only face == GL_FRONT_AND_BACK (GL_FRONT/GL_BACK were
  removed in 3.1 core); mode is GL_POINT / GL_LINE / GL_FILL. Both errors
  are GL_INVALID_ENUM with no state change.
- Keep separate front/back slots so GL_POLYGON_MODE round-trips its two
  values (identical under a core context). The raster effect (VkPolygonMode
  + fillModeNonSolid) remains a backend follow-up; this is the state layer.

Tests: two RenderStateSanity round-trips; the glClampColor GL_FIXED_ONLY
acceptance assertion is mutation-verified (rejecting it fails the test).
Full SanityTest sweep green (29/29).
2026-07-10 21:21:40 -04:00
swung0x48 e460536119 [Feat] (MG_Impl/GLImpl, MG_State): implement glHint, glPointParameter*, glPixelStoref, glGetDoublev
Six pure-state entry points that were stubs or empty // TODO bodies, all backed by new
context state and read back through glGet*.

* glHint: Hint_State was an empty TODO. Store the 4 GL 3.3 core hint targets (LINE_SMOOTH,
  POLYGON_SMOOTH, TEXTURE_COMPRESSION, FRAGMENT_SHADER_DERIVATIVE), default GL_DONT_CARE.
  Validate target and mode (FASTEST/NICEST/DONT_CARE) -> GL_INVALID_ENUM otherwise. The
  compatibility-only targets (GL_PERSPECTIVE_CORRECTION_HINT, GL_POINT_SMOOTH_HINT, GL_FOG_HINT,
  GL_GENERATE_MIPMAP_HINT) are rejected. The glGetIntegerv hint cases, previously hardcoded to
  GL_DONT_CARE, now read the stored value; glGetBooleanv on a hint is always GL_TRUE.

* glPointParameter{f,i,fv,iv}: the scalar _State bodies were empty TODOs and the *v forms were
  stubs. Only the 2 core pnames are accepted: GL_POINT_FADE_THRESHOLD_SIZE (float, default 1.0,
  GL_INVALID_VALUE if negative) and GL_POINT_SPRITE_COORD_ORIGIN (GL_LOWER_LEFT/GL_UPPER_LEFT,
  default GL_UPPER_LEFT, GL_INVALID_ENUM on a bad value -- note the different error code from the
  fade case). The compat pnames (POINT_SIZE_MIN/MAX, POINT_DISTANCE_ATTENUATION) are rejected. All
  four forms funnel through one (pname, float) handler. glGetIntegerv(GL_POINT_FADE_THRESHOLD_SIZE)
  was hardcoded to 1; it now rounds the stored float, glGetFloatv reads the float directly (keeping
  the fractional part), and GL_POINT_SPRITE_COORD_ORIGIN gained a getter case (it had none).

* glPixelStoref: funnels into the existing glPixelStorei state, but converts per type -- boolean
  pnames (PACK/UNPACK_SWAP_BYTES/LSB_FIRST) by a zero-test so 0.4 -> TRUE, integer pnames by
  round-to-nearest. A blanket round would wrongly turn a fractional true flag into false.

* glGetDoublev: funnels through glGetFloatv and widens, writing exactly the pname's component count
  (1/2/4) so a single-component query cannot overrun the caller's buffer. MobileGL stores no native
  double state (depth range/clear are float), so widening from float matches its real resolution.

State added to RenderStateParameters + RenderState Set/Get + GLContext wrappers, following the
existing LineWidth/DepthRange pattern. Covered by 4 SanityTest cases (set-then-get round trips, the
core-vs-compat enum rejections, the two different error codes, and the glPixelStoref boolean
zero-test, which was verified to fail against a blanket-round implementation).
2026-07-10 20:35:08 -04:00
swung0x48 561d8992bc [Feat] (MG_Impl/GLImpl, MG_State): implement glGetActiveUniformsiv (UBO reflection query)
Completes the uniform-block reflection chain: glGetUniformIndices, glGetActiveUniformName
and glGetActiveUniformBlockiv were already implemented; glGetActiveUniformsiv was the last
stub. Supports all 8 GL 3.3 Core pnames:

* GL_UNIFORM_TYPE / SIZE / NAME_LENGTH / BLOCK_INDEX / OFFSET / ARRAY_STRIDE come straight from
  glslang's TObjectReflection (the same reflection the existing uniform queries use).
* GL_UNIFORM_IS_ROW_MAJOR from the member's TType layout qualifier, guarded by isMatrix() so a
  scalar in a layout(row_major) block does not wrongly report 1.
* GL_UNIFORM_MATRIX_STRIDE is derived: glslang exposes no matrix stride, so it is computed from the
  std140 rule (each column/row vector rounded up to a vec4), which matches the std140 layout
  MobileGL's SPIR-V path emits. Evaluates to 16 for every GL 3.3 float matrix.

The -1-vs-0 distinction is handled explicitly: OFFSET / ARRAY_STRIDE / MATRIX_STRIDE / BLOCK_INDEX
return -1 for a default-block uniform (glslang gives arrayStride 0 there, so it is gated on block
membership), while ARRAY_STRIDE / MATRIX_STRIDE return 0 for a non-array / non-matrix member that IS
in a block. Errors: GL_INVALID_VALUE for uniformCount<0, any index >= active uniform count, or a
never-generated program name; GL_INVALID_OPERATION for a live shader name; GL_INVALID_ENUM for an
unaccepted pname (e.g. the GL 4.2 GL_UNIFORM_ATOMIC_COUNTER_BUFFER_INDEX). All validation runs before
any write, so params is untouched on error. There is no "not linked" error -- an unlinked program has
zero active uniforms, so any index raises GL_INVALID_VALUE.

Also fix GetActiveUniformArraySize, which returned glslang's TObjectReflection.size verbatim: that
field only carries the element count for a non-block array and reports 1 for a block array member,
so GL_UNIFORM_SIZE (and glGetActiveUniform's size out-param, and glGetProgramResourceiv's
GL_ARRAY_SIZE) wrongly reported 1 for an array inside a UBO. Take the count from the TType instead,
which is authoritative for both cases.

Covered by 3 ProgramTest cases (std140 block with scalar/array/mat4 + a default-block sampler, a
row_major variant, and the six error cases) that link real shaders and assert every pname value.
2026-07-10 19:54:33 -04:00
swung0x48 d5e19cb7ba [Feat] (MG_Impl/GLImpl): implement 42 stubbed glVertexAttrib*/glGetVertexAttribdv current-value entry points
These set (or query) the current generic vertex attribute value, GL_CURRENT_VERTEX_ATTRIB.
All funnel into the existing, correct primitives -- VertexAttrib4f / VertexAttribI4i /
VertexAttribI4ui, and GetVertexAttribfv for the double query -- so the new bodies add only a
null-pointer guard; index validation (incl. the deliberate index-0 rejection) is inherited.

Families implemented (of the 49 core glVertexAttrib* setter stubs, all but the 8 packed
glVertexAttribP*ui, which need a real 2_10_10_10 DataType and are left for later):

* d / dv / s / sv and 4bv / 4iv / 4uiv / 4usv: value-preserving conversion to float. These do
  NOT normalize -- only the N forms do.
* 4Nbv / 4Nsv / 4Niv / 4Nusv / 4Nuiv: normalized. Signed normalization uses the GL 3.3 Core
  formula f = (2c + 1) / (2^b - 1), which maps the full signed range onto exactly [-1, 1] (byte
  -128 -> -1.0, 127 -> +1.0) and cannot represent 0 exactly (0 -> 1/(2^b-1)). This is NOT the
  GL 4.2 revision f = max(c/(2^(b-1)-1), -1); using that here would be a conformance bug.
  Unsigned normalization is the version-independent c/(2^b-1). The 32-bit forms compute in double
  because 2*INT_MAX overflows int32 and neither 2^32-1 nor 2^31-1 is representable as float.
* VertexAttribI{1,2,3}{i,iv,ui,uiv} and I4{bv,sv,ubv,usv}: integer forms, writing the integer
  current-value view verbatim (never the float one). Signed sign-extend to VertexAttribI4i,
  unsigned zero-extend to VertexAttribI4ui; w defaults to the integer 1. I4ubv/I4usv route to the
  unsigned setter (distinct from the normalized-float 4Nubv).
* glGetVertexAttribdv mirrors GetVertexAttribfv: reads the float view as four doubles for
  GL_CURRENT_VERTEX_ATTRIB (no bound VAO required), one value for the array pnames, same error rules.

Covered by 5 new round-trip tests whose boundary values (byte -128 -> -1.0 exact, 0 -> 1/255,
INT_MIN/MAX endpoints exact, ushort 65535 non-normalized -> 65535.0, integer w == 1) discriminate
the correct formulas; the signed-normalization test was verified to fail against the GL 4.2 form.
2026-07-10 12:23:23 -04:00
swung0x48 d40f753983 [Fix] (MG_State, MG_Impl, MG_Backend): conformant current generic vertex attribute values
GL 3.3 Core: a shader input whose generic attribute array is disabled reads that
attribute's current value (per-context state, default (0,0,0,1)). Four defects made
that path non-conformant, three of them silently.

* Out-of-bounds current-value reads. m_currentVertexAttributes held 16 entries while
  the DirectVulkan draw path walked shader input locations 0..31 and GL_MAX_VERTEX_ATTRIBS
  was advertised straight from the device (commonly 32). The only guard was MOBILEGL_ASSERT,
  which expands to nothing outside debug builds. Grow the storage capacity to 32, advertise
  min(device limit, capacity), validate against that dynamic limit, and give the accessors
  real runtime bounds checks. Replace the literal 32 loops with the constant, and pin
  MAX_VERTEX_ATTRIBS to the Uint32 mask width and to vertexInputTypes' bound with
  static_asserts so the two can no longer drift apart -- that drift was the bug.

* DirectGLES never fed current values to the driver. Values were stored in MG_State only,
  so a disabled attribute always rendered as the ES driver's own untouched (0,0,0,1) while
  DirectVulkan rendered it correctly: identical GL code, different pixels per backend.
  Add SyncCurrentVertexAttributeValues() to the draw prologue, and hoist the
  glType -> (base type, component count) dispatch into MG_State::GLState so both backends
  resolve the semantics from one place instead of it living inside VulkanRenderer.

* Enabled arrays the backend could not map were silently demoted to the current value.
  ToVkVertexFormat had no DataType::Float16 case, so a GL_HALF_FLOAT array fell to
  VK_FORMAT_UNDEFINED, dropped out of the vertex input state, and became indistinguishable
  from a disabled array: the geometry rendered a constant colour with GL_NO_ERROR. Add the
  Float16 mapping, track an unsupportedAttribMask, and hard-fail the draw before pipeline
  creation so no synthetic attribute is baked into a cached VkPipeline.

* glGetVertexAttrib{fv,iv,Iiv,Iuiv}(GL_CURRENT_VERTEX_ATTRIB) returned before any index
  validation, reading past the array instead of raising GL_INVALID_VALUE.

Also resolve ProgramObject::DoReflection's "TODO: get from backend" 16-location clamp,
which capped the new DirectGLES sync at locations 0..15; report GL_MAX_VERTEX_ATTRIBS
through the same helper the validators use, so the clamp cannot be bypassed; and bound
vertex binding indices by the same dynamic limit, since the default attribute -> binding
mapping is the identity.

Add a "Vertex attributes" driver POST row to both backends: FAIL below the GL 3.3 Core
minimum of 16, WARN above MobileGL's storage capacity (clamped, extra attributes unusable),
PASS in between -- making the driver/host mismatch that caused the out-of-bounds read
visible instead of silently swallowed.

Covered by 7 new regression tests (each verified to fail against the previous behaviour).
2026-07-10 11:23:16 -04:00
swung0x48 eb090c6170 [Fix] (MG_Backend/DirectVulkan): fence-backed GL sync objects and per-frame descriptor rewind
- Track every graphics-queue submission with a real fence: pooled fences
  for mid-frame flushes, the frame slot's fence for Present and readback.
  Completion advances a submit counter via vkGetFenceStatus polls,
  slot-fence waits, and device-idle points, and raises the buffer-manager
  serial floor from the frame serial each submission carried.
- GL sync objects now capture the submission index that will carry the
  commands recorded so far; ClientWaitSync honors
  GL_SYNC_FLUSH_COMMANDS_BIT with a mid-frame submit (gated on the index
  still being unsubmitted so poll loops cannot split the render pass), and
  blocking waits flush then vkWaitForFences with the caller timeout.
- FlushPendingCommands retires the submitted command buffer and restarts
  recording on a fresh one; retired buffers are freed once the slot fence
  is next waited, so an executing buffer is never reset.
- Rewind descriptor-set cursors exactly once per frame in Present (after
  the slot-fence wait), plus after the synchronous readback drain,
  replacing the ten lazy per-draw-path rewinds.

Verified: host tests 168/168, trace-replay 70/70.
2026-07-10 10:55:10 +00:00
swung0x48andClaude Fable 5 7b00255b11 [Feat] (MG_Util/SelfTest): grouped POST rows, merged probes, MobileGL-reported strings
Rows in each backend section now sort FAIL -> WARN -> PASS -> INFO
(stable within groups), with identity strings always last: the device
strings renamed to 'Backend driver reported GL_*' and a new bottom
group 'MobileGL reported GL_VENDOR/GL_VERSION/GL_RENDERER/GL_EXTENSIONS'
showing exactly what MobileGL advertises to applications on that
backend, assembled from the same sources as GL_Getter and the backend
objects (extension-list construction extracted into shared helpers so
POST cannot drift from the real advertisement).

Rows probing the same subject are merged into single verdicts whose
details keep every sub-fact and causal chain: the six EGL setup steps
become one 'ES3 context' row, extension presence + functional probe
become one 'Timer queries' row per backend (including the
MOBILEGL_DISABLE_TIMERQUERY override explanation), and the Vulkan
loader/instance, surface-extension pair, and physical-device/queue/API
chains each collapse into one row.

Capability rows previously dumped as INFO now carry verdicts: index
type uint8 (WARN when absent - uint8 index buffers have no conversion
fallback), VK_KHR_draw_indirect_count (WARN when absent - count draws
degrade to CPU readback loops); buffer_storage/base_instance stay
honest INFO when absent since no MobileGL path degrades.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-10 03:28:50 +00:00
swung0x48andClaude Fable 5 f0dd5d667b [Feat] (MG_Util/SelfTest): timer-query rows and functional probes in POST
GLES section reports GL_EXT_disjoint_timer_query and, when present,
runs a real TIME_ELAPSED span (paced availability polling matching the
runtime path) and reports the observed nanoseconds. Vulkan section
reports timestampValidBits/timestampPeriod and runs a full functional
probe - logical device, command buffer, two vkCmdWriteTimestamp into a
fresh query pool, submit, fenced wait, read-back - with hung-GPU-safe
teardown (a timed-out fence skips vkDeviceWaitIdle and leaks
deliberately rather than hanging the POST). Both sections note when
MOBILEGL_DISABLE_TIMERQUERY suppresses the feature.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-10 01:08:59 +00:00
swung0x48andClaude Fable 5 7eb3994b02 [Feat] (MG_Impl, MG_Backend): GL_ARB_timer_query on both backends
Implements GL timer queries end to end: a frontend query registry
(modeled on the sync module - mutex-guarded objects wrapping opaque
backend handles behind optional function pointers) serving
glGenQueries/glBeginQuery/glEndQuery(GL_TIME_ELAPSED)/glQueryCounter
(GL_TIMESTAMP)/glGetQueryObject*/glGetQueryiv with GL 3.3 error
semantics and a graceful zero-result fallback when a backend cannot
time.

DirectGLES backs spans with GL_EXT_disjoint_timer_query (context-
generation-stamped handles, bounded result waits). DirectVulkan gets a
VkTimerQueryManager: per-frame-in-flight timestamp query pools reset at
command-buffer begin (outside render passes), records harvested by
frame serial before their pool recycles, elapsed = masked tick delta x
timestampPeriod; handles are stamped with a renderer generation that
also now guards fence syncs across renderer recreation. GL_QUERY_
COUNTER_BITS reports 0 unless the live backend can actually time
(dynamic IsTimerQuerySupported hook), and a failed blocking read keeps
the handle alive so the real value stays reachable once the frame
submits.

GL_ARB_timer_query is advertised only when the device supports timing
and MOBILEGL_DISABLE_TIMERQUERY is unset - LWJGL keys Minecraft's F3
'GPU: x%' line off exactly that extension string; verified on device
(Adreno 830) on both backends.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-10 01:08:38 +00:00
swung0x48andClaude Fable 5 7d31a6fcd7 [Refactor] (MG_Config): centralize env-var and driver-feature reads
MG_Config::FeaturesTable snapshots every MOBILEGL_* toggle once in
ConfigLoader::Init with a single truthy rule (non-empty, not '0', not
'false' case-insensitively), replacing 13 scattered std::getenv sites
that used four different parsing conventions. Renderer-derived bits
(IsAngleRenderer/IsAngleLlvmpipeRenderer/AvoidSamplerMipmapMinFilter)
move into GLESCapabilities, set once in FillInGLESCapabilities, so hot
paths (glMemoryBarrier ANGLE flush, sampler min-filter sync) stop doing
per-call string scans. MOBILEGL_PRESENT_DUMP_CALL/_CURRENT_CALL stay
live getenv (the retrace harness mutates them at runtime) and
MOBILEGL_LOG_FILE_PATH stays in Log.cpp (log init precedes config
init); both are documented in Config.h. Known semantic unification:
MOBILEGL_DISABLE_SUBGROUP previously required exactly 'true' and
MOBILEGL_PRESENT_STATS exactly '1'; both now follow the shared rule
(CI's 0/1 values parse identically). Also bumps CoreVersion to 26.07.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-10 01:08:06 +00:00
swung0x48andClaude Fable 5 096d6f591b [Chore] (android-plugin): make versionCode monotonic within a month
major*100 + minor collides for multiple releases in the same month, and
Android refuses to install a package whose versionCode is not strictly
greater than the installed one. Encode as year*1_000_000 + month*10_000 +
monthly-revision (commits since the month start), so every build upgrades
cleanly; the month weight dwarfs the per-month reset on rollover.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-09 22:26:29 +00:00
swung0x48andClaude Fable 5 19348631ab [Chore] (android-plugin): calendar versioning 26.07 with commit-hash build id
versionCode = major * 100 + minor (2607); versionName = 26.07.<short git
hash> (e.g. 26.07.4e558ee, -trace suffixed for trace flavors), replacing
the placeholder versionCode 1 / versionName 'dev'.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-09 22:21:48 +00:00
swung0x48andClaude Fable 5 4e558ee142 [Docs] (trace-replay): refresh fixture-authoring skill from the Create fixture work
Registration now documents the trace_cases.json registry (the CMakeLists /
apk.yml instructions were stale). Adds the field-tested guidance from
authoring the Create fixtures: in-tree apitrace fork requirements (frametrim
DSA/multi-bind, persistent-map shadowing) and the Windows wgltrace wrapper,
frozen-world + unfocused-window capture discipline, late-frame selection,
trim verification, brotli repack (with the stale-archive trap), golden
content verification, Android signing/stale-package/emulator-flake and
stale-result pitfalls.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-09 14:26:52 +00:00
swung0x48andClaude Fable 5 effdaabab3 [Feat] (android-plugin): table-style POST report with tap-to-expand details
Checks render as a two-column table (name | colored status chip) with
alternating row stripes; per-check detail text is hidden until the row
is tapped, and the raw JSON report collapses behind a bottom toggle.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-09 13:55:14 +00:00
swung0x48andClaude Fable 5 a394fe1af3 [Test] (MG_Test): cover the indirect gl_InstanceID probe and shader rewrite
BackendLoaderTest drives ProbeIndirectInstanceIdIncludesBaseInstance
(now externally linked) against a fake GLES function table: conforming
and ANGLE-style leaking drivers, the no-vertex-SSBO skip, draw-error
inconclusiveness, object cleanup, and the FillInGLESCapabilities wiring
end-to-end. SanityTest gains PromoteDrawParameterGlobalsToUniforms
cases pinning the mg_ZeroBasedInstanceID rewrite and the
last-SSBO-binding computation against a non-default binding count,
with RAII capability restoration.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-09 13:44:25 +00:00
swung0x48andClaude Fable 5 d16b7ccd6a [Feat] (MG_Util/SelfTest, android-plugin): driver POST self-test screen
Opening a MobileGL plugin APK now shows a POST screen that probes the
device's GLES and Vulkan drivers independently against MobileGL's
expectations - a device may satisfy only one backend - and reports a
per-backend verdict (OK / DEGRADED / UNSUPPORTED) with per-check rows.

The GLES probe builds its own ES3 pbuffer context on the system driver
and reuses FillInGLESCapabilities, including the indirect-draw
gl_InstanceID semantics probe; the Vulkan probe checks instance/device
requirements and the optional features each DirectVulkan path degrades
without. Results serialize as ASCII-safe JSON through a JNI entry in
libMobileGL.so; PostActivity renders them and caches the run per
process (single-flight, rotation-safe). PluginActivity keeps its
NoDisplay stub but the launcher entry moves to the POST screen; FCL
plugin discovery reads application meta-data and is unaffected.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-09 13:44:14 +00:00
swung0x48andClaude Fable 5 28facc1c3f [Feat] (trace-replay): add Create flywheel indirect and instancing fixtures
Two 1.21.1 NeoForge Create in-world captures facing water wheels and a
large cogwheel, one per flywheel backend (/flywheel backend indirect and
instanced). The indirect trace exercises the compute scatter/cull
pipeline, glMultiDrawElementsIndirect with GPU-written commands, and
draw-parameter emulation; captured with persistent-map shadowing so the
unflushed scatter descriptors Flywheel writes are recorded. Both trimmed
to a single frame and brotli-repacked (~7 MiB each).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-09 12:14:17 +00:00
swung0x48andClaude Fable 5 85b68a9969 [Fix] (MG_Backend/DirectGLES): rebase gl_InstanceID for native indirect draws on ANGLE
ES keeps gl_InstanceID zero-based and ignores the indirect command's
'reserved, must be zero' word, but ANGLE-on-Vulkan forwards the command
verbatim to vkCmdDraw*Indirect and compiles gl_InstanceID to SPIR-V
InstanceIndex, which includes firstInstance. Shaders computing
gl_BaseInstance + gl_InstanceID (Flywheel indirect) then add the base
twice, scrambling instance-to-mesh association.

Probe the actual driver semantics at capability-fill time with a tiny
indirect draw (an ES indirect draw needs a non-default VAO) and, on
leaking drivers, rewrite vertex shaders that use the native indirect
SSBO machinery so gl_InstanceID subtracts the command's baseInstance
word during native indirect draws.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-09 12:14:02 +00:00
swung0x48andClaude Fable 5 a6a5edf573 [Perf] (MG_Backend/DirectGLES, MG_Impl): cache link-time lookups, bound unit scans, honor eglSwapInterval
- BackendProgramObjectImpl::CacheResourceLocations resolves every
  glGetUniformBlockIndex / glGetUniformLocation string query once per
  link and establishes the block binding points there. Per draw,
  BindCurrentProgramWithResources now uses the cached indices, re-issues
  glUniform1i only when a sampler's unit actually changed (program state
  persists), uploads the global UBO only when its content version moved,
  and skips redundant glUseProgram binds (guard reset on program-name
  reuse, MakeCurrent, and every explicit glUseProgram(0)). The caches are
  invalidated through ProgramObject's link version, which also makes a
  relinked program finally re-sync its backend program.
- Track a texture-unit high-water mark (fed by glBindTexture /
  glBindTextureUnit / glBindSampler / glBindImageTexture) so the two
  per-draw unit scans (MAX_TEXTURE_IMAGE_UNITS is 192) and the
  texture-deletion unbind loop only walk units that were ever touched.
- Forward the app's eglSwapInterval to the native EGL surface through a
  new BackendObject::SetEGLSwapInterval hook (applied immediately when
  the surface exists, otherwise deferred to surface creation /
  MakeCurrent). "VSync off" finally reaches the hardware - DirectGLES
  was hard-locked to the display refresh before.

The driver-side cost of the per-draw string lookups was about half of a
30% Adreno driver hotspot; libMobileGL's share of the vanilla render
thread fell from 22% to 9% (simpleperf, Adreno 830).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-09 12:12:51 +00:00
swung0x48andClaude Fable 5 bd208783d7 [Perf] (MG_Backend/DirectVulkan, MG_State): stop re-deriving per-draw state
- Memoize the program content hash on ProgramObject (keyed by the backend
  state version + compile flags; relinking and binding changes invalidate
  it) and the vertex-input hash on VertexArrayObject (keyed by a new
  aggregate config version bumped by every attribute mutation). Full-SPIRV
  XXH64 hashing fell from 13.7% to 1.4% of the render thread.
- ProgramObject also gains a link version and a global-UBO content version
  (bumped by uniform writes and on relink, wrap-safe around the backends'
  "never uploaded" sentinel) for backends to gate uploads and link caches.
- Reuse member scratch vectors in SetupDraw, UploadAndBindVertexBuffers,
  GetOrCreatePipeline and BindProgramUniformBuffers instead of allocating
  per draw (~12% of render-thread time was in the allocator).
- Replace hot-path dynamic_cast with AsMipmapTexture (storage-type tag +
  static_cast); TextureObjectMipmap is the only Mipmap-tagged branch.
- Register/prune texture aliases only when a new (texture, lifetimeId)
  identity appears instead of scanning the entire alive map on every
  sampled-texture sync.
- Make the fallback VkPresentModeKHR log strings report the actual mode.

Vanilla render-thread share of libMobileGL dropped from 48% to 35% on
DirectVulkan (simpleperf, Adreno 830).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-09 12:12:50 +00:00
swung0x48andClaude Fable 5 08e808ef20 [Perf] (MG_State/FastSTL): make object deletion cheap again
- GLContext::MarkBufferObjectForDeletion now detaches the deleted buffer
  only from the currently bound VAO (GL 4.6 5.1.2 semantics; other VAOs
  keep their shared_ptr attachments alive). The old every-VAO scan was
  O(VAOs) per delete - with one VAO per chunk section, vanilla chunk
  churn made it dominate the render thread and FPS decay over minutes.
- Bump FastSTL: erase(key) destroys in place instead of building the
  discarded successor iterator (a linear bucket-array scan), and switch
  the buffer/framebuffer/renderbuffer deletion paths to the key overload.

Together these removed the 34% render-thread deletion overhead measured
in aged vanilla sessions (simpleperf, Adreno 830 / DirectVulkan).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-09 12:12:50 +00:00
swung0x48andClaude Fable 5 bb3a18c627 [Fix] (MG_Backend/DirectGLES): rebind image uniforms to frontend image units
139de763 started preserving layout(binding) on SSBO/image declarations in
transpiled ESSL (ES cannot rebind either through the API). That is correct
for SSBOs and for images whose GL source carries an explicit binding
(Flywheel), but wrong for image uniforms without one: glslang auto-assigns
a binding during transpile, while the app addresses the unit through
desktop-GL semantics - the link-time default (0) or glUniform1i, which ES
forbids on image uniforms. Iris/Photon picks image units with glUniform1i,
so its compute passes (auto exposure / colored light) read and wrote the
transpiler-invented units instead: the photon-v1.3b retrace came out dark
and orange-tinted (ssim 0.65 vs golden).

Rewrite every image uniform declaration's binding qualifier to the
frontend-tracked unit (layout binding reflected at link, overridden by any
later glUniform1i) when transpiling for the backend. Flywheel's explicit
bindings rewrite to the same value; Iris packs get the unit the app
actually bound with glBindImageTexture.

Verified on llvmpipe DirectGLES: photon-v1.3b retrace 0.652 -> 0.9988,
photon-v1.1 control stays at 0.9991, all 147 unit tests pass.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-09 09:06:01 +00:00
swung0x48andClaude Fable 5 74ae1e4a29 [Fix] (MG_Test): expect resolved effective offset in DSA VAO test
Since the ARB_vertex_attrib_binding state model (9fbb708e), the flat
VertexAttribute view backends consume holds the resolved effective
offset (binding offset + relative offset), so
glVertexArrayVertexBuffer(offset=16) + glVertexArrayAttribFormat(
relativeoffset=12) yields Offset == 28. The old expectation of 12
encoded the pre-refactor bug where the binding offset was clobbered
by the last call.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-09 07:41:32 +00:00
swung0x48andClaude Fable 5 139de76347 [Fix] (MG_State/MG_Impl/MG_Backend): render Flywheel instanced+indirect on both backends
Create 6 / Flywheel 1.0.6 now renders correctly with both flywheel:instancing
and flywheel:indirect on DirectGLES and DirectVulkan (verified in-game on
Adreno 830: waterwheels and cogwheels solid, animated, correct pairing, no
crashes across all four combinations).

- MG_State/MG_Impl: sync explicitly-ranged SSBO bindings of FLUSH_EXPLICIT
  persistent maps to the backend before compute dispatches. Flywheel writes
  its scatter-copy descriptors into the staging ring's persistent map and
  never flushes that span (UB per spec, works on drivers whose maps alias
  GPU-visible memory); our maps alias the CPU shadow, so the descriptors
  never reached the GPU: the scatter compute copied nothing (GLES: empty
  draw commands) or stale garbage (Vulkan: wild indirect commands ending in
  VK_ERROR_DEVICE_LOST).
- MG_Impl/MG_Backend: real glFenceSync objects backed by backend fences
  (GLES: native ES syncs guarded by context generation and owner thread;
  Vulkan: buffer-manager frame serials), replacing always-signaled stubs
  that let Flywheel reclaim staging memory the GPU still reads.
- MG_Backend/DirectGLES: compute dispatches now run the same per-program
  resource sync as draws (uniform-block bindings and sampler units must be
  re-established through the API because layout(binding) is stripped from
  transpiled ESSL) and rebind texture units afterwards; the cull shader
  used to read a stale _FlwFrameUniforms binding and the depth-pyramid
  downsample sampled a stale unit-0 texture, zeroing the Hi-Z pyramid and
  occlusion-culling all Flywheel geometry. Image uniforms are excluded from
  glUniform1i (ES bakes their unit via layout(binding)); image-unit sync is
  clamped to the device limit; eliminated/SSBO-classified uniform blocks
  are skipped.
- MG_Backend/DirectGLES: gl_BaseInstance in native indirect draws reads the
  GPU-written command buffer through an injected mg_IndirectParams SSBO
  view addressed per draw instead of the zero CPU shadow; layout(binding)
  is preserved for SSBO/image declarations (ES has no API rebinding for
  them); the ES context ownership claim moved to a global atomic owner
  thread with an EGL ground-truth check, and deferred buffer op state is
  mutex-guarded, so ops cannot silently no-op after context migration.
- MG_Backend/DirectVulkan: new RebaseInstanceIndexPass rewrites vertex
  InstanceIndex loads to (InstanceIndex - BaseInstance). glslang's relaxed
  Vulkan mode aliases gl_InstanceID to InstanceIndex, which includes
  firstInstance, but GL's gl_InstanceID is zero-based - draws with nonzero
  baseInstance paired meshes with wrong instance data (cogwheel drawn as a
  waterwheel, another wheel collapsed invisible). Gated on the
  shaderDrawParameters device feature. Sampled-read barriers additionally
  cover the compute stage (the Hi-Z downsample samples the depth
  attachment from compute), and short uniform-buffer ranges keep the
  existing zero-padding.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-09 06:30:10 +00:00
swung0x48andClaude Fable 5 2395a6ded2 [Fix] (MG_Backend/DirectGLES): always use native indirect draws with a bound buffer
Adreno (830) exposes no GL_EXT_base_instance, and gating the native path
on it sent Flywheel's whole MDI call to the CPU loop, which reads the
stale shadow instanceCount (0) and draws nothing. A non-zero reserved
word is benign on mobile drivers, instanced arrays were never
baseInstance-offset in the emulation anyway, and the CPU loop can never
see GPU-written commands - native is strictly better.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-08 13:47:45 +00:00
swung0x48andClaude Fable 5 41b15955b0 [Fix] (MG_Impl): export real glNamedFramebufferTextureLayer
The GLImpl implementation existed but the exported symbol was still a
stub; Flywheel's indirect OIT framebuffer attaches array-texture layers
through it.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-08 13:35:34 +00:00
swung0x48andClaude Fable 5 07055bb531 [Fix] (MG_Backend/DirectGLES): bind GL_DRAW_INDIRECT_BUFFER for native indirect draws
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-08 13:34:31 +00:00
swung0x48andClaude Fable 5 638999213e [Feat] (MG_Backend/DirectVulkan): native GPU indirect draws + draw parameters
- Enable multiDrawIndirect and shaderDrawParameters device features when
  supported (the latter via VkPhysicalDeviceShaderDrawParametersFeatures on
  Vulkan 1.1+), so DrawIndex/BaseInstance SPIR-V builtins are valid and
  vkCmdDrawIndexedIndirect(Count) may draw more than one command.
- Plain glMultiDrawElementsIndirect no longer requires a GL_PARAMETER_BUFFER
  (it previously drew nothing for the standard Flywheel call); it now issues
  a native vkCmdDrawIndexedIndirect, with a per-command loop fallback when
  the multiDrawIndirect feature is unavailable.
- glDrawElementsIndirect / glDrawArraysIndirect / glMultiDrawArraysIndirect
  read the live GPU buffer via native indirect draws instead of the CPU
  shadow (which cannot see compute-written commands); the CPU path remains
  only for client-memory commands.
- Advertise the same five extensions as DirectGLES for Flywheel's
  capability probe.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-08 13:33:05 +00:00
swung0x48andClaude Fable 5 5ea49f3c50 [Feat] (MG_Backend/DirectGLES): support Flywheel indirect rendering
- Advertise ARB_gpu_shader5 / ARB_multi_bind / ARB_shading_language_420pack /
  ARB_vertex_attrib_binding / ARB_shader_image_size so LWJGL reports
  SUPPORTS_INDIRECT.
- New LowerDrawParametersPass demotes DrawIndex/BaseInstance/BaseVertex
  builtins to Private globals (mg_DrawID/mg_BaseInstance/mg_BaseVertex) for
  the ESSL transpile; SPIRV-Cross otherwise throws for ES profiles. The
  program manager promotes the emitted globals to uniforms and feeds them
  per (sub-)draw.
- Indirect draws now execute natively on the GPU (glDrawElementsIndirect /
  glDrawArraysIndirect per command) when an indirect buffer is bound, so
  compute-written command fields (Flywheel culling updates instanceCount)
  are honored; detects GL_EXT_base_instance and falls back to the CPU loop
  when the command's baseInstance cannot be consumed natively.
- Sync SSBO binding points for graphics draws, not just compute (Flywheel
  vertex shaders read instance data from SSBOs).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-08 13:33:05 +00:00
swung0x48andClaude Fable 5 9fbb708e64 [Feat] (MG_State/MG_Impl): ARB_vertex_attrib_binding + ARB_multi_bind state model
Add a separate binding-point model to VertexArrayObject with eager
resolution into the flat per-attribute view backends already consume.
Implements glBindVertexBuffer(s), glVertexAttrib(I)Format,
glVertexAttribBinding, glVertexBindingDivisor and the DSA variants
(glVertexArrayAttribBinding, glVertexArrayBindingDivisor,
glVertexArrayVertexBuffers), fixing glVertexArrayVertexBuffer which
previously conflated binding index with attribute index. Multi-bind
(glBindBuffersBase/Range) loops over the single-bind entry points.

Needed by Flywheel's indirect backend (GlVertexArrayDSA setup path).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-08 13:32:40 +00:00
swung0x48andClaude Fable 5 f355080b6f [Fix] (MG_Backend/DirectGLES): survive ES context recreation in buffer ops
Track context generation + synced change serial per resource; re-register
ops on MakeCurrent. Fixes frozen buffer contents after the trace replayer's
probe context teardown.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-08 15:02:38 +08:00
swung0x48andClaude Fable 5 b8ffd25148 [WIP] Mesa-style buffer overhaul: resource abstraction + immediate transfer ops
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-08 14:47:51 +08:00
swung0x48 2ed96e9678 [Fix] (MG_Backend/DirectVulkan): pad short uniform buffer ranges 2026-07-08 10:50:14 +08:00
swung0x48 fbbf3c4beb [Chore] (trace-replay): document bliss ANGLE workaround 2026-07-08 07:14:45 +08:00
swung0x48 b88066b73b [Fix] (trace-replay): accept Android SDK licenses explicitly 2026-07-08 01:56:45 +08:00
swung0x48 83d475eb02 [Fix] (trace-replay): stabilize ANGLE retrace cases 2026-07-08 01:07:20 +08:00
swung0x48 292576d2a1 [Fix] (MG_Backend/DirectGLES): avoid ANGLE llvmpipe mipmap hangs 2026-07-07 21:19:50 +08:00
swung0x48 0c8af978db [Chore] (MG_Backend): lower format capability logs 2026-07-07 09:58:30 +08:00
swung0x48 23671f1a99 [Chore] (trace-replay): cache Android retrace AVD 2026-07-07 06:30:15 +08:00
swung0x48 94e882762e [Chore] (trace-replay): reduce retrace CI swap 2026-07-07 06:28:15 +08:00
swung0x48 672538f4f1 [Chore] (trace-replay): add swap to retrace CI 2026-07-07 05:21:50 +08:00
swung0x48 a9763639ed [Chore] (trace-replay): add Derivative Android ANGLE golden 2026-07-06 21:12:41 +08:00
swung0x48 616e694bdd [Fix] (MG_Backend/DirectGLES): flush ANGLE memory barriers 2026-07-06 12:39:51 +08:00
swung0x48 0bee379b61 [Fix] (MG_Util/ShaderTranspiler): keep decomposed workgroup types before globals 2026-07-06 03:58:26 +08:00
swung0x48 d35e452368 [Fix] (MG_Util/ShaderTranspiler): rewrite workgroup vec3 composite loads 2026-07-06 01:25:44 +08:00
swung0x48 86f322e252 [Fix] (MG_Util/ShaderTranspiler): keep workgroup vec3 pass no-op clean 2026-07-06 00:25:49 +08:00
swung0x48 b40def47eb [Refactor] (MG_Util/ShaderTranspiler): replace Photon shared vec3 regex hack with SPIR-V pass
Replace the application-specific PackPhotonSharedVec3Memory GLSL regex
patch with a general DecomposeWorkgroupVec3Pass SPIR-V optimization pass.

The new pass decomposes vec3/ivec3/uvec3/bvec3 Workgroup (shared) memory
variables into scalar arrays (e.g. shared vec3 arr[N][M] -> shared float
arr[N][M][3]), rewriting whole-vector loads/stores into per-component
scalar loads/stores. Component-level accesses (e.g. arr[i].x) are
unchanged since a trailing component index into a float[3] yields the
same scalar pointer as it did for a vec3.

Unlike the regex hack, the pass is application-agnostic: it does not
match on variable names, array dimensions, or shader pack identity, and
runs at the SPIR-V level before SPIRV-Cross decompilation.

Registered in SanitizeAndOptimizeBinary after AggressiveDCE so dead
workgroup accesses are already eliminated. Asserts on unsupported
OpAtomic*/OpCopyMemory targeting vec3 workgroup pointers.

Adds ProgramUtilTest.DecomposeWorkgroupVec3InSpirvPass covering array
declaration, +=, whole load/store, component access, and row-copy loop.
2026-07-05 23:48:27 +08:00
swung0x48 93cf3559e1 [Fix] (MG_Backend/DirectGLES): fix Photon image replay 2026-07-05 18:41:32 +08:00
swung0x48 8f947253ad [Chore] (trace-replay): add Minecraft 1.17 menu fixture 2026-07-05 15:18:54 +08:00
swung0x48 8cce59302b [Fix] (MG_Util/ShaderTranspiler): keep GL shaders off Vulkan macro path 2026-07-05 09:15:47 +08:00
swung0x48 74ad6d76eb [Feat] (trace-replay): add macOS window retrace harness 2026-07-04 23:35:27 +08:00
swung0x48 95f2f5bab9 [Fix] (MG_Impl/Getter): don't ask system GL for context flags 2026-07-04 21:14:04 +08:00
swung0x48 e5ef9b2ace [Fix] (trace-replay): avoid Android startup race 2026-07-04 08:55:43 +08:00
swung0x48 0a138276f8 [Fix] (trace-replay): align Android retrace harness 2026-07-04 08:21:46 +08:00
swung0x48 1549598e52 [Fix] (trace-replay): request compatibility EGL profile 2026-07-04 08:20:39 +08:00
swung0x48 1902518cd6 [Fix] (trace-replay): enable Vulkan fallback in APK CI 2026-07-04 07:51:49 +08:00
swung0x48 bcb8a9b57b [Chore] (trace-replay): skip 26.2 cases in CI 2026-07-03 20:42:46 +08:00
swung0x48 bdb276cd68 Revert "[Fix] (MG_Backend/DirectVulkan): separate EGL surface lifecycle"
This reverts commit 45f1a13cc3.
2026-07-03 15:16:46 +08:00
swung0x48 79aa381722 [Fix] (MG_Backend/DirectVulkan, trace-replay): gate R11G11B10F fallback 2026-07-03 13:00:01 +08:00
swung0x48 45f1a13cc3 [Fix] (MG_Backend/DirectVulkan): separate EGL surface lifecycle 2026-07-03 12:20:40 +08:00
swung0x48 afdbf0a194 [Fix] (MG_Backend/DirectVulkan): support layered texture framebuffers 2026-07-03 12:05:20 +08:00
swung0x48 940ab5fd8e [Fix] (MG_State/GLState, MG_Backend): track layered framebuffer textures 2026-07-03 10:38:51 +08:00
swung0x48 6418561d3c [Fix] (MG_State/EGLState, MG_Backend): defer current EGL surface destruction 2026-07-03 10:14:26 +08:00
swung0x48 ce2b5a793f [Fix] (MG_Backend): support GLES depth-stencil readback 2026-07-03 10:02:49 +08:00
swung0x48 6ecefaec75 [Fix] (MG_Backend): track EGL backend surfaces 2026-07-03 09:15:26 +08:00
swung0x48 bdf29fc4d5 [Fix] (MG_Impl/GLImpl): validate DSA texture parameters 2026-07-03 09:05:52 +08:00
swung0x48 51d9fa91ed [Fix] (MG_Impl/GLImpl, MG_Backend): fix piglit texture and buffer cases 2026-07-03 08:51:22 +08:00
swung0x48 5cdc6c902e [Fix] (MG_Impl/EGLImpl, MG_Backend): track EGL surface lifecycle 2026-07-03 07:45:40 +08:00
swung0x48 03696f8a1a [Fix] (MG_Impl/GLImpl, MG_State, MG_Backend): validate image uniform state 2026-07-03 02:03:23 +08:00
swung0x48 7c26ff1b81 [Fix] (MG_Impl/GLImpl): report fragment image uniform limits 2026-07-03 01:32:59 +08:00
swung0x48 d472d8c32e [Fix] (MG_State/EGLState, MG_Impl/GLImpl): report OpenGL context flags 2026-07-03 01:10:37 +08:00
swung0x48 75e5fe1dd3 [Fix] (MG_State/GLState): allow combined texture unit bindings 2026-07-03 00:19:03 +08:00
swung0x48 fb1da4bbd0 [Fix] (MG_Impl/GLImpl, MG_Backend): avoid image uniform piglit traps [skip ci] 2026-07-03 00:02:11 +08:00
swung0x48 ac43c0224c [Fix] (MG_Impl/GLImpl, MG_State/GLState): fix Vulkan depth-only fragment outputs 2026-07-02 23:46:14 +08:00
swung0x48 011b2ad6f8 Revert "[Fix] (MG_Impl/GLImpl): reject default VAO draws [skip ci]"
This reverts commit 632a4f0859.
2026-07-02 22:50:48 +08:00
swung0x48 e83e6ed76e [Fix] (MG_State/GLState, MG_Impl/GLImpl): track immutable texture storage [skip ci] 2026-07-02 22:49:54 +08:00
swung0x48 edec6e4e62 [Fix] (MG_State/GLState, MG_Util/ShaderTranspiler): validate compute local size [skip ci] 2026-07-02 22:18:56 +08:00
swung0x48 cd96db7829 [Chore] (trace-replay): gate retrace jobs on prerequisites 2026-07-02 21:26:38 +08:00
swung0x48 ca38d8fe86 [Chore] (trace-replay): fetch fixture from mirror 2026-07-02 21:12:56 +08:00
swung0x48 f10f7df389 [Chore] (trace-replay): use manifest file to organize retrace fixtures 2026-07-02 20:51:14 +08:00
swung0x48 1cd75f7f54 [Fix] (MG_Impl/GLImpl): validate named renderbuffer storage [skip ci] 2026-07-02 20:03:16 +08:00
swung0x48 1c84422f8e [Fix] (MG_Impl/GLImpl, MG_Backend/DirectVulkan): allow color renderbuffer framebuffers [skip ci] 2026-07-02 19:59:48 +08:00
swung0x48 ba330cd70a [Fix] (MG_Impl/GLImpl): validate read framebuffer buffers [skip ci] 2026-07-02 19:33:10 +08:00
swung0x48 4439162fea [Fix] (MG_Impl/GLImpl): refresh generated mipmap storage [skip ci] 2026-07-02 19:22:39 +08:00
swung0x48 91120d86ba [Fix] (MG_Backend/DirectVulkan): ignore clear buffer without target [skip ci] 2026-07-02 19:16:14 +08:00
swung0x48 71f5ba9601 [Fix] (MG_Impl/GLImpl): handle program resource names [skip ci] 2026-07-02 19:10:50 +08:00
swung0x48 2e14b44349 [Fix] (MG_Impl/GLImpl): validate compute program queries [skip ci] 2026-07-02 19:04:23 +08:00
swung0x48 ac66ea7790 [Fix] (MG_Impl/GLImpl): validate program interface queries [skip ci] 2026-07-02 18:56:30 +08:00
swung0x48 632a4f0859 [Fix] (MG_Impl/GLImpl): reject default VAO draws [skip ci] 2026-07-02 18:51:11 +08:00
swung0x48 e2e4b6e579 [Fix] (MG_Impl/GLImpl): attach depth-stencil renderbuffers [skip ci] 2026-07-02 18:41:08 +08:00
swung0x48 37255523b1 [Fix] (MG_Impl/GLImpl): report incomplete framebuffer attachments [skip ci] 2026-07-02 18:29:26 +08:00
swung0x48 c3a830e9e6 [Fix] (MG_Impl/GLImpl): validate DSA texture unit binding [skip ci] 2026-07-02 18:05:53 +08:00
swung0x48 8266376838 [Fix] (MG_Impl/GLImpl, MG_State/GLState, MG_Backend): fix DSA renderbuffer defaults [skip ci] 2026-07-02 17:55:15 +08:00
swung0x48 d8e3c29744 [Fix] (MG_Impl/GLImpl): ignore legacy texture enable caps [skip ci] 2026-07-02 17:33:00 +08:00
swung0x48 ef3273674b [Fix] (MG_Impl/GLImpl): validate create texture targets [skip ci] 2026-07-02 17:15:19 +08:00
swung0x48 633a25b456 [Fix] (MG_Impl/GLImpl, MG_State/GLState): validate frag data link locations [skip ci] 2026-07-02 16:47:13 +08:00
swung0x48 b9de562491 [Fix] (MG_Impl/GLImpl, MG_State/GLState): fix frag data location queries [skip ci] 2026-07-02 16:20:43 +08:00
swung0x48 76f5a23b7f [Fix] (replay-trace, MG_Impl/GLImpl): fix OpenRA Android retrace 2026-07-02 16:08:43 +08:00
swung0x48 4a3a226f27 [Fix] (replay-trace) document frame-based fixture trimming 2026-07-02 14:51:41 +08:00
swung0x48 ced7f28898 [Fix] (MG_Impl/GLImpl, MG_State/GLState): reject unlinked empty programs [skip ci] 2026-07-02 14:37:29 +08:00
swung0x48 bc2db26e07 [Fix] (MG_Backend/DirectVulkan): validate shader storage block bindings [skip ci] 2026-07-02 14:25:40 +08:00
swung0x48 6649241193 [Fix] (MG_Impl/GLImpl): report compute shader minimum limits [skip ci] 2026-07-02 14:17:16 +08:00
swung0x48 fea8e615f9 [Fix] (MG_Impl/GLImpl): fix indexed shader storage buffer queries [skip ci] 2026-07-02 13:44:11 +08:00
swung0x48 57eb9bd415 [Fix] (MG_Impl/GLImpl): normalize integer texture border colors [skip ci] 2026-07-02 13:33:28 +08:00
swung0x48 0cd236414e [Fix] (MG_Impl/GLImpl, MG_State/GLState): fix texture integer border color queries [skip ci] 2026-07-02 13:17:08 +08:00
swung0x48 e4957e089a [Fix] (MG_State/GLState): ignore inactive frag data bindings [skip ci] 2026-07-02 12:51:51 +08:00
swung0x48 3c643d943a [Fix] (MG_Impl/GLImpl): fix more OpenGL 3.x piglit cases 2026-07-02 12:36:58 +08:00
swung0x48 9b06475811 [Fix] (replay-trace) refresh Minecraft 26.2 main menu fixture 2026-07-02 11:02:46 +08:00
swung0x48 fabae2465b [Fix] (MG_Impl/GLImpl, MG_Backend): fix OpenGL 3.1 piglit cases 2026-07-02 10:34:17 +08:00
swung0x48 233277d94b [Fix] (replay-trace) add Minecraft 26.2 vanilla fixtures 2026-07-02 09:07:20 +08:00
swung0x48 59976a7f7b [Feat] (MG_Impl/EGLImpl): expose surfaceless platform extensions 2026-07-02 08:09:56 +08:00
swung0x48 4613167abb [Fix] (replay-trace) hide removed mod cases in reports 2026-07-01 17:01:03 +08:00
swung0x48 f5f63aa044 [Feat] (replay-trace): add NeoForge earlydisplay fixture 2026-07-01 15:45:37 +08:00
swung0x48 6495c6dad9 [Fix] (replay-trace) fetch CI mod trace fixtures 2026-07-01 13:32:52 +08:00
swung0x48 2d1b8cdd30 [Fix] (replay-trace) run normal-world mod traces in CI 2026-07-01 13:07:35 +08:00
swung0x48 d2cbd2f596 [Fix] (replay-trace) recapture normal-world Fabric mod fixtures 2026-07-01 12:49:56 +08:00
swung0x48 6c7c5a1bc7 [Fix] (MG_Util/ShaderTranspiler): rename "sampler" in parameter name to avoid driver compiler issues 2026-06-30 22:31:49 +08:00
swung0x48 5b116696f0 [Fix] (MG_Impl/EGLImpl, MG_Backend): handle EGL current handoff for NeoForge earlydisplay
Treat valid-display no-surface eglMakeCurrent calls as EGL release requests, keep EGLState and backend current records consistent across threads, and rebind the native DirectGLES EGL context during attach/release.

Add EGLState coverage for cross-thread owner transfer and same-thread release/reattach behavior.
2026-06-30 16:44:38 +08:00
swung0x48 2f1949e093 [Feat] (iOS): support MobileGL builds and Metal surfaces 2026-06-30 07:25:20 +08:00
swung0x48 cca4df17d9 [Fix] (MG_Impl): preserve macOS surface during resize 2026-06-29 21:07:12 +08:00
swung0x48 ef06d90b6b [Fix] (MG_Backend/DirectGLES): record GenerateMipmap errors 2026-06-29 16:51:16 +08:00
swung0x48 e7e6888768 [Fix] (MG_Util/PixelStoreProcessor, MG_Backend/DirectVulkan): normalize packed RGBA uploads 2026-06-29 16:02:27 +08:00
swung0x48 a762346a3b [Fix] (TraceReplay): support local Android retrace reports 2026-06-29 13:53:30 +08:00
swung0x48 d78892cad0 [Fix] (replay-trace): enable GLES mod retraces and crop minimap 2026-06-29 10:17:30 +08:00
swung0x48 3fc6357f28 [Fix] (MG_Impl): handle Retina drawable resize on macOS 2026-06-28 23:22:33 +08:00
swung0x48 65ff056b2e [Docs] add macOS build and use instructions 2026-06-28 21:59:18 +08:00
swung0x48 f121aeb57f [Feat] (MG_Impl): add macOS CGL and NSOpenGL frontends 2026-06-28 20:33:14 +08:00
swung0x48 d61a0b6904 [Fix] (Tools/TraceReplay): show window surface after first present 2026-06-28 15:00:00 +08:00
swung0x48 0ef9c76224 [Feat] (MG_Backend/DirectVulkan): support macOS Metal surfaces 2026-06-28 14:19:51 +08:00
swung0x48 46f3192c67 [CI] add normal-world per-mod retrace fixtures 2026-06-28 13:00:12 +08:00
swung0x48 b2aafc3f95 [CI] wrap retrace summary status counts 2026-06-28 11:36:50 +08:00
swung0x48 531ebb3537 [CI] improve retrace summary mobile rendering 2026-06-28 11:30:17 +08:00
swung0x48 6a11f96a5b [CI] add per-mod common mod retrace fixtures 2026-06-28 10:40:52 +08:00
swung0x48 4fa2e0a58d [CI] improve retrace summary overview 2026-06-28 10:24:32 +08:00
swung0x48 c3d08a2125 [CI] stream retrace summary rendering 2026-06-28 10:24:31 +08:00
swung0x48 56be5318ab [CI] add common mod retrace fixtures 2026-06-28 07:40:31 +08:00
swung0x48 db388e64b9 [Fix] (MG_Backend/DirectVulkan): disable pipeline cache on PowerVR 2026-06-28 01:21:49 +08:00
swung0x48 5af927224f [CI] skip submodules for artifact-only jobs 2026-06-28 00:34:56 +08:00
swung0x48 b425b37e19 [CI] count crashed retrace summaries as failures 2026-06-28 00:18:48 +08:00
swung0x48 0132781fff [CI] isolate retrace summary images by device 2026-06-27 22:57:24 +08:00
swung0x48 9db9513c30 [CI] find retrace summary goldens from fixtures 2026-06-27 21:09:33 +08:00
swung0x48 2f62b90d7b [CI] show GPU names in retrace summary 2026-06-27 21:00:50 +08:00
swung0x48 f68c7296a6 [Fix] (MG_Backend/DirectGLES): clamp UNORM fallback writes 2026-06-27 20:46:02 +08:00
swung0x48 8fd25acbb6 [CI] upload self-contained retrace summary 2026-06-27 20:05:37 +08:00
swung0x48 59c9b94d76 [CI] add Mali main menu golden 2026-06-27 19:46:24 +08:00
swung0x48 d23e08f564 [CI] add remaining retrace fixtures 2026-06-27 19:20:23 +08:00
swung0x48 9a48c3f10c [CI] upload retrace PDFs without archives 2026-06-27 18:01:54 +08:00
swung0x48 790b542163 [CI] upload retrace summary PDFs separately 2026-06-27 17:32:13 +08:00
swung0x48 5032148cf0 [CI] wrap retrace summary counts 2026-06-27 17:27:17 +08:00
swung0x48 1c14c7b3ba [CI] remove retrace missing image count 2026-06-27 15:11:09 +08:00
swung0x48 82fabe90b3 [CI] clarify retrace summary missing assets 2026-06-27 15:08:07 +08:00
swung0x48 acf7341fb8 [CI] add retrace summary artifacts 2026-06-27 14:50:19 +08:00
swung0x48 ac33292e1b [Fix] (MG_Backend/DirectGLES): fix raw depth fetch sampler on GLES 2026-06-27 13:01:52 +08:00
swung0x48 5d6cb7dfed [Fix] (MG_Backend/DirectGLES): fix Super Duper Vanilla on Adreno
- emulate RGB16 SNORM fallback writes
2026-06-27 00:06:13 +08:00
swung0x48 195330ccea [Fix] (MG_Backend/DirectGLES): fix Complementary shaders on Mali
- emulate RGBA8 SNORM fallback writes
2026-06-26 23:33:46 +08:00
swung0x48 f6114c9e15 [CI] keep OpenRA fixture out of LFS 2026-06-26 20:15:50 +08:00
swung0x48 d2f2a0039f [Fix] (trace-replay): shorten iterationT fixtures 2026-06-26 15:58:53 +08:00
swung0x48 943600edb2 [Feature] (MG_Backend): log format caveat fallbacks 2026-06-26 14:49:51 +08:00
swung0x48 76acae9889 [Fix] (MG_Backend/DirectGLES): make format caveats probe-driven 2026-06-26 14:12:24 +08:00
swung0x48 9cca0a8753 [Feature] (MG_Backend): print format capability tables 2026-06-26 10:44:55 +08:00
swung0x48 8fe8d096fb [CI] fetch trace fixtures on demand 2026-06-25 23:50:24 +08:00
swung0x48 496fa50a23 [Fix] (MG_Impl/GLImpl): report backend format capabilities 2026-06-25 23:25:31 +08:00
swung0x48 9137396eae [Fix] (trace-replay): render DirectGLES replay onscreen by default 2026-06-23 21:42:24 +08:00
swung0x48 2f52264f01 [Fix] (trace-replay): use SSIM for golden validation 2026-06-23 21:26:55 +08:00
swung0x48 f0f6d1e5fa [Fix] (MG_Backend/DirectVulkan): fix prerotated default framebuffer 2026-06-23 20:00:43 +08:00
swung0x48 18d19a9a8b [Fix]: fix Complementary
- add a DirectGLES ANGLE fallback control for 8-bit SNORM texture formats

- normalize SNORM8 textures to float storage so ANGLE can render Complementary intermediate framebuffers

- reuse the normalized upload conversion path for SNORM8 and existing norm16 float fallbacks
2026-06-23 07:37:25 +08:00
swung0x48 3f53041ed2 [Fix]: fix BSL
- keep ANGLE RGBA16 textures on the native norm16 path

- add separate RGB16 and SNORM16 fallback controls for DirectGLES format normalization

- convert RGB16 fallback uploads to float when using RGB32F storage
2026-06-22 23:00:15 +08:00
swung0x48 c08ac7db72 [Fix]: fix Sundial Lite
- detach source texture from synced GLES framebuffers before mipmap generation

- bind a complete scratch framebuffer while calling glGenerateMipmap

- force ANGLE norm16 texture fallback and convert 16-bit normalized uploads

- raise Sundial Lite retrace tolerance for software DirectGLES validation
2026-06-22 22:07:06 +08:00
swung0x48 7419f62159 [Fix] (trace-replay): avoid attached FBO during GLES mipmap generation 2026-06-22 19:39:25 +08:00
swung0x48 252e59334d [Fix] (trace-replay): pass ANGLE path to APK retrace 2026-06-22 12:30:10 +08:00
swung0x48 565dc90bf0 [Fix] (trace-replay): use ANGLE for DirectGLES APK retrace 2026-06-22 12:18:33 +08:00
swung0x48 84eddaef2f [Fix] (ci): use software GPU for GLES APK retrace 2026-06-22 10:17:00 +08:00
swung0x48 641bfb1dd9 [Docs] (trace-replay): add mismatch retrace debugging guide 2026-06-22 09:48:49 +08:00
swung0x48 b87b698148 [Fix] (ci): cache native compilation 2026-06-22 09:24:21 +08:00
swung0x48 dac5f8964f [Chore] (ci): Use supported GPU settings 2026-06-22 08:49:27 +09:00
swung0x48 85ffcb74d8 [Fix] (ci): ignore optional trace artifact copy failures 2026-06-21 01:58:27 +08:00
swung0x48 9e719461e2 [Fix] (ci): fail fast on trace replay process exit 2026-06-21 00:59:36 +08:00
swung0x48 f270988e03 [Fix] (ci): harden Android trace replay CI 2026-06-21 00:07:13 +08:00
swung0x48 b4f9401395 [Fix] (ci): use ANGLE for APK retrace 2026-06-21 00:07:12 +08:00
swung0x48 a1e2007b82 [Fix] (trace-replay): support alternate golden images
- compare actual output against primary and alternate golden images

- record the matched golden path in trace replay results

- allow APK and Linux retrace fixtures to pass alternate golden paths

- keep nostalgia validation accepting both Mesa and PC goldens
2026-06-20 19:04:52 +08:00
swung0x48 e92a57011f [Fix] (ci): share AVD home across runner steps 2026-06-20 18:27:42 +08:00
swung0x48 3736e1fc38 [Fix]: fix Vulkan depth mipmap fallback
- add shader fallback for depth-only mipmap generation when format blit is unsupported

- choose native blit or shader path from Vulkan format features

- clean up temporary depth mipmap render resources per frame
2026-06-20 18:10:13 +08:00
swung0x48 2660e1669c [Fix] (ci): resolve Android SDK tools in AVD runner 2026-06-20 17:55:57 +08:00
swung0x48 be6818effe [Fix] (trace-replay): relax fixture tolerance 2026-06-20 17:15:24 +08:00
swung0x48 a49a463acf [Fix] (ci): split APK retrace AVD lifecycle
- expose AVD create, launch, retrace, diagnostics, and stop as separate workflow steps

- add bounded waits for emulator adb connection, boot, and trace replay execution

- collect emulator diagnostics for APK retrace artifacts
2026-06-20 14:27:11 +08:00
swung0x48 317b3602c3 [Fix] (ci): fix matrix retrace GLES runtime
- install EGL/GLES development runtime in retrace matrix jobs

- assert libEGL.so and libGLESv2.so are available before running trace replay

- remove native build cache wiring from workflows
2026-06-20 12:40:43 +08:00
swung0x48 b637962da0 [Chore] (ci): cache native builds 2026-06-20 12:15:34 +08:00
swung0x48 44f9dcb3a2 [Feat] (trace-replay): run retrace fixtures as matrix jobs 2026-06-20 11:44:41 +08:00
swung0x48 1a2b337618 [Fix] (trace-replay): fix APK retrace CI shell execution 2026-06-20 11:00:16 +08:00
swung0x48 d219ac3f6f [Docs] (trace-replay): add trace fixture authoring guide 2026-06-20 10:51:36 +08:00
swung0x48 1a2f867ba9 [Feat] (trace-replay): run all fixtures in APK retrace CI 2026-06-20 09:40:15 +08:00
swung0x48 0329f40df5 [Feat] (trace-replay): add Minecraft Sundial Lite shader fixture 2026-06-20 07:10:26 +08:00
swung0x48 193204de52 [Feat] (trace-replay): add Minecraft Derivative Main shader fixture 2026-06-20 06:54:40 +08:00
swung0x48 3f945dcfeb [Feat] (trace-replay): add Minecraft Photon v1.3b shader fixture 2026-06-20 06:43:04 +08:00
swung0x48 2f9ccb84d9 [Feat] (trace-replay): add Minecraft Super Duper Vanilla shader fixture 2026-06-20 06:32:25 +08:00
swung0x48 f10ea4ebcd [Chore] (trace-replay): remove local progress notes 2026-06-20 06:08:18 +08:00
swung0x48 ada6923039 [Fix] (trace-replay): fix Nostalgia golden alpha
- strip alpha from the Linux Mesa golden image
2026-06-20 05:59:43 +08:00
swung0x48 f4cf398651 [Feat] (trace-replay): validate remaining Minecraft shader fixtures
- register Chocapic with a Linux Mesa golden

- register Nostalgia with a Linux Mesa golden

- register Photon shader fixture
2026-06-20 05:44:43 +08:00
swung0x48 84dba77275 [Fix]: fix Bliss
- enable glslang NaN min/max/clamp semantics

- register Bliss retrace fixture

- track remaining fixture validation queue
2026-06-19 21:20:02 +08:00
swung0x48 19e4ba386d [Fix]: fix Chocapic V6 Lite
- prune unused SPIR-V interface variables before GLES transpilation

- remap shader varyings through glslang IO resolver bindings

- initialize opaque uniforms from explicit sampler bindings only

- avoid side effects in texture binding assertions

- register Chocapic V6 Lite retrace fixture
2026-06-19 18:42:32 +08:00
swung0x48 7d101182cd [Feat] (trace-replay): validate Minecraft Complementary Unbound shader fixture 2026-06-19 10:50:40 +08:00
swung0x48 e60b044ff7 [Fix] (trace-replay): validate Complementary Reimagined shader fixture
- clear stale temporary framebuffer attachments before DirectGLES color/depth blits

- add Complementary Reimagined in-world trace to retrace validation
2026-06-19 10:28:47 +08:00
swung0x48 4366909cf0 [Feat] (trace-replay): validate Minecraft iterationT no-DSA shader fixture 2026-06-19 09:25:20 +08:00
swung0x48 7b1d8ce9dd [Feat] (trace-replay): validate Minecraft iterationT shader fixture 2026-06-19 09:14:33 +08:00
swung0x48 94fdeb633f [Fix] (trace-replay): relax Minecraft BSL tolerance 2026-06-19 08:21:50 +08:00
swung0x48 50eda634e0 [Fix]: fix iterationT
- implement glCopyImageSubData frontend export and backend dispatch

- add DirectGLES depth-only CopyImageSubData via framebuffer depth blit

- add DirectGLES R32F CopyImageSubData fallback for GLES drivers rejecting native copy

- allocate DirectGLES generated mipmap storage for depth-only and R11FG11FB10F manual generation

- generate DirectGLES depth-only mipmaps with explicit depth blits

- generate DirectGLES R11FG11FB10F mipmaps with explicit color blits

- add DirectVulkan CopyImageSubData with explicit image copy and layout transitions

- use native Vulkan blit for depth-only mipmap generation

- remove unused Vulkan depth mipmap shader fallback path
2026-06-19 08:14:57 +08:00
swung0x48 2bf75537d8 [Feat] (trace-replay): add Minecraft iterationT no-DSA shader fixture 2026-06-18 21:09:23 +08:00
swung0x48 f780736f29 [Feat] (trace-replay): add Minecraft Nostalgia shader fixture 2026-06-18 08:04:22 +08:00
swung0x48 85e71622f8 [Feat] (trace-replay): add Minecraft Complementary Unbound shader fixture 2026-06-18 07:29:10 +08:00
swung0x48 ea02a2fac9 [Feat] (trace-replay): add Minecraft Complementary Reimagined shader fixture 2026-06-18 07:01:26 +08:00
swung0x48 8368901bf9 [Feat] (trace-replay): add Minecraft Chocapic shader fixture 2026-06-18 06:30:36 +08:00
swung0x48 a18170cdb1 [Feat] (trace-replay): add Minecraft Bliss shader fixture 2026-06-18 06:24:07 +08:00
swung0x48 e70fb39cb9 [Feat] (trace-replay): add Minecraft Photon shader fixture 2026-06-18 06:13:22 +08:00
swung0x48 e7ba689ca2 [Feat] (trace-replay): add Minecraft iterationT shader fixture 2026-06-18 05:42:48 +08:00
swung0x48 78dcf43c72 [Feat] (trace-replay): add Minecraft Mellow shader fixture 2026-06-17 23:51:17 +08:00
swung0x48 70951f46e5 [Feat] (trace-replay): add Minecraft MakeUP shader fixture 2026-06-17 20:09:21 +08:00
swung0x48 a6b4c4b049 [Feat] (trace-replay): add Minecraft BSL shader fixture 2026-06-17 17:52:30 +08:00
swung0x48 db3d569ed0 [Feat] (trace-replay): add Minecraft Sodium in-world fixture 2026-06-17 16:38:12 +08:00
swung0x48 ec0a1a0b70 [Fix] (ci): fetch trace fixtures from LFS 2026-06-17 14:11:28 +08:00
swung0x48 42e3cce8c3 [Fix] (ci): force info MobileGL log level 2026-06-17 13:59:38 +08:00
swung0x48 c82062a51b [Fix] (MobileGL): restore default log level 2026-06-17 13:50:48 +08:00
swung0x48 61349ac0c2 [Fix] (trace-replay): shorten Minecraft in-world fixture 2026-06-17 12:34:32 +08:00
swung0x48 102bd2cfd2 [Fix] (MG_Backend/DirectVulkan): support Sundial Lite shader pack 2026-06-17 11:39:20 +08:00
swung0x48 e7bb46e819 [Fix] (MG_Backend/DirectGLES): support Sundial Lite shader pack 2026-06-17 10:58:12 +08:00
swung0x48 02f8c7ab56 [Fix] (ci): use ANGLE for Android Vulkan retrace 2026-06-17 07:51:35 +08:00
swung0x48 96ecabc38b [Fix] (trace-replay): write opaque Android actual images 2026-06-17 07:26:15 +08:00
swung0x48 57600f2bd3 [Fix] (ci): use host GPU for Android Vulkan retrace 2026-06-17 06:59:15 +08:00
swung0x48 a8628feb3c [Fix] (ci): use non-deprecated Android emulator GPU 2026-06-17 06:14:22 +08:00
swung0x48 e2695235ab [Fix] (ci): allow Android Vulkan in-world variance 2026-06-17 05:41:29 +08:00
swung0x48 44c3ea7844 [Feat] (trace-replay): add Minecraft in-world fixture 2026-06-17 00:05:09 +08:00
swung0x48 7c81906459 [Fix] (ci): run all Android retrace fixtures 2026-06-16 20:36:53 +08:00
swung0x48 4e3679c7b7 [Fix] (ci): validate debuggable retrace APKs 2026-06-16 19:31:34 +08:00
swung0x48 19c0ae4e33 [Fix] (ci): make retrace APK debuggable 2026-06-16 18:09:46 +08:00
swung0x48 565649e3b6 [Fix] (ci): split APK retrace validation steps 2026-06-16 17:54:40 +08:00
swung0x48 527ef9653a [Fix] (ci): run APK retrace from parameterized script 2026-06-16 17:47:01 +08:00
swung0x48 23bb5245bd [Fix] (ci): run APK retrace script with bash 2026-06-16 17:04:57 +08:00
swung0x48 e3c4b94b11 [Fix] (ci): package retrace APK for all ABIs 2026-06-16 14:36:17 +08:00
swung0x48 3fa89640cd [Fix] (ci): split APK retrace job 2026-06-16 14:10:55 +08:00
swung0x48 722bddf916 [Feat] (trace-replay): test retrace APK on Android 2026-06-16 14:07:33 +08:00
swung0x48 294dad1773 [Fix] (ci): rename test workflow 2026-06-16 13:21:37 +08:00
swung0x48 b33ae1c481 [Feat] (trace-replay): add Minecraft main menu trace 2026-06-16 13:00:01 +08:00
swung0x48 0dc3a0916e [Feat] (trace-replay): add Minecraft startup trace 2026-06-16 12:22:27 +08:00
swung0x48 24372c8558 [Fix] (ci): rename retrace artifact 2026-06-16 11:06:40 +08:00
swung0x48 49faa5e749 [Fix] (ci): package existing Linux runtime files 2026-06-16 10:11:55 +08:00
swung0x48 69a3985f9d [Fix] (ci): reuse MobileGL artifact for retrace 2026-06-16 09:32:53 +08:00
swung0x48 d335131f52 [Fix] (ci): restore isolated retrace job 2026-06-16 09:14:53 +08:00
swung0x48 fe1b6db653 [Feat] (ci): reuse build outputs across jobs 2026-06-16 08:46:43 +08:00
swung0x48 4c2c4cb565 [Fix] (trace-replay): stabilize GL4ES OpenRA validation 2026-06-15 22:27:39 +08:00
swung0x48 bc8109b695 [Fix] (trace-replay): fix Android Vulkan pbuffer build 2026-06-15 21:01:55 +08:00
swung0x48 a88ca75c14 [Fix] (trace-replay): run Vulkan retrace headlessly 2026-06-15 20:37:40 +08:00
swung0x48 e453a75ea9 [Fix] (trace-replay): validate OpenRA on both backends 2026-06-15 19:59:21 +08:00
swung0x48 627f737bbe [Fix] (trace-replay): checkout nested submodules in CI 2026-06-15 19:35:48 +08:00
swung0x48 ef3e8da1b5 [Feat] (trace-replay): add Linux retrace CI 2026-06-15 18:08:55 +08:00
swung0x48 c2d6134cfa [Feat] (android-plugin): add standalone trace replay profile 2026-06-15 16:57:50 +08:00
swung0x48 d51723c153 [Fix] (MG_Backend/DirectGLES): use safer buffer upload path. MAY AFFECT PERFORMANCE!! 2026-06-11 10:28:39 +08:00
swung0x48 94b2a863bf [Chore] (MG_Impl/GLSync): stub out gl sync 2026-06-11 09:50:20 +08:00
swung0x48 442510f793 [Fix] (MG_Impl/GLImpl): split backend-dependent integer getters 2026-06-11 07:18:29 +08:00
swung0x48 75a0fc2c0c [Fix] (MG_Impl/GLImpl): fix DSA state queries and compatibility tests
Fix texture parameter getters and element array buffer binding queries.
Update framebuffer, texture, program, and VAO tests to match current OpenGL semantics, while preserving VAO 0 compatibility behavior.
2026-06-10 23:33:59 +08:00
swung0x48 72b1f50314 [Fix] (MG_Backend/DirectGLES): don't glFlush on present 2026-06-10 18:44:59 +08:00
swung0x48 66c36cd945 Merge pull request #9 from BZLZHH/Agent/CodexAudit 2026-06-10 12:33:01 +08:00
BZLZHH d091d9c460 [Misc] (...): Remove SOURCE_AUDIT.md 2026-06-10 09:57:07 +08:00
BZLZHH d3a2e2e666 [Chore] (...): Disable debug log. 2026-06-10 09:52:30 +08:00
BZLZHH a4261f8b19 [Fix] (MG_Backend/DirectVulkan, MG_State/TextureState, MG_Test): harden default-fbo clear lifetime tracking 2026-06-10 09:49:16 +08:00
BZLZHH 6051588458 [Feat] (MG_Backend/DirectVulkan): implement multisample texture backend 2026-06-10 01:56:37 +08:00
BZLZHH 5c1fd733da [Feat] (MG_Backend/DirectGLES): implement multisample texture backend 2026-06-10 01:41:44 +08:00
BZLZHH c499480692 [Feat] (MG_Impl/Texture, MG_State/TextureState, MG_Impl/Framebuffer, MG_Test/Texture): implement multisample frontend state 2026-06-10 01:37:59 +08:00
BZLZHH 3da0b1dfd4 [Fix] (MG_Backend/DirectVulkan, MG_Impl/Texture, MG_Test/Texture): fill advertised extension gaps 2026-06-10 01:09:39 +08:00
BZLZHH 720919455f [Fix] (MG_Backend/DirectGLES, MG_Impl/Texture, MG_Test/Texture): fix Voxy base-instance and bound texStorage2D 2026-06-10 00:07:20 +08:00
BZLZHH df90753d85 [Fix] (MG_Impl/Framebuffer, MG_Test/Framebuffer): avoid duplicate glFramebufferTexture attach 2026-06-09 22:18:28 +08:00
BZLZHH 7bee645b9a [Fix] (MG_Util/Texture): remove duplicate depth-stencil normalize case 2026-06-09 21:33:27 +08:00
BZLZHH 83a6f24f93 Merge remote-tracking branch 'origin/Feat/Backend-Direct-Vulkan' into Agent/CodexAudit
# Conflicts:
#	MobileGL/MG_Backend/BackendObject.h
#	MobileGL/MG_Backend/DirectGLES/Managers.cpp
#	MobileGL/MG_Backend/DirectVulkan/BackendObject_DirectVulkan.cpp
#	MobileGL/MG_Backend/DirectVulkan/Renderer/FrameContext.cpp
#	MobileGL/MG_Backend/DirectVulkan/Renderer/VkTextureManager.cpp
#	MobileGL/MG_Backend/DirectVulkan/Renderer/VulkanRenderer.cpp
#	MobileGL/MG_Impl/GLImpl/Buffer/GL_Buffer.cpp
#	MobileGL/MG_Impl/GLImpl/Exporting/Definitions.cpp
#	MobileGL/MG_Impl/GLImpl/Framebuffer/GL_Framebuffer.cpp
#	MobileGL/MG_Impl/GLImpl/Getter/GL_Getter.cpp
#	MobileGL/MG_Impl/GLImpl/Getter/GL_Getter.h
#	MobileGL/MG_Impl/GLImpl/Program/GL_Program.cpp
#	MobileGL/MG_Impl/GLImpl/Program/GL_Program.h
#	MobileGL/MG_Impl/GLImpl/Sync/GL_Sync.cpp
#	MobileGL/MG_Impl/GLImpl/Sync/GL_Sync.h
#	MobileGL/MG_Impl/GLImpl/Texture/GL_Texture.cpp
#	MobileGL/MG_Impl/GLImpl/VertexArray/GL_VertexArray.cpp
#	MobileGL/MG_Impl/GLImpl/VertexArray/GL_VertexArray.h
#	MobileGL/MG_State/GLState/BufferState/BufferObject.cpp
#	MobileGL/MG_State/GLState/BufferState/BufferObject.h
#	MobileGL/MG_Util/BackendLoaders/Vulkan/Loader.cpp
#	MobileGL/MG_Util/BackendLoaders/Vulkan/Loader.h
2026-06-09 21:18:12 +08:00
BZLZHH 8d35be14a0 [Fix] (MG_Backend/DirectGLES, MG_Util/BackendLoader): stop treating partial EGL/GLES symbol load as fatal 2026-06-09 19:57:30 +08:00
swung0x48 85bd0613ca [Fix] (MG_Backend/DirectGLES): support Voxy rendering
Implemented:

- Advertise Voxy-required DirectGLES extensions without raising the reported OpenGL version.

- Add DirectGLES multi draw indirect count emulation and preserve GL draw indirect baseInstance semantics on GLES.

- Add DirectGLES DSA framebuffer clear/blit paths used by Minecraft and Voxy presentation.

Fixed:

- Rewrite gl_BaseInstance in DirectGLES vertex shaders and provide a backend uniform for indirect draw emulation.

- Materialize framebuffer attachment textures during DirectGLES FBO sync so named framebuffer operations do not desync backend attachment state.

- Avoid redundant texture buffer rebinding and handle texture buffers without bound storage during backend sync.

Tests:

- Add MG_Test coverage for DirectGLES Voxy extension advertising, baseInstance shader rewriting, and DSA named framebuffer clear/blit backend wiring.
2026-06-09 17:20:23 +08:00
BZLZHH 727939af5b [Fix] (MG_Impl, MG_State, MG_Backend, MG_Util): Do source audit by Codex. 2026-06-09 15:34:19 +08:00
swung0x48 dd52f0381a [Fix] (MG_Backend/DirectVulkan): fix Voxy subgroup and indirect draw sync
- Implement Vulkan subgroup capability querying and expose KHR subgroup getter values.

- Fix DirectVulkan memory barriers so GL_COMMAND_BARRIER_BIT makes generated indirect draw commands visible.

- Keep Voxy on the DirectVulkan gpu_shader_int64 quad decode path while filtering unsupported optional int64 usage on backends that do not advertise it.

- Add MG_Test coverage for subgroup getters, Voxy subgroup/int64 shader probes, command barrier mapping, and indirect draw command layout.

- Check for whether driver supports shader subgroup operation, disable on demand, and provide env var `MOBILEGL_DISABLE_SUBGROUP` to explicitly disable subgroup features
2026-06-09 09:46:07 +08:00
swung0x48 cf165c0db5 [Fix] (MG_Backend/DirectVulkan): support Voxy rendering
Implemented:

- Advertise Voxy-required DirectVulkan extensions without raising the reported OpenGL version.

- Add DirectVulkan compute, indirect draw count, DSA, readback, and buffer state paths needed by Voxy.

Fixed:

- Enable Vulkan shaderInt64 and drawIndirectFirstInstance so Voxy baseInstance-driven LOD draws address the correct section data.

- Fix DirectVulkan synchronization, framebuffer, texture readback, and shader interface handling used by Voxy and Minecraft screenshots.

Tests:

- Add MG_Test coverage for DirectVulkan extension advertising, DSA buffer/texture/framebuffer/vertex-array behavior, persistent mapped readback, and shader/program paths.
2026-06-09 00:37:37 +08:00
swung0x48 ab9db43599 [Chore]: bump version to 26.06 2026-06-08 14:11:20 +08:00
swung0x48 d553e363a7 [Feat] (MG_Impl/GL_Buffer, MG_State/BufferState, MG_Backend): implement persistent mapping 2026-06-08 14:08:35 +08:00
swung0x48 be3c3eb9bb [Fix] (MG_Test/VertexArray): lossen too strict error test 2026-06-08 09:43:24 +08:00
swung0x48 357807666d [Fix] (MG_Backend/DirectVulkan, MG_Backend/DirectGLES): fix vulkan program
cache, get EGLSurfaceSize on viewport = 0
2026-06-08 05:41:38 +08:00
BZLZHH d1a5a4e39c [Fix] (MG_Util/BackendLoader): Add /usr/lib64 and /lib64 to library search paths for Fedora/RHEL compatibility. 2026-06-07 20:28:19 +08:00
swung0x48 a701c896f0 [Feat] (MG_Backend/DirectVulkan): wire up client-side buffer 2026-06-07 18:05:48 +08:00
swung0x48 b0de886f8e [Fix] (MG_Backend/DirectVulkan): make glmark2 work on Magma 2026-06-07 16:24:30 +08:00
swung0x48 ad1ca4ea92 [Feat] (MG_Impl/VertexArray): implement client-side buffer 2026-06-07 13:02:58 +08:00
swung0x48 fbaf5261e2 [Fix]: properly open X11 display for rendering 2026-06-07 12:26:35 +08:00
swung0x48 19ada4b8f9 [Fix]: fix glmark2 crash
- deal with legacy GLSL syntax (attribute/varying/gl_FragColor/texture2D/etc.)
- implement glGet GL_SHADER_SOURCE_LENGTH, and make sure returns
  original shader source
- expose proper extensions (GL_ARB_depth_texture)
- support env var MOBILEGL_LOG_FILE_PATH
- unit tests to test against those changes
2026-06-07 11:08:38 +08:00
swung0x48 ff41e59282 [Feat] (EGL): support Linux X11 + EGL 2026-06-07 08:21:20 +08:00
swung0x48 a15a13ca46 [Fix]: fix compilation on Linux 2026-06-06 23:18:27 +08:00
swung0x48 2937043e77 [Fix] (MG_Backend/DirectGLES): mark integer varyings flat 2026-06-06 18:58:27 +08:00
swung0x48 24efb0bb17 [Fix] (MG_Impl/Program): implement direct state uniform updates 2026-06-06 17:27:09 +08:00
swung0x48 dd2bd267c1 [Fix] (MG_State/RenderState): track front face mode 2026-06-06 08:46:43 +08:00
swung0x48 5cfe9c8998 [Feat] (MG_Backend/DirectVulkan): support compute shaders 2026-06-05 11:52:10 +08:00
swung0x48 3bd8a62aa8 [Feat] (MG_Backend/DirectGLES): support compute shaders 2026-06-05 10:41:23 +08:00
swung0x48 dcd37f3c38 [Fix] (MG_Util/ShaderTranspiler): preserve reflected uniform backing 2026-06-05 10:39:53 +08:00
swung0x48 a579fd2342 [Feat] (MG_State/ProgramState): attempting to do shader LTO (WIP) 2026-06-01 22:26:16 +08:00
swung0x48 f93ff00642 [Chore] (MG_State/ProgramState): add more remarks to GenerateBinary() 2026-06-01 21:35:28 +08:00
swung0x48 8a628631fb [Feat] (Backend/DirectVulkan): implement min/max lod
- This fixes water waves in Derivative d24.4.14
2026-06-01 05:38:28 +08:00
swung0x48 59733a2a26 [Fix] (MG_Backend/DirectVulkan): clear alpha as 1.0f when using RGB format on GL side. Transition to VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL for clearing 2026-05-24 19:23:36 +08:00
swung0x48 c7d385c03d [Fix] (CI): scan rather than hardcode apk file name 2026-05-24 18:45:24 +08:00
swung0x48 27a8aa057c [Feat] (MG_Impl/RenderState): implement some blend related states 2026-05-24 17:38:44 +08:00
swung0x48 e63bfbabf0 [Chore] (MG_Backend/DirectVulkan): enable vulkan validation layer only on DEBUG log level 2026-05-24 11:11:12 +08:00
swung0x48 c107d9edcf [Fix] (MG_Backend/DirectVulkan): use RGBA format as RGB format
- some drivers (Adreno as I tested) lacks
  VK_FORMAT_FEATURE_COLOR_ATTACHMENT_BLEND_BIT on 24-bit RGB formats,
  use 32-bit ones as a fallback.
2026-05-24 10:07:28 +08:00
swung0x48 49e69c1c7d [CI] (android-plugin): build two (Espryt/Magma) variants 2026-05-24 08:57:02 +08:00
swung0x48 482b6d7bbf [CI] (android-plugin): specify MOBILEGL_LOG_ACTIVE_LEVEL=MOBILEGL_LOG_LEVEL_INFO define 2026-05-24 08:45:02 +08:00
swung0x48 dcfe91bdfc [Optimization] (MG_Backend/DirectVulkan): properly use vkCmdBlitImage() on rotations that
applicable, rather than shader-based blit
2026-05-24 00:14:05 +08:00
swung0x48 6072b5b703 [Fix] (MG_Backend/DirectVulkan): use shader-based default framebuffer blit to fix wrong orientation 2026-05-24 00:07:16 +08:00
swung0x48 9c50ac8a69 [CI]: use DirectVulkan as default backend 2026-05-23 23:01:48 +08:00
swung0x48 8b7acad257 [CI]: add android build key + signing process 2026-05-23 21:54:40 +08:00
swung0x48 cb8cb48a60 [CI]: build MobileGL android renderer plugin 2026-05-23 20:58:03 +08:00
swung0x48 8c00ae1d38 [Fix] (MG_Impl/GL_Texture): don't actually allocate large proxy texture to avoid large allocation makes some devices to crash 2026-05-12 16:33:30 +08:00
swung0x48 633b3d3b0a [Feat] (MG_State/RenderState, MG_Backend/DirectVulkan): make Distant
Horizon work
- Implement BlendEquation/CullFaceMode/PointSize/PolygonMode
- Implement GetFramebufferAttachmentParameter*
- Downgrade some color attachment resolve failure
- Downgrade some overly-strict shader stage linkage check (don't check
  on unused input var)
2026-05-12 12:38:19 +08:00
swung0x48 60199c0323 [Optimization] (MG_Backend/DirectVulkan): optimize CreatePipeline hot path with VkPipelineCache 2026-05-12 00:27:52 +08:00
swung0x48 9e0e03d4c0 [Optimaization] (MG_Backend/DirectVulkan): optimize perf
- Properly reuse descriptor sets rather than always allocating
- Add program lookup cache
2026-05-11 23:20:55 +08:00
swung0x48 4972ebf914 [Fix] (MG_Backend/DirectVulkan): fix 1.21.6+ intermittent crashing
- Try coerce vertex input format to please Vulkan driver
- Skip inactive UBO instead of hard fast-fail
2026-05-10 11:53:26 +08:00
swung0x48 4a36d63c1b [Fix] (MG_Backend/DirectVulkan): fix 26.2 texture bug.
- Fix texture object / buffer lifecycle issues
2026-05-10 10:03:03 +08:00
swung0x48 d7e768096e [Fix] (MG_Backend/DirectVulkan): fix Minecraft 26.2 startup crashes
- Support cube map face uploads with cube-compatible images and per-face array layers
- Add uniform texel buffer descriptor support for samplerBuffer bindings
- Cache transient vertex/index buffer uploads per frame to avoid VMA allocation failures
2026-05-10 08:50:55 +08:00
swung0x48 e13b5d0618 [Chore] (MG_Backend/DirectVulkan): make Photon fix a SPIR-V patch rather than source-level 2026-05-09 17:46:16 +08:00
swung0x48 c5bf0dc07d [Chore] (MG_Backend/DirectVulkan): exclude some validation logic from release build 2026-05-09 13:45:19 +08:00
swung0x48 9fbd83d602 Merge branch 'Feat/Backend-Direct-Vulkan' of https://github.com/MobileGL-Dev/MobileGL into Feat/Backend-Direct-Vulkan 2026-05-09 13:08:12 +08:00
swung0x48 39c5b28dfb [Fix] (MG_Backend/DirectVulkan): fixing Photon v1.1
- Flatten DailyWeatherVariation interface varyings
- Correct internal-format component counts
- Preserve GL draw-buffer slot semantics in render pass creation
- relax GL_NONE / vec4-to-RGB pipeline checks
2026-05-09 09:56:45 +08:00
BZLZHH be533994e5 Merge branch 'dev' into Feat/Backend-Direct-Vulkan 2026-05-09 08:32:33 +08:00
BZLZHH 368c089172 Merge branch 'Perf/Improvement1' into dev 2026-05-09 08:31:36 +08:00
BZLZHH 30c6f55c2d [Fix] (MG_Backend/DirectVulkan): Add namespace qualifier to Version type. 2026-05-09 08:28:46 +08:00
swung0x48 407d4344c4 [Feat] (MG_Backend/DirectVulkan): generate mipmap, add fallback texture, implement shader-based depth mipmap blit, enumerate more vk physical device features
- Supporting iterationT
2026-05-08 09:25:41 +08:00
swung0x48 76e3950028 [Feat] (MG_Backend/DirectVulkan): GenerateMipmap WIP 2026-05-07 15:14:25 +08:00
swung0x48 7337b00ca8 [Feat] (MG_Backend/DirectVulkan): implement 3D texture handling 2026-05-07 12:28:14 +08:00
swung0x48 22582dea3e [Chore] (MG_Backend/DirectVulkan): get rid of 1x1 texture fallback path for unbinded sampler 2026-05-07 09:30:10 +08:00
swung0x48 f600a07404 [Fix] (MG_Backend/DirectVulkan): use fallback texture in case some
shaderpack failes to properly bind texture
2026-05-06 17:57:59 +08:00
swung0x48 ff790e1ff1 [Feat] (MG_Backend/DirectVulkan): implement vulkan backend for glCopyTex(Sub)Image2D 2026-05-06 15:39:59 +08:00
swung0x48 a345369269 [Fix] (MG_Backend/DirectVulkan): fix null dereference crash in VkClearManager 2026-05-06 13:15:08 +08:00
swung0x48 8e4a4359b4 [Chore] (MG_Backend/DirectVulkan): eliminate vague texture binding fallbacks 2026-05-05 18:34:44 +08:00
swung0x48 0a000d1628 [Feat] (MG_Backend/DirectVulkan): more built-in function renames 2026-05-05 18:33:20 +08:00
swung0x48 5bd8e369c4 [Feat] (MG_Backend/DirectVulkan): advertise GL_ARB_draw_buffers_blend for DirectVulkan backend 2026-05-05 18:02:20 +08:00
swung0x48 777d756d1b [Fix] (MG_Impl/GL_Texture): properly unbind texture when texture name == 0 2026-05-05 17:23:57 +08:00
swung0x48 7716a8e05d [Fix] (MG_Backend/DirectVulkan): more flexible ResolveSamplerDescriptor 2026-05-05 17:13:35 +08:00
swung0x48 94e93b171c [Feat] (MG_Backend/DirectVulkan): get real maxProgramBindings from VkDevice 2026-05-05 13:19:45 +08:00
swung0x48 1bf12be278 [Fix] (MG_Util/ShaderTranspiler): add preprocessing to remove name-collided glsl functions 2026-05-05 12:58:36 +08:00
swung0x48 99b753be9a [Feat] (MG_Backend/DirectVulkan): implement backend func for glCopyTex(Sub)Image2D 2026-05-05 12:02:33 +08:00
swung0x48 bc2f2d896b [Chore]: bump version to 26.05 2026-05-05 09:12:01 +08:00
swung0x48 659fbf26da [Fix] (MG_Backend/DirectVulkan): fix depth sampler state, fixing BSL
shadow
2026-05-05 00:40:17 +08:00
swung0x48 f61a7bb9c0 [Fix] (MG_Backend/DirectVulkan): fix some uniform/sampler binding 2026-05-04 22:48:50 +08:00
swung0x48 212309083a [Fix] (MG_State/EGLState): fix compilation error on 32-bit arch where EGLAttrib & EGLint are the same type and collides 2026-05-03 19:52:29 +08:00
swung0x48 c1ebd01a70 Merge pull request #8 from MobileGL-Dev/Feat/Backend-Direct-Vulkan
Feat/backend direct vulkan
2026-04-26 21:55:28 +08:00
swung0x48 af58e2c7b4 [Fix] (MG_Backend/DirectVulkan/VertexInputStateFactory): don't use SSCALED formats 2026-04-26 19:43:27 +08:00
BZLZHH b373535d6e [Fix] (MG_Impl/Texture): Fix proxy texture object handling. 2026-04-06 02:35:04 +08:00
swung0x48 4a3a44924a [Refactor] (MG_Backend/DirectVulkan/ProgramFactory): refactor uniform reflection 2026-04-03 16:45:11 +08:00
swung0x48 1b2a7989af [Fix] (MG_Util/ShaderTranspiler/SpvcSession): use proper usage bit to select the right code path. Fix bugs along the way 2026-04-01 14:57:00 +08:00
swung0x48 83d1ce177e [Optimization] (MG_Util/ShaderTranspiler/SpvcSession): use SPIRV-Reflect to avoid full AST parse, speeding up reflection 2026-04-01 10:28:37 +08:00
swung0x48 4321c4a827 [Submodule] (3rdparty/SPIRV-Reflect): add SPIRV-Reflect as dependency 2026-03-29 00:03:57 +08:00
swung0x48 a039ce0987 [Chore] (MG_State/ProgramState): some renames 2026-03-26 09:49:05 +08:00
swung0x48 accfaab720 [Refactor] (MG_Backend/DirectVulkan): get rid of junk, and rename some symbols 2026-03-24 14:20:21 +08:00
swung0x48 35658eb998 [Refactor] (MG_Backend/DirectVulkan): move uniform reflection from UniformDescriptorBinder to ProgramFactory 2026-03-23 16:36:17 +08:00
swung0x48 ccbde0196e [Fix] (MG_Test/ProgramTest): fix wrong decomp source output 2026-03-21 23:07:27 +08:00
swung0x48 0209c5461f [Feat] (MG_Backend/DirectVulkan): implement naive transient/resident buffer, and heuristics to downgrade resident buffer to transient 2026-03-20 17:39:10 +08:00
swung0x48 810b4886c7 [Feat] (MG_Backend/DirectVulkan): supports uint8 index buffer by VK_KHR_index_type_uint8 / VK_EXT_index_type_uint8 2026-03-20 15:27:57 +08:00
swung0x48 7dfc2149d8 [Feat] (MG_Backend/DirectVulkan): unified transient buffer arena 2026-03-20 13:56:12 +08:00
swung0x48 9d1e8bd7cd [Feat] (MG_Backend/DirectVulkan): VkBufferManager transient upload now includes uniform 2026-03-20 13:31:51 +08:00
swung0x48 bfa4049ac1 [Chore] (MG_Backend/DirectVulkan): unwrap frame context initialization 2026-03-20 09:55:22 +08:00
swung0x48 87c56ce3d5 [Fix] (MG_Backend/DirectVulkan): Fix VkBufferManager initialization assertion failure 2026-03-20 09:36:37 +08:00
swung0x48 f2ab50b84e [Feat] (MG_Backend/DirectVulkan): VkBufferManager 2026-03-19 17:44:35 +08:00
swung0x48 b6ac6c182e [Feat] (MG_Backend/DirectVulkan): Buffer arena, buffer slice 2026-03-19 17:23:52 +08:00
swung0x48 5e9f0f0c70 [Chore] (MG_Backend/DirectVulkan): remove some unused stuff 2026-03-19 08:59:34 +08:00
swung0x48 e4455aed9a [Feat] (MG_Backend/DirectVulkan): add draw cmd MultiDrawIndexedCmd 2026-03-18 16:08:00 +08:00
swung0x48 bc018c9513 [Chore] (MG_Backend/DirectVulkan): add indexBufferView field for draw cmds 2026-03-18 13:25:10 +08:00
swung0x48 2ecba4d70c [Fix] (MG_Test/VertexArrayTest): fix VertexArrayTest compilation error 2026-03-18 13:07:57 +08:00
swung0x48 1e11a5950e [Fix] (MG_Test/BufferTest): fix BufferTest compilation error 2026-03-18 11:07:56 +08:00
swung0x48 b324363db0 [Chore] (MG_Backend/DirectVulkan): hard assert SetupDraw failure 2026-03-18 11:01:00 +08:00
swung0x48 a654b15190 [Feat] (MG_Backend/DirectVulkan): naively implement DrawElementsBaseVertex and MultiDrawElementsBaseVertex 2026-03-18 10:43:30 +08:00
swung0x48 75ea7f8c0c [Chore] (MG_Backend/DirectVulkan): include index buffer upload into SetupDraw 2026-03-17 16:09:02 +08:00
swung0x48 09aeee4c03 [Chore] (MG_State/VertexArrayState): add const getter to index buffer binding slot 2026-03-17 15:55:16 +08:00
swung0x48 87122973be [Chore] (MG_Backend/DirectVulkan): refactor draw cmds 2026-03-17 15:10:17 +08:00
swung0x48 8b9adc5121 [Fix] (MG_Backend/DirectVulkan/VkRenderPassManager): avoid reusing active render pass when draw FBO attachments still have pending clears 2026-03-17 14:34:50 +08:00
swung0x48 9e42e40705 [Chore] (MG_Backend/DirectVulkan): notes for MaterializePendingClearForTexture 2026-03-09 17:13:56 +08:00
swung0x48 8a91225eb1 [Chore] (MG_Backend/DirectVulkan): debug log for clear manager 2026-03-09 16:22:51 +08:00
swung0x48 e82815802e [Feat] (MG_Backend/DirectVulkan): implement texture mipmap 2026-03-09 15:09:05 +08:00
swung0x48 67069d4a12 [Fix]: compilation error after merge 2026-03-08 11:06:27 +08:00
swung0x48 4a38e7224e Merge branch 'dev' into Feat/Backend-Direct-Vulkan 2026-03-08 10:31:44 +08:00
swung0x48 645f2f748f [Fix] (MG_Backend/DirectVulkan): fix missing clear when (texture-FBO attach -> clear -> detach) occurs 2026-03-08 00:24:30 +08:00
swung0x48 5652f9ae5f [Chore] (MG_Backend/DirectVulkan): implements BlitFramebuffer using backend manager APIs 2026-03-07 19:29:33 +08:00
swung0x48 f3b0b242dd [Feat] (MG_Backend/DirectVulkan): implements BlitFramebuffer 2026-03-07 18:22:38 +08:00
swung0x48 876cb7bcd3 [Chore] (MG_Backend/DirectVulkan): asserts fbo existence 2026-03-07 09:33:05 +08:00
swung0x48 ee9a121c6f [Fix] (MG_Impl/Init): bind default fbo to draw/read slot at init 2026-03-07 09:31:42 +08:00
swung0x48 00439c5c4a [Fix] (MG_Backend/DirectVulkan): Fix sampled-texture/render-pass layout hazard 2026-03-06 21:53:50 +08:00
swung0x48 d7286a5832 [Fix] (MG_Backend/DirectVulkan): some transition fixes 2026-03-06 18:25:33 +08:00
swung0x48 972804fdc7 [Fix] (MG_Backend/DirectVulkan): fixing some layout mismatch 2026-03-06 17:16:55 +08:00
swung0x48 bca7328421 [Fix] (MG_Backend/DirectVulkan): use hash to save active render pass 2026-03-06 16:17:56 +08:00
swung0x48 8097c0d7b1 [Fix] (MG_Backend/DirectVulkan): add untreated aspect member in TextureResource move ctor 2026-03-06 15:45:19 +08:00
swung0x48 641f54e1b7 [Feat] (MG_Backend/DirectVulkan): Transition texture for sampling 2026-03-06 15:37:14 +08:00
swung0x48 c36bfe0843 [Fix] (MG_Backend/DirectVulkan): track image layout naively 2026-03-06 14:53:43 +08:00
swung0x48 8ae66521e3 [Fix] (MG_Backend/DirectVulkan/VkRenderPassManager): early return when there's an active render pass that is compatible 2026-03-06 14:46:51 +08:00
swung0x48 6e21fd9a35 [Chore] (MG_Backend/DirectVulkan): a lotta assertions & transition uploaded texture directly to VK_ACCESS_SHADER_READ_BIT 2026-03-05 23:17:27 +08:00
swung0x48 a2e8faafe5 [Fix] (MG_Backend/DirectVulkan): upload buffer using fence, without vkQueueWaitIdle 2026-03-05 18:02:28 +08:00
swung0x48 668fa3033e [Optimize] (MG_Backend/DirectVulkan): store textureResources in permanent scratch space rather than temp memory 2026-03-05 09:44:03 +08:00
swung0x48 139f3f978d [Chore] (MG_Backend/DirectVulkan): get rid of unnecessary checks 2026-03-04 16:19:35 +08:00
swung0x48 09f96e5ba5 [Fix] (MG_Backend/DirectVulkan): Properly handle front face state. save VkDevice as static member 2026-03-04 15:08:23 +08:00
swung0x48 592a69b1c4 [Feat] (MG_Backend/DirectVulkan): integrating cullmode and frontface render state into vk pipeline 2026-03-03 17:01:02 +08:00
swung0x48 9211341ae7 [Chore] (MG_Backend/DirectVulkan): remove unused functions 2026-03-03 15:16:27 +08:00
swung0x48 5f9d354adb [Fix] (CMakeLists): add absent source file 2026-03-03 15:05:33 +08:00
swung0x48 0ae36b71f5 [Chore] (MG_Backend/DirectVulkan): move ClearAttachmentsOnActiveRenderPass to VulkanRenderer 2026-03-03 14:59:03 +08:00
swung0x48 20e2768f27 [Chore] (MG_Backend/DirectVulkan): move enum conversion to MG_Utils 2026-03-03 14:17:28 +08:00
swung0x48 00c8b5ae3a [Chore] (MG_Backend/DirectVulkan): get rid of unused functions 2026-03-03 13:38:06 +08:00
swung0x48 7687c19b33 [Fix] (MG_Backend/DirectVulkan): hook up TextureManager to TextureEnumConverter 2026-03-03 13:30:33 +08:00
swung0x48 fc3a7cd5f1 [Chore] (Config): Bump version to 26.03 2026-03-03 10:50:24 +08:00
swung0x48 0b7f906533 [Fix] (MG_Backend/DirectVulkan): use proper scissor state to fix menu 2026-03-03 09:43:25 +08:00
swung0x48 c78a94ed09 [Chore] (MG_Backend/DirectVulkan): use vkCmdClearAttachments to implement clear semantics when there's one compatible render pass in flight (instead of interrupting it) 2026-03-02 17:16:18 +08:00
swung0x48 debcb171ce [Chore] (MG_Backend/DirectVulkan): relaxing byteSize checks for textures in VkTextureManager 2026-03-02 14:55:55 +08:00
swung0x48 282468c9d5 [Fix] (MG_Backend/DirectVulkan): query clear color/state inside of RenderPassManager 2026-03-02 10:13:59 +08:00
swung0x48 34b06da83b [Fix] (MG_Backend/DirectVulkan): get ImageView from swapchain when creating render pass for default FBO 2026-03-02 09:49:32 +08:00
swung0x48 3d55f38dab [Fix] (ConfigLoader): still defaults to DirectGLES backend 2026-03-02 08:58:15 +08:00
swung0x48 16426db244 [Chore] (MG_Backend/DirectVulkan): manage active renderpass inside RenderPassManager static functions 2026-03-01 23:02:54 +08:00
swung0x48 6f8c76f06c [Fix] (MG_Backend/DirectVulkan): fixing Vulkan backend initialization 2026-03-01 22:39:30 +08:00
swung0x48 43f2043478 [Fix] (MG_Backend/DirectVulkan): Vulkan backend default framebuffer initialization 2026-03-01 21:21:32 +08:00
swung0x48 f61f068e28 [Fix] (MG_Backend/DirectVulkan): refactor VkRenderPassManager and hook it up (this commit only compiles and does not work) 2026-03-01 18:17:34 +08:00
swung0x48 e234d471fe [Fix] (MG_Backend/DirectVulkan): uninitialized vars in VkRenderPassManager 2026-02-28 18:00:31 +08:00
swung0x48 6ff97a9bb1 [Feat] (MG_Backend/DirectVulkan): new VkRenderPassManager and a bunch of changes accordingly 2026-02-28 17:37:45 +08:00
swung0x48 8adf1d3b8a [Chore] (MG_Backend/DirectVulkan): get rid of junk 2026-02-27 17:36:57 +08:00
swung0x48 2935279603 [Chore] (MG_Backend/DirectVulkan): remove "transition" stuff in VkRenderTargetManager 2026-02-27 16:34:09 +08:00
swung0x48 918b39bb63 [Fix] (MG_Backend/DirectVulkan): remove weird texture binding fallback 2026-02-27 16:22:19 +08:00
swung0x48 963e88943c [Chore] (MG_Backend/DirectVulkan): manage default depth buffer in SwapchainObject 2026-02-27 15:33:01 +08:00
swung0x48 1a75bcba5e [Fix] (MG_Backend/DirectVulkan): prevent operation in assert getting compiled out in release 2026-02-27 15:05:10 +08:00
swung0x48 b64309edfc [Chore] (MG_Backend/DirectVulkan): get rid of junk 2026-02-27 14:14:11 +08:00
swung0x48 e3f1db0a9a [Chore] (MG_Backend/DirectVulkan): use VkTextureManager::TransitionImageLayout more 2026-02-27 13:59:39 +08:00
swung0x48 2c848ab44b [Chore] (MG_Backend/DirectVulkan): move TransitionImageLayout to VkTextureManager 2026-02-27 09:44:23 +08:00
swung0x48 9b23594415 [Fix] (MG_Backend/DirectVulkan): misc fixes 2026-02-25 16:49:58 +08:00
swung0x48 e2e52965df [Feat] (MG_Backend/DirectVulkan): VkClearManager 2026-02-25 16:12:33 +08:00
swung0x48 6e7907f183 [Chore] (MG_Backend/DirectVulkan): get rid of more junk 2026-02-25 12:46:47 +08:00
swung0x48 b4be1292b8 [Feat] (MG_Backend/DirectVulkan): TextureManager mipmap completeness check 2026-02-25 11:04:28 +08:00
swung0x48 db58f4c214 [Feat] (MG_Backend/DirectVulkan): TextureManager supports mipmap 2026-02-25 10:52:54 +08:00
swung0x48 59bad77176 [Chore] (MG_Backend/DirectVulkan): rename functions in VkTextureManager 2026-02-25 09:52:15 +08:00
BZLZHH 3504fca8da Merge branch 'dev' into Perf/Improvement1 2026-02-24 22:48:23 +08:00
BZLZHH e61817ff6a [Fix] (MG_Backend/DirectGLES): Improve iteration safety in CollectGarbage. 2026-02-24 22:47:18 +08:00
BZLZHH b9df28838c Merge pull request #5 from Perf/Improvement1
Merge Perf/improvement1 to dev
2026-02-24 22:09:38 +08:00
BZLZHH fff00e65c4 [Perf] (Texture|State): Replace dynamic_cast hot paths with static_cast. 2026-02-24 15:40:06 +08:00
BZLZHH 8320b4f456 [Feat|Fix] (MG_Backend/DirectGLES): Unify state-backend registries with weak-ref GC. 2026-02-24 15:27:28 +08:00
swung0x48 a757669df5 [Improvement] (MG_Backend/DirectVulkan): split TextureSamplerManager into TextureManager and SamplerManager 2026-02-24 15:19:34 +08:00
swung0x48 e16c0645c0 [Improvement] (MG_Backend/DirectVulkan): use VMA to allocate texture images 2026-02-24 14:21:24 +08:00
swung0x48 8d37763fd3 [Improvement] (MG_Backend/DirectVulkan): use VMA to allocate RT images 2026-02-24 13:09:26 +08:00
swung0x48 e0d0551e7b [Chore] (MG_Test/Backend/DirectVulkan/TestExec): FramebufferManager -> RenderTargetManager 2026-02-24 13:07:50 +08:00
swung0x48 caa814e8f9 [Chore] (MG_Test/Backend/DirectVulkan/TestExec): get rid of now useless default renderpass 2026-02-24 12:25:04 +08:00
swung0x48 2502d32a2e [Chore] (MG_Test/Backend/DirectVulkan/TestExec): get rid of necessary check 2026-02-24 12:10:44 +08:00
swung0x48 e57dd3529e [Chore] (MG_Test/Backend/DirectVulkan/TestExec): get rid of junk 2026-02-24 10:19:21 +08:00
swung0x48 4b8d809237 [Fix] (MG_Test/Backend/DirectVulkan/TestExec): initialize MobileGL first then EGL stuff 2026-02-24 09:26:46 +08:00
swung0x48 d42182befc [Fix] (MG_Backend/DirectVulkan): swap swapchain width/height on 90/270 rotation 2026-02-23 23:12:22 +08:00
swung0x48 5efdb1016e [Fix] (MG_Backend/DirectVulkan): make vk_enum_string_helper.h available on Android NDK 2026-02-23 22:11:30 +08:00
BZLZHH 15e24cda78 [Perf|Improvement] (All): Improve performance & optimize code. 2026-02-23 16:00:38 +08:00
BZLZHH d22d2d64f2 [Feat|Fix] (MG_State/EGLState|MG_Backend|MG_Impl/EGLImpl): Initial implemention of EGL API. 2026-02-22 18:22:21 +08:00
swung0x48 5013108a7f [Chore] (MG_Backend/DirectVulkan): get rid of unnecessary checks 2026-02-22 13:17:22 +08:00
swung0x48 359ba1c572 [Fix] (MG_Backend/DirectVulkan): properly compute hash for samplers 2026-02-22 12:51:00 +08:00
swung0x48 733523011b [Chore] (MG_Backend/DirectVulkan): more hard assertions 2026-02-22 12:31:18 +08:00
swung0x48 14fc13c34d [Chore] (MG_Backend/DirectVulkan): get rid of fallback image/sampler/imageview 2026-02-22 12:18:49 +08:00
swung0x48 e9fee1358d [Chore] (MG_Backend/DirectVulkan): hard assert instead of silently fallback 2026-02-22 12:08:31 +08:00
swung0x48 dae3dd9996 [Chore] (MG_Backend/DirectVulkan): unifying framebuffer manager Transition* functiosn 2026-02-22 11:08:43 +08:00
swung0x48 556db8b02e [Chore] (MG_Backend/DirectVulkan): get rid of redundant guardrails (cont.) 2026-02-22 10:35:10 +08:00
swung0x48 96e993eecf [Chore] (MG_Backend/DirectVulkan): get rid of redundant guardrails 2026-02-22 10:19:44 +08:00
swung0x48 fb3e2123cc [Fix] (MG_Backend/DirectVulkan): dynamically retrieve Vulkan functions in loader, fixing compilation error on lower NDK versions 2026-02-22 10:11:14 +08:00
BZLZHH bd8bc1e251 [Improvement] (MG_ConfigLoader): Destroy map after init. 2026-02-21 22:30:50 +08:00
BZLZHH 22416cf2f0 [Docs] (README): Introduce environment variables. 2026-02-21 22:29:23 +08:00
BZLZHH 8bdf990810 [Fix] (MG_Test|MG_Bench): Fix compilation. 2026-02-21 22:25:59 +08:00
BZLZHH 9e90d9508b [Feat] (Core): Add env config loader and refactor initialization entrypoints. 2026-02-21 22:08:55 +08:00
BZLZHH 7ccf858181 Merge branch 'Feat/Backend-Direct-Vulkan' of github.com:MobileGL-Dev/MobileGL into Feat/Backend-Direct-Vulkan 2026-02-21 20:55:18 +08:00
BZLZHH 3c66016489 [Refactor] (MG_Backend/DirectVulkan): Move renderpass/framebuffer vk management out of VulkanRenderer. 2026-02-21 20:53:33 +08:00
swung0x48 b88042bdff [Fix] (MG_Backend/DirectVulkan): fix typo 2026-02-21 20:34:07 +08:00
swung0x48 6540c2eec1 [Feat] (MG_Backend/DirectVulkan): properly handle Vulkan surface transform (pre-rotation) 2026-02-21 20:32:25 +08:00
BZLZHH d5940f40be Merge branch 'Feat/Backend-Direct-Vulkan' of github.com:MobileGL-Dev/MobileGL into Feat/Backend-Direct-Vulkan 2026-02-21 19:53:02 +08:00
BZLZHH 033ba16aff [Refactor] (MG_Backend/DirectVulkan): Decouple default render pass management from VulkanRenderer. 2026-02-21 19:50:26 +08:00
swung0x48 47467ea1ab [Feat] (MG_Backend/DirectVulkan): descriptor set auto re-allocate 2026-02-21 19:01:33 +08:00
BZLZHH d84b4da766 [Feat|Fix] (MG_Backend/DirectVulkan): Impl (Multi)DrawElementsBaseVertex. Fix Blitframebuffer. 2026-02-21 17:37:50 +08:00
BZLZHH 07b7f7eba5 [Feat] (MG_Backend/DirectVulkan): Add optional device extension. Impl MultiDrawElements. 2026-02-21 16:16:07 +08:00
BZLZHH 7f9953fdee [Fix] (MG_Backend/DirectVulkan): Handle shader position transform. 2026-02-21 15:36:28 +08:00
BZLZHH ccd51bf2d3 Merge branch 'dev' into Feat/Backend-Direct-Vulkan 2026-02-21 15:02:59 +08:00
BZLZHH 60f06d1b8d [Improvement] (MG_Backend): Separate Initialize and InitCapabilities. 2026-02-20 15:26:46 +08:00
BZLZHH e34f3d915c [Fix] (MG_Impl/EGLImpl): Fix GetProcAddress. 2026-02-18 22:31:27 +08:00
BZLZHH f65c71da27 [Fix] (MG_Util): Fix typo. 2026-02-18 11:10:49 +08:00
BZLZHH 5fbed32ef6 [Fix] (MG_Util): Fix compilation. 2026-02-18 11:02:36 +08:00
BZLZHH 8413874e82 [Feat|Refactor] (MG_Backend|MG_Impl): Implement BackendObject, replacing previous methods. 2026-02-18 10:36:56 +08:00
BZLZHH fe89dc82dc [Chore] (clang-tidy): Update .clang-tidy 2026-02-18 10:35:29 +08:00
BZLZHH 5938a18131 [Chore] (Scripts): Upgrade clang-format 2026-02-18 10:35:04 +08:00
swung0x48 f79b7a91d7 [Feat] (MG_Backend/DirectVulkan): alpha state 2026-02-18 09:49:58 +08:00
swung0x48 ea71b3d96f [Feat] (MG_Backend/DirectVulkan): depth state 2026-02-18 09:43:45 +08:00
swung0x48 f96f4a0a3b [Fix] (MG_Backend/DirectVulkan): fix vertex buffer corruption 2026-02-18 09:29:17 +08:00
swung0x48 9f062fbd69 [Fix] (MG_Backend/DirectVulkan): use MGLOG_D instead of MGLOG_W 2026-02-18 08:53:35 +08:00
swung0x48 56428df5e5 [Fix] (Includes.h): preprocessor hack to get rid of annoying gl.h 2026-02-18 08:17:23 +08:00
swung0x48 25a5fe0757 [Feat] (MG_Test/Backend/DirectVulkan): test vao vbo ibo? 2026-02-18 07:49:29 +08:00
swung0x48 2104d9865d [Feat] (MG_Backend/DirectVulkan): add more datatype support to vertex input 2026-02-18 00:12:54 +08:00
swung0x48 dcb8bb1871 [Chore] (MG_Backend/DirectVulkan): simplifying draw payload 2026-02-18 00:12:06 +08:00
swung0x48 6b656d3f96 [Feat] (MG_Backend/DirectVulkan): get global UBO binding 2026-02-17 23:25:25 +08:00
swung0x48 c2a0db3d12 [Feat] (MG_Backend/DirectVulkan): initial real implementation of VkTextureSamplerManager 2026-02-17 23:03:26 +08:00
swung0x48 c810b27a83 [Feat] (MG_Backend/DirectVulkan): initial implementation of VkTextureSamplerManager, only fallback path available now 2026-02-17 22:31:56 +08:00
swung0x48 25f6c67859 [Fix] (MG_Backend/DirectVulkan): deferred buffer release to frame end 2026-02-17 22:13:57 +08:00
swung0x48 5f78ff2b51 [Fix] (MG_Backend/DirectVulkan): set swapchain image layout at present 2026-02-17 22:05:09 +08:00
swung0x48 9226ea092c [Feat] (MG_Backend/DirectVulkan): add more VkCompositeAlphaFlagBitsKHR candidates 2026-02-17 22:03:36 +08:00
swung0x48 12d514229c [Fix] (MG_Backend/DirectVulkan): add move ctor for BackendProgramObject 2026-02-17 21:57:29 +08:00
swung0x48 b69b6b2987 [Chore] (MG_Backend/DirectVulkan): unifying TransitionImageLayout 2026-02-17 21:37:05 +08:00
swung0x48 377b967996 [Feat] (MG_Backend/DirectVulkan): per-fbo pending clear state 2026-02-17 20:36:49 +08:00
swung0x48 e132e9edc1 [Feat] (MG_Backend/DirectVulkan): inital FBO implementation, and blit framebuffer 2026-02-17 19:39:10 +08:00
swung0x48 49a18f68e1 [Fix] (MG_Backend/DirectVulkan): fixing inter-frame swapchain sync? 2026-02-17 17:43:28 +08:00
swung0x48 fe6e7902d3 [Feat] (MG_Backend/DirectVulkan): implements uniform, ubo 2026-02-17 17:16:08 +08:00
BZLZHH c4e40c2eb2 [Chore] (format): Update .clang-format 2026-02-17 17:11:52 +08:00
swung0x48 f7ea6cd1d9 [Feat] (MG_Backend/DirectVulkan): dynamically load vulkan functions for vma 2026-02-17 12:47:01 +08:00
swung0x48 cf229c4a5b [Feat] (MG_Backend/DirectVulkan): implement implement multiple vbo in vao binding 2026-02-17 11:45:17 +08:00
swung0x48 058ec6d26e [Feat] (MG_Backend/DirectVulkan): implement vao/vbo binding 2026-02-17 11:33:27 +08:00
swung0x48 098f8d0738 [Feat] (MG_Backend/DirectVulkan): move demo pipeline creation to gl side 2026-02-17 11:17:03 +08:00
swung0x48 5f6a0b5969 [Feat] (MG_Backend/DirectVulkan): Pipeline factory 2026-02-17 10:57:39 +08:00
swung0x48 49b0743422 [Feat] (MG_Backend/DirectVulkan): refactor DrawElements to use payload as param 2026-02-17 10:42:30 +08:00
swung0x48 13aa88b5ef [Feat] (MG_Backend/DirectVulkan): hook up vertex input state 2026-02-17 10:37:49 +08:00
swung0x48 e055b9a644 [Fix] (MG_Backend/DirectVulkan): wrong early return 2026-02-17 10:29:28 +08:00
swung0x48 324498ccac [Feat] (MG_Backend/DirectVulkan): vertex input state factory 2026-02-17 10:24:01 +08:00
swung0x48 206d8ab36a [Feat] (MG_Backend/DirectVulkan): vertex input state builder 2026-02-17 10:11:24 +08:00
swung0x48 53989d1711 [Feat] (submodule): add vma 2026-02-17 09:49:05 +08:00
swung0x48 7b7e00dbb3 [Feat] (MG_Test/Backend/DirectVulkan): test glDrawElements 2026-02-17 09:48:36 +08:00
swung0x48 7d4ebfc305 [Feat] (MG_Backend/DirectVulkan): implement simple DrawElements path to put buffer to the test 2026-02-17 09:47:13 +08:00
swung0x48 dfe91e96a5 [Feat] (MG_Backend/DirectVulkan): integrate vma, implement VkBufferObject 2026-02-17 09:46:29 +08:00
swung0x48 4d61f11bb8 [Feat] (submodule): add VulkanMemoryAllocator 2026-02-17 09:04:00 +08:00
swung0x48 5412d1c165 [Feat] (GL_State/RenderState): implement glDrawArrays (command only) 2026-02-17 08:50:34 +08:00
swung0x48 3ce7a2fd46 [Feat] (GL_State/RenderState): implement ClearStencil 2026-02-17 08:19:22 +08:00
swung0x48 f8f3d6e657 [Feat] (GL_State/RenderState): implement ClearStencil 2026-02-17 08:17:26 +08:00
swung0x48 781bda2573 [Chore] (git): include stuff in gitignore 2026-02-17 07:59:26 +08:00
swung0x48 d06720f534 [Feat] (MG_Backend/DirectVulkan): half-assed glClear implementation 2026-02-17 01:48:32 +08:00
swung0x48 a3b440e7c5 [Feat] (MG_Backend/DirectVulkan): FrameContext: command buffer lifecycle 2026-02-17 00:59:51 +08:00
swung0x48 ebdadcecff [Feat] (MG_Backend/DirectVulkan): implement some FrameContext lifecycle function 2026-02-17 00:40:04 +08:00
swung0x48 876d5e13af [Chore] (MG_Backend/DirectVulkan): simplify FrameContext interface 2026-02-17 00:08:48 +08:00
swung0x48 2ad1207a31 [Feat] (MG_Backend/DirectVulkan): ProgramFactory and some refactoring 2026-02-16 22:29:04 +08:00
BZLZHH 8bd6c9719f Merge branch 'Feat/Backend-Direct-GLES' into dev 2026-02-16 18:32:52 +08:00
swung0x48 91326025f3 [Fix] (MG_Backend/DirectVulkan): guard against missing header 2026-02-16 13:08:35 +08:00
swung0x48 3324dbfbf6 [Fix] (workflow): setup vulkan sdk 2026-02-16 12:28:37 +08:00
swung0x48 e1b59bcb46 [Chore] (MG_Backend/DirectVulkan): improve some wording 2026-02-16 12:10:51 +08:00
swung0x48 8f57e837b8 [Chore] (MG_Test/Backend/DirectVulkan): encapsulate FrameContext (cont.) 2026-02-16 12:04:55 +08:00
swung0x48 6b7de70bf3 [Fix] (MG_Test/Backend/DirectVulkan): encapsulate FrameContext 2026-02-16 11:06:04 +08:00
swung0x48 0ac4d8658d [Fix] (MG_Test/Backend/DirectVulkan): more swapchain logic encapsulated, fix compilation 2026-02-16 10:47:42 +08:00
swung0x48 1a4fde893f [Chore] (MG_Test/Backend/DirectVulkan): get rid of some junk 2026-02-16 10:24:53 +08:00
swung0x48 e01ebc8fc7 [Chore] (MG_Test/Backend/DirectVulkan): encapsulate SwapchainObject 2026-02-16 09:59:56 +08:00
swung0x48 533e6bd57c [Feat] (MG_Test/Backend/DirectVulkan): gracefully handle minimize 2026-02-15 23:23:36 +08:00
swung0x48 ad822e1095 [Feat] (MG_Test/Backend/DirectVulkan): fixing Present when there's no work to queue/present 2026-02-15 22:01:01 +08:00
swung0x48 129091a430 [Feat] (MG_Test/Backend/DirectVulkan): move Render() outside of eglSwapBuffers 2026-02-15 21:36:26 +08:00
BZLZHH 1a91e48219 [Improvement] (MG_Backend/DirectVulkan): Do not crash when validation layers are unavailable. 2026-02-15 20:20:16 +08:00
swung0x48 4bcedc84b9 [Feat] (MG_Test/Backend/DirectVulkan): properly handle out-of-date/suboptimal swapchain 2026-02-15 19:56:14 +08:00
swung0x48 1357435e94 [Feat] (MG_Test/Backend/DirectVulkan): RecreateSwapchain() 2026-02-15 19:34:25 +08:00
swung0x48 7c67c99717 [Fix] (MG_Test/Backend/DirectVulkan): make macOS build compile 2026-02-15 08:52:22 +08:00
swung0x48 a58016f49d [Fix] (MG_Test/Backend/DirectVulkan): add missing define 2026-02-15 08:51:28 +08:00
swung0x48 8a66b0a542 [Feat] (MG_Test/Backend/DirectVulkan): add support on macOS 2026-02-15 08:50:53 +08:00
swung0x48 92cdcd952b [Feat] (MG_Test/Backend/DirectVulkan): move Render() outside of Present() 2026-02-14 23:31:10 +08:00
swung0x48 d7156631d1 [Feat] (MG_Test/Backend/DirectVulkan): seperate Present and Draw logic 2026-02-14 23:30:41 +08:00
swung0x48 81125dd06d [Feat] (MG_Test/Backend/DirectVulkan): use per-frame resources 2026-02-14 21:16:27 +08:00
swung0x48 7bd4d74b2c [Feat] (MG_Backend/DirectVulkan): present, dynamic states, queue submit, and...triangle! 2026-02-14 17:47:14 +08:00
swung0x48 b25562711a [Feat] (MG_Backend/DirectVulkan): sync objects, command buffer, render pass, present (WIP) 2026-02-14 17:22:31 +08:00
swung0x48 927d95fb41 [Fix] (MG_Backend/DirectVulkan): swapchain stuff cleanup, ready to record command 2026-02-14 14:39:54 +08:00
swung0x48 843fdcb47a [Fix] (MG_Backend/DirectVulkan): PrepareDemoRes() (only as placeholder) 2026-02-14 13:28:53 +08:00
swung0x48 ad6ffbe42e [Fix] (MG_Backend/DirectVulkan): create framebuffer and renderpass 2026-02-14 12:34:45 +08:00
swung0x48 5f94f72be5 [Fix] (MG_Backend/DirectVulkan): create command pool and command buffer 2026-02-14 10:21:25 +08:00
swung0x48 0ce95894a3 [Fix] (MG_Backend/DirectVulkan): fix present mode pick logic 2026-02-14 09:27:45 +08:00
swung0x48 beb9301282 [Feat] (MG_Backend/DirectVulkan): get rid of stuff that no longer needed 2026-02-13 15:24:18 +08:00
swung0x48 0822cb871d [Feat] (MG_Test/Backend/DirectVulkan): swapchain image view 2026-02-12 21:37:33 +08:00
swung0x48 bfea5dc8ba [Feat] (MG_Backend/DirectVulkan): get swapchain images 2026-02-12 19:03:46 +08:00
swung0x48 9fb5a38172 [Feat] (MG_Backend/DirectVulkan): create swapchain 2026-02-12 13:50:06 +08:00
swung0x48 74ff24e4a4 [Feat] (MG_Backend/DirectVulkan): more friendly device picker log 2026-02-12 12:55:18 +08:00
swung0x48 178dbd33ba [Feat] (MG_Backend/DirectVulkan): inspect ChooseSwapchainSurfaceFormat, ChooseSwapchainPresentMode 2026-02-12 12:27:13 +08:00
swung0x48 f5e59b1c84 [Feat] (MG_Backend/DirectVulkan): inspect SwapchainCapabilities 2026-02-12 11:43:34 +08:00
swung0x48 ba7bf87ee0 [Feat] (MG_Backend/DirectVulkan): retrieve and check device extension 2026-02-12 11:08:57 +08:00
swung0x48 99bc2e121b [Feat] (MG_Test/Backend/DirectVulkan): pick and compare physical device 2026-02-12 00:07:52 +08:00
swung0x48 341749706d [Feat] (MG_Test/Backend/DirectVulkan): graphics queue and present queue 2026-02-11 23:20:31 +08:00
swung0x48 a25bfcb0d0 [Fix] (MG_Test/Backend/DirectVulkan): prevents double init 2026-02-11 22:54:07 +08:00
swung0x48 b2ea29b91d [Chore] (MG_Test/Backend/DirectVulkan): create surface first, then logical device 2026-02-11 22:53:50 +08:00
swung0x48 a28f5eeee6 [Feat] (MG_Backend/DirectVulkan): refactor queue family stuff 2026-02-11 18:04:24 +08:00
swung0x48 2febb10319 [Feat] (MG_Backend/DirectVulkan): Create vkSurfaceKHR 2026-02-11 17:20:39 +08:00
swung0x48 ae3a27bf06 [Feat] (MG_Backend/DirectVulkan): Create logical device 2026-02-11 15:32:56 +08:00
swung0x48 5a751a6745 [Feat] (MG_Backend/DirectVulkan): pick vkPhysicalDevice 2026-02-11 14:35:37 +08:00
swung0x48 0a7061f375 [Feat] (MG_Backend/DirectVulkan): redo the whole thing, bringing up Vulkan instance 2026-02-11 13:54:40 +08:00
swung0x48 c7db89a200 [Chore] (MG_Backend/DirectVulkan): fix up variable and type naming scheme 2026-02-11 09:15:48 +08:00
swung0x48 a6784e7714 [Feat] (MG_Test/Backend/DirectVulkan): fix wrong preprocessor directive 2026-02-10 23:39:24 +08:00
swung0x48 a9b92a756b [Chore] (MG_Test/Backend/DirectVulkan): use warning instead of error 2026-02-10 23:38:40 +08:00
swung0x48 52eb6b3f2a [Feat] (MG_Test/Backend/DirectVulkan): add a simple test environment 2026-02-10 23:14:20 +08:00
swung0x48 43e59d8fce [Fix] (MG_Backend/DirectVulkan): fix validation error on Windows 2026-02-10 14:16:23 +08:00
swung0x48 ceaa6ff5f8 [Fix] (MG_Backend/DirectVulkan): silence some validation error on Windows 2026-02-10 13:39:51 +08:00
swung0x48 a77088eeb3 [Feat] (MG_Backend/DirectVulkan): use VK_USE_PLATFORM_*_KHR macro instead 2026-02-10 13:32:20 +08:00
swung0x48 162dbf8750 [Feat] (MG_Backend/DirectVulkan): hooking up Windows VK WSI 2026-02-10 13:28:05 +08:00
swung0x48 1c2924eef9 [Feat] (MG_Test/Backend/DirectVulkan): some sanity tests 2026-02-10 13:24:24 +08:00
swung0x48 acc826ee9f [Fix] (MG_Impl/EGLImpl/EGLForVulkan): fix wrong egl function signatures 2026-02-10 11:21:16 +08:00
swung0x48 8e58875b8f [Feat] (MG_Backend/DirectVulkan): use rgba instead of xyzw 2026-02-09 22:34:44 +08:00
swung0x48 51451e8de3 [Feat] (MG_Backend/DirectVulkan): make helper functions static 2026-02-09 22:23:53 +08:00
swung0x48 b806397ae3 [Feat] (MG_Backend/DirectVulkan/RenderStateManager): impelement RenderStateManager 2026-02-09 22:16:22 +08:00
swung0x48 358efe4d1b [Feat] (MG_Backend/DirectVulkan/VertexInputStateManager): impelement VertexInputStateManager 2026-02-09 21:31:27 +08:00
swung0x48 cd3ff1f881 [Feat] (MG_Backend/DirectVulkan/ProgramManager): impelement CreatePipelineShaderStages/GetPipelineShaderStages 2026-02-09 21:02:27 +08:00
swung0x48 6c10876532 [Fix] (MG_Backend/DirectVulkan): fix file header 2026-02-09 20:51:36 +08:00
swung0x48 ce8a2356d7 [Fix] (MG_Test/Program): fix hardcoded stage-index relationship 2026-02-09 20:30:22 +08:00
BZLZHH 37f26d1bb1 [Misc] (gitignore): Ignore /build_* 2026-02-09 18:22:20 +08:00
swung0x48 22bc4fbbc9 [Feat] (MG_Backend/DirectVulkan): ProgramManager - hash program object 2026-02-09 16:18:50 +08:00
swung0x48 18941f9e83 [Feat] (MobileGL/Config): add CacheVersion 2026-02-09 14:43:29 +08:00
swung0x48 0b332bdc58 [Chore] (3rdparty): add xxHash 2026-02-09 13:55:05 +08:00
BZLZHH 2abdebcd96 [Fix] (MG_Backend/DirectVulkan): Acquire next frame image only at the start of frame. 2026-02-08 18:56:25 +08:00
BZLZHH e39af3b940 [Fix|Refactor] (MG_Backend/DirectVulkan): Fix incorrect vkAcquireNextImageKHR call. MOBILEGL_ASSERT_VK -> VK_VERIFY. 2026-02-08 16:28:12 +08:00
BZLZHH 3b2c2028b9 [Feat] (MG_Backend/DirectVulkan): Present frame in eglSwapBuffers. 2026-02-08 14:58:42 +08:00
BZLZHH 55020a1e86 [Improvement] (MG_Backend/DirectVulkan): Unify error handling. 2026-02-08 14:48:04 +08:00
swung0x48 6d4ddc47f6 [Fix] (MG_Backend/DirectVulkan): request Vulkan 1.1 (to make renderdoc happy) 2026-02-08 13:47:27 +08:00
swung0x48 2aff5dc650 [Fix] (MG_Impl/EGL/EGLForVulkan): use GL semantics for demo shader 2026-02-08 13:31:51 +08:00
swung0x48 7aa7b82628 [Fix] (buildsystem): fix build on Android 2026-02-08 11:51:14 +08:00
swung0x48 fd530156a6 [Fix] (buildsystem): fix build on Windows 2026-02-08 10:00:08 +08:00
BZLZHH 56c98041e3 [Misc] (MG_Backend/DirectVulkan): Prioritize MAILBOX/IMMEDIATE present modes. 2026-02-08 01:09:12 +08:00
swung0x48 b90df42a45 [Feat] (MG_Util/Texture, MG_Backend/DirectGLES): implementing BGRA texture readback (WIP) 2026-02-07 23:10:43 +08:00
swung0x48 40333fa84a [Remove] (workflow): remove combined workflow 2026-02-07 20:06:43 +08:00
swung0x48 a079e5e6b9 [Debug] (workflow): checking inter-job artifact exchange 2026-02-07 19:15:45 +08:00
swung0x48 f6f84267b6 [Feat] (workflow): merge two workflows 2026-02-07 18:50:18 +08:00
BZLZHH 6eeb67f08b Merge branch 'dev' into Feat/Backend-Direct-Vulkan 2026-02-07 12:32:16 +08:00
BZLZHH 155aaa0d4b [Docs] (README): Improve accuracy. 2026-02-07 12:32:03 +08:00
BZLZHH 9a6cf7fc7f Merge branch 'dev' into Feat/Backend-Direct-Vulkan 2026-02-07 11:41:11 +08:00
BZLZHH aaeb2711ff Merge branch 'Feat/Backend-Direct-GLES' into dev 2026-02-07 11:25:28 +08:00
BZLZHH d4d0407a1c [Fix] (MG_Backend/DirectGLES): Fix GetTexImage. 2026-02-06 21:42:07 +08:00
BZLZHH eb3621cb3c Revert "[Misc] (MG_Backend/DirectGLES): Handle GL_BGRA as GL_RGBA in ReadPixels and GetTexImage."
This reverts commit 2ad7e2da40.
2026-02-06 20:48:01 +08:00
BZLZHH 2ad7e2da40 [Misc] (MG_Backend/DirectGLES): Handle GL_BGRA as GL_RGBA in ReadPixels and GetTexImage. 2026-02-06 20:21:10 +08:00
BZLZHH a7d8e90600 [Feat] (MG_Backend/DirectGLES|MG_Impl): Initial implementions of GetTexImage and ReadPixels. 2026-02-06 20:14:18 +08:00
BZLZHH e8f385820a Merge branch 'Feat/Backend-Direct-GLES' into dev 2026-02-06 01:11:55 +08:00
BZLZHH 07927dc4a3 [Feat] (MG_Backend/DirectGLES): Sync indexed blend states. 2026-02-06 01:05:18 +08:00
BZLZHH 91eb75a95d [Feat] (MG_Impl/RenderState): Implement Enablei, Disablei, BlendFuncSeparatei, IsEnabled, IsEnabledi. 2026-02-06 01:03:51 +08:00
BZLZHH a109675f1f [Feat] (MG_State/RenderState): Support indexed blend states. 2026-02-06 00:41:30 +08:00
BZLZHH 78f42b5cd0 Merge branch 'Feat/Backend-Direct-GLES' into dev 2026-02-05 22:00:49 +08:00
BZLZHH 68bdea41d2 [Fix] (*/Texture*): Correctly handle the format in CopyTexImage2D. 2026-02-05 21:50:14 +08:00
BZLZHH 00eb158196 [Feat] (MG_Util/Converters): Add ConvertInternalFormatToUnsized. 2026-02-05 18:06:26 +08:00
BZLZHH 3b27533793 [Fix] (MG_Backend/DirectGLES): Bind current texture in CopyTexImage2D. 2026-02-05 16:50:56 +08:00
swung0x48 93f08e251d [Fix] (MG_Util/ShaderTranspiler): forcefully disable validator of spvtools 2026-02-05 15:59:14 +08:00
BZLZHH cd3936666d [Fix] (MG_Backend/DirectGLES): Bind current read FBO in CopyTexImage2D. 2026-02-05 15:27:55 +08:00
BZLZHH 41c8850846 [Feat] (MG_Backend/DirectGLES): Try to handle CopyTex*Image2D for depth textures. 2026-02-05 15:16:10 +08:00
BZLZHH 8fe266e027 [Fix] (MG_Test/BufferObject): Migrate to the new API for dirty ranges. 2026-02-05 14:00:23 +08:00
BZLZHH 9af964de67 [Fix] (MG_Backend/DirectGLES): Remove the use of glVertexAttribFormat. 2026-02-05 13:30:30 +08:00
BZLZHH 9f4c9b61a0 [Fix] (MG_Backend/DirectGLES): Correctly sync attrib.Divisor when attrib.Buffer changes. 2026-02-05 12:54:22 +08:00
swung0x48 8e962345e4 [Fix] (MG_Backend/DirectGLES): remove depth tex copy codepath, fixing FBO state leak 2026-02-05 12:22:11 +08:00
swung0x48 5319367869 [Feat] (MG_Backend/DirectGLES): assertion to check FBO cache integrity 2026-02-05 12:21:32 +08:00
swung0x48 e351ef9f41 [Fix] (MG_Impl/Texture): mark dirty only when pixel transfer happens 2026-02-05 12:20:42 +08:00
swung0x48 4bfa8ce934 [Fix] (MG_State/Framebuffer): properly bump FBO version 2026-02-05 12:20:06 +08:00
swung0x48 6855ae42ef [Feat] (MG_Backend/DirectGLES): add assertion checks against FBO cache 2026-02-05 10:34:24 +08:00
BZLZHH 7fd9eb15d3 Merge remote-tracking branch 'refs/remotes/origin/Feat/Backend-Direct-GLES' into Feat/Backend-Direct-GLES 2026-02-05 02:48:58 +08:00
BZLZHH 319806c48a [Chore] (CMake): Support using check_c*_compiler_flag to detect LTO capability. 2026-02-05 00:55:42 +08:00
swung0x48 de8342a96b Revert "[Optimize] (MG_Backend/DirectGLES): Texture object mipmap dirty bit"
This reverts commit 8f551794
2026-02-04 22:56:28 +08:00
swung0x48 6577e1bcc1 [Feat] (MG_Util/Converters): add depth formats to ConvertInternalFormatToSized 2026-02-04 22:01:44 +08:00
BZLZHH 07638b8577 [Fix] (MG_Backend/DirectGLES): Fix incorrect active texture unit when binding not dirty. 2026-02-04 17:51:56 +08:00
swung0x48 d13a19126b [Fix] (MG_Backend/DirectGLES): properly handle default fbo's attachment? 2026-02-04 16:20:51 +08:00
swung0x48 dfaa2c259b [Fix] (MG_State/Framebuffer): bump attachmentVersions on SetDrawBuffer 2026-02-04 16:19:57 +08:00
swung0x48 cb27ebc576 [Feat] (MG_Util/Converters): add symbolic constants for default FBO into ConvertFramebufferAttachmentTypeToGLEnum 2026-02-04 15:51:16 +08:00
swung0x48 fd5cc2e5c1 [Feat] (MG_Util/Converters): add symbolic constants for default FBO into ConvertGLEnumToFramebufferAttachmentType 2026-02-04 15:34:41 +08:00
swung0x48 5bfb55cfd8 [Fix] (MG_Backend/DirectGLES): re-implement glClearBuffer* 2026-02-04 14:44:41 +08:00
swung0x48 1b47f1bb92 [Fix] (MG_Backend/DirectGLES): re-implement FBO sync, attachment remapping 2026-02-04 14:42:48 +08:00
swung0x48 f4ce17af51 [Perf] (MG_Backend/DirectGLES): skip redundant attachment object sync 2026-02-04 10:42:23 +08:00
swung0x48 2088009c01 [Fix] (MG_Backend/DirectGLES): direct draw buffer mapping, fix up simple case 2026-02-04 10:27:01 +08:00
swung0x48 77378bbf07 [Fix] (MG_Backend/DirectGLES): fix renaming error in BackendFramebufferObject::SyncToBackend 2026-02-03 23:43:55 +08:00
BZLZHH 74509ae0a3 [Perf] (MG_Backend/DirectGLES): No need to use shared_ptr for g_boundVertexBufferObject. 2026-02-03 21:07:14 +08:00
BZLZHH f0ab82ea2a [Fix] (MG_Backend/DirectGLES): Fix VBO binding state leakage. 2026-02-03 21:02:54 +08:00
BZLZHH d251bd3a91 Merge remote-tracking branch 'origin/dev' into Feat/Backend-Direct-GLES 2026-02-03 20:35:06 +08:00
BZLZHH 850d363cac [Chore] (Config): Bump version to 26.02 2026-02-03 20:22:23 +08:00
BZLZHH 5addbb3bdd [Perf] (MG_Backend/DirectGLES): Add RenderState sync cache. 2026-02-03 18:42:05 +08:00
BZLZHH 8e3bbda2f2 [Fix] (MG_State/RenderState): Versioning for SetColorMask. 2026-02-03 18:24:26 +08:00
BZLZHH eb4a81b55f Merge remote-tracking branch 'refs/remotes/origin/Feat/Backend-Direct-GLES' into Feat/Backend-Direct-GLES 2026-02-03 17:51:19 +08:00
BZLZHH ea098c0409 [Feat|Refactor] (MG_State/RenderState): Versioning for RenderStateParameters. 2026-02-03 17:50:46 +08:00
swung0x48 bf0bae0e59 Merge branch 'Feat/Backend-Direct-GLES' of https://github.com/MobileGL-Dev/MobileGL into Feat/Backend-Direct-GLES 2026-02-03 17:50:34 +08:00
swung0x48 41f6670a10 [Perf] (MG_Backend/DirectGLES): less shared_ptr deref 2026-02-03 17:50:20 +08:00
swung0x48 c2ffa93c90 [Perf] (MG_Backend/DirectGLES): use version to skip unnecessary FBO sync in BindCurrentFBO 2026-02-03 17:49:47 +08:00
BZLZHH fc9653f460 Merge remote-tracking branch 'refs/remotes/origin/Feat/Backend-Direct-GLES' into Feat/Backend-Direct-GLES 2026-02-03 17:30:47 +08:00
BZLZHH afa89772e7 [Refactor] (MG_State/RenderState): Separate RenderStateParameters from RenderState. 2026-02-03 17:29:55 +08:00
swung0x48 ca23fe4d6f [Perf] (MG_Backend/DirectGLES): use version to skip unnecessary FBO sync 2026-02-03 17:29:10 +08:00
swung0x48 522d5ad9f7 Merge branch 'Feat/Backend-Direct-GLES' of https://github.com/MobileGL-Dev/MobileGL into Feat/Backend-Direct-GLES 2026-02-03 16:58:38 +08:00
swung0x48 202922613b [Refactor] (MG_State/Framebuffer, MG_Backend/DirectGLES): Versioned framebuffer sync 2026-02-03 16:50:20 +08:00
BZLZHH 4db0fe58c0 Merge remote-tracking branch 'origin/Feat/Backend-Direct-GLES' into Feat/Backend-Direct-GLES 2026-02-03 16:44:21 +08:00
BZLZHH 5eff8b2e30 [Perf] (MG_Backend/DirectGLES): Add cache for Texture and Sampler binding. 2026-02-03 16:44:00 +08:00
BZLZHH b966ef8b5e [Chore] (CMake): DO not link static lib for Android. 2026-02-03 16:36:40 +08:00
swung0x48 751c5745b0 [Fix] (MG_Util/Converters): properly handle GL_NONE in ConvertGLEnumToFramebufferAttachmentType 2026-02-03 13:06:55 +08:00
swung0x48 6823b1e46a [Feat] (MG_Impl/Framebuffer): implement glReadBuffer 2026-02-03 12:59:11 +08:00
BZLZHH 207b746273 [Perf] (MG_Backend/DirectGLES): Avoid redunant VBO binding. 2026-02-03 11:41:23 +08:00
swung0x48 edff307782 [Chore] (MG_Impl/Framebuffer, MG_Impl/RenderState): move ReadBuffer to the right place 2026-02-03 10:23:20 +08:00
BZLZHH 1143c961b6 [Perf] (MG_Backend/DirectGLES): Use glVertexAttribFormat to avoid redunant buffer binding. 2026-02-03 02:52:34 +08:00
BZLZHH 2fab6c5b0b [Fix] (MG_Backend/DirectGLES): Always bind VBO before glVertexAttribPointer. 2026-02-03 02:38:50 +08:00
BZLZHH 42ad1634bf [Perf] (MG_State|MG_Util): Do not bump resource version when nothing changes. 2026-02-03 02:17:09 +08:00
BZLZHH 8e897d54a2 [Perf] (MG_Backend/DirectGLES): Skip IBO binding for VA when not dirty. 2026-02-03 01:52:24 +08:00
BZLZHH 863aa77ff0 [Feat] (MG_Util): Versioning for BindingSlot. 2026-02-03 01:49:46 +08:00
BZLZHH 5e3cb98934 [Perf] (MG_Backend/DirectGLES): Use SwitchDirty in VA. 2026-02-03 01:37:27 +08:00
BZLZHH c301591dcc [Feat] (MG_State/VertexArrayState): Add SwitchVersion for VA. 2026-02-03 01:33:50 +08:00
BZLZHH 5c63515259 [Feat|Perf|Fix] (MG_Backend/DirectGLES): Skip redundant sync for VA when not dirty. 2026-02-03 01:29:30 +08:00
BZLZHH 0ae1b76262 [Feat] (MG_State/VertexArrayState): Replace dirty mark with resource version for VA. 2026-02-03 01:27:58 +08:00
BZLZHH 99d32439a8 [Perf] (MG_Backend/DirectGLES): Remove binding state protectors. 2026-02-03 00:42:24 +08:00
BZLZHH 4225cc4333 [Feat|Perf] (MG_Backend/DirectGLES): Skip whole texture params sync when not dirty. 2026-02-03 00:17:02 +08:00
BZLZHH 7daa69cf73 [Feat] (MG_State/TextureState): Add resource version for texture params. 2026-02-03 00:15:50 +08:00
BZLZHH 653ca9ea74 [Feat|Perf] (MG_Backend/DirectGLES): Skip whole sampler object when not dirty. 2026-02-03 00:08:25 +08:00
BZLZHH 3f0744a8ce [Chore] (CMake): Use ThinLTO with priority if possible. 2026-02-02 22:57:29 +08:00
BZLZHH 7f1cb14d33 [Feat] (MG_State/SamplerState): Add resource version. 2026-02-02 22:01:48 +08:00
BZLZHH de17fdf5b0 [Misc] (MG_Backend/DirectGLES): Separate BackendTextureObject::SyncToBackend 2026-02-02 20:35:03 +08:00
BZLZHH 39a8e72ee9 [Perf] (MG_Backend/DirectGLES): Directly sync texture objects instead of collecting first. 2026-02-02 18:28:17 +08:00
swung0x48 8f55179493 [Optimize] (MG_Backend/DirectGLES): Texture object mipmap dirty bit 2026-02-02 15:37:55 +08:00
swung0x48 cb2ce8f2a5 [Optimize] (MG_Backend/DirectGLES): sync buffer object directly 2026-02-02 12:58:50 +08:00
swung0x48 33a4afba5e [Optimize] (MG_Backend/DirectGLES): get rid of dedup logic in buffer sync 2026-02-02 11:17:16 +08:00
BZLZHH 3d420f6d12 Merge branch 'dev' into Feat/Backend-Direct-GLES 2026-02-02 02:29:47 +08:00
BZLZHH 1e58be34da Merge remote-tracking branch 'origin/Feat/Backend-Direct-GLES' into Feat/Backend-Direct-GLES 2026-02-02 02:28:56 +08:00
BZLZHH 0cf9d9223d [Feat|Perf] (*/BufferState): Improve dirty mark for Buffer. 2026-02-02 02:25:41 +08:00
BZLZHH 938b92277f [Fix] (MG_State/ProgramState): Correct compiling flags in ShaderObject::Compile 2026-02-01 09:23:25 +08:00
BZLZHH 419ffb3b5e [Fix] (MG_Backend/DirectVulkan): Use VK_KHR_ANDROID_SURFACE only on Android. 2026-02-01 00:17:03 +08:00
BZLZHH ad7d145ece [Fix] (MG_Backend/DirectVulkan): Avoid directly using ANativeWindow in abstracted layers. 2026-02-01 00:05:50 +08:00
BZLZHH 516566321d [Fix] (MG_Backend/DirectVulkan): Fix compiling error on linux. 2026-01-31 23:06:58 +08:00
BZLZHH 7918300848 [Chore] (...): Run scripts. 2026-01-31 22:58:22 +08:00
BZLZHH 00679642d6 [Feat] (MG_Backend/DirectVulkan): Basic Vulkan renderer and EGL impl for Vulkan. 2026-01-31 22:51:24 +08:00
BZLZHH 4769a9cf7b [Chore] (MG_Config): Use DirectVulkan backend. 2026-01-31 16:49:37 +08:00
BZLZHH 9f9e955b92 [Chore] (CI): Run workflows for Feat/Backend-Direct-Vulkan 2026-01-31 16:45:39 +08:00
BZLZHH 85f7c8f4a6 [Feat] (MG_Backend/DirectVulkan): Add DirectVulkan backend. 2026-01-31 16:44:08 +08:00
BZLZHH f0ccd40a6b [Docs] (README): Update status & improve descriptions. 2026-01-31 16:15:46 +08:00
BZLZHH 2f39c43270 [Docs] (README): Update status. 2026-01-31 15:41:52 +08:00
swung0x48 acda4c24aa [Fix]: fix typo 2026-01-31 13:10:45 +08:00
BZLZHH 1021a7f741 Merge branch 'Feat/Backend-Direct-GLES' into dev 2026-01-31 12:52:56 +08:00
BZLZHH 91650e29c5 [Misc] (...): Fix typo. 2026-01-31 12:50:52 +08:00
swung0x48 a09d6fa8ff [Fix]: fix typo 2026-01-31 12:50:21 +08:00
swung0x48 9d6a6548e8 [Fix] (MG_Impl/Buffer): wrong range set in BindBufferBase_State 2026-01-31 11:49:55 +08:00
BZLZHH b112fc0408 Merge branch 'Feat/Backend-Direct-GLES' into dev 2026-01-31 08:57:23 +08:00
BZLZHH d0f54395c7 [Chore] (CMake): Use googletest v1.17.0 2026-01-30 20:59:52 +08:00
swung0x48 31b3053c56 [Chore] (MG_Util/ShaderTranspiler): rename function, more log 2026-01-30 16:44:33 +08:00
swung0x48 f69fbef4b0 [Chore] (MG_Util/ShaderTranspiler): rename function 2026-01-30 11:10:27 +08:00
swung0x48 99299cf0f3 [Fix] (MG_Impl/Getter): avoid crash when no buffer is bound 2026-01-29 23:43:27 +08:00
swung0x48 197fdb972b [Chore] (Defines): shouldn't enable scope marker by default 2026-01-29 22:57:25 +08:00
swung0x48 9ae554cabe [Fix] (MG_Backend/DirectGLES): fix broken mipmap uploading (hardcoded level for some reason) 2026-01-29 22:53:07 +08:00
swung0x48 0fe514fe1d [Chore] (MG_Impl/Texture): more logs 2026-01-29 20:23:21 +08:00
swung0x48 5c7457dbc6 [Chore] (MG_Backend/DirectGLES, MG_Impl/Texture): more logging 2026-01-29 17:58:25 +08:00
swung0x48 77aa26661d [Feat] (MG_Util/BackendLoaders/OpenGL, MG_Impl/Getter): retrieve real GL_UNIFORM_BUFFER_OFFSET_ALIGNMENT from backend 2026-01-29 16:48:01 +08:00
swung0x48 ffec1618f1 [Fix] (MG_State/Texture): relaxing completeness check on reasonable 0x0 mipmap 2026-01-29 15:17:53 +08:00
swung0x48 afc97efcaf [Chore] (MG_Util/Texture): more logs 2026-01-29 14:12:53 +08:00
swung0x48 aa0cff5742 [Fix] (MG_Util/ShaderTranspiler): fix bug FloatEqualsZeroEliminationPass where it may skip one instruction 2026-01-25 13:19:28 +08:00
swung0x48 639ec18a50 [Fix]: fix compilation on Windows 2026-01-25 11:27:51 +08:00
swung0x48 0b4014d665 [Feat] (MG_Util/ShaderTranspiler): patch op OpFOrdNotEqual/OpFUnordNotEqual 2026-01-24 22:14:00 +08:00
swung0x48 e9ef6db44b [Fix] (MG_State/Program): properly invoke SPIR-V sanitize routine 2026-01-24 19:22:13 +08:00
swung0x48 eac7a9e474 [Fix] (MG_Backend/DirectGLES): revert to targeting essl 320 2026-01-24 19:21:10 +08:00
swung0x48 53e4778054 [Fix] (MG_Impl/EGLImpl): fix BindAPI debug log 2026-01-24 19:03:08 +08:00
swung0x48 484174767d [Feat] (MG_Util/ShaderTranspiler): do FloatEqualsZero elimination by leveraging SPIRV-Tool opt pass 2026-01-24 17:35:33 +08:00
swung0x48 3b5047f2c4 [Feat] (MG_Util/Converters): EGLEnumConverter 2026-01-23 13:04:06 +08:00
swung0x48 0a7bd794b5 [Chore] (MG_Impl/EGLImpl): add more logs to EGLWrapper 2026-01-23 11:21:33 +08:00
swung0x48 8c2dd621b6 [Fix] (EGLImpl/EGLWrapper): hardcode binding to EGL_OPENGL_ES_API for now 2026-01-18 22:06:43 +08:00
swung0x48 f60a3002e9 [Fix] (MG_State/Texture): add missing RGB16 format 2026-01-18 18:50:54 +08:00
swung0x48 a52ec9116e [Fix] (MG_Util/BackendLoaders): correct LibPathPrefixes precedence, fixing load on Android 2026-01-18 10:55:17 +08:00
BZLZHH 20fbfc2956 [Chore] (LICENSE): Switch project license to LGPLv3. 2026-01-18 09:33:33 +08:00
swung0x48 8a388f3908 [Fix] (MG_Util/BackendLoaders, MG_Impl/GetProcAddress): fixing hiccups when load by LD_LIBRARY_PATH 2026-01-17 13:04:44 +08:00
swung0x48 35fd55d4be [Chore]: small program to do a tiny self-check 2026-01-17 11:23:36 +08:00
swung0x48 80bb46cbb9 [Fix] (MG_Impl/GetProcAddress, Exporting): properly get proc address, clear reliance on dlsym 2026-01-17 09:19:38 +08:00
swung0x48 97cbb35dbd [Feat] (MG_Impl/EGLImpl): Implement eglQueryString 2026-01-14 22:50:40 +08:00
swung0x48 c7ca2fecf2 [Chore] (MG_Impl/Texture): more logs 2026-01-11 18:14:03 +08:00
swung0x48 00b972252b [Feat] (CMake): bring back SPIRV-Tools-opt 2026-01-11 17:30:51 +08:00
swung0x48 fbac2ceb4e [Chore] (Config): update vendor string 2026-01-11 09:29:41 +08:00
swung0x48 b67a8d2e3a [Fix] (MG_Backend/DirectGLES): patches for Photon (4th patch) 2026-01-11 09:07:25 +08:00
swung0x48 a051e51946 [Fix] (MG_Backend/DirectGLES): patches for Photon (3rd patch) 2026-01-10 21:59:03 +08:00
swung0x48 3b807f6275 [Chore] (Defines): MOBILEGL_LOG_ACTIVE_LEVEL defaults to MOBILEGL_LOG_LEVEL_INFO 2026-01-10 13:43:59 +08:00
swung0x48 26ab093679 [Feat] (MG_Util/Texture): use fallback formats when GL_EXT_texture_norm16 is not supported 2026-01-10 13:23:02 +08:00
swung0x48 db2806a12a [Feat] (MG_Util/BackendLoaders): check for GL_EXT_texture_norm16 2026-01-10 12:54:35 +08:00
swung0x48 cc7e95c84d [Chore] (MG_Backend/DirectGLES): check for ES error when glTexImage* 2026-01-10 11:43:15 +08:00
swung0x48 48d5e522d8 [Chore] (MG_Util): add/fix some logging 2026-01-10 11:27:56 +08:00
swung0x48 60ab186b5c [Fix] (MG_Backend/DirectGLES): patches for Photon (cont.) 2026-01-10 00:54:57 +08:00
swung0x48 c24015b618 [Fix] (MG_Backend/DirectGLES): patches for Photon (WIP) 2026-01-09 23:49:10 +08:00
swung0x48 27ed4cd30b [Feat] (MG_Backend/DirectGLES): OpenGL scope marker 2026-01-09 16:23:30 +08:00
swung0x48 1e49519c81 [Chore] (MG_Backend/DirectGLES): tidying up code 2026-01-09 10:29:07 +08:00
swung0x48 39182f3a5e [Fix] (MG_Backend/DirectGLES): fix bad texture binding in CopyTexImage2D 2026-01-08 14:07:51 +08:00
swung0x48 d7139894da [Chore] (MG_Backend/DirectGLES): more debug stuff 2026-01-08 14:07:05 +08:00
swung0x48 6efcecc147 [Chore] (MG_Backend/DirectGLES): more debug stuff 2026-01-08 11:38:57 +08:00
swung0x48 0d4c227196 [Chore] (MG_Backend/DirectGLES): fix param order in GenerateTextureFormatInfo 2026-01-08 10:33:57 +08:00
swung0x48 d7e1aee645 [Chore] (MG_Impl/Texture): convert base internal format to sized ones (on a best-effort basis) 2026-01-08 10:19:20 +08:00
swung0x48 a601307d6f [Chore] (MG_Util/Texture): rearrange formats in NormalizePixelFormat (cont.) 2026-01-06 22:48:32 +08:00
swung0x48 4b8e558565 [Chore] (MG_Util/Texture): rearrange formats in NormalizePixelFormat 2026-01-06 14:02:20 +08:00
swung0x48 4c0cc8b038 [Fix] (MG_Util/Texture): use proper GL_RGBA16 to unbreak gbuffer unpack in some shaders 2026-01-06 09:29:50 +08:00
swung0x48 d4a98ad94f [Fix] (MG_Util/Texture): fix D32 depth format in NormalizePixelFormat, fixing Photon shadow 2026-01-06 09:28:51 +08:00
swung0x48 bdd4261a5a [Chore] (MG_Util/Metrics): add fallback assertion when getting unknown GL type size 2026-01-05 17:46:04 +08:00
swung0x48 0a1e85e9e6 [Fix] (MG_Util/Debug/Log): force turn off stacktrace 2026-01-05 15:33:15 +08:00
swung0x48 08a9c9bb61 [Fix] (MG_Impl/Tetxture): properly fix CopyTexImage2D's frontend state 2026-01-05 12:52:47 +08:00
swung0x48 b3fe9c1544 [Chore] (MG_Util/Texture): move NormalizePixelFormat to MG_Util 2026-01-05 12:43:47 +08:00
swung0x48 5e9844a4e5 [Chore] (MG_Util/Debug/Log): give up on stacktrace 2026-01-05 10:03:14 +08:00
swung0x48 c6443e5039 [Fix] (CMake): make MSVC properly report __cplusplus macro 2026-01-05 09:46:38 +08:00
swung0x48 141eeb4e87 [Optimize] (MG_Backend/DirectGLES): use texture target instead of upload target 2026-01-05 09:30:16 +08:00
swung0x48 4233a6031a [Fix] (MG_Backend/DirectGLES): why do I need to get "real" internalformat anyway?? 2026-01-04 23:22:49 +08:00
swung0x48 05f5c0c2b5 [Feat] (MG_Impl/GLImpl): export glDrawBuffer 2026-01-04 23:21:59 +08:00
swung0x48 2657edc003 [Feat] (MG_Impl/Framebuffer): implement glDrawBuffer 2026-01-04 23:21:19 +08:00
swung0x48 52d98ee7c3 [Feat] (MG_Backend/DirectGLES): implement glTexImage3D in the ES backend 2026-01-04 17:37:24 +08:00
swung0x48 c537f9814c [Feat] (MG_Impl/Texture): implement glTexImage3D in the frontend 2026-01-04 16:39:14 +08:00
swung0x48 7819a8e405 [Fix] (MG_Util/TextureMetrics): fix wrong size of RGB16F, RGB16I, RGB16UI 2026-01-04 16:38:18 +08:00
swung0x48 b281afe665 [Feat] (MG_Backend/DirectGLES): add proper handling when internalformat is GL_R16 2026-01-04 16:03:50 +08:00
BZLZHH 28c15148f2 [Fix] (...): Some fix for TexSubImage2D(MG_Impl) and ... 2026-01-02 19:40:05 +08:00
BZLZHH 3822d8169a [Docs] (README): Better build instructions. 2026-01-02 18:28:42 +08:00
BZLZHH 8db0841949 [Improvement] (CMake): Unify CMake options. 2026-01-02 18:14:44 +08:00
BZLZHH e5c0782615 [Fix|Chore] (3rdparty): Update glslang for disabling GL_ARB_derivative_control. 2026-01-01 13:54:38 +08:00
BZLZHH b68d2859e8 [Feat] (MG_Util|MG_State/TextureState): Add TexturePixelDataType::HalfFloat and TexturePixelDataType::UnsignedInt248. Handle TexturePixelDataType::Float32UnsignedInt248Rev. 2026-01-01 13:17:25 +08:00
BZLZHH 21dcbc9e52 [Chore] (CI): Use Ninja and clang. 2026-01-01 12:16:26 +08:00
BZLZHH e4f027e13b [Fix] (MG_Util): Skip GLES initializing if the libs do not exist. 2026-01-01 11:32:12 +08:00
BZLZHH 876195de80 Revert "[Fix] (...): Skip external libraries loading for MG_Test and MG_Bench."
This reverts commit da0e326534.
2026-01-01 10:49:01 +08:00
BZLZHH e298e5be51 Revert "[Chore] (...): Cmake option MOBILEGL_FORCE_SKIP_EXTERNAL_LIB_LOADING."
This reverts commit 0b262d4f3a.
2026-01-01 10:48:49 +08:00
BZLZHH 0b262d4f3a [Chore] (...): Cmake option MOBILEGL_FORCE_SKIP_EXTERNAL_LIB_LOADING. 2026-01-01 01:48:30 +08:00
BZLZHH da0e326534 [Fix] (...): Skip external libraries loading for MG_Test and MG_Bench. 2026-01-01 01:33:11 +08:00
BZLZHH 3714e275ab [Chore] (All): Update copyright year in source code files. 2026-01-01 00:42:06 +08:00
BZLZHH ee4dc70336 [Fix] (...): Avoid some weird crashes. 2026-01-01 00:41:23 +08:00
BZLZHH 7c2380ccce [Chore] (MG_Util): Always skip patch string when == 0 for Version. 2026-01-01 00:27:11 +08:00
BZLZHH adc927668b [Chore] (Config): Bump version to 26.01 2026-01-01 00:05:11 +08:00
BZLZHH 04335fdad7 [Chore] (LICENSE): Update copyright year in LICENSE. 2026-01-01 00:00:40 +08:00
BZLZHH e7d9da42dc [Chore] (All): Adjust copyright declaration. 2025-12-31 21:49:54 +08:00
BZLZHH 58b620dee3 [Feat] (MG_Backend|MG_State/ProgramState): Add default fragment shader if missing for backends requiring FS. 2025-12-31 21:09:19 +08:00
BZLZHH c902721683 [Feat] (MG_State/RenderbufferState): Add RenderbufferObject::GetExternalIndex() 2025-12-31 19:57:46 +08:00
BZLZHH e5c3a6beba [Feat] (MG_Backend/DirectGLES): Add cache for backend RBO. 2025-12-31 19:52:12 +08:00
BZLZHH 937ace68a6 [Feat] (MG_Backend/DirectGLES): Sync RBO in backend. 2025-12-31 19:45:49 +08:00
BZLZHH 2c214affbe [Fix] (MG_Impl/Framebuffer): Correctly set internal format for RBO. 2025-12-31 19:45:11 +08:00
BZLZHH 9f4a1041ba Merge branch 'dev' into Feat/Backend-Direct-GLES 2025-12-31 15:46:56 +08:00
BZLZHH 8ed8efe347 [Chore] (All): Add standardized source file header and update script. 2025-12-31 15:45:34 +08:00
swung0x48 aa83aa1519 [Fix] (MG_Util/ShaderTranspiler): process shader version directive correctly when it is not the first line 2025-12-30 21:20:37 +08:00
swung0x48 69caca5903 [Fix] (MG_Impl/Texture): read PBO if pixels == NULL at TexSubImage2D 2025-12-30 12:39:19 +08:00
swung0x48 e886a93a18 [Chore] (MG_Impl/RenderState, MG_State/RenderState): more logs 2025-12-29 11:10:38 +08:00
swung0x48 45276bbb7c [Feat] (MG_Util/PixelStoreProcessor): properly handle BGRA to RGBA
swizzle
2025-12-28 23:18:26 +08:00
swung0x48 b220c8baab [Feat] (MG_Impl/Texture): Decouple texture internal format and input format 2025-12-15 14:16:36 +08:00
swung0x48 02a2f4af4a [Feat] (MG_Impl/Texture): accept GL_TEXTURE_LOD_BIAS at frontend 2025-12-15 12:35:24 +08:00
BZLZHH de028204a2 [Feat] (MG_Backend/DirectGLES): Implement ClearBuffer* in backend. 2025-12-14 12:06:48 +08:00
BZLZHH 5071a98e00 [Feat] (MG_Impl/Framebuffer): Add ClearBuffer*. 2025-12-14 11:37:15 +08:00
BZLZHH 4f1def412c [Fix] (MG_State/RenderBufferState): Add missing RenderbufferObject::GetSamples 2025-12-14 11:30:49 +08:00
BZLZHH 9ab001bf75 [Feat] (MG_Impl/Framebuffer): Implement renderbuffer funcs. 2025-12-14 11:28:02 +08:00
BZLZHH 69a7374b51 [Feat] (MG_Utils/Converters): Converters for Renderbuffer enum. 2025-12-14 11:26:47 +08:00
BZLZHH e4cc101639 [Docs] (README): Fix funny link. 2025-12-14 11:25:13 +08:00
BZLZHH 3063374834 [Feat] (MG_State/RenderbufferObject): Better RenderbufferObject. 2025-12-14 11:17:09 +08:00
BZLZHH 100d5bca99 [Feat] (MG_Util/Types): Add ComponentSizes. 2025-12-14 11:15:27 +08:00
BZLZHH 711e427b76 [Feat] (MG_State): Integration with RenderbufferState. 2025-12-14 09:49:55 +08:00
BZLZHH 5bb9faaaa5 [Feat] (MG_State/RenderBufferState): Initially implement RenderbufferState. 2025-12-14 09:40:36 +08:00
BZLZHH 96c3024544 Merge remote-tracking branch 'origin/Feat/Backend-Direct-GLES' into Feat/Backend-Direct-GLES 2025-12-14 08:17:48 +08:00
BZLZHH 5d2a954b4b [Misc] (MG_Impl/Getter): Stub for GL_MAX_SAMPLES. 2025-12-14 08:17:07 +08:00
swung0x48 c3755d77ef [Feat] (MG_Impl/Texture): implement GL_TEXTURE_SWIZZLE_RGBA 2025-12-13 21:28:04 +08:00
swung0x48 81a717ada7 [Feat] (MG_Impl/Texture): partially implement glTexParameter*v
- Fixing NeoForge loading screen
2025-12-13 20:48:59 +08:00
swung0x48 17bbe3e6ba [Feat] (CMake): make TRACY_ENABLE as an option 2025-12-12 23:40:39 +08:00
swung0x48 0519cdeb9c [Optimization] (MG_Backend/DirectGLES): add more tracy zones 2025-12-12 10:25:39 +08:00
swung0x48 f08859d1c5 [Fix] (3rdparty/tracy): enable TRACY_NO_CRASH_HANDLER to prevent unwanted crash detection 2025-12-12 09:30:34 +08:00
swung0x48 6a9738a7c5 [Optimization] (MG_Backend/DirectGLES): optimize BackendTextureBindingProtector usage 2025-12-11 20:38:09 +08:00
swung0x48 91b04f6995 [Feat] (MG_Backend/DirectGLES): tracy integration for DirectGLES backend 2025-12-11 20:37:20 +08:00
swung0x48 ffd4ec3408 [Feat] (tracy): initial tracy integration 2025-12-11 17:18:26 +08:00
swung0x48 0e9bca40f3 [Chore] (CMake): use set() instead of option() 2025-12-11 16:29:03 +08:00
swung0x48 1e64a85bcd [Fix] (Defines.h): include mingw as Windows platform 2025-12-11 15:14:07 +08:00
swung0x48 f94861926a [Feat] (3rdparty/tracy): initial integration of Tracy Profiler 2025-12-11 15:12:19 +08:00
swung0x48 6b4c911f06 [Fix] (CMake): lower tests to O2 optimization 2025-12-10 17:53:33 +08:00
swung0x48 eb705c53bf [Chore] (MG_State/Texture): explicitly specify value for enums 2025-12-10 15:29:59 +08:00
swung0x48 a1a9b16457 [Chore] (MG_Backend/DirectGLES): rearrange DebugImpl 2025-12-10 15:25:20 +08:00
swung0x48 b79424a78c [Feat] (MG_Backend/DirectGLES): sync tex buffer to backend 2025-12-10 09:17:30 +08:00
swung0x48 cb4e6b5f19 [Feat] (MG_State/Texture, MG_Impl/Texture): glTexBuffer (and implement TextureObjectBuffer accordingly) 2025-12-09 21:20:39 +08:00
swung0x48 3f36248638 [Fix] (MG_Test/Program): does this fix ci failure? 2025-12-09 13:48:18 +08:00
swung0x48 0a89ad4f30 [Feat] (MG_State/Texture): separate mipmap from TextureObjectBase 2025-12-09 10:57:10 +08:00
BZLZHH 56f45499e1 [Feat] (MG_Backend/DirectGLES): Set divisor for VAO attrib. 2025-12-07 11:07:58 +08:00
BZLZHH 4089a42d3b [Feat] (MG_Impl/VertexArray): Implement VertexAttribDivisor. 2025-12-07 11:03:22 +08:00
BZLZHH 13abb24324 [Feat] (MG_State/VertexArrayState): Implement divisor. 2025-12-07 11:03:00 +08:00
BZLZHH 407d57e9b9 [Feat] (MG_Impl/Drawing): Implement more draw funcs. 2025-12-07 10:50:26 +08:00
BZLZHH b3824c871c [Feat] (MG_Backend/DirectGLES): Implement more draw funcs. Add DrawSyncBit. 2025-12-07 10:50:13 +08:00
BZLZHH 1da2550774 [Chore] (...): Use Calender Versioning. 2025-12-07 09:41:25 +08:00
BZLZHH ecc91290cb [Docs] (README): Better introduction. 2025-12-07 02:13:02 +08:00
BZLZHH c69cae1ba2 [Docs] (README): Introduce this project. 2025-12-07 02:03:32 +08:00
BZLZHH 9934b1b2b3 [Chore] (3rdparty): Remove unordered_dense. 2025-12-07 01:18:42 +08:00
BZLZHH 5860856bc1 [Chore] (3rdparty): Remove glm. 2025-12-07 01:17:16 +08:00
swung0x48 ab6d9f60e7 [Refactor] (MG_State/Texture): decouple texture object and mipmap storage 2025-12-06 22:24:30 +08:00
BZLZHH 6293f3f0ab [Feat] (MG_State/TextureState): Add GL_FLOAT_32_UNSIGNED_INT_24_8_REV. 2025-11-30 11:42:20 +08:00
BZLZHH 7a9cb2dafb [Fix] (MG_Backend/DirectGLES): Handle more internal format. 2025-11-30 11:24:21 +08:00
swung0x48 fe6bd76cfa [Fix] (MG_State/TextureStorage): fix wrong assertion 2025-11-30 10:34:03 +08:00
swung0x48 ea61946bfc Merge branch 'Feat/Backend-Direct-GLES' of https://github.com/MobileGL-Dev/MobileGL into Feat/Backend-Direct-GLES 2025-11-30 10:19:48 +08:00
swung0x48 5e0a6c70b8 [Chore] (submodule): revert glslang to 15.4.0 2025-11-30 10:19:03 +08:00
BZLZHH e8b668a701 Merge branch 'Feat/Backend-Direct-GLES' of github.com:MobileGL-Dev/MobileGL into Feat/Backend-Direct-GLES 2025-11-30 10:13:43 +08:00
BZLZHH fe741f892e [Fix] (MG_Util/Metrics): Handle TextureInternalFormat::Red 2025-11-30 10:13:31 +08:00
swung0x48 1b48ffaaf7 [Chore]: re-point glslang submodule to forked repo 2025-11-30 10:00:37 +08:00
swung0x48 e58402bc9e [Fix] (MG_State/Program): insist compile for vulkan. (will require patching glslang) 2025-11-30 00:15:04 +08:00
swung0x48 0ee8a060e2 [Feat] (MG_Test/Program): add test for malicious shader using sampler as variable name 2025-11-29 23:29:20 +08:00
BZLZHH 3ba9709748 Merge branch 'Feat/Backend-Direct-GLES' of github.com:MobileGL-Dev/MobileGL into Feat/Backend-Direct-GLES 2025-11-29 23:06:34 +08:00
BZLZHH 51554eac7c [Perf|Fix] (MG_Backend/DirectGLES): Clear dirty after buffer sync. 2025-11-29 22:57:40 +08:00
swung0x48 11aff346f1 [Fix] (MG_Impl/Getter|CMake): avoid git hash header name collision with SPIRV-Cross 2025-11-29 21:45:13 +08:00
BZLZHH a9c49cbc77 [Feat] (MG_Impl/Getter|CMake): Show git commit hash. Adjust some texts. 2025-11-29 21:21:13 +08:00
BZLZHH d1c58904f4 [Fix] (MG_Backend/DirectGLES): Bind sampler object in backend. 2025-11-29 20:02:08 +08:00
BZLZHH 49e80ae4cf [Fix] (MG_Backend/DirectGLES): Fix sampler sync. 2025-11-29 20:01:33 +08:00
BZLZHH 37ffacb373 [Fix] (MG_State/ProgramState): Add CompileForOpenGL bit for shader compilation. 2025-11-29 19:27:39 +08:00
BZLZHH a87a828297 [Fix] (MG_Backend/DirectGLES): Also sync minFilter when mipmapMode changes. 2025-11-29 18:06:26 +08:00
BZLZHH 882a9302e5 [Fix] (MG_Backend/DirectGLES): Remove incorrect branch to skip unit binding sync. 2025-11-29 18:04:10 +08:00
BZLZHH b048037145 [Perf] (MG_Backend/DirectGLES): Enable invalidate when syncing buffer data. 2025-11-29 17:59:43 +08:00
BZLZHH d2d95cb4cc [Fix] (MG_State/SamplerState): mipmapMode should be None by default. 2025-11-29 17:56:38 +08:00
BZLZHH 1a9f546309 [Feat] (MG_Util/BackendLoaders): Detect buffer storage extension. 2025-11-29 14:26:01 +08:00
BZLZHH 521bcadbee [Fix] (...): Fix code mess. 2025-11-29 01:43:58 +08:00
BZLZHH 7a30c56b13 [Improvement] (MG_Backend/DirectGLES): Add cache for swizzle params. 2025-11-29 01:35:58 +08:00
BZLZHH 32c062d019 [Feat] (MG_State/TextureState): Add ITextureObject::GetAllSwizzleParams 2025-11-29 01:33:58 +08:00
BZLZHH 75fc52febe [Feat] (MG_State/TextureState): Stubs for unimplemented texture types. 2025-11-29 01:31:41 +08:00
BZLZHH 6ba9382321 [Feat] (MG_Util/Converters): More converters for Texture enum. 2025-11-29 01:23:34 +08:00
BZLZHH 8ca8fa1520 [Perf|Fix] (MG_Backend/DirectGLES): Improve perf. 2025-11-29 01:21:34 +08:00
BZLZHH 936abafde9 Revert "[Improvement] (MG_State/TextureState): Separate TextureStorage.h into .cpp/.h"
This reverts commit 657c672899.
2025-11-28 22:37:49 +08:00
BZLZHH e72bdb67b5 [Feat] (MG_State/TextureState): Add more TextureUploadTarget. 2025-11-28 21:37:47 +08:00
BZLZHH 657c672899 [Improvement] (MG_State/TextureState): Separate TextureStorage.h into .cpp/.h 2025-11-28 21:09:14 +08:00
BZLZHH a6b34ee5bf [Chore] (...): Format code. 2025-11-28 15:17:50 +08:00
BZLZHH c67e6e26fa [Fix] (MG_Backend/DirectGLES): Do not bind PBO. 2025-11-28 15:16:07 +08:00
swung0x48 d1f5aff440 [Fix] (MG_State/Texture): properly implement GetBaseSize() and IsComplete() for cubemap 2025-11-27 15:02:22 +08:00
swung0x48 e244974928 [Chore] (MG_Impl/Texture): add more assertion over unimplemented stubs 2025-11-26 22:13:41 +08:00
swung0x48 da5b9686ba [Fix]: build on macOS 2025-11-26 22:05:02 +08:00
swung0x48 a0aaba3cb5 [Feat] (MG_State/Texture): Initial implementation of cube map 2025-11-25 22:47:41 +08:00
swung0x48 4d44dda117 [Chore] (MG_State/TextureObject): separate TextureObjectWithOneMipmap 2025-11-25 21:52:01 +08:00
swung0x48 45ae87c017 [Chore]: fix compilation in gcc 2025-11-25 14:22:28 +08:00
swung0x48 e79d2fd059 [Chore]: get rid of junk in texture stuff 2025-11-25 14:20:37 +08:00
swung0x48 352df37b91 [Feat] (MG_State/TextureObject): implement GetIndexOfTextureUploadTarget() 2025-11-25 14:14:05 +08:00
swung0x48 1a997ae8d4 [Feat]: more refined MOBILEGL_ASSERT() macro 2025-11-25 14:12:46 +08:00
swung0x48 7fe156cebc [Chore] (MG_Backend/DirectGLES): adjust some log severity 2025-11-25 13:33:22 +08:00
swung0x48 64fd36bb60 [Fix] (MG_State/TextureObject): fix silly tex input data bug introduced by the refractor 2025-11-25 10:50:13 +08:00
swung0x48 419a67cd08 [Feat] (MG_State/TextureState): refractor mipmap (TextureStorage) 2025-11-25 00:10:13 +08:00
swung0x48 73b583cc00 [Feat] (Backends): advertise GL_ARB_draw_buffers_blend 2025-11-25 00:08:10 +08:00
swung0x48 d0f4b1d7d1 Merge branch 'Feat/Backend-Direct-GLES' of https://github.com/MobileGL-Dev/MobileGL into Feat/Backend-Direct-GLES 2025-11-24 17:03:01 +08:00
swung0x48 718eeaab43 [Chore] (MG_State/TextureObject): extract mipmap stuff 2025-11-24 16:59:59 +08:00
BZLZHH d3db296b6d [Chore] (Git): Remove .gitattributes file 2025-11-24 12:09:08 +08:00
BZLZHH 1454c967c6 [Chore] (Library): Remove all built binaries. 2025-11-24 12:08:26 +08:00
swung0x48 ca8d2b7bab [Chore]: separate TextureObject child classes into individual files 2025-11-24 09:51:39 +08:00
swung0x48 1c318db4a0 [Fix] (cmake): fix compilation on MSVC 2025-11-24 09:33:59 +08:00
BZLZHH 9cd749b707 [Improvement] (All): Better assertion. 2025-11-23 10:27:01 +08:00
swung0x48 363bedb245 [Chore] (MG_Impl/Texture): use .empty() instead of .size() 2025-11-22 23:21:36 +08:00
swung0x48 4af61f9c00 [Feat] (MG_Util/ShaderTranspiler): remove noperspective in preprocessing 2025-11-22 18:15:02 +08:00
swung0x48 6e5e458501 [Feat] (MG_Impl/Exporting): add stub for glBlend*ARB for ARB_draw_buffers_blend 2025-11-22 09:37:47 +08:00
swung0x48 69cf694ca1 [Fix]: fix crash on shader compile 2025-11-22 08:44:04 +08:00
swung0x48 e3f73291e9 [Fix] (MG_Impl/GL_Program): fix GetUniform_State for mat3 alignment issues 2025-11-21 22:24:47 +08:00
swung0x48 854d293404 [Fix] (MG_Impl/Getter): fix typo 2025-11-19 12:59:18 +08:00
swung0x48 caf10a267d [Fix] (MG_Backend/DirectGLES): correctly bind texture on CopyTexSubImage2D 2025-11-19 10:17:52 +08:00
swung0x48 d8cd5a235a [Chore] (MG_Backend/DirectGLES): trim redundant stuff in BackendFramebufferObject::SyncToBackend 2025-11-18 22:37:24 +08:00
swung0x48 0c31de3afc [Fix]: compilation on Windows 2025-11-18 21:17:44 +08:00
swung0x48 8d3dd14498 [Fix] (MG_Impl/Texture): don't malloc if unnecessary 2025-11-18 12:47:09 +08:00
swung0x48 2709b9754f [Fix] (MG_Impl/Program): fixing UniformMatrix3fv improper alignment 2025-11-18 11:16:29 +08:00
swung0x48 ef6ef0fc31 [Fix] (MG_Util/Converters): add MirrorClampToEdge 2025-11-17 22:19:52 +08:00
swung0x48 fb9a32c224 [Fix] (MG_Util/ShaderTranspiler): maxFragmentUniformVectors increase to 256 2025-11-17 22:18:51 +08:00
swung0x48 55db06bf5c [Feat] (MG_Backend/DirectGLES): implement glGenerateMipmap 2025-11-17 17:36:42 +08:00
swung0x48 0139cabfbc [Fix] (MG_Util/Metrics): fix bool uniform size 2025-11-17 15:04:29 +08:00
swung0x48 ff0a3c5b9a [Feat] (MG_Util/Converters, MG_State/Sampler, MG_State/Texture): properly implement min/mag/mip filters 2025-11-17 13:40:34 +08:00
swung0x48 8182d9e402 [Fix] (MG_Util/Converters): fix incorrectly converted GL_TEXTURE_SWIZZLE_* pnames 2025-11-16 22:56:03 +08:00
swung0x48 126239db24 [Fix?] (MG_Test/ProgramTest): make ci shut up? 2025-11-16 21:52:42 +08:00
swung0x48 6efc4d4fc3 [Chore] (MG_Util/Converters): add log when encountered unknown format 2025-11-16 21:50:17 +08:00
swung0x48 6d86c9fe98 [Chore] (MG_Backend/DirectGLES): fix incorrect log level 2025-11-16 21:21:52 +08:00
swung0x48 2b915d5680 [Chore] (MG_Backend/DirectGLES): log ES error when syncing texture 2025-11-16 21:20:18 +08:00
swung0x48 dc49873d3e [Chore] (MG_Backend/DirectGLES): get rid of clutter 2025-11-16 21:18:16 +08:00
swung0x48 426895766d [Fix] (MG_Impl/Getter): properly report GPU name 2025-11-16 21:17:34 +08:00
swung0x48 1e5e993704 [Fix] (MG_Backend/DirectGLES/Utils): tweaks on NormalizePixelFormat, fixing shaders on some Mali 2025-11-16 21:02:18 +08:00
swung0x48 37e0312c72 [Feat] (MG_Backend/DirectGLES): ErrorLooper 2025-11-16 18:36:06 +08:00
swung0x48 95e086442c [Feat] (MG_Backend/DirectGLES): implement glCopyTexImage2D/CopyTexSubImage2D 2025-11-16 12:44:41 +08:00
BZLZHH 131c9a2db6 [Improvement] (MG_Impl/Sampler): Create sampler object even when not bound. 2025-11-16 02:19:16 +08:00
BZLZHH fe7af0839e [Fix] (MG_Impl/Getter): Fix wrong error record for GL_MAX_COLOR_ATTACHMENTS and GL_MAX_DRAW_BUFFERS. 2025-11-16 02:16:23 +08:00
BZLZHH 6b6f224e1e [Feat] (MG_Backend/DirectGLES): Implement sampler object sync. 2025-11-16 01:31:24 +08:00
BZLZHH 850081d313 [Feat] (MG_State/SamplerState): Uniform SamplerParameters. 2025-11-16 00:43:23 +08:00
BZLZHH 60bb091927 [Feat] (MG_Impl/Sampler): Implement full sampler object frontend. 2025-11-16 00:36:21 +08:00
BZLZHH 3809a9f52f [Feat] (MG_State/SamplerState): Implement SamplerState. 2025-11-15 23:53:54 +08:00
BZLZHH c664815fee [Fix] (MG_Backend/DirectGLES): Do not upload junk data for texture. 2025-11-15 23:32:11 +08:00
BZLZHH 784b53344c [Feat] (MG_State/TextureState|MG_Impl/Texture): Add hasData mark for MipmapLevelInternal. 2025-11-15 23:17:01 +08:00
BZLZHH 8b39e3c8a9 [Feat] (MG_Impl/Texture): Implement PBO. 2025-11-15 23:02:00 +08:00
BZLZHH e944944e7c [Misc] (MG_Impl/Getter): GL_MAX_COLOR_ATTACHMENTS in GetIntegerv. 2025-11-15 22:41:30 +08:00
BZLZHH 7af4c7d71b [Fix] (MG_State/FramebufferState): Set default readBuffer value as Color0. 2025-11-15 22:09:57 +08:00
BZLZHH 845f699e3f [Fix] (MG_State/FramebufferState): FramebufferAttachment::IsEmpty should be const. 2025-11-15 21:57:43 +08:00
BZLZHH 49b66c30c1 [Feat] (MG_State/TextureState|MG_Impl/Texture): Add fake CubeMapTexture support. 2025-11-15 21:47:50 +08:00
BZLZHH a0cc3e5f3e [Misc] (MG_Impl/Getter): Hardcode the value returned by GL_UNIFORM_BUFFER_OFFSET_ALIGNMENT as 256. 2025-11-15 21:40:25 +08:00
BZLZHH 2ce2d1c731 [Misc] (MG_State/ProgramState): Better log. 2025-11-15 21:39:01 +08:00
BZLZHH e85b067314 [Fix] (MG_Backend/DirectGLES|MG_Impl/Program): Correct UBO binding. 2025-11-15 21:37:08 +08:00
BZLZHH 4cb82e2e50 [Fix] (MG_Backend/DirectGLES): Correct MRT sync. 2025-11-15 21:34:40 +08:00
BZLZHH 2534394df3 [Improvement] (MG_Backend/DirectGLES): Better buffer sync. 2025-11-15 21:31:34 +08:00
BZLZHH 1c8af9253b [Improvement] (MG_Backend): Better log. 2025-11-15 14:35:44 +08:00
BZLZHH ac5c26af99 [Feat] (MG_Impl/Drawing): Export glDrawElementsBaseVertex. 2025-11-15 14:16:40 +08:00
swung0x48 e93dff52dc [Fix] (MG_Impl/Framebuffer, MG_State/Framebuffer, MG_Backend/DirectGLES): redone fbo attachment management. remap GL -> ES attachment names 2025-11-15 00:39:07 +08:00
swung0x48 899563165e [Feat] (MG_Backend/DirectGLES): hook up glDrawBuffers 2025-11-14 17:08:55 +08:00
swung0x48 0d3236c3cc [Feat] (MG_State/Framebuffer, MG_Impl/Framebuffer): implement glDrawBuffers in the state machine 2025-11-14 15:41:25 +08:00
BZLZHH 1f831d79a9 [Chore] (Include): Remove junk files. 2025-11-14 13:34:03 +08:00
BZLZHH 651c91f78e [Chore] (Gradle): Upgrade NDK version. 2025-11-14 12:43:31 +08:00
BZLZHH a01037b6fe [Misc] (MG_State/TextureState): Remove completed TODO. 2025-11-14 11:09:27 +08:00
swung0x48 55e89e169f [Fix?] (MG_Test/Program): why is action sometimes failing? 2025-11-13 15:07:07 +08:00
swung0x48 0d26f49d0b [Fix] (GLImpl/Program): fix log name error 2025-11-13 14:47:05 +08:00
swung0x48 7ee85e5a76 [Chore] (Defines): use DEBUG log level 2025-11-13 14:45:57 +08:00
swung0x48 89bfebf767 [Feat] (MG_Impl/Exporting): export glBindFragDataLocation and glGetFragDataLocation 2025-11-13 13:25:33 +08:00
swung0x48 b3b304e9e6 [Feat]: Implement glBindFragDataLocation and glGetFragDataLocation 2025-11-13 13:23:37 +08:00
swung0x48 5b2d18fdff [Fix]: (MG_Util/ShaderTranspiler): implement logic to reserve explicitly set frag outs 2025-11-13 12:54:05 +08:00
swung0x48 1c3a3455ab [Fix]: (MG_Util/ShaderTranspiler): rename explicitAttribLocations to explicitVertexInLocations in ProgramAttrib 2025-11-13 12:46:18 +08:00
swung0x48 2878939712 [Fix]: (MG_Util/ShaderTranspiler): add explicitFragmentOutLocations to program link attribs 2025-11-13 12:20:07 +08:00
swung0x48 cf87891b35 [Fix] (MG_Impl/GL_Program): emit missing gl error 2025-11-13 10:51:38 +08:00
swung0x48 b04481e6da [Chore] (MG_State/ProgramObject): rename attrib to vertex in for clarity 2025-11-13 10:50:37 +08:00
swung0x48 d3ea83992c [Fix]: (MG_Util/ShaderTranspiler/ShaderSourceProcessor): fix trailing \n not get removed 2025-11-13 09:39:53 +08:00
swung0x48 e6c5e132b8 [Fix] (MG_Util/Debug/Log): more log scratch space to avoid truncation 2025-11-12 22:50:21 +08:00
swung0x48 6e65942891 [Chore] (MG_Util/ShaderSourceProcessor): trim unnecessary part of shader source 2025-11-12 18:03:29 +08:00
swung0x48 755b4605e4 [Fix]: (MG_State/Program): fix incorrect Optfine behavior 2025-11-12 16:01:34 +08:00
swung0x48 9bc0ae6b97 [Chore]: (MG_State/Program): use proper enum constant, get rid of junk 2025-11-12 16:00:44 +08:00
swung0x48 bfeb827eb7 [Feat]: (MG_Test/Program): add test to check optfine shader behavior 2025-11-12 15:56:40 +08:00
swung0x48 8b8fa41ef2 [Feat]: (MG_Test/ProgramUtil): CompileAndLinkBlitProgram 2025-11-12 13:08:53 +08:00
swung0x48 f0cf49f3ec [Fix]: (MG_Util/ShaderTranspiler/TMglGlslIoResolver): guard against vertex stage 2025-11-11 17:51:33 +08:00
swung0x48 6ac0fd6f0a [Feat]: (MG_Util/ShaderTranspiler): TMglGlslIoResolver: a custom glslang IoResolver to realize glBindAttribLocation semantics 2025-11-11 17:06:46 +08:00
swung0x48 3e9b53cecc [Feat]: (MG_Util/ShaderTranspiler): the skeleton of defining a custom TIoResolver 2025-11-10 15:53:43 +08:00
swung0x48 fd3b5c3881 [Fix] (MG_Impl/GL_Sync): fix compilation error on msvc 2025-11-10 15:49:26 +08:00
swung0x48 d51d75c3ed [Fix] (CMakeLists): detect and enable LTO through CMake 2025-11-10 14:24:58 +08:00
swung0x48 c30ce008ca [Chore] (MG_State/ProgramObject): more friendly global ubo debug msg 2025-11-09 18:21:46 +08:00
BZLZHH b83977b906 [Fix] (MG_State/ProgramState): Separate detach/remove shader in ProgramObject. Add more log. 2025-11-09 11:37:50 +08:00
BZLZHH e68089590d [Chore|Perf] (CMakeLists): Optimize compile/link options. 2025-11-09 10:03:59 +08:00
swung0x48 b151b2bba7 [Fix]: build test on macOS 2025-11-08 20:02:21 +08:00
swung0x48 3f36992f98 [Fix] (MG_State/ProgramObject): don't link when shader involved failed to compile 2025-11-06 23:55:38 +08:00
swung0x48 7228b01c2d [Fix] (GLImpl/Program, MG_Backend/DirectGLES): guard against not linked program object 2025-11-06 23:21:23 +08:00
swung0x48 98a8a3a5e9 [Chore] (GLImpl/GL_Buffer): add some log 2025-11-06 00:02:02 +08:00
swung0x48 a6ffb24f30 [Fix] (MG_State/Program): fix ubo name mistaken for uniform name 2025-11-05 16:18:35 +08:00
swung0x48 13319a6847 [Feat] (MG_Test/Program): add minecraft core shader tex_color_1216 2025-11-05 15:37:55 +08:00
swung0x48 ef1924d7f9 [Feat] (MG_State/Program, DirectGLES): plumb ubo to backend 2025-11-05 15:37:10 +08:00
swung0x48 c39c03d866 [Fix] (MG_Impl/Program): DeleteShader name check bug 2025-11-05 15:12:37 +08:00
swung0x48 62798ce1b8 [Feat] (MG_State/Program): refractor UBO handling 2025-11-05 13:51:05 +08:00
swung0x48 57dd0fe480 [Feat]: implement glBindVertexAttribLocation in DirectGLES backend (fixing OptiFine?) 2025-11-04 22:16:16 +08:00
swung0x48 2f67620a6e [Fix]: some not-added stuff 2025-11-02 23:51:19 +08:00
swung0x48 1ea32e8538 [Fix] (GL_Impl/Program): fix logging 2025-11-02 11:22:52 +08:00
swung0x48 c69e83735c [Chore] (GL_Impl/Program): add more logging 2025-11-02 11:15:42 +08:00
swung0x48 6a21462554 [Fix] (GL_Impl/Program): fix dumb bug regarding IsActiveUniformBlock 2025-11-02 10:59:08 +08:00
swung0x48 1d3fbedf29 [Feat] (GL_State/Buffer, GL_Impl/Buffer): implement glBindBufferRange 2025-11-02 10:31:05 +08:00
swung0x48 4b4d38a00a [Feat] (GL_State/Buffer, GL_Impl/Buffer): implement glBindBufferBase 2025-11-02 09:34:32 +08:00
BZLZHH effeb7d9f7 Merge branch 'Feat/Backend-Direct-GLES' of github.com:MobileGL-Dev/MobileGL into Feat/Backend-Direct-GLES 2025-11-01 23:48:42 +08:00
BZLZHH a39d6b67f9 [Fix] (MG_Backend/DirectGLES): Fix wrong return; in buffer syncing. 2025-11-01 23:48:25 +08:00
swung0x48 4e2b348e96 Merge branch 'Feat/Backend-Direct-GLES' of https://github.com/MobileGL-Dev/MobileGL into Feat/Backend-Direct-GLES 2025-11-01 23:07:32 +08:00
swung0x48 278656ac5a [Feat]: (MG_Impl/Program, MG_State/Program): implement UBO 2025-11-01 23:06:25 +08:00
BZLZHH 2c05d937e5 Merge branch 'Feat/Backend-Direct-GLES' of github.com:MobileGL-Dev/MobileGL into Feat/Backend-Direct-GLES 2025-11-01 21:43:13 +08:00
BZLZHH 984ae97579 [Improvement] (...): Better handling for enabling/disabling attribute in VAO. 2025-11-01 21:42:05 +08:00
swung0x48 4706dea9de [Chore] (GLImpl/Texture): adjust some log level to avoid distraction 2025-11-01 20:52:13 +08:00
swung0x48 69a867a9a9 [Feat] (GLImpl/Getter): GL_UNIFORM_BUFFER_OFFSET_ALIGNMENT 2025-11-01 20:48:15 +08:00
swung0x48 fc745c402c [Feat] (GLImpl/Getter): GL_CONTEXT_PROFILE_MASK 2025-11-01 20:41:53 +08:00
BZLZHH d652645346 [Feat] (...): Handle pixel store correctly. 2025-11-01 19:52:33 +08:00
BZLZHH bcb947235d [Feat] (...): Implement scissor box in frontend and backend. 2025-11-01 16:40:38 +08:00
BZLZHH 708db4b5eb [Fix] (MG_Impl/Texture): Fix wrong function call for GL_TEXTURE_MAX_LEVEL. 2025-11-01 16:20:25 +08:00
BZLZHH 6c4340af43 [Feat] (MG_Backend/DirectGLES): Handle newly added params in backend. 2025-11-01 16:03:18 +08:00
BZLZHH cb768f9644 [Feat] (MG_Impl/Texture): Handle newly added params in TexParameter*. 2025-11-01 16:00:35 +08:00
BZLZHH 5ffc4d1e2d [Feat] (MG_Utils/Converters): Add converters for TextureSwizzleParam. 2025-11-01 15:51:58 +08:00
BZLZHH 4d8db7fb3b [Feat] (MG_State/TextureState): Implement full texture parameter track. 2025-11-01 15:49:16 +08:00
BZLZHH dfb08ac8b0 [Fix] (MG_Backend/DirectGLES): Ensure other methods for buffer syncing available. 2025-11-01 13:39:01 +08:00
BZLZHH e8d6cd4b31 [Feat] (...): Implement glDrawArrays. 2025-11-01 13:06:18 +08:00
BZLZHH 0ae69cfe9e [Fix] (MG_Impl/Getter): Fix wrong return value for GL_ACTIVE_TEXTURE. 2025-11-01 12:32:40 +08:00
BZLZHH 3858e8ebda [Fix] (MG_Impl/Getter): Fix crashing when object is nullptr in GetIntegerv. 2025-11-01 12:24:07 +08:00
BZLZHH 7abd9af8b6 [Fix] (MG_State/TextureState): Add missing TextureUnit::GetSamplerObject() 2025-11-01 12:03:20 +08:00
BZLZHH c4992797c7 [Feat] (MG_Impl/Getter): Implement basic GetIntegerv. 2025-11-01 11:59:12 +08:00
BZLZHH 394cf14198 [Feat] (MG_State/TextureObject): Add missing TextureObjectBase::GetExternalIndex() 2025-11-01 11:30:17 +08:00
BZLZHH 1269bc76f3 [Feat] (MG_State): Add external index getter for each object. 2025-11-01 11:18:35 +08:00
BZLZHH 8da681c720 [Fix] (MG_State/ProgramState): Handle version directive in shader source. 2025-11-01 10:07:36 +08:00
BZLZHH 9b0589840b [Fix] (MG_Test/VertexArrayTest): Allow default VAO. 2025-10-31 15:29:25 +08:00
BZLZHH d36e42103b [Feat] (MG_Impl/VertexArrayState): Allow VAO at index 0. 2025-10-31 14:40:47 +08:00
BZLZHH 731281eb61 [Feat] (MG_State/VertexArrayState): Implement default VAO at index 0. 2025-10-31 14:40:14 +08:00
BZLZHH 6959405518 [Fix] (MG_Impl/TextureImpl|FramebufferImpl): Handle texture 0. 2025-10-31 14:13:38 +08:00
BZLZHH 73f8b88b5c [Fix] (MG_Backend): Fix RendererInfoPtr not accessible. 2025-10-31 13:44:51 +08:00
BZLZHH d982928a23 [Improvement] (...): Optimize code. 2025-10-31 13:29:48 +08:00
BZLZHH 2652a12fdc [Fix] (Scripts): Ensure full bar at 100% in formatting script. 2025-10-31 12:44:49 +08:00
swung0x48 e190f3887d [Feat] (GLImpl/Sync): manifold for Sync 2025-10-30 22:59:39 +08:00
swung0x48 b82c481605 [Feat] (MG_Backend/DirectGLES, GL_Impl/Getter): hardcode getter, sync some sampler parameters 2025-10-29 16:39:03 +08:00
swung0x48 683d8b35bf [Feat] (MG_Impl/Exporting): Unstub MapBufferRange 2025-10-29 16:36:30 +08:00
swung0x48 2416225502 [Fix] (MG_State/ProgramState): select correct binary to do reflection 2025-10-29 10:28:59 +08:00
swung0x48 1d00808719 [Fix] (MG_Util/Types): Memcpy really should not be constexpr 2025-10-29 09:20:50 +08:00
swung0x48 798898b9ad [Feat] (MG_Impl/GLImpl): relax check for DepthComponent32 to workaround misuse in Minecraft 1.21.5+ 2025-10-28 22:27:40 +08:00
swung0x48 6927f81754 [Feat] (MG_Backend/DirectGLES): properly implement BlitFramebuffer 2025-10-28 21:48:46 +08:00
swung0x48 0e01a7281e [Fix] (MG_State/GL_Texture): SubImage2D missing a row of texels 2025-10-28 16:57:06 +08:00
swung0x48 b3e7987985 [Fix] (MG_Backend/DirectGLES): properly sync integer vertex pointer 2025-10-28 15:43:35 +08:00
swung0x48 67475fcf34 [Fix] (MG_Backend/DirectGLES): properly bind global UBO 2025-10-28 14:46:57 +08:00
swung0x48 2597a184f0 [Fix] (MG_Backend/DirectGLES): sync more states at Clear() 2025-10-28 13:45:05 +08:00
swung0x48 de78e423fd [Fix] (MG_State/GL_Texture): take GL_UNPACK_SKIP_PIXELS and GL_UNPACK_SKIP_ROWS into account 2025-10-28 12:13:46 +08:00
swung0x48 7151080a67 [Fix] (Types, GL_Texture): Memcpy insanity, proxy texture fix 2025-10-28 11:49:08 +08:00
swung0x48 bd01e4f99d [Fix] (MG_Util/TextureMetrics, MG_State/Texture): reimplement TextureMetrics, attempting to fix glTexSubImage2D 2025-10-28 10:17:56 +08:00
swung0x48 507476d513 [Feat] (MG_Backend/DirectGLES): sync PBO 2025-10-27 17:00:42 +08:00
swung0x48 56c6d73185 [Feat] (MG_State/ProgramObject, MG_Backend/DirectGLES): bind texture to uniform in backend 2025-10-27 15:45:36 +08:00
swung0x48 460b7a6eb3 [Chore] (MG_Backend/DirectGLES/Manager): log backend glGetError on failure 2025-10-27 14:25:31 +08:00
swung0x48 9883ab47fa Merge branch 'dev' into Feat/Backend-Direct-GLES 2025-10-27 13:42:31 +08:00
swung0x48 5b3d5c998a [Feat] (MG_State/ProgramObject, MG_State/GL_Program): implement sampler unit in program state 2025-10-27 13:17:42 +08:00
swung0x48 8e5cc46577 [Chore] (MG_State/ProgramObject): directly use TProgram for reflection 2025-10-27 12:59:55 +08:00
BZLZHH e31f3b8057 Merge branch 'dev' into Feat/Backend-Direct-GLES 2025-10-27 12:06:51 +08:00
BZLZHH 47ea1788db [Chore] (All): Format code. 2025-10-27 12:03:05 +08:00
BZLZHH ea9fc4dbe8 [Improvement] (MG_Backend/DirectGLES): Remove unused code. 2025-10-27 12:01:04 +08:00
swung0x48 034aeb9b12 [Fix] (MG_State/GL_Program): wrong guard condition in Uniformv_State 2025-10-27 11:20:23 +08:00
swung0x48 5e5d0f3dbe [Feat] (MG_Test/Program): add test for real shader (Minecraft position_tex) 2025-10-27 10:53:06 +08:00
swung0x48 d73bd5dcd2 [Fix] (MG_State/ProgramObject): Properly allocate location for location-not-explicitly-defined uniforms 2025-10-27 10:51:41 +08:00
swung0x48 b91f180c7b [Fix]: fix compilation on Windows again 2025-10-26 23:06:28 +08:00
swung0x48 f951f0451f [Chore] (MG_Test/ProgramTest): add more checks to ProgramTest 2025-10-26 23:00:48 +08:00
swung0x48 63295b5493 [Chore]: fix compilation on Windows 2025-10-26 22:43:42 +08:00
BZLZHH 5da6a0e05e [Fix] (MG_Backend/DirectGLES): Actually compile shader and use.
* TODO: remove junk code.
2025-10-26 11:43:10 +08:00
BZLZHH b8d8188239 [Improvement] (MG_Backend/DirectGLES): Make most stuff const auto& 2025-10-26 09:56:56 +08:00
BZLZHH d90e35d630 [Fix] (MG_Backend/DirectGLES): Fix wrong buffer data in sync. 2025-10-26 09:50:05 +08:00
BZLZHH 21d659214f [Fix] (MG_Backend/DirectGLES): Fix default FBO. 2025-10-26 09:25:17 +08:00
BZLZHH 60129e1a61 [Fix] (MG_Backend/DirectGLES): Bind current state. 2025-10-19 12:28:15 +08:00
BZLZHH 6423a32a2e [Fix] (MG_Backend/DirectGLES|MG_State/BufferState): Fix crash. 2025-10-19 12:04:45 +08:00
BZLZHH 93a0bbaed8 [Feat] (MG_Backend/DirectGLES): Implement basic stuff for DirectGLES backend. 2025-10-19 11:47:44 +08:00
BZLZHH ef2221659a [Misc] (MG_Impl/Drawing): Test glClear in backend. 2025-10-06 16:21:02 +08:00
BZLZHH bd1056f9c9 [Feat|Fix] (...): Add/Fix lots of stuff, being able not to crash in MC. 2025-10-06 16:08:35 +08:00
BZLZHH e37dedb72d [Feat] (...): Basic ability to load GLES/EGL. 2025-10-06 11:47:27 +08:00
BZLZHH 7275df3d60 [Chore] (MG_Backend/Backends): Rename MG-Dir-GLES to Espryt. 2025-10-06 10:32:15 +08:00
BZLZHH 5e42d15c61 [Feat] (MG_Util/BackendLoaders): Add GLES/EGL backend loader. 2025-10-06 01:32:55 +08:00
BZLZHH bcb02fe5e6 [Chore] (MG_Backend/Backends): Add DirectGLES and use. Rename renderer names of Diligent ones. 2025-10-06 01:06:50 +08:00
BZLZHH 834a40247c [Chore] (Workflows): Run on branch . 2025-10-06 00:14:58 +08:00
BZLZHH e77b01ac84 [Feat] (MG_Impl/RenderState): Implement some RenderState GL functions. 2025-10-03 13:16:42 +08:00
BZLZHH f7df90447b [Feat] (MG_Util/Converters): Implement converters related to RenderState enum. 2025-10-03 12:45:52 +08:00
BZLZHH 30d4964a5e [Improvement] (MG_State/RenderState): Remove redundant cullFaceEnabled setter/getter. 2025-10-03 12:25:36 +08:00
BZLZHH 1e2922faa5 [Fix] (MG_Impl/GLImpl): Fix missing header file in Exporting.h 2025-10-02 23:53:56 +08:00
BZLZHH 4a303184e4 [Feat] (MG_Impl/Framebuffer): Implement essential framebuffer functions. 2025-10-02 23:42:14 +08:00
BZLZHH e2e7ee93db [Fix] (MG_Util/Converters): Fix incorrect functions in MGToGL/FramebufferEnumConverter.cpp 2025-10-02 22:47:33 +08:00
BZLZHH 87f487c3aa [Feat] (MG_Util/Converters): Implement converters related to framebuffer enum. 2025-10-02 22:30:17 +08:00
BZLZHH 3ba1842758 [Fix] (MG_State/FramebufferState): Fix missing functions. 2025-10-02 21:44:11 +08:00
BZLZHH d6b54f8e30 [Feat] (MG_State/FramebufferState): Implement FramebufferAttachment, FramebufferObject and FramebufferState. 2025-10-02 21:27:33 +08:00
BZLZHH 776e1d99cf [Feat] (MG_State/TextureState): Implement TextureObjectBase::IsComplete. 2025-10-02 20:22:12 +08:00
BZLZHH ee971306ca [Misc] (All): Run format_code.sh 2025-10-02 15:11:38 +08:00
BZLZHH 69fe996e15 [Feat] (Scripts): Introduce format_code.sh 2025-10-02 15:10:21 +08:00
BZLZHH 14415d42a9 [Fix] (MG_Test/VertexArrayTest): Fix incorrect check in General_BindWithoutCreation. 2025-10-02 14:39:49 +08:00
BZLZHH 000a2ba3a7 [Perf] (MG_Util/Misc): Reimplement IndexGenerator. 2025-10-02 14:22:03 +08:00
BZLZHH 19a965c1ef [Improvement] (MG_Util/Types): Use FastSTL::unordered_map as the default implementation. 2025-10-02 11:11:35 +08:00
BZLZHH 968d645d17 [Chore] (FastSTL): Add FastSTL as submodule. 2025-10-02 10:55:16 +08:00
BZLZHH f865d231d0 [Chore] (MG_Backend/Backends): Upgrade target OpenGL version to 3.3
* This is to align target OpenGL version with Minecraft 25w37a, which raised the minimum required OpenGL version to 3.3
* With this upgrade, the following features become part of the project's possible implementation scope:
  - Sampler Objects (ARB_sampler_objects)
  - Instanced arrays (ARB_instanced_arrays)
  - Explicit attribute locations (ARB_explicit_attrib_location)
  - Dual-source blending (ARB_blend_func_extended)
  - Timer queries (ARB_timer_query)
* These capabilities may be leveraged in future work depending on project needs
2025-09-14 07:47:33 +08:00
BZLZHH 7310071945 Merge branch 'dev' of github.com:MobileGL-Dev/MobileGL into dev 2025-09-14 07:31:39 +08:00
BZLZHH 1c85d133e4 [Docs] (README): Fix typo. 2025-09-08 12:10:03 +08:00
BZLZHH 32f2b1fbb6 [Feat] (MG_Benchmark/BufferBench): Implement BufferBench. 2025-09-06 13:10:44 +08:00
BZLZHH 6d6bec3d3e [Fix] (MG_State/BufferState): Fix compiling warning. 2025-09-06 12:11:55 +08:00
BZLZHH be46765c56 [Feat] (MG_State/RenderState): Implement RenderState. 2025-09-06 10:02:01 +08:00
BZLZHH 4d45bfc242 [Feat] (MG_Util/Math): Enhance vector types. 2025-09-06 09:36:19 +08:00
BZLZHH 84b2192ca1 [Chore] (3rdparty): Update SPIRV-Cross. 2025-09-06 09:02:17 +08:00
BZLZHH fd82a2495f [Improvement] (MG_State/TextureState): Mark the mipmap as dirty by default. 2025-09-06 08:53:11 +08:00
BZLZHH 57aba42dd7 Merge branch 'dev' of github.com:MobileGL-Dev/MobileGL into dev 2025-08-26 17:56:42 +08:00
swung0x48 445f55af92 [Fix]: guard against dlsym 2025-08-25 20:08:42 +08:00
swung0x48 701e93f26d [Fix] (buildsystem): add /EHsc for msvc 2025-08-25 17:34:53 +08:00
BZLZHH e4c61a926a Merge branch 'dev' of github.com:MobileGL-Dev/MobileGL into dev 2025-08-25 17:15:58 +08:00
swung0x48 7b9c154f85 [Fix] (workflow): fix wrong run path 2025-08-25 16:27:33 +08:00
swung0x48 c601169b84 [Fix] (buildsystem): revert back to use 4 threads to compile 2025-08-25 16:15:32 +08:00
swung0x48 e5b91eaeba [Fix] (buildsystem): enable PIC 2025-08-25 16:13:39 +08:00
swung0x48 f5c3f12746 [Chore] (workflow): attempt to get rid of swap 2025-08-25 16:08:25 +08:00
swung0x48 c8e46fb6e2 [Chore] (workflow): let's build with all the cores available 2025-08-25 16:04:31 +08:00
swung0x48 281a28f901 [Fix] (workflow): add -DCMAKE_POLICY_VERSION_MINIMUM=3.5 to silence cmake version check 2025-08-25 16:00:35 +08:00
swung0x48 c723d1c9b9 [Fix] (workflow): fix typo 2025-08-25 15:58:01 +08:00
swung0x48 d9e7b9c975 [Fix] (workflow): Update glslang external sources 2025-08-25 15:53:20 +08:00
swung0x48 5354ff04c6 [Fix] (workflow): fix typo 2025-08-25 15:49:18 +08:00
swung0x48 69f7dda3de Merge branch 'dev' of https://github.com/MobileGL-Dev/MobileGL into dev 2025-08-25 15:47:11 +08:00
swung0x48 3513e3bffe [Refactor] (buildsystem, 3rdparty): link test and benchmark to MobileGL library 2025-08-25 15:46:59 +08:00
BZLZHH b86a749b00 Merge branch 'dev' of github.com:MobileGL-Dev/MobileGL into dev 2025-08-25 15:21:20 +08:00
BZLZHH 262e2be9cb [Feat] (MG_Impl/Texture): Implement TexSubImage2D. 2025-08-25 15:21:08 +08:00
BZLZHH b92bc0b44a [Feat] (MG_State/TextureState): Add dirty mark for MipmapLevelInternal. 2025-08-25 15:18:34 +08:00
BZLZHH 427e069085 [Feat] (MG_State/TextureState): Implement GetMipmap for TextureObject. 2025-08-25 15:13:01 +08:00
swung0x48 a19c0a214a [Chore] (buildsystem): fix compilation and linking on Windows when building 3rdparty from source 2025-08-25 14:53:22 +08:00
BZLZHH 86a68df114 Merge branch 'dev' of github.com:MobileGL-Dev/MobileGL into dev 2025-08-25 14:22:30 +08:00
swung0x48 aebfa2745a [Chore] (3rdparty): add glslang and SPIRV-Cross as submodules 2025-08-25 14:10:43 +08:00
swung0x48 2be199bad8 [Refactor] (buildsystem): make MG_Benchmark also use FindXXX.cmake 2025-08-25 13:46:00 +08:00
swung0x48 700d72f180 [Refactor] (buildsystem): don't require SPIRV-Tools 2025-08-25 13:30:48 +08:00
swung0x48 fae9bcd0df [Refactor] (buildsystem): use FindXXX.cmake to find 3rdparty libraries 2025-08-25 12:30:32 +08:00
swung0x48 591f61a9f0 [Feat] (MG_Benchmark/Program): add linking benchmark, add more metrics to benchmarks 2025-08-25 09:28:55 +08:00
swung0x48 a5ab9fe503 [Chore] (MG_State/Program): get rid of junk printing when linking 2025-08-25 09:28:09 +08:00
swung0x48 556d47a9d5 [Benchmark] (MG_Benchmark/Program): shader compilation benchmark 2025-08-24 12:56:24 +08:00
swung0x48 620391b7ec [Test] (MG_Test/ProgramTest/UniformLocationGaps): add test to check uniform locations with gap 2025-08-22 17:53:42 +08:00
swung0x48 0da2a59e4d [Test] (MG_Test/ProgramTest/UniformMatrixFunctions): get rid of junk 2025-08-22 17:35:38 +08:00
swung0x48 ee129c4fb6 [Test] (MG_Test/ProgramTest/UniformMatrixTranspose): hard assert that uniforms to be tested exists 2025-08-22 17:34:13 +08:00
swung0x48 c33056fd8e [Feat] (MG_State/Program): glUniformMatrix* with transpose, 2025-08-22 17:29:31 +08:00
swung0x48 7a7f6a0533 [Feat] (MG_Util/Metrics): GetGLTypeSize 2025-08-22 17:29:25 +08:00
BZLZHH 03cf61441b Merge branch 'dev' of github.com:MobileGL-Dev/MobileGL into dev 2025-08-22 16:21:51 +08:00
swung0x48 2be194c147 [Feat] (MG_State/Program): glUniformMatrix* without transpose 2025-08-22 15:47:14 +08:00
swung0x48 bc46cb9c5f [Feat] (MG_State/Program): glUniform*v 2025-08-22 14:58:24 +08:00
swung0x48 476de2b8f7 [Feat] (MG_State/Program): Get current program 2025-08-21 22:48:20 +08:00
swung0x48 2617903e71 [Feat] (MG_State/Program): GetActiveAttrib 2025-08-18 14:32:03 +08:00
swung0x48 cb59bc0431 [Feat] (MG_State/Program): generate program binary (SPIR-V), reflect generated ubo size/offsets 2025-08-18 11:10:24 +08:00
swung0x48 2036caa4a0 [Chore] (MG_State/Program): remove shaderTypes from ProgramAttrib 2025-08-18 09:50:30 +08:00
swung0x48 f6a0042356 [Chore] (workflow): don't debug output by default 2025-08-16 23:40:30 +08:00
swung0x48 dc1a344cf5 [Feat] (MG_Test/Program): Test for GetAttribLocation/BindAttribLocation 2025-08-16 23:10:52 +08:00
swung0x48 a072c2fc70 [Feat] (MG_State/Program): GetAttribLocation 2025-08-16 23:10:12 +08:00
swung0x48 6416788856 [Fix] (MG_State/Program): skip attrib location binding when it is not active at the first place 2025-08-16 22:54:31 +08:00
swung0x48 f328f71f62 [Feat] (MG_State/Program): BindAttribLocation 2025-08-16 22:51:21 +08:00
swung0x48 d6620959b3 [Feat] (MG_State/Program): BindAttribLocation WIP 2025-08-16 22:50:46 +08:00
BZLZHH e50d4bb19c [Chore] (clang-format): Upload .clang-format 2025-08-15 18:27:35 +08:00
BZLZHH a21dcae309 Merge branch 'dev' of github.com:MobileGL-Dev/MobileGL into dev 2025-08-15 18:22:03 +08:00
swung0x48 13a5fd9761 [Chore] (MG_State/Program): un-implement ValidateProgram 2025-08-15 17:51:14 +08:00
swung0x48 5a729cd02e [Feat] (MG_State/Program): GetShaderiv 2025-08-15 17:42:30 +08:00
swung0x48 a050248982 [Feat] (MG_State/Program): GetProgramiv: GL_ACTIVE_UNIFORM_BLOCKS, GL_ACTIVE_UNIFORM_BLOCK_MAX_NAME_LENGTH 2025-08-15 17:31:58 +08:00
swung0x48 ec95c0401a [Feat] (MG_State/Program): GetProgramiv WIP 2025-08-15 17:16:49 +08:00
swung0x48 ef5b7cd99a [Refactor] (MG_State/Program): get rid of spvc junk 2025-08-15 15:58:25 +08:00
swung0x48 4aa70fda65 [Refactor] (MG_State/Program): refractor uniform reflection using glslang reflection API 2025-08-15 15:49:31 +08:00
swung0x48 a4769996c3 [Feat] (MG_Util/ShaderCompiler): separates GetSpirvBinaryFromProgram() from LinkProgram() 2025-08-15 09:35:05 +08:00
swung0x48 7bece3f8c9 [Chore] (MG_Test): get rid of -g -O0 2025-08-15 09:00:40 +08:00
BZLZHH a2c5ed20de [Chore] (MG_State/ProgramState): Remove printf. 2025-08-14 23:05:25 +08:00
swung0x48 a989cf9958 [Chore] (workflow): update Vulkan SDK version to 1.4.321.1 2025-08-14 22:09:46 +08:00
swung0x48 f4ec3c3997 [Fix] (MG_State/Program): add more prints in PostLink() to debug 2025-08-14 22:06:47 +08:00
swung0x48 c1966c5f04 [Fix] (MG_State/Program): does it still crash? 2025-08-14 21:23:55 +08:00
swung0x48 634fb4fa57 [Chore] (MG_State/Program): revert PostLink() 2025-08-14 20:12:18 +08:00
swung0x48 0a3fd42019 [Chore] (workflow): Does debug build spit errors? 2025-08-14 20:08:39 +08:00
swung0x48 94508f6395 [Chore] (MG_State/Program): PostLink bisect 2 2025-08-14 20:06:29 +08:00
BZLZHH 5ee9b44f3b [Chore] (MG_Test/CMake): Set debug build type and flags. 2025-08-14 18:52:24 +08:00
BZLZHH c624cc1b0c [Refactor] (MG_Impl/Texture): Optimize code. 2025-08-14 18:48:03 +08:00
BZLZHH 62922288a1 Merge branch 'dev' of github.com:MobileGL-Dev/MobileGL into dev 2025-08-14 18:35:14 +08:00
BZLZHH 675ee4915b [Feat|Fix] (MG_Impl/Texture): Implement TexImage2D & related stuff. 2025-08-14 18:32:37 +08:00
swung0x48 3743922d4d [Chore] (MG_Test/Program): bisect PostLink() no.1. 2025-08-14 17:51:42 +08:00
swung0x48 0cba505ad0 [Chore] (MG_Test/Program): test if PreLink only passes 2025-08-14 17:41:50 +08:00
swung0x48 a39a46c7e3 [Chore] (MG_Test/Program): try to not link program? 2025-08-14 17:36:33 +08:00
swung0x48 1c1d3e00a2 [Fix] (MG_Test/Program): Free context at teardown 2025-08-14 17:32:35 +08:00
swung0x48 c9fd4ecb8f [Fix] (MG_Test/Program): use Setup() instead of ctor 2025-08-14 17:20:33 +08:00
swung0x48 a4556a3742 [Chore] (MG_Test/Program): add test prints 2025-08-14 15:45:47 +08:00
swung0x48 fc74360fd2 Merge branch 'dev' of https://github.com/MobileGL-Dev/MobileGL into dev 2025-08-14 15:32:56 +08:00
swung0x48 4ce1b33304 [Feat] (MG_State/Program): Uniform* got aliased to Uniform*v 2025-08-14 15:32:05 +08:00
BZLZHH f713a3785b [Feat] (MG_Util/Converters): Add converters for TextureUploadTarget and additional TextureTarget. 2025-08-14 15:21:48 +08:00
BZLZHH 115cdef6fd [Feat] (MG_State/TextureState): Add TextureUploadTarget enum. Add more TextureTarget enum. 2025-08-14 15:19:32 +08:00
swung0x48 238d0ffade [Feat] (MG_State/Program): GetActiveUniform 2025-08-14 13:50:34 +08:00
swung0x48 eb926848be [Feat] (MG_Util/Converters/SpvcTypeConverter): covert spvc types to GLenum 2025-08-14 13:49:18 +08:00
swung0x48 238d63cff7 [Fix] (MG_Util/glsl/UniformTraverser): get rid of samplers from retrieved uniforms 2025-08-14 13:48:18 +08:00
swung0x48 70b440839d [Feat] (MG_Util/SpvcSession): reflect member types from SPIR-V binary 2025-08-14 10:33:15 +08:00
swung0x48 bb75045584 [Test] (MG_Test/Program): test for glGetUniformLocation 2025-08-13 23:32:40 +08:00
swung0x48 aa2aefac28 [Feat] (MG_State/Program): glGetUniformLocation 2025-08-13 23:32:33 +08:00
swung0x48 5422dcf164 [Test] (MG_Test/Program): add simple integration test for shader/program state machine 2025-08-13 23:15:05 +08:00
swung0x48 df444655e3 [Feat] (MG_State/Program): retrieve/generate layout location from/for program, and retrieve generated ubo size and all the offsets of members 2025-08-13 23:14:22 +08:00
BZLZHH b7d5de7ce0 [Feat] (MG_Impl/Texture): Implement IsTexture, ActiveTexture. 2025-08-13 21:59:17 +08:00
BZLZHH ded4ef195f Merge branch 'dev' of github.com:MobileGL-Dev/MobileGL into dev 2025-08-13 21:53:35 +08:00
BZLZHH b48e632829 [Fix] (MG_Impl/Buffer): Don't produce gl error in IsBuffer. 2025-08-13 21:52:29 +08:00
swung0x48 09d1e035ed Revert "[Fix] (MG_State/Program): use vector to save uniforms instead"
This reverts commit bfb62872c9.
2025-08-13 17:05:21 +08:00
swung0x48 bfb62872c9 [Fix] (MG_State/Program): use vector to save uniforms instead 2025-08-13 16:41:46 +08:00
swung0x48 d1942bc57d [Feat] (MG_Test/Program): test uniform without location 2025-08-13 16:31:15 +08:00
swung0x48 7f0e65f8c7 [Feat] (MG_Util/ShaderCompiler, MG_State/Program): reflect uniform location 2025-08-13 15:18:34 +08:00
swung0x48 5e1407ec95 Merge branch 'dev' of https://github.com/MobileGL-Dev/MobileGL into dev 2025-08-13 14:20:36 +08:00
swung0x48 00f5741f7f [Feat] (MG_Util/ShaderCompiler): add new item to ShaderCompileBits and implement it 2025-08-13 14:19:37 +08:00
BZLZHH a347a9780c [Feat] (MG_Impl/Texture): Implement GenTextures, DeleteTextures, BindTexture. 2025-08-12 18:17:23 +08:00
BZLZHH 7ba3258150 [Feat] (MG_Impl/Texture): Implement basic validators for texture. 2025-08-12 18:17:14 +08:00
BZLZHH 4eba014513 [Fix] (MG_State/TextureState): Fix incorrect behavior. 2025-08-12 18:11:36 +08:00
BZLZHH a78c53ecdd [Feat] (MG_Util/Converters): Implement texture enum converters. 2025-08-12 18:05:02 +08:00
BZLZHH 256e947a5d [Fix] (MG_Impl/VertexArray|Buffer): Fix incorrect name zero operations. 2025-08-12 16:54:56 +08:00
BZLZHH 5127479874 [Chore] (CMake): Remove libshaderconv.so 2025-08-12 15:30:16 +08:00
BZLZHH 0a95d64f2b [Chore] (CMake): Support more platforms. 2025-08-12 15:28:12 +08:00
BZLZHH c50d5255ec [Chore] (CMake): Remove unnecessary args. 2025-08-12 14:55:50 +08:00
swung0x48 1f7053cb31 [Feat] (MG_State/Program): GetProgramInfoLog, GetShaderInfoLog 2025-08-11 23:37:58 +08:00
BZLZHH 323df933c4 Merge remote-tracking branch 'origin/dev' into dev 2025-08-11 23:26:25 +08:00
BZLZHH 2b685e4e18 [Fix] (MG_Impl/GLImpl): Fix missing header. 2025-08-11 23:25:21 +08:00
swung0x48 af32784f37 [Feat] (MG_State/Program): GetShaderSource 2025-08-11 23:19:10 +08:00
swung0x48 408b62a495 [Feat] (MG_State/Program): GetAttachedShaders 2025-08-11 23:07:15 +08:00
swung0x48 21a46ee151 [Feat] (MG_State/Program): glShaderSource, glUseProgram 2025-08-11 16:47:18 +08:00
swung0x48 7517711308 [Chore] (workflow): test 4 parallel jobs 2025-08-11 16:15:32 +08:00
swung0x48 19071c0217 [Fix] (MG_State/Program): typo in ProgramState::CreateProgram 2025-08-11 16:02:42 +08:00
BZLZHH eb9866cd87 Merge remote-tracking branch 'origin/dev' into dev 2025-08-11 15:57:28 +08:00
BZLZHH b7ecc69cfb [Misc] (MG_Impl/Texture): Add texture function stubs. 2025-08-11 15:56:04 +08:00
swung0x48 429618a00a [Feat] (MG_Impl/Program): glAttachShader 2025-08-11 15:50:24 +08:00
swung0x48 4ec815a383 [Feat] (MG_Impl/Program): use helper functions to simplify the code 2025-08-11 15:40:17 +08:00
swung0x48 2c40177f06 [Feat] (MG_Impl/Program, MG_State/Program): initial impl of shader related states 2025-08-11 15:19:35 +08:00
swung0x48 9944408104 [Chore] (workflow): Force single-threaded compilation on CI 2025-08-11 13:27:55 +08:00
swung0x48 e96e0ecc42 [Fix] (MG_State/Program): fix ShaderObject compilation error 2025-08-11 13:12:50 +08:00
swung0x48 ace0b6d226 [Fix] (workflow): Enable swap on CI in an effort to
prevent compiler processes getting killed
2025-08-11 13:07:34 +08:00
swung0x48 99a8726506 [Chore] (MG_Test): move library finding to parent CMakeList and link libraries to all the test targets 2025-08-11 12:52:44 +08:00
BZLZHH 1ca0a96628 [Fix] (MG_Test): Fix compiling error. 2025-08-10 23:34:15 +08:00
BZLZHH fefccf808a [Fix] (MG_Util): Fix compiling error. 2025-08-10 23:24:49 +08:00
BZLZHH 98efe13ac5 Merge commit '12335da41bc30334c599dfc1d2e5b47dcf92ef0d' into dev 2025-08-10 23:18:41 +08:00
BZLZHH 253e14f2c9 [Improvement] (...): Optimize code. 2025-08-10 23:18:01 +08:00
BZLZHH 0b13cb5714 [Feat] (MG_State/TextureState): Implement TextureState. 2025-08-10 23:13:22 +08:00
swung0x48 12335da41b [Chore] (MG_Test): add missing includes in tests 2025-08-09 23:53:02 +08:00
BZLZHH 93ca669929 [Refactor] (All): Restructure include system. 2025-08-09 23:10:34 +08:00
BZLZHH a8914c09ce [Docs] (README): Correct expression in notice. 2025-08-09 13:12:33 +08:00
swung0x48 4ecd4e4a07 [Feat] (MG_State/Program, MG_Impl/Program): skeleton and initial impl of program/shader state machine 2025-08-09 13:08:26 +08:00
BZLZHH 4b4b876a25 [Docs] (README): Remove progress. 2025-08-09 12:57:50 +08:00
swung0x48 e848ca8730 [Chore] (MG_Test/Program): rename previous ProgramTest to ProgramUtilTest 2025-08-09 12:38:33 +08:00
swung0x48 c34f816544 [Fix] (Includes.h): Add WIN32_LEAN_AND_MEAN to get rid of Windows.h garbage includes 2025-08-08 23:42:52 +08:00
swung0x48 919274924e [Feat]: Flags<Bit, Underlying> template for manipulating flag sets 2025-08-08 16:49:41 +08:00
swung0x48 916fdf40af [Feat] (MG_Util/ShaderCompiler): extract global UBO offset from GL plain uniforms 2025-08-08 13:46:08 +08:00
swung0x48 fcd52a9177 [Fix] (MG_Util/ShaderCompiler): make glslang don't emit demote to replace discard 2025-08-08 10:30:25 +08:00
swung0x48 38c0a54fcc [Feat] (MG_Util/ShaderTranspiler): separate SpvcSession 2025-08-07 12:53:51 +08:00
swung0x48 70d66d320f [Fix] (MG_Util/Debug): pthread_getname_np also works on __APPLE__ 2025-08-06 21:09:45 +08:00
BZLZHH b44950bddd [Chore] (CMake): Add DOWNLOAD_EXTRACT_TIMESTAMP for benchmark fetch. 2025-08-06 18:27:35 +08:00
BZLZHH fa2bf8b665 Merge commit '54826327' into dev 2025-08-06 18:09:18 +08:00
BZLZHH 75f0d27ca7 [Misc] (...): Fix CMake error. Fix unexpected error. 2025-08-06 18:04:11 +08:00
swung0x48 548263279e [Feat] (MG_Util/ShaderTranspiler): POC to query member offsets from UBO 2025-08-06 17:14:01 +08:00
swung0x48 cbf6019d92 [Chore] (workflow): fix some wording 2025-08-06 13:58:19 +08:00
swung0x48 70614b769a [Fix] (MG_Benchmark/Sanity): add missing include 2025-08-06 13:49:32 +08:00
swung0x48 8501745c43 [Fix] (workflow): fix CI for benchmark 2025-08-06 13:45:45 +08:00
swung0x48 510c2fa01e [Chore] (workflow): setup CI for benchmarks 2025-08-06 13:41:10 +08:00
swung0x48 3606b80016 [Chore] (MG_Benchmark): add benchmark 2025-08-06 13:25:24 +08:00
swung0x48 2c651f2359 [Optimization] (MG_State/BufferState, VertexArrayState): optimize performance on vao deletion 2025-08-06 10:32:16 +08:00
BZLZHH 25fa70ff9d [Chore] (Workflow): Rename Feat/Rewriting to dev. 2025-08-05 18:58:36 +08:00
BZLZHH d52c3ddfde [Chore] (gitignore): Ignore clangd file. 2025-08-05 18:58:36 +08:00
BZLZHH a696fb2350 [Fix] (MG_Impl/Buffer): Fix incorrect return outside if. 2025-08-05 18:58:26 +08:00
BZLZHH e8af08aff0 [Chore] (gitignore): Ignore Visual Studio Code directory. 2025-08-05 18:35:35 +08:00
BZLZHH 3d18e702b0 [Fix] (MG_State/BufferState, VertexArrayState): Correct IBO binding slot. 2025-08-03 18:56:50 +08:00
swung0x48 972a4efed1 Revert "[Chore] (MG_Util/Program): use SPIRV-Cross C++ API instead of C ones"
This reverts commit 8e0284faec.
2025-08-02 18:01:36 +08:00
swung0x48 8e0284faec [Chore] (MG_Util/Program): use SPIRV-Cross C++ API instead of C ones 2025-08-02 12:25:08 +08:00
BZLZHH 26a9cafcb8 [Fix] (MG_Test): Fix compiling error. 2025-07-25 21:42:15 +08:00
BZLZHH 47f7039720 [Feat] (All): Continue building the basic structure.
Feat: implement MG_Impl/VertexArray
Feat: add tests about MG_Impl/VertexArray
Feat: add several converters
Feat: implement IsBuffer
2025-07-25 21:36:14 +08:00
BZLZHH e7a21423da [Feat] (MG_State/VertexArrayState): Add IsInteger in attribute. 2025-07-25 19:28:40 +08:00
BZLZHH 17bd9801e0 [Fix] (MG_Test/BufferTest): Fix compiling error. 2025-07-25 17:02:59 +08:00
BZLZHH 6b66608354 [Feat] (MG_Test/VertexArrayTest): Implement VertexArrayTest. 2025-07-25 16:53:10 +08:00
BZLZHH 4154d3f4ee [Feat] (MG_State/VertexArrayState): Implement VertexArrayState. 2025-07-25 16:52:38 +08:00
BZLZHH fc9018f97c [Misc] (MG_State/Buffer): Separate BufferState.cpp into 2 files. 2025-07-25 14:06:51 +08:00
BZLZHH 5962499147 [Improvement] (MG_Util/Misc): Replace byte array with 64-bit bitmap in IndexGenerator. 2025-07-25 12:40:38 +08:00
BZLZHH e79a2fa809 [Feat|Fix|Improvement] (All): Continue building the basic structure.
Feat: implement MG_Impl/Buffer
Feat: implement MG_State/ErrorState and integrate it into MG_State/GLContext
Feat: add buffer deletion management
Feat: introduce `INSERTION_POINT` (https://github.com/MobileGL-Dev/MobileGLCodeManager)
Feat: add tests about MG_Impl/Buffer and buffer deletion feature
Feat: add several converters
Fix: fix some compiling errors
Fix: fix some incorrect behaviors in MG_State/Buffer
Improvement: remove some current statements at the beginning of the source file, which will be added uniformly soon
Improvement: optimize some naming
2025-07-23 23:04:36 +08:00
BZLZHH 06804d94f8 [Chore] (CMakeLists): Remove removed files. 2025-07-22 15:08:18 +08:00
swung0x48 d317f7f99b [Chore] (MG_Util/Program): auto generate ubo for plain GL uniforms 2025-07-22 13:03:06 +08:00
swung0x48 fa82c9b964 [Chore] (MG_Util/Program): SpvcSession rule-of-three? 2025-07-21 22:44:02 +08:00
swung0x48 01e71d7b5f [Chore] (MG_Util/Program): wraps spirv-cross-c 2025-07-21 21:39:04 +08:00
swung0x48 97a951fabb [Chore] (MG_Test/Program/CMakeLists.txt): fix compilation on macOS 2025-07-21 20:18:57 +08:00
swung0x48 bbd05fe8aa [Chore] (MG_Util/Program): test uniform linkage across stages 2025-07-21 17:51:06 +08:00
swung0x48 cb59412fd9 [Chore] (MG_Util/Program): test in/out linkage across stages 2025-07-21 17:40:16 +08:00
swung0x48 4dfbb789be [Chore] (MG_Util/Program): get rid of junk 2025-07-21 14:45:19 +08:00
swung0x48 1ad2513700 [Fix] (MG_Util/Program): program linking 2025-07-21 14:37:32 +08:00
swung0x48 bb396f8651 [Fix] (MG_Util/Program): fix sampler extraction 2025-07-21 11:11:26 +08:00
swung0x48 0afe4c4acb [Fix] (MG_Util/Program): fix UniformTraverser and add test for it 2025-07-21 10:47:05 +08:00
swung0x48 0dfd535c40 [Chore] (MG_Test/Program/CMakeLists.txt): use debug library on debug 2025-07-21 10:05:38 +08:00
swung0x48 f1ae8f0353 [Chore] (MG_Test/Program/CMakeLists.txt): tests compile on windows 2025-07-21 09:16:14 +08:00
swung0x48 4c9f0c5399 [Chore] (Include.h): remove strstream as it is deprecated 2025-07-20 21:59:17 +08:00
swung0x48 90a004cdd4 [Chore] (MG_Test/Program): find all components for SPIRV-Cross 2025-07-20 21:57:31 +08:00
swung0x48 94af204ed8 [Chore] (MG_Test/Program): include SPIRV-Cross 2025-07-20 21:56:00 +08:00
swung0x48 bff7711e2c [Fix] (MG_Test/Program): fix CompileSimpleFragmentShader 2025-07-20 21:07:31 +08:00
swung0x48 ad041d6dab [CI] (3rdparty): attempting to install glslang 2025-07-20 20:02:47 +08:00
swung0x48 18675f72f3 [Feat] (MG_Util/ShaderTranspiler): Implement simple shader compile 2025-07-20 19:54:29 +08:00
BZLZHH 0388cd316b Merge remote-tracking branch 'origin/Feat/Rewriting' into Feat/Rewriting 2025-07-20 15:41:38 +08:00
BZLZHH bd2c5e1ebc [Improvement] (MG_Utils): Improve performance in IndexGenerator. 2025-07-20 15:33:55 +08:00
swung0x48 4665735c89 [Fix] (MG_State/Buffer): do not shrink_to_fit() if not necessary 2025-07-20 09:58:17 +08:00
swung0x48 ded2691155 [Fix] (MG_Test/BufferTest): fixed some assertions
Fixed:
    PingPong
2025-07-20 08:42:55 +08:00
BZLZHH 29a3704463 [Feat] (MG_Test/BufferTest): Add more buffer tests.
Added:
    GenerateManyNames_NoPrematureCreation
    AcquireMemory
    AcquireMemoryRangeWithoutExplicit
    AcquireMemoryRangeWithExplicit
    CopyBufferSubData
    WriteWhileMapped
    PartialUpdate
2025-07-20 02:31:57 +08:00
BZLZHH 6c920ce5dc [Feat|Fix] (MG_State/BufferState): Implement more functions.
Implemented:
    BufferObject: ReleaseMemory, FlushMemoryRange, UploadSubData, CopyDataFrom, ClearDirty

Fixed:
    BufferObject: AcquireMemory, AcquireMemoryRange
    Range1D: UnionUpdate
2025-07-20 02:30:53 +08:00
BZLZHH 46da761dcf [Chore] (gitignore): Ignore Visual Studio directory and output directory. 2025-07-19 23:45:51 +08:00
BZLZHH 3ae519d600 [Fix] (All): Prevent Windows.h from defining min and max macros. 2025-07-19 23:19:27 +08:00
swung0x48 8a9340749d [Chore] (github): CI tests 2025-07-19 22:59:45 +08:00
swung0x48 16697b8c2b [Fix] (MG_State/Buffer): pass PingPong test 2025-07-19 22:00:01 +08:00
swung0x48 6f455bc26a [Test] (MG_Test/Program): add Sanity test 2025-07-19 21:33:28 +08:00
swung0x48 ba485e4adc [Fix] (MG_Util/Program): use std::string instead of to_string 2025-07-19 21:32:47 +08:00
swung0x48 509f3d2879 [Feat] (MG_State/Buffer): separate UploadData() into Resize()+UploadData() 2025-07-18 10:02:08 +08:00
swung0x48 0d73120d15 [Feat] (MG_State/Buffer): separate UploadData() into Resize()+UploadData() 2025-07-18 10:01:40 +08:00
swung0x48 99eaf317ba [Feat] (Range1D): IntersectionUpdate 2025-07-17 23:09:24 +08:00
swung0x48 3f0a99d272 [Fix] (MG_State/Buffer): fix some typo 2025-07-17 22:46:16 +08:00
swung0x48 5c1b0a8f10 [Test] (BufferTest): add Binding test, and fix compile errors 2025-07-17 22:15:31 +08:00
swung0x48 6de362cd1c [Fix] (Types.h): add typename specifier 2025-07-17 22:04:37 +08:00
swung0x48 e72c1f70aa [Fix] (MG_State/Buffer): remove redundant buffer target 2025-07-17 21:55:27 +08:00
swung0x48 f000ef4cbd [Fix] (MG_State/Core): fix typo 2025-07-17 21:39:06 +08:00
BZLZHH 7cabf01944 Merge remote-tracking branch 'origin/Feat/Rewriting' into Feat/Rewriting 2025-07-17 13:21:44 +08:00
BZLZHH ea64124963 [Feat] (MG_State/GLState): Implement BufferState. 2025-07-17 13:21:28 +08:00
swung0x48 6a2b122ab7 [Test] (MG_Test/Sanity): Setup basic sanity test. 2025-07-17 12:42:44 +08:00
BZLZHH 9604bdd50a [Fix] (Build): Remove missing source file. 2025-07-16 20:40:15 +08:00
BZLZHH 9ceff83c91 Merge remote-tracking branch 'origin/Feat/Rewriting' into Feat/Rewriting
# Conflicts:
#	CMakeLists.txt
#	MobileGL/Includes.h
2025-07-16 17:55:16 +08:00
BZLZHH 62be9fed93 [Feat] (MG_State/GLState): Implement BufferObject. 2025-07-16 17:51:42 +08:00
swung0x48 1d40f89dfe [Feat] (MG_Util/Compiler): shader compiler WIP 2 2025-07-16 17:25:49 +08:00
BZLZHH 1ee6a1349c [Fix] (MG_Impl/GL): Correct GL_SHADING_LANGUAGE_VERSION in glGet. 2025-07-16 12:43:05 +08:00
BZLZHH b056e7be0a [Fix] (MG_Impl/GL): Correct GL_CONTEXT_PROFILE_MASK in glGet. 2025-07-16 12:10:04 +08:00
BZLZHH 38e3222c31 [Chore] (gitignore): Ignore CMakeSettings.json 2025-07-16 12:01:09 +08:00
swung0x48 8e1427fbd0 [Misc] (3rdparty): Update glslang to 15.4.0 2025-07-15 09:58:37 +08:00
swung0x48 ea30e0ee92 [Feat] (MG_Util/Compiler): shader compiler WIP 2025-07-13 21:14:18 +08:00
swung0x48 d6bdd6854f [Misc] (include): add missing headers in glslang 2025-07-13 09:13:06 +08:00
BZLZHH 9194e1c97f [Feat] (All): Continue building the basic structure. 2025-07-12 20:29:20 +08:00
BZLZHH 9542512209 [Feat] (MG_Util/Converter): Implement ConvertGLEnumToString. 2025-07-12 15:42:59 +08:00
BZLZHH c552bc6a4e [Chore] (Config): Rename log file name. 2025-07-11 19:18:59 +08:00
BZLZHH f928661045 [Feat] (MG_Impl/EGL): Implement a simplified egl temporarily. 2025-07-11 19:16:56 +08:00
BZLZHH 3078667e1d [Feat] (MG_Impl/GLX): Implement glXGetProcAddress. 2025-07-11 18:47:42 +08:00
BZLZHH 62e141000e [Fix] (All): Fix compiling error. 2025-07-11 18:20:50 +08:00
BZLZHH b76c23429f [Feat] (All): Implement init, log and other related components. 2025-07-11 18:09:45 +08:00
BZLZHH 0eed6f17a2 Merge remote-tracking branch 'origin/dev' into Feat/Rewritting 2025-07-11 16:39:41 +08:00
BZLZHH 08ca58c867 Merge commit '05493e5e150febc5a1ccf236465e3859f30021b2' into Feat/Rewritting
# Conflicts:
#	README.md
2025-07-11 16:34:57 +08:00
BZLZHH 614730543c Remove most stuff, ready to rewrite this project. 2025-07-11 16:26:10 +08:00
BZLZHH 8f950fc345 [Chore] (Global): Disable debug. Set log target to all. 2025-07-11 09:17:57 +08:00
BZLZHH 83cfacf94b [Fix] (MG_State/Buffer): Prevent crashing when buffer obj is not created but is going to be deleted. 2025-07-10 23:08:38 +08:00
BZLZHH dae5827666 [Fix] (MG_Util/GLSL): Enhance BindInputLayoutLocationsForGLSL. 2025-07-10 23:07:44 +08:00
BZLZHH b119c45c16 [Feat] (Diligent/Drawing): Convert Uint8 IBO into Uint16. 2025-07-10 19:45:24 +08:00
swung0x48 a59fe679a7 Merge branch 'Feat/Diligent' of https://github.com/MobileGL-Dev/MobileGL into feat/Diligent 2025-07-10 18:04:41 +08:00
swung0x48 82a4be37f2 [Fix] (MG_State/Program): fixing discrapencies between builtins of Vulkan and OpenGL GLSL (gl_VertexID/gl_VertexIndex) 2025-07-10 18:04:19 +08:00
BZLZHH f56453093f [Improvement] (Diligent/PSO): Add UniformStageCache. 2025-07-10 17:09:53 +08:00
BZLZHH 59e0291f9e [Improvement] (HeaderSystem): Optimize header system, highly improving performance. 2025-07-10 14:01:09 +08:00
BZLZHH 833679e58a [Chore] (gitignore): Ignore Visual Studio directory and output directory. 2025-07-10 11:41:33 +08:00
BZLZHH f04207905f [Chore] (DEBUG): Enable debug. 2025-07-09 18:17:10 +08:00
swung0x48 8c98afb1ac [Fix] (MG_State/Buffer): 1. Don't check on GetBufferObject(), do it on creation 2. Don't modify g_BufferMap on querying 2025-07-08 17:53:21 +08:00
swung0x48 8c52cd34ed [Fix] (MG_State/Clear): set render targets before clear 2025-07-08 16:17:47 +08:00
swung0x48 fbb1fc1fdb [Misc] (MG_State/Buffer): reserve buffer size rounding up to next power of 2 to make resize complexity logarithmic 2025-07-08 15:44:11 +08:00
swung0x48 c43ae7ed2c [Misc] (Diligent/Present): hard code disable vsync for now 2025-07-08 15:42:18 +08:00
swung0x48 ad626025d5 [Fix] (Diligent/Init): request NativeMultiDraw feature 2025-07-08 15:41:10 +08:00
swung0x48 9db24e6593 [Optimization] (Diligent/Framebuffer): explicitly unbind framebuffer on texture copy (BlitFramebuffer) 2025-07-08 14:32:25 +08:00
swung0x48 e3765f1f50 [Optimization] (MG_Constant): use vector instead of unordered_set to improve performance 2025-07-08 12:39:39 +08:00
swung0x48 532ca5ced5 [Fix] (MG_State/Texture, MG_State/Framebuffer): add stub for glCopyTexSubImage2D, glDrawBuffer, glDrawBuffers and glReadBuffer 2025-07-08 11:05:59 +08:00
swung0x48 20d02b75e1 [Fix] (MG_State/Texture): re-enable multi-miplevels 2025-07-07 10:39:00 +08:00
swung0x48 992ea967a7 [Fix] (MG_State/Texture): correctly maintain mag filter compare mode 2025-07-07 10:05:19 +08:00
swung0x48 9e3a5aefad [Optimize] (Diligent/RenderPass): remove renderpass usage 2025-07-06 10:21:15 +08:00
BZLZHH bf0c29b384 [Fix] (MG_Util/Program): Completely fix uniform conflicting. 2025-07-05 12:25:22 +08:00
BZLZHH 164c2f25d4 [Fix] (MG_Util/Program): Avoid uniform variables conflicting. 2025-07-05 11:56:15 +08:00
BZLZHH 4cf85c4f2a [Fix] (MG_State/Program): Map IO binding in FinalizeProgramPipeline. 2025-07-05 10:28:39 +08:00
swung0x48 bcaf0e6e32 Revert "[Fix] (MG_Util/GLSLTool): actually linking & mapping IO?"
This reverts commit 92cd0f3a82.
2025-07-04 20:11:33 +08:00
swung0x48 92cd0f3a82 [Fix] (MG_Util/GLSLTool): actually linking & mapping IO? 2025-07-02 14:35:41 +08:00
swung0x48 067d517527 [Fix] (MG_Util/GLSLTool): get rid of unnecessary whitespace removal 2025-06-30 15:32:59 +08:00
swung0x48 a6bcded3e4 [Fix] (Diligent/Drawing): set g_TriangleFanIndexBuffer to null after release 2025-06-30 13:48:24 +08:00
swung0x48 79e5eb6a74 [Fix] (MG_State/Buffer): ignore 0-sized reallocation 2025-06-30 13:47:07 +08:00
swung0x48 1078a33147 [Fix] (MG_Util/GLSLTool): set preamble to fix compilation error with vulkan target 2025-06-30 13:02:09 +08:00
swung0x48 3fb314fc44 [Fix] (MG_Util/GLSLTool): specify vulkan semantics to convert gl_VertexID/gl_InstanceID 2025-06-30 12:29:45 +08:00
BZLZHH e1fd5678ec [Fix] (Diligent/Shader): Try to bind varying in glsl str. 2025-06-29 11:42:38 +08:00
swung0x48 8a0d00f94b [Optimize] (MG_State/Buffer): vector to replace umap (does that optimize anything?) 2025-06-29 01:02:00 +08:00
swung0x48 0207ee85b7 [Optimize] (MG_Util/Debug): avoid runtime cost of unneeded log function (forced at compile time) 2025-06-27 22:29:24 +08:00
swung0x48 a5a661261d [Feat] (Diligent/EGL_Init, MG_State/Getter): separates engine init and swapchain creation 2025-06-27 13:47:43 +08:00
swung0x48 d056acf0af [Feat] (Diligent/PSO, MG_State/Buffer): implement GL_TRIANGLE_FAN emulation, fixing sky 2025-06-27 10:14:05 +08:00
swung0x48 229b5f292e [Fix] (MG_State/Texture): revert GetUnpackParam_ to private 2025-06-26 16:03:34 +08:00
swung0x48 3e71f83d61 [Fix] (MG_State/Texture): implement GL_UNPACK_SKIP_ROWS and GL_UNPACK_SKIP_PIXELS, fixing non-unicode fonts 2025-06-26 13:58:07 +08:00
swung0x48 fa6ace0955 [Misc]: minor fixes 2025-06-25 23:49:43 +08:00
swung0x48 1e6f91809e [Fix] (MG_State/Texture): deal with GL_UNPACK_ROW_LENGTH 2025-06-25 23:48:24 +08:00
swung0x48 afcc892b32 [Misc] (MG_GL/Getter): return real GL_MAX_VERTEX_ATTRIBS value 2025-06-25 17:02:34 +08:00
swung0x48 1c0a1fcbcb [Misc] (MG_State/Drawing): minor optimizations 2025-06-25 16:59:50 +08:00
swung0x48 bf8aaaa9c1 [Fix] (MG_State/VertexArray): use array to save attribs to maintain order and optimize performance 2025-06-25 16:22:16 +08:00
swung0x48 0359a4e97f [Fix] (MG_State/Texture): get rid of 0.25 max lod clamp 2025-06-25 11:58:51 +08:00
swung0x48 a18360c931 [Fix] (MG_State/PSO, GLSLTool): revert to flip y in shader 2025-06-24 17:36:45 +08:00
swung0x48 0c031d3e0b [Fix] (MG/GLSLTool): Finally fixing blur shader!
- use glslang mapIO() function to correctly link shader in/out varyings
- no need to flip y (already using VK_KHR_maintenance1 to specify negative viewport height)
- use pointers to avoid unnecessary copying
2025-06-24 16:33:16 +08:00
swung0x48 20a945c6f0 [Misc] (MG_State/PSO): temporarily disable culling, deal with cw/ccw later 2025-06-24 16:27:20 +08:00
swung0x48 433a5ac39d [Fix] (MG_State/GL_Texture): no need to clamp max lod min value 2025-06-24 16:26:09 +08:00
swung0x48 b444b7de88 [Fix] (MG_State/GL_Texture): do not automatically generate mipmaps 2025-06-24 09:02:50 +08:00
swung0x48 94dfdb6905 [Fix] (MG_Util/Program/GLSLTool): Really really hacky way to fix blur shader 2025-06-23 23:24:39 +08:00
swung0x48 2f1b06d0f9 [Fix] (MG/Framebuffer): get rid of suspicious GL_FRAMEBUFFER handling 2025-06-23 10:51:24 +08:00
swung0x48 14b1d5a2d1 [Fix] (MG/Constants): put log level in order 2025-06-23 09:37:32 +08:00
swung0x48 7c3912b9ae [Feat] (MG_State/Texture): implement GL_TEXTURE_COMPARE_MODE 2025-06-23 09:32:25 +08:00
swung0x48 fa657fbf0b [Misc] (Diligent/Texture): Log unhandled texture state 2025-06-22 22:00:17 +08:00
swung0x48 6e9f990eed [Fix] (Diligent/PSO,Program): get rid of phantom program 0 2025-06-22 21:59:20 +08:00
swung0x48 a8ae34b3bd [Improvement] (Getter): better glGetString with GPU name 2025-06-22 19:57:41 +08:00
swung0x48 e959126ac0 [Fix] (MG_State/Texture): properly disable mip filter when instructed 2025-06-22 19:56:15 +08:00
swung0x48 7e1906da57 [Fix] (MG_State/Texture): add same handling logic to glTexParameterf 2025-06-22 17:40:38 +08:00
swung0x48 9075177533 [Fix] (MG_State/Texture): Handle missing texture states 2025-06-22 13:08:50 +08:00
swung0x48 e73db426eb [Fix] (DebugTool.cpp): Fix uniform value debug output 2025-06-22 10:20:15 +08:00
BZLZHH 150bfa15a6 [Fix] (DiligentEngine): Increase the size of dynamic heap buffer. 2025-06-21 22:07:14 +08:00
BZLZHH cab375917b [Fix] (Diligent/PSO): Disable FrontCounterClockwise currently. 2025-06-21 21:44:43 +08:00
BZLZHH 6ac9beaa61 [Fix] (Diligent/Shader): Flip vertex y for vertex shaders. 2025-06-21 21:44:22 +08:00
BZLZHH a1bdaed2f6 [Chore] (DiligentEngine): Rename the renderer with Diligent Engine. 2025-06-21 21:43:32 +08:00
BZLZHH ee29a397da [Fix] (Diligent/PSO): Use GLSL For Vulkan mode somewhere. 2025-06-21 19:35:16 +08:00
BZLZHH cbf63dd2b6 [Fix] (MG_Util/Program): Allow GLSL For Vulkan to be converted into spirv. 2025-06-21 19:34:13 +08:00
BZLZHH 6d73806d1a [Fix] (Diligent/PSO): Use SPIRV-Cross to get the uniform offset. 2025-06-21 18:35:06 +08:00
BZLZHH f6c416bdf1 [Fix] (Diligent/Drawing): Prevent shader missing when shader has been deleted. 2025-06-21 17:04:32 +08:00
BZLZHH 99dd2f5dec [Fix] (Diligent/Buffer): Fix flags absence of buffer objects in Diligent. 2025-06-21 13:23:40 +08:00
BZLZHH d3b94dd1c6 [Fix] (Diligent/Drawing): Set IBO in glMultiDrawElementsBaseVertex. 2025-06-21 12:24:02 +08:00
BZLZHH edd1ad1a80 [Fix] (MG_State/Buffer): Do not consider GL_DYNAMIC_COPY and GL_STREAM_DRAW as dynamic buffer. 2025-06-21 11:30:47 +08:00
BZLZHH ae5c37b7e4 [Fix] (Diligent/Drawing): Fix vertex in glMultiDrawElements, 2025-06-21 10:41:19 +08:00
BZLZHH 7c3b4e52c3 [Feat] (Diligent/Drawing): Reimplement glMultiDrawElements through indirect drawing. 2025-06-21 09:48:08 +08:00
BZLZHH 61ae5e2e34 [Feat] (Diligent/Drawing): Implement glMultiDrawElements. 2025-06-21 04:11:40 +08:00
BZLZHH 6992c541af [Fix] (Diligent/Framebuffer): Correct GL_FRAMEBUFFER target handling. 2025-06-21 02:02:51 +08:00
BZLZHH 5d6bf42397 [Fix] (MG_State/Framebuffer): Correct GL_FRAMEBUFFER target handling and resource management. 2025-06-21 02:02:26 +08:00
BZLZHH bc61669dad [Improvement] (All): Remove redundant code. 2025-06-20 23:44:20 +08:00
BZLZHH 537ec9e2b0 [Fix] (Diligent/PSO): Try hashing bound texture ids for PSO. 2025-06-20 23:42:38 +08:00
BZLZHH 4ae9c00c06 Reapply "[Fix] (EGL_impl.cpp): make swapchain rotation right"
This reverts commit 832fc56a1b.
2025-06-20 21:55:53 +08:00
BZLZHH 3583e24bd8 Merge remote-tracking branch 'origin/dev-es' into Feat/Diligent 2025-06-20 17:56:01 +08:00
BZLZHH 832fc56a1b Revert "[Fix] (EGL_impl.cpp): make swapchain rotation right"
This reverts commit db93ddd280.

# Conflicts:
#	MG/MG_GL/Implementations/EGL/Diligent/EGL_impl.cpp
2025-06-20 16:50:29 +08:00
BZLZHH e77b56c9ad [Fix] (Diligent/PSO): Avoid crashing when MG_DEFAULT_UBO does not exist. 2025-06-20 16:41:13 +08:00
BZLZHH ac4cb2217e [Fix] (Diligent/Framebuffer): Do not begin renderpass in glBindFramebuffer. 2025-06-20 16:40:33 +08:00
BZLZHH cc2177e36c [Fix] (Diligent/Common): Handle renderpass in glClear. 2025-06-20 16:39:43 +08:00
BZLZHH ac6827fdd8 [Fix] (Diligent/Texture): Set sampler for texture. 2025-06-20 15:42:31 +08:00
BZLZHH 3c30d3aba9 Merge branch 'dev-es' into Feat/Diligent
# Conflicts:
#	MG/Constants.h
#	MG/Global.h
2025-06-20 13:25:44 +08:00
BZLZHH e4c77d1432 [Improvement] (MG_State/Program): Optimize the logic for DeleteShader. 2025-06-20 12:50:42 +08:00
BZLZHH e8ca8161c8 [Fix] (Diligent/Shader): Do not delete the Diligent shader obj when glDeleteShader is called. 2025-06-20 12:49:09 +08:00
swung0x48 a65ae7202e [Fix] (EGL_impl.cpp): probably fixed PSO hashing 2025-06-19 16:53:58 +08:00
swung0x48 09d13579fc [Fix]: PSO caching broken? Just re-generate on mismatch (TODO: fix this later) 2025-06-19 15:55:17 +08:00
swung0x48 3d2596f701 [Optimization] (EGL_impl.cpp): don't copy the whole unordered_map 2025-06-18 16:21:07 +08:00
swung0x48 6bc28c2ae9 [Fix] (EGL_impl.cpp): properly implement colorMask 2025-06-18 16:16:51 +08:00
swung0x48 2cd5edd08b [Fix] (EGL_impl.cpp): fix PSO hashing bugs 2025-06-18 13:05:06 +08:00
swung0x48 58a46c6106 [Fix] (EGL_impl.cpp): use RGBA8_UNORM as ColorBufferFormat, avoiding auto sRGB color correction 2025-06-18 10:36:08 +08:00
swung0x48 db93ddd280 [Fix] (EGL_impl.cpp): make swapchain rotation right 2025-06-18 10:18:01 +08:00
BZLZHH 6a1b1a5ed9 [Fix] (Diligent/PSO): Miscellaneous fix. 2025-06-15 11:52:34 +08:00
BZLZHH df95930481 [Fix] (DiligentEngine): Increase the size of dynamic heap buffer. 2025-06-15 10:33:17 +08:00
BZLZHH 0c2449dc5e [Fix] (Diligent/Buffer): Recreate buffer object when the size changes. 2025-06-15 10:32:38 +08:00
BZLZHH 8fcf58a732 [Fix] (Diligent/PSO): Correct std140 alignment in uniform offset recording. 2025-06-15 09:37:21 +08:00
BZLZHH 937cab736b [Feat] (Diligent/Drawing): Handle uint8 in MultiDrawElementsBaseVertex. 2025-06-15 08:13:22 +08:00
BZLZHH fa7bb59a82 [Feat] (Diligent/Drawing): Implement (Multi)DrawElementsBaseVertex. 2025-06-10 02:15:56 +08:00
BZLZHH a0016861e8 [Fix] (Diligent/PSO): Avoid crashing when uniform data is invalid. 2025-06-10 01:55:04 +08:00
BZLZHH 964f483fd5 [Fix] (Diligent/Buffer): Make all types of buffer mappable. 2025-06-10 01:54:19 +08:00
BZLZHH c5ea0a7bf1 [Fix] (BufferState): Better judgement for obj.isDynamic. 2025-06-10 01:53:42 +08:00
BZLZHH aad270bcd0 [Fix] (Diligent/PSO): Do not use immutable samplers. 2025-06-10 01:00:20 +08:00
BZLZHH 994e0a6675 [Misc] (Debug): Improve some logging. 2025-06-09 19:12:25 +08:00
BZLZHH 836c169100 [Fix] (Diligent/Shader): Rename glsl builtins for Vulkan. 2025-06-09 19:10:01 +08:00
BZLZHH 2fb0690804 [Fix] (Diligent/PSO): Try to bind input layout locations for GLSL. 2025-06-09 13:38:16 +08:00
BZLZHH 30b7f4d69d [Fix] (Diligent/Texture): Make multi-level textures correct. 2025-06-09 01:54:11 +08:00
BZLZHH 44e787c56a [Fix] (Diligent/PSO): Get real stage for uniform sampler. 2025-06-09 00:26:41 +08:00
BZLZHH 0c4a5f54f2 [Fix] (Diligent/PSO): Avoid adding duplicate shader resources. 2025-06-09 00:25:50 +08:00
BZLZHH b73c6e749e [Fix] (Diligent/Texture): Remove useless judgement in glTexSubImage2D. 2025-06-08 23:23:23 +08:00
BZLZHH 1022a4dfc3 [Fix] (Diligent/Buffer): Update all dynamic buffers in glDraw*. 2025-06-08 23:00:13 +08:00
BZLZHH ee72f7d07f [Fix] (Diligent/Framebuffer): Make sure glBlitFramebuffer is not in renderpass. 2025-06-08 22:23:12 +08:00
swung0x48 8af2aa262b Merge branch 'Feat/Diligent' of https://github.com/MobileGL-Dev/MobileGL into feat/Diligent 2025-06-08 20:19:36 +08:00
swung0x48 40a458b743 [Fix]: save order of uniform names, and apply it at linking and buffer mapping 2025-06-08 20:19:06 +08:00
BZLZHH e645167c94 [Fix] (Diligent/PSO): Set stride value for layout element. 2025-06-08 18:56:56 +08:00
BZLZHH c183203264 [Fix] (Diligent/Drawing): Use real type for IBO. 2025-06-08 18:17:05 +08:00
BZLZHH 4dfbc01479 [Fix] (Diligent/PSO): Build InputLayout for PSO. 2025-06-08 17:29:10 +08:00
BZLZHH f3497bd2fa [Improvement] (ProgramState): Rename AttributeBindings -> AttributeLocations. 2025-06-08 16:01:31 +08:00
BZLZHH 3c98bc5eca [Improvement] (ProgramState): Remove useless programObj.attribBindings. 2025-06-08 15:54:10 +08:00
swung0x48 9640e167df [Feat] (GL_Buffer.cpp): name buffers 2025-06-08 13:46:41 +08:00
swung0x48 b580605c86 [Fix] (EGL_impl.h): get rid of redundant extern var 2025-06-08 13:45:27 +08:00
BZLZHH 292c7eeecf [Fix] (Diligent/Buffer): Create dynamic buffer in glDraw*. 2025-06-08 13:35:32 +08:00
BZLZHH 848f110658 [Fix] (DiligentEngine): Fix some miscellaneous issues. 2025-06-08 01:57:13 +08:00
BZLZHH 979d31407f [Fix] (DiligentEngine): Bind renderpass for PSO. 2025-06-08 01:04:05 +08:00
BZLZHH f5c3514dde [Fix] (Diligent/Drawing): Bind shader resources to pipeline. 2025-06-08 00:11:24 +08:00
BZLZHH beecb3dac0 [Fix] (DiligentEngine): Use SHADER_TYPE_VS_PS as stages for uniform block. 2025-06-07 23:03:12 +08:00
BZLZHH ea871e0188 [Fix] (DiligentEngine): Add static for ImmutableSamplers and Variables in ConfigureResourceLayout. 2025-06-07 22:42:38 +08:00
BZLZHH ad6b9c1ca7 [Fix] (Diligent/Texture): Fix glTexSubImage2D crashing. 2025-06-07 22:14:34 +08:00
BZLZHH 2caade5a36 [Fix] (Diligent/FrameBuffer): Remove the release of RTVs in fbo 0. 2025-06-07 22:02:30 +08:00
BZLZHH 8eb055ca81 [Fix] (Diligent/FrameBuffer): Fix UpdateDefaultFramebuffer crashing. 2025-06-07 21:15:29 +08:00
BZLZHH 852b843b4a [Fix] (Diligent/Texture): Add BIND_RENDER(/DEPTH)_TARGET for texture. 2025-06-07 20:49:48 +08:00
BZLZHH 211bf5de39 [Fix] (Diligent/Texture): Fix the 'Overwriting reference' bug in TexImage2D. 2025-06-07 20:42:25 +08:00
BZLZHH f5a14c20a9 [Feat] (DiligentEngine): Implement most rendering by DiligentEngine. 2025-06-07 19:41:32 +08:00
BZLZHH c95077f263 [Misc] (Debug): Add all gl enum constants in GLEnumToString. 2025-06-06 21:01:25 +08:00
BZLZHH ca5c1a123b Merge remote-tracking branch 'origin/dev-es' into Feat/Diligent 2025-06-05 14:03:41 +08:00
BZLZHH 6075ae1445 [Feat] (DiligentEngine): Capable to render. 2025-06-05 13:58:34 +08:00
BZLZHH 2466897531 [Feat] (Diligent): Add Diligent Vulkan backend. 2025-05-25 11:46:38 +08:00
swung0x48 604482d55c [Feat]: Making DiligentCore EGL init work 2025-05-18 20:51:58 +08:00
swung0x48 906323f219 [Misc]: bringing in DiligentCore 2025-05-17 22:47:59 +08:00
swung0x48 13022c79bf [Misc]: add DiligentCore as submodule 2025-05-17 22:11:38 +08:00
1167 changed files with 191526 additions and 121111 deletions
+27
View File
@@ -0,0 +1,27 @@
BasedOnStyle: Microsoft
IndentWidth: 4
UseTab: Never
AccessModifierOffset: -4
PointerAlignment: Left
BreakBeforeBraces: Custom
BraceWrapping:
AfterFunction: false
AfterClass: false
AfterControlStatement: Never
AfterEnum: false
AfterNamespace: false
AfterStruct: false
AfterUnion: false
BeforeElse: false
SplitEmptyFunction: false
SplitEmptyRecord: false
AllowShortBlocksOnASingleLine: Empty
AllowShortIfStatementsOnASingleLine: WithoutElse
AlwaysBreakTemplateDeclarations: Yes
NamespaceIndentation: All
AllowShortFunctionsOnASingleLine: Inline
SortIncludes: false
FixNamespaceComments: true
ShortNamespaceLines: 0
CompactNamespaces: false
+142
View File
@@ -0,0 +1,142 @@
#Generated from CLion Inspection settings
---
Checks: '-*,
bugprone-argument-comment,
bugprone-assert-side-effect,
bugprone-bad-signal-to-kill-thread,
bugprone-branch-clone,
bugprone-copy-constructor-init,
bugprone-dangling-handle,
bugprone-dynamic-static-initializers,
bugprone-fold-init-type,
bugprone-forward-declaration-namespace,
bugprone-forwarding-reference-overload,
bugprone-inaccurate-erase,
bugprone-incorrect-roundings,
bugprone-integer-division,
bugprone-macro-parentheses,
bugprone-macro-repeated-side-effects,
bugprone-misplaced-operator-in-strlen-in-alloc,
bugprone-misplaced-pointer-arithmetic-in-alloc,
bugprone-misplaced-widening-cast,
bugprone-move-forwarding-reference,
bugprone-multiple-statement-macro,
bugprone-no-escape,
bugprone-parent-virtual-call,
bugprone-posix-return,
bugprone-reserved-identifier,
bugprone-sizeof-container,
bugprone-sizeof-expression,
bugprone-spuriously-wake-up-functions,
bugprone-string-constructor,
bugprone-string-integer-assignment,
bugprone-string-literal-with-embedded-nul,
bugprone-suspicious-enum-usage,
bugprone-suspicious-include,
bugprone-suspicious-memset-usage,
bugprone-suspicious-missing-comma,
bugprone-suspicious-semicolon,
bugprone-suspicious-string-compare,
bugprone-suspicious-memory-comparison,
bugprone-suspicious-realloc-usage,
bugprone-swapped-arguments,
bugprone-terminating-continue,
bugprone-throw-keyword-missing,
bugprone-too-small-loop-variable,
bugprone-undefined-memory-manipulation,
bugprone-undelegated-constructor,
bugprone-unhandled-self-assignment,
bugprone-unused-raii,
bugprone-unused-return-value,
bugprone-use-after-move,
bugprone-virtual-near-miss,
cert-dcl21-cpp,
cert-dcl58-cpp,
cert-err34-c,
cert-err52-cpp,
cert-err60-cpp,
cert-flp30-c,
cert-msc50-cpp,
cert-msc51-cpp,
cert-str34-c,
cppcoreguidelines-interfaces-global-init,
cppcoreguidelines-narrowing-conversions,
cppcoreguidelines-pro-type-member-init,
cppcoreguidelines-slicing,
google-default-arguments,
google-runtime-operator,
hicpp-exception-baseclass,
hicpp-multiway-paths-covered,
misc-misplaced-const,
misc-new-delete-overloads,
misc-non-copyable-objects,
misc-throw-by-value-catch-by-reference,
misc-unconventional-assign-operator,
misc-uniqueptr-reset-release,
modernize-avoid-bind,
modernize-concat-nested-namespaces,
modernize-deprecated-headers,
modernize-deprecated-ios-base-aliases,
modernize-loop-convert,
modernize-make-shared,
modernize-make-unique,
modernize-pass-by-value,
modernize-raw-string-literal,
modernize-redundant-void-arg,
modernize-replace-auto-ptr,
modernize-replace-disallow-copy-and-assign-macro,
modernize-replace-random-shuffle,
modernize-return-braced-init-list,
modernize-shrink-to-fit,
modernize-unary-static-assert,
modernize-use-auto,
modernize-use-bool-literals,
modernize-use-emplace,
modernize-use-equals-default,
modernize-use-equals-delete,
modernize-use-noexcept,
modernize-use-nullptr,
modernize-use-override,
modernize-use-transparent-functors,
modernize-use-uncaught-exceptions,
mpi-buffer-deref,
mpi-type-mismatch,
openmp-use-default-none,
performance-faster-string-find,
performance-for-range-copy,
performance-implicit-conversion-in-loop,
performance-inefficient-algorithm,
performance-inefficient-string-concatenation,
performance-inefficient-vector-operation,
performance-move-const-arg,
performance-move-constructor-init,
performance-no-automatic-move,
performance-noexcept-move-constructor,
performance-trivially-destructible,
performance-type-promotion-in-math-fn,
performance-unnecessary-copy-initialization,
performance-unnecessary-value-param,
portability-simd-intrinsics,
readability-avoid-const-params-in-decls,
readability-const-return-type,
readability-container-size-empty,
readability-convert-member-functions-to-static,
readability-delete-null-pointer,
readability-deleted-default,
readability-inconsistent-declaration-parameter-name,
readability-make-member-function-const,
readability-misleading-indentation,
readability-misplaced-array-index,
readability-non-const-parameter,
readability-redundant-control-flow,
readability-redundant-declaration,
readability-redundant-function-ptr-dereference,
readability-redundant-smartptr-get,
readability-redundant-string-cstr,
readability-redundant-string-init,
readability-simplify-subscript-expr,
readability-static-accessed-through-instance,
readability-static-definition-in-anonymous-namespace,
readability-string-compare,
readability-uniqueptr-delete-release,
readability-use-anyofallof'
+4
View File
@@ -0,0 +1,4 @@
tools/trace_replay/fixtures/*.tgz filter=lfs diff=lfs merge=lfs -text
tools/trace_replay/fixtures/*.png filter=lfs diff=lfs merge=lfs -text
tools/trace_replay/fixtures/openra.tgz -filter -diff -merge -text
tools/trace_replay/fixtures/openra.0000031249.png -filter -diff -merge -text
+246
View File
@@ -0,0 +1,246 @@
#!/usr/bin/env bash
set -euo pipefail
if [ "$#" -lt 1 ] || [ "$#" -gt 2 ]; then
echo "usage: $0 <trace-case> [fixture-dir]" >&2
exit 2
fi
case_name="$1"
fixture_dir="${2:-tools/trace_replay/fixtures}"
python_bin="${PYTHON:-python3}"
# Fixture mirrors, tried in order before falling back to Git LFS. Override the
# whole list with MOBILEGL_TRACE_FIXTURE_MIRROR_BASES (whitespace separated);
# MOBILEGL_TRACE_FIXTURE_MIRROR_BASE still works and is tried first.
default_mirror_bases=(
"https://git.hit.moe/swung0x48/MobileGL/media/branch/dev/tools/trace_replay/fixtures"
"https://repo.miawa.cn/mgl/tools/trace_replay/fixtures"
)
if [ -n "${MOBILEGL_TRACE_FIXTURE_MIRROR_BASES:-}" ]; then
read -r -a mirror_bases <<< "${MOBILEGL_TRACE_FIXTURE_MIRROR_BASES}"
else
mirror_bases=("${default_mirror_bases[@]}")
fi
if [ -n "${MOBILEGL_TRACE_FIXTURE_MIRROR_BASE:-}" ]; then
mirror_bases=("${MOBILEGL_TRACE_FIXTURE_MIRROR_BASE}" "${mirror_bases[@]}")
fi
# Optional bearer token for mirrors that require authentication (private Gitea).
mirror_token="${MOBILEGL_TRACE_FIXTURE_MIRROR_TOKEN:-}"
download_attempts="${MOBILEGL_TRACE_FIXTURE_DOWNLOAD_ATTEMPTS:-5}"
retry_delay="${MOBILEGL_TRACE_FIXTURE_RETRY_DELAY:-2}"
if ! command -v "${python_bin}" >/dev/null 2>&1 && command -v python >/dev/null 2>&1; then
python_bin=python
fi
if ! [[ "${download_attempts}" =~ ^[1-9][0-9]*$ ]]; then
echo "MOBILEGL_TRACE_FIXTURE_DOWNLOAD_ATTEMPTS must be a positive integer: ${download_attempts}" >&2
exit 2
fi
if ! [[ "${retry_delay}" =~ ^[0-9]+$ ]]; then
echo "MOBILEGL_TRACE_FIXTURE_RETRY_DELAY must be a non-negative integer: ${retry_delay}" >&2
exit 2
fi
fixture_list="$("${python_bin}" tools/trace_replay/trace_cases.py \
--format fixture-files \
--case "${case_name}" \
--fixture-root "${fixture_dir}")"
# Strip CR so the script also works when python emits CRLF (Git Bash on Windows).
mapfile -t files < <(printf '%s\n' "${fixture_list}" | tr -d '\r')
include="$(IFS=,; echo "${files[*]}")"
if [ "${case_name}" = "OpenRA" ]; then
echo "Fixture files for ${case_name} are stored in Git: ${include}"
for file in "${files[@]}"; do
test -s "${file}"
if head -n 1 "${file}" | grep -q "version https://git-lfs.github.com/spec/v1"; then
echo "fixture should not be stored as an LFS pointer: ${file}" >&2
exit 1
fi
done
exit 0
fi
get_lfs_metadata() {
local file="$1"
local pointer
local expected_oid
local expected_size
if ! pointer="$(git show "HEAD:${file}" 2>/dev/null)"; then
echo "failed to read tracked fixture metadata: ${file}" >&2
return 1
fi
if ! grep -q '^version https://git-lfs.github.com/spec/v1$' <<< "${pointer}"; then
echo "tracked fixture is not a Git LFS pointer: ${file}" >&2
return 1
fi
expected_oid="$(awk '$1 == "oid" && $2 ~ /^sha256:/ { sub(/^sha256:/, "", $2); print $2 }' <<< "${pointer}")"
expected_size="$(awk '$1 == "size" { print $2 }' <<< "${pointer}")"
if ! [[ "${expected_oid}" =~ ^[0-9a-f]{64}$ ]] || ! [[ "${expected_size}" =~ ^[0-9]+$ ]]; then
echo "invalid Git LFS pointer metadata: ${file}" >&2
return 1
fi
printf '%s %s\n' "${expected_oid}" "${expected_size}"
}
verify_fixture_file() {
local downloaded_file="$1"
local display_name="$2"
local expected_oid="$3"
local expected_size="$4"
local actual_oid
local actual_size
if [ ! -f "${downloaded_file}" ]; then
echo "fixture file is missing: ${display_name}" >&2
return 1
fi
actual_size="$(wc -c < "${downloaded_file}" | tr -d '[:space:]')"
if [ "${actual_size}" != "${expected_size}" ]; then
echo "fixture size mismatch for ${display_name}: expected ${expected_size}, got ${actual_size}" >&2
return 1
fi
actual_oid="$(sha256sum "${downloaded_file}" | awk '{ print $1 }')"
if [ "${actual_oid}" != "${expected_oid}" ]; then
echo "fixture SHA-256 mismatch for ${display_name}: expected ${expected_oid}, got ${actual_oid}" >&2
return 1
fi
}
fetch_file_from_mirror() {
local file="$1"
local url="$2"
local metadata
local expected_oid
local expected_size
local tmp_file="${file}.tmp"
local attempt
local partial_size
local curl_status
local curl_auth
metadata="$(get_lfs_metadata "${file}")" || return 1
read -r expected_oid expected_size <<< "${metadata}"
if [ -f "${tmp_file}" ]; then
partial_size="$(wc -c < "${tmp_file}" | tr -d '[:space:]')"
if [ "${partial_size}" -gt "${expected_size}" ]; then
echo "Discarding oversized partial fixture ${tmp_file}: ${partial_size} > ${expected_size}" >&2
rm -f "${tmp_file}"
elif [ "${partial_size}" = "${expected_size}" ]; then
if verify_fixture_file "${tmp_file}" "${file}" "${expected_oid}" "${expected_size}"; then
mv "${tmp_file}" "${file}"
return 0
fi
rm -f "${tmp_file}"
fi
fi
for ((attempt = 1; attempt <= download_attempts; attempt++)); do
partial_size=0
if [ -f "${tmp_file}" ]; then
partial_size="$(wc -c < "${tmp_file}" | tr -d '[:space:]')"
fi
if [ "${partial_size}" -gt 0 ]; then
echo "Resuming mirror download for ${file} at byte ${partial_size} (attempt ${attempt}/${download_attempts})"
else
echo "Starting mirror download for ${file} (attempt ${attempt}/${download_attempts})"
fi
curl_auth=()
if [ -n "${mirror_token}" ]; then
curl_auth=(--header "Authorization: token ${mirror_token}")
fi
if curl -L --fail --show-error --continue-at - "${curl_auth[@]}" --output "${tmp_file}" "${url}"; then
if verify_fixture_file "${tmp_file}" "${file}" "${expected_oid}" "${expected_size}"; then
mv "${tmp_file}" "${file}"
return 0
fi
echo "Mirror download failed integrity verification; retrying from the beginning: ${file}" >&2
rm -f "${tmp_file}"
else
curl_status=$?
partial_size=0
if [ -f "${tmp_file}" ]; then
partial_size="$(wc -c < "${tmp_file}" | tr -d '[:space:]')"
fi
if [ "${partial_size}" = "${expected_size}" ]; then
if verify_fixture_file "${tmp_file}" "${file}" "${expected_oid}" "${expected_size}"; then
mv "${tmp_file}" "${file}"
return 0
fi
rm -f "${tmp_file}"
partial_size=0
elif [ "${partial_size}" -gt "${expected_size}" ]; then
echo "Discarding oversized partial fixture ${tmp_file}: ${partial_size} > ${expected_size}" >&2
rm -f "${tmp_file}"
partial_size=0
elif [ "${curl_status}" -eq 33 ]; then
echo "Mirror refused the resume request; retrying from the beginning: ${file}" >&2
rm -f "${tmp_file}"
partial_size=0
fi
echo "Mirror download attempt ${attempt}/${download_attempts} failed with curl exit ${curl_status}; retained ${partial_size} bytes for resume: ${file}" >&2
fi
if [ "${attempt}" -lt "${download_attempts}" ]; then
sleep "${retry_delay}"
fi
done
rm -f "${tmp_file}"
return 1
}
# Files no mirror could serve, even after retrying every mirror. Only these fall
# back to Git LFS, so a mirror that served the rest of the case still spares
# GitHub the bandwidth for those files.
mirror_failures=()
fetch_from_mirror() {
mkdir -p "${fixture_dir}"
for file in "${files[@]}"; do
local name
local url
local base
local fetched=0
name="$(basename "${file}")"
for base in "${mirror_bases[@]}"; do
url="${base%/}/${name}"
echo "Fetching trace fixture from mirror: ${url}"
if fetch_file_from_mirror "${file}" "${url}"; then
fetched=1
break
fi
echo "Mirror did not serve ${name}; trying the next mirror" >&2
done
if [ "${fetched}" -ne 1 ]; then
mirror_failures+=("${file}")
fi
done
[ "${#mirror_failures[@]}" -eq 0 ]
}
if fetch_from_mirror; then
echo "Fetched trace fixture files for ${case_name} from mirror: ${include}"
else
fallback_include="$(IFS=,; echo "${mirror_failures[*]}")"
echo "All mirrors failed for ${#mirror_failures[@]} of ${#files[@]} file(s) of ${case_name}; falling back to Git LFS: ${fallback_include}"
git lfs install --local
git lfs pull --include="${fallback_include}" --exclude=""
fi
for file in "${files[@]}"; do
metadata="$(get_lfs_metadata "${file}")"
read -r expected_oid expected_size <<< "${metadata}"
verify_fixture_file "${file}" "${file}" "${expected_oid}" "${expected_size}"
done
+75
View File
@@ -0,0 +1,75 @@
#!/usr/bin/env bash
set -euo pipefail
if [[ $# -ne 3 ]]; then
echo "Usage: $0 <aapt2> <plugin-apk> <trace-apk>" >&2
exit 64
fi
aapt2=$1
plugin_apk=$2
trace_apk=$3
require() {
local needle=$1
local content=$2
local description=$3
if ! grep -Fq -- "$needle" <<<"$content"; then
echo "::error::Missing ${description}: ${needle}" >&2
exit 1
fi
}
for apk in "$plugin_apk" "$trace_apk"; do
[[ -f "$apk" ]] || { echo "::error::APK not found: $apk" >&2; exit 1; }
done
plugin_manifest=$("$aapt2" dump xmltree --file AndroidManifest.xml "$plugin_apk")
plugin_resources=$("$aapt2" dump resources "$plugin_apk")
plugin_resource_text=$(tr -d '"' <<<"$plugin_resources")
trace_manifest=$("$aapt2" dump xmltree --file AndroidManifest.xml "$trace_apk")
plugin_contents=$(unzip -Z1 "$plugin_apk")
require 'top.mobilegl.plugin' "$plugin_manifest" 'plugin package name'
require 'MobileGL' "$plugin_manifest" 'plugin label'
require 'fclPlugin' "$plugin_manifest" 'legacy plugin marker'
require 'fclPlugin_V2' "$plugin_manifest" 'V2 plugin marker'
require 'LIBGL_ES=3:POJAV_RENDERER=opengles3:MOBILEGL_BACKEND_TYPE=DirectGLES' "$plugin_manifest" 'V1 DirectGLES fallback'
require 'string/config' "$plugin_resources" 'V2 renderer configuration resource'
require '{displayName:MobileGL,rendererId:opengles3' "$plugin_resource_text" 'V2 MobileGL entry and renderer ID'
require 'rendererGLPath:**|libMobileGL.so' "$plugin_resource_text" 'V2 GL library path'
require 'rendererEGLPath:**|libMobileGL.so' "$plugin_resource_text" 'V2 EGL library path'
require 'key:LIBGL_ES,value:3' "$plugin_resource_text" 'V2 fixed LIBGL_ES variable'
require 'key:MOBILEGL_BACKEND_TYPE' "$plugin_resource_text" 'V2 backend variable'
require 'defaultValue:DirectGLES' "$plugin_resource_text" 'V2 DirectGLES default'
require 'DirectVulkan' "$plugin_resource_text" 'V2 DirectVulkan option'
require 'key:MOBILEGL_DISABLE_TIMERQUERY' "$plugin_resource_text" 'V2 timer-query toggle'
require 'key:MOBILEGL_DISABLE_SUBGROUP' "$plugin_resource_text" 'V2 Vulkan subgroup toggle'
require 'key:MOBILEGL_MAGMA_R11G11B10F_FALLBACK' "$plugin_resource_text" 'V2 Magma format fallback toggle'
require 'key:MOBILEGL_MAGMA_FRAMESINFLIGHT' "$plugin_resource_text" 'V2 Magma frames-in-flight setting'
require 'key:MOBILEGL_AVOID_SAMPLER_MIPMAP_MIN_FILTER' "$plugin_resource_text" 'V2 sampler workaround toggle'
require 'key:MOBILEGL_COHERENT_AS_FLUSH' "$plugin_resource_text" 'V2 coherent-as-flush toggle'
require 'key:MOBILEGL_USE_ANGLE' "$plugin_resource_text" 'V2 ANGLE toggle'
if [[ $(grep -Fc 'fclPlugin_V2' <<<"$plugin_manifest") -ne 1 ]]; then
echo '::error::Plugin manifest must expose exactly one V2 descriptor' >&2
exit 1
fi
if ! grep -Eq '^lib/[^/]+/libMobileGL\.so$' <<<"$plugin_contents"; then
echo '::error::Plugin APK does not contain libMobileGL.so' >&2
exit 1
fi
require 'top.mobilegl.plugin.trace' "$trace_manifest" 'trace package name'
require 'top.mobilegl.plugin.TRACE_REPLAY' "$trace_manifest" 'trace replay action'
if grep -Fq 'fclPlugin' <<<"$trace_manifest"; then
echo '::error::Trace APK must not advertise renderer-plugin metadata' >&2
exit 1
fi
if grep -Fq 'android.intent.action.MAIN' <<<"$trace_manifest"; then
echo '::error::Trace APK must not expose a launcher activity' >&2
exit 1
fi
echo 'Validated unified MobileGL plugin APK and isolated trace APK.'
+560
View File
@@ -0,0 +1,560 @@
name: MobileGL APK
on:
push:
branches:
- dev
- Feat/Backend-Direct-GLES
- Feat/Backend-Direct-Vulkan
workflow_dispatch:
jobs:
build:
runs-on: ubuntu-latest
env:
CCACHE_BASEDIR: ${{ github.workspace }}
CCACHE_COMPRESS: "true"
CCACHE_DIR: ${{ github.workspace }}/.ccache
CCACHE_MAXSIZE: 4G
CCACHE_NOHASHDIR: "true"
MOBILEGL_CMAKE_COMPILER_LAUNCHER: ccache
steps:
- name: Checkout repo
uses: actions/checkout@v6
with:
submodules: recursive
- name: Set artifact metadata
run: |
echo "date_today=$(date +'%Y-%m-%d')" >> "$GITHUB_ENV"
- name: Set up JDK
uses: actions/setup-java@v5
with:
distribution: zulu
java-version: '17'
- name: Setup Gradle
uses: gradle/actions/setup-gradle@v6
with:
gradle-version: 8.10.2
- name: Restore ccache
uses: actions/cache@v5
with:
path: .ccache
key: ${{ runner.os }}-apk-${{ github.job }}-ccache-${{ github.ref_name }}-${{ github.run_id }}
restore-keys: |
${{ runner.os }}-apk-${{ github.job }}-ccache-${{ github.ref_name }}-
${{ runner.os }}-apk-${{ github.job }}-ccache-
- name: Install ccache
run: |
sudo apt-get update
sudo apt-get install -y ccache
ccache --version
- name: Setup Android SDK
uses: android-actions/setup-android@v4
with:
accept-android-sdk-licenses: false
- name: Accept Android SDK licenses
run: yes | sdkmanager --licenses >/dev/null
- name: Install Android NDK
run: |
sdkmanager "ndk;27.3.13750724"
echo "ndk.dir=$ANDROID_HOME/ndk/27.3.13750724" >> android-plugin/local.properties
- name: Update glslang external sources
working-directory: 3rdparty/glslang
run: python update_glslang_sources.py
- name: Build plugin APK
run: gradle --no-daemon -p android-plugin :app:assemblePluginRelease -Pmobilegl.apkSuffix="${GITHUB_SHA}" -Pmobilegl.logLevel=MOBILEGL_LOG_LEVEL_INFO --parallel --max-workers "$(nproc)"
env:
SIGNING_STORE_PASSWORD: ${{ secrets.SIGNING_STORE_PASSWORD }}
SIGNING_KEY_ALIAS: ${{ secrets.SIGNING_KEY_ALIAS }}
SIGNING_KEY_PASSWORD: ${{ secrets.SIGNING_KEY_PASSWORD }}
- name: Download ANGLE x86_64 libraries
run: |
angle_dir="android-plugin/app/src/trace/jniLibs/x86_64"
rm -rf "${angle_dir}"
mkdir -p "${angle_dir}"
package_angle_variant() {
variant="$1"
commit="$2"
egl_sha="$3"
gles_sha="$4"
source_dir="${RUNNER_TEMP}/mobilegl-angle-${variant}"
base="https://raw.githubusercontent.com/FCL-Team/FoldCraftLauncher/${commit}/FCLauncher/src/main/jniLibs/x86_64"
mkdir -p "${source_dir}"
curl -L --fail --retry 3 -o "${source_dir}/libEGL_angle.so" "${base}/libEGL_angle.so"
curl -L --fail --retry 3 -o "${source_dir}/libGLESv2_angle.so" "${base}/libGLESv2_angle.so"
echo "${egl_sha} ${source_dir}/libEGL_angle.so" | sha256sum -c -
echo "${gles_sha} ${source_dir}/libGLESv2_angle.so" | sha256sum -c -
for library in libEGL_angle libGLESv2_angle; do
filename="${library}_${variant}.so"
cp "${source_dir}/${library}.so" "${angle_dir}/${filename}"
done
}
package_angle_variant \
ec889e6ea831 \
f2a3d510dffd8f6540a52e1a7d0c5787d151075b \
c41828768d089899fa058ec0bee711a91be88347f29bdb935223da6be1149c40 \
e4f820d99f94365c66df868c7740fef142fe5c0cd7c941790a9e30638857ca4d
package_angle_variant \
90a62123d794 \
bdcc96ac11c79001018ae4375eb73cb54a9f682f \
d0f4298ccc770cc801fc52e21733521646161e8a4adb3bd0052d9a1b57ee0ca8 \
66fdc867e552192d553d59095ea2e3cef4829de65c356f1fd826027b1905972e
- name: Build retrace APK
run: gradle --no-daemon -p android-plugin :app:assembleTraceRelease -Pmobilegl.apkSuffix="${GITHUB_SHA}" -Pmobilegl.abis=all -Pmobilegl.debuggableRelease=true -Pmobilegl.logLevel=MOBILEGL_LOG_LEVEL_INFO --parallel --max-workers "$(nproc)"
env:
SIGNING_STORE_PASSWORD: ${{ secrets.SIGNING_STORE_PASSWORD }}
SIGNING_KEY_ALIAS: ${{ secrets.SIGNING_KEY_ALIAS }}
SIGNING_KEY_PASSWORD: ${{ secrets.SIGNING_KEY_PASSWORD }}
- name: Show ccache stats
if: always()
run: ccache --show-stats
- name: Verify APK metadata and packaging
run: |
AAPT2="$(find "$ANDROID_HOME/build-tools" -name aapt2 -type f | sort -V | tail -n 1)"
plugin_apk="android-plugin/app/build/outputs/apk/plugin/release/MobileGL-plugin-release-${GITHUB_SHA}.apk"
trace_apk="android-plugin/app/build/outputs/apk/trace/release/MobileGL-plugin-trace-release-${GITHUB_SHA}.apk"
test -f "${plugin_apk}"
test -f "${trace_apk}"
bash .github/scripts/validate-plugin-apks.sh "$AAPT2" "$plugin_apk" "$trace_apk"
- name: Verify signed APKs
run: |
APKSIGNER="$(find "$ANDROID_HOME/build-tools" -name apksigner -type f | sort -V | tail -n 1)"
mapfile -t APKS < <(printf '%s\n' \
"android-plugin/app/build/outputs/apk/plugin/release/MobileGL-plugin-release-${GITHUB_SHA}.apk" \
"android-plugin/app/build/outputs/apk/trace/release/MobileGL-plugin-trace-release-${GITHUB_SHA}.apk")
for APK in "${APKS[@]}"; do
if [[ ! -f "$APK" ]]; then
echo "::error::Expected release APK was not produced: $APK"
exit 1
fi
done
for APK in "${APKS[@]}"; do
if [[ "$APK" == *-unsigned.apk ]]; then
echo "::error::Unsigned release APK produced: $APK"
exit 1
fi
"$APKSIGNER" verify --verbose "$APK"
done
- name: Upload plugin APK
uses: actions/upload-artifact@v7
with:
name: MobileGL-plugin-${{ env.date_today }}-${{ github.sha }}
path: android-plugin/app/build/outputs/apk/plugin/release/MobileGL-plugin-release-${{ github.sha }}.apk
archive: false
if-no-files-found: error
- name: Upload retrace APK
uses: actions/upload-artifact@v7
with:
name: MobileGL-retrace-apk-${{ env.date_today }}-${{ github.sha }}
path: android-plugin/app/build/outputs/apk/trace/release/MobileGL-plugin-trace-release-${{ github.sha }}.apk
archive: false
if-no-files-found: error
trace-cases:
name: trace case matrix
runs-on: ubuntu-latest
needs: build
outputs:
android: ${{ steps.trace-cases.outputs.android }}
names: ${{ steps.trace-cases.outputs.names }}
steps:
- name: Checkout repo
uses: actions/checkout@v6
- name: Load trace cases
id: trace-cases
run: |
echo "android=$(python3 tools/trace_replay/trace_cases.py --ci --format github-apk)" >> "$GITHUB_OUTPUT"
echo "names=$(python3 tools/trace_replay/trace_cases.py --ci --format names)" >> "$GITHUB_OUTPUT"
trace-fixtures:
name: trace fixture (${{ matrix.case }})
runs-on: ubuntu-latest
needs: trace-cases
strategy:
fail-fast: false
max-parallel: 4
matrix:
case: ${{ fromJSON(needs.trace-cases.outputs.names) }}
steps:
- name: Checkout repo
uses: actions/checkout@v6
- name: Fetch trace fixture
run: bash .github/scripts/fetch-trace-fixture-lfs.sh '${{ matrix.case }}'
- name: Stage trace fixture
run: |
safe_case="$(printf '%s' '${{ matrix.case }}' | sed 's/[^A-Za-z0-9._-]/_/g')"
stage_dir="trace-fixtures/${safe_case}"
mkdir -p "${stage_dir}"
python3 tools/trace_replay/trace_cases.py --format fixture-files --case '${{ matrix.case }}' |
while IFS= read -r file; do
cp "${file}" "${stage_dir}/"
done
- name: Upload trace fixture
uses: actions/upload-artifact@v7
with:
name: MobileGL-trace-fixture-${{ matrix.case }}
path: trace-fixtures/**
if-no-files-found: error
android-avd:
name: android avd image
runs-on: ubuntu-latest
env:
AVD_NAME: mobilegl-ci
ANDROID_AVD_HOME: ${{ github.workspace }}/.android/avd
ANDROID_HOME: ${{ github.workspace }}/.android/sdk
ANDROID_SDK_ROOT: ${{ github.workspace }}/.android/sdk
steps:
- name: Checkout repo
uses: actions/checkout@v6
- name: Setup Android SDK
uses: android-actions/setup-android@v4
with:
accept-android-sdk-licenses: false
- name: Accept Android SDK licenses
run: yes | sdkmanager --licenses >/dev/null
- name: Restore Android AVD cache
id: android-avd-cache
uses: actions/cache@v5
with:
path: |
${{ env.ANDROID_AVD_HOME }}
${{ env.ANDROID_SDK_ROOT }}/emulator
${{ env.ANDROID_SDK_ROOT }}/platform-tools
${{ env.ANDROID_SDK_ROOT }}/platforms/android-35
${{ env.ANDROID_SDK_ROOT }}/system-images/android-35/google_apis/x86_64
key: ${{ runner.os }}-mobilegl-avd-api35-google_apis-x86_64-pixel_6-v2-${{ hashFiles('android-plugin/run-avd-ci.sh') }}
- name: Create AVD
if: steps.android-avd-cache.outputs.cache-hit != 'true'
run: |
sh android-plugin/run-avd-ci.sh create \
--api-level 35 \
--target google_apis \
--arch x86_64 \
--profile pixel_6 \
--avd-name "${AVD_NAME}"
retrace:
name: retrace (${{ matrix.backend.name }}, ${{ matrix.case.name }})
runs-on: ubuntu-latest
needs:
- build
- android-avd
- trace-cases
- trace-fixtures
if: ${{ always() && needs.build.result == 'success' && needs.android-avd.result == 'success' && needs.trace-cases.result == 'success' }}
timeout-minutes: 75
env:
AVD_NAME: mobilegl-ci
ANDROID_AVD_HOME: ${{ github.workspace }}/.android/avd
ANDROID_HOME: ${{ github.workspace }}/.android/sdk
ANDROID_SDK_ROOT: ${{ github.workspace }}/.android/sdk
strategy:
fail-fast: false
max-parallel: 4
matrix:
backend:
- name: DirectGLES
gpu: software
- name: DirectVulkan
gpu: lavapipe
case: ${{ fromJSON(needs.trace-cases.outputs.android) }}
steps:
- name: Set Swap Space
uses: pierotofy/set-swap-space@v1.0
with:
swap-size-gb: 8
- name: Checkout repo
uses: actions/checkout@v6
- name: Download trace fixture
uses: actions/download-artifact@v8
with:
name: MobileGL-trace-fixture-${{ matrix.case.name }}
path: trace-fixture-download
- name: Install trace fixture
run: |
mkdir -p tools/trace_replay/fixtures
find trace-fixture-download -type f -exec cp {} tools/trace_replay/fixtures/ \;
- name: Set artifact metadata
run: |
echo "date_today=$(date +'%Y-%m-%d')" >> "$GITHUB_ENV"
echo "EMULATOR_LOG=${RUNNER_TEMP}/mobilegl-emulator.log" >> "$GITHUB_ENV"
echo "EMULATOR_PID_FILE=${RUNNER_TEMP}/mobilegl-emulator.pid" >> "$GITHUB_ENV"
- name: Setup Android SDK
uses: android-actions/setup-android@v4
with:
accept-android-sdk-licenses: false
- name: Accept Android SDK licenses
run: yes | sdkmanager --licenses >/dev/null
- name: Restore Android AVD cache
id: android-avd-cache
uses: actions/cache/restore@v5
with:
path: |
${{ env.ANDROID_AVD_HOME }}
${{ env.ANDROID_SDK_ROOT }}/emulator
${{ env.ANDROID_SDK_ROOT }}/platform-tools
${{ env.ANDROID_SDK_ROOT }}/platforms/android-35
${{ env.ANDROID_SDK_ROOT }}/system-images/android-35/google_apis/x86_64
key: ${{ runner.os }}-mobilegl-avd-api35-google_apis-x86_64-pixel_6-v2-${{ hashFiles('android-plugin/run-avd-ci.sh') }}
- name: Download retrace APK
uses: actions/download-artifact@v8
with:
name: MobileGL-plugin-trace-release-${{ github.sha }}.apk
path: android-retrace-apks
- name: Enable KVM
run: |
echo 'KERNEL=="kvm", GROUP="kvm", MODE="0666", OPTIONS+="static_node=kvm"' | sudo tee /etc/udev/rules.d/99-kvm4all.rules
sudo udevadm control --reload-rules
sudo udevadm trigger --name-match=kvm
- name: Create AVD
if: steps.android-avd-cache.outputs.cache-hit != 'true'
run: |
sh android-plugin/run-avd-ci.sh create \
--api-level 35 \
--target google_apis \
--arch x86_64 \
--profile pixel_6 \
--avd-name "${AVD_NAME}"
- name: Launch Emulator
run: |
sh android-plugin/run-avd-ci.sh start \
--avd-name "${AVD_NAME}" \
--gpu "${{ matrix.backend.gpu }}" \
--emulator-log "${EMULATOR_LOG}" \
--pid-file "${EMULATOR_PID_FILE}" \
--boot-timeout 300
- name: Retrace and validate
env:
MOBILEGL_USE_ANGLE: ${{ matrix.backend.name == 'DirectGLES' && '1' || '0' }}
MOBILEGL_TRACE_ANGLE_VARIANT: ${{ matrix.case.name == 'minecraft-1.21.4-fabric-iris-bliss-in-world' && '90a62123d794' || 'ec889e6ea831' }}
MOBILEGL_MAGMA_R11G11B10F_FALLBACK: ${{ matrix.backend.name == 'DirectVulkan' && '1' || '0' }}
run: |
apk_file="android-retrace-apks/MobileGL-plugin-trace-release-${GITHUB_SHA}.apk"
test -f "${apk_file}"
extra_retrace_args=()
# Bliss needs the newer signed ANGLE variant plus sampler mipmap
# min-filter downgrading on ANGLE llvmpipe.
if [ "${{ matrix.backend.name }}" = "DirectGLES" ] && [ "${{ matrix.case.name }}" = "minecraft-1.21.4-fabric-iris-bliss-in-world" ]; then
extra_retrace_args+=(--avoid-angle-llvmpipe-sampler-mipmap-min-filter)
fi
if [ "${{ matrix.case.coherent_as_flush || false }}" = "true" ]; then
extra_retrace_args+=(--coherent-as-flush)
fi
run_retrace() {
timeout "$(( ${{ matrix.case.timeout_seconds }} + 300 ))" sh android-plugin/trace-replay-ci.sh \
--apk-file "${apk_file}" \
--package top.mobilegl.plugin.trace \
--backend "${{ matrix.backend.name }}" \
--result-root android-retrace-result \
--fixture-root android-retrace-fixture \
--case "${{ matrix.case.name }}" \
--trace-archive "${{ matrix.case.trace_archive }}" \
--trace-file "${{ matrix.case.trace_file }}" \
--golden "${{ matrix.case.golden }}" \
--alternate-golden "${{ matrix.case.alternate_golden || '' }}" \
--target-call "${{ matrix.case.target_call }}" \
--width "${{ matrix.case.width }}" \
--height "${{ matrix.case.height }}" \
--ssim-threshold "${{ matrix.case.ssim_threshold || '0.99' }}" \
--crop-x "${{ matrix.case.crop_x }}" \
--crop-y "${{ matrix.case.crop_y }}" \
--crop-width "${{ matrix.case.crop_width }}" \
--crop-height "${{ matrix.case.crop_height }}" \
--timeout-seconds "${{ matrix.case.timeout_seconds }}" \
"${extra_retrace_args[@]}"
}
retrace_status=0
run_retrace || retrace_status=$?
if [ "${retrace_status}" -eq 75 ]; then
echo "::warning::Android emulator infrastructure failed; restarting it and retrying this retrace once."
sh android-plugin/run-avd-ci.sh stop \
--avd-name "${AVD_NAME}" \
--emulator-log "${EMULATOR_LOG}" \
--pid-file "${EMULATOR_PID_FILE}"
adb kill-server || true
sleep 2
sh android-plugin/run-avd-ci.sh start \
--avd-name "${AVD_NAME}" \
--gpu "${{ matrix.backend.gpu }}" \
--emulator-log "${EMULATOR_LOG}" \
--pid-file "${EMULATOR_PID_FILE}" \
--boot-timeout 300
run_retrace
elif [ "${retrace_status}" -ne 0 ]; then
exit "${retrace_status}"
fi
- name: Collect retrace summary inputs
if: always()
run: |
safe_case="$(printf '%s' '${{ matrix.case.name }}' | sed 's/[^A-Za-z0-9._-]/_/g')"
result_dir="android-retrace-result/${safe_case}-${{ matrix.backend.name }}"
mkdir -p "${result_dir}"
if [ -s "${{ matrix.case.golden }}" ]; then
cp "${{ matrix.case.golden }}" "${result_dir}/${safe_case}-${{ matrix.backend.name }}-golden.png"
fi
if [ -n "${{ matrix.case.alternate_golden || '' }}" ] && [ -s "${{ matrix.case.alternate_golden || '' }}" ]; then
cp "${{ matrix.case.alternate_golden || '' }}" "${result_dir}/${safe_case}-${{ matrix.backend.name }}-alternate-golden.png"
fi
- name: Collect emulator diagnostics
if: always()
run: |
mkdir -p android-retrace-result/diagnostics
adb devices -l > android-retrace-result/diagnostics/adb-devices.txt || true
timeout 30 adb logcat -d -t 1000 > android-retrace-result/diagnostics/logcat.txt || true
if [ -f "${EMULATOR_LOG}" ]; then
cp "${EMULATOR_LOG}" android-retrace-result/diagnostics/emulator.log
fi
- name: Stop Emulator
if: always()
run: |
sh android-plugin/run-avd-ci.sh stop \
--avd-name "${AVD_NAME}" \
--emulator-log "${EMULATOR_LOG}" \
--pid-file "${EMULATOR_PID_FILE}"
- name: Upload Android retrace result
if: always()
uses: actions/upload-artifact@v7
with:
name: MobileGL-android-retrace-result-${{ env.date_today }}-${{ github.sha }}-${{ matrix.backend.name }}-${{ matrix.case.name }}
path: android-retrace-result/**
if-no-files-found: warn
retrace-summary:
name: retrace summary
runs-on: ubuntu-latest
needs: retrace
if: always()
steps:
- name: Checkout repo
uses: actions/checkout@v6
- name: Set artifact metadata
run: |
echo "date_today=$(date +'%Y-%m-%d')" >> "$GITHUB_ENV"
- name: Set up Node.js
uses: actions/setup-node@v7
with:
node-version: '22'
- name: Download Android retrace results
uses: actions/download-artifact@v8
with:
pattern: MobileGL-android-retrace-result-*
path: retrace-artifacts
- name: Render retrace summary
run: |
node tools/trace_replay/render_retrace_summary.mjs \
--input retrace-artifacts \
--output-dir android-retrace-summary \
--title "MobileGL Android retrace overview" \
--group-label "Android Emulator" \
--html mobilegl-android-retrace-overview.html
- name: Upload Android retrace summary
uses: actions/upload-artifact@v7
with:
path: android-retrace-summary/mobilegl-android-retrace-overview.html
archive: false
if-no-files-found: error
remove-artifact-clutter:
name: remove artifact clutter
runs-on: ubuntu-latest
needs: retrace-summary
if: always()
permissions:
actions: write
steps:
- name: Delete intermediate Android retrace artifacts
env:
GH_TOKEN: ${{ github.token }}
run: |
declare -A failed_cases=()
while IFS= read -r job_name; do
case_name="${job_name#retrace (*, }"
case_name="${case_name%)}"
failed_cases["${case_name}"]=1
done < <(
gh api --paginate "repos/${GITHUB_REPOSITORY}/actions/runs/${GITHUB_RUN_ID}/jobs?per_page=100" \
--jq '.jobs[] | select(.name | startswith("retrace (")) | select(.conclusion == "failure" or .conclusion == "cancelled" or .conclusion == "timed_out" or .conclusion == "action_required") | .name'
)
if ((${#failed_cases[@]})); then
echo "Retaining fixtures for failed retrace case(s):"
printf ' %s\n' "${!failed_cases[@]}"
else
echo "All retrace jobs succeeded; no fixtures need to be retained."
fi
deleted=0
retained=0
while IFS=$'\t' read -r artifact_id artifact_name; do
if [[ "${artifact_name}" == MobileGL-trace-fixture-* ]]; then
case_name="${artifact_name#MobileGL-trace-fixture-}"
if [[ -v "failed_cases[${case_name}]" ]]; then
echo "Retaining ${artifact_name} (${artifact_id}) for failed retrace."
((retained += 1))
continue
fi
fi
echo "Deleting ${artifact_name} (${artifact_id})"
gh api --method DELETE "repos/${GITHUB_REPOSITORY}/actions/artifacts/${artifact_id}"
((deleted += 1))
done < <(
gh api --paginate "repos/${GITHUB_REPOSITORY}/actions/runs/${GITHUB_RUN_ID}/artifacts?per_page=100" \
--jq '.artifacts[] | select(.name | startswith("MobileGL-trace-fixture-") or startswith("MobileGL-android-retrace-result-") or startswith("trace-fixture-") or startswith("retrace-result-")) | [.id, .name] | @tsv'
)
echo "Deleted ${deleted} intermediate Android artifact(s); retained ${retained} failed-retrace fixture(s)."
+573
View File
@@ -0,0 +1,573 @@
name: Test
on:
push:
branches:
- dev
- Feat/Backend-Direct-GLES
- Feat/Backend-Direct-Vulkan
workflow_dispatch:
jobs:
build-linux:
runs-on: ubuntu-latest
env:
BUILD_DIR: build-linux
CCACHE_BASEDIR: ${{ github.workspace }}
CCACHE_COMPRESS: "true"
CCACHE_DIR: ${{ github.workspace }}/.ccache
CCACHE_MAXSIZE: 4G
CCACHE_NOHASHDIR: "true"
steps:
- name: Set Swap Space
uses: pierotofy/set-swap-space@v1.0
with:
swap-size-gb: 32
- name: Checkout repo
uses: actions/checkout@v6
with:
submodules: recursive
- name: Get CMake
uses: lukka/get-cmake@v4.3.3
- name: Restore ccache
uses: actions/cache@v5
with:
path: .ccache
key: ${{ runner.os }}-test-${{ github.job }}-ccache-${{ github.ref_name }}-${{ github.run_id }}
restore-keys: |
${{ runner.os }}-test-${{ github.job }}-ccache-${{ github.ref_name }}-
${{ runner.os }}-test-${{ github.job }}-ccache-
- name: Prepare Vulkan SDK
uses: humbletim/setup-vulkan-sdk@v1.2.1
with:
vulkan-query-version: 1.4.304.1
vulkan-components: Vulkan-Headers, Vulkan-Loader
vulkan-use-cache: true
- name: Update glslang external sources
working-directory: 3rdparty/glslang
run: python update_glslang_sources.py
- name: Install build dependencies
run: |
sudo apt-get update
sudo apt-get install -y ccache clang-20 clang++-20 lld-20 libc++-20-dev libc++abi-20-dev libvulkan-dev libegl1-mesa-dev libgles2-mesa-dev libgl1-mesa-dri mesa-vulkan-drivers ninja-build
- name: Show installed toolchain
run: |
ccache --version
clang-20 --version
clang++-20 --version
ld.lld-20 --version || ld.lld --version || true
dpkg -l 'libc++*' 'libegl*' 'libgles*' 'mesa*' 'vulkan*' || true
- name: Configure CMake
run: |
if [ "${{ secrets.ACTIONS_STEP_DEBUG }}" = "true" ]; then
BUILD_TYPE=Debug
else
BUILD_TYPE=Release
fi
cmake -S . -B "${BUILD_DIR}" -G Ninja \
-DCMAKE_C_COMPILER=clang-20 \
-DCMAKE_CXX_COMPILER=clang++-20 \
-DCMAKE_C_COMPILER_LAUNCHER=ccache \
-DCMAKE_CXX_COMPILER_LAUNCHER=ccache \
-DCMAKE_BUILD_TYPE="${BUILD_TYPE}" \
-DMOBILEGL_LOG_ACTIVE_LEVEL=MOBILEGL_LOG_LEVEL_INFO \
-DMOBILEGL_BUILD_TEST=ON \
-DMOBILEGL_BUILD_BENCHMARK=ON \
-DMOBILEGL_BUILD_TRACE_REPLAY=OFF \
-DBENCHMARK_DOWNLOAD_DEPENDENCIES=ON \
-DBENCHMARK_ENABLE_TESTING=OFF \
-DCMAKE_POLICY_VERSION_MINIMUM=3.5
- name: Build
run: cmake --build "${BUILD_DIR}" --parallel "$(nproc)"
- name: Show ccache stats
if: always()
run: ccache --show-stats
- name: Package Linux runtime
run: |
mkdir -p ci-artifacts
mapfile -t SHARED_LIBS < <(find "${BUILD_DIR}" -type f \( -name '*.so' -o -name '*.so.*' \) -print | sort)
tar \
--exclude='*/CMakeFiles' \
--exclude='*.o' \
--exclude='*.a' \
--exclude='*.ninja*' \
--exclude='build.ninja' \
--exclude='cmake_install.cmake' \
-czf ci-artifacts/mobilegl-linux-runtime.tgz \
"${BUILD_DIR}/CTestTestfile.cmake" \
"${BUILD_DIR}/MobileGL/MG_Test" \
"${BUILD_DIR}/MobileGL/MG_Benchmark" \
"${SHARED_LIBS[@]}"
- name: Upload Linux runtime
uses: actions/upload-artifact@v7
with:
name: mobilegl-linux-runtime
path: ci-artifacts/mobilegl-linux-runtime.tgz
if-no-files-found: error
test:
runs-on: ubuntu-latest
needs: build-linux
steps:
- name: Checkout repo
uses: actions/checkout@v6
- name: Get CMake
uses: lukka/get-cmake@v4.3.3
- name: Install runtime dependencies
run: |
sudo apt-get update
sudo apt-get install -y libvulkan1 libegl1 libgles2 libgl1-mesa-dri mesa-vulkan-drivers
- name: Download Linux runtime
uses: actions/download-artifact@v8
with:
name: mobilegl-linux-runtime
path: .
- name: Unpack Linux runtime
run: tar -xzf mobilegl-linux-runtime.tgz
- name: Normalize CTest command paths
run: |
python - <<'PY'
from pathlib import Path
import re
for path in Path('build-linux').rglob('CTestTestfile.cmake'):
text = path.read_text()
text = re.sub(r'"[^"]*/cmake-[^"]*/bin/cmake"', '"cmake"', text)
path.write_text(text)
PY
- name: Test
working-directory: build-linux
run: |
if [ "${{ secrets.ACTIONS_STEP_DEBUG }}" = "true" ]; then
ctest -V -L unit --no-tests=error
else
ctest --output-on-failure -L unit --no-tests=error
fi
benchmark:
runs-on: ubuntu-latest
needs: build-linux
steps:
- name: Checkout repo
uses: actions/checkout@v6
- name: Get CMake
uses: lukka/get-cmake@v4.3.3
- name: Install runtime dependencies
# libegl-mesa0 is the EGL vendor library itself: DriverBench brings up a
# real GL context, and libegl1 is only glvnd's dispatch. It normally
# arrives as a Recommends of libegl1, which is too quiet a dependency for
# the one job that needs a working driver.
run: |
sudo apt-get update
sudo apt-get install -y libvulkan1 libegl1 libegl-mesa0 libgles2 libgl1-mesa-dri mesa-vulkan-drivers
- name: Download Linux runtime
uses: actions/download-artifact@v8
with:
name: mobilegl-linux-runtime
path: .
- name: Unpack Linux runtime
run: tar -xzf mobilegl-linux-runtime.tgz
- name: Normalize CTest command paths
run: |
python - <<'PY'
from pathlib import Path
import re
for path in Path('build-linux').rglob('CTestTestfile.cmake'):
text = path.read_text()
text = re.sub(r'"[^"]*/cmake-[^"]*/bin/cmake"', '"cmake"', text)
path.write_text(text)
PY
- name: Benchmark
working-directory: build-linux
run: ctest -V -C Release -L benchmark --no-tests=error
build-retrace:
runs-on: ubuntu-latest
needs:
- build-linux
- test
- benchmark
env:
BUILD_DIR: build-retrace
CCACHE_BASEDIR: ${{ github.workspace }}
CCACHE_COMPRESS: "true"
CCACHE_DIR: ${{ github.workspace }}/.ccache
CCACHE_MAXSIZE: 4G
CCACHE_NOHASHDIR: "true"
MOBILEGL_LIBRARY: ${{ github.workspace }}/build-linux/libMobileGL.so
steps:
- name: Set Swap Space
uses: pierotofy/set-swap-space@v1.0
with:
swap-size-gb: 32
- name: Checkout repo
uses: actions/checkout@v6
with:
submodules: recursive
- name: Get CMake
uses: lukka/get-cmake@v4.3.3
- name: Restore ccache
uses: actions/cache@v5
with:
path: .ccache
key: ${{ runner.os }}-test-${{ github.job }}-ccache-${{ github.ref_name }}-${{ github.run_id }}
restore-keys: |
${{ runner.os }}-test-${{ github.job }}-ccache-${{ github.ref_name }}-
${{ runner.os }}-test-${{ github.job }}-ccache-
- name: Prepare Vulkan SDK
uses: humbletim/setup-vulkan-sdk@v1.2.1
with:
vulkan-query-version: 1.4.304.1
vulkan-components: Vulkan-Headers, Vulkan-Loader
vulkan-use-cache: true
- name: Update glslang external sources
working-directory: 3rdparty/glslang
run: python update_glslang_sources.py
- name: Install dependencies
run: |
sudo apt-get update
sudo apt-get install -y ccache clang-20 clang++-20 lld-20 libc++-20-dev libc++abi-20-dev libvulkan-dev libegl1-mesa-dev libgles2-mesa-dev libgl1-mesa-dri mesa-vulkan-drivers ninja-build
- name: Show installed toolchain
run: |
ccache --version
clang-20 --version
clang++-20 --version
ld.lld-20 --version || ld.lld --version || true
dpkg -l 'libc++*' 'libegl*' 'libgles*' 'mesa*' 'vulkan*' || true
- name: Download Linux runtime
uses: actions/download-artifact@v8
with:
name: mobilegl-linux-runtime
path: .
- name: Unpack Linux runtime
run: |
tar -xzf mobilegl-linux-runtime.tgz
test -f "${MOBILEGL_LIBRARY}"
- name: Configure CMake
run: |
if [ "${{ secrets.ACTIONS_STEP_DEBUG }}" = "true" ]; then
BUILD_TYPE=Debug
else
BUILD_TYPE=Release
fi
cmake -S . -B "${BUILD_DIR}" -G Ninja \
-DCMAKE_C_COMPILER=clang-20 \
-DCMAKE_CXX_COMPILER=clang++-20 \
-DCMAKE_C_COMPILER_LAUNCHER=ccache \
-DCMAKE_CXX_COMPILER_LAUNCHER=ccache \
-DCMAKE_BUILD_TYPE="${BUILD_TYPE}" \
-DMOBILEGL_LOG_ACTIVE_LEVEL=MOBILEGL_LOG_LEVEL_INFO \
-DMOBILEGL_BUILD_TEST=OFF \
-DMOBILEGL_BUILD_BENCHMARK=OFF \
-DMOBILEGL_BUILD_TRACE_REPLAY=ON \
-DMOBILEGL_TRACE_REPLAY_MOBILEGL_LIBRARY="${MOBILEGL_LIBRARY}" \
-DCMAKE_POLICY_VERSION_MINIMUM=3.5
- name: Build trace replay
run: cmake --build "${BUILD_DIR}" --target mobilegl_trace_replay --parallel "$(nproc)"
- name: Show ccache stats
if: always()
run: ccache --show-stats
- name: Normalize CTest command paths
run: |
python - <<'PY'
from pathlib import Path
import re
for path in Path('build-retrace').rglob('CTestTestfile.cmake'):
text = path.read_text()
text = re.sub(r'"[^"]*/cmake-[^"]*/bin/cmake"', '"cmake"', text)
path.write_text(text)
PY
- name: Package trace replay
run: |
mkdir -p ci-artifacts
tar -czf ci-artifacts/mobilegl-trace-replay.tgz \
build-retrace/tools/trace_replay/mobilegl_trace_replay \
build-retrace/tools/trace_replay/CTestTestfile.cmake
- name: Upload trace replay
uses: actions/upload-artifact@v7
with:
name: mobilegl-trace-replay
path: ci-artifacts/mobilegl-trace-replay.tgz
if-no-files-found: error
trace-cases:
name: trace case matrix
runs-on: ubuntu-latest
needs:
- test
- benchmark
outputs:
names: ${{ steps.trace-cases.outputs.names }}
steps:
- name: Checkout repo
uses: actions/checkout@v6
- name: Load trace cases
id: trace-cases
run: echo "names=$(python3 tools/trace_replay/trace_cases.py --ci --format names)" >> "$GITHUB_OUTPUT"
trace-fixtures:
name: trace fixture (${{ matrix.case }})
runs-on: ubuntu-latest
needs: trace-cases
strategy:
fail-fast: false
max-parallel: 4
matrix:
case: ${{ fromJSON(needs.trace-cases.outputs.names) }}
steps:
- name: Checkout repo
uses: actions/checkout@v6
- name: Fetch trace fixture
run: bash .github/scripts/fetch-trace-fixture-lfs.sh '${{ matrix.case }}'
- name: Stage trace fixture
run: |
safe_case="$(printf '%s' '${{ matrix.case }}' | sed 's/[^A-Za-z0-9._-]/_/g')"
stage_dir="trace-fixtures/${safe_case}"
mkdir -p "${stage_dir}"
python3 tools/trace_replay/trace_cases.py --format fixture-files --case '${{ matrix.case }}' |
while IFS= read -r file; do
cp "${file}" "${stage_dir}/"
done
- name: Upload trace fixture
uses: actions/upload-artifact@v7
with:
name: trace-fixture-${{ matrix.case }}
path: trace-fixtures/**
if-no-files-found: error
retrace:
name: retrace (${{ matrix.backend }}, ${{ matrix.case }})
runs-on: ubuntu-latest
needs:
- build-linux
- build-retrace
- trace-cases
- trace-fixtures
if: ${{ always() && needs.build-linux.result == 'success' && needs.build-retrace.result == 'success' && needs.trace-cases.result == 'success' }}
strategy:
fail-fast: false
max-parallel: 4
matrix:
backend:
- DirectGLES
- DirectVulkan
case: ${{ fromJSON(needs.trace-cases.outputs.names) }}
steps:
- name: Set Swap Space
uses: pierotofy/set-swap-space@v1.0
with:
swap-size-gb: 16
- name: Checkout repo
uses: actions/checkout@v6
- name: Download trace fixture
uses: actions/download-artifact@v8
with:
name: trace-fixture-${{ matrix.case }}
path: trace-fixture-download
- name: Install trace fixture
run: |
mkdir -p tools/trace_replay/fixtures
find trace-fixture-download -type f -exec cp {} tools/trace_replay/fixtures/ \;
- name: Get CMake
uses: lukka/get-cmake@v4.3.3
- name: Install runtime dependencies
run: |
sudo apt-get update
sudo apt-get install -y libvulkan1 libegl1-mesa-dev libgles2-mesa-dev libgl1-mesa-dri mesa-vulkan-drivers
test -e /usr/lib/x86_64-linux-gnu/libEGL.so
test -e /usr/lib/x86_64-linux-gnu/libGLESv2.so
- name: Download Linux runtime
uses: actions/download-artifact@v8
with:
name: mobilegl-linux-runtime
path: .
- name: Download trace replay
uses: actions/download-artifact@v8
with:
name: mobilegl-trace-replay
path: .
- name: Unpack retrace runtime
run: |
tar -xzf mobilegl-linux-runtime.tgz
tar -xzf mobilegl-trace-replay.tgz
test -f build-linux/libMobileGL.so
test -f build-retrace/tools/trace_replay/mobilegl_trace_replay
- name: Retrace and validate
working-directory: build-retrace/tools/trace_replay
run: |
if [ '${{ matrix.backend }}' = 'DirectVulkan' ]; then
export MOBILEGL_MAGMA_R11G11B10F_FALLBACK=1
fi
# The blended depth-write quirk auto-enables only on Qualcomm, which no CI
# runner has, so force it on for the OIT case it exists to fix. ForceOn
# bypasses only the vendor gate, so this exercises the real strip on
# lavapipe. The Android AVD lane deliberately leaves it off, keeping the
# unstripped path covered for the same trace.
if [ '${{ matrix.backend }}' = 'DirectVulkan' ] \
&& [ '${{ matrix.case }}' = 'improved-transparency-minecraft-26.3' ]; then
export MOBILEGL_MAGMA_DISABLE_BLENDED_DEPTH_WRITE=1
fi
ctest -V --no-tests=error -R '^MobileGLTraceReplay\.${{ matrix.case }}\.${{ matrix.backend }}$'
- name: Upload actual image
if: always()
uses: actions/upload-artifact@v7
with:
name: retrace-result-${{ matrix.backend }}-${{ matrix.case }}
path: |
build-retrace/tools/trace_replay/${{ matrix.case }}/actual-images/**
build-retrace/tools/trace_replay/${{ matrix.case }}/${{ matrix.backend }}/output/**
if-no-files-found: warn
retrace-summary:
name: retrace summary
runs-on: ubuntu-latest
needs: retrace
if: ${{ always() && needs.retrace.result != 'skipped' }}
steps:
- name: Checkout repo
uses: actions/checkout@v6
- name: Set artifact metadata
run: |
echo "date_today=$(date +'%Y-%m-%d')" >> "$GITHUB_ENV"
- name: Set up Node.js
uses: actions/setup-node@v7
with:
node-version: '22'
- name: Download retrace results
uses: actions/download-artifact@v8
with:
pattern: retrace-result-*
path: retrace-artifacts
- name: Render retrace summary
run: |
node tools/trace_replay/render_retrace_summary.mjs \
--input retrace-artifacts \
--output-dir retrace-summary \
--title "MobileGL Linux retrace overview" \
--group-label "Linux" \
--html mobilegl-linux-retrace-overview.html
- name: Upload retrace summary
uses: actions/upload-artifact@v7
with:
path: retrace-summary/mobilegl-linux-retrace-overview.html
archive: false
if-no-files-found: error
remove-artifact-clutter:
name: remove artifact clutter
runs-on: ubuntu-latest
needs: retrace-summary
if: always()
permissions:
actions: write
steps:
- name: Delete intermediate Linux retrace artifacts
env:
GH_TOKEN: ${{ github.token }}
run: |
declare -A failed_cases=()
while IFS= read -r job_name; do
case_name="${job_name#retrace (*, }"
case_name="${case_name%)}"
failed_cases["${case_name}"]=1
done < <(
gh api --paginate "repos/${GITHUB_REPOSITORY}/actions/runs/${GITHUB_RUN_ID}/jobs?per_page=100" \
--jq '.jobs[] | select(.name | startswith("retrace (")) | select(.conclusion == "failure" or .conclusion == "cancelled" or .conclusion == "timed_out" or .conclusion == "action_required") | .name'
)
if ((${#failed_cases[@]})); then
echo "Retaining fixtures for failed retrace case(s):"
printf ' %s\n' "${!failed_cases[@]}"
else
echo "All retrace jobs succeeded; no fixtures need to be retained."
fi
deleted=0
retained=0
while IFS=$'\t' read -r artifact_id artifact_name; do
if [[ "${artifact_name}" == trace-fixture-* ]]; then
case_name="${artifact_name#trace-fixture-}"
if [[ -v "failed_cases[${case_name}]" ]]; then
echo "Retaining ${artifact_name} (${artifact_id}) for failed retrace."
((retained += 1))
continue
fi
fi
echo "Deleting ${artifact_name} (${artifact_id})"
gh api --method DELETE "repos/${GITHUB_REPOSITORY}/actions/artifacts/${artifact_id}"
((deleted += 1))
done < <(
gh api --paginate "repos/${GITHUB_REPOSITORY}/actions/runs/${GITHUB_RUN_ID}/artifacts?per_page=100" \
--jq '.artifacts[] | select(.name | startswith("trace-fixture-") or startswith("retrace-result-")) | [.id, .name] | @tsv'
)
echo "Deleted ${deleted} intermediate Linux artifact(s); retained ${retained} failed-retrace fixture(s)."
+24
View File
@@ -3,3 +3,27 @@
################################################################################ ################################################################################
/build /build
.cxx
/.vs
/out/build
CMakeSettings.json
MobileGL/MG_Test/out
MobileGL/MG_Test/.vs
MobileGLCodeManager.*
MobileGLCodeManager
.vscode
.clangd
MobileGL/MG_Test/build
/build_*
/cmake-build*
.idea
MobileGL/MG*/build*
MobileGL/MG*/cmake-build*
/android-plugin/.gradle
/android-plugin/build
/android-plugin/app/build
/android-plugin/app/src/trace/jniLibs
/android-plugin/local.properties
tools/trace_replay/work/
__pycache__/
*.py[cod]
+39
View File
@@ -0,0 +1,39 @@
[submodule "3rdparty/DiligentCore"]
path = 3rdparty/DiligentCore
url = https://github.com/DiligentGraphics/DiligentCore.git
[submodule "3rdparty/glslang"]
path = 3rdparty/glslang
url = https://github.com/MobileGL-Dev/glslang.git
[submodule "3rdparty/SPIRV-Cross"]
path = 3rdparty/SPIRV-Cross
url = https://github.com/KhronosGroup/SPIRV-Cross.git
[submodule "include/FastSTL"]
path = include/FastSTL
url = https://github.com/MobileGL-Dev/FastSTL.git
[submodule "3rdparty/tracy"]
path = 3rdparty/tracy
url = https://github.com/wolfpld/tracy.git
[submodule "3rdparty/xxHash"]
path = 3rdparty/xxHash
url = https://github.com/Cyan4973/xxHash.git
[submodule "3rdparty/VulkanMemoryAllocator"]
path = 3rdparty/VulkanMemoryAllocator
url = https://github.com/GPUOpen-LibrariesAndSDKs/VulkanMemoryAllocator.git
[submodule "3rdparty/Vulkan-Utility-Libraries"]
path = 3rdparty/Vulkan-Utility-Libraries
url = https://github.com/KhronosGroup/Vulkan-Utility-Libraries.git
[submodule "3rdparty/Vulkan-Headers"]
path = 3rdparty/Vulkan-Headers
url = https://github.com/KhronosGroup/Vulkan-Headers.git
[submodule "3rdparty/SPIRV-Reflect"]
path = 3rdparty/SPIRV-Reflect
url = https://github.com/KhronosGroup/SPIRV-Reflect.git
[submodule "3rdparty/apitrace"]
path = 3rdparty/apitrace
url = https://github.com/MobileGL-Dev/apitrace.git
[submodule "3rdparty/asio"]
path = 3rdparty/asio
url = https://github.com/chriskohlhoff/asio.git
[submodule "3rdparty/libfork"]
path = 3rdparty/libfork
url = https://github.com/ConorWilliams/libfork.git
Vendored Submodule
+1
Submodule 3rdparty/DiligentCore added at f36e638805
Vendored Submodule
+1
Submodule 3rdparty/SPIRV-Cross added at 072444287f
Vendored Submodule
+1
Submodule 3rdparty/SPIRV-Reflect added at 10b4f09a24
Vendored Submodule
+1
Submodule 3rdparty/Vulkan-Headers added at ad9ce1235e
Vendored Submodule
+1
Submodule 3rdparty/apitrace added at 10935bb5e4
Vendored Submodule
+1
Submodule 3rdparty/asio added at 8806a6803c
Vendored Submodule
+1
Submodule 3rdparty/glslang added at 900b29d449
Vendored Submodule
+1
Submodule 3rdparty/libfork added at 9b2b844a5f
Vendored Submodule
+1
Submodule 3rdparty/tracy added at e6b9ea4609
Vendored Submodule
+1
Submodule 3rdparty/xxHash added at 1d7b2a9d21
+566 -97
View File
@@ -2,123 +2,592 @@ cmake_minimum_required(VERSION 3.22.1)
project("MobileGL") project("MobileGL")
option(MOBILEGL_BUILD_TEST "Build MobileGL tests" ON )
option(MOBILEGL_BUILD_BENCHMARK "Build MobileGL benchmarks" ON )
# Headless end-to-end GPU scenarios (MobileGL/MG_IntegrationTest). They need a
# real GPU/ICD to do anything, so they are off by default for CI; every scenario
# skips cleanly where there is none. Registered under the `integration-gpu`
# ctest label so a run can select or exclude them.
option(MOBILEGL_BUILD_INTEGRATION_TEST "Build MobileGL headless GPU integration tests" OFF)
option(MOBILEGL_FORCE_RELEASE_OPT "Enable Release optimization flags in Debug build" ON )
option(MOBILEGL_ENABLE_TRACY "Enable tracy for profiling" OFF)
option(MOBILEGL_BUILD_TRACE_REPLAY "Build desktop apitrace replay runner" OFF)
option(MOBILEGL_TRACE_ANGLE_VARIANTS "Enable signed trace-APK ANGLE variant loading" OFF)
option(MOBILEGL_IOS "Build MobileGL for iOS instead of macOS when APPLE is set" OFF)
set(MOBILEGL_LOG_ACTIVE_LEVEL "MOBILEGL_LOG_LEVEL_INFO" CACHE STRING "MobileGL active log level macro")
set(MOBILEGL_VULKAN_LIBRARY "" CACHE FILEPATH "Vulkan loader/MoltenVK library to link for iOS builds")
if (ANDROID)
set(MOBILEGL_BUILD_TEST OFF CACHE BOOL "Build MobileGL tests" FORCE)
set(MOBILEGL_BUILD_BENCHMARK OFF CACHE BOOL "Build MobileGL benchmarks" FORCE)
endif()
option(MOBILEGL_ENABLE_LTO "Build with ThinLTO/IPO" OFF)
if ((NOT CMAKE_BUILD_TYPE STREQUAL "Debug" OR MOBILEGL_FORCE_RELEASE_OPT) AND MOBILEGL_ENABLE_LTO)
# Check if ThinLTO or LTO is suppported
include(CheckIPOSupported)
include(CheckCCompilerFlag)
include(CheckCXXCompilerFlag)
check_ipo_supported(RESULT LTOSupported OUTPUT LTOError)
check_c_compiler_flag("-flto" HAS_LTO_C)
check_cxx_compiler_flag("-flto" HAS_LTO_CXX)
if (LTOSupported OR (HAS_LTO_C AND HAS_LTO_CXX))
# Check ThinLTO
check_c_compiler_flag("-flto=thin" HAS_THINLTO_C)
check_cxx_compiler_flag("-flto=thin" HAS_THINLTO_CXX)
if (HAS_THINLTO_C AND HAS_THINLTO_CXX)
message(STATUS "ThinLTO supported, using -flto=thin")
add_compile_options(-flto=thin)
add_link_options(-flto=thin)
else()
# ThinLTO is not supported
message(STATUS "ThinLTO not available, fallback to CMAKE IPO")
set(CMAKE_INTERPROCEDURAL_OPTIMIZATION TRUE)
endif()
else()
message(STATUS "IPO not supported: ${LTOError}")
endif()
if (CMAKE_CXX_COMPILER_ID MATCHES "GNU|Clang" AND NOT MATCHES "AppleClang")
add_compile_options(-O3 -ffunction-sections -fdata-sections)
add_link_options(-Wl,--gc-sections)
elseif (CMAKE_CXX_COMPILER_ID MATCHES "MSVC")
# add_compile_options(/O2)
else ()
add_compile_options(-O2)
endif()
endif()
if (CMAKE_CXX_COMPILER_ID MATCHES "MSVC")
add_compile_options(/Zc:preprocessor)
add_compile_options(/Zc:__cplusplus)
endif()
enable_language(CXX) enable_language(CXX)
set(CMAKE_CXX_STANDARD 20) set(CMAKE_CXX_STANDARD 23)
set(CMAKE_CXX_STANDARD_REQUIRED ON) set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -w -fvisibility=hidden -funwind-tables -g -D_THREAD_SAFE -fPIC -stdlib=libc++") set(CMAKE_EXPORT_COMPILE_COMMANDS ON)
#set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -w -g -std=gnu99 -funwind-tables -O3 -fvisibility=hidden") set(CMAKE_POSITION_INDEPENDENT_CODE ON)
set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -static-libstdc++") if (MSVC)
set(CMAKE_CXX_FLAGS "/EHsc ${CMAKE_CXX_FLAGS}")
endif()
set(CMAKE_ANDROID_STL_TYPE c++_static) # Generate MGGitHash.h
execute_process(
COMMAND git rev-parse HEAD
WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}
OUTPUT_VARIABLE GIT_COMMIT_HASH_FULL
OUTPUT_STRIP_TRAILING_WHITESPACE
)
#set(CMAKE_BUILD_TYPE Release) string(SUBSTRING "${GIT_COMMIT_HASH_FULL}" 0 7 GIT_COMMIT_HASH_SHORT)
set(PROFILING OFF) configure_file(
${CMAKE_SOURCE_DIR}/MobileGL/MG_Util/Miscellany/MGGitHash.h.in
${CMAKE_BINARY_DIR}/generated/MGGitHash.h
@ONLY
)
find_library(GLSLANG_LIB glslang PATHS ${CMAKE_SOURCE_DIR}/libraries/arm64-v8a/) include_directories(${CMAKE_BINARY_DIR}/generated)
set(ENABLE_RTTI ON CACHE BOOL "Enables RTTI (will be took by glslang)" FORCE)
set(ENABLE_GLSLANG_BINARIES OFF CACHE BOOL "Enable glslangValidator/spirv-remap" FORCE)
set(ENABLE_SPVREMAPPER OFF CACHE BOOL "Enable SPVRemapper" FORCE)
set(ENABLE_OPT ON CACHE BOOL "Enable SPIRV-Tools opt usage in glslang" FORCE)
set(BUILD_EXTERNAL ON CACHE BOOL "Build external deps in External/" FORCE)
set(ENABLE_GLSLANG_INSTALL OFF CACHE BOOL "Install glslang targets" FORCE)
set(SPIRV_CROSS_C_API ON CACHE BOOL "Enable C API" FORCE)
set(SPIRV_CROSS_ENABLE_GLSL ON CACHE BOOL "Enable GLSL backend" FORCE)
set(SPIRV_CROSS_ENABLE_HLSL OFF CACHE BOOL "Disable HLSL backend" FORCE)
set(SPIRV_CROSS_ENABLE_MSL OFF CACHE BOOL "Disable MSL backend" FORCE)
set(SPIRV_CROSS_ENABLE_CPP OFF CACHE BOOL "Disable C++ API target" FORCE)
set(SPIRV_CROSS_CLI OFF CACHE BOOL "Disable CLI binary" FORCE)
set(SPIRV_CROSS_STATIC ON CACHE BOOL "Prefer static libs" FORCE)
set(SPIRV_REFLECT_EXECUTABLE OFF CACHE BOOL "Build spirv-reflect executable" FORCE)
set(SPIRV_REFLECT_STATIC_LIB ON CACHE BOOL "Build a SPIRV-Reflect static library" FORCE)
set(SPIRV_REFLECT_BUILD_TESTS OFF CACHE BOOL "Build the SPIRV-Reflect test suite" FORCE)
set(SPIRV_REFLECT_ENABLE_ASSERTS OFF CACHE BOOL "Enable asserts for debugging" FORCE)
set(SPIRV_REFLECT_ENABLE_ASAN OFF CACHE BOOL "Use address sanitization" FORCE)
set(SPIRV_REFLECT_INSTALL OFF CACHE BOOL "Whether to install" FORCE)
# add_subdirectory(3rdparty/DiligentCore)
add_subdirectory(3rdparty/glslang)
add_subdirectory(3rdparty/SPIRV-Cross)
add_subdirectory(3rdparty/VulkanMemoryAllocator)
add_subdirectory(3rdparty/Vulkan-Headers)
add_subdirectory(3rdparty/Vulkan-Utility-Libraries)
add_subdirectory(3rdparty/SPIRV-Reflect)
set(XXHASH_BUILD_XXHSUM OFF)
option(BUILD_SHARED_LIBS OFF)
add_subdirectory(3rdparty/xxHash/build/cmake xxhash_build EXCLUDE_FROM_ALL)
set(TRACY_ENABLE ${MOBILEGL_ENABLE_TRACY} CACHE BOOL "Enable Tracy, this is an internal variable" FORCE)
if (TRACY_ENABLE)
set(TRACY_ON_DEMAND ON CACHE BOOL "Enable profiling only connected" FORCE)
set(TRACY_NO_EXIT OFF CACHE BOOL "Don't exit Tracy until connected" FORCE)
set(TRACY_DELAYED_INIT ON CACHE BOOL "Don't init Tracy on library load" FORCE)
set(TRACY_MANUAL_LIFETIME ON CACHE BOOL "Manually control Tracy lifetime" FORCE)
set(TRACY_NO_CRASH_HANDLER ON CACHE BOOL "Disable crash handling" FORCE)
add_subdirectory(3rdparty/tracy)
endif ()
set(SOURCE_FILES
MobileGL/Init.cpp
MobileGL/GlobalObjects.cpp
MobileGL/ConfigLoader.cpp
MobileGL/MG_Util/Debug/Log.cpp
MobileGL/MG_Util/Async/JobNode.cpp
MobileGL/MG_Util/Async/ShaderCompilePool.cpp
MobileGL/MG_Util/Math/VectorTypes.cpp
MobileGL/MG_Util/Metrics/TextureMetrics.cpp
MobileGL/MG_Util/Metrics/BufferMetrics.cpp
MobileGL/MG_Util/Converters/GLToStr/GLEnumConverter.cpp
MobileGL/MG_Util/Converters/EGLToStr/EGLEnumConverter.cpp
MobileGL/MG_Util/Converters/MGToStr/DataTypeConverter.cpp
MobileGL/MG_Util/Converters/MGToStr/RenderStateEnumConverter.cpp
MobileGL/MG_Util/Converters/MGToStr/GLExtensionConverter.cpp
MobileGL/MG_Util/Converters/MGToStr/BufferEnumConverter.cpp
MobileGL/MG_Util/Converters/MGToStr/FramebufferEnumConverter.cpp
MobileGL/MG_Util/Converters/MGToStr/TextureEnumConverter.cpp
MobileGL/MG_Util/Converters/GLToGlslang/ProgramEnumConverter.cpp
MobileGL/MG_Util/Converters/MGToGL/ErrorCodeConverter.cpp
MobileGL/MG_Util/Converters/MGToGL/BufferEnumConverter.cpp
MobileGL/MG_Util/Converters/MGToGL/FramebufferEnumConverter.cpp
MobileGL/MG_Util/Converters/MGToGL/TextureEnumConverter.cpp
MobileGL/MG_Util/Converters/MGToGL/DataTypeConverter.cpp
MobileGL/MG_Util/Converters/MGToGL/RenderStateEnumConverter.cpp
MobileGL/MG_Util/Converters/MGToGL/ProgramEnumConverter.cpp
MobileGL/MG_Util/Converters/GLToMG/BufferEnumConverter.cpp
MobileGL/MG_Util/Converters/GLToMG/FramebufferEnumConverter.cpp
MobileGL/MG_Util/Converters/GLToMG/TextureEnumConverter.cpp
MobileGL/MG_Util/Converters/GLToMG/DataTypeConverter.cpp
MobileGL/MG_Util/Converters/GLToMG/RenderStateEnumConverter.cpp
MobileGL/MG_Util/Converters/GLToMG/ProgramEnumConverter.cpp
MobileGL/MG_Util/Converters/MGToMG/TextureEnumConverter.cpp
MobileGL/MG_Util/Converters/MGToVk/RenderStateEnumConverter.cpp
MobileGL/MG_Util/Converters/MGToVk/TextureEnumConverter.cpp
MobileGL/MG_Util/Classifiers/TextureEnumClassifier.cpp
MobileGL/MG_Util/ShaderTranspiler/CompileEnv.cpp
MobileGL/MG_Util/ShaderTranspiler/ShaderCompiler.cpp
MobileGL/MG_Util/ShaderTranspiler/SpvcSession.cpp
MobileGL/MG_Util/ShaderTranspiler/ShaderSourceProcessor.cpp
MobileGL/MG_Util/ShaderTranspiler/glslang/TMglGlslIoResolver.cpp
MobileGL/MG_Util/ShaderTranspiler/SpirvPasses/FlattenInterfaceStructPass.cpp
MobileGL/MG_Util/ShaderTranspiler/SpirvPasses/EliminateFloatEqualsZeroPass.cpp
MobileGL/MG_Util/ShaderTranspiler/SpirvPasses/RenameSamplerFunctionParameterPass.cpp
MobileGL/MG_Util/ShaderTranspiler/SpirvPasses/RenameBuiltinShadowingFunctionsPass.cpp
MobileGL/MG_Util/ShaderTranspiler/SpirvPasses/DecomposeWorkgroupVec3Pass.cpp
MobileGL/MG_Util/ShaderTranspiler/SpirvPasses/DecoratePositionInvariantPass.cpp
MobileGL/MG_Util/ShaderTranspiler/SpirvPasses/LowerDrawParametersPass.cpp
MobileGL/MG_Util/ShaderTranspiler/SpirvPasses/PackDoubleVertexInputsPass.cpp
MobileGL/MG_Util/ShaderTranspiler/SpirvPasses/RebaseInstanceIndexPass.cpp
MobileGL/MG_Util/ShaderTranspiler/SpirvPasses/NormalizeRectCoordinatesPass.cpp
MobileGL/MG_Util/ShaderTranspiler/SpirvPasses/StripUboMemberRelaxedPrecisionPass.cpp
MobileGL/MG_Util/ShaderTranspiler/SpirvPasses/StripNoPerspectivePass.cpp
MobileGL/MG_Util/ShaderTranspiler/SpirvPasses/EmulateNoPerspectivePass.cpp
MobileGL/MG_Util/BackendLoaders/OpenGL/Loader.cpp
MobileGL/MG_Util/BackendLoaders/Vulkan/Loader.cpp
MobileGL/MG_Util/SelfTest/DriverPost.cpp
MobileGL/MG_Util/Texture/PixelStoreProcessor.cpp
MobileGL/MG_Util/Texture/TextureFormatProcessor.cpp
MobileGL/MG_Impl/GLXImpl/Exporting/Definitions.cpp
MobileGL/MG_Impl/GLXImpl/GLXImpl.cpp
MobileGL/MG_Impl/GLXImpl/LookUp/LookUp.cpp
MobileGL/MG_Impl/EGLImpl/Exporting/Definitions.cpp
MobileGL/MG_Impl/EGLImpl/EGLImpl.cpp
# @INSERTION_POINT:SOURCE_FILE_GLIMPL@ #
MobileGL/MG_Impl/GLImpl/Sampler/Validators.cpp
MobileGL/MG_Impl/GLImpl/Sampler/GL_Sampler.cpp
MobileGL/MG_Impl/GLImpl/Drawing/GL_Drawing.cpp
MobileGL/MG_Impl/GLImpl/RenderState/GL_RenderState.cpp
MobileGL/MG_Impl/GLImpl/Framebuffer/Validators.cpp
MobileGL/MG_Impl/GLImpl/Framebuffer/GL_Framebuffer.cpp
MobileGL/MG_Impl/GLImpl/Program/GL_Program.cpp
MobileGL/MG_Impl/GLImpl/Program/ProgramInterface.cpp
MobileGL/MG_Impl/GLImpl/Program/GL_ProgramPipeline.cpp
MobileGL/MG_Impl/GLImpl/Texture/GL_Texture.cpp
MobileGL/MG_Impl/GLImpl/Texture/Validators.cpp
MobileGL/MG_Impl/GLImpl/Texture/ProxyTexture.cpp
MobileGL/MG_Impl/GLImpl/VertexArray/GL_VertexArray.cpp
MobileGL/MG_Impl/GLImpl/VertexArray/Validators.cpp
MobileGL/MG_Impl/GLImpl/Buffer/GL_Buffer.cpp
MobileGL/MG_Impl/GLImpl/Buffer/Validators.cpp
MobileGL/MG_Impl/GLImpl/Exporting/Definitions.cpp
MobileGL/MG_Impl/GLImpl/Getter/GL_Getter.cpp
MobileGL/MG_Impl/GLImpl/Sync/GL_Sync.cpp
MobileGL/MG_Impl/GLImpl/Query/GL_Query.cpp
MobileGL/MG_Impl/Init.cpp
MobileGL/MG_Impl/GetProcAddress.cpp
MobileGL/MG_Backend/Init.cpp
MobileGL/MG_Backend/BackendObject.cpp
MobileGL/MG_Backend/DirectGLES/DirectGLES.cpp
MobileGL/MG_Backend/DirectGLES/BackendObject_DirectGLES.cpp
MobileGL/MG_Backend/DirectGLES/Utils.cpp
MobileGL/MG_Backend/DirectGLES/Managers.cpp
MobileGL/MG_Backend/DirectGLES/MultiDraw.cpp
MobileGL/MG_Backend/DirectVulkan/DirectVulkan.cpp
MobileGL/MG_Backend/DirectVulkan/BackendObject_DirectVulkan.cpp
MobileGL/MG_Backend/DirectVulkan/VmaImpl.cpp
MobileGL/MG_Backend/DirectVulkan/Renderer/VulkanRenderer.cpp
MobileGL/MG_Backend/DirectVulkan/Renderer/SwapchainObject.cpp
MobileGL/MG_Backend/DirectVulkan/Renderer/FrameContext.cpp
MobileGL/MG_Backend/DirectVulkan/Renderer/PipelineFactory.cpp
MobileGL/MG_Backend/DirectVulkan/Renderer/ProgramFactory.cpp
MobileGL/MG_Backend/DirectVulkan/Renderer/UniformManager.cpp
MobileGL/MG_Backend/DirectVulkan/Renderer/BufferArena.cpp
MobileGL/MG_Backend/DirectVulkan/Renderer/VkBufferManager.cpp
MobileGL/MG_Backend/DirectVulkan/Renderer/VertexInputStateBuilder.cpp
MobileGL/MG_Backend/DirectVulkan/Renderer/VertexInputStateFactory.cpp
MobileGL/MG_Backend/DirectVulkan/Renderer/VkBufferObject.cpp
MobileGL/MG_Backend/DirectVulkan/Renderer/VkTextureManager.cpp
MobileGL/MG_Backend/DirectVulkan/Renderer/VkTimerQueryManager.cpp
MobileGL/MG_Backend/DirectVulkan/Renderer/VkSamplerManager.cpp
MobileGL/MG_Backend/DirectVulkan/Renderer/VkClearManager.cpp
MobileGL/MG_Backend/DirectVulkan/Renderer/VkRenderPassManager.cpp
MobileGL/MG_State/GLState/Core.cpp
MobileGL/MG_State/EGLState/Core.cpp
MobileGL/MG_State/GLState/ErrorState/Error.cpp
MobileGL/MG_State/GLState/BufferState/BufferState.cpp
MobileGL/MG_State/GLState/BufferState/BufferObject.cpp
MobileGL/MG_State/GLState/VertexArrayState/VertexArrayState.cpp
MobileGL/MG_State/GLState/VertexArrayState/VertexArrayObject.cpp
MobileGL/MG_State/GLState/TextureState/MipmapStorage.cpp
MobileGL/MG_State/GLState/TextureState/TextureObject.cpp
MobileGL/MG_State/GLState/TextureState/TextureObject1D.cpp
MobileGL/MG_State/GLState/TextureState/TextureObject2D.cpp
MobileGL/MG_State/GLState/TextureState/TextureObject2DCube.cpp
MobileGL/MG_State/GLState/TextureState/TextureObject3D.cpp
MobileGL/MG_State/GLState/TextureState/TextureObjectBuffer.cpp
MobileGL/MG_State/GLState/TextureState/TextureUnit.cpp
MobileGL/MG_State/GLState/TextureState/TextureState.cpp
MobileGL/MG_State/GLState/ProgramState/ProgramObject.cpp
MobileGL/MG_State/GLState/ProgramState/ProgramLinkTask.cpp
MobileGL/MG_State/GLState/ProgramState/ShaderCompileTask.cpp
MobileGL/MG_State/GLState/ProgramState/ShaderObject.cpp
MobileGL/MG_State/GLState/ProgramState/ShaderPreprocessCache.cpp
MobileGL/MG_State/GLState/ProgramState/ShaderCompileAdoptionMap.cpp
MobileGL/MG_State/GLState/ProgramState/ProgramState.cpp
MobileGL/MG_State/GLState/RenderState/RenderState.cpp
MobileGL/MG_State/GLState/FramebufferState/FramebufferObject.cpp
MobileGL/MG_State/GLState/FramebufferState/FramebufferState.cpp
MobileGL/MG_State/GLState/SamplerState/SamplerObject.cpp
MobileGL/MG_State/GLState/SamplerState/SamplerState.cpp
MobileGL/MG_State/GLState/RenderbufferState/RenderbufferObject.cpp
MobileGL/MG_State/GLState/RenderbufferState/RenderbufferState.cpp
)
if (APPLE AND NOT MOBILEGL_IOS)
list(APPEND SOURCE_FILES
MobileGL/MG_Impl/CGLImpl/CGLImpl.cpp
MobileGL/MG_Impl/CGLImpl/Exporting/Definitions.cpp
MobileGL/MG_Impl/DyldInterpose/DyldInterpose.cpp
MobileGL/MG_Impl/NSOpenGLImpl/NSOpenGLImpl.cpp
)
endif()
if (ANDROID)
list(APPEND SOURCE_FILES
MobileGL/MG_Util/SelfTest/DriverPostJni.cpp
MobileGL/MG_Util/SelfTest/DriverBenchJni.cpp
)
endif()
if (WIN32)
list(APPEND SOURCE_FILES
MobileGL/MG_Impl/WGLImpl/WGLImpl.cpp
MobileGL/MG_Impl/WGLImpl/Exporting/Definitions.cpp
)
endif()
# The shader-compile pool runs standalone Asio on real threads. This host's glibc (>= 2.34)
# merged pthread into libc, so it links without asking, but the NDK and musl are not
# guaranteed to be as forgiving - ask for it explicitly rather than rely on the accident.
find_package(Threads REQUIRED)
set(MOBILEGL_LINK_LIBRARIES
glslang::glslang
spirv-cross-c
SPIRV-Tools-opt
SPIRV-Tools
xxHash::xxhash
GPUOpen::VulkanMemoryAllocator
Vulkan::UtilityHeaders
spirv-reflect-static
Threads::Threads
)
set(MOBILEGL_COMPILE_DEF
-DVMA_STATIC_VULKAN_FUNCTIONS=0
-DVMA_DYNAMIC_VULKAN_FUNCTIONS=1
-DVMA_VULKAN_VERSION=1001000
# Header-only Asio, no Boost, no deprecated interfaces. Set on the definition list
# rather than per-target so the shared library and the _s static target agree.
-DASIO_STANDALONE
-DASIO_NO_DEPRECATED
)
message(STATUS "MOBILEGL_COMPILE_DEF=${MOBILEGL_COMPILE_DEF}")
set(MOBILEGL_INCLUDE_DIR
${CMAKE_SOURCE_DIR}/include
${CMAKE_SOURCE_DIR}/MobileGL
${spirv-tools_SOURCE_DIR}
${spirv-tools_SOURCE_DIR}/include
${spirv-tools_BINARY_DIR}
${SPIRV-Headers_SOURCE_DIR}/include
# Header-only submodule: no add_subdirectory, no link target. Only
# MG_Util/Async/ShaderCompilePool.cpp includes it, and it stays behind that file's
# pimpl so no consumer target needs this path.
${CMAKE_SOURCE_DIR}/3rdparty/asio/asio/include
# The second shader-compile execution engine (MOBILEGL_ASYNC_POOL=libfork), on the
# same terms as Asio above: header-only, no add_subdirectory (its CMakeLists only
# declares an INTERFACE target plus install/test scaffolding we do not want), no link
# target, and reachable from exactly one translation unit. libfork's own
# target_compile_features asks for cxx_std_23, which this project already sets
# globally, so its C++20 coroutines need no per-source standard override.
${CMAKE_SOURCE_DIR}/3rdparty/libfork/include
)
add_library(${CMAKE_PROJECT_NAME} SHARED add_library(${CMAKE_PROJECT_NAME} SHARED
MG/Init.cpp ${SOURCE_FILES}
# MG_GL/Implementations/GLX
MG/MG_GL/Implementations/GLX/GLXFuncsDefinitions/GLXFuncsDefinitions.cpp
# MG_GL/Implementations/GL
MG/MG_GL/Implementations/GL/GLFuncsDefinitions/GLFuncsDefinitions.cpp
MG/MG_GL/Implementations/GL/Getter/GL_Getter.cpp
MG/MG_GL/Implementations/GL/Getter/BackendInfo.cpp
MG/MG_GL/Implementations/GL/Framebuffer/GL_Framebuffer.cpp
MG/MG_GL/Implementations/GL/Common/GL_Common.cpp
MG/MG_GL/Implementations/GL/Buffer/GL_Buffer.cpp
MG/MG_GL/Implementations/GL/Drawing/GL_Drawing.cpp
MG/MG_GL/Implementations/GL/Program/GL_Program.cpp
MG/MG_GL/Implementations/GL/Texture/GL_Texture.cpp
MG/MG_GL/Implementations/GL/VertexArray/GL_VertexArray.cpp
# MG_GL/Implementations/GLX
MG/MG_GL/Implementations/GLX/LookUp/LookUp.cpp
# MG_GL/Implementations/EGL
MG/MG_GL/Implementations/EGL/VK/EGL_EMU.cpp
MG/MG_GL/Implementations/EGL/GLES/EGL_WRAP.cpp
# MG_GL/State
MG/MG_GL/State/Core/GLState.cpp
MG/MG_GL/State/Common/CommonState.cpp
MG/MG_GL/State/Texture/TextureState.cpp
MG/MG_GL/State/VertexArray/VertexArrayState.cpp
MG/MG_GL/State/Buffer/BufferState.cpp
MG/MG_GL/State/Program/ShaderObject.cpp
MG/MG_GL/State/Program/ProgramState.cpp
MG/MG_GL/State/Framebuffer/FramebufferState.cpp
# MG_GL/BackendLoader
MG/MG_GL/BackendLoader/GLES/Loader.cpp
# MG_UTIL/Debug
MG/MG_UTIL/Debug/Debug.cpp
# MG_UTIL/Program
MG/MG_UTIL/Program/DebugTool.cpp
MG/MG_UTIL/Program/GLSLTool.cpp
# MG_RHI/GLES
MG/MG_RHI/GLES/Test/TestDrawing.cpp
) )
target_include_directories(${CMAKE_PROJECT_NAME} PRIVATE ./includes) if (WIN32)
# The wgl* entry points are exported via .def (see the comment in wgl.def);
# only the shared library links it.
target_sources(${CMAKE_PROJECT_NAME} PRIVATE
MobileGL/MG_Impl/WGLImpl/Exporting/wgl.def
)
endif()
if (CMAKE_BUILD_TYPE STREQUAL "Debug")
set_target_properties(${CMAKE_PROJECT_NAME} PROPERTIES
C_VISIBILITY_PRESET default
CXX_VISIBILITY_PRESET default
VISIBILITY_INLINES_HIDDEN OFF
)
else()
set_target_properties(${CMAKE_PROJECT_NAME} PROPERTIES
C_VISIBILITY_PRESET hidden
CXX_VISIBILITY_PRESET hidden
VISIBILITY_INLINES_HIDDEN ON
)
endif()
target_include_directories(${CMAKE_PROJECT_NAME} PUBLIC
${MOBILEGL_INCLUDE_DIR}
)
target_link_libraries(${CMAKE_PROJECT_NAME} target_link_libraries(${CMAKE_PROJECT_NAME}
${CMAKE_SOURCE_DIR}/library/arm64-v8a/libglslang.a PUBLIC
${CMAKE_SOURCE_DIR}/library/arm64-v8a/libspirv-cross-c-shared.so ${MOBILEGL_LINK_LIBRARIES}
#${CMAKE_SOURCE_DIR}/library/arm64-v8a/libshaderconv.so
${CMAKE_SOURCE_DIR}/library/arm64-v8a/libGenericCodeGen.a
${CMAKE_SOURCE_DIR}/library/arm64-v8a/libglslang-default-resource-limits.a
${CMAKE_SOURCE_DIR}/library/arm64-v8a/libMachineIndependent.a
${CMAKE_SOURCE_DIR}/library/arm64-v8a/libOSDependent.a
${CMAKE_SOURCE_DIR}/library/arm64-v8a/libSPIRV-Tools-diff.a
${CMAKE_SOURCE_DIR}/library/arm64-v8a/libSPIRV-Tools-link.a
${CMAKE_SOURCE_DIR}/library/arm64-v8a/libSPIRV-Tools-lint.a
${CMAKE_SOURCE_DIR}/library/arm64-v8a/libSPIRV-Tools-opt.a
${CMAKE_SOURCE_DIR}/library/arm64-v8a/libSPIRV-Tools-reduce.a
${CMAKE_SOURCE_DIR}/library/arm64-v8a/libSPIRV-Tools.a
${CMAKE_SOURCE_DIR}/library/arm64-v8a/libSPIRV.a
${CMAKE_SOURCE_DIR}/library/arm64-v8a/libSPVRemapper.a
android
log
EGL
vulkan
) )
target_include_directories(MobileGL PUBLIC target_compile_definitions(${CMAKE_PROJECT_NAME}
${CMAKE_SOURCE_DIR}/include PUBLIC
${MOBILEGL_COMPILE_DEF}
MOBILEGL_LOG_ACTIVE_LEVEL=${MOBILEGL_LOG_ACTIVE_LEVEL}
$<$<BOOL:${MOBILEGL_TRACE_ANGLE_VARIANTS}>:MOBILEGL_TRACE_ANGLE_VARIANTS=1>
)
if(UNIX AND NOT APPLE AND NOT ANDROID)
foreach(MOBILEGL_LOADER_ALIAS
libEGL.so libEGL.so.1)
add_custom_command(TARGET ${CMAKE_PROJECT_NAME} POST_BUILD
COMMAND ${CMAKE_COMMAND} -E create_symlink
"$<TARGET_FILE_NAME:${CMAKE_PROJECT_NAME}>"
"$<TARGET_FILE_DIR:${CMAKE_PROJECT_NAME}>/${MOBILEGL_LOADER_ALIAS}"
COMMENT "Creating ${MOBILEGL_LOADER_ALIAS} alias for Linux GL/EGL loaders"
) )
endforeach()
endif()
if(WIN32)
# Drop-in for the classic GL loader path: a copy named opengl32.dll placed
# next to a host executable is what LoadLibrary("opengl32.dll") and gdi32's
# pixel-format forwarding will resolve.
add_custom_command(TARGET ${CMAKE_PROJECT_NAME} POST_BUILD
COMMAND ${CMAKE_COMMAND} -E copy_if_different
"$<TARGET_FILE:${CMAKE_PROJECT_NAME}>"
"$<TARGET_FILE_DIR:${CMAKE_PROJECT_NAME}>/opengl32.dll"
COMMENT "Creating opengl32.dll drop-in copy"
)
endif()
if (PROFILING) if(NOT ANDROID)
find_package(Threads) add_library(${CMAKE_PROJECT_NAME}_s STATIC
include_directories(${CMAKE_SOURCE_DIR}/3rdparty/perfetto/sdk) ${SOURCE_FILES}
add_library(perfetto STATIC ${CMAKE_SOURCE_DIR}/3rdparty/perfetto/sdk/perfetto.cc) )
target_link_libraries(MobileGL perfetto ${CMAKE_THREAD_LIBS_INIT})
target_compile_definitions(MobileGL PUBLIC PROFILING=1) if (CMAKE_BUILD_TYPE STREQUAL "Debug")
set_target_properties(${CMAKE_PROJECT_NAME}_s PROPERTIES
C_VISIBILITY_PRESET default
CXX_VISIBILITY_PRESET default
VISIBILITY_INLINES_HIDDEN OFF
)
else()
set_target_properties(${CMAKE_PROJECT_NAME}_s PROPERTIES
C_VISIBILITY_PRESET hidden
CXX_VISIBILITY_PRESET hidden
VISIBILITY_INLINES_HIDDEN ON
)
endif()
target_include_directories(${CMAKE_PROJECT_NAME}_s PUBLIC
${MOBILEGL_INCLUDE_DIR}
)
target_link_libraries(${CMAKE_PROJECT_NAME}_s
PUBLIC
${MOBILEGL_LINK_LIBRARIES}
)
target_compile_definitions(${CMAKE_PROJECT_NAME}_s
PUBLIC
${MOBILEGL_COMPILE_DEF}
MOBILEGL_LOG_ACTIVE_LEVEL=${MOBILEGL_LOG_ACTIVE_LEVEL}
)
endif()
if (TRACY_ENABLE)
target_link_libraries(${CMAKE_PROJECT_NAME} PUBLIC Tracy::TracyClient)
target_link_libraries(${CMAKE_PROJECT_NAME}_s PUBLIC Tracy::TracyClient)
target_compile_definitions(${CMAKE_PROJECT_NAME} PUBLIC -DTRACY_ENABLE)
target_compile_definitions(${CMAKE_PROJECT_NAME}_s PUBLIC -DTRACY_ENABLE)
endif ()
if (ANDROID)
target_link_libraries(${CMAKE_PROJECT_NAME} PUBLIC
android
log
vulkan
)
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"
objc)
if(TARGET ${CMAKE_PROJECT_NAME}_s)
target_link_libraries(${CMAKE_PROJECT_NAME}_s PUBLIC
"-framework Cocoa"
"-framework CoreVideo"
"-framework QuartzCore"
"-framework Foundation"
"-framework OpenGL"
objc)
endif()
endif()
if (APPLE AND MOBILEGL_IOS)
target_compile_definitions(${CMAKE_PROJECT_NAME} PUBLIC MOBILEGL_IOS=1 _LIBCPP_DISABLE_AVAILABILITY)
target_link_libraries(${CMAKE_PROJECT_NAME} PUBLIC
"-framework CoreGraphics"
"-framework Foundation"
"-framework QuartzCore"
objc)
if (MOBILEGL_VULKAN_LIBRARY)
target_link_libraries(${CMAKE_PROJECT_NAME} PUBLIC "${MOBILEGL_VULKAN_LIBRARY}")
endif()
if(TARGET ${CMAKE_PROJECT_NAME}_s)
target_compile_definitions(${CMAKE_PROJECT_NAME}_s PUBLIC MOBILEGL_IOS=1 _LIBCPP_DISABLE_AVAILABILITY)
target_link_libraries(${CMAKE_PROJECT_NAME}_s PUBLIC
"-framework CoreGraphics"
"-framework Foundation"
"-framework QuartzCore"
objc)
if (MOBILEGL_VULKAN_LIBRARY)
target_link_libraries(${CMAKE_PROJECT_NAME}_s PUBLIC "${MOBILEGL_VULKAN_LIBRARY}")
endif()
endif()
endif()
if (NOT ANDROID AND NOT MOBILEGL_IOS)
find_package(Vulkan)
if (Vulkan_FOUND)
target_link_libraries(${CMAKE_PROJECT_NAME} PUBLIC Vulkan::Vulkan Vulkan::Headers)
target_link_libraries(${CMAKE_PROJECT_NAME}_s PUBLIC Vulkan::Vulkan Vulkan::Headers)
target_include_directories(${CMAKE_PROJECT_NAME} PUBLIC ${Vulkan_INCLUDE_DIR})
target_include_directories(${CMAKE_PROJECT_NAME}_s PUBLIC ${Vulkan_INCLUDE_DIR})
endif ()
endif ()
if (NOT ANDROID)
# Enable testing in the top-level scope so a CTestTestfile.cmake is emitted
# at the build-tree root. This lets `ctest` be invoked from the top-level
# build directory (IDE "run all tests", CI) and discover every test in the
# subdirectories below, instead of having to descend into each
# MG_Test/MG_Benchmark subdirectory. Tests are tagged with CTest labels
# (unit / benchmark / integration), so e.g. `ctest -L unit` selects just
# the unit suite.
enable_testing()
if (MOBILEGL_BUILD_TEST)
add_subdirectory(MobileGL/MG_Test)
endif()
# After MG_Test so googletest is already available when the unit tests are
# built; the module fetches its own copy when they are not.
if (MOBILEGL_BUILD_INTEGRATION_TEST)
add_subdirectory(MobileGL/MG_IntegrationTest)
endif()
if (MOBILEGL_BUILD_BENCHMARK)
add_subdirectory(MobileGL/MG_Benchmark)
endif()
if (MOBILEGL_BUILD_TRACE_REPLAY)
add_subdirectory(tools/trace_replay)
endif()
endif() endif()
+674
View File
@@ -0,0 +1,674 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.
+165
View File
@@ -0,0 +1,165 @@
GNU LESSER GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
This version of the GNU Lesser General Public License incorporates
the terms and conditions of version 3 of the GNU General Public
License, supplemented by the additional permissions listed below.
0. Additional Definitions.
As used herein, "this License" refers to version 3 of the GNU Lesser
General Public License, and the "GNU GPL" refers to version 3 of the GNU
General Public License.
"The Library" refers to a covered work governed by this License,
other than an Application or a Combined Work as defined below.
An "Application" is any work that makes use of an interface provided
by the Library, but which is not otherwise based on the Library.
Defining a subclass of a class defined by the Library is deemed a mode
of using an interface provided by the Library.
A "Combined Work" is a work produced by combining or linking an
Application with the Library. The particular version of the Library
with which the Combined Work was made is also called the "Linked
Version".
The "Minimal Corresponding Source" for a Combined Work means the
Corresponding Source for the Combined Work, excluding any source code
for portions of the Combined Work that, considered in isolation, are
based on the Application, and not on the Linked Version.
The "Corresponding Application Code" for a Combined Work means the
object code and/or source code for the Application, including any data
and utility programs needed for reproducing the Combined Work from the
Application, but excluding the System Libraries of the Combined Work.
1. Exception to Section 3 of the GNU GPL.
You may convey a covered work under sections 3 and 4 of this License
without being bound by section 3 of the GNU GPL.
2. Conveying Modified Versions.
If you modify a copy of the Library, and, in your modifications, a
facility refers to a function or data to be supplied by an Application
that uses the facility (other than as an argument passed when the
facility is invoked), then you may convey a copy of the modified
version:
a) under this License, provided that you make a good faith effort to
ensure that, in the event an Application does not supply the
function or data, the facility still operates, and performs
whatever part of its purpose remains meaningful, or
b) under the GNU GPL, with none of the additional permissions of
this License applicable to that copy.
3. Object Code Incorporating Material from Library Header Files.
The object code form of an Application may incorporate material from
a header file that is part of the Library. You may convey such object
code under terms of your choice, provided that, if the incorporated
material is not limited to numerical parameters, data structure
layouts and accessors, or small macros, inline functions and templates
(ten or fewer lines in length), you do both of the following:
a) Give prominent notice with each copy of the object code that the
Library is used in it and that the Library and its use are
covered by this License.
b) Accompany the object code with a copy of the GNU GPL and this license
document.
4. Combined Works.
You may convey a Combined Work under terms of your choice that,
taken together, effectively do not restrict modification of the
portions of the Library contained in the Combined Work and reverse
engineering for debugging such modifications, if you also do each of
the following:
a) Give prominent notice with each copy of the Combined Work that
the Library is used in it and that the Library and its use are
covered by this License.
b) Accompany the Combined Work with a copy of the GNU GPL and this license
document.
c) For a Combined Work that displays copyright notices during
execution, include the copyright notice for the Library among
these notices, as well as a reference directing the user to the
copies of the GNU GPL and this license document.
d) Do one of the following:
0) Convey the Minimal Corresponding Source under the terms of this
License, and the Corresponding Application Code in a form
suitable for, and under terms that permit, the user to
recombine or relink the Application with a modified version of
the Linked Version to produce a modified Combined Work, in the
manner specified by section 6 of the GNU GPL for conveying
Corresponding Source.
1) Use a suitable shared library mechanism for linking with the
Library. A suitable mechanism is one that (a) uses at run time
a copy of the Library already present on the user's computer
system, and (b) will operate properly with a modified version
of the Library that is interface-compatible with the Linked
Version.
e) Provide Installation Information, but only if you would otherwise
be required to provide such information under section 6 of the
GNU GPL, and only to the extent that such information is
necessary to install and execute a modified version of the
Combined Work produced by recombining or relinking the
Application with a modified version of the Linked Version. (If
you use option 4d0, the Installation Information must accompany
the Minimal Corresponding Source and Corresponding Application
Code. If you use option 4d1, you must provide the Installation
Information in the manner specified by section 6 of the GNU GPL
for conveying Corresponding Source.)
5. Combined Libraries.
You may place library facilities that are a work based on the
Library side by side in a single library together with other library
facilities that are not Applications and are not covered by this
License, and convey such a combined library under terms of your
choice, if you do both of the following:
a) Accompany the combined library with a copy of the same work based
on the Library, uncombined with any other library facilities,
conveyed under the terms of this License.
b) Give prominent notice with the combined library that part of it
is a work based on the Library, and explaining where to find the
accompanying uncombined form of the same work.
6. Revised Versions of the GNU Lesser General Public License.
The Free Software Foundation may publish revised and/or new versions
of the GNU Lesser General Public License from time to time. Such new
versions will be similar in spirit to the present version, but may
differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the
Library as you received it specifies that a certain numbered version
of the GNU Lesser General Public License "or any later version"
applies to it, you have the option of following the terms and
conditions either of that published version or of any later version
published by the Free Software Foundation. If the Library as you
received it does not specify a version number of the GNU Lesser
General Public License, you may choose any version of the GNU Lesser
General Public License ever published by the Free Software Foundation.
If the Library as you received it specifies that a proxy can decide
whether future versions of the GNU Lesser General Public License shall
apply, that proxy's public statement of acceptance of any version is
permanent authorization for you to choose that version for the
Library.
+3 -457
View File
@@ -1,458 +1,4 @@
Copyright (c) 2025 MobileGL-Dev Copyright (c) 2025-2026 MobileGL-Dev
GNU LESSER GENERAL PUBLIC LICENSE This project is licensed under the GNU Lesser General Public License v3.0.
Version 2.1, February 1999 See COPYING and COPYING.LESSER for the full text of the LGPLv3 license.
Copyright (C) 1991, 1999 Free Software Foundation, Inc.
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
[This is the first released version of the Lesser GPL. It also counts
as the successor of the GNU Library Public License, version 2, hence
the version number 2.1.]
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
Licenses are intended to guarantee your freedom to share and change
free software--to make sure the software is free for all its users.
This license, the Lesser General Public License, applies to some
specially designated software packages--typically libraries--of the
Free Software Foundation and other authors who decide to use it. You
can use it too, but we suggest you first think carefully about whether
this license or the ordinary General Public License is the better
strategy to use in any particular case, based on the explanations below.
When we speak of free software, we are referring to freedom of use,
not price. Our General Public Licenses are designed to make sure that
you have the freedom to distribute copies of free software (and charge
for this service if you wish); that you receive source code or can get
it if you want it; that you can change the software and use pieces of
it in new free programs; and that you are informed that you can do
these things.
To protect your rights, we need to make restrictions that forbid
distributors to deny you these rights or to ask you to surrender these
rights. These restrictions translate to certain responsibilities for
you if you distribute copies of the library or if you modify it.
For example, if you distribute copies of the library, whether gratis
or for a fee, you must give the recipients all the rights that we gave
you. You must make sure that they, too, receive or can get the source
code. If you link other code with the library, you must provide
complete object files to the recipients, so that they can relink them
with the library after making changes to the library and recompiling
it. And you must show them these terms so they know their rights.
We protect your rights with a two-step method: (1) we copyright the
library, and (2) we offer you this license, which gives you legal
permission to copy, distribute and/or modify the library.
To protect each distributor, we want to make it very clear that
there is no warranty for the free library. Also, if the library is
modified by someone else and passed on, the recipients should know
that what they have is not the original version, so that the original
author's reputation will not be affected by problems that might be
introduced by others.
Finally, software patents pose a constant threat to the existence of
any free program. We wish to make sure that a company cannot
effectively restrict the users of a free program by obtaining a
restrictive license from a patent holder. Therefore, we insist that
any patent license obtained for a version of the library must be
consistent with the full freedom of use specified in this license.
Most GNU software, including some libraries, is covered by the
ordinary GNU General Public License. This license, the GNU Lesser
General Public License, applies to certain designated libraries, and
is quite different from the ordinary General Public License. We use
this license for certain libraries in order to permit linking those
libraries into non-free programs.
When a program is linked with a library, whether statically or using
a shared library, the combination of the two is legally speaking a
combined work, a derivative of the original library. The ordinary
General Public License therefore permits such linking only if the
entire combination fits its criteria of freedom. The Lesser General
Public License permits more lax criteria for linking other code with
the library.
We call this license the "Lesser" General Public License because it
does Less to protect the user's freedom than the ordinary General
Public License. It also provides other free software developers Less
of an advantage over competing non-free programs. These disadvantages
are the reason we use the ordinary General Public License for many
libraries. However, the Lesser license provides advantages in certain
special circumstances.
For example, on rare occasions, there may be a special need to
encourage the widest possible use of a certain library, so that it becomes
a de-facto standard. To achieve this, non-free programs must be
allowed to use the library. A more frequent case is that a free
library does the same job as widely used non-free libraries. In this
case, there is little to gain by limiting the free library to free
software only, so we use the Lesser General Public License.
In other cases, permission to use a particular library in non-free
programs enables a greater number of people to use a large body of
free software. For example, permission to use the GNU C Library in
non-free programs enables many more people to use the whole GNU
operating system, as well as its variant, the GNU/Linux operating
system.
Although the Lesser General Public License is Less protective of the
users' freedom, it does ensure that the user of a program that is
linked with the Library has the freedom and the wherewithal to run
that program using a modified version of the Library.
The precise terms and conditions for copying, distribution and
modification follow. Pay close attention to the difference between a
"work based on the library" and a "work that uses the library". The
former contains code derived from the library, whereas the latter must
be combined with the library in order to run.
GNU LESSER GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License Agreement applies to any software library or other
program which contains a notice placed by the copyright holder or
other authorized party saying it may be distributed under the terms of
this Lesser General Public License (also called "this License").
Each licensee is addressed as "you".
A "library" means a collection of software functions and/or data
prepared so as to be conveniently linked with application programs
(which use some of those functions and data) to form executables.
The "Library", below, refers to any such software library or work
which has been distributed under these terms. A "work based on the
Library" means either the Library or any derivative work under
copyright law: that is to say, a work containing the Library or a
portion of it, either verbatim or with modifications and/or translated
straightforwardly into another language. (Hereinafter, translation is
included without limitation in the term "modification".)
"Source code" for a work means the preferred form of the work for
making modifications to it. For a library, complete source code means
all the source code for all modules it contains, plus any associated
interface definition files, plus the scripts used to control compilation
and installation of the library.
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running a program using the Library is not restricted, and output from
such a program is covered only if its contents constitute a work based
on the Library (independent of the use of the Library in a tool for
writing it). Whether that is true depends on what the Library does
and what the program that uses the Library does.
1. You may copy and distribute verbatim copies of the Library's
complete source code as you receive it, in any medium, provided that
you conspicuously and appropriately publish on each copy an
appropriate copyright notice and disclaimer of warranty; keep intact
all the notices that refer to this License and to the absence of any
warranty; and distribute a copy of this License along with the
Library.
You may charge a fee for the physical act of transferring a copy,
and you may at your option offer warranty protection in exchange for a
fee.
2. You may modify your copy or copies of the Library or any portion
of it, thus forming a work based on the Library, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
a) The modified work must itself be a software library.
b) You must cause the files modified to carry prominent notices
stating that you changed the files and the date of any change.
c) You must cause the whole of the work to be licensed at no
charge to all third parties under the terms of this License.
d) If a facility in the modified Library refers to a function or a
table of data to be supplied by an application program that uses
the facility, other than as an argument passed when the facility
is invoked, then you must make a good faith effort to ensure that,
in the event an application does not supply such function or
table, the facility still operates, and performs whatever part of
its purpose remains meaningful.
(For example, a function in a library to compute square roots has
a purpose that is entirely well-defined independent of the
application. Therefore, Subsection 2d requires that any
application-supplied function or table used by this function must
be optional: if the application does not supply it, the square
root function must still compute square roots.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Library,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Library, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote
it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Library.
In addition, mere aggregation of another work not based on the Library
with the Library (or with a work based on the Library) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may opt to apply the terms of the ordinary GNU General Public
License instead of this License to a given copy of the Library. To do
this, you must alter all the notices that refer to this License, so
that they refer to the ordinary GNU General Public License, version 2,
instead of to this License. (If a newer version than version 2 of the
ordinary GNU General Public License has appeared, then you can specify
that version instead if you wish.) Do not make any other change in
these notices.
Once this change is made in a given copy, it is irreversible for
that copy, so the ordinary GNU General Public License applies to all
subsequent copies and derivative works made from that copy.
This option is useful when you wish to copy part of the code of
the Library into a program that is not a library.
4. You may copy and distribute the Library (or a portion or
derivative of it, under Section 2) in object code or executable form
under the terms of Sections 1 and 2 above provided that you accompany
it with the complete corresponding machine-readable source code, which
must be distributed under the terms of Sections 1 and 2 above on a
medium customarily used for software interchange.
If distribution of object code is made by offering access to copy
from a designated place, then offering equivalent access to copy the
source code from the same place satisfies the requirement to
distribute the source code, even though third parties are not
compelled to copy the source along with the object code.
5. A program that contains no derivative of any portion of the
Library, but is designed to work with the Library by being compiled or
linked with it, is called a "work that uses the Library". Such a
work, in isolation, is not a derivative work of the Library, and
therefore falls outside the scope of this License.
However, linking a "work that uses the Library" with the Library
creates an executable that is a derivative of the Library (because it
contains portions of the Library), rather than a "work that uses the
library". The executable is therefore covered by this License.
Section 6 states terms for distribution of such executables.
When a "work that uses the Library" uses material from a header file
that is part of the Library, the object code for the work may be a
derivative work of the Library even though the source code is not.
Whether this is true is especially significant if the work can be
linked without the Library, or if the work is itself a library. The
threshold for this to be true is not precisely defined by law.
If such an object file uses only numerical parameters, data
structure layouts and accessors, and small macros and small inline
functions (ten lines or less in length), then the use of the object
file is unrestricted, regardless of whether it is legally a derivative
work. (Executables containing this object code plus portions of the
Library will still fall under Section 6.)
Otherwise, if the work is a derivative of the Library, you may
distribute the object code for the work under the terms of Section 6.
Any executables containing that work also fall under Section 6,
whether or not they are linked directly with the Library itself.
6. As an exception to the Sections above, you may also combine or
link a "work that uses the Library" with the Library to produce a
work containing portions of the Library, and distribute that work
under terms of your choice, provided that the terms permit
modification of the work for the customer's own use and reverse
engineering for debugging such modifications.
You must give prominent notice with each copy of the work that the
Library is used in it and that the Library and its use are covered by
this License. You must supply a copy of this License. If the work
during execution displays copyright notices, you must include the
copyright notice for the Library among them, as well as a reference
directing the user to the copy of this License. Also, you must do one
of these things:
a) Accompany the work with the complete corresponding
machine-readable source code for the Library including whatever
changes were used in the work (which must be distributed under
Sections 1 and 2 above); and, if the work is an executable linked
with the Library, with the complete machine-readable "work that
uses the Library", as object code and/or source code, so that the
user can modify the Library and then relink to produce a modified
executable containing the modified Library. (It is understood
that the user who changes the contents of definitions files in the
Library will not necessarily be able to recompile the application
to use the modified definitions.)
b) Use a suitable shared library mechanism for linking with the
Library. A suitable mechanism is one that (1) uses at run time a
copy of the library already present on the user's computer system,
rather than copying library functions into the executable, and (2)
will operate properly with a modified version of the library, if
the user installs one, as long as the modified version is
interface-compatible with the version that the work was made with.
c) Accompany the work with a written offer, valid for at
least three years, to give the same user the materials
specified in Subsection 6a, above, for a charge no more
than the cost of performing this distribution.
d) If distribution of the work is made by offering access to copy
from a designated place, offer equivalent access to copy the above
specified materials from the same place.
e) Verify that the user has already received a copy of these
materials or that you have already sent this user a copy.
For an executable, the required form of the "work that uses the
Library" must include any data and utility programs needed for
reproducing the executable from it. However, as a special exception,
the materials to be distributed need not include anything that is
normally distributed (in either source or binary form) with the major
components (compiler, kernel, and so on) of the operating system on
which the executable runs, unless that component itself accompanies
the executable.
It may happen that this requirement contradicts the license
restrictions of other proprietary libraries that do not normally
accompany the operating system. Such a contradiction means you cannot
use both them and the Library together in an executable that you
distribute.
7. You may place library facilities that are a work based on the
Library side-by-side in a single library together with other library
facilities not covered by this License, and distribute such a combined
library, provided that the separate distribution of the work based on
the Library and of the other library facilities is otherwise
permitted, and provided that you do these two things:
a) Accompany the combined library with a copy of the same work
based on the Library, uncombined with any other library
facilities. This must be distributed under the terms of the
Sections above.
b) Give prominent notice with the combined library of the fact
that part of it is a work based on the Library, and explaining
where to find the accompanying uncombined form of the same work.
8. You may not copy, modify, sublicense, link with, or distribute
the Library except as expressly provided under this License. Any
attempt otherwise to copy, modify, sublicense, link with, or
distribute the Library is void, and will automatically terminate your
rights under this License. However, parties who have received copies,
or rights, from you under this License will not have their licenses
terminated so long as such parties remain in full compliance.
9. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Library or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Library (or any work based on the
Library), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Library or works based on it.
10. Each time you redistribute the Library (or any work based on the
Library), the recipient automatically receives a license from the
original licensor to copy, distribute, link with or modify the Library
subject to these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties with
this License.
11. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Library at all. For example, if a patent
license would not permit royalty-free redistribution of the Library by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Library.
If any portion of this section is held invalid or unenforceable under any
particular circumstance, the balance of the section is intended to apply,
and the section as a whole is intended to apply in other circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
12. If the distribution and/or use of the Library is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Library under this License may add
an explicit geographical distribution limitation excluding those countries,
so that distribution is permitted only in or among countries not thus
excluded. In such case, this License incorporates the limitation as if
written in the body of this License.
13. The Free Software Foundation may publish revised and/or new
versions of the Lesser General Public License from time to time.
Such new versions will be similar in spirit to the present version,
but may differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the Library
specifies a version number of this License which applies to it and
"any later version", you have the option of following the terms and
conditions either of that version or of any later version published by
the Free Software Foundation. If the Library does not specify a
license version number, you may choose any version ever published by
the Free Software Foundation.
14. If you wish to incorporate parts of the Library into other free
programs whose distribution conditions are incompatible with these,
write to the author to ask for permission. For software which is
copyrighted by the Free Software Foundation, write to the Free
Software Foundation; we sometimes make exceptions for this. Our
decision will be guided by the two goals of preserving the free status
of all derivatives of our free software and of promoting the sharing
and reuse of software generally.
NO WARRANTY
15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO
WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW.
EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR
OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY
KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE
LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME
THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN
WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY
AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU
FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR
CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE
LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A
FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
DAMAGES.
-192
View File
@@ -1,192 +0,0 @@
//
// Created by BZLZHH on 2025/3/15.
//
#ifndef MOBILEGL_CONSTANTS_H
#define MOBILEGL_CONSTANTS_H
#include <array>
#include <unordered_map>
#include <unordered_set>
#include <GL/gl.h>
#include <ankerl/unordered_dense.h>
#ifdef __ANDROID__
#define __ANDROID_API__ 26
#endif
#ifdef _WIN32
#define MG_EXPORT extern "C" __declspec(dllexport)
#else
#define MG_EXPORT extern "C" __attribute__((visibility("default")))
#endif
namespace ankerl {
template <typename K, typename V>
using unordered_map = ankerl::unordered_dense::map<K, V>;
template <typename T>
using unordered_set = ankerl::unordered_dense::set<T>;
}
namespace MG_Constants {
namespace Common {
inline constexpr int LOG_LEVEL_DEBUG = 0x0010;
inline constexpr int LOG_LEVEL_WARN = 0x0011;
inline constexpr int LOG_LEVEL_ERROR = 0x0012;
inline constexpr int LOG_LEVEL_INFO = 0x0013;
inline constexpr int LOG_LEVEL_FATAL = 0x0014;
inline constexpr int LOG_TARGET_NONE = 0x00;
inline constexpr int LOG_TARGET_CONSOLE = 0x01;
inline constexpr int LOG_TARGET_FILE = 0x02;
inline constexpr int LOG_TARGET_ANDROID = 0x04; // Android logcat
inline constexpr int LOG_TARGET_ALL = LOG_TARGET_CONSOLE | LOG_TARGET_FILE | LOG_TARGET_ANDROID;
}
namespace Blend {
static const ankerl::unordered_set<GLenum> VALID_FACTORS = {
GL_ZERO, GL_ONE, GL_SRC_COLOR, GL_ONE_MINUS_SRC_COLOR,
GL_DST_COLOR, GL_ONE_MINUS_DST_COLOR, GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA,
GL_DST_ALPHA, GL_ONE_MINUS_DST_ALPHA, GL_CONSTANT_COLOR, GL_ONE_MINUS_CONSTANT_COLOR,
GL_CONSTANT_ALPHA, GL_ONE_MINUS_CONSTANT_ALPHA, GL_SRC_ALPHA_SATURATE
}; // OpenGL 3
}
namespace Depth {
static const ankerl::unordered_set<GLenum> VALID_FUNCS = {
GL_NEVER, GL_LESS, GL_EQUAL, GL_LEQUAL, GL_GREATER, GL_NOTEQUAL, GL_GEQUAL, GL_ALWAYS
}; // OpenGL 3
}
namespace CommonState {
static const ankerl::unordered_set<GLenum> VALID_CAPS = {
GL_BLEND, GL_DEPTH_TEST, GL_STENCIL_TEST, GL_SCISSOR_TEST, GL_CULL_FACE,
GL_POLYGON_OFFSET_FILL, GL_SAMPLE_ALPHA_TO_COVERAGE, GL_SAMPLE_COVERAGE
}; // OpenGL 3
}
namespace Framebuffer {
static const ankerl::unordered_set<GLenum> VALID_ATTACHMENTS = {
GL_COLOR_ATTACHMENT0, GL_DEPTH_ATTACHMENT,
GL_STENCIL_ATTACHMENT, GL_DEPTH_STENCIL_ATTACHMENT
}; // OpenGL 3
static const ankerl::unordered_set<GLenum> VALID_TARGETS = {
GL_FRAMEBUFFER, GL_DRAW_FRAMEBUFFER, GL_READ_FRAMEBUFFER
}; // OpenGL 3
static const ankerl::unordered_set<GLenum> VALID_ACCESS = {
GL_READ_ONLY, GL_WRITE_ONLY, GL_READ_WRITE
}; // OpenGL 3
}
namespace Buffer {
static const ankerl::unordered_set<GLenum> VALID_PARAM_NAMES = {
GL_BUFFER_ACCESS, GL_BUFFER_MAPPED, GL_BUFFER_SIZE, GL_BUFFER_USAGE
}; // OpenGL 3
static const ankerl::unordered_set<GLenum> VALID_TARGETS = {
GL_ARRAY_BUFFER, GL_COPY_READ_BUFFER, GL_COPY_WRITE_BUFFER, GL_ELEMENT_ARRAY_BUFFER,
GL_PIXEL_PACK_BUFFER, GL_PIXEL_UNPACK_BUFFER, GL_TEXTURE_BUFFER,
GL_TRANSFORM_FEEDBACK_BUFFER, GL_UNIFORM_BUFFER
}; // OpenGL 3
static const ankerl::unordered_set<GLenum> VALID_ACCESS = {
GL_READ_ONLY, GL_WRITE_ONLY, GL_READ_WRITE
}; // OpenGL 3
}
namespace PixelStore {
static const ankerl::unordered_map<GLenum, GLint> DEFAULT_VALUES_MAP = {
{GL_PACK_SWAP_BYTES, GL_FALSE},
{GL_PACK_LSB_FIRST, GL_FALSE},
{GL_PACK_ROW_LENGTH, 0},
{GL_PACK_IMAGE_HEIGHT, 0},
{GL_PACK_SKIP_ROWS, 0},
{GL_PACK_SKIP_PIXELS, 0},
{GL_PACK_SKIP_IMAGES, 0},
{GL_PACK_ALIGNMENT, 4},
{GL_UNPACK_SWAP_BYTES, GL_FALSE},
{GL_UNPACK_LSB_FIRST, GL_FALSE},
{GL_UNPACK_ROW_LENGTH, 0},
{GL_UNPACK_IMAGE_HEIGHT, 0},
{GL_UNPACK_SKIP_ROWS, 0},
{GL_UNPACK_SKIP_PIXELS,0},
{GL_UNPACK_SKIP_IMAGES,0},
{GL_UNPACK_ALIGNMENT, 4}
}; // OpenGL 3
static const ankerl::unordered_set<GLenum> VALID_PARAM_NAMES = {
GL_PACK_SWAP_BYTES, GL_PACK_LSB_FIRST, GL_PACK_ROW_LENGTH, GL_PACK_IMAGE_HEIGHT,
GL_PACK_SKIP_ROWS, GL_PACK_SKIP_PIXELS, GL_PACK_SKIP_IMAGES, GL_PACK_ALIGNMENT,
GL_UNPACK_SWAP_BYTES, GL_UNPACK_LSB_FIRST, GL_UNPACK_ROW_LENGTH,
GL_UNPACK_IMAGE_HEIGHT,
GL_UNPACK_SKIP_ROWS, GL_UNPACK_SKIP_PIXELS, GL_UNPACK_SKIP_IMAGES,
GL_UNPACK_ALIGNMENT
}; // OpenGL 3
}
namespace Texture {
inline const GLuint MAX_TEXTURE_UNITS = 80;
const GLsizei MAX_TEXTURE_SIZE = 32768;
const GLsizei MAX_ARRAY_LAYERS = 256;
inline const ankerl::unordered_set<GLenum> VALID_TARGETS = {
GL_TEXTURE_2D, GL_PROXY_TEXTURE_2D, GL_TEXTURE_1D_ARRAY, GL_PROXY_TEXTURE_1D_ARRAY,
GL_TEXTURE_RECTANGLE, GL_PROXY_TEXTURE_RECTANGLE, GL_TEXTURE_CUBE_MAP_POSITIVE_X,
GL_TEXTURE_CUBE_MAP_NEGATIVE_X, GL_TEXTURE_CUBE_MAP_POSITIVE_Y, GL_TEXTURE_CUBE_MAP_NEGATIVE_Y,
GL_TEXTURE_CUBE_MAP_POSITIVE_Z, GL_TEXTURE_CUBE_MAP_NEGATIVE_Z, GL_PROXY_TEXTURE_CUBE_MAP
}; // OpenGL 3
inline const ankerl::unordered_set<GLenum> VALID_FORMATS = {
GL_RED, GL_RG, GL_RGB, GL_BGR, GL_RGBA, GL_BGRA, GL_DEPTH_COMPONENT, GL_DEPTH_STENCIL
}; // OpenGL 3
inline const ankerl::unordered_set<GLenum> VALID_INTERNAL_FORMATS = {
GL_RED, GL_RG, GL_RGB, GL_BGR, GL_RGBA, GL_BGRA, GL_DEPTH_COMPONENT, GL_DEPTH_STENCIL,
GL_RGBA32F, GL_RGBA32I, GL_RGBA32UI, GL_RGBA16, GL_RGBA16F, GL_RGBA16I,
GL_RGBA16UI, GL_RGBA8, GL_RGBA8UI, GL_SRGB8_ALPHA8, GL_RGB10_A2, GL_RGB10_A2UI,
GL_R11F_G11F_B10F, GL_RG32F, GL_RG32I, GL_RG32UI, GL_RG16, GL_RG16F, GL_RGB16I,
GL_RGB16UI, GL_RG8, GL_RG8I, GL_RG8UI, GL_R32F, GL_R32I, GL_R32UI, GL_R16F,
GL_R16I, GL_R16UI, GL_R8, GL_R8I, GL_R8UI, GL_RGBA16_SNORM, GL_RGBA8_SNORM,
GL_RGB32F, GL_RGB32I, GL_RGB32UI, GL_RGB16_SNORM, GL_RGB16F, GL_RGB16I, GL_RGB16UI,
GL_RGB16, GL_RGB8_SNORM, GL_RGB8, GL_RGB8I, GL_RGB8UI, GL_SRGB8, GL_RGB9_E5,
GL_RG16_SNORM, GL_RG8_SNORM, GL_COMPRESSED_RG_RGTC2, GL_COMPRESSED_SIGNED_RG_RGTC2,
GL_R16_SNORM, GL_R8_SNORM, GL_COMPRESSED_RED_RGTC1, GL_COMPRESSED_SIGNED_RED_RGTC1,
GL_DEPTH_COMPONENT32F, GL_DEPTH_COMPONENT32, GL_DEPTH_COMPONENT24, GL_DEPTH_COMPONENT16,
GL_DEPTH32F_STENCIL8, GL_DEPTH24_STENCIL8
}; // OpenGL 3
inline const ankerl::unordered_set<GLenum> VALID_TYPES = {
GL_UNSIGNED_BYTE, GL_BYTE, GL_UNSIGNED_SHORT, GL_SHORT, GL_UNSIGNED_INT, GL_INT,
GL_FLOAT, GL_UNSIGNED_BYTE_3_3_2, GL_UNSIGNED_BYTE_2_3_3_REV, GL_UNSIGNED_SHORT_5_6_5,
GL_UNSIGNED_SHORT_5_6_5_REV, GL_UNSIGNED_SHORT_4_4_4_4, GL_UNSIGNED_SHORT_4_4_4_4_REV,
GL_UNSIGNED_SHORT_5_5_5_1, GL_UNSIGNED_SHORT_1_5_5_5_REV, GL_UNSIGNED_INT_8_8_8_8,
GL_UNSIGNED_INT_8_8_8_8_REV, GL_UNSIGNED_INT_10_10_10_2, GL_UNSIGNED_INT_2_10_10_10_REV
}; // OpenGL 3
inline const ankerl::unordered_set<GLenum> VALID_TEXTURE_PARAM_NAMES = {
GL_TEXTURE_BASE_LEVEL, GL_TEXTURE_COMPARE_FUNC, GL_TEXTURE_COMPARE_MODE, GL_TEXTURE_MIN_FILTER,
GL_TEXTURE_MAG_FILTER, GL_TEXTURE_MAX_LEVEL, GL_TEXTURE_SWIZZLE_R, GL_TEXTURE_SWIZZLE_G,
GL_TEXTURE_SWIZZLE_B, GL_TEXTURE_SWIZZLE_A, GL_TEXTURE_SWIZZLE_RGBA, GL_TEXTURE_WRAP_S,
GL_TEXTURE_WRAP_T, GL_TEXTURE_WRAP_R, GL_TEXTURE_LOD_BIAS, GL_TEXTURE_MIN_LOD, GL_TEXTURE_MAX_LOD, GL_TEXTURE_BORDER_COLOR
}; // OpenGL 3
inline const ankerl::unordered_set<GLenum> VALID_QUERY_LEVEL_PROPERTY_PARAM_NAMES = {
GL_TEXTURE_WIDTH, GL_TEXTURE_HEIGHT, GL_TEXTURE_DEPTH, GL_TEXTURE_INTERNAL_FORMAT,
GL_TEXTURE_RED_SIZE, GL_TEXTURE_GREEN_SIZE, GL_TEXTURE_BLUE_SIZE, GL_TEXTURE_ALPHA_SIZE,
GL_TEXTURE_DEPTH_SIZE, GL_TEXTURE_COMPRESSED, GL_TEXTURE_COMPRESSED_IMAGE_SIZE
}; // OpenGL 3
}
namespace Backend {
#define BACKEND_VULKAN 0x0015
#define BACKEND_METAL 0x0016
#define BACKEND_GLES 0x0017
}
inline const char* RenderName = "MobileGL";
}
#endif //MOBILEGL_CONSTANTS_H
-41
View File
@@ -1,41 +0,0 @@
//
// Created by BZLZHH on 2025/3/15.
//
#ifndef MOBILEGL_GLOBAL_H
#define MOBILEGL_GLOBAL_H
#include "Includes.h"
namespace MG_Global {
namespace MG {
inline const int VersionMajor = 1;
inline const int VersionMinor = 0;
inline const int VersionRevision = 0;
inline const int VersionPatch = 0;
inline const std::string VersionSuffix = "-Dev";
}
namespace Backend {
// BACKEND_TYPE is defined in Includes.h
}
namespace GL {
inline const int GLVersionMajor = 3;
inline const int GLVersionMinor = 2;
inline const int GLVersionRevision = 0;
}
namespace Common {
inline constexpr int LogLevel = MG_Constants::Common::LOG_LEVEL_INFO;
inline constexpr int LogTarget = MG_Constants::Common::LOG_TARGET_ALL;
#ifdef __ANDROID__
inline const char* LOG_FILE_PATH = "/sdcard/MG/latest.log";
#else
inline const char* LOG_FILE_PATH = nullptr;
#endif
}
}
#endif //MOBILEGL_GLOBAL_H
-140
View File
@@ -1,140 +0,0 @@
//
// Created by BZLZHH on 2025/3/15.
//
#include "Constants.h"
#define BACKEND_TYPE BACKEND_GLES
#include "Global.h"
#ifndef MOBILEGL_GLES_LOADER_H
#include "MG_GL/BackendLoader/GLES/Loader.h"
#endif
#ifndef MOBILEGL_GL_FRAMEBUFFER_H
#include "MG_GL/Implementations/GL/Framebuffer/GL_Framebuffer.h"
#endif
#ifndef MOBILEGL_GL_GETTER_H
#include "MG_GL/Implementations/GL/Getter/GL_Getter.h"
#endif
#ifndef MOBILEGL_BACKENDINFO_H
#include "MG_GL/Implementations/GL/Getter/BackendInfo.h"
#endif
#ifndef MOBILEGL_GL_BUFFER_H
#include "MG_GL/Implementations/GL/Buffer/GL_Buffer.h"
#endif
#ifndef MOBILEGL_GL_DRAWING_H
#include "MG_GL/Implementations/GL/Drawing/GL_Drawing.h"
#endif
#ifndef MOBILEGL_GL_PROGRAM_H
#include "MG_GL/Implementations/GL/Program/GL_Program.h"
#endif
#ifndef MOBILEGL_GL_TEXTURE_H
#include "MG_GL/Implementations/GL/Texture/GL_Texture.h"
#endif
#ifndef MOBILEGL_GL_VERTEXARRAY_H
#include "MG_GL/Implementations/GL/VertexArray/GL_VertexArray.h"
#endif
#ifndef MOBILEGL_GLSTATE_H
#include "MG_GL/State/Core/GLState.h"
#endif
#ifndef MOBILEGL_COMMONSTATE_H
#include "MG_GL/State/Common/CommonState.h"
#endif
#ifndef MOBILEGL_TEXTURESTATE_H
#include "MG_GL/State/Texture/TextureState.h"
#endif
#ifndef MOBILEGL_VERTEXARRAYSTATE_H
#include "MG_GL/State/VertexArray/VertexArrayState.h"
#endif
#ifndef MOBILEGL_BUFFERSTATE_H
#include "MG_GL/State/Buffer/BufferState.h"
#endif
#ifndef MOBILEGL_SHADEROBJECT_H
#include "MG_GL/State/Program/ShaderObject.h"
#endif
#ifndef MOBILEGL_PROGRAMSTATE_H
#include "MG_GL/State/Program/ProgramState.h"
#endif
#ifndef MOBILEGL_FRAMEBUFFERSTATE_H
#include "MG_GL/State/Framebuffer/FramebufferState.h"
#endif
#ifndef MOBILEGL_LOOKUP_H
#include "MG_GL/Implementations/GLX/LookUp/LookUp.h"
#endif
#ifndef MOBILEGL_DEBUG_H
#include "MG_UTIL/Debug/Debug.h"
#endif
#ifndef MOBILEGL_GLSLTOOL_H
#include "MG_UTIL/Program/GLSLTool.h"
#endif
#ifndef MOBILEGL_PROGRAM_DEBUGTOOL_H
#include "MG_UTIL/Program/DebugTool.h"
#endif
#ifndef MOBILEGL_GL_COMMON_H
#include "MG_GL/Implementations/GL/Common/GL_Common.h"
#endif
#ifndef MOBILEGL_EGL_VK_EMU_H
#include "MG_GL/Implementations/EGL/VK/EGL_EMU.h"
#endif
#ifndef MOBILEGL_EGL_GLES_EGL_WRAP_H
#include "MG_GL/Implementations/EGL/GLES/EGL_WRAP.h"
#endif
#ifndef MOBILEGL_TESTDRAWING_H
#include "MG_RHI/GLES/Test/TestDrawing.h"
#endif
#include <cstring>
#include <iostream>
#include <cstdio>
#include <ctime>
#include <chrono>
#include <thread>
#include <string>
#include <map>
#include <vector>
#include <stdexcept>
#include <atomic>
#include <regex>
#include <strstream>
#include <algorithm>
#include <array>
#include <random>
#include <optional>
#include <unordered_map>
#include <queue>
#include <format>
#include <glslang/Public/ShaderLang.h>
#include <glslang/Include/Types.h>
#include <glslang/Public/ShaderLang.h>
#include <spirv_cross/spirv_cross_c.h>
#include <glslang/SPIRV/GlslangToSpv.h>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/glm.hpp>
#include <ankerl/unordered_dense.h>
#include <GLES3/gl32.h>
#include "MG_Include/UncertainBool.hpp"
#ifdef _WIN32
#include <Windows.h>
#endif
#ifndef _WIN32
#include <dlfcn.h>
#include <unistd.h>
#include <vulkan/vulkan.h>
#endif
#ifdef __ANDROID__
#include <android/log.h>
#include <pthread.h>
#include <vulkan/vulkan_android.h>
#include <android/native_window.h>
#elif _WIN32
#include <windows.h>
#include <processthreadsapi.h>
#else
#include <pthread.h>
#endif
#include <EGL/egl.h>
#include <GL/gl.h>
#include <GL/glext.h>
-46
View File
@@ -1,46 +0,0 @@
//
// Created by BZLZHH on 2025/3/15.
//
#include "Includes.h"
void MG_Initialize() {
MG_Util::Debug::LogInit();
MG_Util::Debug::LogI("MobileGL Initializing...");
MG_State::Init();
MG_GL::BackendLoader::Init();
}
void MG_Destroy() {
MG_Util::Debug::LogI("MobileGL Exiting...");
MG_State::Destroy();
}
#if defined(__linux__) || defined(__APPLE__)
__attribute__((constructor)) static void AutoInit() {
MG_Initialize();
}
__attribute__((destructor)) static void AutoDestroy() {
MG_Destroy();
}
#endif
#ifdef _WIN32
BOOL WINAPI DllMain(HMODULE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved)
{
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
MG_Initialize();
break;
case DLL_PROCESS_DETACH:
MG_Destroy();
break;
}
return TRUE;
}
#endif
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
@@ -1,179 +0,0 @@
//
// Created by BZLZHH on 2025/4/26.
//
#include "EGL_WRAP.h"
#if BACKEND_TYPE == BACKEND_GLES
MG_EXPORT EGLint eglGetError(void) {
LOAD_EGL(eglGetError)
return egl_eglGetError();
}
MG_EXPORT EGLDisplay eglGetDisplay(EGLNativeDisplayType display_id) {
LOAD_EGL(eglGetDisplay)
return egl_eglGetDisplay(display_id);
}
MG_EXPORT EGLBoolean eglInitialize(EGLDisplay dpy, EGLint *major, EGLint *minor) {
LOAD_EGL(eglInitialize)
return egl_eglInitialize(dpy, major, minor);
}
MG_EXPORT EGLBoolean eglTerminate(EGLDisplay dpy) {
LOAD_EGL(eglTerminate)
return egl_eglTerminate(dpy);
}
MG_EXPORT const char *eglQueryString(EGLDisplay dpy, EGLint name) {
LOAD_EGL(eglQueryString)
return egl_eglQueryString(dpy, name);
}
MG_EXPORT EGLBoolean eglGetConfigs(EGLDisplay dpy, EGLConfig *configs, EGLint config_size, EGLint *num_config) {
LOAD_EGL(eglGetConfigs)
return egl_eglGetConfigs(dpy, configs, config_size, num_config);
}
MG_EXPORT EGLBoolean eglChooseConfig(EGLDisplay dpy, const EGLint *attrib_list, EGLConfig *configs, EGLint config_size, EGLint *num_config) {
LOAD_EGL(eglChooseConfig)
return egl_eglChooseConfig(dpy, attrib_list, configs, config_size, num_config);
}
MG_EXPORT EGLBoolean eglGetConfigAttrib(EGLDisplay dpy, EGLConfig config, EGLint attribute, EGLint *value) {
LOAD_EGL(eglGetConfigAttrib)
return egl_eglGetConfigAttrib(dpy, config, attribute, value);
}
MG_EXPORT EGLSurface eglCreateWindowSurface(EGLDisplay dpy, EGLConfig config, EGLNativeWindowType win, const EGLint *attrib_list) {
LOAD_EGL(eglCreateWindowSurface)
return egl_eglCreateWindowSurface(dpy, config, win, attrib_list);
}
MG_EXPORT EGLSurface eglCreatePbufferSurface(EGLDisplay dpy, EGLConfig config, const EGLint *attrib_list) {
LOAD_EGL(eglCreatePbufferSurface)
return egl_eglCreatePbufferSurface(dpy, config, attrib_list);
}
MG_EXPORT EGLSurface eglCreatePixmapSurface(EGLDisplay dpy, EGLConfig config, EGLNativePixmapType pixmap, const EGLint *attrib_list) {
LOAD_EGL(eglCreatePixmapSurface)
return egl_eglCreatePixmapSurface(dpy, config, pixmap, attrib_list);
}
MG_EXPORT EGLBoolean eglDestroySurface(EGLDisplay dpy, EGLSurface surface) {
LOAD_EGL(eglDestroySurface)
return egl_eglDestroySurface(dpy, surface);
}
MG_EXPORT EGLBoolean eglQuerySurface(EGLDisplay dpy, EGLSurface surface, EGLint attribute, EGLint *value) {
LOAD_EGL(eglQuerySurface)
return egl_eglQuerySurface(dpy, surface, attribute, value);
}
MG_EXPORT EGLBoolean eglBindAPI(EGLenum api) {
LOAD_EGL(eglBindAPI)
return egl_eglBindAPI(api);
}
MG_EXPORT EGLenum eglQueryAPI(void) {
LOAD_EGL(eglQueryAPI)
return egl_eglQueryAPI();
}
MG_EXPORT EGLBoolean eglWaitClient(void) {
LOAD_EGL(eglWaitClient)
return egl_eglWaitClient();
}
MG_EXPORT EGLBoolean eglReleaseThread(void) {
LOAD_EGL(eglReleaseThread)
return egl_eglReleaseThread();
}
MG_EXPORT EGLSurface eglCreatePbufferFromClientBuffer(EGLDisplay dpy, EGLenum buftype, EGLClientBuffer buffer, EGLConfig config, const EGLint *attrib_list) {
LOAD_EGL(eglCreatePbufferFromClientBuffer)
return egl_eglCreatePbufferFromClientBuffer(dpy, buftype, buffer, config, attrib_list);
}
MG_EXPORT EGLBoolean eglSurfaceAttrib(EGLDisplay dpy, EGLSurface surface, EGLint attribute, EGLint value) {
LOAD_EGL(eglSurfaceAttrib)
return egl_eglSurfaceAttrib(dpy, surface, attribute, value);
}
MG_EXPORT EGLBoolean eglBindTexImage(EGLDisplay dpy, EGLSurface surface, EGLint buffer) {
LOAD_EGL(eglBindTexImage)
return egl_eglBindTexImage(dpy, surface, buffer);
}
MG_EXPORT EGLBoolean eglReleaseTexImage(EGLDisplay dpy, EGLSurface surface, EGLint buffer) {
LOAD_EGL(eglReleaseTexImage)
return egl_eglReleaseTexImage(dpy, surface, buffer);
}
MG_EXPORT EGLBoolean eglSwapInterval(EGLDisplay dpy, EGLint interval) {
LOAD_EGL(eglSwapInterval)
return egl_eglSwapInterval(dpy, interval);
}
MG_EXPORT EGLContext eglCreateContext(EGLDisplay dpy, EGLConfig config, EGLContext share_context, const EGLint *attrib_list) {
LOAD_EGL(eglCreateContext)
return egl_eglCreateContext(dpy, config, share_context, attrib_list);
}
MG_EXPORT EGLBoolean eglDestroyContext(EGLDisplay dpy, EGLContext ctx) {
LOAD_EGL(eglDestroyContext)
return egl_eglDestroyContext(dpy, ctx);
}
MG_EXPORT EGLBoolean eglMakeCurrent(EGLDisplay dpy, EGLSurface draw, EGLSurface read, EGLContext ctx) {
LOAD_EGL(eglMakeCurrent)
return egl_eglMakeCurrent(dpy, draw, read, ctx);
}
MG_EXPORT EGLContext eglGetCurrentContext(void) {
LOAD_EGL(eglGetCurrentContext)
return egl_eglGetCurrentContext();
}
MG_EXPORT EGLSurface eglGetCurrentSurface(EGLint readdraw) {
LOAD_EGL(eglGetCurrentSurface)
return egl_eglGetCurrentSurface(readdraw);
}
MG_EXPORT EGLDisplay eglGetCurrentDisplay(void) {
LOAD_EGL(eglGetCurrentDisplay)
return egl_eglGetCurrentDisplay();
}
MG_EXPORT EGLBoolean eglQueryContext(EGLDisplay dpy, EGLContext ctx, EGLint attribute, EGLint *value) {
LOAD_EGL(eglQueryContext)
return egl_eglQueryContext(dpy, ctx, attribute, value);
}
MG_EXPORT EGLBoolean eglWaitGL(void) {
LOAD_EGL(eglWaitGL)
return egl_eglWaitGL();
}
MG_EXPORT EGLBoolean eglWaitNative(EGLint engine) {
LOAD_EGL(eglWaitNative)
return egl_eglWaitNative(engine);
}
MG_EXPORT EGLBoolean eglSwapBuffers(EGLDisplay dpy, EGLSurface surface) {
LOAD_EGL(eglSwapBuffers)
return egl_eglSwapBuffers(dpy, surface);
}
MG_EXPORT EGLBoolean eglCopyBuffers(EGLDisplay dpy, EGLSurface surface, EGLNativePixmapType target) {
LOAD_EGL(eglCopyBuffers)
return egl_eglCopyBuffers(dpy, surface, target);
}
MG_EXPORT EGLDisplay eglGetPlatformDisplay(EGLenum platform, void *native_display, const EGLAttrib *attrib_list) {
LOAD_EGL(eglGetPlatformDisplay)
return egl_eglGetPlatformDisplay(platform, native_display, (const EGLint *)attrib_list);
}
#endif
@@ -1,14 +0,0 @@
//
// Created by BZLZHH on 2025/4/26.
//
#ifndef MOBILEGL_EGL_GLES_EGL_WRAP_H
#define MOBILEGL_EGL_GLES_EGL_WRAP_H
#include "../../../../Includes.h"
#if BACKEND_TYPE == BACKEND_GLES
#endif
#endif //MOBILEGL_EGL_GLES_EGL_WRAP_H
-551
View File
@@ -1,551 +0,0 @@
//
// Created by BZLZHH on 2025/3/30.
//
#include "EGL_EMU.h"
#if BACKEND_TYPE == BACKEND_VULKAN
std::atomic<uintptr_t> g_nextContextId{1};
std::atomic<uintptr_t> g_nextSurfaceId{1};
EGLenum g_currentAPI = EGL_OPENGL_ES_API;
std::mutex g_globalMutex;
ankerl::unordered_map<EGLDisplay, VulkanDisplay> g_displays;
ankerl::unordered_map<EGLSurface, VulkanSurface> g_surfaces;
ankerl::unordered_map<EGLContext, VulkanContext> g_contexts;
EGLint g_lastError = EGL_SUCCESS;
thread_local EGLContext tls_currentContext = EGL_NO_CONTEXT;
thread_local EGLSurface tls_drawSurface = EGL_NO_SURFACE;
thread_local EGLSurface tls_readSurface = EGL_NO_SURFACE;
static VkResult CreateRenderPass(VulkanDisplay& display, VulkanContext& ctx) {
VkAttachmentDescription colorAttachment{};
colorAttachment.format = VK_FORMAT_B8G8R8A8_SRGB;
colorAttachment.samples = VK_SAMPLE_COUNT_1_BIT;
colorAttachment.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR;
colorAttachment.storeOp = VK_ATTACHMENT_STORE_OP_STORE;
colorAttachment.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
colorAttachment.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
colorAttachment.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
colorAttachment.finalLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR;
VkAttachmentReference colorRef{0, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL};
VkSubpassDescription subpass{};
subpass.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS;
subpass.colorAttachmentCount = 1;
subpass.pColorAttachments = &colorRef;
VkRenderPassCreateInfo rpInfo{};
rpInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO;
rpInfo.subpassCount = 1;
rpInfo.pSubpasses = &subpass;
rpInfo.attachmentCount = 1;
rpInfo.pAttachments = &colorAttachment;
return vkCreateRenderPass(display.device, &rpInfo, nullptr, &ctx.renderPass);
}
EGLDisplay eglGetDisplay(NativeDisplayType display) {
std::lock_guard<std::mutex> lock(g_globalMutex);
static uintptr_t nextDisplayId = 1;
EGLDisplay newDisplay = (EGLDisplay)nextDisplayId++;
g_displays[newDisplay].initialized = false;
return newDisplay;
}
EGLBoolean eglInitialize(EGLDisplay dpy, EGLint* major, EGLint* minor) {
VulkanDisplay& vkDpy = g_displays[dpy];
if (vkDpy.initialized) return EGL_TRUE;
VkInstanceCreateInfo instInfo{};
instInfo.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;
const char* extensions[] = {
VK_KHR_SURFACE_EXTENSION_NAME,
VK_KHR_ANDROID_SURFACE_EXTENSION_NAME
};
instInfo.enabledExtensionCount = 2;
instInfo.ppEnabledExtensionNames = extensions;
if (vkCreateInstance(&instInfo, nullptr, &vkDpy.instance) != VK_SUCCESS) {
g_lastError = EGL_NOT_INITIALIZED;
return EGL_FALSE;
}
uint32_t devCount = 0;
vkEnumeratePhysicalDevices(vkDpy.instance, &devCount, nullptr);
std::vector<VkPhysicalDevice> devices(devCount);
vkEnumeratePhysicalDevices(vkDpy.instance, &devCount, devices.data());
vkDpy.physicalDevice = devices[0];
uint32_t queueFamilyCount = 0;
vkGetPhysicalDeviceQueueFamilyProperties(vkDpy.physicalDevice, &queueFamilyCount, nullptr);
std::vector<VkQueueFamilyProperties> queueFamilies(queueFamilyCount);
vkGetPhysicalDeviceQueueFamilyProperties(vkDpy.physicalDevice, &queueFamilyCount, queueFamilies.data());
// 寻找支持图形和呈现的队列家族
bool foundQueue = false;
for (uint32_t i = 0; i < queueFamilyCount; ++i) {
VkBool32 presentSupport = VK_FALSE;
vkGetPhysicalDeviceSurfaceSupportKHR(vkDpy.physicalDevice, i, VK_NULL_HANDLE, &presentSupport);
if ((queueFamilies[i].queueFlags & VK_QUEUE_GRAPHICS_BIT) && presentSupport) {
vkDpy.graphicsQueueFamily = i;
foundQueue = true;
break;
}
}
if (!foundQueue) {
g_lastError = EGL_NOT_INITIALIZED;
return EGL_FALSE;
}
// 创建逻辑设备时请求队列
float queuePriority = 1.0f;
VkDeviceQueueCreateInfo queueInfo{};
queueInfo.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO;
queueInfo.queueFamilyIndex = vkDpy.graphicsQueueFamily;
queueInfo.queueCount = 1;
queueInfo.pQueuePriorities = &queuePriority;
const char* devExtensions[] = {VK_KHR_SWAPCHAIN_EXTENSION_NAME};
VkDeviceCreateInfo devInfo{};
devInfo.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO;
devInfo.pQueueCreateInfos = &queueInfo;
devInfo.queueCreateInfoCount = 1;
devInfo.ppEnabledExtensionNames = devExtensions;
devInfo.enabledExtensionCount = 1;
if (vkCreateDevice(vkDpy.physicalDevice, &devInfo, nullptr, &vkDpy.device) != VK_SUCCESS) {
g_lastError = EGL_NOT_INITIALIZED;
return EGL_FALSE;
}
vkDpy.vkCreateSwapchainKHR = (PFN_vkCreateSwapchainKHR)vkGetDeviceProcAddr(vkDpy.device, "vkCreateSwapchainKHR");
vkDpy.vkDestroySwapchainKHR = (PFN_vkDestroySwapchainKHR)vkGetDeviceProcAddr(vkDpy.device, "vkDestroySwapchainKHR");
vkDpy.vkGetSwapchainImagesKHR = (PFN_vkGetSwapchainImagesKHR)vkGetDeviceProcAddr(vkDpy.device, "vkGetSwapchainImagesKHR");
vkDpy.vkAcquireNextImageKHR = (PFN_vkAcquireNextImageKHR)vkGetDeviceProcAddr(vkDpy.device, "vkAcquireNextImageKHR");
vkDpy.vkQueuePresentKHR = (PFN_vkQueuePresentKHR)vkGetDeviceProcAddr(vkDpy.device, "vkQueuePresentKHR");
vkGetDeviceQueue(vkDpy.device, vkDpy.graphicsQueueFamily, 0, &vkDpy.graphicsQueue);
vkDpy.presentQueue = vkDpy.graphicsQueue;
vkDpy.initialized = true;
if (major) *major = 1;
if (minor) *minor = 5;
return EGL_TRUE;
}
EGLBoolean eglChooseConfig(EGLDisplay dpy, const EGLint* attrib_list, EGLConfig* configs, EGLint config_size, EGLint* num_config) {
VulkanDisplay& vkDpy = g_displays[dpy];
EGLInternalConfig defaultConfig{ VK_FORMAT_B8G8R8A8_SRGB, VK_COLOR_SPACE_SRGB_NONLINEAR_KHR, 1 };
vkDpy.configs = {defaultConfig};
EGLint returnCount = 1;
if (configs && config_size > 0) {
configs[0] = (EGLConfig)0;
}
if (num_config) *num_config = returnCount;
return EGL_TRUE;
}
EGLSurface eglCreateWindowSurface(EGLDisplay dpy, EGLConfig config, NativeWindowType window, const EGLint* attrib_list) {
VulkanDisplay& disp = g_displays[dpy];
static uintptr_t nextSurfId = 1;
ANativeWindow* nativeWindow = static_cast<ANativeWindow*>(window);
if (!nativeWindow || ANativeWindow_getWidth(nativeWindow) <= 0 || ANativeWindow_getHeight(nativeWindow) <= 0) {
g_lastError = EGL_BAD_NATIVE_WINDOW;
return EGL_NO_SURFACE;
}
auto vkCreateAndroidSurfaceKHR = (PFN_vkCreateAndroidSurfaceKHR)vkGetInstanceProcAddr(
disp.instance, "vkCreateAndroidSurfaceKHR");
if (!vkCreateAndroidSurfaceKHR) {
g_lastError = EGL_BAD_ALLOC;
return EGL_NO_SURFACE;
}
VulkanSurface surface{};
surface.type = VulkanSurface::WINDOW;
VkAndroidSurfaceCreateInfoKHR createInfo{};
createInfo.sType = VK_STRUCTURE_TYPE_ANDROID_SURFACE_CREATE_INFO_KHR;
createInfo.window = nativeWindow;
VkResult result = vkCreateAndroidSurfaceKHR(disp.instance, &createInfo, nullptr, &surface.surface);
if (result != VK_SUCCESS) {
g_lastError = (result == VK_ERROR_NATIVE_WINDOW_IN_USE_KHR) ?
EGL_BAD_NATIVE_WINDOW : EGL_BAD_ALLOC;
return EGL_NO_SURFACE;
}
VkBool32 supported = VK_FALSE;
vkGetPhysicalDeviceSurfaceSupportKHR(disp.physicalDevice,
disp.graphicsQueueFamily,
surface.surface,
&supported);
if (!supported) {
vkDestroySurfaceKHR(disp.instance, surface.surface, nullptr);
g_lastError = EGL_BAD_MATCH;
return EGL_NO_SURFACE;
}
VkSurfaceCapabilitiesKHR caps;
vkGetPhysicalDeviceSurfaceCapabilitiesKHR(disp.physicalDevice, surface.surface, &caps);
const VkExtent2D swapchainExtent = {
(std::max)(caps.minImageExtent.width, (uint32_t)ANativeWindow_getWidth(nativeWindow)),
(std::max)(caps.minImageExtent.height, (uint32_t)ANativeWindow_getHeight(nativeWindow))
};
VkSwapchainCreateInfoKHR swapInfo{};
swapInfo.sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR;
swapInfo.surface = surface.surface;
swapInfo.minImageCount = 3;
swapInfo.imageFormat = VK_FORMAT_R8G8B8A8_SRGB;
swapInfo.imageColorSpace = VK_COLOR_SPACE_SRGB_NONLINEAR_KHR;
swapInfo.imageExtent = swapchainExtent;
swapInfo.imageArrayLayers = 1;
swapInfo.imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT;
swapInfo.preTransform = caps.currentTransform;
swapInfo.compositeAlpha = VK_COMPOSITE_ALPHA_INHERIT_BIT_KHR;
swapInfo.presentMode = VK_PRESENT_MODE_MAILBOX_KHR;
if (disp.vkCreateSwapchainKHR(disp.device, &swapInfo, nullptr, &surface.swapchain) != VK_SUCCESS) {
vkDestroySurfaceKHR(disp.instance, surface.surface, nullptr);
g_lastError = EGL_BAD_ALLOC;
return EGL_NO_SURFACE;
}
uint32_t imageCount = 0;
disp.vkGetSwapchainImagesKHR(disp.device, surface.swapchain, &imageCount, nullptr);
surface.images.resize(imageCount);
disp.vkGetSwapchainImagesKHR(disp.device, surface.swapchain, &imageCount, surface.images.data());
surface.imageViews.resize(imageCount);
for (uint32_t i = 0; i < imageCount; ++i) {
VkImageViewCreateInfo viewInfo{};
viewInfo.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;
viewInfo.image = surface.images[i];
viewInfo.viewType = VK_IMAGE_VIEW_TYPE_2D;
viewInfo.format = swapInfo.imageFormat;
viewInfo.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1};
if (vkCreateImageView(disp.device, &viewInfo, nullptr, &surface.imageViews[i]) != VK_SUCCESS) {
// Handle error
}
}
ANativeWindow_acquire(nativeWindow);
ANativeWindow_setBuffersGeometry(nativeWindow,
swapchainExtent.width,
swapchainExtent.height,
AHARDWAREBUFFER_FORMAT_R8G8B8A8_UNORM);
EGLSurface surfId = (EGLSurface)nextSurfId++;
g_surfaces[surfId] = std::move(surface);
return surfId;
}
EGLContext eglCreateContext(EGLDisplay dpy, EGLConfig config, EGLContext shareCtx, const EGLint* attrib_list) {
static uintptr_t nextCtxId = 1;
VulkanDisplay &disp = g_displays[dpy];
VulkanContext ctx{};
VkCommandPoolCreateInfo poolInfo{};
poolInfo.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
poolInfo.queueFamilyIndex = 0;
if (vkCreateCommandPool(disp.device, &poolInfo, nullptr, &ctx.cmdPool) != VK_SUCCESS) {
g_lastError = EGL_BAD_ALLOC;
return EGL_NO_CONTEXT;
}
ctx.frameFences.resize(2);
ctx.acquireSemaphores.resize(2);
ctx.presentSemaphores.resize(2);
for (uint32_t i = 0; i < 2; ++i) {
VkFenceCreateInfo fenceInfo{VK_STRUCTURE_TYPE_FENCE_CREATE_INFO, nullptr,
VK_FENCE_CREATE_SIGNALED_BIT};
vkCreateFence(disp.device, &fenceInfo, nullptr, &ctx.frameFences[i]);
VkSemaphoreCreateInfo semInfo{VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO};
vkCreateSemaphore(disp.device, &semInfo, nullptr, &ctx.acquireSemaphores[i]);
vkCreateSemaphore(disp.device, &semInfo, nullptr, &ctx.presentSemaphores[i]);
}
if (CreateRenderPass(disp, ctx) != VK_SUCCESS) {
g_lastError = EGL_BAD_CONFIG;
return EGL_NO_CONTEXT;
}
EGLContext ctxId = (EGLContext)nextCtxId++;
g_contexts[ctxId] = std::move(ctx);
return ctxId;
}
EGLint eglGetError() {
return EGL_SUCCESS;
}
EGLBoolean eglMakeCurrent(EGLDisplay dpy, EGLSurface draw, EGLSurface read, EGLContext ctx) {
std::lock_guard<std::mutex> lock(g_globalMutex);
if (dpy == EGL_NO_DISPLAY || (ctx != EGL_NO_CONTEXT && !g_contexts.count(ctx)) ||
(draw != EGL_NO_SURFACE && !g_surfaces.count(draw)) ||
(read != EGL_NO_SURFACE && !g_surfaces.count(read))) {
g_lastError = EGL_BAD_PARAMETER;
return EGL_FALSE;
}
if (tls_currentContext != EGL_NO_CONTEXT) {
VulkanContext& oldCtx = g_contexts[tls_currentContext];
if (oldCtx.currentCmdBuffer) {
vkEndCommandBuffer(oldCtx.currentCmdBuffer);
oldCtx.currentCmdBuffer = VK_NULL_HANDLE;
}
}
if (ctx != EGL_NO_CONTEXT) {
VulkanContext& newCtx = g_contexts[ctx];
VulkanDisplay& disp = g_displays[dpy];
VkCommandBufferAllocateInfo allocInfo{};
allocInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
allocInfo.commandPool = newCtx.cmdPool;
allocInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
allocInfo.commandBufferCount = 1;
if (vkAllocateCommandBuffers(disp.device, &allocInfo, &newCtx.currentCmdBuffer) != VK_SUCCESS) {
g_lastError = EGL_BAD_ALLOC;
return EGL_FALSE;
}
VkCommandBufferBeginInfo beginInfo{};
beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
vkBeginCommandBuffer(newCtx.currentCmdBuffer, &beginInfo);
}
tls_currentContext = ctx;
tls_drawSurface = draw;
tls_readSurface = read;
return EGL_TRUE;
}
EGLBoolean eglDestroyContext(EGLDisplay dpy, EGLContext ctx) {
std::lock_guard<std::mutex> lock(g_globalMutex);
if (!g_contexts.count(ctx)) {
g_lastError = EGL_BAD_CONTEXT;
return EGL_FALSE;
}
VulkanContext& vkCtx = g_contexts[ctx];
VulkanDisplay& disp = g_displays[dpy];
vkDeviceWaitIdle(disp.device);
vkDestroyCommandPool(disp.device, vkCtx.cmdPool, nullptr);
vkDestroyRenderPass(disp.device, vkCtx.renderPass, nullptr);
for (auto& fence : vkCtx.frameFences)
vkDestroyFence(disp.device, fence, nullptr);
for (auto& sem : vkCtx.acquireSemaphores)
vkDestroySemaphore(disp.device, sem, nullptr);
for (auto& sem : vkCtx.presentSemaphores)
vkDestroySemaphore(disp.device, sem, nullptr);
g_contexts.erase(ctx);
if (tls_currentContext == ctx)
tls_currentContext = EGL_NO_CONTEXT;
return EGL_TRUE;
}
EGLBoolean eglDestroySurface(EGLDisplay dpy, EGLSurface surface) {
std::lock_guard<std::mutex> lock(g_globalMutex);
if (!g_surfaces.count(surface)) {
g_lastError = EGL_BAD_SURFACE;
return EGL_FALSE;
}
VulkanSurface& surf = g_surfaces[surface];
VulkanDisplay& disp = g_displays[dpy];
vkDeviceWaitIdle(disp.device);
if (surf.type == VulkanSurface::WINDOW) {
disp.vkDestroySwapchainKHR(disp.device, surf.swapchain, nullptr);
vkDestroySurfaceKHR(disp.instance, surf.surface, nullptr);
for (auto& view : surf.imageViews)
vkDestroyImageView(disp.device, view, nullptr);
} else {
vkDestroyImageView(disp.device, surf.pbufferImageView, nullptr);
vkDestroyImage(disp.device, surf.pbufferImage, nullptr);
}
g_surfaces.erase(surface);
return EGL_TRUE;
}
EGLBoolean eglTerminate(EGLDisplay dpy) {
std::lock_guard<std::mutex> lock(g_globalMutex);
if (!g_displays.count(dpy)) {
g_lastError = EGL_BAD_DISPLAY;
return EGL_FALSE;
}
VulkanDisplay& disp = g_displays[dpy];
for (auto& [ctxId, ctx] : g_contexts)
eglDestroyContext(dpy, ctxId);
for (auto& [surfId, surf] : g_surfaces)
eglDestroySurface(dpy, surfId);
vkDestroyDevice(disp.device, nullptr);
vkDestroyInstance(disp.instance, nullptr);
g_displays.erase(dpy);
return EGL_TRUE;
}
EGLBoolean eglReleaseThread(void) {
tls_currentContext = EGL_NO_CONTEXT;
tls_drawSurface = EGL_NO_SURFACE;
tls_readSurface = EGL_NO_SURFACE;
return EGL_TRUE;
}
EGLContext eglGetCurrentContext(void) {
return tls_currentContext;
}
EGLBoolean eglGetConfigAttrib(EGLDisplay dpy, EGLConfig config, EGLint attribute, EGLint *value) {
VulkanDisplay& disp = g_displays[dpy];
if (!disp.configs.empty() && config == (EGLConfig)0) {
switch (attribute) {
case EGL_BUFFER_SIZE: *value = 32; break;
case EGL_RED_SIZE: *value = 8; break;
case EGL_GREEN_SIZE: *value = 8; break;
case EGL_BLUE_SIZE: *value = 8; break;
case EGL_ALPHA_SIZE: *value = 8; break;
case EGL_CONFIG_ID: *value = 1; break;
default: return EGL_FALSE;
}
return EGL_TRUE;
}
return EGL_FALSE;
}
EGLBoolean eglBindAPI(EGLenum api) {
if (api == EGL_OPENGL_ES_API) {
g_currentAPI = api;
return EGL_TRUE;
}
return EGL_FALSE;
}
EGLSurface eglCreatePbufferSurface(EGLDisplay dpy, EGLConfig config, const EGLint *attrib_list) {
VulkanDisplay& disp = g_displays[dpy];
VulkanSurface surface{};
surface.type = VulkanSurface::PBUFFER;
VkImageCreateInfo imgInfo{};
imgInfo.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO;
imgInfo.imageType = VK_IMAGE_TYPE_2D;
imgInfo.format = VK_FORMAT_R8G8B8A8_SRGB;
imgInfo.extent = {512, 512, 1};
imgInfo.mipLevels = 1;
imgInfo.arrayLayers = 1;
imgInfo.samples = VK_SAMPLE_COUNT_1_BIT;
imgInfo.tiling = VK_IMAGE_TILING_OPTIMAL;
imgInfo.usage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT;
imgInfo.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
if (vkCreateImage(disp.device, &imgInfo, nullptr, &surface.pbufferImage) != VK_SUCCESS) {
g_lastError = EGL_BAD_ALLOC;
return EGL_NO_SURFACE;
}
VkImageViewCreateInfo viewInfo{};
viewInfo.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;
viewInfo.image = surface.pbufferImage;
viewInfo.viewType = VK_IMAGE_VIEW_TYPE_2D;
viewInfo.format = imgInfo.format;
viewInfo.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1};
if (vkCreateImageView(disp.device, &viewInfo, nullptr, &surface.pbufferImageView) != VK_SUCCESS) {
vkDestroyImage(disp.device, surface.pbufferImage, nullptr);
g_lastError = EGL_BAD_ALLOC;
return EGL_NO_SURFACE;
}
EGLSurface surfId = (EGLSurface)g_nextSurfaceId++;
g_surfaces[surfId] = surface;
return surfId;
}
EGLBoolean eglSwapBuffers(EGLDisplay dpy, EGLSurface draw) {
VulkanSurface& surf = g_surfaces[draw];
VulkanDisplay& disp = g_displays[dpy];
VulkanContext& ctx = g_contexts[tls_currentContext];
if (!disp.presentQueue) {
g_lastError = EGL_BAD_DISPLAY;
return EGL_FALSE;
}
if (surf.type != VulkanSurface::WINDOW) {
g_lastError = EGL_BAD_SURFACE;
return EGL_FALSE;
}
vkEndCommandBuffer(ctx.currentCmdBuffer);
VkSubmitInfo submitInfo{};
submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
submitInfo.commandBufferCount = 1;
submitInfo.pCommandBuffers = &ctx.currentCmdBuffer;
vkQueueSubmit(disp.graphicsQueue, 1, &submitInfo, VK_NULL_HANDLE);
VkPresentInfoKHR presentInfo{};
presentInfo.sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR;
presentInfo.swapchainCount = 1;
presentInfo.pSwapchains = &surf.swapchain;
presentInfo.pImageIndices = &ctx.frameIndex;
VkResult result = disp.vkQueuePresentKHR(disp.presentQueue, &presentInfo);
if (result != VK_SUCCESS) {
g_lastError = EGL_BAD_ALLOC;
return EGL_FALSE;
}
ctx.frameIndex = (ctx.frameIndex + 1) % surf.images.size();
return EGL_TRUE;
}
EGLBoolean eglSwapInterval(EGLDisplay dpy, EGLint interval) {
// TODO
return EGL_TRUE;
}
EGLSurface eglGetCurrentSurface(EGLint readdraw) {
return (readdraw == EGL_READ) ? tls_readSurface : tls_drawSurface;
}
EGLBoolean eglQuerySurface(EGLDisplay display, EGLSurface surface, EGLint attribute, EGLint *value) {
VulkanSurface& surf = g_surfaces[surface];
switch (attribute) {
case EGL_WIDTH: *value = surf.extent.width; break;
case EGL_HEIGHT: *value = surf.extent.height; break;
case EGL_CONFIG_ID: *value = 1; break;
default: return EGL_FALSE;
}
return EGL_TRUE;
}
#endif
-103
View File
@@ -1,103 +0,0 @@
//
// Created by BZLZHH on 2025/3/30.
//
#ifndef MOBILEGL_EGL_VK_EMU_H
#define MOBILEGL_EGL_VK_EMU_H
#include "../../../../Includes.h"
#if BACKEND_TYPE == BACKEND_VULKAN
struct EGLInternalConfig {
VkFormat format;
VkColorSpaceKHR colorSpace;
uint32_t samples;
};
struct VulkanDisplay {
VkInstance instance;
VkPhysicalDevice physicalDevice;
VkDevice device;
uint32_t graphicsQueueFamily;
VkQueue graphicsQueue;
std::vector<EGLInternalConfig> configs;
bool initialized = false;
PFN_vkCreateSwapchainKHR vkCreateSwapchainKHR;
PFN_vkDestroySwapchainKHR vkDestroySwapchainKHR;
PFN_vkGetSwapchainImagesKHR vkGetSwapchainImagesKHR;
PFN_vkAcquireNextImageKHR vkAcquireNextImageKHR;
PFN_vkQueuePresentKHR vkQueuePresentKHR;
VkRenderPass defaultRenderPass;
VkQueue presentQueue = VK_NULL_HANDLE;
};
struct VulkanSurface {
enum Type { WINDOW, PBUFFER } type;
VkSurfaceKHR surface;
VkSwapchainKHR swapchain;
std::vector<VkImage> images;
std::vector<VkImageView> imageViews;
VkExtent2D extent;
VkFormat format;
VkImage pbImage;
VkImageView pbImageView;
VkDeviceMemory pbMemory;
VkFramebuffer framebuffer;
VkImage pbufferImage;
VkImageView pbufferImageView;
};
struct VulkanContext {
VkCommandPool cmdPool;
std::vector<VkCommandBuffer> cmdBuffers;
uint32_t currentFrame = 0;
VkRenderPass renderPass;
VkPipelineLayout pipelineLayout;
VkPipeline graphicsPipeline;
std::vector<VkFence> frameFences;
std::vector<VkSemaphore> acquireSemaphores;
std::vector<VkSemaphore> presentSemaphores;
VulkanSurface* boundSurface = nullptr;
VkCommandBuffer currentCmdBuffer;
uint32_t frameIndex;
VkClearColorValue clearColor;
};
extern std::atomic<uintptr_t> g_nextContextId;
extern std::atomic<uintptr_t> g_nextSurfaceId;
extern EGLenum g_currentAPI;
extern std::mutex g_globalMutex;
extern ankerl::unordered_map<EGLDisplay, VulkanDisplay> g_displays;
extern ankerl::unordered_map<EGLSurface, VulkanSurface> g_surfaces;
extern ankerl::unordered_map<EGLContext, VulkanContext> g_contexts;
extern EGLint g_lastError;
extern thread_local EGLContext tls_currentContext;
extern thread_local EGLSurface tls_drawSurface;
extern thread_local EGLSurface tls_readSurface;
MG_EXPORT EGLSurface eglCreateWindowSurface(EGLDisplay dpy, EGLConfig config, NativeWindowType window, const EGLint* attrib_list);
MG_EXPORT EGLBoolean eglChooseConfig(EGLDisplay dpy, const EGLint* attrib_list, EGLConfig* configs, EGLint config_size, EGLint* num_config);
MG_EXPORT EGLContext eglCreateContext(EGLDisplay dpy, EGLConfig config, EGLContext shareCtx, const EGLint* attrib_list);
MG_EXPORT EGLBoolean eglInitialize(EGLDisplay dpy, EGLint* major, EGLint* minor);
MG_EXPORT EGLDisplay eglGetDisplay(NativeDisplayType display);
MG_EXPORT EGLint eglGetError();
MG_EXPORT EGLBoolean eglMakeCurrent(EGLDisplay dpy, EGLSurface draw, EGLSurface read, EGLContext ctx);
MG_EXPORT EGLBoolean eglDestroyContext(EGLDisplay dpy, EGLContext ctx);
MG_EXPORT EGLBoolean eglDestroySurface(EGLDisplay dpy, EGLSurface surface);
MG_EXPORT EGLBoolean eglTerminate(EGLDisplay dpy);
MG_EXPORT EGLBoolean eglReleaseThread(void);
MG_EXPORT EGLContext eglGetCurrentContext(void);
MG_EXPORT EGLBoolean eglGetConfigAttrib(EGLDisplay dpy, EGLConfig config, EGLint attribute, EGLint *value);
MG_EXPORT EGLBoolean eglBindAPI(EGLenum api);
MG_EXPORT EGLSurface eglGetCurrentSurface(EGLint readdraw);
MG_EXPORT EGLBoolean eglQuerySurface(EGLDisplay display, EGLSurface surface, EGLint attribute, EGLint *value);
MG_EXPORT EGLBoolean eglSwapInterval(EGLDisplay dpy, EGLint interval);
MG_EXPORT EGLBoolean eglSwapBuffers(EGLDisplay dpy, EGLSurface draw);
MG_EXPORT EGLSurface eglCreatePbufferSurface(EGLDisplay dpy, EGLConfig config, const EGLint *attrib_list);
#endif
#endif //MOBILEGL_EGL_VK_EMU_H
@@ -1,188 +0,0 @@
//
// Created by BZLZHH on 2025/3/15.
//
#include "GL_Buffer.h"
namespace MG_GL::GL {
void* MapBufferRange(GLenum target, GLintptr offset, GLsizeiptr length,
GLbitfield access) {
MG_Util::Debug::LogD("glMapBufferRange, target: %s, offset: %lld, length: %lld, access: 0x%X",
MG_Util::Debug::GLEnumToString(target),
static_cast<long long>(offset),
static_cast<long long>(length),
access);
void* mappedPointer = nullptr;
GLenum result = MG_State::AcquireBufferMemoryRange(target, offset, length, access, &mappedPointer);
if (result == GL_NO_ERROR) {
MG_Util::Debug::LogD("Mapped pointer: %p", mappedPointer);
return mappedPointer;
}
MG_State::SetError(result);
MG_Util::Debug::LogE("Error mapping buffer range: %s", MG_Util::Debug::GLEnumToString(result));
return nullptr;
}
void FlushMappedBufferRange(GLenum target, GLintptr offset, GLsizeiptr length) {
MG_Util::Debug::LogD("glFlushMappedBufferRange, target: %s, offset: %lld, length: %lld",
MG_Util::Debug::GLEnumToString(target),
static_cast<long long>(offset),
static_cast<long long>(length));
GLenum result = MG_State::SyncBufferMemory(target, offset, length);
if (result == GL_NO_ERROR) {
return;
}
MG_State::SetError(result);
MG_Util::Debug::LogE("Error flushing mapped buffer range: %s",
MG_Util::Debug::GLEnumToString(result));
}
void CopyBufferSubData(GLenum readTarget, GLenum writeTarget,
GLintptr readOffset, GLintptr writeOffset,
GLsizeiptr size) {
MG_Util::Debug::LogD("glCopyBufferSubData, readTarget: %s, writeTarget: %s, "
"readOffset: %lld, writeOffset: %lld, size: %lld",
MG_Util::Debug::GLEnumToString(readTarget),
MG_Util::Debug::GLEnumToString(writeTarget),
static_cast<long long>(readOffset),
static_cast<long long>(writeOffset),
static_cast<long long>(size));
GLenum result = MG_State::CopyBufferRange(readTarget, writeTarget, readOffset, writeOffset, size);
if (result == GL_NO_ERROR) {
return;
}
MG_State::SetError(result);
MG_Util::Debug::LogE("Error copying buffer subdata: %s",
MG_Util::Debug::GLEnumToString(result));
}
void* MapBuffer(GLenum target, GLenum access) {
MG_Util::Debug::LogD("glMapBuffer(target=0x%x, access=0x%x)", target, access);
void* mappedPtr = nullptr;
GLenum err = MG_State::AcquireBufferMemory(target, access, &mappedPtr);
if (err != GL_NO_ERROR) {
MG_State::SetError(err);
MG_Util::Debug::LogE("glMapBuffer failed: %s", MG_Util::Debug::GLEnumToString(err));
return nullptr;
}
MG_Util::Debug::LogD("glMapBuffer returns %p", mappedPtr);
return mappedPtr;
}
GLboolean UnmapBuffer(GLenum target) {
MG_Util::Debug::LogD("glUnmapBuffer(target=0x%x)", target);
GLenum err = MG_State::ReleaseBufferMemory(target);
if (err != GL_NO_ERROR) {
MG_State::SetError(err);
MG_Util::Debug::LogE("glUnmapBuffer failed: %s", MG_Util::Debug::GLEnumToString(err));
return GL_FALSE;
}
MG_Util::Debug::LogD("glUnmapBuffer succeeded");
return GL_TRUE;
}
void BindBuffer(GLenum target, GLuint buffer) {
MG_Util::Debug::LogD("glBindBuffer, target: %s, buffer: %d", MG_Util::Debug::GLEnumToString(target), buffer);
if (buffer != 0 &&
MG_State::ValidateGeneratedName(buffer) &&
!MG_State::ValidateAllocatedBufferHandle(buffer)) {
MG_Util::Debug::LogD("Actually creating buffer: %u", buffer);
GLenum result = MG_State::CreateBuffer(buffer);
if (result != GL_NO_ERROR) {
MG_State::SetError(result);
MG_Util::Debug::LogE("Error from MG State: %s", MG_Util::Debug::GLEnumToString(result));
return;
}
}
if (buffer != 0 && !MG_State::ValidateAllocatedBufferHandle(buffer)) {
MG_State::SetError(GL_INVALID_VALUE);
MG_Util::Debug::LogE("Invalid buffer handle: %u", buffer);
return;
}
GLenum result = MG_State::BindBuffer(target, buffer);
if (result == GL_NO_ERROR)
return;
MG_State::SetError(result);
MG_Util::Debug::LogE("Error from MG State: %s", MG_Util::Debug::GLEnumToString(result));
}
void BufferData(GLenum target, GLsizeiptr size, const void* data, GLenum usage) {
MG_Util::Debug::LogD("glBufferData, target: %s, size: %zd, data: %p, usage: %s",
MG_Util::Debug::GLEnumToString(target), size, data, MG_Util::Debug::GLEnumToString(usage));
GLenum result = MG_State::CommitBufferStorage(target, size, data, usage);
if (result == GL_NO_ERROR)
return;
MG_State::SetError(result);
MG_Util::Debug::LogE("Error from MG State: %s", MG_Util::Debug::GLEnumToString(result));
}
void GetBufferParameteriv(GLenum target, GLenum pname, GLint* params) {
MG_Util::Debug::LogD("glGetBufferParameteriv, target: %d, pname: %d, params: %p",
target, pname, params);
GLenum result = MG_State::QueryBufferPropertyIntVector(target, pname, params);
if (result == GL_NO_ERROR)
return;
MG_State::SetError(result);
MG_Util::Debug::LogE("GetBufferParameteriv not implemented");
}
void GenBuffers(GLsizei n, GLuint* buffers) {
MG_Util::Debug::LogD("glGenBuffers, n: %d, buffers: %p", n, buffers);
if (n < 0) {
MG_State::SetError(GL_INVALID_VALUE);
MG_Util::Debug::LogE("Invalid buffer count: %d", n);
return;
}
GLenum result = MG_State::GenBufferNames(n, buffers);
if (result == GL_NO_ERROR) {
MG_Util::Debug::LogD("Generated buffer names:");
for (GLsizei i = 0; i < n; ++i) {
MG_Util::Debug::LogD(" Buffer[%d] = %u", i, buffers[i]);
}
return;
}
MG_State::SetError(result);
MG_Util::Debug::LogE("Error from MG State: %s", MG_Util::Debug::GLEnumToString(result));
}
GLboolean IsBuffer(GLuint buffer) {
MG_Util::Debug::LogD("glIsBuffer, buffer: %u", buffer);
if (buffer == 0) {
return GL_FALSE;
}
bool isValid = MG_State::ValidateAllocatedBufferHandle(buffer);
// Should we report gl error here or in MG_State?
MG_Util::Debug::LogD("Buffer %u is %s", buffer, isValid ? "valid" : "invalid");
return isValid ? GL_TRUE : GL_FALSE;
}
void BufferSubData(GLenum target, GLintptr offset, GLsizeiptr size, const void* data) {
MG_Util::Debug::LogD("glBufferSubData, target: %s, offset: %lld, size: %lld, data: %p",
MG_Util::Debug::GLEnumToString(target),
static_cast<long long>(offset),
static_cast<long long>(size),
data);
GLenum result = MG_State::CommitBufferStorageRegion(target, offset, size, data);
if (result != GL_NO_ERROR) {
MG_State::SetError(result);
MG_Util::Debug::LogE("Error from MG State: %s", MG_Util::Debug::GLEnumToString(result));
}
}
void DeleteBuffers(GLsizei n, const GLuint *buffers) {
MG_Util::Debug::LogD("glDeleteBuffers, n: %d, buffers: %p", n, buffers);
GLenum result = MG_State::DeleteBuffers(n, buffers);
if (result == GL_NO_ERROR)
return;
MG_State::SetError(result);
MG_Util::Debug::LogE("Error from MG State: %s", MG_Util::Debug::GLEnumToString(result));
}
}
@@ -1,25 +0,0 @@
//
// Created by BZLZHH on 2025/3/15.
//
#ifndef MOBILEGL_GL_BUFFER_H
#define MOBILEGL_GL_BUFFER_H
#include "../../../../Includes.h"
namespace MG_GL::GL {
void* MapBufferRange(GLenum target, GLintptr offset, GLsizeiptr length, GLbitfield access);
void FlushMappedBufferRange(GLenum target, GLintptr offset, GLsizeiptr length);
void CopyBufferSubData(GLenum readTarget, GLenum writeTarget, GLintptr readOffset, GLintptr writeOffset, GLsizeiptr size);
void* MapBuffer(GLenum target, GLenum access);
GLboolean UnmapBuffer(GLenum target);
void BindBuffer(GLenum target, GLuint buffer);
void BufferData(GLenum target, GLsizeiptr size, const void* data, GLenum usage);
void BufferSubData(GLenum target, GLintptr offset, GLsizeiptr size, const void* data);
void GetBufferParameteriv(GLenum target, GLenum pname, GLint* params);
void GenBuffers(GLsizei n, GLuint* buffers);
void DeleteBuffers(GLsizei n, const GLuint *buffers);
GLboolean IsBuffer(GLuint buffer);
}
#endif //MOBILEGL_GL_BUFFER_H
@@ -1,113 +0,0 @@
//
// Created by BZLZHH on 2025/3/15.
//
#include "GL_Common.h"
namespace MG_GL::GL {
void Clear(GLbitfield mask) {
MG_Util::Debug::LogD("glClear, mask: 0x%X", mask);
GLenum result = MG_State::glClear(mask);
if (result == GL_NO_ERROR) {
return;
}
MG_State::SetError(result);
MG_Util::Debug::LogE("Error clearing buffers: %s", MG_Util::Debug::GLEnumToString(result));
}
void Enable(GLenum cap) {
MG_Util::Debug::LogD("glEnable, cap: %s", MG_Util::Debug::GLEnumToString(cap));
GLenum result = MG_State::glEnable(cap);
if (result == GL_NO_ERROR) return;
MG_State::SetError(result);
MG_Util::Debug::LogE("Error enabling capability: %s", MG_Util::Debug::GLEnumToString(result));
}
void Disable(GLenum cap) {
MG_Util::Debug::LogD("glDisable, cap: %s", MG_Util::Debug::GLEnumToString(cap));
GLenum result = MG_State::glDisable(cap);
if (result == GL_NO_ERROR) return;
MG_State::SetError(result);
MG_Util::Debug::LogE("Error disabling capability: %s", MG_Util::Debug::GLEnumToString(result));
}
void BlendFunc(GLenum sfactor, GLenum dfactor) {
MG_Util::Debug::LogD("glBlendFunc, sfactor: %s, dfactor: %s",
MG_Util::Debug::GLEnumToString(sfactor),
MG_Util::Debug::GLEnumToString(dfactor));
GLenum result = MG_State::glBlendFunc(sfactor, dfactor);
if (result == GL_NO_ERROR) return;
MG_State::SetError(result);
MG_Util::Debug::LogE("Error setting blend func: %s", MG_Util::Debug::GLEnumToString(result));
}
void BlendFuncSeparate(GLenum srcRGB, GLenum dstRGB, GLenum srcAlpha, GLenum dstAlpha) {
MG_Util::Debug::LogD("glBlendFuncSeparate, srcRGB: %s, dstRGB: %s, srcAlpha: %s, dstAlpha: %s",
MG_Util::Debug::GLEnumToString(srcRGB),
MG_Util::Debug::GLEnumToString(dstRGB),
MG_Util::Debug::GLEnumToString(srcAlpha),
MG_Util::Debug::GLEnumToString(dstAlpha));
GLenum result = MG_State::glBlendFuncSeparate(srcRGB, dstRGB, srcAlpha, dstAlpha);
if (result == GL_NO_ERROR) return;
MG_State::SetError(result);
MG_Util::Debug::LogE("Error setting separate blend func: %s", MG_Util::Debug::GLEnumToString(result));
}
void ClearColor(GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha) {
MG_Util::Debug::LogD("glClearColor, rgba: [%.2f, %.2f, %.2f, %.2f]", red, green, blue, alpha);
GLenum result = MG_State::glClearColor(red, green, blue, alpha);
if (result == GL_NO_ERROR) return;
MG_State::SetError(result);
MG_Util::Debug::LogE("Error setting clear color: %s", MG_Util::Debug::GLEnumToString(result));
}
void ClearDepth(GLdouble depth) {
MG_Util::Debug::LogD("glClearDepth, depth: %.3f", depth);
GLenum result = MG_State::glClearDepth(depth);
if (result == GL_NO_ERROR) return;
MG_State::SetError(result);
MG_Util::Debug::LogE("Error setting clear depth: %s", MG_Util::Debug::GLEnumToString(result));
}
void ColorMask(GLboolean red, GLboolean green, GLboolean blue, GLboolean alpha) {
MG_Util::Debug::LogD("glColorMask, rgba: [%d, %d, %d, %d]", red, green, blue, alpha);
GLenum result = MG_State::glColorMask(red, green, blue, alpha);
if (result == GL_NO_ERROR) return;
MG_State::SetError(result);
MG_Util::Debug::LogE("Error setting color mask: %s", MG_Util::Debug::GLEnumToString(result));
}
void DepthFunc(GLenum func) {
MG_Util::Debug::LogD("glDepthFunc, func: %s", MG_Util::Debug::GLEnumToString(func));
GLenum result = MG_State::glDepthFunc(func);
if (result == GL_NO_ERROR) return;
MG_State::SetError(result);
MG_Util::Debug::LogE("Error setting depth func: %s", MG_Util::Debug::GLEnumToString(result));
}
void DepthMask(GLboolean flag) {
MG_Util::Debug::LogD("glDepthMask, flag: %d", flag);
GLenum result = MG_State::glDepthMask(flag);
if (result == GL_NO_ERROR) return;
MG_State::SetError(result);
MG_Util::Debug::LogE("Error setting depth mask: %s", MG_Util::Debug::GLEnumToString(result));
}
void Viewport(GLint x, GLint y, GLsizei width, GLsizei height) {
MG_Util::Debug::LogD("glViewport, x: %d, y: %d, width: %d, height: %d",
x, y, width, height);
GLenum result = MG_State::glViewport(x, y, width, height);
if (result == GL_NO_ERROR) return;
MG_State::SetError(result);
MG_Util::Debug::LogE("Error setting viewport: %s", MG_Util::Debug::GLEnumToString(result));
}
void PixelStorei(GLenum pname, GLint param) {
MG_Util::Debug::LogD("glPixelStorei, pname: %d, param: %d", pname, param);
GLenum result = MG_State::SetPixelStoreInt(pname,param);
if (result == GL_NO_ERROR)
return;
MG_State::SetError(result);
MG_Util::Debug::LogE("Error from MG State: %s", MG_Util::Debug::GLEnumToString(result));
}
}
@@ -1,25 +0,0 @@
//
// Created by BZLZHH on 2025/3/15.
//
#ifndef MOBILEGL_GL_COMMON_H
#define MOBILEGL_GL_COMMON_H
#include "../../../../Includes.h"
namespace MG_GL::GL {
void ClearDepth(GLdouble depth);
void ClearColor(GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha);
void Clear(GLbitfield mask);
void PixelStorei(GLenum pname, GLint param);
void Enable(GLenum cap);
void Disable(GLenum cap);
void BlendFunc(GLenum sfactor, GLenum dfactor);
void BlendFuncSeparate(GLenum srcRGB, GLenum dstRGB, GLenum srcAlpha, GLenum dstAlpha);
void ColorMask(GLboolean red, GLboolean green, GLboolean blue, GLboolean alpha);
void DepthFunc(GLenum func);
void DepthMask(GLboolean flag);
void Viewport(GLint x, GLint y, GLsizei width, GLsizei height);
}
#endif //MOBILEGL_GL_COMMON_H
@@ -1,31 +0,0 @@
//
// Created by BZLZHH on 2025/3/15.
//
#include "GL_Drawing.h"
namespace MG_GL::GL {
void DrawElements(GLenum mode, GLsizei count, GLenum type, const void *indices) {
// TODO
}
void DrawArrays(GLenum mode, GLint first, GLsizei count) {
// TODO
}
void DrawElementsBaseVertex(GLenum mode, GLsizei count, GLenum type, const GLvoid *indices, GLint basevertex) {
// TODO
}
void MultiDrawElements(GLenum mode, const GLsizei *count, GLenum type, const GLvoid *const *indices, GLsizei drawcount) {
// TODO
}
void MultiDrawElementsBaseVertex(GLenum mode, const GLsizei *count, GLenum type, const GLvoid *const *indices, GLsizei drawcount, const GLint *basevertex) {
// TODO
}
void DrawBuffer(GLenum buf) {
// TODO
}
}
@@ -1,18 +0,0 @@
//
// Created by BZLZHH on 2025/3/15.
//
#ifndef MOBILEGL_GL_DRAWING_H
#define MOBILEGL_GL_DRAWING_H
#include "../../../../Includes.h"
namespace MG_GL::GL {
void DrawElements(GLenum mode, GLsizei count, GLenum type, const void *indices);
void DrawArrays(GLenum mode, GLint first, GLsizei count);
void DrawElementsBaseVertex(GLenum mode, GLsizei count, GLenum type, const GLvoid *indices, GLint basevertex);
void MultiDrawElements(GLenum mode, const GLsizei *count, GLenum type, const GLvoid *const *indices, GLsizei drawcount);
void MultiDrawElementsBaseVertex(GLenum mode, const GLsizei *count, GLenum type, const GLvoid *const *indices, GLsizei drawcount, const GLint *basevertex);
void DrawBuffer(GLenum buf);
}
#endif //MOBILEGL_GL_DRAWING_H
@@ -1,73 +0,0 @@
//
// Created by BZLZHH on 2025/3/15.
//
#include "GL_Framebuffer.h"
namespace MG_GL::GL {
void GenFramebuffers(GLsizei n, GLuint* framebuffers) {
MG_Util::Debug::LogD("glGenFramebuffers, n: %d, framebuffers: %p", n, framebuffers);
GLenum result = MG_State::CreateFramebuffers(n, framebuffers);
if (result == GL_NO_ERROR) return;
MG_State::SetError(result);
MG_Util::Debug::LogE("Framebuffer generation failed: %s", MG_Util::Debug::GLEnumToString(result));
}
void DeleteFramebuffers(GLsizei n, const GLuint* framebuffers) {
MG_Util::Debug::LogD("glDeleteFramebuffers, n: %d, framebuffers: %p", n, framebuffers);
for (GLsizei i = 0; i < n; ++i) {
GLenum result = MG_State::DeleteFramebuffer(framebuffers[i]);
if (result != GL_NO_ERROR) {
MG_State::SetError(result);
MG_Util::Debug::LogE("Failed to delete framebuffer %u: %s",
framebuffers[i], MG_Util::Debug::GLEnumToString(result));
}
}
}
void BindFramebuffer(GLenum target, GLuint framebuffer) {
MG_Util::Debug::LogD("glBindFramebuffer, target: %s, fb: %u",
MG_Util::Debug::GLEnumToString(target), framebuffer);
GLenum result = MG_State::BindFramebuffer(target, framebuffer);
if (result == GL_NO_ERROR) return;
MG_State::SetError(result);
MG_Util::Debug::LogE("Framebuffer bind error: %s", MG_Util::Debug::GLEnumToString(result));
}
void FramebufferTexture2D(GLenum target, GLenum attachment, GLenum textarget,
GLuint texture, GLint level) {
MG_Util::Debug::LogD("glFramebufferTexture2D, target: %s, attach: %s, textarget: %s, tex: %u, level: %d",
MG_Util::Debug::GLEnumToString(target),
MG_Util::Debug::GLEnumToString(attachment),
MG_Util::Debug::GLEnumToString(textarget),
texture, level);
GLenum result = MG_State::AttachTexture2DToFramebuffer(
target, attachment, textarget, texture, level
);
if (result == GL_NO_ERROR) return;
MG_State::SetError(result);
MG_Util::Debug::LogE("Texture attachment failed: %s", MG_Util::Debug::GLEnumToString(result));
}
GLenum CheckFramebufferStatus(GLenum target) {
MG_Util::Debug::LogD("glCheckFramebufferStatus, target: %s",
MG_Util::Debug::GLEnumToString(target));
GLenum result = MG_State::ValidateFramebufferCompleteness(target);
if (result >= GL_FRAMEBUFFER_COMPLETE) {
MG_Util::Debug::LogD("Framebuffer status: %s",
MG_Util::Debug::GLEnumToString(result));
return result;
}
MG_State::SetError(result);
MG_Util::Debug::LogE("Framebuffer incomplete: %s",
MG_Util::Debug::GLEnumToString(result));
return result;
}
void BlitFramebuffer(GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1,
GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1, GLbitfield mask, GLenum filter) {
// TODO
}
}
@@ -1,19 +0,0 @@
//
// Created by BZLZHH on 2025/3/15.
//
#ifndef MOBILEGL_GL_FRAMEBUFFER_H
#define MOBILEGL_GL_FRAMEBUFFER_H
#include "../../../../Includes.h"
namespace MG_GL::GL {
void GenFramebuffers(GLsizei n, GLuint* framebuffers);
void DeleteFramebuffers(GLsizei n, const GLuint* framebuffers);
void BindFramebuffer(GLenum target, GLuint framebuffer);
void FramebufferTexture2D(GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level);
GLenum CheckFramebufferStatus(GLenum target);
void BlitFramebuffer(GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1, GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1, GLbitfield mask, GLenum filter);
}
#endif //MOBILEGL_GL_FRAMEBUFFER_H
@@ -1,10 +0,0 @@
//
// Created by BZLZHH on 2025/3/15.
//
#ifndef MOBILEGL_GL_FUNCS_DEFINITIONS_H
#define MOBILEGL_GL_FUNCS_DEFINITIONS_H
#include "../../../../Includes.h"
#endif //MOBILEGL_GL_FUNCS_DEFINITIONS_H
@@ -1,93 +0,0 @@
//
// Created by BZLZHH on 2025/3/15.
//
#include "BackendInfo.h"
namespace MG_GL::Getter {
const std::string GetBackendName() {
#if BACKEND_TYPE == BACKEND_VULKAN
return "Vulkan";
#elif BACKEND_TYPE == BACKEND_METAL
return "Metal";
#elif BACKEND_TYPE == BACKEND_GLES
return "OpenGL ES";
#else
return "<Unknown Backend>";
#endif
}
const std::string GetMGName() {
#if BACKEND_TYPE == BACKEND_VULKAN
return "MobileGluvk";
#elif BACKEND_TYPE == BACKEND_METAL
return "MobileGlumtl";
#elif BACKEND_TYPE == BACKEND_GLES
return "MobileGlues";
#else
return "<Unknown MobileGL Version>";
#endif
}
void LogMGInfo() {
std::string MGName = MG_GL::Getter::GetMGName() + " (MobileGL Core)";
std::string MGVersion = std::to_string(MG_Global::MG::VersionMajor) + "."
+ std::to_string(MG_Global::MG::VersionMinor) + "."
+ std::to_string(MG_Global::MG::VersionRevision);
if (MG_Global::MG::VersionPatch != 0)
MGVersion += "." + std::to_string(MG_Global::MG::VersionPatch);
MGVersion += MG_Global::MG::VersionSuffix;
std::string GLVersion = std::to_string(MG_Global::GL::GLVersionMajor) + "."
+ std::to_string(MG_Global::GL::GLVersionMinor) + "."
+ std::to_string(MG_Global::GL::GLVersionRevision);
std::string backendName = MG_GL::Getter::GetBackendName();
std::string backendVersion;
#if BACKEND_TYPE == BACKEND_VULKAN
VkApplicationInfo appInfo = {};
appInfo.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO;
appInfo.pApplicationName = "Vulkan Version Query";
appInfo.applicationVersion = VK_MAKE_VERSION(1, 0, 0);
appInfo.pEngineName = "No Engine";
appInfo.engineVersion = VK_MAKE_VERSION(1, 0, 0);
appInfo.apiVersion = VK_API_VERSION_1_0;
VkInstanceCreateInfo createInfo = {};
createInfo.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;
createInfo.pApplicationInfo = &appInfo;
VkInstance instance;
if (vkCreateInstance(&createInfo, nullptr, &instance) != VK_SUCCESS) {
throw std::runtime_error("Failed to create Vulkan instance!");
}
uint32_t deviceCount = 0;
vkEnumeratePhysicalDevices(instance, &deviceCount, nullptr);
if (deviceCount == 0) {
throw std::runtime_error("No Vulkan devices found!");
}
VkPhysicalDevice physicalDevice;
vkEnumeratePhysicalDevices(instance, &deviceCount, &physicalDevice);
VkPhysicalDeviceProperties deviceProperties;
vkGetPhysicalDeviceProperties(physicalDevice, &deviceProperties);
uint32_t major = VK_VERSION_MAJOR(deviceProperties.apiVersion);
uint32_t minor = VK_VERSION_MINOR(deviceProperties.apiVersion);
uint32_t patch = VK_VERSION_PATCH(deviceProperties.apiVersion);
vkDestroyInstance(instance, nullptr);
backendVersion = "Vulkan " + std::to_string(major) + "." +
std::to_string(minor)+"." + std::to_string(patch);
#elif BACKEND_TYPE == BACKEND_GLES
backendVersion = std::string((const char*)::GLES::glGetString(GL_VERSION));
#else
backendVersion = "<Unknown Backend>";
#endif
MG_Util::Debug::LogI("MobileGL Renderer Info:");
MG_Util::Debug::LogI("----%s:", MGName.c_str());
MG_Util::Debug::LogI("--------MobileGL Version: %s", MGVersion.c_str());
MG_Util::Debug::LogI("--------Target OpenGL Implementation Version: %s", GLVersion.c_str());
MG_Util::Debug::LogI("--------Backend: %s", backendName.c_str());
MG_Util::Debug::LogI("--------Backend Version: %s", backendVersion.c_str());
}
}
@@ -1,16 +0,0 @@
//
// Created by BZLZHH on 2025/3/15.
//
#ifndef MOBILEGL_BACKENDINFO_H
#define MOBILEGL_BACKENDINFO_H
#include "../../../../Includes.h"
namespace MG_GL::Getter {
const std::string GetBackendName();
const std::string GetMGName();
void LogMGInfo();
}
#endif //MOBILEGL_BACKENDINFO_H
@@ -1,320 +0,0 @@
//
// Created by BZLZHH on 2025/3/15.
//
#include "GL_Getter.h"
namespace MG_GL::GL {
static std::string rendererString;
static bool loggedMGInfo;
const GLubyte* GetString(GLenum name) {
if (!loggedMGInfo) {
loggedMGInfo = true;
MG_GL::Getter::LogMGInfo();
}
MG_Util::Debug::LogD("glGetString, name: %s", MG_Util::Debug::GLEnumToString(name));
switch (name) {
case GL_VENDOR:
return (const GLubyte *)"MobileGL-Dev";
case GL_VERSION: {
static std::string versionStr;
if (versionStr.empty()) {
versionStr = std::to_string(MG_Global::GL::GLVersionMajor) + "."
+ std::to_string(MG_Global::GL::GLVersionMinor) + "."
+ std::to_string(MG_Global::GL::GLVersionRevision)
+ " "+ MG_GL::Getter::GetMGName() +
", MobileGL Core, " + MG_GL::Getter::GetBackendName() + " Backend, Version "
+ std::to_string(MG_Global::MG::VersionMajor) + "."
+ std::to_string(MG_Global::MG::VersionMinor) + "."
+ std::to_string(MG_Global::MG::VersionRevision);
if (MG_Global::MG::VersionPatch != 0)
versionStr += "." + std::to_string(MG_Global::MG::VersionPatch);
versionStr += MG_Global::MG::VersionSuffix;
}
return (const GLubyte *)versionStr.c_str();
}
case GL_RENDERER:
{
/*
if (rendererString == std::string("")) {
const char* gpuName = getGpuName();
const char* glesName = getGLESName();
rendererString = std::string(gpuName) + " | " + std::string(glesName);
}
return (const GLubyte *)rendererString.c_str();
*/
return (const GLubyte *)(MG_GL::Getter::GetMGName() + " (MobileGL Core) Renderer").c_str();
}
case GL_SHADING_LANGUAGE_VERSION:
return (const GLubyte *) "4.50 MobileGL with glslang";
case GL_EXTENSIONS:
return (const GLubyte *) "OpenGL11 "
"OpenGL12 "
"OpenGL13 "
"OpenGL14 "
"OpenGL15 "
"OpenGL20 "
"OpenGL21 "
"OpenGL30 ";
default:
return (const GLubyte *) "Unknown enum";
}
}
const GLubyte* GetStringi(GLenum name, GLuint index) {
MG_Util::Debug::LogD("glGetStringi, name: %s, index: %d", MG_Util::Debug::GLEnumToString(name), index);
if (name != GL_EXTENSIONS)
return (const GLubyte*)"";
typedef struct {
GLenum name;
const char** parts;
GLuint count;
} StringCache;
static StringCache caches[] = {
{GL_EXTENSIONS, nullptr, 0},
};
static int initialized = 0;
if (!initialized) {
for (auto & cache : caches) {
GLenum target = cache.name;
const GLubyte* str = nullptr;
const char* delimiter = " ";
str = GetString(GL_EXTENSIONS);
char* copy = strdup((const char*)str);
char* token = strtok(copy, delimiter);
while (token) {
cache.parts = (const char**)realloc(cache.parts, (cache.count + 1) * sizeof(char*));
cache.parts[cache.count++] = strdup(token);
token = strtok(nullptr, delimiter);
}
free(copy);
}
initialized = 1;
}
for (auto & cache : caches) {
if (cache.name == name) {
if (index >= cache.count) {
return nullptr;
}
return (const GLubyte*)cache.parts[index];
}
}
return nullptr;
}
GLenum GetError() {
GLenum error = MG_State::GetError();
MG_Util::Debug::LogD("glGetError -> %s", MG_Util::Debug::GLEnumToString(error));
return error;
}
void GetIntegerv(GLenum pname, GLint *params) {
MG_Util::Debug::LogD("glGetIntegerv, pname: %s", MG_Util::Debug::GLEnumToString(pname));
if (!params) {
MG_State::SetError(GL_INVALID_VALUE);
return;
}
switch (pname) {
// General
case GL_CONTEXT_PROFILE_MASK:
params[0] = GL_CONTEXT_CORE_PROFILE_BIT;
break;
case GL_NUM_EXTENSIONS:
static GLint num_extensions = -1;
if (num_extensions == -1) {
const GLubyte* ext_str = MG_GL::GL::GetString(GL_EXTENSIONS);
char *copy = strdup((const char *) ext_str);
char *token = strtok(copy, " ");
num_extensions = 0;
while (token) {
num_extensions++;
token = strtok(nullptr, " ");
}
free(copy);
}
params[0] = num_extensions;
break;
case GL_MAJOR_VERSION:
params[0] = MG_Global::GL::GLVersionMajor;
break;
case GL_MINOR_VERSION:
params[0] = MG_Global::GL::GLVersionMinor;
break;
// Viewport and scissor
case GL_VIEWPORT:
memcpy(params, MG_State_T::commonState->viewport, 4 * sizeof(GLint));
break;
case GL_SCISSOR_BOX:
// TODO: memcpy(params, MG_State_T::commonState->scissorBox, 4 * sizeof(GLint));
break;
case GL_MAX_VIEWPORT_DIMS: {
static const GLint maxDims[2] = {16384, 16384};
memcpy(params, maxDims, sizeof(maxDims));
break;
}
// Buffer bindings
case GL_ARRAY_BUFFER_BINDING:
params[0] = static_cast<GLint>(MG_State_T::bufferState->GetCurrentBinding(GL_ARRAY_BUFFER));
break;
case GL_ELEMENT_ARRAY_BUFFER_BINDING:
params[0] = static_cast<GLint>(MG_State_T::vertexArrayState->GetBoundElementBuffer());
break;
case GL_DRAW_FRAMEBUFFER_BINDING:
params[0] = static_cast<GLint>(MG_State_T::framebufferState->currentBindings_[GL_DRAW_FRAMEBUFFER]);
break;
case GL_READ_FRAMEBUFFER_BINDING:
params[0] = static_cast<GLint>(MG_State_T::framebufferState->currentBindings_[GL_READ_FRAMEBUFFER]);
break;
case GL_RENDERBUFFER_BINDING:
// TODO: params[0] = static_cast<GLint>(MG_State_T::framebufferState->currentRenderbuffer_);
break;
// Program state
case GL_CURRENT_PROGRAM:
params[0] = static_cast<GLint>(MG_State_T::programState->currentProgram_);
break;
case GL_MAX_VERTEX_ATTRIBS:
// TODO: Check the real value
params[0] = 64;
break;
// Texture state
case GL_TEXTURE_BINDING_2D: {
GLuint unit = MG_State_T::textureState->activeTextureUnit_;
auto& textures = MG_State_T::textureState->textureUnits_[unit].boundTextures;
params[0] = textures.count(GL_TEXTURE_2D) ? static_cast<GLint>(textures[GL_TEXTURE_2D]) : 0;
break;
}
case GL_ACTIVE_TEXTURE:
params[0] = GL_TEXTURE0 + MG_State_T::textureState->activeTextureUnit_;
break;
case GL_MAX_TEXTURE_SIZE:
params[0] = 8192;
break;
// Blend state
case GL_BLEND_SRC_RGB:
params[0] = static_cast<GLint>(MG_State_T::commonState->blendSrcRGB);
break;
case GL_BLEND_DST_RGB:
params[0] = static_cast<GLint>(MG_State_T::commonState->blendDstRGB);
break;
case GL_BLEND_SRC_ALPHA:
params[0] = static_cast<GLint>(MG_State_T::commonState->blendSrcAlpha);
break;
case GL_BLEND_DST_ALPHA:
params[0] = static_cast<GLint>(MG_State_T::commonState->blendDstAlpha);
break;
// Depth and stencil
case GL_DEPTH_FUNC:
params[0] = static_cast<GLint>(MG_State_T::commonState->depthFunc);
break;
case GL_DEPTH_WRITEMASK:
params[0] = static_cast<GLint>(MG_State_T::commonState->depthMask);
break;
case GL_STENCIL_REF:
// TODO: params[0] = MG_State_T::commonState->stencilRef;
break;
// Capability enables
case GL_BLEND:
params[0] = MG_State_T::commonState->capabilities[GL_BLEND] ? GL_TRUE : GL_FALSE;
break;
case GL_DEPTH_TEST:
params[0] = MG_State_T::commonState->capabilities[GL_DEPTH_TEST] ? GL_TRUE : GL_FALSE;
break;
case GL_SCISSOR_TEST:
params[0] = MG_State_T::commonState->capabilities[GL_SCISSOR_TEST] ? GL_TRUE : GL_FALSE;
break;
// Pixel operations
case GL_PACK_ALIGNMENT:
params[0] = MG_State_T::commonState->QueryPixelStoreInt(GL_PACK_ALIGNMENT);
break;
case GL_UNPACK_ALIGNMENT:
params[0] = MG_State_T::commonState->QueryPixelStoreInt(GL_UNPACK_ALIGNMENT);
break;
// Hardware limits, TODO: Check the real values
case GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS:
params[0] = 32;
break;
case GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS:
params[0] = 32;
break;
case GL_MAX_TEXTURE_IMAGE_UNITS:
params[0] = 32;
break;
case GL_MAX_RENDERBUFFER_SIZE:
params[0] = 65537;
break;
case GL_MAX_DRAW_BUFFERS:
params[0] = 32;
break;
case GL_MAX_COLOR_ATTACHMENTS:
params[0] = 32;
break;
// Color state
case GL_COLOR_CLEAR_VALUE: {
const auto& c = MG_State_T::commonState->clearColor;
params[0] = static_cast<GLint>(c[0] * 0x7FFF);
params[1] = static_cast<GLint>(c[1] * 0x7FFF);
params[2] = static_cast<GLint>(c[2] * 0x7FFF);
params[3] = static_cast<GLint>(c[3] * 0x7FFF);
break;
}
case GL_COLOR_WRITEMASK:
params[0] = MG_State_T::commonState->colorMask[0];
params[1] = MG_State_T::commonState->colorMask[1];
params[2] = MG_State_T::commonState->colorMask[2];
params[3] = MG_State_T::commonState->colorMask[3];
break;
// Stencil operations
case GL_STENCIL_CLEAR_VALUE:
// TODO: params[0] = MG_State_T::commonState->stencilClearValue;
break;
case GL_STENCIL_BITS:
// TODO: Check the real value
params[0] = 8;
break;
// Implementation limits
case GL_SUBPIXEL_BITS:
// TODO: Check the real value
params[0] = 4;
break;
case GL_NUM_COMPRESSED_TEXTURE_FORMATS:
// TODO: params[0] = static_cast<GLint>(MG_State_T::textureState->compressedFormats_.size());
break;
case GL_COMPRESSED_TEXTURE_FORMATS:
// TODO: Implement GL_COMPRESSED_TEXTURE_FORMATS
break;
// Polygon state
case GL_POLYGON_OFFSET_FACTOR:
// TODO: params[0] = static_cast<GLint>(MG_State_T::commonState->polygonOffsetFactor);
break;
case GL_POLYGON_OFFSET_UNITS:
// TODO: params[0] = static_cast<GLint>(MG_State_T::commonState->polygonOffsetUnits);
break;
// Others...
default:
MG_Util::Debug::LogE("glGetIntegerv: Invalid enum %s (0x%X)", MG_Util::Debug::GLEnumToString(pname), pname);
MG_State::SetError(GL_INVALID_ENUM);
break;
}
}
}
@@ -1,17 +0,0 @@
//
// Created by BZLZHH on 2025/3/15.
//
#ifndef MOBILEGL_GL_GETTER_H
#define MOBILEGL_GL_GETTER_H
#include "../../../../Includes.h"
namespace MG_GL::GL {
const GLubyte* GetString(GLenum name);
const GLubyte* GetStringi(GLenum name, GLuint index);
GLenum GetError();
void GetIntegerv(GLenum pname, GLint *params);
}
#endif //MOBILEGL_GL_GETTER_H
@@ -1,298 +0,0 @@
//
// Created by BZLZHH on 2025/3/15.
//
#include "GL_Program.h"
namespace MG_GL::GL {
GLuint CreateShader(GLenum type) {
MG_Util::Debug::LogD("glCreateShader, type: %s", MG_Util::Debug::GLEnumToString(type));
GLuint shader;
GLenum result = MG_State::CreateShader(type, &shader);
if (result == GL_NO_ERROR) {
MG_Util::Debug::LogD("Created shader ID: %u", shader);
return shader;
}
MG_State::SetError(result);
MG_Util::Debug::LogE("Error creating shader: %s", MG_Util::Debug::GLEnumToString(result));
return 0;
}
GLuint CreateProgram() {
MG_Util::Debug::LogD("glCreateProgram");
GLuint program;
GLenum result = MG_State::CreateProgram(&program);
if (result == GL_NO_ERROR) {
MG_Util::Debug::LogD("Created program ID: %u", program);
return program;
}
MG_State::SetError(result);
MG_Util::Debug::LogE("Error creating program: %s", MG_Util::Debug::GLEnumToString(result));
return 0;
}
void DeleteShader(GLuint shader) {
MG_Util::Debug::LogD("glDeleteShader, shader: %u", shader);
GLenum result = MG_State::DeleteShader(shader);
if (result == GL_NO_ERROR) return;
MG_State::SetError(result);
MG_Util::Debug::LogE("Error deleting shader: %s", MG_Util::Debug::GLEnumToString(result));
}
void DeleteProgram(GLuint program) {
MG_Util::Debug::LogD("glDeleteProgram, program: %u", program);
GLenum result = MG_State::DeleteProgram(program);
if (result == GL_NO_ERROR) return;
MG_State::SetError(result);
MG_Util::Debug::LogE("Error deleting program: %s", MG_Util::Debug::GLEnumToString(result));
}
void AttachShader(GLuint program, GLuint shader) {
MG_Util::Debug::LogD("glAttachShader, program: %u, shader: %u", program, shader);
GLenum result = MG_State::LinkShaderToProgram(program, shader);
if (result == GL_NO_ERROR) return;
MG_State::SetError(result);
MG_Util::Debug::LogE("Error attaching shader: %s", MG_Util::Debug::GLEnumToString(result));
}
void ShaderSource(GLuint shader, GLsizei count, const GLchar *const*string, const GLint* length) {
MG_Util::Debug::LogD("glShaderSource, shader: %u, count: %d", shader, count);
GLenum result = MG_State::UploadShaderSource(shader, count, (const GLchar **)string, length);
if (result == GL_NO_ERROR) return;
MG_State::SetError(result);
MG_Util::Debug::LogE("Error setting shader source: %s", MG_Util::Debug::GLEnumToString(result));
}
void CompileShader(GLuint shader) {
MG_Util::Debug::LogD("glCompileShader, shader: %u", shader);
GLenum result = MG_State::BuildShaderStage(shader);
if (result == GL_NO_ERROR) return;
MG_State::SetError(result);
MG_Util::Debug::LogE("Error compiling shader: %s", MG_Util::Debug::GLEnumToString(result));
}
void LinkProgram(GLuint program) {
MG_Util::Debug::LogD("glLinkProgram, program: %u", program);
GLenum result = MG_State::FinalizeProgramPipeline(program);
if (result == GL_NO_ERROR) return;
MG_State::SetError(result);
MG_Util::Debug::LogE("Error linking program: %s", MG_Util::Debug::GLEnumToString(result));
}
void UseProgram(GLuint program) {
MG_Util::Debug::LogD("glUseProgram, program: %u", program);
GLenum result = MG_State::ActivateRenderProgram(program);
if (result == GL_NO_ERROR) return;
MG_State::SetError(result);
MG_Util::Debug::LogE("Error using program: %s", MG_Util::Debug::GLEnumToString(result));
}
void BindAttribLocation(GLuint program, GLuint index, const GLchar* name) {
MG_Util::Debug::LogD("glBindAttribLocation, program: %u, index: %u, name: %s", program, index, name);
GLenum result = MG_State::DefineProgramAttributeBinding(program, index, name);
if (result == GL_NO_ERROR) return;
MG_State::SetError(result);
MG_Util::Debug::LogE("Error binding attribute: %s", MG_Util::Debug::GLEnumToString(result));
}
GLint GetAttribLocation(GLuint program, const GLchar* name) {
MG_Util::Debug::LogD("glGetAttribLocation, program: %u, name: %s", program, name);
GLint location = MG_State::QueryProgramAttributeBinding(program, name);
if (location != -1) return location;
MG_State::SetError(GL_INVALID_OPERATION);
MG_Util::Debug::LogE("Attribute not found: %s", name);
return -1;
}
GLint GetUniformLocation(GLuint program, const GLchar* name) {
MG_Util::Debug::LogD("glGetUniformLocation, program: %u, name: %s", program, name);
GLint location = MG_State::QueryProgramUniformLocation(program, name);
if (location != -1) return location;
MG_State::SetError(GL_INVALID_OPERATION);
MG_Util::Debug::LogE("Uniform not found: %s", name);
return -1;
}
void GetProgramiv(GLuint program, GLenum pname, GLint* params) {
MG_Util::Debug::LogD("glGetProgramiv, program: %u, pname: %s",
program, MG_Util::Debug::GLEnumToString(pname));
GLenum result = MG_State::QueryProgramStateIntVector(program, pname, params);
if (result == GL_NO_ERROR) return;
MG_State::SetError(result);
MG_Util::Debug::LogE("Error getting program param: %s", MG_Util::Debug::GLEnumToString(result));
}
void GetShaderiv(GLuint shader, GLenum pname, GLint* params) {
MG_Util::Debug::LogD("glGetShaderiv, shader: %u, pname: %s",
shader, MG_Util::Debug::GLEnumToString(pname));
GLenum result = MG_State::QueryShaderStateIntVector(shader, pname, params);
if (result == GL_NO_ERROR) return;
MG_State::SetError(result);
MG_Util::Debug::LogE("Error getting shader param: %s", MG_Util::Debug::GLEnumToString(result));
}
void Uniform1f(GLint location, GLfloat v0) {
MG_Util::Debug::LogD("glUniform1f, location: %d, v0: %f", location, v0);
MG_State::UpdateProgramUniformFloat1(location, v0);
}
void Uniform2f(GLint location, GLfloat v0, GLfloat v1) {
MG_Util::Debug::LogD("glUniform2f, location: %d, v0: %f, v1: %f", location, v0, v1);
MG_State::UpdateProgramUniformFloat2(location, v0, v1);
}
void Uniform3f(GLint location, GLfloat v0, GLfloat v1, GLfloat v2) {
MG_Util::Debug::LogD("glUniform3f, location: %d, v0: %f, v1: %f, v2: %f", location, v0, v1, v2);
MG_State::UpdateProgramUniformFloat3(location, v0, v1, v2);
}
void Uniform4f(GLint location, GLfloat v0, GLfloat v1, GLfloat v2, GLfloat v3) {
MG_Util::Debug::LogD("glUniform4f, location: %d, v0: %f, v1: %f, v2: %f, v3: %f", location, v0, v1, v2, v3);
MG_State::UpdateProgramUniformFloat4(location, v0, v1, v2, v3);
}
void Uniform1fv(GLint location, GLsizei count, const GLfloat* value) {
MG_Util::Debug::LogD("glUniform1fv, location: %d, count: %d", location, count);
MG_State::UpdateProgramUniformFloatVector1(location, count, value);
}
void Uniform2fv(GLint location, GLsizei count, const GLfloat* value) {
MG_Util::Debug::LogD("glUniform2fv, location: %d, count: %d", location, count);
MG_State::UpdateProgramUniformFloatVector2(location, count, value);
}
void Uniform3fv(GLint location, GLsizei count, const GLfloat* value) {
MG_Util::Debug::LogD("glUniform3fv, location: %d, count: %d", location, count);
MG_State::UpdateProgramUniformFloatVector3(location, count, value);
}
void Uniform4fv(GLint location, GLsizei count, const GLfloat* value) {
MG_Util::Debug::LogD("glUniform4fv, location: %d, count: %d", location, count);
MG_State::UpdateProgramUniformFloatVector4(location, count, value);
}
void Uniform1i(GLint location, GLint v0) {
MG_Util::Debug::LogD("glUniform1i, location: %d, v0: %d", location, v0);
MG_State::UpdateProgramUniformInt1(location, v0);
}
void Uniform2i(GLint location, GLint v0, GLint v1) {
MG_Util::Debug::LogD("glUniform2i, location: %d, v0: %d, v1: %d", location, v0, v1);
MG_State::UpdateProgramUniformInt2(location, v0, v1);
}
void Uniform3i(GLint location, GLint v0, GLint v1, GLint v2) {
MG_Util::Debug::LogD("glUniform3i, location: %d, v0: %d, v1: %d, v2: %d", location, v0, v1, v2);
MG_State::UpdateProgramUniformInt3(location, v0, v1, v2);
}
void Uniform4i(GLint location, GLint v0, GLint v1, GLint v2, GLint v3) {
MG_Util::Debug::LogD("glUniform4i, location: %d, v0: %d, v1: %d, v2: %d, v3: %d", location, v0, v1, v2, v3);
MG_State::UpdateProgramUniformInt4(location, v0, v1, v2, v3);
}
void Uniform1iv(GLint location, GLsizei count, const GLint* value) {
MG_Util::Debug::LogD("glUniform1iv, location: %d, count: %d", location, count);
MG_State::UpdateProgramUniformIntVector1(location, count, value);
}
void Uniform2iv(GLint location, GLsizei count, const GLint* value) {
MG_Util::Debug::LogD("glUniform2iv, location: %d, count: %d", location, count);
MG_State::UpdateProgramUniformIntVector2(location, count, value);
}
void Uniform3iv(GLint location, GLsizei count, const GLint* value) {
MG_Util::Debug::LogD("glUniform3iv, location: %d, count: %d", location, count);
MG_State::UpdateProgramUniformIntVector3(location, count, value);
}
void Uniform4iv(GLint location, GLsizei count, const GLint* value) {
MG_Util::Debug::LogD("glUniform4iv, location: %d, count: %d", location, count);
MG_State::UpdateProgramUniformIntVector4(location, count, value);
}
void Uniform1ui(GLint location, GLuint v0) {
MG_Util::Debug::LogD("glUniform1ui, location: %d, v0: %u", location, v0);
MG_State::UpdateProgramUniformUInt1(location, v0);
}
void Uniform2ui(GLint location, GLuint v0, GLuint v1) {
MG_Util::Debug::LogD("glUniform2ui, location: %d, v0: %u, v1: %u", location, v0, v1);
MG_State::UpdateProgramUniformUInt2(location, v0, v1);
}
void Uniform3ui(GLint location, GLuint v0, GLuint v1, GLuint v2) {
MG_Util::Debug::LogD("glUniform3ui, location: %d, v0: %u, v1: %u, v2: %u", location, v0, v1, v2);
MG_State::UpdateProgramUniformUInt3(location, v0, v1, v2);
}
void Uniform4ui(GLint location, GLuint v0, GLuint v1, GLuint v2, GLuint v3) {
MG_Util::Debug::LogD("glUniform4ui, location: %d, v0: %u, v1: %u, v2: %u, v3: %u", location, v0, v1, v2, v3);
MG_State::UpdateProgramUniformUInt4(location, v0, v1, v2, v3);
}
void Uniform1uiv(GLint location, GLsizei count, const GLuint* value) {
MG_Util::Debug::LogD("glUniform1uiv, location: %d, count: %d", location, count);
MG_State::UpdateProgramUniformUIntVector1(location, count, value);
}
void Uniform2uiv(GLint location, GLsizei count, const GLuint* value) {
MG_Util::Debug::LogD("glUniform2uiv, location: %d, count: %d", location, count);
MG_State::UpdateProgramUniformUIntVector2(location, count, value);
}
void Uniform3uiv(GLint location, GLsizei count, const GLuint* value) {
MG_Util::Debug::LogD("glUniform3uiv, location: %d, count: %d", location, count);
MG_State::UpdateProgramUniformUIntVector3(location, count, value);
}
void Uniform4uiv(GLint location, GLsizei count, const GLuint* value) {
MG_Util::Debug::LogD("glUniform4uiv, location: %d, count: %d", location, count);
MG_State::UpdateProgramUniformUIntVector4(location, count, value);
}
void UniformMatrix2fv(GLint location, GLsizei count, GLboolean transpose, const GLfloat* value) {
MG_Util::Debug::LogD("glUniformMatrix2fv, location: %d, count: %d, transpose: %d", location, count, transpose);
MG_State::UpdateProgramUniformMatrix2x2Vector(location, count, transpose, value);
}
void UniformMatrix3fv(GLint location, GLsizei count, GLboolean transpose, const GLfloat* value) {
MG_Util::Debug::LogD("glUniformMatrix3fv, location: %d, count: %d, transpose: %d", location, count, transpose);
MG_State::UpdateProgramUniformMatrix3x3Vector(location, count, transpose, value);
}
void UniformMatrix4fv(GLint location, GLsizei count, GLboolean transpose, const GLfloat* value) {
MG_Util::Debug::LogD("glUniformMatrix4fv, location: %d, count: %d, transpose: %d", location, count, transpose);
MG_State::UpdateProgramUniformMatrix4x4Vector(location, count, transpose, value);
}
void UniformMatrix2x3fv(GLint location, GLsizei count, GLboolean transpose, const GLfloat* value) {
MG_Util::Debug::LogD("glUniformMatrix2x3fv, location: %d, count: %d, transpose: %d", location, count, transpose);
MG_State::UpdateProgramUniformMatrix2x3Vector(location, count, transpose, value);
}
void UniformMatrix2x4fv(GLint location, GLsizei count, GLboolean transpose, const GLfloat* value) {
MG_Util::Debug::LogD("glUniformMatrix2x4fv, location: %d, count: %d, transpose: %d", location, count, transpose);
MG_State::UpdateProgramUniformMatrix2x4Vector(location, count, transpose, value);
}
void UniformMatrix3x2fv(GLint location, GLsizei count, GLboolean transpose, const GLfloat* value) {
MG_Util::Debug::LogD("glUniformMatrix3x2fv, location: %d, count: %d, transpose: %d", location, count, transpose);
MG_State::UpdateProgramUniformMatrix3x2Vector(location, count, transpose, value);
}
void UniformMatrix3x4fv(GLint location, GLsizei count, GLboolean transpose, const GLfloat* value) {
MG_Util::Debug::LogD("glUniformMatrix3x4fv, location: %d, count: %d, transpose: %d", location, count, transpose);
MG_State::UpdateProgramUniformMatrix3x4Vector(location, count, transpose, value);
}
void UniformMatrix4x2fv(GLint location, GLsizei count, GLboolean transpose, const GLfloat* value) {
MG_Util::Debug::LogD("glUniformMatrix4x2fv, location: %d, count: %d, transpose: %d", location, count, transpose);
MG_State::UpdateProgramUniformMatrix4x2Vector(location, count, transpose, value);
}
void UniformMatrix4x3fv(GLint location, GLsizei count, GLboolean transpose, const GLfloat* value) {
MG_Util::Debug::LogD("glUniformMatrix4x3fv, location: %d, count: %d, transpose: %d", location, count, transpose);
MG_State::UpdateProgramUniformMatrix4x3Vector(location, count, transpose, value);
}
}
@@ -1,60 +0,0 @@
//
// Created by BZLZHH on 2025/3/15.
//
#ifndef MOBILEGL_GL_PROGRAM_H
#define MOBILEGL_GL_PROGRAM_H
#include "../../../../Includes.h"
namespace MG_GL::GL {
GLuint CreateShader(GLenum type);
GLuint CreateProgram();
void DeleteShader(GLuint shader);
void DeleteProgram(GLuint program);
void AttachShader(GLuint program, GLuint shader);
void ShaderSource(GLuint shader, GLsizei count, const GLchar *const*string, const GLint* length);
void CompileShader(GLuint shader);
void LinkProgram(GLuint program);
void UseProgram(GLuint program);
void BindAttribLocation(GLuint program, GLuint index, const GLchar* name);
GLint GetAttribLocation(GLuint program, const GLchar* name);
GLint GetUniformLocation(GLuint program, const GLchar* name);
void GetProgramiv(GLuint program, GLenum pname, GLint* params);
void GetShaderiv(GLuint shader, GLenum pname, GLint* params);
void Uniform1f(GLint location, GLfloat v0);
void Uniform2f(GLint location, GLfloat v0, GLfloat v1);
void Uniform3f(GLint location, GLfloat v0, GLfloat v1, GLfloat v2);
void Uniform4f(GLint location, GLfloat v0, GLfloat v1, GLfloat v2, GLfloat v3);
void Uniform1fv(GLint location, GLsizei count, const GLfloat* value);
void Uniform2fv(GLint location, GLsizei count, const GLfloat* value);
void Uniform3fv(GLint location, GLsizei count, const GLfloat* value);
void Uniform4fv(GLint location, GLsizei count, const GLfloat* value);
void Uniform1i(GLint location, GLint v0);
void Uniform2i(GLint location, GLint v0, GLint v1);
void Uniform3i(GLint location, GLint v0, GLint v1, GLint v2);
void Uniform4i(GLint location, GLint v0, GLint v1, GLint v2, GLint v3);
void Uniform1iv(GLint location, GLsizei count, const GLint* value);
void Uniform2iv(GLint location, GLsizei count, const GLint* value);
void Uniform3iv(GLint location, GLsizei count, const GLint* value);
void Uniform4iv(GLint location, GLsizei count, const GLint* value);
void Uniform1ui(GLint location, GLuint v0);
void Uniform2ui(GLint location, GLuint v0, GLuint v1);
void Uniform3ui(GLint location, GLuint v0, GLuint v1, GLuint v2);
void Uniform4ui(GLint location, GLuint v0, GLuint v1, GLuint v2, GLuint v3);
void Uniform1uiv(GLint location, GLsizei count, const GLuint* value);
void Uniform2uiv(GLint location, GLsizei count, const GLuint* value);
void Uniform3uiv(GLint location, GLsizei count, const GLuint* value);
void Uniform4uiv(GLint location, GLsizei count, const GLuint* value);
void UniformMatrix2fv(GLint location, GLsizei count, GLboolean transpose, const GLfloat* value);
void UniformMatrix3fv(GLint location, GLsizei count, GLboolean transpose, const GLfloat* value);
void UniformMatrix4fv(GLint location, GLsizei count, GLboolean transpose, const GLfloat* value);
void UniformMatrix2x3fv(GLint location, GLsizei count, GLboolean transpose, const GLfloat* value);
void UniformMatrix2x4fv(GLint location, GLsizei count, GLboolean transpose, const GLfloat* value);
void UniformMatrix3x2fv(GLint location, GLsizei count, GLboolean transpose, const GLfloat* value);
void UniformMatrix3x4fv(GLint location, GLsizei count, GLboolean transpose, const GLfloat* value);
void UniformMatrix4x2fv(GLint location, GLsizei count, GLboolean transpose, const GLfloat* value);
void UniformMatrix4x3fv(GLint location, GLsizei count, GLboolean transpose, const GLfloat* value);
}
#endif //MOBILEGL_GL_PROGRAM_H
@@ -1,93 +0,0 @@
//
// Created by BZLZHH on 2025/3/15.
//
#include "GL_Texture.h"
namespace MG_GL::GL {
void ActiveTexture(GLenum texture) {
MG_Util::Debug::LogD("glActiveTexture, texture: %d", texture);
GLenum result = MG_State::BindTextureUnit(texture);
if (result == GL_NO_ERROR)
return;
MG_State::SetError(result);
MG_Util::Debug::LogE("Error from MG State: %s", MG_Util::Debug::GLEnumToString(result));
}
void BindTexture(GLenum target, GLuint texture) {
MG_Util::Debug::LogD("glBindTexture, target: %d, texture: %d", target, texture);
GLenum result = MG_State::BindTexture(target, texture);
if (result == GL_NO_ERROR)
return;
MG_State::SetError(result);
MG_Util::Debug::LogE("Error from MG State: %s", MG_Util::Debug::GLEnumToString(result));
}
void DeleteTextures(GLsizei n, const GLuint* textures) {
MG_Util::Debug::LogD("glDeleteTextures, n: %d, textures: %p", n, textures);
GLenum result = MG_State::DeleteTextures(n, textures);
if (result == GL_NO_ERROR)
return;
MG_State::SetError(result);
MG_Util::Debug::LogE("Error from MG State: %s", MG_Util::Debug::GLEnumToString(result));
}
void GenTextures(GLsizei n, GLuint* textures) {
MG_Util::Debug::LogD("glGenTextures, n: %d, textures: %p", n, textures);
GLenum result = MG_State::CreateTextures(n, textures);
if (result == GL_NO_ERROR)
return;
MG_State::SetError(result);
MG_Util::Debug::LogE("Error from MG State: %s", MG_Util::Debug::GLEnumToString(result));
}
void TexImage2D(GLenum target, GLint level, GLint internalFormat, GLsizei width, GLsizei height, GLint border,
GLenum format, GLenum type, const void* data) {
MG_Util::Debug::LogD("glTexImage2D, target: %d, level: %d, internalFormat: %d, width: %d, height: %d, format: %d, type: %d, data: %p",
target, level, internalFormat, width, height, format, type, data);
GLenum result = MG_State::UploadTexture2D(target, level, internalFormat, width, height, border, format, type, data);
if (result == GL_NO_ERROR)
return;
MG_State::SetError(result);
MG_Util::Debug::LogE("Error from MG State: %s", MG_Util::Debug::GLEnumToString(result));
}
void TexParameterf(GLenum target, GLenum pname, GLfloat param) {
MG_Util::Debug::LogD("glTexParameterf, target: %d, pname: %d, param: %f", target, pname, param);
GLenum result = MG_State::SetTexturePropertyFloat(target, pname, param);
if (result == GL_NO_ERROR)
return;
MG_State::SetError(result);
MG_Util::Debug::LogE("Error from MG State: %s", MG_Util::Debug::GLEnumToString(result));
}
void TexParameteri(GLenum target, GLenum pname, GLint param) {
MG_Util::Debug::LogD("glTexParameteri, target: %d, pname: %d, param: %d", target, pname, param);
GLenum result = MG_State::SetTexturePropertyInt(target, pname, param);
if (result == GL_NO_ERROR)
return;
MG_State::SetError(result);
MG_Util::Debug::LogE("Error from MG State: %s", MG_Util::Debug::GLEnumToString(result));
}
void TexSubImage2D(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width,
GLsizei height, GLenum format, GLenum type, const void* pixels) {
MG_Util::Debug::LogD("glTexSubImage2D, target: %d, level: %d, xoffset: %d, yoffset: %d, width: %d, height: %d, format: %d, type: %d, pixels: %p",
target, level, xoffset, yoffset, width, height, format, type, pixels);
GLenum result = MG_State::UpdateTextureRegion2D(target, level, xoffset, yoffset, width, height, format, type, pixels);
if (result == GL_NO_ERROR)
return;
MG_State::SetError(result);
MG_Util::Debug::LogE("Error from MG State: %s", MG_Util::Debug::GLEnumToString(result));
}
void GetTexLevelParameteriv(GLenum target, GLint level, GLenum pname, GLint* params) {
MG_Util::Debug::LogD("glGetTexLevelParameteriv, target: %d, level: %d, pname: %d, params: %p",
target, level, pname, params);
GLenum result = MG_State::QueryTextureLevelPropertyIntVector(target, level, pname, params);
if (result == GL_NO_ERROR)
return;
MG_State::SetError(result);
MG_Util::Debug::LogE("Error from MG State: %s", MG_Util::Debug::GLEnumToString(result));
}
}
@@ -1,22 +0,0 @@
//
// Created by BZLZHH on 2025/3/15.
//
#ifndef MOBILEGL_GL_TEXTURE_H
#define MOBILEGL_GL_TEXTURE_H
#include "../../../../Includes.h"
namespace MG_GL::GL {
void ActiveTexture(GLenum texture);
void BindTexture(GLenum target, GLuint texture);
void DeleteTextures(GLsizei n, const GLuint* textures);
void GenTextures(GLsizei n, GLuint* textures);
void TexImage2D(GLenum target, GLint level, GLint internalFormat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, const void* data);
void TexParameterf(GLenum target, GLenum pname, GLfloat param);
void TexParameteri(GLenum target, GLenum pname, GLint param);
void TexSubImage2D(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, const void* pixels);
void GetTexLevelParameteriv(GLenum target, GLint level, GLenum pname, GLint* params);
}
#endif //MOBILEGL_GL_TEXTURE_H
@@ -1,53 +0,0 @@
//
// Created by BZLZHH on 2025/3/15.
//
#include "GL_VertexArray.h"
namespace MG_GL::GL {
void GenVertexArrays(GLsizei n, GLuint* arrays) {
MG_Util::Debug::LogD("glGenVertexArrays, n: %d, arrays: %p", n, arrays);
GLenum result = MG_State::GenVertexArraysNames(n, arrays);
if (result == GL_NO_ERROR) return;
MG_State::SetError(result);
MG_Util::Debug::LogE("Error from MG State: %s", MG_Util::Debug::GLEnumToString(result));
}
void BindVertexArray(GLuint array) {
MG_Util::Debug::LogD("glBindVertexArray, array: %u", array);
GLenum result = MG_State::BindVertexArray(array);
if (result == GL_NO_ERROR) return;
MG_State::SetError(result);
MG_Util::Debug::LogE("Error from MG State: %s", MG_Util::Debug::GLEnumToString(result));
}
void EnableVertexAttribArray(GLuint index) {
MG_Util::Debug::LogD("glEnableVertexAttribArray, index: %u", index);
GLenum result = MG_State::EnableVertexAttribArray(index);
if (result == GL_NO_ERROR) return;
MG_State::SetError(result);
MG_Util::Debug::LogE("Error from MG State: %s", MG_Util::Debug::GLEnumToString(result));
}
void VertexAttribPointer(GLuint index, GLint size, GLenum type,
GLboolean normalized, GLsizei stride, const void* pointer) {
MG_Util::Debug::LogD("glVertexAttribPointer, index: %u, size: %d, type: %s, norm: %d, stride: %d, ptr: %p",
index, size, MG_Util::Debug::GLEnumToString(type), normalized, stride, pointer);
GLenum result = MG_State::SetVertexAttributeLayout(index, size, type, normalized, stride, pointer);
if (result == GL_NO_ERROR) return;
MG_State::SetError(result);
MG_Util::Debug::LogE("Error from MG State: %s", MG_Util::Debug::GLEnumToString(result));
}
void VertexAttribIPointer(GLuint index, GLint size, GLenum type,
GLsizei stride, const void* pointer) {
MG_Util::Debug::LogD("glVertexAttribIPointer, index: %u, size: %d, type: %s, stride: %d, ptr: %p",
index, size, MG_Util::Debug::GLEnumToString(type), stride, pointer);
GLenum result = MG_State::SetVertexAttributeLayoutInt(index, size, type, stride, pointer);
if (result == GL_NO_ERROR) return;
MG_State::SetError(result);
MG_Util::Debug::LogE("Error from MG State: %s", MG_Util::Debug::GLEnumToString(result));
}
}
@@ -1,18 +0,0 @@
//
// Created by BZLZHH on 2025/3/15.
//
#ifndef MOBILEGL_GL_VERTEXARRAY_H
#define MOBILEGL_GL_VERTEXARRAY_H
#include "../../../../Includes.h"
namespace MG_GL::GL {
void GenVertexArrays(GLsizei n, GLuint* arrays);
void BindVertexArray(GLuint array);
void EnableVertexAttribArray(GLuint index);
void VertexAttribPointer(GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, const void* pointer);
void VertexAttribIPointer(GLuint index, GLint size, GLenum type, GLsizei stride, const void* pointer);
}
#endif //MOBILEGL_GL_VERTEXARRAY_H
@@ -1,13 +0,0 @@
//
// Created by Swung 0x48 on 2025/6/20.
//
#include "GLXFuncsDefinitions.h"
MG_EXPORT void* glXGetProcAddress(const char *name) {
return MG_GL::GLX::GetProcAddress(name);
}
MG_EXPORT void* glXGetProcAddressARB(const char *name) {
return MG_GL::GLX::GetProcAddressARB(name);
}
@@ -1,10 +0,0 @@
//
// Created by Swung 0x48 on 2025/6/20.
//
#ifndef MOBILEGL_GLX_FUNCS_DEFINITIONS_H
#define MOBILEGL_GLX_FUNCS_DEFINITIONS_H
#include "../../../../Includes.h"
#endif //MOBILEGL_GLX_FUNCS_DEFINITIONS_H
@@ -1,25 +0,0 @@
//
// Created by BZLZHH on 2025/3/15.
//
#include "LookUp.h"
#include "../../../../Includes.h"
namespace MG_GL::GLX {
void* GetProcAddress(const char *name) {
MG_Util::Debug::LogD("glXGetProcAddress(\"%s\")", name);
void* proc = dlsym(RTLD_DEFAULT, (const char*)name);
if (!proc) {
MG_Util::Debug::LogW("Failed to get function: %s", (const char*)name);
return nullptr;
}
return proc;
}
void* GetProcAddressARB(const char *name) {
return GetProcAddress(name);
}
}
@@ -1,12 +0,0 @@
//
// Created by BZLZHH on 2025/3/15.
//
#ifndef MOBILEGL_LOOKUP_H
#define MOBILEGL_LOOKUP_H
namespace MG_GL::GLX {
void* GetProcAddress(const char *name);
void* GetProcAddressARB(const char *name);
}
#endif //MOBILEGL_LOOKUP_H
-328
View File
@@ -1,328 +0,0 @@
//
// Created by BZLZHH on 2025/5/1.
//
// TODO: Add more gl error check for buffer state manager.
#include "BufferState.h"
GLenum BufferState::GenName(GLuint *buffer) {
MG_Util::Debug::LogD("MG_State: Buffer: GenName");
if (!buffer)
return GL_INVALID_VALUE;
GLuint id = 0;
if (freeId_.empty()) {
id = lastId_++;
} else {
id = freeId_.back();
freeId_.pop_back();
}
*buffer = id;
MG_Util::Debug::LogD("MG_State: Buffer: Gen new name %d", id);
return GL_NO_ERROR;
}
GLenum BufferState::GenNameN(GLsizei n, GLuint* buffers) {
MG_Util::Debug::LogD("MG_State: Buffer: GenNameN called with n=%d", n);
if (n < 0) return GL_INVALID_VALUE;
for (GLsizei i = 0; i < n; ++i) {
GLenum result = GenName(&buffers[i]);
if (result != GL_NO_ERROR) {
MG_Util::Debug::LogE("MG_State: Buffer: GenNameN failed with error 0x%x", result);
return result;
}
}
MG_Util::Debug::LogD("MG_State: Buffer: GenNameN created buffers successfully");
return GL_NO_ERROR;
}
GLenum BufferState::Create(GLuint buffer) {
MG_Util::Debug::LogD("MG_State: Buffer: Create called");
if (!buffer)
return GL_INVALID_VALUE;
if (ValidateAllocatedHandle(buffer))
return GL_INVALID_VALUE;
BufferObject& obj = buffers_[buffer];
MG_Util::Debug::LogD("MG_State: Buffer: Create created buffer %d", buffer);
obj.generated = true;
obj.dirty = true;
return GL_NO_ERROR;
}
GLenum BufferState::Bind(GLenum target, GLuint buffer) {
// We don't handle unallocated buffer names here, just plain bind
if (!IsValidTarget_(target)) return GL_INVALID_ENUM;
MG_Util::Debug::LogD("MG_State: Buffer: Bind called with target=%s, buffer=%u", MG_Util::Debug::GLEnumToString(target), buffer);
currentBindings_[target] = buffer;
MG_Util::Debug::LogD("MG_State: Buffer: Bind succeed bind buffer %u to target 0x%x", buffer, target);
return GL_NO_ERROR;
}
GLenum BufferState::CommitStorage(GLenum target, GLsizeiptr size, const void* data, GLenum usage) {
MG_Util::Debug::LogD("MG_State: Buffer: CommitStorage called on target 0x%x",target);
auto it = currentBindings_.find(target);
if (it == currentBindings_.end() || it->second == 0)
return GL_INVALID_OPERATION;
BufferObject& obj = buffers_[it->second];
MG_Util::Debug::LogD("MG_State: Buffer: CommitStorage get buffer object %u at target 0x%x",it->second,target);
obj.usage = usage;
obj.data.resize(size);
if (data) {
memcpy(obj.data.data(), data, size);
obj.dataValid = true;
}
obj.dirty = true;
MG_Util::Debug::LogD("MG_State: Buffer: CommitStorage buffer at target 0x%x committed storage, size = %zu, usage=0x%x", target, size, usage);
return GL_NO_ERROR;
}
GLenum BufferState::CommitStorageRegion(GLenum target, GLintptr offset, GLsizeiptr size, const void* data) {
MG_Util::Debug::LogD("MG_State: Buffer: BufferSubData called on target 0x%x, offset=%ld, size=%ld", target, offset, size);
if (!IsValidTarget_(target)) return GL_INVALID_ENUM;
if (offset < 0 || size < 0) return GL_INVALID_VALUE;
auto it = currentBindings_.find(target);
if (it == currentBindings_.end() || it->second == 0)
return GL_INVALID_OPERATION;
BufferObject& obj = buffers_[it->second];
MG_Util::Debug::LogD("MG_State: Buffer: BufferSubData get buffer object %u at target 0x%x", it->second, target);
if (static_cast<size_t>(offset + size) > obj.data.size()) return GL_INVALID_VALUE;
if (data) {
memcpy(obj.data.data() + offset, data, size);
obj.dirty = true;
}
return GL_NO_ERROR;
}
GLenum BufferState::AcquireBufferMemoryRange(GLenum target, GLintptr offset, GLsizeiptr length, GLbitfield access, void** mappedPointer) {
MG_Util::Debug::LogD("MG_State: Buffer: AcquireBufferMemoryRange called with target=0x%x, offset=%ld, length=%ld, access=0x%x", target, offset, length, access);
if (!IsValidTarget_(target)) {
MG_Util::Debug::LogE("MG_State: Buffer: AcquireBufferMemoryRange failed: invalid target 0x%x", target);
return GL_INVALID_ENUM;
}
if (offset < 0 || length <= 0) {
MG_Util::Debug::LogE("MG_State: Buffer: AcquireBufferMemoryRange failed: invalid offset %ld or length %ld", offset, length);
return GL_INVALID_VALUE;
}
auto it = currentBindings_.find(target);
if (it == currentBindings_.end() || it->second == 0) {
MG_Util::Debug::LogE("MG_State: Buffer: AcquireBufferMemoryRange failed: no buffer bound to target 0x%x", target);
return GL_INVALID_OPERATION;
}
BufferObject& obj = buffers_[it->second];
MG_Util::Debug::LogD("MG_State: Buffer: AcquireBufferMemoryRange operating on buffer %u", it->second);
if (obj.isMapped) {
MG_Util::Debug::LogE("MG_State: Buffer: AcquireBufferMemoryRange failed: buffer %u is already mapped", it->second);
return GL_INVALID_OPERATION;
}
const GLbitfield validFlags = GL_MAP_READ_BIT | GL_MAP_WRITE_BIT | GL_MAP_INVALIDATE_RANGE_BIT | GL_MAP_FLUSH_EXPLICIT_BIT | GL_MAP_UNSYNCHRONIZED_BIT | GL_MAP_INVALIDATE_BUFFER_BIT ;
if ((access & ~validFlags) != 0) {
MG_Util::Debug::LogE("MG_State: Buffer: AcquireBufferMemoryRange failed: invalid access flags 0x%x", access);
return GL_INVALID_VALUE;
}
if (static_cast<size_t>(offset + length) > obj.data.size()) {
MG_Util::Debug::LogE("MG_State: Buffer: AcquireBufferMemoryRange failed: requested range [%ld, %ld) exceeds buffer size %zu", offset, offset + length, obj.data.size());
return GL_INVALID_VALUE;
}
obj.isMapped = true;
obj.mapOffset = offset;
obj.mapLength = length;
obj.mapAccessFlags = access;
obj.dirty = true;
*mappedPointer = obj.data.data() + offset;
MG_Util::Debug::LogD("MG_State: Buffer: AcquireBufferMemoryRange succeeded for buffer %u. Mapped pointer: %p", it->second, *mappedPointer);
return GL_NO_ERROR;
}
GLenum BufferState::SyncBufferMemory(GLenum target, GLintptr offset, GLsizeiptr length) {
if (!IsValidTarget_(target)) return GL_INVALID_ENUM;
if (offset < 0 || length <= 0) return GL_INVALID_VALUE;
auto it = currentBindings_.find(target);
if (it == currentBindings_.end() || it->second == 0)
return GL_INVALID_OPERATION;
BufferObject& obj = buffers_[it->second];
if (!obj.isMapped || !(obj.mapAccessFlags & GL_MAP_FLUSH_EXPLICIT_BIT))
return GL_INVALID_OPERATION;
if (offset < obj.mapOffset || offset + length > obj.mapOffset + obj.mapLength)
return GL_INVALID_VALUE;
// TODO: Add support for flush range.
// Now only mark it as dirty.
obj.dirty = true;
return GL_NO_ERROR;
}
GLenum BufferState::CopyBufferRange(GLenum readTarget, GLenum writeTarget, GLintptr readOffset, GLintptr writeOffset, GLsizeiptr size) {
if (!IsValidTarget_(readTarget) || !IsValidTarget_(writeTarget))
return GL_INVALID_ENUM;
if (readOffset < 0 || writeOffset < 0 || size < 0)
return GL_INVALID_VALUE;
GLuint readBuffer = currentBindings_[readTarget];
GLuint writeBuffer = currentBindings_[writeTarget];
if (readBuffer == 0 || writeBuffer == 0 || readBuffer == writeBuffer)
return GL_INVALID_OPERATION;
BufferObject& src = buffers_[readBuffer];
BufferObject& dst = buffers_[writeBuffer];
if (static_cast<size_t>(readOffset + size) > src.data.size() ||
static_cast<size_t>(writeOffset + size) > dst.data.size())
return GL_INVALID_VALUE;
memcpy(dst.data.data() + writeOffset, src.data.data() + readOffset, size);
dst.dirty = true;
return GL_NO_ERROR;
}
GLenum BufferState::AcquireBufferMemory(GLenum target, GLenum access, void** mappedPointer) {
GLbitfield flags = 0;
switch (access) {
case GL_READ_ONLY: flags = GL_MAP_READ_BIT; break;
case GL_WRITE_ONLY: flags = GL_MAP_WRITE_BIT; break;
case GL_READ_WRITE: flags = GL_MAP_READ_BIT | GL_MAP_WRITE_BIT; break;
default:
flags = access;
}
return AcquireBufferMemoryRange(target, 0, buffers_[currentBindings_[target]].data.size(), flags, mappedPointer);
}
GLenum BufferState::ReleaseBufferMemory(GLenum target) {
if (!IsValidTarget_(target))
return GL_INVALID_ENUM;
auto it = currentBindings_.find(target);
if (it == currentBindings_.end() || it->second == 0)
return GL_INVALID_OPERATION;
BufferObject& obj = buffers_[it->second];
if (!obj.isMapped)
return GL_INVALID_OPERATION;
if ((obj.mapAccessFlags & GL_MAP_FLUSH_EXPLICIT_BIT) == 0) {
obj.dirty = true;
}
obj.isMapped = false;
obj.mapOffset = 0;
obj.mapLength = 0;
obj.mapAccessFlags = 0;
obj.accessMode = GL_READ_WRITE;
return GL_NO_ERROR;
}
bool BufferState::ValidateAllocatedHandle(GLuint buffer) {
bool isValid = buffers_.find(buffer) != buffers_.end();
MG_Util::Debug::LogD("MG_State: Buffer: ValidateAllocatedHandle called on buffer %u returns %d", buffer, isValid);
return isValid;
}
bool BufferState::ValidateGeneratedName(GLuint buffer) {
bool inFreeList = std::find(freeId_.begin(), freeId_.end(), buffer) != freeId_.end();
bool lessThanLast = buffer < lastId_; // lastId_ is not generated yet
MG_Util::Debug::LogD("MG_State: Buffer: ValidateGeneratedName called on buffer %u returns %d", buffer, lessThanLast && !inFreeList);
return lessThanLast && !inFreeList;
}
void BufferState::Delete(GLuint buffer) {
buffers_.erase(buffer);
if (ValidateGeneratedName(buffer))
// TODO: Prevent the object that uses a freeId from conflicting with legacy object in the backend.
//freeId_.emplace_back(buffer);
for (auto& [target, id] : currentBindings_) {
if (id == buffer) id = 0;
}
MG_Util::Debug::LogD("MG_State: Buffer: Delete buffer %u", buffer);
}
GLenum BufferState::DeleteN(GLsizei n, const GLuint* buffers) {
MG_Util::Debug::LogD("MG_State: Buffer: DeleteN called with n=%d", n);
if (n < 0) return GL_INVALID_VALUE;
for (GLsizei i = 0; i < n; ++i) {
Delete(buffers[i]);
}
MG_Util::Debug::LogD("MG_State: Buffer: DeleteN deleted buffers successfully");
return GL_NO_ERROR;
}
bool BufferState::IsValidTarget_(GLenum target) {
MG_Util::Debug::LogD("MG_State: Buffer: IsValidTarget_ called with target=0x%x,result=%d", target, !(MG_Constants::Buffer::VALID_TARGETS.find(target) == MG_Constants::Buffer::VALID_TARGETS.end()));
return !(MG_Constants::Buffer::VALID_TARGETS.find(target) == MG_Constants::Buffer::VALID_TARGETS.end());
}
GLenum BufferState::QueryPropertyIntVector(GLenum target, GLenum pname, GLint* params) const {
MG_Util::Debug::LogD("MG_State: Buffer: QueryPropertyIntVector called at target 0x%x,param name = 0x%x",target,pname);
static const std::set<GLenum> validTargets = {
GL_ARRAY_BUFFER, GL_ELEMENT_ARRAY_BUFFER,
GL_PIXEL_PACK_BUFFER, GL_PIXEL_UNPACK_BUFFER
};
if (validTargets.find(target) == validTargets.end()) {
return GL_INVALID_ENUM;
}
if (MG_Constants::Buffer::VALID_PARAM_NAMES.find(pname) == MG_Constants::Buffer::VALID_PARAM_NAMES.end()) {
return GL_INVALID_ENUM;
}
auto bindingIt = currentBindings_.find(target);
if (bindingIt == currentBindings_.end() || bindingIt->second == 0) {
return GL_INVALID_OPERATION;
}
GLuint bufferId = bindingIt->second;
auto bufferIt = buffers_.find(bufferId);
if (bufferIt == buffers_.end()) {
return GL_INVALID_OPERATION;
}
const BufferObject& buffer = bufferIt->second;
switch (pname) {
case GL_BUFFER_ACCESS:
*params = static_cast<GLint>(buffer.accessMode);
break;
case GL_BUFFER_MAPPED:
*params = buffer.isMapped ? GL_TRUE : GL_FALSE;
break;
case GL_BUFFER_SIZE:
*params = static_cast<GLint>(buffer.data.size());
break;
case GL_BUFFER_USAGE:
*params = static_cast<GLint>(buffer.usage);
break;
MG_Util::Debug::LogD("MG_State: Buffer: QueryPropertyIntVector Query info about buffer %u succeed", target);
default:
return GL_INVALID_ENUM;
}
return GL_NO_ERROR;
}
GLuint BufferState::GetCurrentBinding(GLenum target) const {
auto it = currentBindings_.find(target);
if (it != currentBindings_.end()) {
return it->second;
}
return 0;
}
-58
View File
@@ -1,58 +0,0 @@
//
// Created by BZLZHH on 2025/5/1.
//
#ifndef MOBILEGL_BUFFERSTATE_H
#define MOBILEGL_BUFFERSTATE_H
#define MOBILEGL_GLSTATE_H
#include "../../../Includes.h"
class BufferState {
template <typename K, typename V>
using unordered_map = ankerl::unordered_dense::map<K, V>;
public:
struct BufferObject {
GLenum usage = GL_STATIC_DRAW;
std::vector<GLubyte> data;
bool dataValid = false;
bool dirty = false; // TODO: encapsulate this with an public API to RHI
bool isMapped = false;
bool generated = false;
GLenum accessMode = GL_READ_WRITE;
GLintptr mapOffset = 0;
GLsizeiptr mapLength = 0;
GLbitfield mapAccessFlags = 0;
};
// Return: the validity of the operation, according to OpenGL 3 standard
GLenum GenName(GLuint* buffer);
GLenum GenNameN(GLsizei n, GLuint* buffers);
GLenum Create(GLuint buffer);
GLenum Bind(GLenum target, GLuint buffer);
GLenum CommitStorage(GLenum target, GLsizeiptr size, const void* data, GLenum usage);
GLenum CommitStorageRegion(GLenum target, GLintptr offset, GLsizeiptr size, const void* data);
GLenum AcquireBufferMemoryRange(GLenum target, GLintptr offset, GLsizeiptr length, GLbitfield access, void** mappedPointer);
GLenum SyncBufferMemory(GLenum target, GLintptr offset, GLsizeiptr length);
GLenum CopyBufferRange(GLenum readTarget, GLenum writeTarget, GLintptr readOffset, GLintptr writeOffset, GLsizeiptr size);
GLenum AcquireBufferMemory(GLenum target, GLenum access, void** mappedPointer);
GLenum ReleaseBufferMemory(GLenum target);
GLenum QueryPropertyIntVector(GLenum target, GLenum pname, GLint* params) const;
GLenum DeleteN(GLsizei n, const GLuint* buffers);
bool ValidateAllocatedHandle(GLuint buffer);
bool ValidateGeneratedName(GLuint buffer);
void Delete(GLuint buffer);
GLuint GetCurrentBinding(GLenum target) const;
unordered_map<GLenum, GLuint> currentBindings_;
unordered_map<GLuint, BufferObject> buffers_;
private:
std::vector<GLuint> freeId_;
GLuint lastId_ = 1;
static bool IsValidTarget_(GLenum target);
};
#endif //MOBILEGL_BUFFERSTATE_H
-158
View File
@@ -1,158 +0,0 @@
//
// Created by BZLZHH on 2025/4/30.
//
#include "CommonState.h"
CommonState::CommonState() {
pixelStoreParams[GL_PACK_ALIGNMENT] = 4;
pixelStoreParams[GL_UNPACK_ALIGNMENT] = 4;
}
GLenum CommonState::SetPixelStoreInt(GLenum pname, GLint param) {
if (MG_Constants::PixelStore::VALID_PARAM_NAMES.find(pname) == MG_Constants::PixelStore::VALID_PARAM_NAMES.end()) {
return GL_INVALID_ENUM;
}
switch (pname) {
case GL_PACK_SWAP_BYTES:
case GL_PACK_LSB_FIRST:
case GL_UNPACK_SWAP_BYTES:
case GL_UNPACK_LSB_FIRST:
break;
case GL_PACK_ROW_LENGTH:
case GL_PACK_IMAGE_HEIGHT:
case GL_PACK_SKIP_ROWS:
case GL_PACK_SKIP_PIXELS:
case GL_PACK_SKIP_IMAGES:
case GL_UNPACK_ROW_LENGTH:
case GL_UNPACK_IMAGE_HEIGHT:
case GL_UNPACK_SKIP_ROWS:
case GL_UNPACK_SKIP_PIXELS:
case GL_UNPACK_SKIP_IMAGES:
if (param < 0) {
return GL_INVALID_VALUE;
}
break;
case GL_PACK_ALIGNMENT:
case GL_UNPACK_ALIGNMENT:
if (param != 1 && param != 2 && param != 4 && param != 8) {
return GL_INVALID_VALUE;
}
break;
default:
return GL_INVALID_ENUM;
}
pixelStoreParams[pname] = param;
return GL_NO_ERROR;
}
GLint CommonState::QueryPixelStoreInt(GLenum pname) {
auto it = pixelStoreParams.find(pname);
if (it != pixelStoreParams.end()) {
return it->second;
}
auto defaultIt = MG_Constants::PixelStore::DEFAULT_VALUES_MAP.find(pname);
return (defaultIt != MG_Constants::PixelStore::DEFAULT_VALUES_MAP.end()) ? defaultIt->second : 0;
}
GLenum CommonState::Enable(GLenum cap) {
if (MG_Constants::CommonState::VALID_CAPS.find(cap) == MG_Constants::CommonState::VALID_CAPS.end()) {
return GL_INVALID_ENUM;
}
capabilities[cap] = true;
return GL_NO_ERROR;
}
GLenum CommonState::Disable(GLenum cap) {
if (MG_Constants::CommonState::VALID_CAPS.find(cap) == MG_Constants::CommonState::VALID_CAPS.end()) {
return GL_INVALID_ENUM;
}
capabilities[cap] = false;
return GL_NO_ERROR;
}
GLenum CommonState::BlendFunc(GLenum sfactor, GLenum dfactor) {
if (MG_Constants::Blend::VALID_FACTORS.find(sfactor) == MG_Constants::Blend::VALID_FACTORS.end() ||
MG_Constants::Blend::VALID_FACTORS.find(dfactor) == MG_Constants::Blend::VALID_FACTORS.end()) {
return GL_INVALID_ENUM;
}
blendSrcRGB = blendSrcAlpha = sfactor;
blendDstRGB = blendDstAlpha = dfactor;
return GL_NO_ERROR;
}
GLenum CommonState::BlendFuncSeparate(GLenum srcRGB, GLenum dstRGB,
GLenum srcAlpha, GLenum dstAlpha) {
if (MG_Constants::Blend::VALID_FACTORS.find(srcRGB) == MG_Constants::Blend::VALID_FACTORS.end() ||
MG_Constants::Blend::VALID_FACTORS.find(dstRGB) == MG_Constants::Blend::VALID_FACTORS.end() ||
MG_Constants::Blend::VALID_FACTORS.find(srcAlpha) == MG_Constants::Blend::VALID_FACTORS.end() ||
MG_Constants::Blend::VALID_FACTORS.find(dstAlpha) == MG_Constants::Blend::VALID_FACTORS.end()) {
return GL_INVALID_ENUM;
}
blendSrcRGB = srcRGB;
blendDstRGB = dstRGB;
blendSrcAlpha = srcAlpha;
blendDstAlpha = dstAlpha;
return GL_NO_ERROR;
}
GLenum CommonState::Clear(GLbitfield mask) {
const GLbitfield validBits = GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT;
if ((mask & ~validBits) != 0) {
return GL_INVALID_VALUE;
}
clearMask = mask;
return GL_NO_ERROR;
}
GLenum CommonState::ClearColor(GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha) {
clearColor[0] = red;
clearColor[1] = green;
clearColor[2] = blue;
clearColor[3] = alpha;
return GL_NO_ERROR;
}
GLenum CommonState::ClearDepth(GLfloat depth) {
clearDepth = depth;
return GL_NO_ERROR;
}
GLenum CommonState::ColorMask(GLboolean red, GLboolean green, GLboolean blue, GLboolean alpha) {
colorMask[0] = red;
colorMask[1] = green;
colorMask[2] = blue;
colorMask[3] = alpha;
return GL_NO_ERROR;
}
GLenum CommonState::DepthFunc(GLenum func) {
if (MG_Constants::Depth::VALID_FUNCS.find(func) == MG_Constants::Depth::VALID_FUNCS.end()) {
return GL_INVALID_ENUM;
}
depthFunc = func;
return GL_NO_ERROR;
}
GLenum CommonState::DepthMask(GLboolean flag) {
depthMask = flag;
return GL_NO_ERROR;
}
GLenum CommonState::Viewport(GLint x, GLint y, GLsizei width, GLsizei height) {
if (width < 0 || height < 0) {
return GL_INVALID_VALUE;
}
viewport[0] = x;
viewport[1] = y;
viewport[2] = width;
viewport[3] = height;
return GL_NO_ERROR;
}
-65
View File
@@ -1,65 +0,0 @@
//
// Created by BZLZHH on 2025/4/30.
//
#ifndef MOBILEGL_COMMONSTATE_H
#define MOBILEGL_COMMONSTATE_H
#define MOBILEGL_GLSTATE_H
#include "../../../Includes.h"
class CommonState {
template <typename K, typename V>
using unordered_map = ankerl::unordered_dense::map<K, V>;
public:
// Viewport
GLint viewport[4] = {0, 0, 0, 0};
// Color mask
GLboolean colorMask[4] = {GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE};
// Pixel storage parameters
unordered_map<GLenum, GLint> pixelStoreParams;
// Blend state
GLenum blendSrcRGB = GL_ONE;
GLenum blendDstRGB = GL_ZERO;
GLenum blendSrcAlpha = GL_ONE;
GLenum blendDstAlpha = GL_ZERO;
// Clear state
GLfloat clearColor[4] = {0.0f, 0.0f, 0.0f, 0.0f};
GLfloat clearDepth = 1.0f;
GLenum clearMask;
// Depth state
GLenum depthFunc = GL_LESS;
GLboolean depthMask = GL_TRUE;
// Capability enables
unordered_map<GLenum, bool> capabilities;
CommonState();
// Return: the validity of the operation, according to OpenGL 3 standard
GLenum SetPixelStoreInt(GLenum pname, GLint param);
GLenum Enable(GLenum cap);
GLenum Disable(GLenum cap);
GLenum BlendFunc(GLenum sfactor, GLenum dfactor);
GLenum BlendFuncSeparate(GLenum srcRGB, GLenum dstRGB,
GLenum srcAlpha, GLenum dstAlpha);
GLenum Clear(GLbitfield mask);
GLenum ClearColor(GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha);
GLenum ClearDepth(GLfloat depth);
GLenum ColorMask(GLboolean red, GLboolean green,
GLboolean blue, GLboolean alpha);
GLenum DepthFunc(GLenum func);
GLenum DepthMask(GLboolean flag);
GLenum Viewport(GLint x, GLint y, GLsizei width, GLsizei height);
GLint QueryPixelStoreInt(GLenum pname);
};
#endif //MOBILEGL_COMMONSTATE_H
-407
View File
@@ -1,407 +0,0 @@
//
// Created by BZLZHH on 2025/4/4.
//
#include "GLState.h"
std::queue<GLenum> MG_State_T::glErrorQueue;
TextureState* MG_State_T::textureState = nullptr;
CommonState* MG_State_T::commonState = nullptr;
BufferState* MG_State_T::bufferState = nullptr;
VertexArrayState* MG_State_T::vertexArrayState = nullptr;
ProgramState* MG_State_T::programState = nullptr;
FramebufferState* MG_State_T::framebufferState = nullptr;
namespace MG_State {
void Init() {
MG_State_T::textureState = new TextureState();
MG_State_T::commonState = new CommonState();
MG_State_T::bufferState = new BufferState();
MG_State_T::vertexArrayState = new VertexArrayState();
MG_State_T::programState = new ProgramState();
MG_State_T::framebufferState = new FramebufferState();
}
void Destroy() {
delete MG_State_T::textureState;
delete MG_State_T::commonState;
delete MG_State_T::bufferState;
delete MG_State_T::vertexArrayState;
delete MG_State_T::programState;
delete MG_State_T::framebufferState;
}
void SetError(GLenum error) {
if (error == GL_NO_ERROR) {
return;
}
MG_State_T::glErrorQueue.push(error);
}
GLenum GetError() {
if (MG_State_T::glErrorQueue.empty()) {
return GL_NO_ERROR;
}
GLenum error = MG_State_T::glErrorQueue.front();
MG_State_T::glErrorQueue.pop();
return error;
}
// TODO: Take these functions apart into multiple files.
// Texture
GLenum BindTextureUnit(GLenum textureUnit) {
return MG_State_T::textureState->BindUnit(textureUnit);
}
GLenum CreateTexture(GLuint* texture) {
return MG_State_T::textureState->Create(texture);
}
GLenum CreateTextures(GLsizei n, GLuint* textures) {
return MG_State_T::textureState->CreateN(n, textures);
}
GLenum BindTexture(GLenum target, GLuint texture) {
return MG_State_T::textureState->Bind(target, texture);
}
GLenum UploadTexture2D(GLenum target, GLint level, GLint internalFormat,
GLsizei width, GLsizei height, GLint border, GLenum format,
GLenum type, const void* data) {
return MG_State_T::textureState->Upload2D(target, level, internalFormat, width, height, border, format, type, data);
}
GLenum UpdateTextureRegion2D(GLenum target, GLint level, GLint xoffset,
GLint yoffset, GLsizei width, GLsizei height, GLenum format,
GLenum type, const GLvoid* data) {
return MG_State_T::textureState->UpdateRegion2D(target, level, xoffset, yoffset, width, height, format, type, data);
}
GLenum SetTexturePropertyInt(GLenum target, GLenum pname, GLint param) {
return MG_State_T::textureState->SetTexturePropertyInt(target, pname, param);
}
GLenum SetTexturePropertyFloat(GLenum target, GLenum pname, GLfloat param) {
return MG_State_T::textureState->SetTexturePropertyFloat(target, pname, param);
}
GLenum DeleteTexture(GLuint texture) {
return MG_State_T::textureState->Delete(texture);
}
GLenum DeleteTextures(GLsizei n, const GLuint* textures) {
return MG_State_T::textureState->DeleteN(n, textures);
}
GLenum QueryTextureLevelPropertyIntVector(GLenum target, GLint level, GLenum pname, GLint* params) {
return MG_State_T::textureState->QueryLevelPropertyIntVector(target, level, pname, params);
}
// Common
GLenum SetPixelStoreInt(GLenum pname, GLint param) {
return MG_State_T::commonState->SetPixelStoreInt(pname, param);
}
GLint QueryPixelStoreInt(GLenum pname) {
return MG_State_T::commonState->QueryPixelStoreInt(pname);
}
GLenum glEnable(GLenum cap) {
return MG_State_T::commonState->Enable(cap);
}
GLenum glDisable(GLenum cap) {
return MG_State_T::commonState->Disable(cap);
}
GLenum glBlendFunc(GLenum sfactor, GLenum dfactor) {
return MG_State_T::commonState->BlendFunc(sfactor, dfactor);
}
GLenum glBlendFuncSeparate(GLenum srcRGB, GLenum dstRGB, GLenum srcAlpha, GLenum dstAlpha) {
return MG_State_T::commonState->BlendFuncSeparate(srcRGB, dstRGB, srcAlpha, dstAlpha);
}
GLenum glClear(GLbitfield mask) {
return MG_State_T::commonState->Clear(mask);
}
GLenum glClearColor(GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha) {
return MG_State_T::commonState->ClearColor(red, green, blue, alpha);
}
GLenum glClearDepth(GLdouble depth) {
return MG_State_T::commonState->ClearDepth(static_cast<GLfloat>(depth));
}
GLenum glColorMask(GLboolean red, GLboolean green, GLboolean blue, GLboolean alpha) {
return MG_State_T::commonState->ColorMask(red, green, blue, alpha);
}
GLenum glDepthFunc(GLenum func) {
return MG_State_T::commonState->DepthFunc(func);
}
GLenum glDepthMask(GLboolean flag) {
return MG_State_T::commonState->DepthMask(flag);
}
GLenum glViewport(GLint x, GLint y, GLsizei width, GLsizei height) {
return MG_State_T::commonState->Viewport(x, y, width, height);
}
// Buffer
GLenum AcquireBufferMemory(GLenum target, GLenum access, void** mappedPtr) {
return MG_State_T::bufferState->AcquireBufferMemory(target, access, mappedPtr);
}
GLenum AcquireBufferMemoryRange(GLenum target, GLintptr offset, GLsizeiptr length, GLbitfield access, void** mappedPointer) {
return MG_State_T::bufferState->AcquireBufferMemoryRange(target, offset, length, access, mappedPointer);
}
GLenum SyncBufferMemory(GLenum target, GLintptr offset, GLsizeiptr length) {
return MG_State_T::bufferState->SyncBufferMemory(target, offset, length);
}
GLenum CopyBufferRange(GLenum readTarget, GLenum writeTarget, GLintptr readOffset, GLintptr writeOffset, GLsizeiptr size) {
return MG_State_T::bufferState->CopyBufferRange(readTarget, writeTarget, readOffset,
writeOffset, size);
}
GLenum ReleaseBufferMemory(GLenum target) {
return MG_State_T::bufferState->ReleaseBufferMemory(target);
}
GLenum CreateBuffer(GLuint buffer) {
return MG_State_T::bufferState->Create(buffer);
}
GLenum GenBufferNames(GLsizei n, GLuint* buffers) {
return MG_State_T::bufferState->GenNameN(n, buffers);
}
GLenum BindBuffer(GLenum target, GLuint buffer) {
if (target == GL_ELEMENT_ARRAY_BUFFER) {
auto* vao = MG_State_T::vertexArrayState->GetCurrentVAO();
if (!vao) return GL_INVALID_OPERATION;
vao->elementBuffer = (GLuint)buffer;
vao->eboDirty = true;
}
return MG_State_T::bufferState->Bind(target, buffer);
}
GLenum CommitBufferStorage(GLenum target, GLsizeiptr size, const void* data, GLenum usage) {
return MG_State_T::bufferState->CommitStorage(target, size, data, usage);
}
GLenum CommitBufferStorageRegion(GLenum target, GLintptr offset, GLsizeiptr size, const void* data) {
return MG_State_T::bufferState->CommitStorageRegion(target, offset, size, data);
}
bool ValidateAllocatedBufferHandle(GLuint buffer) {
return MG_State_T::bufferState->ValidateAllocatedHandle(buffer);
}
bool ValidateGeneratedName(GLuint buffer) {
return MG_State_T::bufferState->ValidateGeneratedName(buffer);
}
void DeleteBuffer(GLuint buffer) {
return MG_State_T::bufferState->Delete(buffer);
}
GLenum DeleteBuffers(GLsizei n, const GLuint* buffers) {
return MG_State_T::bufferState->DeleteN(n, buffers);
}
GLenum QueryBufferPropertyIntVector(GLenum target, GLenum pname, GLint* params) {
return MG_State_T::bufferState->QueryPropertyIntVector(target, pname, params);
}
// VertexArray
GLenum BindVertexArray(GLuint array) {
return MG_State_T::vertexArrayState->Bind(array);
}
GLenum CreateVertexArray(GLuint* array) {
return MG_State_T::vertexArrayState->Create(array);
}
GLenum CreateVertexArrays(GLsizei n, GLuint* arrays) {
return MG_State_T::vertexArrayState->CreateN(n, arrays);
}
GLenum GenVertexArraysNames(GLsizei n, GLuint* arrays) {
return MG_State_T::vertexArrayState->GenNameN(n, arrays);
}
GLenum EnableVertexAttribArray(GLuint index) {
return MG_State_T::vertexArrayState->EnableAttrib(index);
}
GLenum DisableVertexAttribArray(GLuint index) {
return MG_State_T::vertexArrayState->DisableAttrib(index);
}
GLenum SetVertexAttributeLayout(GLuint index, GLint size, GLenum type,
GLboolean normalized, GLsizei stride,
const void* pointer) {
GLuint currentBuffer = MG_State_T::bufferState->GetCurrentBinding(GL_ARRAY_BUFFER);
return MG_State_T::vertexArrayState->SetAttribPointer(
index, size, type, normalized, stride, pointer, false, currentBuffer
);
}
GLenum SetVertexAttributeLayoutInt(GLuint index, GLint size, GLenum type,
GLsizei stride, const void* pointer) {
GLuint currentBuffer = MG_State_T::bufferState->GetCurrentBinding(GL_ARRAY_BUFFER);
return MG_State_T::vertexArrayState->SetAttribPointer(
index, size, type, GL_FALSE, stride, pointer, true, currentBuffer
);
}
// Program
GLenum CreateShader(GLenum type, GLuint* shader) {
return MG_State_T::programState->CreateShader(type, shader);
}
GLenum CreateProgram(GLuint* program) {
return MG_State_T::programState->CreateProgram(program);
}
GLenum DeleteShader(GLuint shader) {
return MG_State_T::programState->DeleteShader(shader);
}
GLenum DeleteProgram(GLuint program) {
return MG_State_T::programState->DeleteProgram(program);
}
GLenum LinkShaderToProgram(GLuint program, GLuint shader) {
return MG_State_T::programState->LinkShaderToProgram(program, shader);
}
GLenum UploadShaderSource(GLuint shader, GLsizei count, const GLchar** string, const GLint* length) {
return MG_State_T::programState->UploadShaderSource(shader, count, string, length);
}
GLenum BuildShaderStage(GLuint shader) {
return MG_State_T::programState->BuildShaderStage(shader);
}
GLenum FinalizeProgramPipeline(GLuint program) {
return MG_State_T::programState->FinalizeProgramPipeline(program);
}
GLenum ActivateRenderProgram(GLuint program) {
return MG_State_T::programState->ActivateRenderProgram(program);
}
GLenum DefineProgramAttributeBinding(GLuint program, GLuint index, const GLchar* name) {
return MG_State_T::programState->DefineProgramAttributeBinding(program, index, name);
}
GLint QueryProgramAttributeBinding(GLuint program, const GLchar* name) {
return MG_State_T::programState->QueryProgramAttributeBinding(program, name);
}
GLint QueryProgramUniformLocation(GLuint program, const GLchar* name) {
return MG_State_T::programState->QueryProgramUniformLocation(program, name);
}
GLenum QueryProgramStateIntVector(GLuint program, GLenum pname, GLint* params) {
return MG_State_T::programState->QueryProgramStateIntVector(program, pname, params);
}
GLenum QueryShaderStateIntVector(GLuint shader, GLenum pname, GLint* params) {
return MG_State_T::programState->QueryShaderStateIntVector(shader, pname, params);
}
#define IMPLEMENT_UNIFORM_FUNCTIONS(type, suffix, vecType) \
void UpdateProgramUniform##suffix##1(GLint location, type v0) { \
MG_State_T::programState->UpdateUniform##suffix##1(location, v0); \
} \
void UpdateProgramUniform##suffix##2(GLint location, type v0, type v1) { \
MG_State_T::programState->UpdateUniform##suffix##2(location, v0, v1); \
} \
void UpdateProgramUniform##suffix##3(GLint location, type v0, type v1, type v2) { \
MG_State_T::programState->UpdateUniform##suffix##3(location, v0, v1, v2); \
} \
void UpdateProgramUniform##suffix##4(GLint location, type v0, type v1, type v2, type v3) { \
MG_State_T::programState->UpdateUniform##suffix##4(location, v0, v1, v2, v3); \
} \
void UpdateProgramUniform##suffix##Vector1(GLint location, GLsizei count, const type* value) { \
MG_State_T::programState->UpdateUniform##suffix##Vector1(location, count,value); \
} \
void UpdateProgramUniform##suffix##Vector2(GLint location, GLsizei count, const type* value) { \
MG_State_T::programState->UpdateUniform##suffix##Vector2(location, count, value); \
} \
void UpdateProgramUniform##suffix##Vector3(GLint location, GLsizei count, const type* value) { \
MG_State_T::programState->UpdateUniform##suffix##Vector3(location, count, value); \
} \
void UpdateProgramUniform##suffix##Vector4(GLint location, GLsizei count, const type* value) { \
MG_State_T::programState->UpdateUniform##suffix##Vector4(location, count, value); \
}
IMPLEMENT_UNIFORM_FUNCTIONS(GLfloat, Float, GL_FLOAT_VEC4)
IMPLEMENT_UNIFORM_FUNCTIONS(GLint, Int, GL_INT_VEC4)
IMPLEMENT_UNIFORM_FUNCTIONS(GLuint, UInt, GL_UNSIGNED_INT_VEC4)
IMPLEMENT_UNIFORM_FUNCTIONS(GLboolean, Bool, GL_BOOL_VEC4)
#undef IMPLEMENT_UNIFORM_FUNCTIONS
#define IMPLEMENT_MATRIX_FUNCTIONS(suffix, matrixType) \
void UpdateProgramUniformMatrix##suffix##Vector(GLint location, GLsizei count, GLboolean transpose, const GLfloat* value) { \
MG_State_T::programState->UpdateUniformMatrix##suffix##Vector(location, count, transpose, value); \
}
IMPLEMENT_MATRIX_FUNCTIONS(2x2, GL_FLOAT_MAT2)
IMPLEMENT_MATRIX_FUNCTIONS(3x3, GL_FLOAT_MAT3)
IMPLEMENT_MATRIX_FUNCTIONS(4x4, GL_FLOAT_MAT4)
IMPLEMENT_MATRIX_FUNCTIONS(2x3, GL_FLOAT_MAT2x3)
IMPLEMENT_MATRIX_FUNCTIONS(2x4, GL_FLOAT_MAT2x4)
IMPLEMENT_MATRIX_FUNCTIONS(3x2, GL_FLOAT_MAT3x2)
IMPLEMENT_MATRIX_FUNCTIONS(3x4, GL_FLOAT_MAT3x4)
IMPLEMENT_MATRIX_FUNCTIONS(4x2, GL_FLOAT_MAT4x2)
IMPLEMENT_MATRIX_FUNCTIONS(4x3, GL_FLOAT_MAT4x3)
#undef IMPLEMENT_MATRIX_FUNCTIONS
GLuint GetCurrentProgram() {
return MG_State_T::programState->GetCurrentProgram();
}
bool SetProgramStatus(GLuint program, GLboolean status) {
return MG_State_T::programState->SetProgramStatus(program, status);
}
bool SetShaderStatus(GLuint shader, GLboolean status) {
return MG_State_T::programState->SetShaderStatus(shader, status);
}
// Framebuffer
GLenum MG_State::CreateFramebuffer(GLuint* framebuffer) {
return MG_State_T::framebufferState->Create(framebuffer);
}
GLenum MG_State::CreateFramebuffers(GLsizei n, GLuint* framebuffers) {
return MG_State_T::framebufferState->CreateN(n, framebuffers);
}
GLenum MG_State::DeleteFramebuffer(GLuint framebuffer) {
return MG_State_T::framebufferState->Delete(framebuffer);
}
GLenum MG_State::BindFramebuffer(GLenum target, GLuint framebuffer) {
return MG_State_T::framebufferState->Bind(target, framebuffer);
}
GLenum MG_State::AttachTexture2DToFramebuffer(GLenum target, GLenum attachment, GLenum textarget,
GLuint texture, GLint level) {
return MG_State_T::framebufferState->AttachTexture2D(target, attachment, textarget,
texture, level);
}
GLenum MG_State::ValidateFramebufferCompleteness(GLenum target) {
return MG_State_T::framebufferState->ValidateCompleteness(target);
}
}
-151
View File
@@ -1,151 +0,0 @@
//
// Created by BZLZHH on 2025/4/4.
//
#ifndef MOBILEGL_GLSTATE_H
#define MOBILEGL_GLSTATE_H
#include "../../../Includes.h"
struct MG_State_T {
static std::queue<GLenum> glErrorQueue;
static TextureState* textureState;
static CommonState* commonState;
static BufferState* bufferState;
static VertexArrayState* vertexArrayState;
static ProgramState* programState;
static FramebufferState* framebufferState;
};
namespace MG_State {
void Init();
void Destroy();
void SetError(GLenum error);
GLenum GetError();
//Texture
GLenum BindTextureUnit(GLenum textureUnit);
GLenum CreateTexture(GLuint* texture);
GLenum CreateTextures(GLsizei n, GLuint* textures);
GLenum BindTexture(GLenum target, GLuint texture);
GLenum UploadTexture2D(GLenum target, GLint level, GLint internalFormat,
GLsizei width, GLsizei height, GLint border, GLenum format,
GLenum type, const void* data);
GLenum UpdateTextureRegion2D(GLenum target, GLint level, GLint xoffset,
GLint yoffset, GLsizei width, GLsizei height, GLenum format,
GLenum type, const GLvoid* data);
GLenum SetTexturePropertyInt(GLenum target, GLenum pname, GLint param);
GLenum SetTexturePropertyFloat(GLenum target, GLenum pname, GLfloat param);
GLenum DeleteTexture(GLuint texture);
GLenum DeleteTextures(GLsizei n, const GLuint* textures);
GLenum QueryTextureLevelPropertyIntVector(GLenum target, GLint level, GLenum pname, GLint* params);
// Common
GLenum SetPixelStoreInt(GLenum pname, GLint param);
GLint QueryPixelStoreInt(GLenum pname);
GLenum glEnable(GLenum cap);
GLenum glDisable(GLenum cap);
GLenum glBlendFunc(GLenum sfactor, GLenum dfactor);
GLenum glBlendFuncSeparate(GLenum srcRGB, GLenum dstRGB, GLenum srcAlpha, GLenum dstAlpha);
GLenum glClear(GLbitfield mask);
GLenum glClearColor(GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha);
GLenum glClearDepth(GLdouble depth);
GLenum glColorMask(GLboolean red, GLboolean green, GLboolean blue, GLboolean alpha);
GLenum glDepthFunc(GLenum func);
GLenum glDepthMask(GLboolean flag);
GLenum glViewport(GLint x, GLint y, GLsizei width, GLsizei height);
// Buffer
GLenum AcquireBufferMemory(GLenum target, GLenum access, void** mappedPtr);
GLenum AcquireBufferMemoryRange(GLenum target, GLintptr offset, GLsizeiptr length, GLbitfield access, void** mappedPointer);
GLenum SyncBufferMemory(GLenum target, GLintptr offset, GLsizeiptr length);
GLenum CopyBufferRange(GLenum readTarget, GLenum writeTarget, GLintptr readOffset, GLintptr writeOffset, GLsizeiptr size);
GLenum ReleaseBufferMemory(GLenum target);
GLenum CreateBuffer(GLuint buffer);
GLenum GenBufferNames(GLsizei n, GLuint* buffers);
GLenum BindBuffer(GLenum target, GLuint buffer);
GLenum CommitBufferStorage(GLenum target, GLsizeiptr size, const void* data, GLenum usage);
GLenum CommitBufferStorageRegion(GLenum target, GLintptr offset, GLsizeiptr size, const void* data);
bool ValidateAllocatedBufferHandle(GLuint buffer);
bool ValidateGeneratedName(GLuint buffer);
void DeleteBuffer(GLuint buffer);
GLenum DeleteBuffers(GLsizei n, const GLuint* buffers);
GLenum QueryBufferPropertyIntVector(GLenum target, GLenum pname, GLint* params);
// VertexArray
GLenum CreateVertexArray(GLuint* array);
GLenum CreateVertexArrays(GLsizei n, GLuint* arrays);
GLenum GenVertexArraysNames(GLsizei n, GLuint* arrays);
GLenum BindVertexArray(GLuint array);
GLenum EnableVertexAttribArray(GLuint index);
GLenum DisableVertexAttribArray(GLuint index);
GLenum SetVertexAttributeLayout(GLuint index, GLint size, GLenum type,
GLboolean normalized, GLsizei stride,
const void* pointer);
GLenum SetVertexAttributeLayoutInt(GLuint index, GLint size, GLenum type,
GLsizei stride, const void* pointer);
// Program
GLenum CreateShader(GLenum type, GLuint* shader);
GLenum CreateProgram(GLuint* program);
GLenum DeleteShader(GLuint shader);
GLenum DeleteProgram(GLuint program);
GLenum LinkShaderToProgram(GLuint program, GLuint shader);
GLenum UploadShaderSource(GLuint shader, GLsizei count, const GLchar** string, const GLint* length);
GLenum BuildShaderStage(GLuint shader);
GLenum FinalizeProgramPipeline(GLuint program);
GLenum ActivateRenderProgram(GLuint program);
GLenum DefineProgramAttributeBinding(GLuint program, GLuint index, const GLchar* name);
GLint QueryProgramAttributeBinding(GLuint program, const GLchar* name);
GLint QueryProgramUniformLocation(GLuint program, const GLchar* name);
GLenum QueryProgramStateIntVector(GLuint program, GLenum pname, GLint* params);
GLenum QueryShaderStateIntVector(GLuint shader, GLenum pname, GLint* params);
template<typename T>
GLenum SetUniform(GLuint program, GLint location, GLsizei count, const T* value, GLenum type);
template<typename T>
GLenum SetUniformMatrix(GLuint program, GLint location, GLsizei count, GLboolean transpose, const T* value, GLenum matrixType);
#define DECLARE_UNIFORM_FUNCTIONS(type, suffix, vecType) \
void UpdateProgramUniform##suffix##1(GLint location, type v0); \
void UpdateProgramUniform##suffix##2(GLint location, type v0, type v1); \
void UpdateProgramUniform##suffix##3(GLint location, type v0, type v1, type v2); \
void UpdateProgramUniform##suffix##4(GLint location, type v0, type v1, type v2, type v3); \
void UpdateProgramUniform##suffix##Vector1(GLint location, GLsizei count, const type* value); \
void UpdateProgramUniform##suffix##Vector2(GLint location, GLsizei count, const type* value); \
void UpdateProgramUniform##suffix##Vector3(GLint location, GLsizei count, const type* value); \
void UpdateProgramUniform##suffix##Vector4(GLint location, GLsizei count, const type* value);
DECLARE_UNIFORM_FUNCTIONS(GLfloat, Float, GL_FLOAT)
DECLARE_UNIFORM_FUNCTIONS(GLint, Int, GL_INT)
DECLARE_UNIFORM_FUNCTIONS(GLuint, UInt, GL_UNSIGNED_INT)
DECLARE_UNIFORM_FUNCTIONS(GLboolean, Bool, GL_BOOL)
#undef DECLARE_UNIFORM_FUNCTIONS
#define DECLARE_MATRIX_FUNCTIONS(suffix, matrixType) \
void UpdateProgramUniformMatrix##suffix##Vector(GLint location, GLsizei count, GLboolean transpose, const GLfloat* value);
DECLARE_MATRIX_FUNCTIONS(2x2, GL_FLOAT_MAT2)
DECLARE_MATRIX_FUNCTIONS(3x3, GL_FLOAT_MAT3)
DECLARE_MATRIX_FUNCTIONS(4x4, GL_FLOAT_MAT4)
DECLARE_MATRIX_FUNCTIONS(2x3, GL_FLOAT_MAT2x3)
DECLARE_MATRIX_FUNCTIONS(2x4, GL_FLOAT_MAT2x4)
DECLARE_MATRIX_FUNCTIONS(3x2, GL_FLOAT_MAT3x2)
DECLARE_MATRIX_FUNCTIONS(3x4, GL_FLOAT_MAT3x4)
DECLARE_MATRIX_FUNCTIONS(4x2, GL_FLOAT_MAT4x2)
DECLARE_MATRIX_FUNCTIONS(4x3, GL_FLOAT_MAT4x3)
#undef DECLARE_MATRIX_FUNCTIONS
GLuint GetCurrentProgram();
bool SetProgramStatus(GLuint program, GLboolean status);
bool SetShaderStatus(GLuint shader, GLboolean status);
// Framebuffer
GLenum CreateFramebuffer(GLuint* framebuffer);
GLenum CreateFramebuffers(GLsizei n, GLuint* framebuffers);
GLenum DeleteFramebuffer(GLuint framebuffer);
GLenum BindFramebuffer(GLenum target, GLuint framebuffer);
GLenum AttachTexture2DToFramebuffer(GLenum target, GLenum attachment, GLenum textarget,
GLuint texture, GLint level);
GLenum ValidateFramebufferCompleteness(GLenum target);
}
#endif //MOBILEGL_GLSTATE_H
@@ -1,165 +0,0 @@
//
// Created by BZLZHH on 2025/5/3.
//
// TODO: Add more gl error check for framebuffer state manager.
// TODO: Check if the state machine really meets up to OpenGL 3 standard.
#include "FramebufferState.h"
// Re-Include Includes.h, cuz of the absence of GLState.h
#undef MOBILEGL_GLSTATE_H
#include "../../../Includes.h"
GLenum FramebufferState::Create(GLuint* framebuffer) {
if (!framebuffer) return GL_INVALID_VALUE;
GLuint id = freeIds_.empty() ? ++lastId_ : *freeIds_.begin();
if (!freeIds_.empty()) freeIds_.erase(freeIds_.begin());
*framebuffer = id;
framebuffers_[id].generated = true;
return GL_NO_ERROR;
}
GLenum FramebufferState::CreateN(GLsizei n, GLuint* framebuffers) {
if (n < 0) return GL_INVALID_VALUE;
for (GLsizei i = 0; i < n; ++i) {
if (GLenum err = Create(&framebuffers[i])) return err;
}
return GL_NO_ERROR;
}
GLenum FramebufferState::Delete(GLuint framebuffer) {
if (framebuffer == 0) return GL_INVALID_VALUE;
if (framebuffers_.erase(framebuffer)) {
// TODO: Prevent the object that uses a freeId from conflicting with legacy object in the backend.
//freeIds_.insert(framebuffer);
for (auto& [target, id] : currentBindings_) {
if (id == framebuffer) id = 0;
}
}
return GL_NO_ERROR;
}
GLenum FramebufferState::Bind(GLenum target, GLuint framebuffer) {
if (MG_Constants::Framebuffer::VALID_TARGETS.find(target) == MG_Constants::Framebuffer::VALID_TARGETS.end())
return GL_INVALID_ENUM;
if (framebuffer != 0 && !ValidateHandle(framebuffer))
return GL_INVALID_OPERATION;
if (target == GL_FRAMEBUFFER) {
currentBindings_[GL_READ_FRAMEBUFFER] = framebuffer;
currentBindings_[GL_DRAW_FRAMEBUFFER] = framebuffer;
} else {
currentBindings_[target] = framebuffer;
}
return GL_NO_ERROR;
}
GLenum FramebufferState::AttachTexture2D(GLenum target, GLenum attachment,
GLenum textarget, GLuint texture, GLint level) {
if (MG_Constants::Framebuffer::VALID_ATTACHMENTS.find(attachment) == MG_Constants::Framebuffer::VALID_ATTACHMENTS.end() ||
MG_Constants::Texture::VALID_TARGETS.find(textarget) == MG_Constants::Texture::VALID_TARGETS.end())
return GL_INVALID_ENUM;
if (target == GL_FRAMEBUFFER) target = GL_DRAW_FRAMEBUFFER;
FramebufferObject* fbo = GetCurrentFBO(target);
if (!fbo) return GL_INVALID_OPERATION;
if (texture != 0 && !MG_State_T::textureState->IsTexture(texture))
return GL_INVALID_VALUE;
FramebufferAttachment att;
att.type = GL_TEXTURE_2D;
att.handle = texture;
att.mipLevel = level;
fbo->attachments[attachment] = att;
if (texture != 0) {
GLint params = 0;
MG_State_T::textureState->QueryLevelPropertyIntVector(
textarget, level, GL_TEXTURE_WIDTH, &params);
fbo->width = params;
MG_State_T::textureState->QueryLevelPropertyIntVector(
textarget, level, GL_TEXTURE_HEIGHT, &params);
fbo->height = params;
}
UpdateCompleteness(*fbo);
return GL_NO_ERROR;
}
GLenum FramebufferState::ValidateCompleteness(GLenum target) {
if (target == GL_FRAMEBUFFER) target = GL_DRAW_FRAMEBUFFER;
FramebufferObject* fbo = GetCurrentFBO(target);
if (!fbo) return GL_INVALID_OPERATION;
return fbo->status;
}
void FramebufferState::UpdateCompleteness(FramebufferObject& fbo) {
if (fbo.attachments.empty()) {
fbo.status = GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT;
return;
}
bool hasColor = false;
bool hasDepth = false;
bool hasStencil = false;
GLsizei width = 0, height = 0;
for (const auto& [attach, att] : fbo.attachments) {
GLsizei attWidth = 0, attHeight = 0;
if (att.handle != 0) {
GLint params = 0;
MG_State_T::textureState->QueryLevelPropertyIntVector(
GL_TEXTURE_2D, att.mipLevel, GL_TEXTURE_WIDTH, &params);
attWidth = params;
MG_State_T::textureState->QueryLevelPropertyIntVector(
GL_TEXTURE_2D, att.mipLevel, GL_TEXTURE_HEIGHT, &params);
attHeight = params;
}
if (width == 0) {
width = attWidth;
height = attHeight;
} else if (attWidth != width || attHeight != height) {
fbo.status = GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS;
return;
}
if (attach == GL_DEPTH_ATTACHMENT) hasDepth = true;
if (attach == GL_STENCIL_ATTACHMENT) hasStencil = true;
if (attach >= GL_COLOR_ATTACHMENT0 &&
attach <= GL_COLOR_ATTACHMENT31) hasColor = true;
}
if (!ValidateAttachmentCombination(fbo)) {
fbo.status = GL_FRAMEBUFFER_UNSUPPORTED;
return;
}
fbo.status = GL_FRAMEBUFFER_COMPLETE;
}
bool FramebufferState::ValidateAttachmentCombination(const FramebufferObject& fbo) {
bool depthStencilConflict = false;
for (const auto& [attach, att] : fbo.attachments) {
if (attach == GL_DEPTH_STENCIL_ATTACHMENT) {
GLint internalFormat = 0;
MG_State_T::textureState->QueryLevelPropertyIntVector(
GL_TEXTURE_2D, att.mipLevel, GL_TEXTURE_INTERNAL_FORMAT, &internalFormat);
if (internalFormat != GL_DEPTH24_STENCIL8 &&
internalFormat != GL_DEPTH32F_STENCIL8) {
return false;
}
}
}
return true;
}
FramebufferObject* FramebufferState::GetCurrentFBO(GLenum target) {
auto it = currentBindings_.find(target);
if (it == currentBindings_.end()) return nullptr;
GLuint id = it->second;
if (id == 0) return nullptr;
auto fboIt = framebuffers_.find(id);
return (fboIt != framebuffers_.end()) ? &fboIt->second : nullptr;
}
bool FramebufferState::ValidateHandle(GLuint framebuffer) {
return framebuffers_.count(framebuffer) &&
framebuffers_[framebuffer].generated;
}
@@ -1,49 +0,0 @@
//
// Created by BZLZHH on 2025/5/3.
//
#ifndef MOBILEGL_FRAMEBUFFERSTATE_H
#define MOBILEGL_FRAMEBUFFERSTATE_H
#define MOBILEGL_GLSTATE_H
#include "../../../Includes.h"
struct FramebufferAttachment {
GLenum type = GL_NONE;
GLuint handle = 0;
GLint mipLevel = 0;
GLint zoffset = 0;
};
struct FramebufferObject {
bool generated = false;
ankerl::unordered_map<GLenum, FramebufferAttachment> attachments;
GLenum status = GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT;
GLsizei width = 0;
GLsizei height = 0;
};
class FramebufferState {
public:
// Return: the validity of the operation
GLenum Create(GLuint* framebuffer);
GLenum CreateN(GLsizei n, GLuint* framebuffers);
GLenum Delete(GLuint framebuffer);
GLenum Bind(GLenum target, GLuint framebuffer);
GLenum AttachTexture2D(GLenum target, GLenum attachment,
GLenum textarget, GLuint texture, GLint level);
GLenum ValidateCompleteness(GLenum target);
FramebufferObject* GetCurrentFBO(GLenum target);
ankerl::unordered_map<GLenum, GLuint> currentBindings_; // READ/DRAW
private:
ankerl::unordered_map<GLuint, FramebufferObject> framebuffers_;
std::set<GLuint> freeIds_;
GLuint lastId_ = 0;
bool ValidateHandle(GLuint framebuffer);
static void UpdateCompleteness(FramebufferObject& fbo);
static bool ValidateAttachmentCombination(const FramebufferObject& fbo);
};
#endif //MOBILEGL_FRAMEBUFFERSTATE_H
-577
View File
@@ -1,577 +0,0 @@
//
// Created by BZLZHH on 2025/5/1.
// TODO: Add more gl error check for buffer state manager.
// TODO: Check if the state machine really meets up to OpenGL 3 standard.
#include "ProgramState.h"
// Re-Include Includes.h, cuz of the absence of Program/DebugTool.h and Program/GLSLTool.cpp.
#undef MOBILEGL_GLSLTOOL_H
#undef MOBILEGL_PROGRAM_DEBUGTOOL_H
#include "../../../Includes.h"
ProgramState::ProgramState() {
glslang::InitializeProcess();
}
ProgramState::~ProgramState() {
glslang::FinalizeProcess();
}
GLenum ProgramState::CreateProgram(GLuint* program) {
MG_Util::Debug::LogD("MG_State: Program: CreateProgram called, program ptr=%p", program);
if (!program) {
MG_Util::Debug::LogE("MG_State: Program: CreateProgram error: program pointer is null");
return GL_INVALID_VALUE;
}
GLuint id = freeProgramIds_.empty() ? ++lastProgramId_ : *freeProgramIds_.begin();
if (!freeProgramIds_.empty())
freeProgramIds_.erase(freeProgramIds_.begin());
ProgramObject obj;
obj.linked = {UncertainBool::Unknown, UncertainBool::False};
obj.linkStatus = GL_FALSE;
obj.markedForDeletion = false;
programs_[id] = obj;
*program = id;
MG_Util::Debug::LogD("MG_State: Program: CreateProgram success, new id=%u", id);
return GL_NO_ERROR;
}
GLenum ProgramState::DeleteProgram(GLuint program) {
MG_Util::Debug::LogD("MG_State: Program: DeleteProgram called, id=%u", program);
if (!ValidateProgram_(program)) {
MG_Util::Debug::LogE("MG_State: Program: DeleteProgram error: invalid program id %u", program);
return GL_INVALID_VALUE;
}
programs_.erase(program);
//freeProgramIds_.insert(program);
if (currentProgram_ == program)
currentProgram_ = 0;
MG_Util::Debug::LogD("MG_State: Program: DeleteProgram success, id=%u", program);
return GL_NO_ERROR;
}
GLenum ProgramState::LinkShaderToProgram(GLuint program, GLuint shader) {
MG_Util::Debug::LogD("MG_State: Program: LinkShaderToProgram called, program=%u, shader=%u",
program, shader);
if (!ValidateProgram_(program) || !ValidateShader_(shader)) {
MG_Util::Debug::LogE("MG_State: Program: LinkShaderToProgram error: invalid ids program=%u shader=%u",
program, shader);
return GL_INVALID_VALUE;
}
auto& prog = programs_[program];
if (std::find(prog.attachedShaders.begin(),
prog.attachedShaders.end(), shader) != prog.attachedShaders.end()) {
MG_Util::Debug::LogW("MG_State: Program: LinkShaderToProgram warning: shader %u already attached to program %u",
shader, program);
return GL_INVALID_OPERATION;
}
prog.attachedShaders.push_back(shader);
MG_Util::Debug::LogD("MG_State: Program: LinkShaderToProgram success: shader %u attached to program %u",
shader, program);
return GL_NO_ERROR;
}
GLenum ProgramState::FinalizeProgramPipeline(GLuint program) {
MG_Util::Debug::LogD("MG_State: Program: FinalizeProgramPipeline called, id=%u", program);
if (!ValidateProgram_(program)) {
MG_Util::Debug::LogE("MG_State: Program: FinalizeProgramPipeline error: invalid program id %u", program);
return GL_INVALID_VALUE;
}
auto& prog = programs_[program];
for (GLuint shader : prog.attachedShaders) {
if (!shaders_[shader].compiled.toBool()) {
MG_Util::Debug::LogE("MG_State: Program: FinalizeProgramPipeline error: shader %u not compiled", shader);
return GL_INVALID_OPERATION;
}
}
prog.infoLog.clear();
for (GLuint shaderId : prog.attachedShaders) {
auto& shader = shaders_[shaderId];
if (!shader.compiled.toBool() || shader.compiledSpirv.empty()) {
prog.infoLog = "Program linking failed: \n" +
MG_Util::Program::GetShaderTypeName(shader.type) + " is not compiled.";
prog.linked = UncertainBool::False;
prog.linkStatus = GL_FALSE;
MG_Util::Debug::LogE("MG_State: Program: FinalizeProgramPipeline error: %s", prog.infoLog.c_str());
return GL_INVALID_OPERATION;
}
}
std::vector<std::vector<unsigned>> allSpirv =
MG_Util::Program::CompileMultipleShadersToSPIRV(*this, prog, prog.infoLog);
MG_Util::Program::ReflectSPIRVUniforms(allSpirv, prog, prog.infoLog);
if (!prog.infoLog.empty()) {
prog.linked = UncertainBool::False;
prog.linkStatus = GL_FALSE;
prog.infoLog = "Program linking failed: " + prog.infoLog;
MG_Util::Debug::LogE("MG_State: Program: FinalizeProgramPipeline error: %s", prog.infoLog.c_str());
return GL_INVALID_OPERATION;
}
for (auto& [name, index] : prog.attribBindings) {
prog.attribLocations[name] = index;
}
prog.linked = {UncertainBool::Unknown, UncertainBool::True};
prog.linkStatus = GL_TRUE;
CleanupShaders_();
MG_Util::Program::DumpUniforms(*this, program);
MG_Util::Debug::LogD("MG_State: Program: FinalizeProgramPipeline success, id=%u", program);
return GL_NO_ERROR;
}
GLenum ProgramState::ActivateRenderProgram(GLuint program) {
MG_Util::Debug::LogD("MG_State: Program: ActivateRenderProgram called, id=%u", program);
if (program != 0 && !ValidateProgram_(program)) {
MG_Util::Debug::LogE("MG_State: Program: ActivateRenderProgram error: invalid program id %u", program);
return GL_INVALID_VALUE;
}
MG_Util::Program::DumpCurrentUniforms(*this);
currentProgram_ = program;
MG_Util::Program::DumpCurrentUniforms(*this);
MG_Util::Debug::LogD("MG_State: Program: ActivateRenderProgram success, current program=%u", currentProgram_);
return GL_NO_ERROR;
}
GLenum ProgramState::DefineProgramAttributeBinding(GLuint program, GLuint index, const GLchar* name) {
MG_Util::Debug::LogD("MG_State: Program: DefineProgramAttributeBinding called, program=%u, index=%u, name=%s",
program, index, name);
if (!ValidateProgram_(program)) {
MG_Util::Debug::LogE("MG_State: Program: DefineProgramAttributeBinding error: invalid program id %u", program);
return GL_INVALID_VALUE;
}
if (index >= GL_MAX_VERTEX_ATTRIBS) {
MG_Util::Debug::LogE("MG_State: Program: DefineProgramAttributeBinding error: index %u out of range", index);
return GL_INVALID_VALUE;
}
programs_[program].attribBindings[name] = index;
MG_Util::Debug::LogD("MG_State: Program: DefineProgramAttributeBinding success: %s -> %u", name, index);
return GL_NO_ERROR;
}
GLint ProgramState::QueryProgramAttributeBinding(GLuint program, const GLchar* name) {
MG_Util::Debug::LogD("MG_State: Program: QueryProgramAttributeBinding called, program=%u, name=%s",
program, name);
if (!ValidateProgram_(program)) {
MG_Util::Debug::LogE("MG_State: Program: QueryProgramAttributeBinding error: invalid program id %u", program);
return -1;
}
auto& prog = programs_[program];
auto it = prog.attribLocations.find(name);
if (it != prog.attribLocations.end()) {
GLint loc = it->second;
MG_Util::Debug::LogD("MG_State: Program: QueryProgramAttributeBinding success: %s -> %d", name, loc);
return loc;
}
MG_Util::Debug::LogW("MG_State: Program: QueryProgramAttributeBinding warning: name '%s' not found", name);
return -1;
}
GLenum ProgramState::QueryProgramStateIntVector(GLuint program, GLenum pname, GLint* params) {
MG_Util::Debug::LogD("MG_State: Program: QueryProgramStateIntVector called, program=%u, pname=0x%X",
program, pname);
if (!ValidateProgram_(program)) {
MG_Util::Debug::LogE("MG_State: Program: QueryProgramStateIntVector error: invalid program id %u", program);
return GL_INVALID_VALUE;
}
auto& prog = programs_[program];
switch (pname) {
case GL_LINK_STATUS: *params = prog.linkStatus; break;
case GL_DELETE_STATUS: *params = prog.markedForDeletion; break;
case GL_ATTACHED_SHADERS:*params = (GLint)prog.attachedShaders.size(); break;
default:
MG_Util::Debug::LogE("MG_State: Program: QueryProgramStateIntVector error: invalid pname 0x%X", pname);
return GL_INVALID_ENUM;
}
MG_Util::Debug::LogD("MG_State: Program: QueryProgramStateIntVector success: value=%d", *params);
return GL_NO_ERROR;
}
GLenum ProgramState::QueryShaderStateIntVector(GLuint shader, GLenum pname, GLint* params) {
MG_Util::Debug::LogD("MG_State: Program: QueryShaderStateIntVector called, shader=%u, pname=0x%X",
shader, pname);
if (!ValidateShader_(shader)) {
MG_Util::Debug::LogE("MG_State: Program: QueryShaderStateIntVector error: invalid shader id %u", shader);
return GL_INVALID_VALUE;
}
auto& obj = shaders_[shader];
switch (pname) {
case GL_COMPILE_STATUS: *params = obj.compileStatus; break;
case GL_DELETE_STATUS: *params = obj.markedForDeletion; break;
case GL_SHADER_TYPE: *params = obj.type; break;
default:
MG_Util::Debug::LogE("MG_State: Program: QueryShaderStateIntVector error: invalid pname 0x%X", pname);
return GL_INVALID_ENUM;
}
MG_Util::Debug::LogD("MG_State: Program: QueryShaderStateIntVector success: value=%d", *params);
return GL_NO_ERROR;
}
template<typename T>
GLenum ProgramState::SetUniform(GLuint program, GLint location, GLsizei count, const T* value, GLenum type) {
MG_Util::Debug::LogD("MG_State: Program: SetUniform called, program=%u, location=%d, count=%d, type=0x%X",
program, location, count, type);
if (!ValidateProgram_(program)) {
MG_Util::Debug::LogE("MG_State: Program: SetUniform error: invalid program id %u", program);
return GL_INVALID_VALUE;
}
if (location < -1) {
MG_Util::Debug::LogE("MG_State: Program: SetUniform error: invalid location %d", location);
return GL_INVALID_VALUE;
}
if (count < 0) {
MG_Util::Debug::LogE("MG_State: Program: SetUniform error: invalid count %d", count);
return GL_INVALID_VALUE;
}
if (location == -1) {
MG_Util::Debug::LogW("MG_State: Program: SetUniform warning: location -1, no-op");
return GL_NO_ERROR;
}
ProgramObject& prog = programs_[program];
std::string uniformName;
for (const auto& pair : prog.uniformLocations) {
if (pair.second == location) {
uniformName = pair.first;
break;
}
}
if (uniformName.empty()) {
MG_Util::Debug::LogE("MG_State: Program: SetUniform error: no uniform at location %d in program %u",
location, program);
return GL_INVALID_OPERATION;
}
UniformValue& uniform = prog.uniformValues[uniformName];
uniform.setData(type, count, value);
MG_Util::Debug::LogD("MG_State: Program: SetUniform success: %s set", uniformName.c_str());
return GL_NO_ERROR;
}
template<typename T>
GLenum ProgramState::SetUniformMatrix(GLuint program, GLint location, GLsizei count, GLboolean transpose, const T* value, GLenum matrixType) {
MG_Util::Debug::LogD("MG_State: Program: SetUniformMatrix called, program=%u, location=%d, count=%d, matrixType=0x%X",
program, location, count, matrixType);
(void)transpose;
if (!ValidateProgram_(program)) {
MG_Util::Debug::LogE("MG_State: Program: SetUniformMatrix error: invalid program id %u", program);
return GL_INVALID_VALUE;
}
if (location < -1) {
MG_Util::Debug::LogE("MG_State: Program: SetUniformMatrix error: invalid location %d", location);
return GL_INVALID_VALUE;
}
if (count < 0) {
MG_Util::Debug::LogE("MG_State: Program: SetUniformMatrix error: invalid count %d", count);
return GL_INVALID_VALUE;
}
if (location == -1) {
MG_Util::Debug::LogW("MG_State: Program: SetUniformMatrix warning: location -1, no-op");
return GL_NO_ERROR;
}
ProgramObject& prog = programs_[program];
std::string uniformName;
for (const auto& pair : prog.uniformLocations) {
if (pair.second == location) {
uniformName = pair.first;
break;
}
}
if (uniformName.empty()) {
MG_Util::Debug::LogE("MG_State: Program: SetUniformMatrix error: no uniform at location %d in program %u",
location, program);
return GL_INVALID_OPERATION;
}
UniformValue& uniform = prog.uniformValues[uniformName];
uniform.setData(matrixType, count, value);
MG_Util::Debug::LogD("MG_State: Program: SetUniformMatrix success: %s set", uniformName.c_str());
return GL_NO_ERROR;
}
#define IMPLEMENT_UNIFORM_FUNCTIONS(type, suffix, vecType) \
void ProgramState::UpdateUniform##suffix##1(GLint location, type v0) { \
MG_Util::Debug::LogD("MG_State: Program: UpdateUniform" #suffix "1 called, location=%d", location); \
SetUniform<type>(currentProgram_, location, 1, &v0, vecType); \
} \
void ProgramState::UpdateUniform##suffix##2(GLint location, type v0, type v1) { \
type values[2] = {v0, v1}; \
MG_Util::Debug::LogD("MG_State: Program: UpdateUniform" #suffix "2 called, location=%d", location); \
SetUniform<type>(currentProgram_, location, 1, values, vecType); \
} \
void ProgramState::UpdateUniform##suffix##3(GLint location, type v0, type v1, type v2) { \
type values[3] = {v0, v1, v2}; \
MG_Util::Debug::LogD("MG_State: Program: UpdateUniform" #suffix "3 called, location=%d", location); \
SetUniform<type>(currentProgram_, location, 1, values, vecType); \
} \
void ProgramState::UpdateUniform##suffix##4(GLint location, type v0, type v1, type v2, type v3) { \
type values[4] = {v0, v1, v2, v3}; \
MG_Util::Debug::LogD("MG_State: Program: UpdateUniform" #suffix "4 called, location=%d", location); \
SetUniform<type>(currentProgram_, location, 1, values, vecType); \
} \
void ProgramState::UpdateUniform##suffix##Vector1(GLint location, GLsizei count, const type* value) { \
MG_Util::Debug::LogD("MG_State: Program: UpdateUniform" #suffix "Vector1 called, location=%d, count=%d", location, count); \
SetUniform<type>(currentProgram_, location, count, value, vecType); \
} \
void ProgramState::UpdateUniform##suffix##Vector2(GLint location, GLsizei count, const type* value) { \
MG_Util::Debug::LogD("MG_State: Program: UpdateUniform" #suffix "Vector2 called, location=%d, count=%d", location, count); \
SetUniform<type>(currentProgram_, location, count, value, vecType); \
} \
void ProgramState::UpdateUniform##suffix##Vector3(GLint location, GLsizei count, const type* value) { \
MG_Util::Debug::LogD("MG_State: Program: UpdateUniform" #suffix "Vector3 called, location=%d, count=%d", location, count); \
SetUniform<type>(currentProgram_, location, count, value, vecType); \
} \
void ProgramState::UpdateUniform##suffix##Vector4(GLint location, GLsizei count, const type* value) { \
MG_Util::Debug::LogD("MG_State: Program: UpdateUniform" #suffix "Vector4 called, location=%d, count=%d", location, count); \
SetUniform<type>(currentProgram_, location, count, value, vecType); \
}
IMPLEMENT_UNIFORM_FUNCTIONS(GLfloat, Float, GL_FLOAT_VEC4)
IMPLEMENT_UNIFORM_FUNCTIONS(GLint, Int, GL_INT_VEC4)
IMPLEMENT_UNIFORM_FUNCTIONS(GLuint, UInt, GL_UNSIGNED_INT_VEC4)
IMPLEMENT_UNIFORM_FUNCTIONS(GLboolean, Bool, GL_BOOL_VEC4)
#undef IMPLEMENT_UNIFORM_FUNCTIONS
#define IMPLEMENT_MATRIX_FUNCTIONS(suffix, matrixType) \
void ProgramState::UpdateUniformMatrix##suffix##Vector(GLint location, GLsizei count, GLboolean transpose, const GLfloat* value) { \
MG_Util::Debug::LogD("MG_State: Program: UpdateUniformMatrix" #suffix "Vector called, location=%d, count=%d", location, count); \
SetUniformMatrix<GLfloat>(currentProgram_, location, count, transpose, value, matrixType); \
}
IMPLEMENT_MATRIX_FUNCTIONS(2x2, GL_FLOAT_MAT2)
IMPLEMENT_MATRIX_FUNCTIONS(3x3, GL_FLOAT_MAT3)
IMPLEMENT_MATRIX_FUNCTIONS(4x4, GL_FLOAT_MAT4)
IMPLEMENT_MATRIX_FUNCTIONS(2x3, GL_FLOAT_MAT2x3)
IMPLEMENT_MATRIX_FUNCTIONS(2x4, GL_FLOAT_MAT2x4)
IMPLEMENT_MATRIX_FUNCTIONS(3x2, GL_FLOAT_MAT3x2)
IMPLEMENT_MATRIX_FUNCTIONS(3x4, GL_FLOAT_MAT3x4)
IMPLEMENT_MATRIX_FUNCTIONS(4x2, GL_FLOAT_MAT4x2)
IMPLEMENT_MATRIX_FUNCTIONS(4x3, GL_FLOAT_MAT4x3)
#undef IMPLEMENT_MATRIX_FUNCTIONS
GLint ProgramState::QueryProgramUniformLocation(GLuint program, const GLchar* name) {
MG_Util::Debug::LogD("MG_State: Program: QueryProgramUniformLocation called, program=%u, name=%s", program, name);
if (!ValidateProgram_(program)) {
MG_Util::Debug::LogE("MG_State: Program: QueryProgramUniformLocation error: invalid program id %u", program);
return -1;
}
auto& prog = programs_[program];
auto it = prog.uniformLocations.find(name);
if (it != prog.uniformLocations.end()) {
GLint loc = it->second;
MG_Util::Debug::LogD("MG_State: Program: QueryProgramUniformLocation success: %s -> %d", name, loc);
return loc;
}
MG_Util::Debug::LogW("MG_State: Program: QueryProgramUniformLocation warning: name '%s' not found", name);
return -1;
}
bool ProgramState::SetProgramStatus(GLuint program, GLboolean status) {
MG_Util::Debug::LogD("MG_State: Program: SetProgramStatus called, program=%u, status=%d", program, status);
if (!ValidateProgram_(program)) {
MG_Util::Debug::LogE("MG_State: Program: SetProgramStatus error: invalid program id %u", program);
return false;
}
auto& prog = programs_[program];
if (prog.linked.getValue() != UncertainBool::Unknown) {
MG_Util::Debug::LogW("MG_State: Program: SetProgramStatus warning: link state already known");
return false;
}
prog.linked = (status == GL_TRUE) ? UncertainBool::True : UncertainBool::False;
prog.linkStatus = status;
MG_Util::Debug::LogD("MG_State: Program: SetProgramStatus success, status=%d", status);
return true;
}
GLuint ProgramState::GetCurrentProgram() const {
MG_Util::Debug::LogD("MG_State: Program: GetCurrentProgram called, returning %u", currentProgram_);
return currentProgram_;
}
ShaderObject ProgramState::GetShaderObject(GLuint shader) const {
MG_Util::Debug::LogD("MG_State: Program: GetShaderObject called, shader=%u", shader);
auto it = shaders_.find(shader);
if (it == shaders_.end()) {
MG_Util::Debug::LogW("MG_State: Program: GetShaderObject warning: invalid shader id %u", shader);
return ShaderObject();
}
MG_Util::Debug::LogD("MG_State: Program: GetShaderObject success, returning object");
return it->second;
}
ProgramObject ProgramState::GetProgramObject(GLuint program) const {
MG_Util::Debug::LogD("MG_State: Program: GetProgramObject called, program=%u", program);
auto it = programs_.find(program);
if (it == programs_.end()) {
MG_Util::Debug::LogW("MG_State: Program: GetProgramObject warning: invalid program id %u", program);
return ProgramObject();
}
MG_Util::Debug::LogD("MG_State: Program: GetProgramObject success, returning object");
return it->second;
}
bool ProgramState::ValidateProgram_(GLuint program) {
bool ok = programs_.count(program) && !programs_[program].markedForDeletion;
MG_Util::Debug::LogD("MG_State: Program: ValidateProgram_ called, program=%u, result=%d", program, ok);
return ok;
}
void ProgramState::CleanupShaders_() {
MG_Util::Debug::LogD("MG_State: Program: CleanupShaders_ start");
auto it = shaders_.begin();
while (it != shaders_.end()) {
if (it->second.markedForDeletion) {
bool inUse = false;
for (auto& [progId, program] : programs_) {
if (std::find(program.attachedShaders.begin(),
program.attachedShaders.end(), it->first) != program.attachedShaders.end()) {
inUse = true;
break;
}
}
if (!inUse) {
MG_Util::Debug::LogD("MG_State: Program: CleanupShaders_ deleting shader %u", it->first);
freeShaderIds_.insert(it->first);
it = shaders_.erase(it);
continue;
}
}
++it;
}
MG_Util::Debug::LogD("MG_State: Program: CleanupShaders_ end");
}
// UniformValue
template<typename T>
void UniformValue::setData(GLenum uniformType, GLsizei count_, const T* values) {
MG_Util::Debug::LogD("MG_State: Program: UniformValue::setData called, type=0x%X, count=%d", uniformType, count_);
//type = uniformType;
count = count_;
floatData.clear();
intData.clear();
uintData.clear();
boolData.clear();
switch (type) {
case GL_FLOAT: numElements = count_ * 1; break;
case GL_FLOAT_VEC2: numElements = count_ * 2; break;
case GL_FLOAT_VEC3: numElements = count_ * 3; break;
case GL_FLOAT_VEC4: numElements = count_ * 4; break;
case GL_INT: numElements = count_ * 1; break;
case GL_INT_VEC2: numElements = count_ * 2; break;
case GL_INT_VEC3: numElements = count_ * 3; break;
case GL_INT_VEC4: numElements = count_ * 4; break;
case GL_UNSIGNED_INT: numElements = count_ * 1; break;
case GL_UNSIGNED_INT_VEC2: numElements = count_ * 2; break;
case GL_UNSIGNED_INT_VEC3: numElements = count_ * 3; break;
case GL_UNSIGNED_INT_VEC4: numElements = count_ * 4; break;
case GL_BOOL: numElements = count_ * 1; break;
case GL_BOOL_VEC2: numElements = count_ * 2; break;
case GL_BOOL_VEC3: numElements = count_ * 3; break;
case GL_BOOL_VEC4: numElements = count_ * 4; break;
case GL_FLOAT_MAT2: numElements = count_ * 4; break; // 2x2
case GL_FLOAT_MAT3: numElements = count_ * 9; break; // 3x3
case GL_FLOAT_MAT4: numElements = count_ * 16; break; // 4x4
case GL_FLOAT_MAT2x3: numElements = count_ * 6; break; // 2x3
case GL_FLOAT_MAT2x4: numElements = count_ * 8; break; // 2x4
case GL_FLOAT_MAT3x2: numElements = count_ * 6; break; // 3x2
case GL_FLOAT_MAT3x4: numElements = count_ * 12; break; // 3x4
case GL_FLOAT_MAT4x2: numElements = count_ * 8; break; // 4x2
case GL_FLOAT_MAT4x3: numElements = count_ * 12; break; // 4x3
case GL_SAMPLER_1D:
case GL_SAMPLER_2D:
case GL_SAMPLER_3D:
case GL_SAMPLER_CUBE:
case GL_SAMPLER_1D_SHADOW:
case GL_SAMPLER_2D_SHADOW:
case GL_SAMPLER_CUBE_SHADOW:
case GL_SAMPLER_1D_ARRAY:
case GL_SAMPLER_2D_ARRAY:
case GL_SAMPLER_1D_ARRAY_SHADOW:
case GL_SAMPLER_2D_ARRAY_SHADOW:
case GL_SAMPLER_BUFFER:
case GL_SAMPLER_2D_MULTISAMPLE:
case GL_SAMPLER_2D_MULTISAMPLE_ARRAY: numElements = count_ * 1; break;
default:
MG_Util::Debug::LogW("MG_State: Program: UniformValue::setData warning: unsupported type 0x%X for numElements", uniformType);
numElements = 1;
return;
}
for (GLsizei i = 0; i < numElements; ++i) {
switch (uniformType) {
case GL_FLOAT:
case GL_FLOAT_VEC2:
case GL_FLOAT_VEC3:
case GL_FLOAT_VEC4:
case GL_FLOAT_MAT2:
case GL_FLOAT_MAT3:
case GL_FLOAT_MAT4:
case GL_FLOAT_MAT2x3:
case GL_FLOAT_MAT2x4:
case GL_FLOAT_MAT3x2:
case GL_FLOAT_MAT3x4:
case GL_FLOAT_MAT4x2:
case GL_FLOAT_MAT4x3:
floatData.push_back(static_cast<GLfloat>(values[i]));
break;
case GL_INT:
case GL_INT_VEC2:
case GL_INT_VEC3:
case GL_INT_VEC4:
case GL_SAMPLER_1D:
case GL_SAMPLER_2D:
case GL_SAMPLER_3D:
case GL_SAMPLER_CUBE:
case GL_SAMPLER_1D_SHADOW:
case GL_SAMPLER_2D_SHADOW:
case GL_SAMPLER_CUBE_SHADOW:
case GL_SAMPLER_1D_ARRAY:
case GL_SAMPLER_2D_ARRAY:
case GL_SAMPLER_1D_ARRAY_SHADOW:
case GL_SAMPLER_2D_ARRAY_SHADOW:
case GL_SAMPLER_BUFFER:
case GL_SAMPLER_2D_MULTISAMPLE:
case GL_SAMPLER_2D_MULTISAMPLE_ARRAY:
intData.push_back(static_cast<GLint>(values[i]));
break;
case GL_UNSIGNED_INT:
case GL_UNSIGNED_INT_VEC2:
case GL_UNSIGNED_INT_VEC3:
case GL_UNSIGNED_INT_VEC4:
uintData.push_back(static_cast<GLuint>(values[i]));
break;
case GL_BOOL:
case GL_BOOL_VEC2:
case GL_BOOL_VEC3:
case GL_BOOL_VEC4:
boolData.push_back(values[i] ? GL_TRUE : GL_FALSE);
break;
default:
MG_Util::Debug::LogW("MG_State: Program: UniformValue::setData warning: unsupported type 0x%X", uniformType);
break;
}
}
MG_Util::Debug::LogD("MG_State: Program: UniformValue::setData end");
}
-126
View File
@@ -1,126 +0,0 @@
//
// Created by BZLZHH on 2025/5/1.
//
#ifndef MOBILEGL_PROGRAMSTATE_H
#define MOBILEGL_PROGRAMSTATE_H
#define MOBILEGL_GLSTATE_H
#define MOBILEGL_PROGRAM_DEBUGTOOL_H
#define MOBILEGL_GLSLTOOL_H
#include "../../../Includes.h"
struct ShaderObject {
GLenum type;
std::string source;
std::vector<unsigned int> compiledSpirv;
UncertainBool compiled;
GLint compileStatus;
std::string infoLog;
bool markedForDeletion;
};
struct UniformValue {
GLenum type;
std::vector<GLfloat> floatData;
std::vector<GLint> intData;
std::vector<GLuint> uintData;
std::vector<GLboolean> boolData;
GLsizei count;
GLsizei numElements;
UniformValue() : type(0), count(0) {}
template<typename T>
void setData(GLenum uniformType, GLsizei count_, const T* values);
};
struct ProgramObject {
std::vector<GLuint> attachedShaders;
UncertainBool linked;
bool dirty;
GLint linkStatus;
std::string infoLog;
ankerl::unordered_map<std::string, GLint> attribBindings;
ankerl::unordered_map<std::string, GLint> attribLocations;
ankerl::unordered_map<std::string, GLint> uniformLocations;
ankerl::unordered_map<std::string, UniformValue> uniformValues;
bool markedForDeletion;
};
class ProgramState {
public:
ankerl::unordered_map<GLuint, ShaderObject> shaders_;
ankerl::unordered_map<GLuint, ProgramObject> programs_;
std::set<GLuint> freeShaderIds_;
std::set<GLuint> freeProgramIds_;
GLuint lastShaderId_ = 0;
GLuint lastProgramId_ = 0;
GLuint currentProgram_ = 0;
ProgramState();
~ProgramState();
// Return: the validity of the operation, according to OpenGL 3 standard
GLenum CreateShader(GLenum type, GLuint* shader);
GLenum CreateProgram(GLuint* program);
GLenum DeleteShader(GLuint shader);
GLenum DeleteProgram(GLuint program);
GLenum LinkShaderToProgram(GLuint program, GLuint shader);
GLenum UploadShaderSource(GLuint shader, GLsizei count, const GLchar** string, const GLint* length);
GLenum BuildShaderStage(GLuint shader);
GLenum FinalizeProgramPipeline(GLuint program);
GLenum ActivateRenderProgram(GLuint program);
GLenum DefineProgramAttributeBinding(GLuint program, GLuint index, const GLchar* name);
GLint QueryProgramAttributeBinding(GLuint program, const GLchar* name);
GLint QueryProgramUniformLocation(GLuint program, const GLchar* name);
GLenum QueryProgramStateIntVector(GLuint program, GLenum pname, GLint* params);
GLenum QueryShaderStateIntVector(GLuint shader, GLenum pname, GLint* params);
template<typename T>
GLenum SetUniform(GLuint program, GLint location, GLsizei count, const T* value, GLenum type);
template<typename T>
GLenum SetUniformMatrix(GLuint program, GLint location, GLsizei count, GLboolean transpose, const T* value, GLenum matrixType);
#define DECLARE_UNIFORM_FUNCTIONS(type, suffix, vecType) \
void UpdateUniform##suffix##1(GLint location, type v0); \
void UpdateUniform##suffix##2(GLint location, type v0, type v1); \
void UpdateUniform##suffix##3(GLint location, type v0, type v1, type v2); \
void UpdateUniform##suffix##4(GLint location, type v0, type v1, type v2, type v3); \
void UpdateUniform##suffix##Vector1(GLint location, GLsizei count, const type* value); \
void UpdateUniform##suffix##Vector2(GLint location, GLsizei count, const type* value); \
void UpdateUniform##suffix##Vector3(GLint location, GLsizei count, const type* value); \
void UpdateUniform##suffix##Vector4(GLint location, GLsizei count, const type* value);
DECLARE_UNIFORM_FUNCTIONS(GLfloat, Float, GL_FLOAT)
DECLARE_UNIFORM_FUNCTIONS(GLint, Int, GL_INT)
DECLARE_UNIFORM_FUNCTIONS(GLuint, UInt, GL_UNSIGNED_INT)
DECLARE_UNIFORM_FUNCTIONS(GLboolean, Bool, GL_BOOL)
#undef DECLARE_UNIFORM_FUNCTIONS
#define DECLARE_MATRIX_FUNCTIONS(suffix, matrixType) \
void UpdateUniformMatrix##suffix##Vector(GLint location, GLsizei count, GLboolean transpose, const GLfloat* value);
DECLARE_MATRIX_FUNCTIONS(2x2, GL_FLOAT_MAT2)
DECLARE_MATRIX_FUNCTIONS(3x3, GL_FLOAT_MAT3)
DECLARE_MATRIX_FUNCTIONS(4x4, GL_FLOAT_MAT4)
DECLARE_MATRIX_FUNCTIONS(2x3, GL_FLOAT_MAT2x3)
DECLARE_MATRIX_FUNCTIONS(2x4, GL_FLOAT_MAT2x4)
DECLARE_MATRIX_FUNCTIONS(3x2, GL_FLOAT_MAT3x2)
DECLARE_MATRIX_FUNCTIONS(3x4, GL_FLOAT_MAT3x4)
DECLARE_MATRIX_FUNCTIONS(4x2, GL_FLOAT_MAT4x2)
DECLARE_MATRIX_FUNCTIONS(4x3, GL_FLOAT_MAT4x3)
#undef DECLARE_MATRIX_FUNCTIONS
ProgramObject GetProgramObject(GLuint program) const;
ShaderObject GetShaderObject(GLuint program) const;
GLuint GetCurrentProgram() const;
bool SetProgramStatus(GLuint program, GLboolean status);
bool SetShaderStatus(GLuint shader, GLboolean status);
private:
bool ValidateShader_(GLuint shader);
bool ValidateProgram_(GLuint program);
void CleanupShaders_();
GLint GetUniformLocation_(GLuint program, GLint location, const GLchar* name);
};
#endif // MOBILEGL_PROGRAMSTATE_H
-139
View File
@@ -1,139 +0,0 @@
//
// Created by BZLZHH on 2025/5/3.
//
#include "ShaderObject.h"
// Re-Include Includes.h, cuz of the absence of Program/DebugTool.h and Program/GLSLTool.cpp.
#undef MOBILEGL_GLSLTOOL_H
#undef MOBILEGL_PROGRAM_DEBUGTOOL_H
#include "../../../Includes.h"
GLenum ProgramState::CreateShader(GLenum type, GLuint* shader) {
MG_Util::Debug::LogD("MG_State: Program: CreateShader called, type=0x%X, shader ptr=%p", type, shader);
if (!shader) {
MG_Util::Debug::LogE("MG_State: Program: CreateShader error: shader pointer is null");
return GL_INVALID_VALUE;
}
if (type != GL_VERTEX_SHADER && type != GL_FRAGMENT_SHADER) {
MG_Util::Debug::LogE("MG_State: Program: CreateShader error: invalid shader type 0x%X", type);
return GL_INVALID_ENUM;
}
GLuint id = freeShaderIds_.empty() ? ++lastShaderId_ : *freeShaderIds_.begin();
if (!freeShaderIds_.empty())
freeShaderIds_.erase(freeShaderIds_.begin());
ShaderObject obj;
obj.type = type;
obj.compiled = {UncertainBool::Unknown, UncertainBool::False};
obj.compiledSpirv = {};
obj.markedForDeletion = false;
obj.compileStatus = GL_FALSE;
shaders_[id] = obj;
*shader = id;
MG_Util::Debug::LogD("MG_State: Program: CreateShader success, new shader id=%u", id);
return GL_NO_ERROR;
}
GLenum ProgramState::DeleteShader(GLuint shader) {
MG_Util::Debug::LogD("MG_State: Program: DeleteShader called, shader id=%u", shader);
if (!ValidateShader_(shader)) {
MG_Util::Debug::LogE("MG_State: Program: DeleteShader error: invalid shader id %u", shader);
return GL_INVALID_VALUE;
}
if (shaders_[shader].markedForDeletion) {
MG_Util::Debug::LogW("MG_State: Program: DeleteShader warning: shader %u already marked for deletion", shader);
return GL_NO_ERROR;
}
bool inUse = false;
for (auto& [progId, program] : programs_) {
if (std::find(program.attachedShaders.begin(),
program.attachedShaders.end(), shader) != program.attachedShaders.end()) {
inUse = true;
break;
}
}
if (inUse) {
shaders_[shader].markedForDeletion = true;
MG_Util::Debug::LogD("MG_State: Program: DeleteShader info: shader %u marked for deferred deletion (in use)", shader);
} else {
shaders_.erase(shader);
// TODO: Prevent the object that uses a freeId from conflicting with legacy object in the backend.
//freeShaderIds_.insert(shader);
MG_Util::Debug::LogD("MG_State: Program: DeleteShader success: shader %u deleted immediately", shader);
}
return GL_NO_ERROR;
}
GLenum ProgramState::UploadShaderSource(GLuint shader, GLsizei count,
const GLchar** string, const GLint* length) {
MG_Util::Debug::LogD("MG_State: Program: UploadShaderSource called, shader id=%u, count=%d", shader, count);
if (!ValidateShader_(shader)) {
MG_Util::Debug::LogE("MG_State: Program: UploadShaderSource error: invalid shader id %u", shader);
return GL_INVALID_VALUE;
}
if (count < 0) {
MG_Util::Debug::LogE("MG_State: Program: UploadShaderSource error: negative count %d", count);
return GL_INVALID_VALUE;
}
std::string source;
for (GLsizei i = 0; i < count; ++i) {
const GLchar* str = string[i];
GLint len = (length && length[i] >= 0) ? length[i] : strlen(str);
source.append(str, len);
}
shaders_[shader].source = std::move(source);
MG_Util::Debug::LogD("MG_State: Program: UploadShaderSource success: source uploaded (length=%zu)", shaders_[shader].source.size());
return GL_NO_ERROR;
}
GLenum ProgramState::BuildShaderStage(GLuint shader) {
MG_Util::Debug::LogD("MG_State: Program: BuildShaderStage called, shader id=%u", shader);
if (!ValidateShader_(shader)) {
MG_Util::Debug::LogE("MG_State: Program: BuildShaderStage error: invalid shader id %u", shader);
return GL_INVALID_VALUE;
}
auto& obj = shaders_[shader];
std::string compilationLog;
auto spirv = MG_Util::Program::CompileGLSLToSPIRV(obj.type, obj.source, compilationLog);
if (spirv.empty()) {
obj.infoLog = "Shader compilation failed: " + compilationLog;
obj.compiled = UncertainBool::False;
obj.compileStatus = GL_FALSE;
MG_Util::Debug::LogE("MG_State: Program: BuildShaderStage error: %s", compilationLog.c_str());
return GL_INVALID_OPERATION;
}
obj.compiledSpirv = spirv;
obj.compiled = {UncertainBool::Unknown, UncertainBool::True};
obj.compileStatus = GL_TRUE;
obj.infoLog.clear();
MG_Util::Debug::LogD("MG_State: Program: BuildShaderStage success: shader %u compiled to SPIR-V (size=%zu bytes)", shader, spirv.size() * sizeof(unsigned));
return GL_NO_ERROR;
}
bool ProgramState::SetShaderStatus(GLuint shader, GLboolean status) {
MG_Util::Debug::LogD("MG_State: Program: SetShaderStatus called, shader id=%u, status=%d", shader, status);
if (!ValidateShader_(shader)) {
MG_Util::Debug::LogE("MG_State: Program: SetShaderStatus error: invalid shader id %u", shader);
return false;
}
auto& obj = shaders_[shader];
if (obj.compiled.getValue() != UncertainBool::Unknown) {
MG_Util::Debug::LogW("MG_State: Program: SetShaderStatus warning: shader %u status already set", shader);
return false;
}
obj.compiled = (status == GL_TRUE) ? UncertainBool::True : UncertainBool::False;
obj.compileStatus = status;
MG_Util::Debug::LogD("MG_State: Program: SetShaderStatus success: shader %u status=%d", shader, status);
return true;
}
bool ProgramState::ValidateShader_(GLuint shader) {
bool valid = shaders_.count(shader) && !shaders_[shader].markedForDeletion;
MG_Util::Debug::LogD("MG_State: Program: ValidateShader_ called, shader id=%u, result=%d", shader, valid);
return valid;
}
-12
View File
@@ -1,12 +0,0 @@
//
// Created by BZLZHH on 2025/5/3.
//
#ifndef MOBILEGL_SHADEROBJECT_H
#define MOBILEGL_SHADEROBJECT_H
#define MOBILEGL_GLSTATE_H
#include "../../../Includes.h"
#endif //MOBILEGL_SHADEROBJECT_H
File diff suppressed because it is too large Load Diff
-117
View File
@@ -1,117 +0,0 @@
//
// Created by BZLZHH on 2025/4/4.
//
#ifndef MOBILEGL_TEXTURESTATE_H
#define MOBILEGL_TEXTURESTATE_H
#define MOBILEGL_GLSTATE_H
#include "../../../Includes.h"
struct ComponentSizes {
GLint red = 0;
GLint green = 0;
GLint blue = 0;
GLint alpha = 0;
GLint depth = 0;
GLint stencil = 0;
bool isCompressed = false;
};
struct TextureParams {
template <typename K, typename V>
using unordered_map = ankerl::unordered_dense::map<K, V>;
unordered_map<GLenum, GLfloat> texPropertiesFloat;
unordered_map<GLenum, GLint> texPropertiesInt;
struct MipmapLevel {
GLsizei width = 0;
GLsizei height = 0;
GLenum format = GL_RGBA;
GLenum internalFormat = GL_RGBA;
GLenum type = GL_UNSIGNED_BYTE;
std::vector<GLubyte> pixelData;
bool hasData = false;
bool dirty = false; // TODO: encapsulate this with an public API to RHI
};
unordered_map<GLint, MipmapLevel> mipmapData;
};
class TextureObject {
public:
bool generated = false;
GLenum target = GL_NONE;
TextureParams params;
const void* data = nullptr;
bool IsImmutable() const;
uint64_t createTimestamp{};
};
class TextureUnitState {
template <typename K, typename V>
using unordered_map = ankerl::unordered_dense::map<K, V>;
private:
GLenum activeTarget = GL_TEXTURE_2D;
public:
unordered_map<GLenum, GLuint> boundTextures;
void Bind(GLenum target, GLuint texture);
GLuint GetBoundTexture(GLenum target);
};
class TextureState {
template <typename K, typename V>
using unordered_map = ankerl::unordered_dense::map<K, V>;
private:
GLuint lastUsedID_ = 1;
// ankerl::unordered_set<GLuint> freeIDs_;
std::vector<GLuint> freeID_;
unordered_map<GLenum, TextureObject> proxyTextures_;
static GLint GetUnpackParam_(GLenum pname);
public:
TextureState();
bool IsTextureGenerated(GLuint texture);
bool IsTexture(GLuint texture);
unordered_map<GLuint, TextureObject> textures;
// Return: the validity of the operation, according to OpenGL 3 standard
GLenum BindUnit(GLenum textureUnit);
GLenum Create(GLuint* texture);
GLenum CreateN(GLsizei n, GLuint* textures);
GLenum Bind(GLenum target, GLuint texture);
GLenum Upload2D(GLenum target, GLint level, GLint internalFormat,
GLsizei width, GLsizei height, GLint border, GLenum format,
GLenum type, const void* data);
GLenum UpdateRegion2D(GLenum target, GLint level, GLint xoffset,
GLint yoffset, GLsizei width, GLsizei height, GLenum format,
GLenum type, const GLvoid* data);
GLenum SetTexturePropertyInt(GLenum target, GLenum pname, GLint param);
GLenum SetTexturePropertyFloat(GLenum target, GLenum pname, GLfloat param);
GLenum Delete(GLuint texture);
GLenum DeleteN(GLsizei n, const GLuint* textures);
GLenum QueryLevelPropertyIntVector(GLenum target, GLint level, GLenum pname, GLint* params);
std::vector<TextureUnitState> textureUnits_;
GLuint activeTextureUnit_ = 0;
private:
size_t CalculatePixelDataSize_(GLenum format, GLenum type, GLsizei width, GLsizei height);
void InvalidateTextureInAllUnits_(GLuint texture);
static ComponentSizes GetComponentSize_s_(GLenum internalFormat);
size_t CalculateBytesPerPixel_(GLenum format, GLenum type);
static size_t GetComponentSize_(GLenum type);
void SwapBytesForTexture_(GLenum format, GLenum type, const GLubyte* src, GLubyte* dst, GLsizei width);
static void ReverseBitOrder_(const GLubyte* src, GLubyte* dst, size_t size);
static GLubyte ReverseBits_(GLubyte b);
void SwapPixelBytes_(GLenum format, GLenum type, const GLubyte* src, GLubyte* dst);
GLenum CheckUploadingTexture2DValidity_(GLenum target, GLint level, GLint internalFormat,
GLsizei width, GLsizei height, GLint border, GLenum format,
GLenum type, const void* data);
GLenum CheckUpdatingTextureRegion2DValidity_(GLenum target, GLint level, GLint xoffset,
GLint yoffset, GLsizei width, GLsizei height, GLenum format,
GLenum type, const GLvoid* data);
};
#endif //MOBILEGL_TEXTURESTATE_H
@@ -1,162 +0,0 @@
//
// Created by BZLZHH on 2025/5/1.
//
// TODO: Add more gl error check for vertex array state manager.
#include "VertexArrayState.h"
VertexArrayState::VertexArrayState() {
vaos_[0];
}
GLenum VertexArrayState::GenName(GLuint *array) {
MG_Util::Debug::LogD("MG_State: VAO: GenName");
if (!array)
return GL_INVALID_VALUE;
GLuint id;
if (freeIds_.empty()) {
id = ++lastId_;
} else {
id = *freeIds_.begin();
freeIds_.erase(freeIds_.begin());
}
*array = id;
MG_Util::Debug::LogD("MG_State: VAO: Generated new name %d", id);
return GL_NO_ERROR;
}
GLenum VertexArrayState::GenNameN(GLsizei n, GLuint* arrays) {
MG_Util::Debug::LogD("MG_State: VAO: GenNameN called with n=%d", n);
if (n < 0)
return GL_INVALID_VALUE;
for (GLsizei i = 0; i < n; ++i) {
GLenum result = GenName(&arrays[i]);
if (result != GL_NO_ERROR) {
MG_Util::Debug::LogE("MG_State: VAO: GenNameN failed at index %d with error 0x%x", i, result);
return result;
}
}
MG_Util::Debug::LogD("MG_State: VAO: GenNameN created %d names", n);
return GL_NO_ERROR;
}
GLenum VertexArrayState::Create(GLuint* array) {
if (array == nullptr) return GL_INVALID_VALUE;
GLuint id = freeIds_.empty() ? ++lastId_ : *freeIds_.begin();
if (!freeIds_.empty()) {
freeIds_.erase(freeIds_.begin());
}
*array = id;
vaos_[id].generated = true;
return GL_NO_ERROR;
}
GLenum VertexArrayState::CreateN(GLsizei n, GLuint* arrays) {
if (n < 0) {
return GL_INVALID_VALUE;
}
if (n > 0 && arrays == nullptr) {
return GL_INVALID_VALUE;
}
for (GLsizei i = 0; i < n; ++i) {
if (GLenum error = Create(&arrays[i]); error != GL_NO_ERROR) {
return error;
}
}
return GL_NO_ERROR;
}
GLenum VertexArrayState::Bind(GLuint array) {
MG_Util::Debug::LogD("MG_State: VAO: Bind called for %u", array);
if (array != 0) {
if (!ValidateGeneratedName(array)) {
MG_Util::Debug::LogE("MG_State: VAO: Bind invalid name %u", array);
return GL_INVALID_OPERATION;
}
auto& vao = vaos_[array];
if (!vao.generated) {
MG_Util::Debug::LogD("MG_State: VAO: Creating VAO %u during bind", array);
vao.generated = true;
}
}
currentVao_ = array;
MG_Util::Debug::LogD("MG_State: VAO: Bound to %u", array);
return GL_NO_ERROR;
}
bool VertexArrayState::ValidateGeneratedName(GLuint array) {
if (array == 0)
return true;
bool inFreeList = freeIds_.count(array) > 0;
bool valid = (array <= lastId_) && !inFreeList;
MG_Util::Debug::LogD("MG_State: VAO: ValidateGeneratedName %u: %d", array, valid);
return valid;
}
bool VertexArrayState::ValidateAllocatedHandle(GLuint array) {
bool exists = vaos_.count(array) && vaos_[array].generated;
MG_Util::Debug::LogD("MG_State: VAO: ValidateAllocatedHandle %u: %d", array, exists);
return exists;
}
GLenum VertexArrayState::EnableAttrib(GLuint index) {
if (!ValidateAllocatedHandle(currentVao_))
return GL_INVALID_OPERATION;
if (index >= GL_MAX_VERTEX_ATTRIBS) return GL_INVALID_VALUE;
GetCurrentVAO()->attribs[index].enabled = true;
MG_Util::Debug::LogD("Attrib vaos_[%u].attribs[%u].enabled = %d", currentVao_, index, vaos_[currentVao_].attribs[index].enabled);
GetCurrentVAO()->attribDirty = true;
return GL_NO_ERROR;
}
GLenum VertexArrayState::DisableAttrib(GLuint index) {
if (!ValidateAllocatedHandle(currentVao_))
return GL_INVALID_OPERATION;
if (index >= GL_MAX_VERTEX_ATTRIBS) return GL_INVALID_VALUE;
GetCurrentVAO()->attribs[index].enabled = false;
MG_Util::Debug::LogD("Attrib vaos_[%u].attribs[%u].enabled = %d", currentVao_, index, vaos_[currentVao_].attribs[index].enabled);
GetCurrentVAO()->attribDirty = true;
return GL_NO_ERROR;
}
GLenum VertexArrayState::SetAttribPointer(GLuint index, GLint size, GLenum type,
GLboolean normalized, GLsizei stride,
const void* pointer, bool isInteger,
GLuint currentArrayBuffer) {
if (!ValidateAllocatedHandle(currentVao_))
return GL_INVALID_OPERATION;
if (index >= GL_MAX_VERTEX_ATTRIBS) return GL_INVALID_VALUE;
VertexAttribState state;
state.size = size;
state.type = type;
state.normalized = normalized;
state.stride = stride;
state.pointer = pointer;
state.buffer = currentArrayBuffer;
state.isInteger = isInteger;
if (vaos_[currentVao_].attribs.count(index) && vaos_[currentVao_].attribs[index].enabled)
state.enabled = true;
vaos_[currentVao_].attribs[index] = state;
GetCurrentVAO()->attribDirty = true;
return GL_NO_ERROR;
}
GLuint VertexArrayState::GetBoundElementBuffer() {
auto it = vaos_.find(currentVao_);
return (it != vaos_.end()) ? it->second.elementBuffer : 0;
}
VertexArrayObject* VertexArrayState::GetCurrentVAO() {
auto it = vaos_.find(currentVao_);
return (it != vaos_.end()) ? &it->second : &vaos_.at(0);
}
@@ -1,59 +0,0 @@
//
// Created by BZLZHH on 2025/5/1.
//
#ifndef MOBILEGL_VERTEXARRAYSTATE_H
#define MOBILEGL_VERTEXARRAYSTATE_H
#define MOBILEGL_GLSTATE_H
#include "../../../Includes.h"
struct VertexAttribState {
bool enabled;
GLint size = 4;
GLenum type = GL_FLOAT;
GLboolean normalized = GL_FALSE;
GLsizei stride = 0;
const GLvoid* pointer = nullptr;
GLuint buffer = 0;
bool isInteger = false;
};
struct VertexArrayObject {
bool generated = false;
bool attribDirty = false;
bool eboDirty = false;
GLuint elementBuffer = 0;
ankerl::unordered_map<GLuint, VertexAttribState> attribs;
};
class VertexArrayState {
public:
VertexArrayState();
// Return: the validity of the operation, according to OpenGL 3 standard
GLenum GenName(GLuint* array);
GLenum GenNameN(GLsizei n, GLuint* arrays);
GLenum Create(GLuint* array);
GLenum CreateN(GLsizei n, GLuint* arrays);
GLenum Bind(GLuint array);
GLenum EnableAttrib(GLuint index);
GLenum DisableAttrib(GLuint index);
GLenum SetAttribPointer(GLuint index, GLint size, GLenum type,
GLboolean normalized, GLsizei stride,
const void* pointer, bool isInteger,
GLuint currentArrayBuffer);
GLuint GetBoundElementBuffer();
VertexArrayObject* GetCurrentVAO();
bool ValidateGeneratedName(GLuint array);
bool ValidateAllocatedHandle(GLuint array);
GLuint currentVao_ = 0;
ankerl::unordered_map<GLuint, VertexArrayObject> vaos_;
private:
std::set<GLuint> freeIds_;
GLuint lastId_ = 0;
};
#endif //MOBILEGL_VERTEXARRAYSTATE_H
-127
View File
@@ -1,127 +0,0 @@
//
// Created by BZLZHH on 2025/5/3.
//
#pragma once
#include <initializer_list>
#include <stdexcept>
#include <utility>
class UncertainBool {
public:
enum Value { False = 0, True = 1, Unknown = 2 };
UncertainBool() : value_(False), default_(false) {}
explicit UncertainBool(bool b) : value_(b ? True : False), default_(false) {}
UncertainBool(Value val, bool def) : value_(val), default_(def) {
validateValue();
}
UncertainBool(bool val, bool def) : value_(val ? True : False), default_(def) {
validateValue();
}
UncertainBool& operator=(Value val) {
value_ = val;
validateValue();
return *this;
}
UncertainBool& operator=(bool b) {
value_ = b ? True : False;
return *this;
}
UncertainBool& operator=(std::initializer_list<std::pair<bool, bool>> init) {
if (init.size() != 1) throw std::invalid_argument("Invalid initializer");
value_ = init.begin()->first ? True : False;
default_ = init.begin()->second;
return *this;
}
explicit operator bool() const {
return toBool();
}
bool toBool() const {
if (value_ == True) return true;
else if (value_ == False) return false;
else return default_;
}
UncertainBool operator!() const {
return {static_cast<bool>(*this) ? False : True, false};
}
bool operator==(const UncertainBool& rhs) const {
return static_cast<bool>(*this) == static_cast<bool>(rhs);
}
bool operator!=(const UncertainBool& rhs) const { return !(*this == rhs); }
friend UncertainBool operator&&(const UncertainBool& lhs, const UncertainBool& rhs) {
bool actualDefault = lhs.default_ && rhs.default_;
if(lhs.value_ == False || rhs.value_ == False) return {False,actualDefault};
else if(lhs.value_ == True && rhs.value_ == True) return {True,actualDefault};
else return {Unknown, actualDefault};
}
friend UncertainBool operator||(const UncertainBool& lhs, const UncertainBool& rhs) {
bool actualDefault = lhs.default_ || rhs.default_;
if(lhs.value_ == True || rhs.value_ == True) return {True,actualDefault};
else if(lhs.value_ == False && rhs.value_ == False) return {False,actualDefault};
else return {Unknown, actualDefault};
}
friend UncertainBool operator&&(bool lhs,const UncertainBool& rhs){
return UncertainBool(lhs, lhs) && rhs;
}
friend UncertainBool operator||(bool lhs,const UncertainBool& rhs){
return UncertainBool(lhs, lhs) || rhs;
}
UncertainBool& operator&=(const UncertainBool& rhs) {
*this = *this && rhs;
return *this;
}
UncertainBool& operator|=(const UncertainBool& rhs) {
*this = *this || rhs;
return *this;
}
UncertainBool& operator=(std::initializer_list<std::pair<Value, bool>> init) {
if (init.size() != 1) throw std::invalid_argument("Invalid initializer");
value_ = init.begin()->first;
default_ = init.begin()->second;
validateValue();
return *this;
}
Value getValue() const { return value_; }
bool getDefault() const { return default_; }
private:
Value value_;
bool default_;
void validateValue() {
if (value_ != False && value_ != True && value_ != Unknown) {
throw std::invalid_argument("Invalid value");
}
}
};
inline UncertainBool operator!(const UncertainBool& lhs) {
return lhs.operator!();
}
inline bool operator==(bool lhs, const UncertainBool& rhs) {
return static_cast<bool>(rhs) == lhs;
}
inline bool operator!=(bool lhs, const UncertainBool& rhs) {
return !(lhs == rhs);
}
-234
View File
@@ -1,234 +0,0 @@
//
// Created by BZLZHH on 2025/4/26.
//
#include "TestDrawing.h"
namespace MG_RHI::GLES::Test {
constexpr int DISPLAY_COLUMNS = 8;
constexpr int DISPLAY_ROWS = 10;
constexpr int MAX_DISPLAY_TEXTURES = DISPLAY_COLUMNS * DISPLAY_ROWS;
bool IsTextureComplete(const TextureObject& tex) {
return !tex.params.mipmapData.empty();
}
bool CheckShaderCompileStatus(GLuint shader, const char* type) {
GLint success;
::GLES::glGetShaderiv(shader, GL_COMPILE_STATUS, &success);
if (!success) {
GLchar infoLog[512];
::GLES::glGetShaderInfoLog(shader, 512, NULL, infoLog);
MG_Util::Debug::LogE("Shader compilation error (%s): %s", type, infoLog);
return false;
}
return true;
}
bool CheckProgramLinkStatus(GLuint program) {
GLint success;
::GLES::glGetProgramiv(program, GL_LINK_STATUS, &success);
if (!success) {
GLchar infoLog[512];
::GLES::glGetProgramInfoLog(program, 512, NULL, infoLog);
MG_Util::Debug::LogE("Program link error: %s", infoLog);
return false;
}
return true;
}
// TODO: Use the textures state from MG_RHI(another state?) rather than directly from MG_State
void DrawAllTextures() {
::GLES::glClearColor(1,1,1,1);
::GLES::glClear(GL_COLOR_BUFFER_BIT);
struct ScreenResources {
GLuint program = 0;
GLuint quadVAO = 0;
GLuint quadVBO = 0;
GLint uTexLoc = -1;
GLint uMVPLoc = -1;
ankerl::unordered_map<GLuint, GLuint> textureCache;
ankerl::unordered_map<GLuint, bool> textureDirty;
};
static ScreenResources sRes;
static glm::ivec2 lastScreenSize{0, 0};
GLint viewport[4];
::GLES::glGetIntegerv(GL_VIEWPORT, viewport);
const glm::ivec2 screenSize(viewport[2], viewport[3]);
if (screenSize != lastScreenSize) {
if (sRes.quadVAO) {
::GLES::glDeleteVertexArrays(1, &sRes.quadVAO);
::GLES::glDeleteBuffers(1, &sRes.quadVBO);
sRes.quadVAO = sRes.quadVBO = 0;
}
lastScreenSize = screenSize;
}
if (!sRes.program) {
const char* vsSrc = R"(#version 320 es
layout(location=0) in vec2 aPos;
layout(location=1) in vec2 aTexUV;
out vec2 vUV;
uniform mat4 uMVP;
void main() {
gl_Position = uMVP * vec4(aPos, 0.0, 1.0);
vUV = aTexUV;
})";
const char* fsSrc = R"(#version 320 es
precision mediump float;
in vec2 vUV;
uniform sampler2D uTex;
out vec4 FragColor;
void main() {
FragColor = texture(uTex, vUV);
})";
GLuint vs = ::GLES::glCreateShader(GL_VERTEX_SHADER);
::GLES::glShaderSource(vs, 1, &vsSrc, NULL);
::GLES::glCompileShader(vs);
if (!CheckShaderCompileStatus(vs, "vertex")) return;
GLuint fs = ::GLES::glCreateShader(GL_FRAGMENT_SHADER);
::GLES::glShaderSource(fs, 1, &fsSrc, NULL);
::GLES::glCompileShader(fs);
if (!CheckShaderCompileStatus(fs, "fragment")) return;
sRes.program = ::GLES::glCreateProgram();
::GLES::glAttachShader(sRes.program, vs);
::GLES::glAttachShader(sRes.program, fs);
::GLES::glLinkProgram(sRes.program);
if (!CheckProgramLinkStatus(sRes.program)) return;
sRes.uTexLoc = ::GLES::glGetUniformLocation(sRes.program, "uTex");
sRes.uMVPLoc = ::GLES::glGetUniformLocation(sRes.program, "uMVP");
::GLES::glDeleteShader(vs);
::GLES::glDeleteShader(fs);
}
if (!sRes.quadVAO) {
const float margin = 0.01f;
const float gridWidth = (2.0f - 2*margin) / DISPLAY_COLUMNS;
const float gridHeight = (2.0f - 2*margin) / DISPLAY_ROWS;
std::vector<float> vertices;
vertices.reserve(MAX_DISPLAY_TEXTURES * 16);
for (int col = 0; col < DISPLAY_COLUMNS; ++col) {
for (int row = 0; row < DISPLAY_ROWS; ++row) {
const float xStart = -1.0f + margin + col * gridWidth;
const float yStart = -1.0f + margin + row * gridHeight;
const float xEnd = xStart + gridWidth - margin;
const float yEnd = yStart + gridHeight - margin;
vertices.insert(vertices.end(), {
xStart, yStart, 0.0f, 0.0f,
xEnd, yStart, 1.0f, 0.0f,
xEnd, yEnd, 1.0f, 1.0f,
xStart, yEnd, 0.0f, 1.0f
});
}
}
::GLES::glGenVertexArrays(1, &sRes.quadVAO);
::GLES::glGenBuffers(1, &sRes.quadVBO);
::GLES::glBindVertexArray(sRes.quadVAO);
::GLES::glBindBuffer(GL_ARRAY_BUFFER, sRes.quadVBO);
::GLES::glBufferData(GL_ARRAY_BUFFER,
vertices.size() * sizeof(float),
vertices.data(),
GL_STATIC_DRAW
);
::GLES::glEnableVertexAttribArray(0);
::GLES::glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE,
4 * sizeof(float), (void*)0
);
::GLES::glEnableVertexAttribArray(1);
::GLES::glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE,
4 * sizeof(float), (void*)(2 * sizeof(float))
);
::GLES::glBindVertexArray(0);
}
std::vector<std::pair<GLuint, TextureObject*>> sortedTextures;
for (auto&& [stateID, texObj] : MG_State_T::textureState->textures) {
if (!texObj.generated || texObj.target != GL_TEXTURE_2D) continue;
if (texObj.params.mipmapData.empty()) continue;
sortedTextures.emplace_back(stateID, &texObj);
}
std::sort(sortedTextures.begin(), sortedTextures.end(),
[](auto& a, auto& b) {
return a.second->createTimestamp > b.second->createTimestamp;
}
);
sortedTextures.resize(std::min<size_t>(sortedTextures.size(), MAX_DISPLAY_TEXTURES));
for (auto&& [stateID, texObj] : sortedTextures) {
auto& dirtyFlag = sRes.textureDirty[stateID];
bool needCreate = !sRes.textureCache.count(stateID);
if (needCreate) {
GLuint glTexID;
::GLES::glGenTextures(1, &glTexID);
sRes.textureCache[stateID] = glTexID;
dirtyFlag = true;
}
if (dirtyFlag || needCreate) {
const auto& mip0 = texObj->params.mipmapData.begin()->second;
if (mip0.hasData) {
GLuint glTexID = sRes.textureCache[stateID];
::GLES::glBindTexture(GL_TEXTURE_2D, glTexID);
::GLES::glTexImage2D(GL_TEXTURE_2D, 0, mip0.internalFormat,
mip0.width, mip0.height, 0,
mip0.format, mip0.type, mip0.pixelData.data()
);
::GLES::glTexParameteri(GL_TEXTURE_2D,
GL_TEXTURE_MIN_FILTER, GL_LINEAR);
::GLES::glTexParameteri(GL_TEXTURE_2D,
GL_TEXTURE_MAG_FILTER, GL_LINEAR);
::GLES::glTexParameteri(GL_TEXTURE_2D,
GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
::GLES::glTexParameteri(GL_TEXTURE_2D,
GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
if (texObj->params.mipmapData.size() > 1) {
::GLES::glGenerateMipmap(GL_TEXTURE_2D);
}
dirtyFlag = false;
}
}
}
GLboolean origDepthTest = ::GLES::glIsEnabled(GL_DEPTH_TEST);
GLint origProgram, origViewport[4];
::GLES::glGetIntegerv(GL_VIEWPORT, origViewport);
::GLES::glGetIntegerv(GL_CURRENT_PROGRAM, &origProgram);
::GLES::glDisable(GL_DEPTH_TEST);
::GLES::glUseProgram(sRes.program);
::GLES::glUniformMatrix4fv(sRes.uMVPLoc, 1, GL_FALSE,
&glm::mat4(1.0f)[0][0]
);
::GLES::glUniform1i(sRes.uTexLoc, 0);
::GLES::glBindVertexArray(sRes.quadVAO);
for (size_t i = 0; i < sortedTextures.size(); ++i) {
const GLuint glTexID = sRes.textureCache[sortedTextures[i].first];
::GLES::glActiveTexture(GL_TEXTURE0);
::GLES::glBindTexture(GL_TEXTURE_2D, glTexID);
::GLES::glDrawArrays(GL_TRIANGLE_FAN, static_cast<GLint>(i*4), 4);
}
if (origDepthTest) ::GLES::glEnable(GL_DEPTH_TEST);
::GLES::glUseProgram(origProgram);
::GLES::glViewport(origViewport[0], origViewport[1],
origViewport[2], origViewport[3]);
}
}
-14
View File
@@ -1,14 +0,0 @@
//
// Created by BZLZHH on 2025/4/26.
//
#ifndef MOBILEGL_TESTDRAWING_H
#define MOBILEGL_TESTDRAWING_H
#include "../../../Includes.h"
namespace MG_RHI::GLES::Test {
void DrawAllTextures();
}
#endif //MOBILEGL_TESTDRAWING_H
File diff suppressed because it is too large Load Diff
-31
View File
@@ -1,31 +0,0 @@
//
// Created by BZLZHH on 2025/1/26.
//
#ifndef MOBILEGL_DEBUG_H
#define MOBILEGL_DEBUG_H
#include "../../Includes.h"
#define FORCE_SYNC_WITH_LOG_FILE 0
namespace MG_Util {
namespace Debug {
const char* GetOSName();
void LogD (const char* format, ...);
void LogW (const char* format, ...);
void LogE (const char* format, ...);
void LogI (const char* format, ...);
void LogF (const char* format, ...);
void LogClear();
void LogInit();
void LogWrite(const char* format, va_list args);
const char* GLEnumToString(::GLenum value);
}
}
#define MOBILEGL_DEBUG_H
#endif //MOBILEGL_DEBUG_H
-150
View File
@@ -1,150 +0,0 @@
//
// Created by BZLZHH on 2025/5/3.
//
#include "DebugTool.h"
namespace MG_Util::Program {
std::string GLTypeToString(GLenum type) {
switch(type) {
case GL_FLOAT: return "float";
case GL_FLOAT_VEC2: return "vec2";
case GL_FLOAT_VEC3: return "vec3";
case GL_FLOAT_VEC4: return "vec4";
case GL_INT: return "int";
case GL_INT_VEC2: return "ivec2";
case GL_INT_VEC3: return "ivec3";
case GL_INT_VEC4: return "ivec4";
case GL_UNSIGNED_INT: return "uint";
case GL_UNSIGNED_INT_VEC2: return "uvec2";
case GL_UNSIGNED_INT_VEC3: return "uvec3";
case GL_UNSIGNED_INT_VEC4: return "uvec4";
case GL_BOOL: return "bool";
case GL_BOOL_VEC2: return "bvec2";
case GL_BOOL_VEC3: return "bvec3";
case GL_BOOL_VEC4: return "bvec4";
case GL_FLOAT_MAT2: return "mat2";
case GL_FLOAT_MAT3: return "mat3";
case GL_FLOAT_MAT4: return "mat4";
case GL_FLOAT_MAT2x3: return "mat2x3";
case GL_FLOAT_MAT2x4: return "mat2x4";
case GL_FLOAT_MAT3x2: return "mat3x2";
case GL_FLOAT_MAT3x4: return "mat3x4";
case GL_FLOAT_MAT4x2: return "mat4x2";
case GL_FLOAT_MAT4x3: return "mat4x3";
case GL_SAMPLER_1D: return "sampler1D";
case GL_SAMPLER_2D: return "sampler2D";
case GL_SAMPLER_3D: return "sampler3D";
case GL_SAMPLER_CUBE: return "samplerCube";
case GL_SAMPLER_1D_SHADOW: return "sampler1DShadow";
case GL_SAMPLER_2D_SHADOW: return "sampler2DShadow";
case GL_SAMPLER_CUBE_SHADOW: return "samplerCubeShadow";
case GL_SAMPLER_1D_ARRAY: return "sampler1DArray";
case GL_SAMPLER_2D_ARRAY: return "sampler2DArray";
case GL_SAMPLER_1D_ARRAY_SHADOW: return "sampler1DArrayShadow";
case GL_SAMPLER_2D_ARRAY_SHADOW: return "sampler2DArrayShadow";
case GL_SAMPLER_BUFFER: return "samplerBuffer";
case GL_SAMPLER_2D_MULTISAMPLE: return "sampler2DMS";
case GL_SAMPLER_2D_MULTISAMPLE_ARRAY: return "sampler2DMSArray";
default: return "UnknownType(0x" + std::to_string(type) + ")";
}
}
std::string FormatUniformValue(const UniformValue& value) {
std::ostringstream ss;
ss << "[";
const size_t elemCount = std::min<size_t>(value.count, 16);
switch(value.type) {
case GL_FLOAT:
case GL_FLOAT_VEC2:
case GL_FLOAT_VEC3:
case GL_FLOAT_VEC4:
case GL_FLOAT_MAT2:
case GL_FLOAT_MAT3:
case GL_FLOAT_MAT4:
case GL_FLOAT_MAT2x3:
case GL_FLOAT_MAT2x4:
case GL_FLOAT_MAT3x2:
case GL_FLOAT_MAT3x4:
case GL_FLOAT_MAT4x2:
case GL_FLOAT_MAT4x3:
for(size_t i=0; i<elemCount; ++i) {
if (i > 0) ss << ", ";
ss << (i < value.floatData.size() ? value.floatData[i] : 0.0f);
}
break;
case GL_INT:
case GL_INT_VEC2:
case GL_INT_VEC3:
case GL_INT_VEC4:
for(size_t i=0; i<elemCount; ++i) {
if (i > 0) ss << ", ";
ss << (i < value.intData.size() ? value.intData[i] : 0);
}
break;
case GL_UNSIGNED_INT:
case GL_UNSIGNED_INT_VEC2:
case GL_UNSIGNED_INT_VEC3:
case GL_UNSIGNED_INT_VEC4:
for(size_t i=0; i<elemCount; ++i) {
if (i > 0) ss << ", ";
ss << (i < value.uintData.size() ? value.uintData[i] : 0);
}
break;
case GL_BOOL:
case GL_BOOL_VEC2:
case GL_BOOL_VEC3:
case GL_BOOL_VEC4:
for(size_t i=0; i<elemCount; ++i) {
if (i > 0) ss << ", ";
ss << (i < value.boolData.size() ? (value.boolData[i] ? "true" : "false") : "false");
}
break;
default:
ss << "N/A";
}
if (value.count > elemCount) ss << ", ...";
ss << "]";
return ss.str();
}
void DumpUniforms(const ProgramState& state, GLuint program) {
if (MG_Global::Common::LogLevel > MG_Constants::Common::LOG_LEVEL_DEBUG)
return;
auto prog = (ProgramObject)state.GetProgramObject(program);
if (!prog.linked.toBool()) {
MG_Util::Debug::LogE("Program %u not linked", program);
return;
}
MG_Util::Debug::LogD("=== Dumping uniforms for program %u ===", program);
for(const auto& [name, loc] : prog.uniformLocations) {
const auto& value = prog.uniformValues.at(name);
MG_Util::Debug::LogD("Uniform: %-24s Location: %-4d Type: %-16s Count: %-3d Value: %s",
name.c_str(),
loc,
GLTypeToString(value.type).c_str(),
value.count,
FormatUniformValue(value).c_str());
}
}
void DumpCurrentUniforms(const ProgramState& state) {
if (MG_Global::Common::LogLevel > MG_Constants::Common::LOG_LEVEL_DEBUG)
return;
GLuint current = state.GetCurrentProgram();
if (current == 0) {
MG_Util::Debug::LogE("No active program");
return;
}
DumpUniforms(state, current);
}
}
-16
View File
@@ -1,16 +0,0 @@
//
// Created by BZLZHH on 2025/5/3.
//
#ifndef MOBILEGL_PROGRAM_DEBUGTOOL_H
#define MOBILEGL_PROGRAM_DEBUGTOOL_H
#include "../../Includes.h"
namespace MG_Util::Program {
std::string GLTypeToString(GLenum type);
std::string FormatUniformValue(const UniformValue& value);
void DumpUniforms(const ProgramState& state, GLuint program);
void DumpCurrentUniforms(const ProgramState& state);
}
#endif //MOBILEGL_PROGRAM_DEBUGTOOL_H
-438
View File
@@ -1,438 +0,0 @@
//
// Created by BZLZHH on 2025/5/3.
//
#include "GLSLTool.h"
namespace MG_Util::Program {
std::string CompileGLSLToTShader(GLenum shaderType, const std::string& source, glslang::TShader *&shader) {
std::string infoLog;
using namespace glslang;
int glslVersion = QueryGLSLVersion(source);
EShLanguage language = GetEShLanguageByShaderType(shaderType);
if (language == EShLanguage::EShLangCount) {
infoLog += "Error: [Preprocess] Unsupported shader type: " +
std::to_string(shaderType);
TShader tmpShader(EShLanguage::EShLangVertex);
return infoLog;
}
shader = new TShader(language);
const char *src = source.c_str();
shader->setStrings(&src, 1);
shader->setEnvInput(EShSourceGlsl, language, EShClientVulkan, glslVersion);
shader->setEnvClient(EShClientOpenGL, EShTargetOpenGL_450);
shader->setEnvTarget(EShTargetSpv, EShTargetSpv_1_6);
shader->setAutoMapLocations(true);
shader->setAutoMapBindings(true);
// Is InitResources() really correct?
TBuiltInResource resources = InitResources();
if (!shader->parse(&resources, glslVersion, true, EShMsgDefault)) {
infoLog += "Error: [glslang] Cannot compile the " + GetShaderTypeName(shaderType) + ":\n"
+ std::to_string(shader->getInfoLog());
return infoLog;
}
return {};
}
std::vector<std::vector<unsigned>> CompileMultipleShadersToSPIRV(const ProgramState& state, ProgramObject& prog, std::string& infoLog) {
using namespace glslang;
std::vector<EShLanguage> usedShaderTypes;
TProgram program;
for (GLuint shaderId : prog.attachedShaders) {
auto shaderObject = state.GetShaderObject(shaderId);
EShLanguage shLanguage = GetEShLanguageByShaderType(shaderObject.type);
TShader* shader = nullptr;
std::string infoLogOfShader = CompileGLSLToTShader(shaderObject.type, shaderObject.source, shader);
if (!infoLogOfShader.empty()) {
infoLog = "Error: [glslang] Cannot compile " + GetShaderTypeName(shaderObject.type) +
" :\n" + infoLogOfShader;
return {};
}
program.addShader(shader);
usedShaderTypes.push_back(shLanguage);
}
if (!program.link(EShMsgDefault)) {
infoLog = "Error: [glslang] Cannot link the program:\n" + std::to_string(program.getInfoLog());
return {};
}
SpvOptions spvOptions;
spvOptions.disableOptimizer = false;
std::vector<std::vector<unsigned>> allSpirv;
for(auto type : usedShaderTypes) {
std::vector<unsigned> spirv;
GlslangToSpv(*program.getIntermediate(type), spirv, &spvOptions);
allSpirv.push_back(spirv);
}
return allSpirv;
}
std::vector<unsigned> CompileGLSLToSPIRV(GLenum shaderType, const std::string &source, std::string &infoLog) {
using namespace glslang;
TShader* shader = nullptr;
std::string infoLogOfShader = CompileGLSLToTShader(shaderType, source, shader);
if (!infoLogOfShader.empty()) {
infoLog = "Error: [glslang] Cannot compile " + GetShaderTypeName(shaderType) + ":\n" + infoLogOfShader;
return {};
}
TProgram program;
program.addShader(shader);
if (!program.link(EShMsgDefault)) {
infoLog = "Error: [glslang] Cannot link the program of the single shader:\n" + std::to_string(program.getInfoLog());
return {};
}
std::vector<unsigned> spirv;
SpvOptions spvOptions;
spvOptions.disableOptimizer = false;
EShLanguage language = GetEShLanguageByShaderType(shaderType);
GlslangToSpv(*program.getIntermediate(language), spirv, &spvOptions);
return spirv;
}
void ReflectSPIRVUniforms(const std::vector<std::vector<unsigned>>& allSpirv, ProgramObject& prog, std::string& infoLog) {
spvc_context context = nullptr;
if (spvc_context_create(&context) != SPVC_SUCCESS) {
infoLog = "Failed to create SPIRV-Cross context";
return;
}
ankerl::unordered_set<GLint> used_locations;
GLint auto_location = 0;
for (auto spirv: allSpirv) {
spvc_parsed_ir ir = nullptr;
spvc_compiler compiler = nullptr;
spvc_resources resources = nullptr;
spvc_result result = spvc_context_parse_spirv(context, spirv.data(), spirv.size(), &ir);
if (result != SPVC_SUCCESS) {
infoLog = "SPIR-V parsing failed";
spvc_context_destroy(context);
return;
}
result = spvc_context_create_compiler(context, SPVC_BACKEND_GLSL, ir,
SPVC_CAPTURE_MODE_TAKE_OWNERSHIP, &compiler);
if (result != SPVC_SUCCESS) {
infoLog = "Failed to create SPIRV-Cross compiler";
spvc_context_destroy(context);
return;
}
result = spvc_compiler_create_shader_resources(compiler, &resources);
if (result != SPVC_SUCCESS) {
infoLog = "Failed to get shader resources";
spvc_context_destroy(context);
return;
}
const spvc_reflected_resource *uniform_buffers = nullptr;
const spvc_reflected_resource *uniform_vars = nullptr;
const spvc_reflected_resource *sampled_images = nullptr;
size_t uniform_buffer_count = 0;
size_t uniform_var_count = 0;
size_t sampled_image_count = 0;
spvc_resources_get_resource_list_for_type(resources, SPVC_RESOURCE_TYPE_UNIFORM_BUFFER,
&uniform_buffers, &uniform_buffer_count);
spvc_resources_get_resource_list_for_type(resources,
SPVC_RESOURCE_TYPE_GL_PLAIN_UNIFORM,
&uniform_vars, &uniform_var_count);
spvc_resources_get_resource_list_for_type(resources, SPVC_RESOURCE_TYPE_SAMPLED_IMAGE,
&sampled_images, &sampled_image_count);
std::vector<const spvc_reflected_resource *> all_resources;
for (size_t i = 0; i < uniform_buffer_count; ++i)
all_resources.push_back(&uniform_buffers[i]);
for (size_t i = 0; i < uniform_var_count; ++i)
all_resources.push_back(&uniform_vars[i]);
for (size_t i = 0; i < sampled_image_count; ++i)
all_resources.push_back(&sampled_images[i]);
for (const auto res_ptr: all_resources) {
const spvc_reflected_resource &res = *res_ptr;
const char *name = res.name;
if (name[0] == '_') continue;
unsigned spirv_location = spvc_compiler_get_decoration(compiler, res.id,
SpvDecorationLocation);
GLint final_location;
if (spirv_location > 0) {
if (used_locations.find(spirv_location) != used_locations.end()) {
infoLog += "\nLocation conflict for uniform: " + std::string(name);
continue;
}
final_location = spirv_location;
} else {
while (used_locations.find(auto_location) != used_locations.end()) {
auto_location++;
}
final_location = auto_location;
}
used_locations.insert(final_location);
spvc_type_id type_id = res.type_id;
spvc_type type = spvc_compiler_get_type_handle(compiler, type_id);
spvc_basetype base_type = spvc_type_get_basetype(type);
GLenum gl_type = GL_NONE;
if (base_type == SPVC_BASETYPE_SAMPLED_IMAGE) {
SpvDim dim = spvc_type_get_image_dimension(type);
bool is_array = spvc_type_get_image_arrayed(type);
bool is_shadow = spvc_type_get_image_is_depth(type);
bool is_ms = spvc_type_get_image_multisampled(type);
switch (dim) {
case SpvDim1D:
gl_type = is_array ? GL_SAMPLER_1D_ARRAY : GL_SAMPLER_1D;
if (is_shadow)
gl_type = is_array ? GL_SAMPLER_1D_ARRAY_SHADOW
: GL_SAMPLER_1D_SHADOW;
break;
case SpvDim2D:
if (is_ms) {
gl_type = is_array ? GL_SAMPLER_2D_MULTISAMPLE_ARRAY
: GL_SAMPLER_2D_MULTISAMPLE;
} else {
gl_type = is_array ? GL_SAMPLER_2D_ARRAY : GL_SAMPLER_2D;
if (is_shadow)
gl_type = is_array ? GL_SAMPLER_2D_ARRAY_SHADOW
: GL_SAMPLER_2D_SHADOW;
}
break;
case SpvDim3D:
gl_type = GL_SAMPLER_3D;
break;
case SpvDimCube:
gl_type = is_array ? GL_SAMPLER_CUBE_MAP_ARRAY : GL_SAMPLER_CUBE;
if (is_shadow)
gl_type = is_array ? GL_SAMPLER_CUBE_MAP_ARRAY_SHADOW
: GL_SAMPLER_CUBE_SHADOW;
break;
case SpvDimRect:
gl_type = is_shadow ? GL_SAMPLER_2D_RECT_SHADOW : GL_SAMPLER_2D_RECT;
break;
case SpvDimBuffer:
gl_type = GL_SAMPLER_BUFFER;
break;
default:
gl_type = GL_SAMPLER_2D;
}
spvc_basetype sampled_base = spvc_type_get_basetype(type);
if (sampled_base == SPVC_BASETYPE_INT32) {
switch (gl_type) {
case GL_SAMPLER_1D:
gl_type = GL_INT_SAMPLER_1D;
break;
case GL_SAMPLER_2D:
gl_type = GL_INT_SAMPLER_2D;
break;
case GL_SAMPLER_3D:
gl_type = GL_INT_SAMPLER_3D;
break;
case GL_SAMPLER_CUBE:
gl_type = GL_INT_SAMPLER_CUBE;
break;
case GL_SAMPLER_1D_ARRAY:
gl_type = GL_INT_SAMPLER_1D_ARRAY;
break;
case GL_SAMPLER_2D_ARRAY:
gl_type = GL_INT_SAMPLER_2D_ARRAY;
break;
case GL_SAMPLER_CUBE_MAP_ARRAY:
gl_type = GL_INT_SAMPLER_CUBE_MAP_ARRAY;
break;
case GL_SAMPLER_2D_RECT:
gl_type = GL_INT_SAMPLER_2D_RECT;
break;
case GL_SAMPLER_BUFFER:
gl_type = GL_INT_SAMPLER_BUFFER;
break;
case GL_SAMPLER_2D_MULTISAMPLE:
gl_type = GL_INT_SAMPLER_2D_MULTISAMPLE;
break;
case GL_SAMPLER_2D_MULTISAMPLE_ARRAY:
gl_type = GL_INT_SAMPLER_2D_MULTISAMPLE_ARRAY;
break;
}
} else if (sampled_base == SPVC_BASETYPE_UINT32) {
switch (gl_type) {
case GL_SAMPLER_1D:
gl_type = GL_UNSIGNED_INT_SAMPLER_1D;
break;
case GL_SAMPLER_2D:
gl_type = GL_UNSIGNED_INT_SAMPLER_2D;
break;
case GL_SAMPLER_3D:
gl_type = GL_UNSIGNED_INT_SAMPLER_3D;
break;
case GL_SAMPLER_CUBE:
gl_type = GL_UNSIGNED_INT_SAMPLER_CUBE;
break;
case GL_SAMPLER_1D_ARRAY:
gl_type = GL_UNSIGNED_INT_SAMPLER_1D_ARRAY;
break;
case GL_SAMPLER_2D_ARRAY:
gl_type = GL_UNSIGNED_INT_SAMPLER_2D_ARRAY;
break;
case GL_SAMPLER_CUBE_MAP_ARRAY:
gl_type = GL_UNSIGNED_INT_SAMPLER_CUBE_MAP_ARRAY;
break;
case GL_SAMPLER_2D_RECT:
gl_type = GL_UNSIGNED_INT_SAMPLER_2D_RECT;
break;
case GL_SAMPLER_BUFFER:
gl_type = GL_UNSIGNED_INT_SAMPLER_BUFFER;
break;
case GL_SAMPLER_2D_MULTISAMPLE:
gl_type = GL_UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE;
break;
case GL_SAMPLER_2D_MULTISAMPLE_ARRAY:
gl_type = GL_UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE_ARRAY;
break;
}
}
} else {
unsigned vec_size = spvc_type_get_vector_size(type);
unsigned columns = spvc_type_get_columns(type);
switch (base_type) {
case SPVC_BASETYPE_FP32:
if (columns > 1) {
if (vec_size == 2 && columns == 2) gl_type = GL_FLOAT_MAT2;
else if (vec_size == 3 && columns == 3) gl_type = GL_FLOAT_MAT3;
else if (vec_size == 4 && columns == 4) gl_type = GL_FLOAT_MAT4;
else if (vec_size == 3 && columns == 2) gl_type = GL_FLOAT_MAT2x3;
else if (vec_size == 4 && columns == 2) gl_type = GL_FLOAT_MAT2x4;
else if (vec_size == 2 && columns == 3) gl_type = GL_FLOAT_MAT3x2;
else if (vec_size == 4 && columns == 3) gl_type = GL_FLOAT_MAT3x4;
else if (vec_size == 2 && columns == 4) gl_type = GL_FLOAT_MAT4x2;
else if (vec_size == 3 && columns == 4) gl_type = GL_FLOAT_MAT4x3;
} else {
switch (vec_size) {
case 1:
gl_type = GL_FLOAT;
break;
case 2:
gl_type = GL_FLOAT_VEC2;
break;
case 3:
gl_type = GL_FLOAT_VEC3;
break;
case 4:
gl_type = GL_FLOAT_VEC4;
break;
}
}
break;
case SPVC_BASETYPE_INT32:
switch (vec_size) {
case 1:
gl_type = GL_INT;
break;
case 2:
gl_type = GL_INT_VEC2;
break;
case 3:
gl_type = GL_INT_VEC3;
break;
case 4:
gl_type = GL_INT_VEC4;
break;
}
break;
case SPVC_BASETYPE_UINT32:
switch (vec_size) {
case 1:
gl_type = GL_UNSIGNED_INT;
break;
case 2:
gl_type = GL_UNSIGNED_INT_VEC2;
break;
case 3:
gl_type = GL_UNSIGNED_INT_VEC3;
break;
case 4:
gl_type = GL_UNSIGNED_INT_VEC4;
break;
}
break;
case SPVC_BASETYPE_BOOLEAN:
switch (vec_size) {
case 1:
gl_type = GL_BOOL;
break;
case 2:
gl_type = GL_BOOL_VEC2;
break;
case 3:
gl_type = GL_BOOL_VEC3;
break;
case 4:
gl_type = GL_BOOL_VEC4;
break;
}
break;
default:
continue;
}
}
prog.uniformLocations[name] = final_location;
UniformValue uniformValue;
uniformValue.type = gl_type;
prog.uniformValues[name] = uniformValue;
}
}
spvc_context_destroy(context);
}
std::string CompileSPIRVToGLSL(std::vector<unsigned int> spirv, uint glslVersion, bool isES) {
spvc_context context = nullptr;
spvc_parsed_ir ir = nullptr;
spvc_compiler compiler_glsl = nullptr;
spvc_compiler_options options = nullptr;
spvc_resources resources = nullptr;
const spvc_reflected_resource *list = nullptr;
const char *result = nullptr;
size_t count;
const SpvId *p_spirv = spirv.data();
size_t word_count = spirv.size();
spvc_context_create(&context);
spvc_context_parse_spirv(context, p_spirv, word_count, &ir);
spvc_context_create_compiler(context, SPVC_BACKEND_GLSL, ir, SPVC_CAPTURE_MODE_TAKE_OWNERSHIP, &compiler_glsl);
spvc_compiler_create_shader_resources(compiler_glsl, &resources);
spvc_resources_get_resource_list_for_type(resources, SPVC_RESOURCE_TYPE_UNIFORM_BUFFER, &list, &count);
spvc_compiler_create_compiler_options(compiler_glsl, &options);
spvc_compiler_options_set_uint(options, SPVC_COMPILER_OPTION_GLSL_VERSION, glslVersion);
spvc_compiler_options_set_bool(options, SPVC_COMPILER_OPTION_GLSL_ES, isES ? SPVC_TRUE : SPVC_FALSE);
spvc_compiler_install_compiler_options(compiler_glsl, options);
spvc_compiler_compile(compiler_glsl, &result);
if (!result) {
return{};
}
std::string essl = result;
spvc_context_destroy(context);
return essl;
}
}
-183
View File
@@ -1,183 +0,0 @@
//
// Created by BZLZHH on 2025/5/3.
//
#ifndef MOBILEGL_GLSLTOOL_H
#define MOBILEGL_GLSLTOOL_H
#include "../../Includes.h"
namespace MG_Util::Program {
inline static TBuiltInResource InitResources()
{
TBuiltInResource Resources{};
Resources.maxLights = 32;
Resources.maxClipPlanes = 6;
Resources.maxTextureUnits = 32;
Resources.maxTextureCoords = 32;
Resources.maxVertexAttribs = 64;
Resources.maxVertexUniformComponents = 4096;
Resources.maxVaryingFloats = 64;
Resources.maxVertexTextureImageUnits = 32;
Resources.maxCombinedTextureImageUnits = 80;
Resources.maxTextureImageUnits = 32;
Resources.maxFragmentUniformComponents = 4096;
Resources.maxDrawBuffers = 32;
Resources.maxVertexUniformVectors = 128;
Resources.maxVaryingVectors = 8;
Resources.maxFragmentUniformVectors = 16;
Resources.maxVertexOutputVectors = 16;
Resources.maxFragmentInputVectors = 15;
Resources.minProgramTexelOffset = -8;
Resources.maxProgramTexelOffset = 7;
Resources.maxClipDistances = 8;
Resources.maxComputeWorkGroupCountX = 65535;
Resources.maxComputeWorkGroupCountY = 65535;
Resources.maxComputeWorkGroupCountZ = 65535;
Resources.maxComputeWorkGroupSizeX = 1024;
Resources.maxComputeWorkGroupSizeY = 1024;
Resources.maxComputeWorkGroupSizeZ = 64;
Resources.maxComputeUniformComponents = 1024;
Resources.maxComputeTextureImageUnits = 16;
Resources.maxComputeImageUniforms = 8;
Resources.maxComputeAtomicCounters = 8;
Resources.maxComputeAtomicCounterBuffers = 1;
Resources.maxVaryingComponents = 60;
Resources.maxVertexOutputComponents = 64;
Resources.maxGeometryInputComponents = 64;
Resources.maxGeometryOutputComponents = 128;
Resources.maxFragmentInputComponents = 128;
Resources.maxImageUnits = 8;
Resources.maxCombinedImageUnitsAndFragmentOutputs = 8;
Resources.maxCombinedShaderOutputResources = 8;
Resources.maxImageSamples = 0;
Resources.maxVertexImageUniforms = 0;
Resources.maxTessControlImageUniforms = 0;
Resources.maxTessEvaluationImageUniforms = 0;
Resources.maxGeometryImageUniforms = 0;
Resources.maxFragmentImageUniforms = 8;
Resources.maxCombinedImageUniforms = 8;
Resources.maxGeometryTextureImageUnits = 16;
Resources.maxGeometryOutputVertices = 256;
Resources.maxGeometryTotalOutputComponents = 1024;
Resources.maxGeometryUniformComponents = 1024;
Resources.maxGeometryVaryingComponents = 64;
Resources.maxTessControlInputComponents = 128;
Resources.maxTessControlOutputComponents = 128;
Resources.maxTessControlTextureImageUnits = 16;
Resources.maxTessControlUniformComponents = 1024;
Resources.maxTessControlTotalOutputComponents = 4096;
Resources.maxTessEvaluationInputComponents = 128;
Resources.maxTessEvaluationOutputComponents = 128;
Resources.maxTessEvaluationTextureImageUnits = 16;
Resources.maxTessEvaluationUniformComponents = 1024;
Resources.maxTessPatchComponents = 120;
Resources.maxPatchVertices = 32;
Resources.maxTessGenLevel = 64;
Resources.maxViewports = 16;
Resources.maxVertexAtomicCounters = 0;
Resources.maxTessControlAtomicCounters = 0;
Resources.maxTessEvaluationAtomicCounters = 0;
Resources.maxGeometryAtomicCounters = 0;
Resources.maxFragmentAtomicCounters = 8;
Resources.maxCombinedAtomicCounters = 8;
Resources.maxAtomicCounterBindings = 1;
Resources.maxVertexAtomicCounterBuffers = 0;
Resources.maxTessControlAtomicCounterBuffers = 0;
Resources.maxTessEvaluationAtomicCounterBuffers = 0;
Resources.maxGeometryAtomicCounterBuffers = 0;
Resources.maxFragmentAtomicCounterBuffers = 1;
Resources.maxCombinedAtomicCounterBuffers = 1;
Resources.maxAtomicCounterBufferSize = 16384;
Resources.maxTransformFeedbackBuffers = 4;
Resources.maxTransformFeedbackInterleavedComponents = 64;
Resources.maxCullDistances = 8;
Resources.maxCombinedClipAndCullDistances = 8;
Resources.maxSamples = 4;
Resources.maxMeshOutputVerticesNV = 256;
Resources.maxMeshOutputPrimitivesNV = 512;
Resources.maxMeshWorkGroupSizeX_NV = 32;
Resources.maxMeshWorkGroupSizeY_NV = 1;
Resources.maxMeshWorkGroupSizeZ_NV = 1;
Resources.maxTaskWorkGroupSizeX_NV = 32;
Resources.maxTaskWorkGroupSizeY_NV = 1;
Resources.maxTaskWorkGroupSizeZ_NV = 1;
Resources.maxMeshViewCountNV = 4;
Resources.limits.nonInductiveForLoops = true;
Resources.limits.whileLoops = true;
Resources.limits.doWhileLoops = true;
Resources.limits.generalUniformIndexing = true;
Resources.limits.generalAttributeMatrixVectorIndexing = true;
Resources.limits.generalVaryingIndexing = true;
Resources.limits.generalSamplerIndexing = true;
Resources.limits.generalVariableIndexing = true;
Resources.limits.generalConstantMatrixVectorIndexing = true;
return Resources;
}
inline int QueryGLSLVersion(const std::string& code) {
static std::regex version_pattern(R"(#version\s+(\d{3}))");
std::smatch match;
if (std::regex_search(code, match, version_pattern)) {
return std::stoi(match[1].str());
}
return -1;
}
inline GLsizei GetMatrixElementCount(GLenum matrixType) {
switch(matrixType) {
case GL_FLOAT_MAT2: return 4;
case GL_FLOAT_MAT3: return 9;
case GL_FLOAT_MAT4: return 16;
case GL_FLOAT_MAT2x3: return 6;
case GL_FLOAT_MAT2x4: return 8;
case GL_FLOAT_MAT3x2: return 6;
case GL_FLOAT_MAT3x4: return 12;
case GL_FLOAT_MAT4x2: return 8;
case GL_FLOAT_MAT4x3: return 12;
default: return 0;
}
}
inline std::string GetShaderTypeName(GLenum shaderType) {
switch(shaderType) {
case GL_VERTEX_SHADER: return "Vertex Shader";
case GL_FRAGMENT_SHADER: return "Fragment Shader";
case GL_GEOMETRY_SHADER: return "Geometry Shader";
case GL_TESS_CONTROL_SHADER: return "Tessellation Control Shader";
case GL_TESS_EVALUATION_SHADER: return "Tessellation Evaluation Shader";
case GL_COMPUTE_SHADER: return "Compute Shader";
default: return "Unknown Shader Type (" + std::to_string(shaderType) + ")";
}
}
inline EShLanguage GetEShLanguageByShaderType(GLenum shaderType) {
switch (shaderType) {
case GL_VERTEX_SHADER:
return EShLanguage::EShLangVertex;
case GL_FRAGMENT_SHADER:
return EShLanguage::EShLangFragment;
case GL_COMPUTE_SHADER:
return EShLanguage::EShLangCompute;
case GL_TESS_CONTROL_SHADER:
return EShLanguage::EShLangTessControl;
case GL_TESS_EVALUATION_SHADER:
return EShLanguage::EShLangTessEvaluation;
case GL_GEOMETRY_SHADER:
return EShLanguage::EShLangGeometry;
default:
return EShLanguage::EShLangCount;
}
}
std::vector<unsigned> CompileGLSLToSPIRV(GLenum shaderType, const std::string& source, std::string& infoLog);
std::string CompileGLSLToTShader(GLenum shaderType, const std::string& source, glslang::TShader *&shader);
std::vector<std::vector<unsigned>> CompileMultipleShadersToSPIRV(const ProgramState& state, ProgramObject& prog, std::string& infoLog);
void ReflectSPIRVUniforms(const std::vector<std::vector<unsigned>>& allSpirv, ProgramObject& prog, std::string& infoLog);
std::string CompileSPIRVToGLSL(std::vector<unsigned int> spirv, uint glslVersion, bool isES);
}
#endif //MOBILEGL_GLSLTOOL_H
+147
View File
@@ -0,0 +1,147 @@
// MobileGL - MobileGL/Config.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 <Includes.h>
#include <MG_Backend/BackendObjects.h>
namespace MobileGL::MG_Config {
inline const String ProjectName = "MobileGL";
inline const String CoreName = "MobileGL Core";
inline const String CoreVendor = "MobileGL-Dev (BZLZHH, Swung0x48, Tungsten)";
inline const Version CoreVersion = {26, 8, 0, "-dev", VersionType::Development};
inline const VersionStringFormatAttrib DefaultVersionStringFormatAttrib = {2, 2, 0, true, true};
inline const Uint64 CacheVersion = 0;
extern BackendType ActiveBackendType;
// Tri-state override for device-specific quirks: Auto lets the detected device decide,
// ForceOn/ForceOff bypass the detection in either direction. ForceOn only bypasses the
// device gate - each quirk keeps its structural safety checks.
enum class QuirkOverride : Uint8 {
Auto = 0,
ForceOn,
ForceOff,
};
// Preferred DirectVulkan dispatch tier for the glMultiDraw* families. A preference,
// never a demand: the renderer clamps it to what the device supports at device
// creation, falling down the chain ext -> indirect -> unroll with one log line.
enum class MultiDrawMode : Uint8 {
Auto = 0, // unset: best supported tier
Ext, // VK_EXT_multi_draw: one vkCmdDrawMultiEXT / vkCmdDrawMultiIndexedEXT
Indirect, // multiDrawIndirect feature: one vkCmdDraw*Indirect over a transient command array
Unroll, // one vkCmdDraw* per sub-draw
};
// Preferred DirectGLES emulation tier for glMultiDrawElements(BaseVertex). GLES has no
// such entry point in core, so every tier below is an emulation; they differ only in
// which driver capability they lean on and how many driver calls a batch costs. Like
// the Magma knob this is a preference, clamped at resolution time to what the ES
// driver actually supports, with one log line when it falls back.
enum class GLESMultiDrawMode : Uint8 {
Auto = 0, // unset: best supported tier
Ext, // one glMultiDrawElementsBaseVertexEXT
MultiIndirect, // one glMultiDrawElementsIndirectEXT over a scratch command buffer
Indirect, // one glDrawElementsIndirect per sub-draw over that same buffer
BaseVertex, // one glDrawElementsBaseVertex per sub-draw
DrawElements, // baseVertex folded into a scratch index buffer on the CPU, then plain
// glDrawElements per sub-draw (for drivers with no base-vertex draw at all)
Compute, // a compute shader flattens every sub-draw into one rebased index buffer,
// drawn by a single glDrawElements
};
// Feature toggles parsed once from environment variables in MG_ConfigLoader::Init()
// (ConfigLoader.cpp), before the accepted-env map is destroyed. All Bool fields share
// one truthy rule: the variable is set, non-empty, not "0", and not "false"
// (case-insensitive).
//
// Env variables intentionally NOT mirrored here (kept as live std::getenv at their
// call sites):
// - DISPLAY: X11 session variable, not MobileGL configuration.
// - MOBILEGL_LOG_FILE_PATH: log-file init runs before MG_ConfigLoader::Init
// (see MG_Util/Debug/Log.cpp).
// - MOBILEGL_ASYNC_POOL: a ShaderCompilePool is constructed by binaries that never call
// MobileGL::Initialize() and so never run MG_ConfigLoader::Init - MG_Test's
// JobNodeTest builds pools directly, and it is the suite that runs the whole async
// matrix against both execution engines. Mirroring it here would resolve to the
// default in exactly the tests that exist to tell the engines apart (see
// MG_Util/Async/ShaderCompilePool.cpp, DetectAsyncPoolEngine).
struct FeaturesTable {
// MOBILEGL_DISABLE_TIMERQUERY: do not advertise or use GPU timer queries.
Bool DisableTimerQuery = false;
// MOBILEGL_USE_ANGLE: load ANGLE EGL/GLES libraries.
Bool UseAngle = false;
#if defined(MOBILEGL_TRACE_ANGLE_VARIANTS)
// MOBILEGL_TRACE_ANGLE_VARIANT: signed trace-APK ANGLE build short hash.
String TraceAngleVariant;
#endif
// MOBILEGL_DISABLE_SUBGROUP: force-disable Vulkan shader subgroup support.
Bool DisableSubgroup = false;
// MOBILEGL_MAGMA_R11G11B10F_FALLBACK: use fallback format for R11G11B10F on Vulkan.
Bool MagmaR11G11B10FFallback = false;
// MOBILEGL_MAGMA_FRAMESINFLIGHT: requested Magma frames in flight, defaulting to 3.
Uint32 MagmaFramesInFlight = 3;
// MOBILEGL_AVOID_SAMPLER_MIPMAP_MIN_FILTER: avoid mipmap min filters in samplers,
// resolves certain rendering bugs on ANGLE + llvmpipe.
Bool AvoidSamplerMipmapMinFilter = false;
// MOBILEGL_COHERENT_AS_FLUSH: app-compat for engines (e.g. Flywheel) that write
// GPU-read data through persistent GL_MAP_FLUSH_EXPLICIT_BIT maps they never
// flush. Persistent FLUSH_EXPLICIT map requests are rewritten to coherent
// semantics: writes reach the backend without glFlushMappedBufferRange, and
// flush calls on rewritten maps become error-free no-ops. Non-persistent maps
// keep spec FLUSH_EXPLICIT behavior.
Bool CoherentAsFlush = false;
// MOBILEGL_TRACE_SKIP_AUTODESTROY: skip teardown in the ELF destructor (Init.cpp).
Bool TraceSkipAutodestroy = false;
// MOBILEGL_DISABLE_UBO_RING: force the DirectGLES global-UBO upload back to the
// per-draw glBufferSubData path instead of the persistent-mapped ring allocator
// (negative control / driver-bug escape hatch).
Bool DisableUboRing = false;
// MOBILEGL_RELAXED_SEMANTICS: relax strict core-profile rules (e.g. VAO-0 draws,
// texture-name reuse after delete) even on contexts that explicitly requested a core
// profile. Without it, relaxed semantics still apply to every context that did not
// explicitly request a core profile via EGL_CONTEXT_OPENGL_PROFILE_MASK / a >=3.1
// version request.
Bool RelaxedSemantics = false;
// MOBILEGL_QUIRK_SUBGROUP_PREFIX_SCAN: overrides the shader-source quirk that
// 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_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
// cross-pipeline vertex position invariance. Sorted-transparency "over" blends,
// gl_FragDepth writers, and fully color-masked attachments are exempt (see
// PipelineFactory::ShouldSuppressDepthWrite). Auto detects Qualcomm.
QuirkOverride MagmaDisableBlendedDepthWriteQuirk = QuirkOverride::Auto;
// MOBILEGL_DISABLE_ROBUST_BUFFER_ACCESS: leave the Vulkan robustBufferAccess device
// feature off. It is enabled by default to match GL's defined out-of-range fetch
// behavior; this escape hatch exists to measure or dodge its GPU cost on a device.
Bool DisableRobustBufferAccess = false;
// MOBILEGL_MAGMA_MULTIDRAW_MODE: preferred DirectVulkan multi-draw dispatch tier
// ("ext" | "indirect" | "unroll", see MultiDrawMode). Clamped to device support;
// unset picks the best supported tier.
MultiDrawMode MagmaMultiDrawMode = MultiDrawMode::Auto;
// MOBILEGL_ESPRYT_MULTIDRAW_MODE: preferred DirectGLES glMultiDrawElements emulation
// tier ("ext" | "multiindirect" | "indirect" | "basevertex" | "drawelements" |
// "compute", see GLESMultiDrawMode). Clamped to driver support; unset picks the best
// supported tier, which never includes "compute" - see the note on its resolution.
GLESMultiDrawMode EsprytMultiDrawMode = GLESMultiDrawMode::Auto;
// MOBILEGL_ASYNC_SHADER_COMPILE: overrides asynchronous shader compilation. Unset
// keeps the built-in default (MG_Util::Async::kAsyncShaderCompileDefault); falsy
// forces every glCompileShader/glLinkProgram to run synchronously on the calling
// thread AND withdraws GL_KHR_parallel_shader_compile, so the single switch reverts
// both the threading and the application-visible behaviour change.
QuirkOverride AsyncShaderCompile = QuirkOverride::Auto;
// MOBILEGL_ASYNC_SHADER_COMPILE_THREADS: shader-compile worker count. 0 (unset) means
// auto, which is min(4, big cores); an explicit value is honoured as given.
Uint32 AsyncShaderCompileThreads = 0;
};
extern FeaturesTable Features;
} // namespace MobileGL::MG_Config
+214
View File
@@ -0,0 +1,214 @@
// MobileGL - MobileGL/ConfigLoader.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 "Config.h"
#include <cerrno>
#include <cstdlib>
#ifndef _WIN32
extern char** environ;
#endif
namespace MobileGL::MG_Config {
// Zero/default-initialized at static-init time (all fields have constexpr-friendly
// defaults), so it is safe to read even if MG_ConfigLoader::Init has not run yet.
FeaturesTable Features;
} // namespace MobileGL::MG_Config
namespace MobileGL::MG_ConfigLoader {
static UniquePtr<UnorderedMap<String, String>> acceptedEnvVariablesMap;
static Bool IsAcceptedPrefix(const String& key) {
return (key.compare(0, 6, "LIBGL_") == 0 || key.compare(0, 9, "MOBILEGL_") == 0);
}
inline void InitializeAcceptedEnvVariables() {
if (!acceptedEnvVariablesMap) {
acceptedEnvVariablesMap = MakeUnique<UnorderedMap<String, String>>();
} else {
acceptedEnvVariablesMap->clear();
}
char** envPtr = nullptr;
#ifdef _WIN32
envPtr = _environ;
#else // POSIX
envPtr = ::environ;
#endif
if (envPtr == nullptr) return;
for (char** env = envPtr; *env != nullptr; ++env) {
String entry(*env);
SizeT pos = entry.find('=');
if (pos != String::npos) {
String key = entry.substr(0, pos);
String value = entry.substr(pos + 1);
if (IsAcceptedPrefix(key)) {
(*acceptedEnvVariablesMap)[key] = value;
MGLOG_D("Config: Accepted env variable: %s=%s", key.c_str(), value.c_str());
}
}
}
}
inline void QueryEnvVariable(const String& key, String& outValue, const String& defaultValue) {
auto it = acceptedEnvVariablesMap->find(key);
if (it != acceptedEnvVariablesMap->end()) {
outValue = it->second;
} else {
outValue = defaultValue;
}
}
// Unified truthy rule for boolean feature env variables: set, non-empty, not "0",
// and not "false" (case-insensitive).
static Bool IsTruthyValue(const String& value) {
if (value.empty() || value == "0") {
return false;
}
String lowered = value;
std::transform(lowered.begin(), lowered.end(), lowered.begin(),
[](unsigned char c) { return static_cast<char>(std::tolower(c)); });
return lowered != "false";
}
inline Bool QueryEnvFlag(const String& key) {
auto it = acceptedEnvVariablesMap->find(key);
return it != acceptedEnvVariablesMap->end() && IsTruthyValue(it->second);
}
// Quirk overrides are tri-state: an unset variable keeps device auto-detection, a truthy
// value forces the quirk on, anything else set ("0", "false", "") forces it off.
inline MG_Config::QuirkOverride QueryEnvQuirkOverride(const String& key) {
auto it = acceptedEnvVariablesMap->find(key);
if (it == acceptedEnvVariablesMap->end()) {
return MG_Config::QuirkOverride::Auto;
}
return IsTruthyValue(it->second) ? MG_Config::QuirkOverride::ForceOn
: MG_Config::QuirkOverride::ForceOff;
}
// Multi-draw mode is a named-value preference: unset keeps Auto (best supported tier),
// a recognized name selects that tier as the ceiling, anything else warns and keeps Auto.
inline MG_Config::MultiDrawMode QueryEnvMultiDrawMode(const String& key) {
auto it = acceptedEnvVariablesMap->find(key);
if (it == acceptedEnvVariablesMap->end()) {
return MG_Config::MultiDrawMode::Auto;
}
String lowered = it->second;
std::transform(lowered.begin(), lowered.end(), lowered.begin(),
[](unsigned char c) { return static_cast<char>(std::tolower(c)); });
if (lowered == "ext") return MG_Config::MultiDrawMode::Ext;
if (lowered == "indirect") return MG_Config::MultiDrawMode::Indirect;
if (lowered == "unroll") return MG_Config::MultiDrawMode::Unroll;
if (lowered.empty() || lowered == "auto") return MG_Config::MultiDrawMode::Auto;
MGLOG_W("Config: Ignoring invalid env variable %s='%s'; expected ext|indirect|unroll|auto, using auto",
key.c_str(), it->second.c_str());
return MG_Config::MultiDrawMode::Auto;
}
// Same contract as QueryEnvMultiDrawMode, over the DirectGLES tier names.
inline MG_Config::GLESMultiDrawMode QueryEnvGLESMultiDrawMode(const String& key) {
auto it = acceptedEnvVariablesMap->find(key);
if (it == acceptedEnvVariablesMap->end()) {
return MG_Config::GLESMultiDrawMode::Auto;
}
String lowered = it->second;
std::transform(lowered.begin(), lowered.end(), lowered.begin(),
[](unsigned char c) { return static_cast<char>(std::tolower(c)); });
if (lowered == "ext") return MG_Config::GLESMultiDrawMode::Ext;
if (lowered == "multiindirect") return MG_Config::GLESMultiDrawMode::MultiIndirect;
if (lowered == "indirect") return MG_Config::GLESMultiDrawMode::Indirect;
if (lowered == "basevertex") return MG_Config::GLESMultiDrawMode::BaseVertex;
if (lowered == "drawelements") return MG_Config::GLESMultiDrawMode::DrawElements;
if (lowered == "compute") return MG_Config::GLESMultiDrawMode::Compute;
if (lowered.empty() || lowered == "auto") return MG_Config::GLESMultiDrawMode::Auto;
MGLOG_W("Config: Ignoring invalid env variable %s='%s'; expected "
"ext|multiindirect|indirect|basevertex|drawelements|compute|auto, using auto",
key.c_str(), it->second.c_str());
return MG_Config::GLESMultiDrawMode::Auto;
}
inline Uint32 QueryEnvUint32(const String& key, Uint32 defaultValue, Uint32 minValue, Uint32 maxValue) {
auto it = acceptedEnvVariablesMap->find(key);
if (it == acceptedEnvVariablesMap->end()) {
return defaultValue;
}
const String& value = it->second;
char* parseEnd = nullptr;
errno = 0;
const unsigned long parsedValue = std::strtoul(value.c_str(), &parseEnd, 10);
if (parseEnd == value.c_str() || *parseEnd != '\0' || errno == ERANGE || parsedValue < minValue ||
parsedValue > maxValue) {
MGLOG_W("Config: Ignoring invalid env variable %s='%s'; expected an integer in range [%u, %u], "
"using default %u",
key.c_str(), value.c_str(), minValue, maxValue, defaultValue);
return defaultValue;
}
return static_cast<Uint32>(parsedValue);
}
inline void InitFeatures() {
auto& features = MG_Config::Features;
features.DisableTimerQuery = QueryEnvFlag("MOBILEGL_DISABLE_TIMERQUERY");
features.UseAngle = QueryEnvFlag("MOBILEGL_USE_ANGLE");
#if defined(MOBILEGL_TRACE_ANGLE_VARIANTS)
QueryEnvVariable("MOBILEGL_TRACE_ANGLE_VARIANT", features.TraceAngleVariant, "");
#endif
features.DisableSubgroup = QueryEnvFlag("MOBILEGL_DISABLE_SUBGROUP");
features.MagmaR11G11B10FFallback = QueryEnvFlag("MOBILEGL_MAGMA_R11G11B10F_FALLBACK");
features.MagmaFramesInFlight = QueryEnvUint32("MOBILEGL_MAGMA_FRAMESINFLIGHT", 3, 1, 64);
features.AvoidSamplerMipmapMinFilter =
QueryEnvFlag("MOBILEGL_AVOID_SAMPLER_MIPMAP_MIN_FILTER");
features.CoherentAsFlush = QueryEnvFlag("MOBILEGL_COHERENT_AS_FLUSH");
features.TraceSkipAutodestroy = QueryEnvFlag("MOBILEGL_TRACE_SKIP_AUTODESTROY");
features.DisableUboRing = QueryEnvFlag("MOBILEGL_DISABLE_UBO_RING");
features.RelaxedSemantics = QueryEnvFlag("MOBILEGL_RELAXED_SEMANTICS");
features.SubgroupPrefixScanQuirk = QueryEnvQuirkOverride("MOBILEGL_QUIRK_SUBGROUP_PREFIX_SCAN");
features.MagmaDisableBlendedDepthWriteQuirk =
QueryEnvQuirkOverride("MOBILEGL_MAGMA_DISABLE_BLENDED_DEPTH_WRITE");
features.DisableRobustBufferAccess = QueryEnvFlag("MOBILEGL_DISABLE_ROBUST_BUFFER_ACCESS");
features.MagmaMultiDrawMode = QueryEnvMultiDrawMode("MOBILEGL_MAGMA_MULTIDRAW_MODE");
features.EsprytMultiDrawMode = QueryEnvGLESMultiDrawMode("MOBILEGL_ESPRYT_MULTIDRAW_MODE");
features.AsyncShaderCompile = QueryEnvQuirkOverride("MOBILEGL_ASYNC_SHADER_COMPILE");
features.AsyncShaderCompileThreads = QueryEnvUint32("MOBILEGL_ASYNC_SHADER_COMPILE_THREADS", 0, 0, 64);
}
inline void InitBackendType() {
String backendTypeStr;
QueryEnvVariable("MOBILEGL_BACKEND_TYPE", backendTypeStr, "DirectGLES");
#define ENTRY(backendType) \
if (backendTypeStr == #backendType) { \
MG_Config::ActiveBackendType = BackendType::backendType; \
MGLOG_I("Config: Active backend type set to " #backendType); \
return; \
}
ENTRY(DirectGLES)
ENTRY(DirectVulkan)
ENTRY(Unknown)
MG_Config::ActiveBackendType = BackendType::Unknown;
#undef ENTRY
}
void Init() {
MGLOG_D("Loading configuration from environment variables...");
InitializeAcceptedEnvVariables();
InitBackendType();
InitFeatures();
// Destroy the map since we won't need it anymore
acceptedEnvVariablesMap.reset();
}
} // namespace MobileGL::MG_ConfigLoader
+82
View File
@@ -0,0 +1,82 @@
// MobileGL - MobileGL/Defines.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
// ============== Platform-specific definitions and macros ============== //
#ifdef __ANDROID__
#undef __ANDROID_API__
#define __ANDROID_API__ 26 // force Android API level to 26 for compatibility
#endif
#ifdef _WIN32
#ifndef NOMINMAX
#define NOMINMAX 1 // prevent Windows.h from defining min and max macros
#endif
#endif
// ================== MobileGL definitions and macros =================== //
#ifdef _WIN32
#define MOBILEGL_EXPORT extern "C" __declspec(dllexport)
#else
#define MOBILEGL_EXPORT extern "C" __attribute__((visibility("default")))
#endif
#define MOBILEGL_API MOBILEGL_EXPORT
#define MOBILEGL_GLX_API MOBILEGL_API
#define MOBILEGL_GL_API MOBILEGL_API
#define MOBILEGL_EGL_API MOBILEGL_API
#define MOBILEGL_CGL_API MOBILEGL_API
#define MOBILEGL_NSOPENGL_API MOBILEGL_API
#define MOBILEGL_WGL_API MOBILEGL_API
// ====================== MobileGL configurations ======================= //
#ifndef MOBILEGL_LOG_ACTIVE_LEVEL
#define MOBILEGL_LOG_ACTIVE_LEVEL MOBILEGL_LOG_LEVEL_INFO
#endif
#define MOBILEGL_LOG_ENABLE_CONSOLE 0
#define MOBILEGL_LOG_ENABLE_FILE 1
#define MOBILEGL_LOG_ENABLE_ANDROID 1
#define MOBILEGL_ENABLE_SCOPE_MARKER 0
// Require C++23
// Clang/Android NDK still doesn't have support for that :(
#if __cplusplus >= 202302L && !__ANDROID__
#define MOBILEGL_LOG_ENABLE_STACKTRACE 0
#endif
#ifdef __ANDROID__
#define MOBILEGL_LOG_FILE_PATH "/sdcard/MG/latest.log"
#else
#define MOBILEGL_LOG_FILE_PATH ""
#endif
#if defined _MSC_VER or defined __MINGW32__ or defined __MINGW64__
#define TRAP assert(false)
#elif __clang__
#define TRAP __builtin_debugtrap()
#else
#include <signal.h>
#define TRAP raise(SIGTRAP)
#endif
// =============================== Utils ================================ //
#if MOBILEGL_LOG_ACTIVE_LEVEL <= MOBILEGL_LOG_LEVEL_DEBUG
#define MOBILEGL_ASSERT(condition, ...) \
do { \
if (!(condition)) { \
MGLOG_F("Assertion failed" __VA_OPT__(": ") __VA_ARGS__); \
MGLOG_F(" at %s:%d (%s)", __FILE__, __LINE__, __func__); \
TRAP; \
} \
} while (0)
#else
#define MOBILEGL_ASSERT(condition, ...)
#endif
+26
View File
@@ -0,0 +1,26 @@
// MobileGL - MobileGL/GlobalObjects.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 "Config.h"
namespace MobileGL {
namespace MG_Config {
BackendType ActiveBackendType;
} // namespace MG_Config
namespace MG_Backend {
// Leak-at-exit storage: the UniquePtr itself lives on the heap and is
// never destroyed by the runtime, so process exit runs no backend
// destructors (static destruction order across TUs is undefined).
// Deterministic teardown happens inside the EGL lifecycle instead:
// the last eglTerminate calls MobileGL::Destroy(), which .reset()s
// these singletons while the process is still healthy.
UniquePtr<BackendObject>& pActiveBackendObject = *new UniquePtr<BackendObject>();
GlobalBackendFunctionsTable gBackendFunctionsTable;
} // namespace MG_Backend
} // namespace MobileGL
+149
View File
@@ -0,0 +1,149 @@
// MobileGL - MobileGL/Includes.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 significant project headers
#include "Defines.h"
#include "MG_Util/PlatformStubs.h"
// Include necessary standard headers
#include <bit>
#include <map>
#include <array>
#include <ctime>
#include <mutex>
#include <queue>
#include <regex>
#include <atomic>
#include <bitset>
#include <cctype>
#include <chrono>
#include <cstdio>
#include <format>
#include <memory>
#include <random>
#include <string>
#include <thread>
#include <vector>
#include <cassert>
#include <climits>
#include <cstdlib>
#include <cstdarg>
#include <cstring>
#include <numeric>
#include <expected>
#include <iostream>
#include <optional>
#include <algorithm>
#include <stdexcept>
#include <functional>
#include <string_view>
#include <unordered_map>
#if __cplusplus >= 202302L && MOBILEGL_LOG_ENABLE_STACKTRACE
#include <stacktrace>
#endif
// Include FastSTL
#include <FastSTL/UnorderedMap.h>
// Include xxHash
#include <xxhash.h>
// Include spirv_cross
#include <spirv_cross/spirv_cross_c.h>
// Include OpenGL and EGL headers
#ifdef GLAPI
#undef GLAPI
#endif
#include <EGL/egl.h>
#define GL_GLEXT_PROTOTYPES
#ifndef NO_GL_H
#include "GL/gl.h"
#endif
#include <GL/glcorearb.h>
#undef GL_GLEXT_PROTOTYPES
#include <GL/glext.h>
#define GL_GLES_PROTOTYPES 0
#include <GLES3/gl32.h>
#undef GL_GLES_PROTOTYPES
// Include glslang headers
#include <glslang/Include/Types.h>
#include <glslang/Public/ShaderLang.h>
#include <glslang/SPIRV/GlslangToSpv.h>
#include <glslang/Include/intermediate.h>
#include <glslang/MachineIndependent/localintermediate.h>
// Include headers for platform-specific functionality
#ifdef __linux__
#include <dlfcn.h>
#include <pthread.h>
#endif
#ifdef _WIN32
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN 1
#endif
#include <windows.h>
#include <processthreadsapi.h>
#endif
#ifdef __ANDROID__
#include <unistd.h>
#include <pthread.h>
#include <android/log.h>
#include <android/native_window.h>
#endif
#ifdef __ANDROID__
#define VK_USE_PLATFORM_ANDROID_KHR
#elif _WIN32
#define VK_USE_PLATFORM_WIN32_KHR
#elif defined(__APPLE__)
#define VK_USE_PLATFORM_METAL_EXT
#elif defined(__linux__)
#define VK_USE_PLATFORM_XLIB_KHR
typedef struct _XDisplay Display;
typedef unsigned long XID;
typedef XID Window;
typedef unsigned long VisualID;
#else
#warning "VK_USE_PLATFORM_*_KHR not defined for this platform!"
#endif
#if defined(VK_USE_PLATFORM_XLIB_KHR)
#pragma push_macro("Bool")
#pragma push_macro("None")
#pragma push_macro("Always")
#pragma push_macro("Status")
#pragma push_macro("LSBFirst")
#pragma push_macro("DestroyAll")
#endif
#include <vulkan/vulkan.h>
#if defined(VK_USE_PLATFORM_XLIB_KHR)
#pragma pop_macro("DestroyAll")
#pragma pop_macro("LSBFirst")
#pragma pop_macro("Status")
#pragma pop_macro("Always")
#pragma pop_macro("None")
#pragma pop_macro("Bool")
#endif
#ifdef TRACY_ENABLE
#include <tracy/Tracy.hpp>
#define TRACY_ZONECOLOR_ENTRY 0xFF0000
#define TRACY_ZONECOLOR_FRONTEND 0x00FF00
#define TRACY_ZONECOLOR_BACKEND 0x00FF00
#endif
// Post-includes for significant project headers
#include "MG_Util/Debug/Log.h"
#include "MG_Util/Types.h"
+147
View File
@@ -0,0 +1,147 @@
// MobileGL - MobileGL/Init.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 "Init.h"
#include "Config.h"
#include <MG_Backend/BackendObjects.h>
#include <MG_Backend/DirectVulkan/DirectVulkan.h>
#include <MG_State/GLState/Core.h>
#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 <MG_Util/Async/ShaderCompilePool.h>
#include <MG_Util/ShaderTranspiler/ShaderCompiler.h>
#include <atomic>
#include <mutex>
namespace MobileGL {
namespace {
std::atomic<Bool> g_isInitialized = false;
thread_local Bool tl_initializing = false;
std::mutex& InitMutex() {
static std::mutex mutex;
return mutex;
}
void DestroyImpl(Bool logLifecycle) {
if (!g_isInitialized) {
return;
}
if (logLifecycle) {
MGLOG_I("MobileGL closing...");
}
// First, before anything else is torn down. In-flight compile/link jobs own
// their own inputs and are safe against everything below EXCEPT glslang's
// process globals and the TShader/TProgram objects hanging off pGLContext,
// both of which this function is about to destroy. This is the one
// cancellation path in the whole design that waits.
MG_Util::Async::ShaderCompilePool::Get().StopAndDrain();
// 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();
MG_Impl::GLImpl::TextureImpl::pProxyTextureManager.reset();
MG_Impl::GLImpl::FramebufferImpl::pDefaultFramebufferInfo.reset();
// Must run AFTER pGLContext.reset(). FinalizeProcess -> ShFinalize deletes
// glslang's process-wide pool allocator and every cached built-in symbol table,
// while the TShader/TProgram objects owned by the shader and program objects
// still reference levels adopted from those tables. Finalizing first left live
// glslang objects pointing at freed memory for the rest of the teardown.
glslang::FinalizeProcess();
// Immediately after, and never apart from it: FinalizeProcess just deleted the
// built-in symbol tables the prewarm latch stands for, so leaving it set would
// make the next Initialize() skip a prewarm it genuinely needs.
MG_Util::ShaderTranspiler::ShaderCompiler::ResetPrewarmLatch();
MG_Backend::gBackendFunctionsTable = {};
g_isInitialized = false;
if (logLifecycle) {
MG_Util::Debug::Close();
}
// TODO: add and use Destroy functions for other subsystems
}
}
void Initialize() {
if (g_isInitialized) {
MGLOG_D("MobileGL already initialized; skipping duplicate Initialize()");
return;
}
MG_Util::Debug::InitFile();
MGLOG_I("Initializing MobileGL...");
MG_ConfigLoader::Init();
MGLOG_I("Config loaded");
MG_State::Init();
MGLOG_D("MG_State initialized");
MG_Backend::Init();
MGLOG_D("MG_Backend initialized");
MG_Impl::Init();
MGLOG_D("MG_Impl initialized");
glslang::InitializeProcess();
// On the GL thread, before any worker can exist. glslang builds its built-in symbol
// tables lazily under a process-wide lock held for the whole build, so without this
// the first concurrent compiles of a shaderpack all serialize behind the very first
// parse and asynchronous compilation looks like it is doing nothing.
//
// Gated on the flag, because the problem it solves only exists when there are
// workers: with compilation synchronous, nothing ever contends for that lock and the
// three throwaway parses buy nothing - they just add to every eglInitialize. Read the
// flag here rather than inside PrewarmBuiltins so ShaderCompiler keeps no dependency
// on the async subsystem (ProgramUtilTest compiles that file without it).
if (MG_Util::Async::AsyncShaderCompileEnabled()) {
MG_Util::ShaderTranspiler::ShaderCompiler::PrewarmBuiltins();
}
MGLOG_D("glslang initialized");
g_isInitialized = true;
MGLOG_I("MobileGL initialized");
}
void EnsureInitialized() {
if (g_isInitialized.load(std::memory_order_acquire)) {
return;
}
// Re-entrant call while this thread is already inside Initialize()
// (e.g. an init step routing back through a public entry point).
if (tl_initializing) {
return;
}
const std::lock_guard<std::mutex> lock(InitMutex());
if (g_isInitialized.load(std::memory_order_acquire)) {
return;
}
tl_initializing = true;
Initialize();
tl_initializing = false;
}
void Destroy() {
DestroyImpl(true);
}
// MobileGL's lifecycle is owned entirely by the host-API layers
// (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
// 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.
} // namespace MobileGL
+38
View File
@@ -0,0 +1,38 @@
// MobileGL - MobileGL/Init.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 "Includes.h"
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.
void EnsureInitialized();
void Destroy();
namespace MG_Util::Debug {
void InitFile();
} // namespace MG_Util::Debug
namespace MG_ConfigLoader {
void Init();
} // namespace MG_ConfigLoader
namespace MG_Backend {
void Init();
} // namespace MG_Backend
namespace MG_Impl {
void Init();
} // namespace MG_Impl
} // namespace MobileGL
+495
View File
@@ -0,0 +1,495 @@
// MobileGL - MobileGL/MG_Backend/BackendObject.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 "BackendObject.h"
#include "MG_Util/Converters/MGToStr/TextureEnumConverter.h"
#include <algorithm>
#include <cstring>
#include <iomanip>
#include <sstream>
namespace MobileGL::MG_Backend {
namespace {
Bool IsReleaseCurrentRequest(EGLDisplay dpy, EGLSurface draw, EGLSurface read, EGLContext ctx) {
(void)dpy;
return draw == EGL_NO_SURFACE && read == EGL_NO_SURFACE && ctx == EGL_NO_CONTEXT;
}
std::thread::id CurrentThreadKey() {
return std::this_thread::get_id();
}
const char* GetFormatCapabilitySupportString(const FormatCapabilityCache& cache,
SizeT targetIndex,
SizeT formatIndex,
FormatCapability capability) {
if (HasFormatCapability(cache.FullCaps[targetIndex][formatIndex], capability)) return "Full";
if (HasFormatCapability(cache.CaveatCaps[targetIndex][formatIndex], capability)) return "Caveat";
return "None";
}
SizeT GetPrintedFormatNameWidth() {
SizeT width = 0;
for (SizeT formatIndex = 0; formatIndex < kFormatCapabilityFormatCount; ++formatIndex) {
const auto format = static_cast<TextureInternalFormat>(formatIndex);
width = std::max(width, MG_Util::ConvertTextureInternalFormatToString(format).size());
}
return width;
}
SizeT GetCapabilityColumnWidth(FormatCapability capability) {
SizeT width = std::strlen(GetFormatCapabilityName(capability));
width = std::max<SizeT>(width, std::strlen("Caveat"));
return width;
}
String BuildFormatCapabilityHeader(SizeT formatNameWidth) {
std::ostringstream line;
line << std::left << std::setw(static_cast<Int>(formatNameWidth)) << "";
for (FormatCapability capability : kReportedFormatCapabilities) {
line << " | " << std::left << std::setw(static_cast<Int>(GetCapabilityColumnWidth(capability)))
<< GetFormatCapabilityName(capability);
}
return line.str();
}
String BuildFormatCapabilityRow(const FormatCapabilityCache& cache,
SizeT targetIndex,
SizeT formatIndex,
SizeT formatNameWidth) {
const auto format = static_cast<TextureInternalFormat>(formatIndex);
std::ostringstream line;
line << std::left << std::setw(static_cast<Int>(formatNameWidth))
<< MG_Util::ConvertTextureInternalFormatToString(format);
for (FormatCapability capability : kReportedFormatCapabilities) {
line << " | " << std::left << std::setw(static_cast<Int>(GetCapabilityColumnWidth(capability)))
<< GetFormatCapabilitySupportString(cache, targetIndex, formatIndex, capability);
}
return line.str();
}
} // namespace
void FormatCapabilityCache::Clear() {
for (auto& row : FullCaps) {
row.fill(FormatCapabilityFlags{});
}
for (auto& row : CaveatCaps) {
row.fill(FormatCapabilityFlags{});
}
for (auto& row : SampleCounts) {
for (auto& counts : row) {
counts.clear();
}
}
}
Bool HasFormatCapability(FormatCapabilityFlags caps, FormatCapability capability) {
return static_cast<Bool>(caps & capability);
}
SizeT GetFormatCapabilityTargetIndex(TextureTarget target) {
if (target == TextureTarget::Unknown || static_cast<Int>(target) < 0 ||
static_cast<SizeT>(target) >= kFormatCapabilityTextureTargetCount) {
return kFormatCapabilityTargetCount;
}
return static_cast<SizeT>(target);
}
SizeT GetRenderbufferFormatCapabilityTargetIndex() {
return kFormatCapabilityRenderbufferTargetIndex;
}
const char* GetFormatCapabilityName(FormatCapability capability) {
switch (capability) {
case FormatCapability::Creatable:
return "Creatable";
case FormatCapability::Sampled:
return "Sampled";
case FormatCapability::LinearFilter:
return "LinearFilter";
case FormatCapability::GenerateMipmap:
return "GenerateMipmap";
case FormatCapability::TextureGather:
return "TextureGather";
case FormatCapability::TextureShadow:
return "TextureShadow";
case FormatCapability::FramebufferRenderable:
return "FramebufferRenderable";
case FormatCapability::FramebufferLayered:
return "FramebufferLayered";
case FormatCapability::MultisampleTexture:
return "MultisampleTexture";
case FormatCapability::MultisampleRenderbuffer:
return "MultisampleRenderbuffer";
case FormatCapability::ColorAttachment:
return "ColorAttachment";
case FormatCapability::DepthAttachment:
return "DepthAttachment";
case FormatCapability::StencilAttachment:
return "StencilAttachment";
case FormatCapability::TextureBuffer:
return "TextureBuffer";
}
return "Unknown";
}
String GetFormatCapabilityTargetName(SizeT targetIndex) {
if (targetIndex == kFormatCapabilityRenderbufferTargetIndex) {
return "Renderbuffer";
}
if (targetIndex >= kFormatCapabilityTextureTargetCount) {
return "Unknown";
}
return MG_Util::ConvertTextureTargetToString(static_cast<TextureTarget>(targetIndex));
}
void PrintFormatCapabilities(const FormatCapabilityCache& cache) {
const SizeT formatNameWidth = GetPrintedFormatNameWidth();
MGLOG_D("Backend format capabilities:");
for (SizeT targetIndex = 0; targetIndex < kFormatCapabilityTargetCount; ++targetIndex) {
MGLOG_D("");
const String targetName = GetFormatCapabilityTargetName(targetIndex);
MGLOG_D("- %s", targetName.c_str());
const String header = BuildFormatCapabilityHeader(formatNameWidth);
MGLOG_D("%s", header.c_str());
for (SizeT formatIndex = 0; formatIndex < kFormatCapabilityFormatCount; ++formatIndex) {
const String row = BuildFormatCapabilityRow(cache, targetIndex, formatIndex, formatNameWidth);
MGLOG_D("%s", row.c_str());
}
}
}
Bool BackendObject::InitializeEGLDisplay(EGLDisplay dpy, EGLint* major, EGLint* minor) {
const std::lock_guard<std::recursive_mutex> lock(m_eglStateMutex);
if (dpy == EGL_NO_DISPLAY) {
MGLOG_E("InitializeEGLDisplay failed: invalid EGLDisplay");
return false;
}
if (m_eglDisplayInitialized && m_eglDisplay != dpy) {
MGLOG_E("InitializeEGLDisplay failed: backend already bound to a different EGLDisplay");
return false;
}
m_eglDisplay = dpy;
m_eglDisplayInitialized = true;
if (major) {
*major = 1;
}
if (minor) {
*minor = 5;
}
return true;
}
Bool BackendObject::CreateEGLWindowSurface(EGLSurface surface, const WindowHandle& handle) {
const std::lock_guard<std::recursive_mutex> lock(m_eglStateMutex);
return RegisterEGLWindowSurface(surface, handle) && ActivateEGLSurface(surface);
}
Bool BackendObject::ResizeEGLWindowSurface(EGLSurface surface, Uint32 width, Uint32 height) {
const std::lock_guard<std::recursive_mutex> lock(m_eglStateMutex);
auto surfaceIt = m_eglSurfaces.find(surface);
if (surfaceIt == m_eglSurfaces.end() || surfaceIt->second.Kind != SurfaceKind::Window) {
MGLOG_E("ResizeEGLWindowSurface failed: no window surface is initialized");
return false;
}
surfaceIt->second.Window.Width = width;
surfaceIt->second.Window.Height = height;
if (m_eglSurface == surface) {
m_windowHandle.Width = width;
m_windowHandle.Height = height;
}
return true;
}
Bool BackendObject::CreateEGLPbufferSurface(EGLSurface surface, EGLint width, EGLint height) {
const std::lock_guard<std::recursive_mutex> lock(m_eglStateMutex);
return RegisterEGLPbufferSurface(surface, width, height) && ActivateEGLSurface(surface);
}
Bool BackendObject::RegisterEGLWindowSurface(EGLSurface surface, const WindowHandle& handle) {
const std::lock_guard<std::recursive_mutex> lock(m_eglStateMutex);
if (!m_eglDisplayInitialized) {
MGLOG_E("RegisterEGLWindowSurface failed: EGL display is not initialized");
return false;
}
if (surface == EGL_NO_SURFACE) {
MGLOG_E("RegisterEGLWindowSurface failed: invalid EGLSurface");
return false;
}
if (handle.Backend == WindowBackend::Unknown || !handle.Handle) {
MGLOG_E("RegisterEGLWindowSurface failed: invalid native window handle");
return false;
}
auto& state = m_eglSurfaces[surface];
state = EGLSurfaceState{
.Kind = SurfaceKind::Window,
.Window = handle,
.Width = static_cast<EGLint>(std::max<Uint32>(handle.Width, 1)),
.Height = static_cast<EGLint>(std::max<Uint32>(handle.Height, 1)),
};
return true;
}
Bool BackendObject::RegisterEGLPbufferSurface(EGLSurface surface, EGLint width, EGLint height) {
const std::lock_guard<std::recursive_mutex> lock(m_eglStateMutex);
if (!m_eglDisplayInitialized) {
MGLOG_E("RegisterEGLPbufferSurface failed: EGL display is not initialized");
return false;
}
if (surface == EGL_NO_SURFACE) {
MGLOG_E("RegisterEGLPbufferSurface failed: invalid EGLSurface");
return false;
}
if (width <= 0 || height <= 0) {
MGLOG_E("RegisterEGLPbufferSurface failed: invalid size %dx%d", width, height);
return false;
}
m_eglSurfaces[surface] = EGLSurfaceState{
.Kind = SurfaceKind::Pbuffer,
.Width = width,
.Height = height,
};
return true;
}
const BackendObject::EGLSurfaceState* BackendObject::GetRegisteredEGLSurface(EGLSurface surface) const {
const std::lock_guard<std::recursive_mutex> lock(m_eglStateMutex);
auto surfaceIt = m_eglSurfaces.find(surface);
return surfaceIt == m_eglSurfaces.end() ? nullptr : &surfaceIt->second;
}
Bool BackendObject::ActivateEGLSurface(EGLSurface surface) {
const std::lock_guard<std::recursive_mutex> lock(m_eglStateMutex);
const auto* surfaceState = GetRegisteredEGLSurface(surface);
if (!surfaceState) {
MGLOG_E("ActivateEGLSurface failed: EGL surface is not registered");
return false;
}
if (m_eglSurfaceInitialized && m_eglSurface == surface) {
return true;
}
if (surfaceState->Kind == SurfaceKind::Window) {
SetWindowHandle(surfaceState->Window);
if (!InitWindowSurface()) {
MGLOG_E("ActivateEGLSurface failed: backend InitWindowSurface failed");
return false;
}
} else if (surfaceState->Kind == SurfaceKind::Pbuffer) {
if (!InitPbufferSurface(surfaceState->Width, surfaceState->Height)) {
MGLOG_E("ActivateEGLSurface failed: backend InitPbufferSurface failed");
return false;
}
} else {
MGLOG_E("ActivateEGLSurface failed: unsupported surface kind");
return false;
}
m_eglSurface = surface;
m_eglSurfaceInitialized = true;
m_eglSurfaceKind = surfaceState->Kind;
m_eglCurrentThreads.clear();
m_backendCapabilitiesInitialized = false;
return true;
}
Bool BackendObject::MakeEGLCurrent(EGLDisplay dpy, EGLSurface draw, EGLSurface read, EGLContext ctx) {
const std::lock_guard<std::recursive_mutex> lock(m_eglStateMutex);
const auto threadKey = CurrentThreadKey();
if (IsReleaseCurrentRequest(dpy, draw, read, ctx)) {
ReleaseEGLCurrentThread(threadKey);
return true;
}
if (!m_eglDisplayInitialized || m_eglDisplay != dpy) {
MGLOG_E("MakeEGLCurrent failed: EGL display mismatch or not initialized");
return false;
}
if (!m_eglSurfaceInitialized) {
if (draw != read || !ActivateEGLSurface(draw)) {
MGLOG_E("MakeEGLCurrent failed: EGL surface is not initialized");
return false;
}
}
if (!GetRegisteredEGLSurface(draw) || !GetRegisteredEGLSurface(read)) {
MGLOG_E("MakeEGLCurrent failed: EGL surface is not registered");
return false;
}
if (draw != read) {
MGLOG_E("MakeEGLCurrent failed: separate draw/read surfaces are not supported");
return false;
}
if (draw != m_eglSurface && !ActivateEGLSurface(draw)) {
MGLOG_E("MakeEGLCurrent failed: EGL surface is not backed by this backend");
return false;
}
if (draw == EGL_NO_SURFACE || read == EGL_NO_SURFACE || ctx == EGL_NO_CONTEXT) {
MGLOG_E("MakeEGLCurrent failed: draw/read/context is invalid");
return false;
}
if (!m_backendCapabilitiesInitialized) {
if (!InitCapabilities()) {
MGLOG_E("MakeEGLCurrent failed: InitCapabilities failed");
return false;
}
m_backendCapabilitiesInitialized = true;
}
ReleaseEGLCurrentThread(threadKey);
m_eglCurrentThreads[threadKey] = EGLCurrentState{
.Display = dpy,
.DrawSurface = draw,
.ReadSurface = read,
.Context = ctx,
};
return true;
}
void BackendObject::ResetEGLRuntimeState() {
const std::lock_guard<std::recursive_mutex> lock(m_eglStateMutex);
m_eglSurfaceInitialized = false;
m_backendCapabilitiesInitialized = false;
m_eglSurfaceKind = SurfaceKind::None;
m_eglSurface = EGL_NO_SURFACE;
m_windowHandle = {};
m_eglCurrentThreads.clear();
}
Bool BackendObject::SwapEGLBuffers(EGLDisplay dpy, EGLSurface draw) {
const std::lock_guard<std::recursive_mutex> lock(m_eglStateMutex);
if (!m_eglDisplayInitialized || m_eglDisplay != dpy) {
MGLOG_E("SwapEGLBuffers failed: EGL display mismatch or not initialized");
return false;
}
const auto currentIt = m_eglCurrentThreads.find(CurrentThreadKey());
if (currentIt == m_eglCurrentThreads.end()) {
MGLOG_E("SwapEGLBuffers failed: no current context attached");
return false;
}
if (currentIt->second.Display != dpy || currentIt->second.DrawSurface != draw ||
currentIt->second.Context == EGL_NO_CONTEXT) {
MGLOG_E("SwapEGLBuffers failed: draw surface is not current on this thread");
return false;
}
if (!m_eglSurfaceInitialized || draw == EGL_NO_SURFACE || draw != m_eglSurface) {
MGLOG_E("SwapEGLBuffers failed: invalid draw surface");
return false;
}
const auto& backendFunctions = GetBackendFunctions();
if (!backendFunctions.Present) {
MGLOG_E("SwapEGLBuffers failed: backend Present function is null");
return false;
}
backendFunctions.Present();
return true;
}
void BackendObject::SetEGLSwapInterval(Int interval) {
const auto& backendFunctions = GetBackendFunctions();
if (backendFunctions.SetSwapInterval) {
backendFunctions.SetSwapInterval(interval);
}
}
Bool BackendObject::IsEGLSurfaceCurrent(EGLSurface surface) const {
if (surface == EGL_NO_SURFACE) {
return false;
}
for (const auto& current : m_eglCurrentThreads) {
if (current.second.DrawSurface == surface || current.second.ReadSurface == surface) {
return true;
}
}
return false;
}
void BackendObject::DestroyPendingEGLSurfaceIfUnused(EGLSurface surface) {
auto surfaceIt = m_eglSurfaces.find(surface);
if (surfaceIt == m_eglSurfaces.end() || !surfaceIt->second.DestroyPending ||
IsEGLSurfaceCurrent(surface)) {
return;
}
m_eglSurfaces.erase(surfaceIt);
if (m_eglSurface == surface) {
OnEGLSurfaceReleased(surface);
ResetEGLRuntimeState();
}
}
void BackendObject::ReleaseEGLCurrentThread(const std::thread::id& threadKey) {
auto currentIt = m_eglCurrentThreads.find(threadKey);
if (currentIt == m_eglCurrentThreads.end()) {
return;
}
const EGLSurface drawSurface = currentIt->second.DrawSurface;
const EGLSurface readSurface = currentIt->second.ReadSurface;
m_eglCurrentThreads.erase(currentIt);
DestroyPendingEGLSurfaceIfUnused(drawSurface);
DestroyPendingEGLSurfaceIfUnused(readSurface);
}
void BackendObject::ReleaseEGLSurface(EGLSurface surface) {
const std::lock_guard<std::recursive_mutex> lock(m_eglStateMutex);
auto surfaceIt = m_eglSurfaces.find(surface);
if (surfaceIt == m_eglSurfaces.end()) {
return;
}
if (IsEGLSurfaceCurrent(surface)) {
surfaceIt->second.DestroyPending = true;
return;
}
m_eglSurfaces.erase(surfaceIt);
if (m_eglSurface == surface) {
OnEGLSurfaceReleased(surface);
ResetEGLRuntimeState();
}
}
void BackendObject::ReleaseEGLResources() {
const std::lock_guard<std::recursive_mutex> lock(m_eglStateMutex);
ResetEGLRuntimeState();
m_eglSurfaces.clear();
m_eglDisplay = EGL_NO_DISPLAY;
m_eglDisplayInitialized = false;
}
void BackendObject::SetWindowHandle(const WindowHandle& handle) {
const std::lock_guard<std::recursive_mutex> lock(m_eglStateMutex);
m_windowHandle = handle;
}
const FormatCapabilityCache& BackendObject::GetFormatCapabilities() const {
return m_formatCapabilities;
}
FormatCapabilityCache& BackendObject::MutableFormatCapabilities() {
return m_formatCapabilities;
}
Bool BackendObject::InitPbufferSurface(EGLint width, EGLint height) {
(void)width;
(void)height;
return false;
}
void BackendObject::OnEGLSurfaceReleased(EGLSurface surface) {
(void)surface;
}
} // namespace MobileGL::MG_Backend
+496
View File
@@ -0,0 +1,496 @@
// MobileGL - MobileGL/MG_Backend/BackendObject.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 <Includes.h>
#include "MG_State/GLState/TextureState/TextureEnum.h"
namespace MobileGL {
namespace MG_State::GLState {
class FramebufferObject;
class ITextureObject;
}
enum class BackendType {
DirectGLES,
DirectVulkan,
BackendTypeCount,
Unknown = -1
};
namespace MG_Backend {
enum class FormatCapability : Uint64 {
Creatable = 1ull << 0,
Sampled = 1ull << 1,
LinearFilter = 1ull << 2,
GenerateMipmap = 1ull << 3,
TextureGather = 1ull << 4,
TextureShadow = 1ull << 5,
FramebufferRenderable = 1ull << 6,
FramebufferLayered = 1ull << 7,
MultisampleTexture = 1ull << 8,
MultisampleRenderbuffer = 1ull << 9,
ColorAttachment = 1ull << 10,
DepthAttachment = 1ull << 11,
StencilAttachment = 1ull << 12,
TextureBuffer = 1ull << 13
};
using FormatCapabilityFlags = Flags<FormatCapability>;
inline constexpr Array<FormatCapability, 14> kReportedFormatCapabilities = {
FormatCapability::Creatable,
FormatCapability::Sampled,
FormatCapability::LinearFilter,
FormatCapability::GenerateMipmap,
FormatCapability::TextureGather,
FormatCapability::TextureShadow,
FormatCapability::FramebufferRenderable,
FormatCapability::FramebufferLayered,
FormatCapability::MultisampleTexture,
FormatCapability::MultisampleRenderbuffer,
FormatCapability::ColorAttachment,
FormatCapability::DepthAttachment,
FormatCapability::StencilAttachment,
FormatCapability::TextureBuffer,
};
inline constexpr SizeT kFormatCapabilityTextureTargetCount =
static_cast<SizeT>(TextureTarget::TextureTargetCount);
inline constexpr SizeT kFormatCapabilityRenderbufferTargetIndex = kFormatCapabilityTextureTargetCount;
inline constexpr SizeT kFormatCapabilityTargetCount = kFormatCapabilityTextureTargetCount + 1;
inline constexpr SizeT kFormatCapabilityFormatCount =
static_cast<SizeT>(TextureInternalFormat::TextureInternalFormatCount);
using FormatCapabilityTable =
Array<Array<FormatCapabilityFlags, kFormatCapabilityFormatCount>, kFormatCapabilityTargetCount>;
using FormatSampleCountTable =
Array<Array<Vector<Int>, kFormatCapabilityFormatCount>, kFormatCapabilityTargetCount>;
struct FormatCapabilityCache {
FormatCapabilityTable FullCaps{};
FormatCapabilityTable CaveatCaps{};
FormatSampleCountTable SampleCounts{};
void Clear();
};
Bool HasFormatCapability(FormatCapabilityFlags caps, FormatCapability capability);
SizeT GetFormatCapabilityTargetIndex(TextureTarget target);
SizeT GetRenderbufferFormatCapabilityTargetIndex();
const char* GetFormatCapabilityName(FormatCapability capability);
String GetFormatCapabilityTargetName(SizeT targetIndex);
void PrintFormatCapabilities(const FormatCapabilityCache& cache);
// Opaque backend fence-sync handle, created by GLFunctionsTable::FenceSync
// and released by GLFunctionsTable::DeleteSync.
using BackendSyncHandle = void*;
// Opaque backend timer-query handle, created by
// GLFunctionsTable::BeginTimeElapsedQuery / QueryCounterTimestamp and
// released by GLFunctionsTable::DeleteBackendQuery.
using BackendQueryHandle = void*;
struct GLFunctionsTable {
void (*DrawArrays)(GLenum mode, GLint first, GLsizei count);
void (*DrawElements)(GLenum mode, GLsizei count, GLenum type, const void* indices);
void (*DrawElementsBaseVertex)(GLenum mode, GLsizei count, GLenum type, const void* indices,
GLint basevertex);
void (*MultiDrawArrays)(GLenum mode, const GLint* first, const GLsizei* count, GLsizei drawcount);
void (*MultiDrawElements)(GLenum mode, const GLsizei* count, GLenum type, const GLvoid* const* indices,
GLsizei drawcount);
void (*MultiDrawElementsBaseVertex)(GLenum mode, const GLsizei* count, GLenum type,
const GLvoid* const* indices, GLsizei drawcount,
const GLint* basevertex);
void (*MultiDrawElementsIndirect)(GLenum mode, GLenum type, const void* indirect, GLsizei drawcount,
GLsizei stride);
void (*MultiDrawArraysIndirect)(GLenum mode, const void* indirect, GLsizei drawcount, GLsizei stride);
void (*MultiDrawElementsIndirectCount)(GLenum mode, GLenum type, const void* indirect,
GLintptr drawcount, GLsizei maxdrawcount, GLsizei stride);
void (*MultiDrawArraysIndirectCount)(GLenum mode, const void* indirect, GLintptr drawcount,
GLsizei maxdrawcount, GLsizei stride);
void (*DrawRangeElementsBaseVertex)(GLenum mode, GLuint start, GLuint end, GLsizei count, GLenum type,
const void* indices, GLint basevertex);
void (*DrawRangeElements)(GLenum mode, GLuint start, GLuint end, GLsizei count, GLenum type,
const void* indices);
void (*DrawElementsInstancedBaseVertexBaseInstance)(GLenum mode, GLsizei count, GLenum type,
const void* indices, GLsizei instancecount,
GLint basevertex, GLuint baseinstance);
void (*DrawElementsInstancedBaseVertex)(GLenum mode, GLsizei count, GLenum type, const void* indices,
GLsizei instancecount, GLint basevertex);
void (*DrawElementsInstancedBaseInstance)(GLenum mode, GLsizei count, GLenum type, const void* indices,
GLsizei instancecount, GLuint baseinstance);
void (*DrawElementsInstanced)(GLenum mode, GLsizei count, GLenum type, const void* indices,
GLsizei instancecount);
void (*DrawArraysInstancedBaseInstance)(GLenum mode, GLint first, GLsizei count, GLsizei instancecount,
GLuint baseinstance);
void (*DrawArraysInstanced)(GLenum mode, GLint first, GLsizei count, GLsizei instancecount);
void (*DrawElementsIndirect)(GLenum mode, GLenum type, const void* indirect);
void (*DrawArraysIndirect)(GLenum mode, const void* indirect);
void (*Clear)(GLbitfield mask);
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);
void (*ClearBufferiv)(GLenum buffer, GLint drawbuffer, const GLint* value);
void (*ClearNamedFramebufferfv)(const SharedPtr<MG_State::GLState::FramebufferObject>& framebuffer,
GLenum buffer, GLint drawbuffer, const GLfloat* value);
void (*ClearNamedFramebufferfi)(const SharedPtr<MG_State::GLState::FramebufferObject>& framebuffer,
GLenum buffer, GLint drawbuffer, GLfloat depth, GLint stencil);
void (*ClearNamedFramebufferiv)(const SharedPtr<MG_State::GLState::FramebufferObject>& framebuffer,
GLenum buffer, GLint drawbuffer, const GLint* value);
void (*ClearNamedFramebufferuiv)(const SharedPtr<MG_State::GLState::FramebufferObject>& framebuffer,
GLenum buffer, GLint drawbuffer, const GLuint* value);
void (*BlitFramebuffer)(GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1, GLint dstX0, GLint dstY0,
GLint dstX1, GLint dstY1, GLbitfield mask, GLenum filter);
void (*BlitNamedFramebuffer)(const SharedPtr<MG_State::GLState::FramebufferObject>& readFramebuffer,
const SharedPtr<MG_State::GLState::FramebufferObject>& drawFramebuffer,
GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1,
GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1,
GLbitfield mask, GLenum filter);
void (*CopyTexImage2D)(GLenum target, GLint level, GLenum internalformat, GLint x, GLint y, GLsizei width,
GLsizei height, GLint border);
void (*CopyTexSubImage2D)(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint x, GLint y,
GLsizei width, GLsizei height);
void (*CopyImageSubData)(const SharedPtr<MG_State::GLState::ITextureObject>& srcTexture,
GLenum srcTarget, GLint srcLevel, GLint srcX, GLint srcY, GLint srcZ,
const SharedPtr<MG_State::GLState::ITextureObject>& dstTexture,
GLenum dstTarget, GLint dstLevel, GLint dstX, GLint dstY, GLint dstZ,
GLsizei srcWidth, GLsizei srcHeight, GLsizei srcDepth);
void (*GenerateMipmap)(GLenum target);
void (*ReadPixels)(GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type,
void* pixels);
void (*GetTexImage)(GLenum target, GLint level, GLenum format, GLenum type, GLvoid* pixels);
void (*GetTextureImage)(const SharedPtr<MG_State::GLState::ITextureObject>& texture,
TextureUploadTarget uploadTarget, GLint level, GLenum format, GLenum type,
GLsizei bufSize, GLvoid* pixels);
void (*DispatchCompute)(GLuint numGroupsX, GLuint numGroupsY, GLuint numGroupsZ);
void (*DispatchComputeIndirect)(GLintptr indirect);
void (*MemoryBarrier)(GLbitfield barriers);
void (*MemoryBarrierByRegion)(GLbitfield barriers);
void (*BindImageTexture)(GLuint unit, GLuint texture, GLint level, GLboolean layered, GLint layer,
GLenum access, GLenum format);
void (*GetIntegeri_v)(GLenum target, GLuint index, GLint* data);
void (*GetInteger64i_v)(GLenum target, GLuint index, GLint64* data);
void (*GetProgramiv)(GLuint program, GLenum pname, GLint* params);
// The GL program interface (glGetProgramInterfaceiv / glGetProgramResource*) is NOT
// a backend query: it describes the program the application wrote, in the
// application's namespace, which neither backend program is in. It is answered
// entirely by MG_Impl/GLImpl/Program/ProgramInterface from the frontend reflection.
// Takes the block's GL NAME, not glShaderStorageBlockBinding's index. The index
// the application passes is the frontend interface-query enumeration's, and no
// backend shares that index space: DirectVulkan enumerates SPIR-V descriptor
// bindings and DirectGLES asks a real driver about SPIRV-Cross-generated ESSL.
// The name is the one coordinate all three agree on, so the frontend resolves the
// index against its own enumeration and each backend maps the name to its own.
void (*ShaderStorageBlockBinding)(GLuint program, const GLchar* storageBlockName,
GLuint storageBlockBinding);
// GL fence sync objects. All entries are optional (may be null); the
// frontend then falls back to always-signaled sync semantics.
// FenceSync may itself return null when the backend cannot create a
// fence right now (e.g. the calling thread does not own the backend
// context); the frontend treats such a sync as always signaled.
BackendSyncHandle (*FenceSync)();
GLenum (*ClientWaitSync)(BackendSyncHandle sync, GLbitfield flags, GLuint64 timeout);
void (*WaitSync)(BackendSyncHandle sync, GLbitfield flags, GLuint64 timeout);
void (*DeleteSync)(BackendSyncHandle sync);
Bool (*GetSyncStatus)(BackendSyncHandle sync); // true = signaled
// GL timer-query objects (GL_ARB_timer_query). All entries are
// optional (may be null); the frontend then falls back to zero
// results and reports GL_QUERY_COUNTER_BITS == 0.
// BeginTimeElapsedQuery / QueryCounterTimestamp may themselves
// return null when the backend cannot create a query right now;
// the frontend treats such a query as immediately available with
// a zero result.
// Dynamic support check: true only when the live backend can
// actually time at the moment of the call (extension / entry
// points / timestamp valid bits are known then, not at table
// init). Gates the advertised GL_QUERY_COUNTER_BITS.
Bool (*IsTimerQuerySupported)();
BackendQueryHandle (*BeginTimeElapsedQuery)(); // starts a TIME_ELAPSED span
void (*EndTimeElapsedQuery)(BackendQueryHandle query); // ends the span
BackendQueryHandle (*QueryCounterTimestamp)(); // glQueryCounter(GL_TIMESTAMP) one-shot
Bool (*IsQueryResultAvailable)(BackendQueryHandle query); // non-blocking
// Returns true when a final value was produced (*outNanoseconds
// written; the frontend may cache it and release the handle).
// Returns false when the result could not be obtained YET - e.g.
// a Vulkan wait that refuses to block on a not-yet-submitted
// frame serial - in which case the frontend must keep the handle
// and leave the query readable later.
Bool (*GetQueryResult64)(BackendQueryHandle query, Bool wait, Uint64* outNanoseconds);
void (*DeleteBackendQuery)(BackendQueryHandle query);
// GL_SAMPLES_PASSED occlusion queries (optional; null = unsupported,
// the frontend then rejects the target). Results/deletion flow through
// GetQueryResult64 / DeleteBackendQuery like timer queries.
BackendQueryHandle (*BeginOcclusionQuery)();
void (*EndOcclusionQuery)(BackendQueryHandle query);
// Transform feedback primitive queries backed by real GPU query pools
// (optional; null = frontend falls back to CPU accounting).
BackendQueryHandle (*BeginXfbPrimitivesQuery)(Bool generated);
void (*EndXfbPrimitivesQuery)(BackendQueryHandle query);
// Transform feedback capture spans, for backends whose own GL/ES driver
// performs the capture (DirectGLES). Both optional; null means the backend
// drives capture from its draw recording instead (DirectVulkan). End is
// called while the frontend capture state is still active, so the backend
// can still see the capture program and buffer bindings.
// GL_PATCH_VERTICES; ES 3.2 spells it the same way.
void (*PatchParameteri)(GLenum pname, GLint value);
void (*BeginTransformFeedback)(GLenum primitiveMode);
void (*EndTransformFeedback)();
// ARB_transform_feedback2. A backend that leaves these null keeps the single
// implicit capture span the frontend has always modelled; the frontend state
// (paused flag, per-object bindings) is tracked either way.
void (*PauseTransformFeedback)();
void (*ResumeTransformFeedback)();
void (*BindTransformFeedback)(GLuint name);
void (*DeleteTransformFeedback)(GLuint name);
Int64 (*GetGpuTimestampNs)(); // glGetInteger64v(GL_TIMESTAMP); 0 if unsupported
};
struct GlobalBackendFunctionsTable {
GLFunctionsTable GL;
void (*Present)();
// Optional: applies the app-requested eglSwapInterval to the native
// presentation path (null = backend keeps its own pacing policy).
void (*SetSwapInterval)(Int interval);
};
// Coarse GPU vendor identity for gating device-specific quirks. Detected from the
// Vulkan physical-device vendorID or the GLES GL_VENDOR/GL_RENDERER strings; stays
// Unknown when detection is inconclusive, in which case auto-gated quirks stay off.
enum class GpuVendorKind : Uint8 {
Unknown = 0,
Qualcomm,
Arm,
Nvidia,
Amd,
Intel,
ImgTec,
// Software rasterizers (llvmpipe/lavapipe, SwiftShader).
Software,
};
struct DynamicBackendParameters {
SizeT UniformBufferOffsetAlignment = 256;
// GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT. 1.0 means the backend cannot filter anisotropically,
// which is also why the extension is not advertised in that case.
Float MaxTextureMaxAnisotropy = 1.0f;
Float AliasedLineWidthRangeMin = 1.0f;
Float AliasedLineWidthRangeMax = 1.0f;
Float SmoothLineWidthRangeMin = 1.0f;
Float SmoothLineWidthRangeMax = 1.0f;
Float SmoothLineWidthGranularity = 1.0f;
Float PointSizeRangeMin = 1.0f;
Float PointSizeRangeMax = 1.0f;
Float PointSizeGranularity = 1.0f;
Int Max3DTextureSize = 16384;
Int MaxArrayTextureLayers = 2048;
Int MaxCubeMapTextureSize = 16384;
Int MaxFramebufferWidth = 16384;
Int MaxFramebufferHeight = 16384;
Int MaxFramebufferLayers = 2048;
Int MaxRenderbufferSize = 16384;
Int MaxTextureSize = 16384;
Int MaxColorTextureSamples = 1;
Int MaxDepthTextureSamples = 1;
Int MaxFramebufferSamples = 1;
Int MaxIntegerSamples = 1;
Int MaxSamples = 1;
Int MaxSampleMaskWords = 1;
// Tessellation limits; defaults are the GL 4.0 core minimums.
Int MaxPatchVertices = 32;
Int MaxTessGenLevel = 64;
// GL_MIN/MAX_PROGRAM_TEXTURE_GATHER_OFFSET. Defaults are the GL 4.0 core
// minimums, which every ES 3.1 driver also guarantees.
Int MinProgramTextureGatherOffset = -8;
Int MaxProgramTextureGatherOffset = 7;
Int MaxTextureImageUnits = 32;
Int MaxVertexTextureImageUnits = 32;
Int MaxComputeTextureImageUnits = 32;
Int MaxCombinedTextureImageUnits = 192;
Int MaxVertexAttribs = 16;
Int MaxComputeShaderStorageBlocks = 8;
Int MaxCombinedShaderStorageBlocks = 32;
Int MaxComputeUniformBlocks = 12;
Int MaxComputeWorkGroupInvocations = 128;
Int MaxShaderStorageBufferBindings = 8;
Int MaxTextureBufferSize = 65536;
// GL_TEXTURE_BUFFER_OFFSET_ALIGNMENT; 1 means the offset is unconstrained.
Int TextureBufferOffsetAlignment = 1;
Int MaxUniformBufferBindings = 24;
Int MaxUniformBlockSize = 16384;
Int MaxImageUnits = 8;
Int MaxCombinedImageUniforms = 8;
Int MaxVertexImageUniforms = 0;
Int MaxGeometryImageUniforms = 0;
Int MaxFragmentImageUniforms = 8;
Int MaxComputeImageUniforms = 8;
Int MaxDrawBuffers = 8;
Int MaxColorAttachments = 8;
Int MaxClipDistances = 8;
Int MaxViewports = 16;
Int MaxViewportWidth = 16384;
Int MaxViewportHeight = 16384;
Float ViewportBoundsRangeMin = 0.0f;
Float ViewportBoundsRangeMax = 0.0f;
Int ViewportSubpixelBits = 0;
// GL 4.x fragment-interpolation offset limits. These defaults are the
// core minimums and are replaced by live GLES/Vulkan device limits.
Float MinFragmentInterpolationOffset = -0.5f;
// For four fractional bits the greatest required legal offset is
// 0.5 - 2^-4 = 0.4375 (GL 4.6 table 23.70).
Float MaxFragmentInterpolationOffset = 0.4375f;
Int FragmentInterpolationOffsetBits = 4;
Bool SupportsWideLines = false;
// Whether a framebuffer whose depth and stencil attachments are distinct
// images can be rendered to. GL only requires support when both refer to the
// same image and lets an implementation answer GL_FRAMEBUFFER_UNSUPPORTED
// otherwise, which is what DirectVulkan (one combined attachment) and the
// real ES drivers behind DirectGLES both do. Defaults to true so a backend
// that never sets it keeps the permissive behaviour.
Bool SupportsDistinctDepthStencilAttachments = true;
// Whether attaching a single layer of a 3D or array texture to a framebuffer actually
// renders to that layer. DirectGLES hands the layer straight to
// glFramebufferTextureLayer, so it does; DirectVulkan maps a GL layer onto a Vulkan
// array layer with no notion of a 3D depth slice, so it does not yet. Defaults to false
// so a backend that never sets it gets the conservative answer.
// Which layered texture targets this backend can attach ONE layer of to a framebuffer
// and then really clear, render and read back that layer. Bit (1u << TextureTarget) is
// set for each supported target. Deliberately per target rather than one flag: the three
// ways a GL layer maps onto Vulkan are independent capabilities. A 2D or 2D multisample
// array layer IS a VkImage array layer and needs nothing extra; a 3D texture's layer is
// a z slice, which needs a 2D-array-compatible image and a per-slice clear that
// vkCmdClearColorImage cannot express; a cube map array needs an image shape and the
// imageCubeArray feature before it can be attached at any layer at all. Defaults to 0 so
// a backend that never sets it gets the conservative answer.
Uint32 PerLayerFramebufferAttachmentTargets = 0;
static constexpr Uint32 PerLayerFramebufferAttachmentBit(TextureTarget target) {
return (static_cast<Int>(target) >= 0 &&
static_cast<Int>(target) < static_cast<Int>(TextureTarget::TextureTargetCount))
? (1u << static_cast<Uint32>(target))
: 0u;
}
Bool SupportsPerLayerFramebufferAttachment(TextureTarget target) const {
const Uint32 bit = PerLayerFramebufferAttachmentBit(target);
return bit != 0 && (PerLayerFramebufferAttachmentTargets & bit) != 0;
}
// Whether glVertexAttribLFormat / glVertexArrayAttribLFormat can be honoured, i.e.
// whether a 64-bit vertex attribute can actually reach a shader unconverted. Detected,
// never assumed: DirectVulkan needs VkPhysicalDeviceFeatures::shaderFloat64 (the
// attribute travels as its 32-bit word pair, so no VK_FORMAT_R64* is required, but the
// bitcast result is Float64); DirectGLES can never have it, ESSL having no fp64 type at
// all. Defaults to false so a backend that never sets it gets the conservative answer.
Bool SupportsFloat64VertexAttributes = false;
SizeT MaxShaderStorageBlockSize = 128 * 1024 * 1024;
Uint32 SubgroupSize = 0;
Uint32 SubgroupSupportedStages = 0;
Uint32 SubgroupSupportedFeatures = 0;
Bool SubgroupQuadOperationsInAllStages = false;
GpuVendorKind GpuVendor = GpuVendorKind::Unknown;
};
enum class WindowBackend {
Android,
X11,
MetalLayer,
Win32, // Handle is an HWND
// TODO: Wayland, etc.
WindowBackendCount,
Unknown = -1
};
struct WindowHandle {
WindowBackend Backend = WindowBackend::Unknown;
void* Handle = nullptr;
Uint32 Width = 0;
Uint32 Height = 0;
};
class BackendObject {
public:
virtual ~BackendObject() = default;
virtual void Initialize() = 0;
virtual Bool InitCapabilities() = 0;
virtual Bool InitWindowSurface() = 0;
virtual Bool InitializeEGLDisplay(EGLDisplay dpy, EGLint* major, EGLint* minor);
virtual Bool CreateEGLWindowSurface(EGLSurface surface, const WindowHandle& handle);
virtual Bool ResizeEGLWindowSurface(EGLSurface surface, Uint32 width, Uint32 height);
virtual Bool CreateEGLPbufferSurface(EGLSurface surface, EGLint width, EGLint height);
virtual Bool MakeEGLCurrent(EGLDisplay dpy, EGLSurface draw, EGLSurface read, EGLContext ctx);
virtual Bool SwapEGLBuffers(EGLDisplay dpy, EGLSurface draw);
// Forwards the app-requested eglSwapInterval to the backend's native
// presentation path (no-op for backends without a SetSwapInterval hook).
virtual void SetEGLSwapInterval(Int interval);
virtual void ReleaseEGLSurface(EGLSurface surface);
virtual void ReleaseEGLResources();
void SetWindowHandle(const WindowHandle& handle);
virtual const RendererInfo& GetRendererInfo() const = 0;
virtual String GetBackendAPIVersionString() const = 0;
virtual const GlobalBackendFunctionsTable& GetBackendFunctions() const = 0;
virtual const DynamicBackendParameters& GetDynamicParameters() const = 0;
const FormatCapabilityCache& GetFormatCapabilities() const;
virtual BackendType GetBackendType() const = 0;
protected:
enum class SurfaceKind {
None,
Window,
Pbuffer
};
struct EGLCurrentState {
EGLDisplay Display = EGL_NO_DISPLAY;
EGLSurface DrawSurface = EGL_NO_SURFACE;
EGLSurface ReadSurface = EGL_NO_SURFACE;
EGLContext Context = EGL_NO_CONTEXT;
};
struct EGLSurfaceState {
SurfaceKind Kind = SurfaceKind::None;
Bool DestroyPending = false;
WindowHandle Window;
EGLint Width = 1;
EGLint Height = 1;
};
void ResetEGLRuntimeState();
Bool RegisterEGLWindowSurface(EGLSurface surface, const WindowHandle& handle);
Bool RegisterEGLPbufferSurface(EGLSurface surface, EGLint width, EGLint height);
const EGLSurfaceState* GetRegisteredEGLSurface(EGLSurface surface) const;
Bool ActivateEGLSurface(EGLSurface surface);
virtual Bool InitPbufferSurface(EGLint width, EGLint height);
virtual void OnEGLSurfaceReleased(EGLSurface surface);
FormatCapabilityCache& MutableFormatCapabilities();
mutable std::recursive_mutex m_eglStateMutex;
FormatCapabilityCache m_formatCapabilities;
WindowHandle m_windowHandle;
EGLDisplay m_eglDisplay = EGL_NO_DISPLAY;
EGLSurface m_eglSurface = EGL_NO_SURFACE;
Bool m_eglDisplayInitialized = false;
Bool m_eglSurfaceInitialized = false;
Bool m_backendCapabilitiesInitialized = false;
SurfaceKind m_eglSurfaceKind = SurfaceKind::None;
UnorderedMap<std::thread::id, EGLCurrentState> m_eglCurrentThreads;
UnorderedMap<EGLSurface, EGLSurfaceState> m_eglSurfaces;
private:
Bool IsEGLSurfaceCurrent(EGLSurface surface) const;
void DestroyPendingEGLSurfaceIfUnused(EGLSurface surface);
void ReleaseEGLCurrentThread(const std::thread::id& threadKey);
};
} // namespace MG_Backend
} // namespace MobileGL
+18
View File
@@ -0,0 +1,18 @@
// MobileGL - MobileGL/MG_Backend/BackendObjects.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 <Includes.h>
#include "BackendObject.h"
#include "DirectGLES/BackendObject_DirectGLES.h"
#include "DirectVulkan/BackendObject_DirectVulkan.h"
namespace MobileGL::MG_Backend {
extern UniquePtr<BackendObject>& pActiveBackendObject;
extern GlobalBackendFunctionsTable gBackendFunctionsTable;
} // namespace MobileGL::MG_Backend
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,78 @@
// MobileGL - MobileGL/MG_Backend/DirectGLES/BackendObject_DirectGLES.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 <Includes.h>
#include "../BackendObject.h"
#include <MG_Util/BackendLoaders/OpenGL/Loader.h>
namespace MobileGL::MG_Backend::DirectGLES {
// Populates the same format-capability cache used by backend startup. The caller
// must keep the supplied GLES context current for the duration of this call.
void PopulateFormatCapabilities(const MG_External::GLESFunctionsTable& gl,
const MG_External::GLESCapabilities& capabilities,
FormatCapabilityCache& cache);
class BackendObject_DirectGLES : public BackendObject {
public:
~BackendObject_DirectGLES() override;
void Initialize() override;
Bool InitCapabilities() override;
Bool InitWindowSurface() override;
Bool InitializeEGLDisplay(EGLDisplay dpy, EGLint* major, EGLint* minor) override;
Bool CreateEGLWindowSurface(EGLSurface surface, const WindowHandle& handle) override;
Bool CreateEGLPbufferSurface(EGLSurface surface, EGLint width, EGLint height) override;
Bool MakeEGLCurrent(EGLDisplay dpy, EGLSurface draw, EGLSurface read, EGLContext ctx) override;
Bool SwapEGLBuffers(EGLDisplay dpy, EGLSurface draw) override;
void ReleaseEGLSurface(EGLSurface surface) override;
void ReleaseEGLResources() override;
const RendererInfo& GetRendererInfo() const override;
String GetBackendAPIVersionString() const override;
const GlobalBackendFunctionsTable& GetBackendFunctions() const override;
const DynamicBackendParameters& GetDynamicParameters() const override;
BackendType GetBackendType() const override;
const MG_External::GLESFunctionsTable& GetGLESFunctions() const;
const MG_External::EGLFunctionsTable& GetEGLFunctions() const;
void ApplyGLESCapabilitiesForTesting(const MG_External::GLESCapabilities& capabilities);
private:
void UpdateDynamicBackendParameters();
Bool InitPbufferSurface(EGLint width, EGLint height) override;
void OnEGLSurfaceReleased(EGLSurface surface) override;
Bool m_initialized = false;
MG_External::EGLFunctionsTable m_EGLFunctions;
MG_External::GLESFunctionsTable m_GLESFunctions;
MG_External::GLESCapabilities m_GLESCapabilities;
DynamicBackendParameters m_dynamicParameters;
};
// Single-source-of-truth helpers shared with the driver POST
// (MG_Util/SelfTest/DriverPost.cpp), so the identity strings and extension list
// MobileGL reports to applications on this backend cannot drift from what the
// POST screen shows.
// Static identity of the Espryt renderer (renderer/backend names, target GL/GLSL
// versions, ExtraVendor). The Extensions vector inside is live backend state that
// is reconciled after capability init; callers that need the advertised list for
// a known capability set must use BuildAdvertisedExtensions instead.
const RendererInfo& GetRendererIdentity();
// The full OpenGL extension list Espryt advertises (glGetString(GL_EXTENSIONS))
// for a device whose timer queries / anisotropic filtering are (or are not) usable.
// The MOBILEGL_DISABLE_TIMERQUERY escape hatch is applied inside.
Vector<GLExtension> BuildAdvertisedExtensions(Bool timerQueriesSupported, Bool anisotropicFilteringSupported);
// Format: <OpenGL ES Renderer>, OpenGL ES <Major>.<Minor> — the exact string an
// initialized backend returns from GetBackendAPIVersionString (and that ends up
// inside the application-visible GL_RENDERER string).
String FormatBackendAPIVersionString(const String& glesRendererString, Int glesMajor, Int glesMinor);
} // namespace MobileGL::MG_Backend::DirectGLES
File diff suppressed because it is too large Load Diff
+214
View File
@@ -0,0 +1,214 @@
// MobileGL - MobileGL/MG_Backend/DirectGLES/DirectGLES.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 <Includes.h>
#include <MG_Backend/BackendObject.h>
#include <MG_State/GLState/FramebufferState/FramebufferObject.h>
#include <MG_State/GLState/TextureState/TextureState.h>
#include <MG_State/GLState/SamplerState/SamplerObject.h>
#include <MG_Util/BackendLoaders/OpenGL/Loader.h>
#define CallAndCheck(operation) \
MGLOG_D("Call GLES func: %s", #operation); \
operation Utils::CheckGLESError();
namespace MobileGL::MG_Backend::DirectGLES {
// Re-establishes the frontend texture-unit bindings on the native ES context.
// Content uploads use scratch bindings, so draws and dispatches call this after
// texture synchronization.
void BindCurrentTextures();
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);
void ClearBufferiv(GLenum buffer, GLint drawbuffer, const GLint* value);
void Clear(GLbitfield mask);
void DrawElements(GLenum mode, GLsizei count, GLenum type, const void* indices);
void DrawArrays(GLenum mode, GLint first, GLsizei count);
void DrawElementsBaseVertex(GLenum mode, GLsizei count, GLenum type, const GLvoid* indices, GLint basevertex);
void MultiDrawArrays(GLenum mode, const GLint* first, const GLsizei* count, GLsizei drawcount);
void MultiDrawElements(GLenum mode, const GLsizei* count, GLenum type, const GLvoid* const* indices,
GLsizei drawcount);
void MultiDrawElementsBaseVertex(GLenum mode, const GLsizei* count, GLenum type, const GLvoid* const* indices,
GLsizei drawcount, const GLint* basevertex);
void MultiDrawElementsIndirect(GLenum mode, GLenum type, const void* indirect, GLsizei drawcount, GLsizei stride);
void MultiDrawElementsIndirectCount(GLenum mode, GLenum type, const void* indirect, GLintptr drawcount,
GLsizei maxdrawcount, GLsizei stride);
void MultiDrawArraysIndirect(GLenum mode, const void* indirect, GLsizei drawcount, GLsizei stride);
void DrawRangeElementsBaseVertex(GLenum mode, GLuint start, GLuint end, GLsizei count, GLenum type,
const void* indices, GLint basevertex);
void DrawRangeElements(GLenum mode, GLuint start, GLuint end, GLsizei count, GLenum type, const void* indices);
void DrawElementsInstancedBaseVertexBaseInstance(GLenum mode, GLsizei count, GLenum type, const void* indices,
GLsizei instancecount, GLint basevertex, GLuint baseinstance);
void DrawElementsInstancedBaseVertex(GLenum mode, GLsizei count, GLenum type, const void* indices,
GLsizei instancecount, GLint basevertex);
void DrawElementsInstancedBaseInstance(GLenum mode, GLsizei count, GLenum type, const void* indices,
GLsizei instancecount, GLuint baseinstance);
void DrawElementsInstanced(GLenum mode, GLsizei count, GLenum type, const void* indices, GLsizei instancecount);
void DrawElementsIndirect(GLenum mode, GLenum type, const void* indirect);
void DrawArraysInstancedBaseInstance(GLenum mode, GLint first, GLsizei count, GLsizei instancecount,
GLuint baseinstance);
void DrawArraysInstanced(GLenum mode, GLint first, GLsizei count, GLsizei instancecount);
void DrawArraysIndirect(GLenum mode, const void* indirect);
void ClearNamedFramebufferfv(const SharedPtr<MG_State::GLState::FramebufferObject>& framebuffer,
GLenum buffer, GLint drawbuffer, const GLfloat* value);
void ClearNamedFramebufferfi(const SharedPtr<MG_State::GLState::FramebufferObject>& framebuffer,
GLenum buffer, GLint drawbuffer, GLfloat depth, GLint stencil);
void ClearNamedFramebufferiv(const SharedPtr<MG_State::GLState::FramebufferObject>& framebuffer,
GLenum buffer, GLint drawbuffer, const GLint* value);
void ClearNamedFramebufferuiv(const SharedPtr<MG_State::GLState::FramebufferObject>& framebuffer,
GLenum buffer, GLint drawbuffer, const GLuint* value);
void BlitFramebuffer(GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1, GLint dstX0, GLint dstY0, GLint dstX1,
GLint dstY1, GLbitfield mask, GLenum filter);
void BlitNamedFramebuffer(const SharedPtr<MG_State::GLState::FramebufferObject>& readFramebuffer,
const SharedPtr<MG_State::GLState::FramebufferObject>& drawFramebuffer,
GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1,
GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1,
GLbitfield mask, GLenum filter);
void CopyTexImage2D(GLenum target, GLint level, GLenum internalformat, GLint x, GLint y, GLsizei width,
GLsizei height, GLint border);
void CopyTexSubImage2D(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint x, GLint y, GLsizei width,
GLsizei height);
void CopyImageSubData(const SharedPtr<MG_State::GLState::ITextureObject>& srcTexture,
GLenum srcTarget, GLint srcLevel, GLint srcX, GLint srcY, GLint srcZ,
const SharedPtr<MG_State::GLState::ITextureObject>& dstTexture,
GLenum dstTarget, GLint dstLevel, GLint dstX, GLint dstY, GLint dstZ,
GLsizei srcWidth, GLsizei srcHeight, GLsizei srcDepth);
void GenerateMipmap(GLenum target);
const GLubyte* GetString(GLenum name);
void ReadPixels(GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, void* pixels);
void GetTexImage(GLenum target, GLint level, GLenum format, GLenum type, GLvoid* pixels);
void DispatchCompute(GLuint numGroupsX, GLuint numGroupsY, GLuint numGroupsZ);
void DispatchComputeIndirect(GLintptr indirect);
void MemoryBarrier(GLbitfield barriers);
void MemoryBarrierByRegion(GLbitfield barriers);
void BindImageTexture(GLuint unit, GLuint texture, GLint level, GLboolean layered, GLint layer, GLenum access,
GLenum format);
void GetIntegeri_v(GLenum target, GLuint index, GLint* data);
void GetInteger64i_v(GLenum target, GLuint index, GLint64* data);
void GetProgramiv(GLuint program, GLenum pname, GLint* params);
void ShaderStorageBlockBinding(GLuint program, const GLchar* storageBlockName, GLuint storageBlockBinding);
Bool InitWindowSurface(NativeWindowType window);
Bool InitPbufferSurface(EGLint width, EGLint height);
Bool MakeCurrent();
Bool ReleaseCurrent();
// True when the backend ES context is current on the calling thread, i.e.
// immediate buffer ops may issue GL calls right now.
Bool IsBackendContextCurrentOnThisThread();
// GL fence sync objects, backed by native ES fences. FenceSync returns null
// (the frontend then falls back to an always-signaled sync) when the calling
// thread does not own the ES context. Waits/queries degrade to "signaled" in
// the same situation, and handles created under a since-destroyed ES context
// are always treated as signaled.
BackendSyncHandle FenceSync();
GLenum ClientWaitSync(BackendSyncHandle sync, GLbitfield flags, GLuint64 timeout);
void WaitSync(BackendSyncHandle sync, GLbitfield flags, GLuint64 timeout);
void DeleteSync(BackendSyncHandle sync);
Bool GetSyncStatus(BackendSyncHandle sync);
// True when GL_EXT_disjoint_timer_query and every entry point the timer
// hooks below need are present. Also gates the E_GL_ARB_timer_query
// advertisement in BackendObject_DirectGLES::InitCapabilities, and is
// registered as the GLFunctionsTable::IsTimerQuerySupported hook: a pure
// capability read needs no current ES context, and it stays false until
// the ES capabilities have been filled in.
Bool AreTimerQueriesSupported();
// GL timer-query objects, backed by GL_EXT_disjoint_timer_query. The
// creators return null (the frontend then falls back to an immediately
// available zero result) when the calling thread does not own the ES
// context or the extension/entry points are missing, and handles created
// under a since-destroyed ES context are always treated as complete with
// a zero result (mirrors the fence-sync handles above).
BackendQueryHandle BeginTimeElapsedQuery();
void EndTimeElapsedQuery(BackendQueryHandle query);
BackendQueryHandle QueryCounterTimestamp();
// GL_ANY_SAMPLES_PASSED(_CONSERVATIVE) occlusion queries: core ES3, independent of
// GL_EXT_disjoint_timer_query and of MOBILEGL_DISABLE_TIMERQUERY. Results/deletion
// flow through GetQueryResult64/DeleteBackendQuery like the timer queries above.
BackendQueryHandle BeginOcclusionQuery();
void EndOcclusionQuery(BackendQueryHandle query);
// GL_TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN / GL_PRIMITIVES_GENERATED, also core ES
// (GL_PRIMITIVES_GENERATED from ES 3.2 on). Null when the target is unavailable, in
// which case the frontend falls back to counting primitives from the draw calls.
BackendQueryHandle BeginXfbPrimitivesQuery(Bool generated);
void EndXfbPrimitivesQuery(BackendQueryHandle query);
Bool IsQueryResultAvailable(BackendQueryHandle query);
// Returns true when a final value landed in *outNanoseconds (a zero for
// null or stale-generation handles IS final: the frontend may cache it
// and release the handle). Returns false only when the calling thread
// does not own the ES context, so the value is genuinely unobtainable
// right now; the handle stays alive and readable later.
Bool GetQueryResult64(BackendQueryHandle query, Bool wait, Uint64* outNanoseconds);
void DeleteBackendQuery(BackendQueryHandle query);
Int64 GetGpuTimestampNs();
void Present();
// Frame-completion watermarks for the buffer-storage pool: CurrentFrameSerial()
// is bumped once per Present(); CompletedFrameSerial() is the newest frame whose
// GPU work has provably finished (advanced by polling a one-fence-per-frame ring).
// A buffer retired during frame N is safe to recycle once CompletedFrameSerial() >= N.
Uint64 CurrentFrameSerial();
Uint64 CompletedFrameSerial();
// Block (up to timeoutNs) until the given frame serial provably retired on the
// GPU, using the per-frame fence ring. False when no usable fence covers the
// serial (fence-less context, foreign thread, or the slot was recycled);
// completion state is untouched in that case.
Bool WaitForFrameSerialCompleted(Uint64 serial, Uint64 timeoutNs);
// Applies (or defers until the window surface exists) the app-requested
// eglSwapInterval on the native EGL surface.
void SetSwapInterval(Int interval);
void SetEGLFuncsTable(const MG_External::EGLFunctionsTable& eglFuncs);
void SetGLESFuncsTable(const MG_External::GLESFunctionsTable& glesFuncs);
void SetGLESCapabilities(const MG_External::GLESCapabilities& capabilities);
void DestroyEGLContext();
// Transform feedback capture spans, performed by the real ES driver. The
// capture set is declared on the backend program at link time; the driver-side
// begin is deferred to the first draw of the span (ES needs the capturing
// program current and the capture buffers bound), and the end also mirrors the
// captured bytes back into the frontend buffer shadows.
void PatchParameteri(GLenum pname, GLint value);
namespace XfbImpl {
Bool AreTransformFeedbacksSupported();
// True while a capture span is open on the current transform feedback object
// (frontend Begin seen and not paused), whether or not the deferred driver-side
// Begin has been issued yet. Draw paths that would restructure the primitive
// stream, or that need to dispatch compute mid-draw, decline while it is set.
Bool IsCaptureSpanOpen();
void BeginTransformFeedback(GLenum primitiveMode);
void EndTransformFeedback();
void PauseTransformFeedback();
void ResumeTransformFeedback();
void BindTransformFeedback(GLuint name);
void DeleteTransformFeedback(GLuint name);
void OnBackendContextDestroyed();
} // namespace XfbImpl
namespace RenderStateImpl {
// Pushes the frontend's render-state block to the ES driver, diffed against what was
// last pushed.
//
// `forColorClear` names the CALLER, and the only thing it changes is the colour write
// mask handed to the driver. A draw into a colour attachment the backend widened from
// three channels to four gets that buffer's alpha channel masked OFF, so nothing can
// move the stored alpha away from the 1.0 the application's three-channel format
// implies (see FramebufferImpl::g_alphaWidenedDrawBufferMask). A CLEAR is how that 1.0
// gets there in the first place, so it must be allowed to write alpha - hence the flag
// rather than an unconditional doctoring. It is part of the sync memo, so a clear
// followed by a draw re-pushes the mask instead of early-outing on an unchanged
// frontend version.
//
// The application's own colour mask is never modified: glGet(GL_COLOR_WRITEMASK)
// answers from the frontend state, which this function only reads.
void SyncRenderState(Bool forColorClear = false);
void InvalidateSyncedRenderState();
} // namespace RenderStateImpl
extern MG_External::EGLFunctionsTable g_EGLFuncs;
extern MG_External::GLESFunctionsTable g_GLESFuncs;
extern MG_External::GLESCapabilities g_GLESCapabilities;
} // namespace MobileGL::MG_Backend::DirectGLES
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,894 @@
// MobileGL - MobileGL/MG_Backend/DirectGLES/MultiDraw.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 "MultiDraw.h"
#include "Managers.h"
#include <MG_State/GLState/Core.h>
#include <cstring>
#include <limits>
namespace MobileGL::MG_Backend::DirectGLES::MultiDrawImpl {
using MG_Config::GLESMultiDrawMode;
namespace {
// ---------------------------------------------------------------------------
// Batch shape
// ---------------------------------------------------------------------------
SizeT IndexTypeSize(GLenum type) {
switch (type) {
case GL_UNSIGNED_BYTE: return 1;
case GL_UNSIGNED_SHORT: return 2;
case GL_UNSIGNED_INT: return 4;
default: return 0;
}
}
// The all-ones value of an index type, which is what GL restarts on once
// primitive restart is in play. CheckPrimitiveRestartSupported has already
// rejected the arbitrary-index form of GL_PRIMITIVE_RESTART, so an enabled
// restart always restarts here and nowhere else.
Uint32 RestartSentinelFor(GLenum type) {
switch (type) {
case GL_UNSIGNED_BYTE: return 0xFFu;
case GL_UNSIGNED_SHORT: return 0xFFFFu;
default: return 0xFFFFFFFFu;
}
}
Bool RestartActive() {
return MG_State::pGLContext->IsCapabilityEnabled(CapabilityInput::PrimitiveRestart) ||
MG_State::pGLContext->IsCapabilityEnabled(CapabilityInput::PrimitiveRestartFixedIndex);
}
// Vertices per primitive for the modes whose sub-draws may be concatenated into a
// single draw without changing the primitive stream. Zero for strip/loop/fan modes
// (concatenation would weld one sub-draw's last primitive to the next sub-draw's
// first) and for GL_PATCHES, whose primitive size is dynamic tessellation state.
Uint32 ConcatenablePrimitiveSize(GLenum mode) {
switch (mode) {
case GL_POINTS: return 1;
case GL_LINES: return 2;
case GL_TRIANGLES: return 3;
case GL_LINES_ADJACENCY: return 4;
case GL_TRIANGLES_ADJACENCY: return 6;
default: return 0;
}
}
// Beyond this an emulated batch would ask for a scratch allocation measured in
// hundreds of megabytes (and the scratch ring never shrinks again); decline and let
// a per-sub-draw tier handle it instead of trying and failing inside the driver.
constexpr SizeT kMaxFlattenedIndices = SizeT{1} << 24;
// The flattening dispatch is one invocation per output index. ES 3.1 only
// guarantees 65535 work groups per dimension, and exceeding it makes
// glDispatchCompute an INVALID_VALUE no-op - which would leave the draw reading an
// uninitialised index buffer rather than failing visibly. Cap the tier there
// instead of querying: 4.19M indices is far past any real multi-draw batch, and
// beyond it the per-sub-draw tiers are the better answer anyway.
constexpr SizeT kComputeWorkGroupSize = 64;
constexpr SizeT kMaxComputeWorkGroups = 65535;
constexpr SizeT kMaxComputeFlattenedIndices = kMaxComputeWorkGroups * kComputeWorkGroupSize;
Uint BoundDrawIndirectBufferId() {
const auto& indirect =
MG_State::pGLContext->GetBufferBindingSlot(BufferTarget::DrawIndirect).GetBoundObject();
if (!indirect) return 0;
const auto* resource = BufferImpl::EnsureBufferResource(indirect);
return resource ? resource->id : 0;
}
const SharedPtr<MG_State::GLState::BufferObject>& BoundIndexBuffer() {
static const SharedPtr<MG_State::GLState::BufferObject> none;
const auto& vao = MG_State::pGLContext->GetBoundVertexArray();
if (!vao) return none;
return vao->GetIndexBufferBindingSlot().GetBoundObject();
}
// The GL name PrepareForDraw left on GL_ELEMENT_ARRAY_BUFFER, i.e. what a tier
// that swaps in a scratch index buffer has to put back. Restoring the exact name
// matters beyond tidiness: the VAO twin memoises that it already synced this
// index binding and will not re-issue it on the next draw.
Uint BoundIndexBufferId() {
const auto& ibo = BoundIndexBuffer();
if (!ibo) return 0;
const auto* resource = BufferImpl::EnsureBufferResource(ibo);
return resource ? resource->id : 0;
}
// ---------------------------------------------------------------------------
// Scratch GL objects
//
// All of them belong to the ES context and are abandoned (not deleted) when it
// dies, exactly like XfbImpl's scatter buffer: the names are the dead context's
// to reclaim, and deleting them would target whatever the successor context
// handed out for the same name.
// ---------------------------------------------------------------------------
struct ScratchBuffer {
Uint id = 0;
SizeT capacity = 0;
SizeT cursor = 0; // ring buffers only: next free byte
};
ScratchBuffer g_indirectCommands; // synthesized DrawElementsIndirectCommand array
ScratchBuffer g_rebasedIndices; // CPU-rebased index stream
ScratchBuffer g_drawInfo; // compute tier: per-sub-draw descriptors
ScratchBuffer g_flattenedIndices; // compute tier: flattened index stream
Uint g_computeProgram = 0;
Bool g_computeProgramFailed = false;
GLint g_uElementSize = -1;
GLint g_uDrawCount = -1;
GLint g_uTotalIndices = -1;
// Reused staging, so a steady stream of batches allocates nothing.
Vector<DrawElementsIndirectCommand> g_commandStaging;
Vector<Uint32> g_indexStaging;
Vector<Uint32> g_drawInfoStaging;
Vector<GLint> g_zeroBaseVertices;
// Everything below stages through GL_ARRAY_BUFFER, the manager-wide staging target
// (BufferImpl::TempBufferTarget); binding it disturbs no VAO state.
Bool EnsureScratchName(ScratchBuffer& buffer) {
if (buffer.id != 0) return true;
GLuint id = 0;
g_GLESFuncs.glGenBuffers(1, &id);
if (id == 0) return false;
buffer.id = id;
buffer.capacity = 0;
buffer.cursor = 0;
return true;
}
// Whole-buffer upload, for the two buffers that are read from offset 0 because they
// are bound as storage blocks. Respecifies rather than sub-updates: glBufferData
// orphans the previous store, so the upload never waits on a dispatch still reading
// the old contents out of the same name.
Bool UploadScratch(ScratchBuffer& buffer, SizeT bytes, const void* data) {
if (bytes == 0) return true;
if (!EnsureScratchName(buffer)) return false;
BufferImpl::BindBufferId(BufferImpl::TempBufferTarget, buffer.id);
// Grow in powers of two so a batch that creeps up in size stops respecifying.
SizeT capacity = buffer.capacity == 0 ? bytes : buffer.capacity;
while (capacity < bytes) capacity *= 2;
g_GLESFuncs.glBufferData(BufferImpl::TempBufferTarget, static_cast<GLsizeiptr>(capacity), nullptr,
GL_STREAM_DRAW);
buffer.capacity = capacity;
buffer.cursor = 0;
if (data) {
g_GLESFuncs.glBufferSubData(BufferImpl::TempBufferTarget, 0, static_cast<GLsizeiptr>(bytes), data);
}
return true;
}
// Ring upload, for the buffers whose consumers can address a byte offset (indirect
// commands and rewritten index streams). Respecifying per batch is what an
// orphan-every-time scheme costs, and on a desktop-class driver that allocation
// dominated the tiers that use these buffers - a multi-draw of 32 sub-draws stages
// 640 bytes and paid for a fresh store to hold them. Bump-allocating instead means
// one respecify per wrap; every byte between two wraps is written exactly once, so
// nothing in flight is overwritten, and the wrap itself orphans.
constexpr SizeT kRingAlignment = 16; // >= 4, so both command and uint32-index offsets stay legal
constexpr SizeT kMinRingBytes = 1u << 16;
Bool UploadScratchRing(ScratchBuffer& buffer, SizeT bytes, const void* data, SizeT& outOffset) {
outOffset = 0;
if (bytes == 0) return true;
if (!EnsureScratchName(buffer)) return false;
BufferImpl::BindBufferId(BufferImpl::TempBufferTarget, buffer.id);
const SizeT aligned = (bytes + kRingAlignment - 1) & ~(kRingAlignment - 1);
if (buffer.capacity < aligned) {
SizeT capacity = buffer.capacity == 0 ? kMinRingBytes : buffer.capacity;
while (capacity < aligned) capacity *= 2;
g_GLESFuncs.glBufferData(BufferImpl::TempBufferTarget, static_cast<GLsizeiptr>(capacity), nullptr,
GL_STREAM_DRAW);
buffer.capacity = capacity;
buffer.cursor = 0;
} else if (buffer.cursor + aligned > buffer.capacity) {
g_GLESFuncs.glBufferData(BufferImpl::TempBufferTarget, static_cast<GLsizeiptr>(buffer.capacity),
nullptr, GL_STREAM_DRAW);
buffer.cursor = 0;
}
outOffset = buffer.cursor;
if (data) {
g_GLESFuncs.glBufferSubData(BufferImpl::TempBufferTarget, static_cast<GLintptr>(outOffset),
static_cast<GLsizeiptr>(bytes), data);
}
buffer.cursor += aligned;
return true;
}
// ---------------------------------------------------------------------------
// Tier resolution
// ---------------------------------------------------------------------------
// Best-first, and measured rather than assumed. MobileGlues orders its own Auto
// multiindirect -> indirect -> basevertex; on both ES drivers available here that
// is backwards, because staging a command buffer per batch costs more than the
// driver entries it saves. mc_sodium_multidraw (132 batches x 32 sub-draws),
// ns/op, median of three:
//
// NVIDIA ES 3.2 Mesa llvmpipe ES 3.2
// ext n/a 19300
// basevertex 2500 25200
// multiindirect 5700 27600
// drawelements 5600 28700
// indirect 5800 31000
//
// Ring-allocating the command staging (instead of respecifying per batch) was
// tried first and moved the indirect tiers by less than noise, so the cost is the
// indirect draw path itself, not the upload. Only "ext" - a real multi-draw entry
// point rather than an indirect one - actually beats replaying the sub-draws.
//
// The compute tier is deliberately absent from the ladder: it rewrites the
// primitive stream rather than replaying it, and it measured slowest of all here,
// so it stays opt-in behind the env knob (the same call MobileGlues makes - its
// Auto never selects Compute either).
constexpr GLESMultiDrawMode kAutoLadder[] = {
GLESMultiDrawMode::Ext, GLESMultiDrawMode::BaseVertex, GLESMultiDrawMode::MultiIndirect,
GLESMultiDrawMode::Indirect, GLESMultiDrawMode::DrawElements,
};
Bool SupportsTier(GLESMultiDrawMode tier) {
return IsTierSupported(g_GLESCapabilities, g_GLESFuncs, tier);
}
GLESMultiDrawMode g_resolvedTier = GLESMultiDrawMode::Auto;
Bool g_tierResolved = false;
String g_tierResolution;
void ResolveTierOnce() {
if (g_tierResolved) return;
g_tierResolved = true;
g_resolvedTier =
ResolveTier(g_GLESCapabilities, g_GLESFuncs, MG_Config::Features.EsprytMultiDrawMode,
&g_tierResolution);
MGLOG_I("DirectGLES multi-draw: %s", g_tierResolution.c_str());
}
// Which tiers have already announced themselves, one bit per GLESMultiDrawMode.
// The resolution line above says which tier was CHOSEN; this says which one a
// batch actually went through, and the two differ whenever a batch's shape
// demotes it. Worth a line each: a multi-draw path that resolves to a tier and
// then quietly runs a different one is exactly how "the batch drew nothing"
// hides.
Uint32 g_announcedTiers = 0;
void NoteTierExecuted(GLESMultiDrawMode tier) {
const Uint32 bit = 1u << static_cast<Uint32>(tier);
if (g_announcedTiers & bit) return;
g_announcedTiers |= bit;
MGLOG_I("DirectGLES multi-draw: first batch executed via tier \"%s\"", TierName(tier));
}
// The tier this particular batch can actually take. A tier is demoted here when
// the batch's own shape - not the driver - rules it out; the compute tier keeps
// its remaining feasibility checks inside its implementation, where the data it
// has to walk is already in hand.
GLESMultiDrawMode ResolveTierForBatch(Bool programReadsDrawID, Bool hasIndexBuffer) {
ResolveTierOnce();
GLESMultiDrawMode tier = g_resolvedTier;
// Batched tiers issue one driver entry for the whole batch, so the emulated
// gl_DrawID uniform can only hold one value across every sub-draw. A program
// that reads gl_DrawID gets an unrolled tier, which feeds each sub-draw its
// own index (the spec's value); nothing else observes the difference.
const Bool batched = tier == GLESMultiDrawMode::Ext || tier == GLESMultiDrawMode::MultiIndirect ||
tier == GLESMultiDrawMode::Compute;
if (batched && programReadsDrawID) {
tier = SupportsTier(GLESMultiDrawMode::BaseVertex) ? GLESMultiDrawMode::BaseVertex
: GLESMultiDrawMode::DrawElements;
}
// The indirect tiers describe each sub-draw as an element offset into the
// bound element array buffer. A client-memory index array has no such buffer,
// and indirect draws are not defined without one.
if (!hasIndexBuffer &&
(tier == GLESMultiDrawMode::MultiIndirect || tier == GLESMultiDrawMode::Indirect)) {
tier = SupportsTier(GLESMultiDrawMode::BaseVertex) ? GLESMultiDrawMode::BaseVertex
: GLESMultiDrawMode::DrawElements;
}
return tier;
}
// ---------------------------------------------------------------------------
// Index rewriting, shared by the two tiers that fold base vertices into indices
// ---------------------------------------------------------------------------
// Both of those tiers emit GL_UNSIGNED_INT regardless of the source type. Keeping
// the source width would be wrong, not merely tight: GL adds baseVertex to the
// index at full precision, so a GL_UNSIGNED_SHORT index plus a base vertex past
// 65535 addresses a vertex the source type cannot spell. Widening also gives the
// rewritten stream a restart sentinel (0xFFFFFFFF) that survives the rebase.
void RebaseIndices(const Uint8* source, SizeT sourceIndexCount, SizeT indexSize, Int32 baseVertex,
Bool restartActive, Uint32 restartSentinel, Uint32* out) {
const Uint32 baseVertexBits = static_cast<Uint32>(baseVertex);
for (SizeT i = 0; i < sourceIndexCount; ++i) {
Uint32 value = 0;
switch (indexSize) {
case 1: value = source[i]; break;
case 2: {
Uint16 narrow = 0;
std::memcpy(&narrow, source + i * 2, sizeof(narrow));
value = narrow;
break;
}
default: std::memcpy(&value, source + i * 4, sizeof(value)); break;
}
// Unsigned wraparound is the defined behaviour for a negative base vertex.
out[i] = (restartActive && value == restartSentinel) ? 0xFFFFFFFFu : value + baseVertexBits;
}
}
// CPU-readable bytes of one sub-draw's indices, from the frontend shadow of the
// bound index buffer or straight from the client array. Null when the sub-draw
// would read outside the buffer.
const Uint8* ResolveSubDrawIndices(const SharedPtr<MG_State::GLState::BufferObject>& indexBuffer,
const Uint8* indexBufferBytes, SizeT indexBufferSize, const void* indices,
SizeT indexCount, SizeT indexSize) {
if (!indexBuffer) {
return static_cast<const Uint8*>(indices);
}
if (!indexBufferBytes) return nullptr;
const SizeT byteOffset = reinterpret_cast<SizeT>(indices);
const SizeT byteEnd = byteOffset + indexCount * indexSize;
if (byteEnd > indexBufferSize || byteEnd < byteOffset) return nullptr;
return indexBufferBytes + byteOffset;
}
// ---------------------------------------------------------------------------
// Tier: Ext - one glMultiDrawElementsBaseVertexEXT
// ---------------------------------------------------------------------------
Bool RunExt(GLenum mode, const GLsizei* count, GLenum type, const GLvoid* const* indices, GLsizei drawcount,
const GLint* basevertex) {
if (!SupportsTier(GLESMultiDrawMode::Ext)) return false;
const GLint* baseVertices = basevertex;
if (!baseVertices) {
// glMultiDrawElements: every base vertex is 0, but the entry point still
// wants an array. One permanently-zero vector serves every such batch.
if (g_zeroBaseVertices.size() < static_cast<SizeT>(drawcount)) {
g_zeroBaseVertices.resize(static_cast<SizeT>(drawcount), 0);
}
baseVertices = g_zeroBaseVertices.data();
}
g_GLESFuncs.glMultiDrawElementsBaseVertexEXT(mode, count, type, indices, drawcount, baseVertices);
NoteTierExecuted(GLESMultiDrawMode::Ext);
return true;
}
// ---------------------------------------------------------------------------
// Tiers: MultiIndirect / Indirect - synthesized indirect commands
// ---------------------------------------------------------------------------
Bool RunIndirect(GLenum mode, const GLsizei* count, GLenum type, const GLvoid* const* indices,
GLsizei drawcount, const GLint* basevertex, Bool batched, Bool feedDrawID) {
if (!SupportsTier(batched ? GLESMultiDrawMode::MultiIndirect : GLESMultiDrawMode::Indirect)) return false;
const SizeT indexSize = IndexTypeSize(type);
if (indexSize == 0) return false;
// Indirect commands address indices as an element offset into the bound element
// array buffer, and an indirect draw is not defined without one.
const auto& indexBuffer = BoundIndexBuffer();
if (!indexBuffer) return false;
g_commandStaging.resize(static_cast<SizeT>(drawcount));
for (GLsizei i = 0; i < drawcount; ++i) {
const SizeT byteOffset = reinterpret_cast<SizeT>(indices[i]);
// firstIndex counts elements, so an offset that is not a whole number of
// them cannot be expressed as a command at all.
if (byteOffset % indexSize != 0) return false;
auto& command = g_commandStaging[static_cast<SizeT>(i)];
command.count = count[i] > 0 ? static_cast<Uint32>(count[i]) : 0u;
command.instanceCount = 1;
command.firstIndex = static_cast<Uint32>(byteOffset / indexSize);
command.baseVertex = basevertex ? basevertex[i] : 0;
command.baseInstance = 0;
}
const SizeT commandBytes = g_commandStaging.size() * sizeof(DrawElementsIndirectCommand);
SizeT commandBase = 0;
if (!UploadScratchRing(g_indirectCommands, commandBytes, g_commandStaging.data(), commandBase)) {
return false;
}
// Every synthesized command carries baseInstance 0. Say so through the direct
// path, which also clears the indirect-params word index a preceding real
// indirect draw may have left pointing into its own command buffer.
SetCurrentBaseInstance(0);
const Uint previousIndirectBinding = BoundDrawIndirectBufferId();
BufferImpl::BindBufferId(GL_DRAW_INDIRECT_BUFFER, g_indirectCommands.id);
if (batched) {
g_GLESFuncs.glMultiDrawElementsIndirectEXT(mode, type, reinterpret_cast<const void*>(commandBase),
drawcount, 0);
} else {
for (GLsizei i = 0; i < drawcount; ++i) {
if (feedDrawID) SetCurrentDrawID(static_cast<Uint32>(i));
const SizeT commandOffset = commandBase + static_cast<SizeT>(i) * sizeof(DrawElementsIndirectCommand);
g_GLESFuncs.glDrawElementsIndirect(mode, type, reinterpret_cast<const void*>(commandOffset));
}
if (feedDrawID) SetCurrentDrawID(0);
}
BufferImpl::BindBufferId(GL_DRAW_INDIRECT_BUFFER, previousIndirectBinding);
NoteTierExecuted(batched ? GLESMultiDrawMode::MultiIndirect : GLESMultiDrawMode::Indirect);
return true;
}
// ---------------------------------------------------------------------------
// Tier: BaseVertex - the per-sub-draw replay
// ---------------------------------------------------------------------------
Bool RunBaseVertexLoop(GLenum mode, const GLsizei* count, GLenum type, const GLvoid* const* indices,
GLsizei drawcount, const GLint* basevertex, Bool feedDrawID) {
if (!SupportsTier(GLESMultiDrawMode::BaseVertex)) return false;
for (GLsizei i = 0; i < drawcount; ++i) {
if (count[i] <= 0) continue;
if (feedDrawID) SetCurrentDrawID(static_cast<Uint32>(i));
g_GLESFuncs.glDrawElementsBaseVertex(mode, count[i], type, indices[i],
basevertex ? basevertex[i] : 0);
}
if (feedDrawID) SetCurrentDrawID(0);
NoteTierExecuted(GLESMultiDrawMode::BaseVertex);
return true;
}
// ---------------------------------------------------------------------------
// Tier: DrawElements - base vertices folded into a scratch index stream
// ---------------------------------------------------------------------------
Bool RunRebasedDrawElements(GLenum mode, const GLsizei* count, GLenum type, const GLvoid* const* indices,
GLsizei drawcount, const GLint* basevertex, Bool feedDrawID) {
const SizeT indexSize = IndexTypeSize(type);
if (indexSize == 0) return false;
SizeT total = 0;
for (GLsizei i = 0; i < drawcount; ++i) {
if (count[i] > 0) total += static_cast<SizeT>(count[i]);
}
if (total == 0) return true;
if (total > kMaxFlattenedIndices) return false;
const auto& indexBuffer = BoundIndexBuffer();
const Uint8* indexBufferBytes = nullptr;
SizeT indexBufferSize = 0;
if (indexBuffer) {
// The shadow is the source of truth for CPU reads, but a persistent map or
// a shader write may have moved past it since the last sync.
indexBuffer->SyncPersistentMappedRange();
indexBuffer->SyncGpuWrites();
indexBufferBytes = indexBuffer->MappedData();
indexBufferSize = indexBuffer->GetSize();
}
const Bool restartActive = RestartActive();
const Uint32 restartSentinel = RestartSentinelFor(type);
g_indexStaging.resize(total);
SizeT cursor = 0;
for (GLsizei i = 0; i < drawcount; ++i) {
if (count[i] <= 0) continue;
const SizeT subDrawCount = static_cast<SizeT>(count[i]);
const Uint8* source = ResolveSubDrawIndices(indexBuffer, indexBufferBytes, indexBufferSize, indices[i],
subDrawCount, indexSize);
if (!source) {
MGLOG_E("DirectGLES multi-draw (drawelements tier): sub-draw %d reads outside the bound index "
"buffer; skipping the batch",
i);
return false;
}
RebaseIndices(source, subDrawCount, indexSize, basevertex ? basevertex[i] : 0, restartActive,
restartSentinel, g_indexStaging.data() + cursor);
cursor += subDrawCount;
}
SizeT indexBase = 0;
if (!UploadScratchRing(g_rebasedIndices, total * sizeof(Uint32), g_indexStaging.data(), indexBase)) {
return false;
}
const Uint previousIndexBinding = BoundIndexBufferId();
BufferImpl::BindBufferId(GL_ELEMENT_ARRAY_BUFFER, g_rebasedIndices.id);
cursor = 0;
for (GLsizei i = 0; i < drawcount; ++i) {
if (count[i] <= 0) continue;
if (feedDrawID) SetCurrentDrawID(static_cast<Uint32>(i));
g_GLESFuncs.glDrawElements(mode, count[i], GL_UNSIGNED_INT,
reinterpret_cast<const void*>(indexBase + cursor * sizeof(Uint32)));
cursor += static_cast<SizeT>(count[i]);
}
if (feedDrawID) SetCurrentDrawID(0);
BufferImpl::BindBufferId(GL_ELEMENT_ARRAY_BUFFER, previousIndexBinding);
NoteTierExecuted(GLESMultiDrawMode::DrawElements);
return true;
}
// ---------------------------------------------------------------------------
// Tier: Compute - the whole batch flattened into one rebased index stream
// ---------------------------------------------------------------------------
// One index per invocation. The sub-draw an output slot belongs to is found by
// binary search over the inclusive prefix sums of the sub-draw counts, which is
// why the descriptors are sorted by construction. Sub-draws with a zero count
// repeat the previous prefix sum and are therefore skipped by the search.
//
// Three storage blocks, not the five the shape suggests: ES 3.1 only guarantees
// four per compute stage, so the per-sub-draw descriptors share one buffer.
constexpr const char* kFlattenComputeSource = R"(#version 310 es
layout(local_size_x = 64) in;
uniform uint uElementSize;
uniform uint uDrawCount;
uniform uint uTotalIndices;
layout(std430, binding = 0) readonly buffer SourceIndices { uint sourceWords[]; };
layout(std430, binding = 1) readonly buffer DrawInfo { uint drawInfo[]; };
layout(std430, binding = 2) writeonly buffer FlatIndices { uint flatIndices[]; };
uint ReadSourceIndex(uint element) {
if (uElementSize == 4u) {
return sourceWords[element];
}
if (uElementSize == 2u) {
uint word = sourceWords[element >> 1u];
return (word >> ((element & 1u) * 16u)) & 0xFFFFu;
}
uint word = sourceWords[element >> 2u];
return (word >> ((element & 3u) * 8u)) & 0xFFu;
}
void main() {
uint outIndex = gl_GlobalInvocationID.x;
if (outIndex >= uTotalIndices) {
return;
}
uint low = 0u;
uint high = uDrawCount - 1u;
while (low < high) {
uint mid = low + (high - low) / 2u;
if (drawInfo[mid * 3u + 2u] > outIndex) {
high = mid;
} else {
low = mid + 1u;
}
}
uint localIndex = outIndex - (low == 0u ? 0u : drawInfo[(low - 1u) * 3u + 2u]);
// Unsigned wraparound is the defined behaviour for a negative base vertex. No
// restart sentinel handling: the tier declines outright while restart is enabled.
flatIndices[outIndex] = ReadSourceIndex(localIndex + drawInfo[low * 3u]) + drawInfo[low * 3u + 1u];
}
)";
struct FlattenedStream {
Uint bufferId = 0;
SizeT indexCount = 0;
};
Bool EnsureComputeProgram() {
if (g_computeProgram != 0) return true;
if (g_computeProgramFailed) return false;
g_computeProgramFailed = true; // cleared again only on a complete success
const GLuint shader = g_GLESFuncs.glCreateShader(GL_COMPUTE_SHADER);
if (shader == 0) {
MGLOG_E("DirectGLES multi-draw (compute tier): glCreateShader(GL_COMPUTE_SHADER) failed");
return false;
}
const char* source = kFlattenComputeSource;
g_GLESFuncs.glShaderSource(shader, 1, &source, nullptr);
g_GLESFuncs.glCompileShader(shader);
GLint status = GL_FALSE;
g_GLESFuncs.glGetShaderiv(shader, GL_COMPILE_STATUS, &status);
if (status != GL_TRUE) {
char log[1024] = {};
g_GLESFuncs.glGetShaderInfoLog(shader, sizeof(log) - 1, nullptr, log);
MGLOG_E("DirectGLES multi-draw (compute tier): index-flattening shader failed to compile: %s", log);
g_GLESFuncs.glDeleteShader(shader);
return false;
}
const GLuint program = g_GLESFuncs.glCreateProgram();
if (program == 0) {
MGLOG_E("DirectGLES multi-draw (compute tier): glCreateProgram failed");
g_GLESFuncs.glDeleteShader(shader);
return false;
}
g_GLESFuncs.glAttachShader(program, shader);
g_GLESFuncs.glLinkProgram(program);
g_GLESFuncs.glDeleteShader(shader);
g_GLESFuncs.glGetProgramiv(program, GL_LINK_STATUS, &status);
if (status != GL_TRUE) {
char log[1024] = {};
g_GLESFuncs.glGetProgramInfoLog(program, sizeof(log) - 1, nullptr, log);
MGLOG_E("DirectGLES multi-draw (compute tier): index-flattening program failed to link: %s", log);
g_GLESFuncs.glDeleteProgram(program);
return false;
}
g_computeProgram = program;
g_uElementSize = g_GLESFuncs.glGetUniformLocation(program, "uElementSize");
g_uDrawCount = g_GLESFuncs.glGetUniformLocation(program, "uDrawCount");
g_uTotalIndices = g_GLESFuncs.glGetUniformLocation(program, "uTotalIndices");
g_computeProgramFailed = false;
MGLOG_I("DirectGLES multi-draw: index-flattening compute program ready (id %u)", program);
return true;
}
// Builds the flattened stream, or leaves `out` empty when this batch's shape rules
// the tier out. Runs BEFORE PrepareForDraw - see the call site - so it may leave
// the compute program current and the first storage points unbound; the
// preparation that follows re-establishes both.
void FlattenWithCompute(GLenum mode, const GLsizei* count, GLenum type, const GLvoid* const* indices,
GLsizei drawcount, const GLint* basevertex, FlattenedStream& out) {
if (!SupportsTier(GLESMultiDrawMode::Compute)) return;
const SizeT indexSize = IndexTypeSize(type);
if (indexSize == 0) return;
// Merging sub-draws into a single draw only reproduces the original primitive
// stream for list-shaped modes: a strip, loop or fan would gain primitives
// spanning the seam between two sub-draws.
const Uint32 primitiveSize = ConcatenablePrimitiveSize(mode);
if (primitiveSize == 0) return;
// Primitive restart defeats the whole-multiple-of-a-primitive argument below,
// even for a list mode. A restart ends the current primitive, so a sub-draw of
// six GL_TRIANGLES indices with a restart after the third emits ONE triangle
// and drops the two leftover vertices - and once concatenated those leftovers
// find a third vertex in the next sub-draw and become a triangle that GL never
// draws. Splicing separator sentinels into the flattened stream could fix it,
// at the cost of a per-sub-draw offset the prefix-sum layout does not carry;
// declining is the honest trade for a tier that is already opt-in.
if (RestartActive()) return;
// The shader reads the source indices as a storage buffer, so there has to be
// a real buffer to read - a client-memory index array has none.
const auto& indexBuffer = BoundIndexBuffer();
if (!indexBuffer) return;
// A dispatch inside an open capture span is not legal, and the span would also
// observe one merged draw rather than the batch it asked for.
if (XfbImpl::IsCaptureSpanOpen()) return;
auto* sourceResource = BufferImpl::EnsureBufferResource(indexBuffer);
if (!sourceResource || sourceResource->id == 0) return;
const SizeT sourceSize = indexBuffer->GetSize();
// std430 addresses the source as uint[]; a tail shorter than a word is not
// reachable, so a narrow index type needs a word-multiple buffer.
if (indexSize < 4 && (sourceSize % 4) != 0) return;
g_drawInfoStaging.resize(3 * static_cast<SizeT>(drawcount));
SizeT total = 0;
for (GLsizei i = 0; i < drawcount; ++i) {
const SizeT subDrawCount = count[i] > 0 ? static_cast<SizeT>(count[i]) : 0;
// GL drops a trailing partial primitive per sub-draw; concatenation would
// instead splice it onto the next sub-draw's first vertices.
if (subDrawCount % primitiveSize != 0) return;
const SizeT byteOffset = reinterpret_cast<SizeT>(indices[i]);
if (byteOffset % indexSize != 0) return;
if (subDrawCount != 0) {
const SizeT byteEnd = byteOffset + subDrawCount * indexSize;
if (byteEnd > sourceSize || byteEnd < byteOffset) return;
}
total += subDrawCount;
if (total > kMaxComputeFlattenedIndices) return;
const SizeT slot = 3 * static_cast<SizeT>(i);
g_drawInfoStaging[slot] = static_cast<Uint32>(byteOffset / indexSize);
g_drawInfoStaging[slot + 1] = static_cast<Uint32>(basevertex ? basevertex[i] : 0);
g_drawInfoStaging[slot + 2] = static_cast<Uint32>(total);
}
if (total == 0) return; // nothing to draw; the ordinary tiers no-op just as well
if (!EnsureComputeProgram()) return;
if (!UploadScratch(g_drawInfo, g_drawInfoStaging.size() * sizeof(Uint32), g_drawInfoStaging.data())) {
return;
}
if (!UploadScratch(g_flattenedIndices, total * sizeof(Uint32), nullptr)) return;
BufferImpl::BindBufferBaseCached(GL_SHADER_STORAGE_BUFFER, 0, sourceResource->id);
BufferImpl::BindBufferBaseCached(GL_SHADER_STORAGE_BUFFER, 1, g_drawInfo.id);
BufferImpl::BindBufferBaseCached(GL_SHADER_STORAGE_BUFFER, 2, g_flattenedIndices.id);
g_GLESFuncs.glUseProgram(g_computeProgram);
PrgramImpl::g_lastUsedBackendProgramId = g_computeProgram;
if (g_uElementSize >= 0) g_GLESFuncs.glUniform1ui(g_uElementSize, static_cast<GLuint>(indexSize));
if (g_uDrawCount >= 0) g_GLESFuncs.glUniform1ui(g_uDrawCount, static_cast<GLuint>(drawcount));
if (g_uTotalIndices >= 0) g_GLESFuncs.glUniform1ui(g_uTotalIndices, static_cast<GLuint>(total));
g_GLESFuncs.glDispatchCompute(
static_cast<GLuint>((total + kComputeWorkGroupSize - 1) / kComputeWorkGroupSize), 1, 1);
g_GLESFuncs.glMemoryBarrier(GL_SHADER_STORAGE_BARRIER_BIT | GL_ELEMENT_ARRAY_BARRIER_BIT);
// Hand the storage points back to their GL default. PrepareForDraw re-syncs
// only the points the app has actually touched, so leaving a scratch buffer on
// an untouched point would keep it visible to the next shader that declares one.
for (Uint point = 0; point < 3; ++point) {
BufferImpl::BindBufferBaseCached(GL_SHADER_STORAGE_BUFFER, point, 0);
}
NoteTierExecuted(GLESMultiDrawMode::Compute);
out.bufferId = g_flattenedIndices.id;
out.indexCount = total;
}
} // namespace
// -------------------------------------------------------------------------------
// Public surface
// -------------------------------------------------------------------------------
Bool IsTierSupported(const MG_External::GLESCapabilities& caps, const MG_External::GLESFunctionsTable& funcs,
GLESMultiDrawMode tier) {
const Bool esAtLeast31 =
caps.GLESVersion.Major > 3 || (caps.GLESVersion.Major == 3 && caps.GLESVersion.Minor >= 1);
switch (tier) {
case GLESMultiDrawMode::Ext:
return caps.SupportsMultiDrawElementsBaseVertex;
case GLESMultiDrawMode::MultiIndirect:
return caps.SupportsMultiDrawIndirect && esAtLeast31 && funcs.glDrawElementsIndirect != nullptr;
case GLESMultiDrawMode::Indirect:
return esAtLeast31 && funcs.glDrawElementsIndirect != nullptr;
case GLESMultiDrawMode::BaseVertex:
return caps.SupportsDrawElementsBaseVertex;
case GLESMultiDrawMode::DrawElements:
// Plain glDrawElements over a rewritten index stream: ES 2 core, so this is
// the floor every other tier can fall back to.
return true;
case GLESMultiDrawMode::Compute:
// Three storage blocks, which is inside the four ES 3.1 guarantees per stage.
return caps.SupportsComputeShader && caps.MaxComputeShaderStorageBlocks >= 3 &&
funcs.glBindBufferBase != nullptr;
case GLESMultiDrawMode::Auto:
break;
}
return false;
}
GLESMultiDrawMode ResolveTier(const MG_External::GLESCapabilities& caps,
const MG_External::GLESFunctionsTable& funcs, GLESMultiDrawMode requested,
String* explanation) {
const auto bestAuto = [&]() {
for (const GLESMultiDrawMode tier : kAutoLadder) {
if (IsTierSupported(caps, funcs, tier)) return tier;
}
return GLESMultiDrawMode::DrawElements;
};
GLESMultiDrawMode resolved = GLESMultiDrawMode::DrawElements;
String line;
if (requested == GLESMultiDrawMode::Auto) {
resolved = bestAuto();
line = String("auto -> ") + TierName(resolved);
} else if (IsTierSupported(caps, funcs, requested)) {
resolved = requested;
line = String("MOBILEGL_ESPRYT_MULTIDRAW_MODE=") + TierName(requested) + " -> " + TierName(resolved);
} else {
resolved = bestAuto();
line = String("MOBILEGL_ESPRYT_MULTIDRAW_MODE=") + TierName(requested) +
" requested but unsupported by this driver -> " + TierName(resolved);
}
if (explanation) {
String supported;
for (const GLESMultiDrawMode tier : kAutoLadder) {
if (!IsTierSupported(caps, funcs, tier)) continue;
if (!supported.empty()) supported += ", ";
supported += TierName(tier);
}
if (IsTierSupported(caps, funcs, GLESMultiDrawMode::Compute)) {
supported += supported.empty() ? "compute (opt-in)" : ", compute (opt-in)";
}
*explanation = line + " (driver supports: " + supported + ")";
}
return resolved;
}
const char* TierName(GLESMultiDrawMode tier) {
switch (tier) {
case GLESMultiDrawMode::Auto: return "auto";
case GLESMultiDrawMode::Ext: return "ext";
case GLESMultiDrawMode::MultiIndirect: return "multiindirect";
case GLESMultiDrawMode::Indirect: return "indirect";
case GLESMultiDrawMode::BaseVertex: return "basevertex";
case GLESMultiDrawMode::DrawElements: return "drawelements";
case GLESMultiDrawMode::Compute: return "compute";
}
return "unknown";
}
GLESMultiDrawMode ResolvedTier() {
ResolveTierOnce();
return g_resolvedTier;
}
String DescribeTierResolution() {
ResolveTierOnce();
return g_tierResolution;
}
void OnBackendContextDestroyed() {
g_indirectCommands = {};
g_rebasedIndices = {};
g_drawInfo = {};
g_flattenedIndices = {};
g_computeProgram = 0;
g_computeProgramFailed = false;
g_uElementSize = -1;
g_uDrawCount = -1;
g_uTotalIndices = -1;
}
void DrawElementsBatch(GLenum mode, const GLsizei* count, GLenum type, const GLvoid* const* indices,
GLsizei drawcount, const GLint* basevertex) {
if (drawcount <= 0 || !count || !indices) return;
// State-independent and possibly throwing, so it runs before any GL work.
CheckPrimitiveRestartSupported(type);
const Bool hasIndexBuffer = BoundIndexBuffer() != nullptr;
// The compute tier dispatches BEFORE the draw state is established: doing it
// afterwards would mean unpicking the program, SSBO and index bindings
// PrepareForDraw just made, and a dispatch inside an open transform feedback
// span is not legal at all. On success it hands back a flattened index stream.
FlattenedStream flattened;
if (ResolvedTier() == GLESMultiDrawMode::Compute && !CurrentProgramReadsDrawID()) {
FlattenWithCompute(mode, count, type, indices, drawcount, basevertex, flattened);
}
PrepareForDraw(DrawSyncBit::IndexBuffer);
if (flattened.indexCount != 0) {
const Uint previousIndexBinding = BoundIndexBufferId();
BufferImpl::BindBufferId(GL_ELEMENT_ARRAY_BUFFER, flattened.bufferId);
g_GLESFuncs.glDrawElements(mode, static_cast<GLsizei>(flattened.indexCount), GL_UNSIGNED_INT, nullptr);
BufferImpl::BindBufferId(GL_ELEMENT_ARRAY_BUFFER, previousIndexBinding);
return;
}
const Bool feedDrawID = CurrentProgramReadsDrawID();
const GLESMultiDrawMode tier = ResolveTierForBatch(feedDrawID, hasIndexBuffer);
Bool drawn = false;
switch (tier) {
case GLESMultiDrawMode::Ext:
drawn = RunExt(mode, count, type, indices, drawcount, basevertex);
break;
case GLESMultiDrawMode::MultiIndirect:
drawn = RunIndirect(mode, count, type, indices, drawcount, basevertex, /*batched=*/true, feedDrawID);
break;
case GLESMultiDrawMode::Indirect:
drawn = RunIndirect(mode, count, type, indices, drawcount, basevertex, /*batched=*/false, feedDrawID);
break;
case GLESMultiDrawMode::BaseVertex:
drawn = RunBaseVertexLoop(mode, count, type, indices, drawcount, basevertex, feedDrawID);
break;
case GLESMultiDrawMode::DrawElements:
drawn = RunRebasedDrawElements(mode, count, type, indices, drawcount, basevertex, feedDrawID);
break;
case GLESMultiDrawMode::Compute:
// Its pre-pass ran above; reaching here means it declined this batch's shape.
break;
case GLESMultiDrawMode::Auto:
break; // resolution never yields Auto
}
// Every tier above may decline a batch whose shape it cannot express. The two
// below are the floor: a base-vertex replay where the driver has one, and the
// rewritten index stream where it does not. Both are safe for any batch these
// entry points can receive.
if (!drawn) drawn = RunBaseVertexLoop(mode, count, type, indices, drawcount, basevertex, feedDrawID);
if (!drawn) drawn = RunRebasedDrawElements(mode, count, type, indices, drawcount, basevertex, feedDrawID);
if (!drawn) {
MGLOG_E("DirectGLES multi-draw: no usable tier for a %d sub-draw batch (mode 0x%x, type 0x%x); "
"the batch was dropped",
drawcount, mode, type);
}
}
} // namespace MobileGL::MG_Backend::DirectGLES::MultiDrawImpl

Some files were not shown because too many files have changed in this diff Show More