Compare commits

...
23 Commits
Author SHA1 Message Date
BZLZHH 10d0441040 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 ad03e059e0 Ask whether a colour format is renderable per target, not in general
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 440e569c98 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 cb62431299 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 06ce55dac3 DirectGLES: keep 16-bit SNORM precision through the multisample 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 7400f46955 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 1679bf9a1e DirectGLES: turn off the driver's sRGB framebuffer encoding
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 8673e89b13 DirectGLES: 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
18 changed files with 1919 additions and 138 deletions
+14
View File
@@ -229,6 +229,13 @@ namespace MobileGL {
// (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.
void (*BeginTransformFeedback)(GLenum primitiveMode);
void (*EndTransformFeedback)();
Int64 (*GetGpuTimestampNs)(); // glGetInteger64v(GL_TIMESTAMP); 0 if unsupported
};
struct GlobalBackendFunctionsTable {
@@ -317,6 +324,13 @@ namespace MobileGL {
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;
SizeT MaxShaderStorageBlockSize = 128 * 1024 * 1024;
Uint32 SubgroupSize = 0;
Uint32 SubgroupSupportedStages = 0;
@@ -210,6 +210,12 @@ namespace MobileGL::MG_Backend::DirectGLES {
if (options & PixelFormatNormalizeOptionBit::NoDepthComponent32) {
reasons.push_back("GL_DEPTH_COMPONENT32 native probe failed on OpenGL ES");
}
if (options & PixelFormatNormalizeOptionBit::NoThreeChannelRenderTarget) {
reasons.push_back("no three-channel multisample storage format on OpenGL ES");
}
if (options & PixelFormatNormalizeOptionBit::NoSnorm16RenderTarget) {
reasons.push_back("EXT_render_snorm not supported");
}
String reason;
for (SizeT i = 0; i < reasons.size(); ++i) {
@@ -357,6 +363,42 @@ namespace MobileGL::MG_Backend::DirectGLES {
return complete;
}
// Whether the driver renders to a framebuffer whose depth and stencil come from
// two different renderbuffers. GL only requires support when both attachments are
// the same image, and ES drivers commonly answer GL_FRAMEBUFFER_UNSUPPORTED here;
// reporting COMPLETE from the frontend and then rendering into a framebuffer the
// driver refuses leaves the results silently empty.
Bool ProbeDistinctDepthStencilAttachments(const MG_External::GLESFunctionsTable& gl) {
if (!gl.glGenFramebuffers || !gl.glBindFramebuffer || !gl.glFramebufferRenderbuffer ||
!gl.glCheckFramebufferStatus || !gl.glDeleteFramebuffers || !gl.glGenRenderbuffers ||
!gl.glBindRenderbuffer || !gl.glRenderbufferStorage || !gl.glDeleteRenderbuffers) {
return true;
}
GLint prevFramebuffer = 0, prevRenderbuffer = 0;
gl.glGetIntegerv(GL_FRAMEBUFFER_BINDING, &prevFramebuffer);
gl.glGetIntegerv(GL_RENDERBUFFER_BINDING, &prevRenderbuffer);
GLuint framebuffer = 0;
GLuint renderbuffers[2] = {0, 0};
gl.glGenFramebuffers(1, &framebuffer);
gl.glGenRenderbuffers(2, renderbuffers);
gl.glBindRenderbuffer(GL_RENDERBUFFER, renderbuffers[0]);
gl.glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT16, 4, 4);
gl.glBindRenderbuffer(GL_RENDERBUFFER, renderbuffers[1]);
gl.glRenderbufferStorage(GL_RENDERBUFFER, GL_STENCIL_INDEX8, 4, 4);
gl.glBindFramebuffer(GL_FRAMEBUFFER, framebuffer);
gl.glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, renderbuffers[0]);
gl.glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_RENDERBUFFER, renderbuffers[1]);
const Bool supported = gl.glCheckFramebufferStatus(GL_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE;
gl.glBindFramebuffer(GL_FRAMEBUFFER, static_cast<GLuint>(prevFramebuffer));
gl.glBindRenderbuffer(GL_RENDERBUFFER, static_cast<GLuint>(prevRenderbuffer));
gl.glDeleteFramebuffers(1, &framebuffer);
gl.glDeleteRenderbuffers(2, renderbuffers);
return supported;
}
Bool ProbeFramebufferCompletenessForRenderbuffer(const MG_External::GLESFunctionsTable& gl,
GLuint renderbuffer,
TextureInternalFormat format) {
@@ -520,20 +562,50 @@ namespace MobileGL::MG_Backend::DirectGLES {
}
const GLESProbeFormatInfo nativeInfo = BuildNativeProbeFormatInfo(requestedInternalFormat);
GLESProbeFormatInfo fallbackInfo;
const Bool hasForcedFallback =
BuildFallbackProbeFormatInfo(requestedInternalFormat, forcedOptions, true, fallbackInfo);
if (!hasForcedFallback) {
BuildFallbackProbeFormatInfo(requestedInternalFormat, driverOptions, false, fallbackInfo);
GLESProbeFormatInfo outerFallbackInfo;
const Bool outerHasForcedFallback =
BuildFallbackProbeFormatInfo(requestedInternalFormat, forcedOptions, true, outerFallbackInfo);
if (!outerHasForcedFallback) {
BuildFallbackProbeFormatInfo(requestedInternalFormat, driverOptions, false, outerFallbackInfo);
}
for (SizeT targetIndex = 0; targetIndex < kFormatCapabilityTextureTargetCount; ++targetIndex) {
const auto target = static_cast<TextureTarget>(targetIndex);
// A multisample texture can only ever be rendered into, so its storage format
// has to stay colour-renderable; the ordinary fallback for a three-channel
// format is a three-channel one, which ES accepts as a texture but rejects as
// multisample storage. Recompute the fallback per target so those formats get
// widened here and nowhere else.
Flags<PixelFormatNormalizeOptionBit> targetOptions;
if (IsGLESProbeMultisampleTarget(target)) {
targetOptions |= PixelFormatNormalizeOptionBit::NoThreeChannelRenderTarget;
if (!capabilities.SupportsRenderSnorm || !capabilities.SupportsNorm16Texture) {
targetOptions |= PixelFormatNormalizeOptionBit::NoSnorm16RenderTarget;
}
}
GLESProbeFormatInfo fallbackInfo = outerFallbackInfo;
Bool hasForcedFallback = outerHasForcedFallback;
if (targetOptions) {
hasForcedFallback = BuildFallbackProbeFormatInfo(
requestedInternalFormat, forcedOptions | targetOptions, true, fallbackInfo);
if (!hasForcedFallback) {
BuildFallbackProbeFormatInfo(requestedInternalFormat, driverOptions | targetOptions,
false, fallbackInfo);
}
}
// 1D, 1D-array and rectangle textures live on an ES target (see
// TextureImpl::MapToBackendTextureTarget), so they have to be probed there too -
// probing the desktop-only target itself always failed, which left those slots
// of the cache empty and stopped any fallback format from being selected for
// them (a GL_DEPTH_COMPONENT32 1D texture then got no storage at all).
const TextureTarget probeTarget = TextureImpl::MapToBackendTextureTarget(target);
Bool shouldProbeFallback = hasForcedFallback;
if (!hasForcedFallback) {
Bool nativeRenderable = false;
const Bool nativeCreated =
ProbeTexture(gl, target, nativeInfo.InternalFormat, nativeInfo.ImageFormat,
ProbeTexture(gl, probeTarget, nativeInfo.InternalFormat, nativeInfo.ImageFormat,
nativeInfo.ImageType, logicalFormat, &nativeRenderable);
if (nativeCreated) {
AddFullFormatCaps(cache, targetIndex, formatIndex,
@@ -548,7 +620,7 @@ namespace MobileGL::MG_Backend::DirectGLES {
if (shouldProbeFallback && fallbackInfo.InternalFormat != GL_UNKNOWN_MGL) {
Bool fallbackRenderable = false;
const Bool fallbackCreated =
ProbeTexture(gl, target, fallbackInfo.InternalFormat, fallbackInfo.ImageFormat,
ProbeTexture(gl, probeTarget, fallbackInfo.InternalFormat, fallbackInfo.ImageFormat,
fallbackInfo.ImageType, logicalFormat, &fallbackRenderable);
if (fallbackCreated) {
if (AddCaveatFormatCaps(cache, targetIndex, formatIndex,
@@ -564,8 +636,8 @@ namespace MobileGL::MG_Backend::DirectGLES {
}
const SizeT renderbufferTargetIndex = GetRenderbufferFormatCapabilityTargetIndex();
Bool shouldProbeFallbackRenderbuffer = hasForcedFallback;
if (!hasForcedFallback) {
Bool shouldProbeFallbackRenderbuffer = outerHasForcedFallback;
if (!outerHasForcedFallback) {
const Bool nativeRenderbufferComplete =
ProbeRenderbuffer(gl, nativeInfo.InternalFormat, logicalFormat, false, 1);
if (nativeRenderbufferComplete) {
@@ -579,16 +651,16 @@ namespace MobileGL::MG_Backend::DirectGLES {
shouldProbeFallbackRenderbuffer = true;
}
}
if (shouldProbeFallbackRenderbuffer && fallbackInfo.InternalFormat != GL_UNKNOWN_MGL &&
ProbeRenderbuffer(gl, fallbackInfo.InternalFormat, logicalFormat, false, 1)) {
if (shouldProbeFallbackRenderbuffer && outerFallbackInfo.InternalFormat != GL_UNKNOWN_MGL &&
ProbeRenderbuffer(gl, outerFallbackInfo.InternalFormat, logicalFormat, false, 1)) {
if (AddCaveatFormatCaps(cache, renderbufferTargetIndex, formatIndex,
GetRenderbufferFeatureCaps(logicalFormat))) {
LogGLESFormatCaveat(logicalFormat, renderbufferTargetIndex, fallbackInfo);
LogGLESFormatCaveat(logicalFormat, renderbufferTargetIndex, outerFallbackInfo);
}
const Int maxSamples =
GetGLESFormatMaxSamples(capabilities, logicalFormat, fallbackInfo.ImageFormat);
GetGLESFormatMaxSamples(capabilities, logicalFormat, outerFallbackInfo.ImageFormat);
cache.SampleCounts[renderbufferTargetIndex][formatIndex] =
ProbeRenderbufferSampleCounts(gl, fallbackInfo.InternalFormat, logicalFormat, maxSamples);
ProbeRenderbufferSampleCounts(gl, outerFallbackInfo.InternalFormat, logicalFormat, maxSamples);
}
}
}
@@ -832,6 +904,12 @@ namespace MobileGL::MG_Backend::DirectGLES {
E_GL_ARB_multi_draw_indirect, E_GL_ARB_indirect_parameters,
E_GL_ARB_shader_draw_parameters, E_GL_ARB_gpu_shader5, E_GL_ARB_multi_bind,
E_GL_ARB_shading_language_420pack, E_GL_ARB_vertex_attrib_binding,
// Both are core from GL 3.2/3.3 on and implemented here for
// every advertised version, but an app targeting 3.0/3.1
// only reaches them through the extension string - the CTS
// picks a whole different shader for draw_buffers without
// explicit_attrib_location. DirectVulkan advertises both.
E_GL_ARB_explicit_attrib_location, E_GL_ARB_texture_multisample,
E_GL_ARB_shader_image_size};
// Only advertised when the device driver actually has usable timer queries
// (GL_EXT_disjoint_timer_query plus its entry points) and the
@@ -942,9 +1020,18 @@ namespace MobileGL::MG_Backend::DirectGLES {
// when the timer-query group above is disabled.
funcsTable.GL.BeginOcclusionQuery = BeginOcclusionQuery;
funcsTable.GL.EndOcclusionQuery = EndOcclusionQuery;
// Real driver primitive counters: the frontend's CPU accounting cannot see a
// geometry shader's amplification.
funcsTable.GL.BeginXfbPrimitivesQuery = BeginXfbPrimitivesQuery;
funcsTable.GL.EndXfbPrimitivesQuery = EndXfbPrimitivesQuery;
funcsTable.GL.IsQueryResultAvailable = IsQueryResultAvailable;
funcsTable.GL.GetQueryResult64 = GetQueryResult64;
funcsTable.GL.DeleteBackendQuery = DeleteBackendQuery;
// Transform feedback is captured by the real ES driver rather than
// reconstructed from the draw recording, so the frontend has to hand the
// span boundaries over.
funcsTable.GL.BeginTransformFeedback = XfbImpl::BeginTransformFeedback;
funcsTable.GL.EndTransformFeedback = XfbImpl::EndTransformFeedback;
funcsTableInitialized = true;
}
return funcsTable;
@@ -1031,6 +1118,8 @@ namespace MobileGL::MG_Backend::DirectGLES {
clampStageImageUniforms(m_GLESCapabilities.MaxFragmentImageUniforms);
m_dynamicParameters.MaxComputeImageUniforms =
clampStageImageUniforms(m_GLESCapabilities.MaxComputeImageUniforms);
m_dynamicParameters.SupportsDistinctDepthStencilAttachments =
ProbeDistinctDepthStencilAttachments(DirectGLES::g_GLESFuncs);
m_dynamicParameters.MaxDrawBuffers = m_GLESCapabilities.MaxDrawBuffers;
m_dynamicParameters.MaxColorAttachments = m_GLESCapabilities.MaxColorAttachments;
m_dynamicParameters.MaxClipDistances = m_GLESCapabilities.MaxClipDistances;
File diff suppressed because it is too large Load Diff
@@ -135,6 +135,11 @@ namespace MobileGL::MG_Backend::DirectGLES {
// 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
@@ -159,6 +164,18 @@ namespace MobileGL::MG_Backend::DirectGLES {
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.
namespace XfbImpl {
Bool AreTransformFeedbacksSupported();
void BeginTransformFeedback(GLenum primitiveMode);
void EndTransformFeedback();
void OnBackendContextDestroyed();
} // namespace XfbImpl
extern MG_External::EGLFunctionsTable g_EGLFuncs;
extern MG_External::GLESFunctionsTable g_GLESFuncs;
extern MG_External::GLESCapabilities g_GLESCapabilities;
+92 -5
View File
@@ -2405,7 +2405,19 @@ namespace MobileGL::MG_Backend::DirectGLES {
MGLOG_D("%s(%s:%d) ES error %s", func, file, line, MG_Util::ConvertGLEnumToString(err).c_str());
});
const auto& swizzleParams = stateTextureObject->GetAllSwizzleParams();
// A three-channel format widened to four for a multisample target (see
// NormalizePixelFormat) gains an alpha channel the frontend format does not have, and
// whatever the draw that filled it wrote there is not what GL would report: a format
// without alpha reads back as 1.0. Answer the ALPHA swizzle source with ONE so the
// promotion stays invisible, composed with the swizzle the application asked for.
Vec4<TextureSwizzleParam> swizzleParams = stateTextureObject->GetAllSwizzleParams();
if (TextureImpl::BackendTextureFormatAddsAlpha(stateTextureObject->GetFormat(), targetInternal)) {
for (SizeT channel = 0; channel < 4; ++channel) {
if (swizzleParams[channel] == TextureSwizzleParam::Alpha) {
swizzleParams[channel] = TextureSwizzleParam::One;
}
}
}
if (swizzleParams != m_cacheSwizzleParams) {
#define SYNC_TEX_SWIZZLE_PARAM_IF_CHANGED(func, glEnum) \
if (m_cacheSwizzleParams.func != swizzleParams.func) { \
@@ -2679,6 +2691,31 @@ namespace MobileGL::MG_Backend::DirectGLES {
return false;
}
Bool IsFixedPointFallbackReadAttachment() {
const auto& readFBO =
MG_State::pGLContext->GetFramebufferBindingSlot(FramebufferTarget::Read).GetBoundObject();
if (!readFBO) {
return false;
}
const auto readBuffer = readFBO->GetReadBuffer();
if (readBuffer < FramebufferAttachmentType::Color0 || readBuffer > FramebufferAttachmentType::Color31) {
return false;
}
// Any signed-normalized attachment, not just the ones currently substituted:
// ES has no GL_CLAMP_READ_COLOR at all, so even a natively stored SNORM buffer
// hands back the negative half that desktop GL clamps away.
const auto& attachmentObject = readFBO->GetAttachment(readBuffer);
if (attachmentObject.IsTexture()) {
const auto& textureObject = attachmentObject.GetTexture();
return textureObject && IsSnormFormat(textureObject->GetFormat());
}
if (attachmentObject.IsRenderbuffer()) {
const auto& renderbufferObject = attachmentObject.GetRenderbuffer();
return renderbufferObject && IsSnormFormat(renderbufferObject->GetInternalFormat());
}
return false;
}
void BackendFramebufferObject::SyncReadBufferToBackend(
const SharedPtr<MG_State::GLState::FramebufferObject>& stateFBOObject) {
if (!stateFBOObject) {
@@ -3181,6 +3218,7 @@ namespace MobileGL::MG_Backend::DirectGLES {
namespace PrgramImpl {
Uint32 g_snormFallbackClampOutputMask = 0;
Uint g_fragColorBroadcastCount = 1;
Uint32 g_unormFallbackClampOutputMask = 0;
Uint g_lastUsedBackendProgramId = 0;
StateBackendObjectRegistry<MG_State::GLState::ProgramObject, BackendProgramObjectImpl> g_backendProgramObjects;
@@ -3232,8 +3270,10 @@ namespace MobileGL::MG_Backend::DirectGLES {
MGLOG_D("Syncing program to backend. State program ID: %u, Backend ID: %u",
stateProgramObject->GetExternalIndex(), m_backendProgramId);
m_backendProgramUsable = true;
m_snormFallbackClampOutputMask = g_snormFallbackClampOutputMask;
m_unormFallbackClampOutputMask = g_unormFallbackClampOutputMask;
m_fragColorBroadcastCount = g_fragColorBroadcastCount;
// Detach all existing shaders
GLint attachedCount = 0;
@@ -3316,6 +3356,17 @@ namespace MobileGL::MG_Backend::DirectGLES {
effectiveSpirv = &noperspectiveSpirv;
}
// ES has no rectangle sampler, and SPIRV-Cross refuses the whole module rather
// than approximating one. Where every use takes integer texel coordinates a
// rectangle image is indistinguishable from a 2D one, so rewrite the type and let
// it through; the pass declines anything it cannot convert exactly.
Vector<unsigned int> rectLoweredSpirv;
if (MG_Util::ShaderTranspiler::ShaderCompiler::LowerRectImagesForEssl(*effectiveSpirv,
rectLoweredSpirv) &&
!rectLoweredSpirv.empty()) {
effectiveSpirv = &rectLoweredSpirv;
}
MG_Util::ShaderTranspiler::SpvcSession spvcSession(*effectiveSpirv,
MG_Util::ShaderTranspiler::SessionUsageBit::Transpile);
@@ -3338,6 +3389,7 @@ namespace MobileGL::MG_Backend::DirectGLES {
r.log += spvcSession.GetLastErrorString();
r.errc = -5;
MGLOG_E("%s", r.log.c_str());
m_backendProgramUsable = false;
continue;
}
@@ -3347,6 +3399,8 @@ namespace MobileGL::MG_Backend::DirectGLES {
source = RemoveLayoutBinding(source);
source = ProcessOutColorLocations(source);
source = ForceFlatIntegerVaryings(source, glShaderType);
source = BroadcastLegacyFragColor(std::move(source), glShaderType, m_fragColorBroadcastCount);
source = EmulateTextureLodBias(source);
source = EmulateBaseInstanceInVertexShader(std::move(source), glShaderType);
source = PromoteDrawParameterGlobalsToUniforms(std::move(source), glShaderType);
source = ForceSupporterOutput(source);
@@ -3377,6 +3431,7 @@ namespace MobileGL::MG_Backend::DirectGLES {
Vector<GLchar> log(logLength);
g_GLESFuncs.glGetShaderInfoLog(backendShaderId, logLength, nullptr, log.data());
MGLOG_E("Shader compilation failed for backend ID %u: %s", backendShaderId, log.data());
m_backendProgramUsable = false;
continue;
}
@@ -3386,12 +3441,33 @@ namespace MobileGL::MG_Backend::DirectGLES {
MGLOG_D("Processed shader source length: %zu", source.length());
}
// Transform feedback capture runs on the real driver (see XfbImpl in
// DirectGLES.cpp), so the capture set has to be declared on the backend
// program before it links. SPIRV-Cross keeps user output names verbatim in
// the transpiled ESSL (`out vec4 result_0;` stays `result_0`), so the
// frontend's requested names carry over unchanged.
if (stateProgramObject->GetTransformFeedbackVaryingCount() > 0 &&
g_GLESFuncs.glTransformFeedbackVaryings != nullptr) {
const auto& xfbVaryings = stateProgramObject->GetTransformFeedbackVaryings();
Vector<const GLchar*> xfbNames;
xfbNames.reserve(xfbVaryings.size());
for (const auto& xfbVarying : xfbVaryings) {
xfbNames.push_back(xfbVarying.name.c_str());
}
MGLOG_D("Declaring %zu transform feedback varyings on program %u", xfbNames.size(),
m_backendProgramId);
g_GLESFuncs.glTransformFeedbackVaryings(m_backendProgramId, static_cast<GLsizei>(xfbNames.size()),
xfbNames.data(),
stateProgramObject->GetTransformFeedbackBufferMode());
}
// Link program
MGLOG_D("Linking program %u", m_backendProgramId);
g_GLESFuncs.glLinkProgram(m_backendProgramId);
GLint linkStatus;
g_GLESFuncs.glGetProgramiv(m_backendProgramId, GL_LINK_STATUS, &linkStatus);
m_backendProgramUsable = m_backendProgramUsable && linkStatus == GL_TRUE;
if (linkStatus != GL_TRUE) {
GLint logLength;
g_GLESFuncs.glGetProgramiv(m_backendProgramId, GL_INFO_LOG_LENGTH, &logLength);
@@ -3504,6 +3580,11 @@ namespace MobileGL::MG_Backend::DirectGLES {
binding.backendLocation = backendLoc;
binding.uniformType = uniformType;
binding.lastAssignedUnit = -1;
// Present only for the samplers EmulateTextureLodBias actually rewrote; the
// pass names it after the sampler, which SPIRV-Cross preserves verbatim.
binding.lodBiasLocation =
g_GLESFuncs.glGetUniformLocation(m_backendProgramId, (String(LOD_BIAS_UNIFORM_PREFIX) + name).c_str());
binding.lastAssignedLodBias = 0.0f;
m_samplerUniformBindings.push_back(binding);
}
}
@@ -3512,12 +3593,18 @@ namespace MobileGL::MG_Backend::DirectGLES {
#ifdef TRACY_ENABLE
ZoneScopedC(TRACY_ZONECOLOR_BACKEND);
#endif
if (g_lastUsedBackendProgramId == m_backendProgramId) {
// glUseProgram on a program that did not link is an INVALID_OPERATION and
// leaves the *previous* program current, so the draw would silently render
// with an unrelated shader (KHR-GL3x.texture_size_promotion read another
// test case's alpha that way once a sampler2DRect stage failed to
// transpile). Bind nothing instead: the draw is then a visible no-op.
const Uint programToBind = m_backendProgramUsable ? m_backendProgramId : 0;
if (g_lastUsedBackendProgramId == programToBind) {
return;
}
MGLOG_D("Using program %u", m_backendProgramId);
g_GLESFuncs.glUseProgram(m_backendProgramId);
g_lastUsedBackendProgramId = m_backendProgramId;
MGLOG_D("Using program %u", programToBind);
g_GLESFuncs.glUseProgram(programToBind);
g_lastUsedBackendProgramId = programToBind;
}
void BackendProgramObjectImpl::SetBaseInstance(Uint32 baseInstance) const {
+37 -7
View File
@@ -270,18 +270,21 @@ namespace MobileGL::MG_Backend::DirectGLES {
namespace TextureImpl {
inline Bool IsSupportedTextureTarget(TextureTarget target) {
// Rectangle textures need non-normalized sampling ES cannot express; everything else is
// either native or emulated (1D -> 2D with height 1, 1D array -> 2D array, see
// MapToBackendTextureTarget). SPIRV-Cross already emits the matching ESSL samplers and
// coordinate padding for 1D/1D-array shaders.
return target != TextureTarget::TextureRectangle;
// Every desktop-only target is stored on an ES one; see MapToBackendTextureTarget.
(void)target;
return true;
}
// ES has no 1D targets: 1D textures are stored as 2D (height 1) and 1D arrays as 2D arrays
// (height 1, layers in depth). Must match SPIRV-Cross's ES 1D-as-2D shader emulation.
// ES has none of the desktop-only targets: 1D textures are stored as 2D (height 1), 1D
// arrays as 2D arrays (height 1, layers in depth), and rectangle textures as plain 2D -
// they are single-level and already clamp, so only the non-normalized coordinates differ.
// Must match the shader-side emulation: SPIRV-Cross handles 1D/1D-array itself, and
// ShaderCompiler::LowerRectImagesForEssl rewrites rectangle images (declining any module
// whose lookups are not integer-coordinate, which SPIRV-Cross then still rejects).
inline TextureTarget MapToBackendTextureTarget(TextureTarget target) {
switch (target) {
case TextureTarget::Texture1D:
case TextureTarget::TextureRectangle:
return TextureTarget::Texture2D;
case TextureTarget::Texture1DArray:
return TextureTarget::Texture2DArray;
@@ -297,6 +300,7 @@ namespace MobileGL::MG_Backend::DirectGLES {
inline GLenum ConvertTextureUploadTargetToBackendGLEnum(TextureUploadTarget uploadTarget) {
switch (uploadTarget) {
case TextureUploadTarget::Texture1D:
case TextureUploadTarget::TextureRectangle:
return GL_TEXTURE_2D;
case TextureUploadTarget::Texture1DArray:
return GL_TEXTURE_2D_ARRAY;
@@ -438,6 +442,13 @@ namespace MobileGL::MG_Backend::DirectGLES {
extern StateBackendObjectRegistry<MG_State::GLState::FramebufferObject, BackendFramebufferObject>
g_backendFramebufferObjects;
// True when the read buffer names a fixed-point (norm/snorm) attachment that the
// backend actually stores in a floating-point format. GL clamps a read from a
// fixed-point colour buffer to [0,1] (GL_CLAMP_READ_COLOR defaults to
// GL_FIXED_ONLY); the substituted float storage would not, so the readback path
// has to apply the clamp itself.
Bool IsFixedPointFallbackReadAttachment();
extern Array<Uint16, SizeT(FramebufferTarget::FramebufferTargetCount)> g_fboBindVersions;
// Tracks the bound FBO's object version (bumped on any attachment/drawbuffer change)
// per target: re-attaching textures or changing draw buffers on an already-bound FBO
@@ -576,6 +587,12 @@ namespace MobileGL::MG_Backend::DirectGLES {
Int backendLocation = -1;
GLenum uniformType = 0;
Int lastAssignedUnit = -1;
// Location of this sampler's emulated GL_TEXTURE_LOD_BIAS uniform
// (PrgramImpl::EmulateTextureLodBias), -1 when the shader has none.
// lastAssignedLodBias mirrors the value the program currently holds,
// so an unbiased shader issues no per-draw glUniform1f at all.
Int lodBiasLocation = -1;
Float lastAssignedLodBias = 0.0f;
};
BackendProgramObjectImpl();
@@ -587,9 +604,14 @@ namespace MobileGL::MG_Backend::DirectGLES {
void SetDrawID(Uint32 drawId) const;
Int GetIndirectParamsBinding() const { return m_indirectParamsBinding; }
Uint GetBackendProgramId() const { return m_backendProgramId; }
// False when the last SyncToBackend could not produce a usable program (a
// shader failed to transpile or compile, or the link itself failed). Use()
// must not leave the previously bound program current in that case.
Bool IsBackendProgramUsable() const { return m_backendProgramUsable; }
Uint GetBackendGlobalUBOId() const { return m_backendGlobalUBOId; }
Uint32 GetSnormFallbackClampOutputMask() const { return m_snormFallbackClampOutputMask; }
Uint32 GetUnormFallbackClampOutputMask() const { return m_unormFallbackClampOutputMask; }
Uint GetFragColorBroadcastCount() const { return m_fragColorBroadcastCount; }
Bool HasGlobalUboBlock() const { return m_globalUboBackendBlockIndex >= 0; }
const Vector<Int>& GetUniformBlockBackendIndices() const { return m_uniformBlockBackendIndices; }
@@ -616,7 +638,11 @@ namespace MobileGL::MG_Backend::DirectGLES {
Int m_indirectParamsBinding = -1;
Uint32 m_snormFallbackClampOutputMask = 0;
Uint32 m_unormFallbackClampOutputMask = 0;
// Draw buffers a legacy gl_FragColor write has to reach (see
// PrgramImpl::BroadcastLegacyFragColor); 1 keeps the plain single-output shader.
Uint m_fragColorBroadcastCount = 1;
Bool m_isInitialized = false;
Bool m_backendProgramUsable = false;
Int m_globalUboBackendBlockIndex = -1;
Int m_globalUboBackendBlockSize = 0;
@@ -629,6 +655,10 @@ namespace MobileGL::MG_Backend::DirectGLES {
extern Uint32 g_snormFallbackClampOutputMask;
extern Uint32 g_unormFallbackClampOutputMask;
// Draw buffers the current draw framebuffer enables. Like the clamp masks above it
// is framebuffer state that the shader has to be compiled against, so a program
// whose snapshot no longer matches is relinked.
extern Uint g_fragColorBroadcastCount;
// Backend id of the last glUseProgram issued through this backend; lets Use()
// skip redundant rebinds. Reset to 0 wherever glUseProgram(0) is issued or the
// ES context is recreated.
+260 -6
View File
@@ -22,6 +22,9 @@
#include <MG_Util/Math/SmallFloat.h>
#include <cmath>
#include <cctype>
#include <cstring>
#include <regex>
namespace MobileGL::MG_Backend::DirectGLES {
namespace {
@@ -45,15 +48,40 @@ namespace MobileGL::MG_Backend::DirectGLES {
return options;
}
Flags<PixelFormatNormalizeOptionBit> GetRuntimeFallbackNormalizeOptions(GLenum requestedInternalFormat) {
Flags<PixelFormatNormalizeOptionBit>
GetRuntimeFallbackNormalizeOptions(GLenum requestedInternalFormat,
Flags<PixelFormatNormalizeOptionBit> extraOptions) {
using namespace MG_Util::TextureFormatProcessor;
const Flags<PixelFormatNormalizeOptionBit> forcedOptions =
GetApplicablePixelFormatNormalizeOptions(requestedInternalFormat, GetForcedPixelFormatNormalizeOptions());
const Flags<PixelFormatNormalizeOptionBit> forcedOptions = GetApplicablePixelFormatNormalizeOptions(
requestedInternalFormat, GetForcedPixelFormatNormalizeOptions() | extraOptions);
if (forcedOptions) {
return forcedOptions;
}
return GetApplicablePixelFormatNormalizeOptions(requestedInternalFormat,
GetDriverPixelFormatNormalizeOptions());
return GetApplicablePixelFormatNormalizeOptions(
requestedInternalFormat, GetDriverPixelFormatNormalizeOptions() | extraOptions);
}
// Multisample textures can only ever be rendered into, never uploaded to, so a fallback
// format for them has to stay colour-renderable - a three-channel float fallback is a legal
// ES texture format but not a legal multisample storage format. Widening to four channels
// is safe here precisely because there is no transfer path that would have to expand
// three-channel client data, and the alpha the draw writes for a three-channel source is
// already the 1.0 the frontend format implies.
Bool TargetRequiresRenderableFormat(SizeT targetIndex) {
return targetIndex == static_cast<SizeT>(TextureTarget::Texture2DMultisample) ||
targetIndex == static_cast<SizeT>(TextureTarget::Texture2DMultisampleArray);
}
Flags<PixelFormatNormalizeOptionBit> GetRenderTargetNormalizeOptions(SizeT targetIndex) {
Flags<PixelFormatNormalizeOptionBit> options;
if (!TargetRequiresRenderableFormat(targetIndex)) {
return options;
}
options |= PixelFormatNormalizeOptionBit::NoThreeChannelRenderTarget;
if (!g_GLESCapabilities.SupportsRenderSnorm || !g_GLESCapabilities.SupportsNorm16Texture) {
options |= PixelFormatNormalizeOptionBit::NoSnorm16RenderTarget;
}
return options;
}
Bool HasCachedFormatCapability(TextureInternalFormat internalFormat,
@@ -113,7 +141,8 @@ namespace MobileGL::MG_Backend::DirectGLES {
const GLenum requestedInternalFormat = MG_Util::ConvertTextureInternalFormatToGLEnum(internalFormat);
Flags<PixelFormatNormalizeOptionBit> options;
if (!pActiveBackendObject || ShouldUseCaveatFormat(internalFormat, targetIndex)) {
options = GetRuntimeFallbackNormalizeOptions(requestedInternalFormat);
options = GetRuntimeFallbackNormalizeOptions(requestedInternalFormat,
GetRenderTargetNormalizeOptions(targetIndex));
}
NormalizePixelFormat(requestedInternalFormat, options, outInternalFormat, outFormat, outType);
}
@@ -148,6 +177,22 @@ namespace MobileGL::MG_Backend::DirectGLES {
Bool ShouldUseCaveatRenderbufferFormat(TextureInternalFormat internalFormat) {
return ShouldUseCaveatFormat(internalFormat, GetRenderbufferFormatCapabilityTargetIndex());
}
Bool BackendTextureFormatAddsAlpha(TextureInternalFormat internalFormat, TextureTarget target) {
const SizeT targetIndex =
target == TextureTarget::Unknown ? kFormatCapabilityTargetCount : GetFormatCapabilityTargetIndex(target);
if (!TargetRequiresRenderableFormat(targetIndex)) {
return false;
}
if (pActiveBackendObject && !ShouldUseCaveatFormat(internalFormat, targetIndex)) {
return false;
}
const GLenum requestedInternalFormat = MG_Util::ConvertTextureInternalFormatToGLEnum(internalFormat);
const Flags<PixelFormatNormalizeOptionBit> options =
GetRuntimeFallbackNormalizeOptions(requestedInternalFormat,
GetRenderTargetNormalizeOptions(targetIndex));
return static_cast<Bool>(options & PixelFormatNormalizeOptionBit::NoThreeChannelRenderTarget);
}
} // namespace TextureImpl
namespace PrgramImpl {
String ProcessOutColorLocations(const String& glslCode) {
@@ -276,6 +321,55 @@ namespace MobileGL::MG_Backend::DirectGLES {
return glslCode;
}
String BroadcastLegacyFragColor(String glslCode, GLenum shaderType, Uint drawBufferCount) {
#ifdef TRACY_ENABLE
ZoneScopedC(TRACY_ZONECOLOR_BACKEND);
#endif
// The name is the marker: ShaderSourceProcessor only emits it when the source
// wrote gl_FragColor, and such a shader can have no other output.
static const char* const kLoweredName = "mg_FragColor";
if (shaderType != GL_FRAGMENT_SHADER || drawBufferCount <= 1) {
return glslCode;
}
static const std::regex declRegex(
R"(layout\s*\(\s*location\s*=\s*0\s*\)\s*out\s+((?:lowp|mediump|highp)\s+)?vec4\s+mg_FragColor\s*;)");
std::smatch declMatch;
if (!std::regex_search(glslCode, declMatch, declRegex)) {
return glslCode;
}
const String precision = declMatch[1].matched ? declMatch[1].str() : String();
String replicaDecls;
String replicaCopies;
for (Uint location = 1; location < drawBufferCount; ++location) {
const String name = String(kLoweredName) + "_" + std::to_string(location);
replicaDecls += "\nlayout(location = " + std::to_string(location) + ") out " + precision + "vec4 " +
name + ";";
replicaCopies += "\n " + name + " = " + kLoweredName + ";";
}
static const std::regex mainRegex(R"(void\s+main\s*\([^)]*\)\s*\{)");
std::smatch mainMatch;
if (!std::regex_search(glslCode, mainMatch, mainRegex)) {
return glslCode;
}
SizeT bracePos = static_cast<SizeT>(mainMatch.position(0) + mainMatch.length(0) - 1);
Int depth = 0;
for (SizeT pos = bracePos; pos < glslCode.size(); ++pos) {
if (glslCode[pos] == '{') {
++depth;
} else if (glslCode[pos] == '}') {
--depth;
if (depth == 0) {
glslCode.insert(pos, replicaCopies + "\n");
break;
}
}
}
glslCode.insert(static_cast<SizeT>(declMatch.position(0)) + declMatch[0].str().size(), replicaDecls);
return glslCode;
}
String ForceFlatIntegerVaryings(const String& glslCode, GLenum shaderType) {
#ifdef TRACY_ENABLE
ZoneScopedC(TRACY_ZONECOLOR_BACKEND);
@@ -342,6 +436,166 @@ namespace MobileGL::MG_Backend::DirectGLES {
}
return result;
}
namespace {
// How a lookup carries its level of detail, and how many arguments it takes
// before the optional bias.
struct LodLookupForm {
const char* name;
Int requiredArgs; // arguments before the optional bias (implicit form)
Int explicitLodArg; // index of the explicit LOD argument, -1 for implicit
};
// texelFetch* is deliberately absent: an integer fetch names its level directly
// and takes no LOD bias. textureGather has no bias either. textureGrad* derives
// the LOD from gradients and offers no argument to fold a bias into, so it is
// left alone rather than rewritten incorrectly.
constexpr LodLookupForm LOD_LOOKUP_FORMS[] = {
{"textureProjLodOffset", 0, 2}, {"textureProjOffset", 4, -1}, {"textureProjLod", 0, 2},
{"textureLodOffset", 0, 2}, {"textureOffset", 3, -1}, {"textureProj", 2, -1},
{"textureLod", 0, 2}, {"texture", 2, -1},
};
// Sampler types with no mip chain, or whose GLSL lookups have no bias overload
// at all (the array-shadow forms), so nothing can or should be folded in.
Bool IsBiasableSamplerType(const String& samplerType) {
if (samplerType.find("MS") != String::npos) return false; // multisample
if (samplerType.find("Buffer") != String::npos) return false; // texture buffer
if (samplerType.find("Rect") != String::npos) return false; // rectangle: no mips
if (samplerType == "sampler2DArrayShadow") return false;
if (samplerType == "samplerCubeArrayShadow") return false;
return true;
}
Bool IsIdentifierChar(char c) { return std::isalnum(static_cast<unsigned char>(c)) || c == '_'; }
// Byte offsets of the top-level argument separators and of the closing paren,
// starting from the '(' at openParen. Empty when the parentheses do not balance.
Vector<SizeT> SplitCallArguments(const String& code, SizeT openParen) {
Vector<SizeT> marks;
Int depth = 0;
for (SizeT i = openParen; i < code.size(); ++i) {
const char c = code[i];
if (c == '(' || c == '[') {
++depth;
} else if (c == ']') {
--depth;
} else if (c == ')') {
--depth;
if (depth == 0) {
marks.push_back(i);
return marks;
}
} else if (c == ',' && depth == 1) {
marks.push_back(i);
}
}
return {};
}
} // namespace
String EmulateTextureLodBias(const String& glslCode) {
#ifdef TRACY_ENABLE
ZoneScopedC(TRACY_ZONECOLOR_BACKEND);
#endif
if (glslCode.find("sampler") == String::npos || glslCode.find("texture") == String::npos) {
return glslCode;
}
// Collect the mip-capable sampler uniforms this shader declares.
static const std::regex samplerDeclRegex(
R"(uniform\s+(?:(?:highp|mediump|lowp)\s+)?([iu]?sampler[A-Za-z0-9]*)\s+([A-Za-z_][A-Za-z0-9_]*)\s*;)");
UnorderedMap<String, String> samplerNames; // name -> bias uniform name
for (std::sregex_iterator it(glslCode.begin(), glslCode.end(), samplerDeclRegex), end; it != end; ++it) {
const String samplerType = (*it)[1].str();
if (!IsBiasableSamplerType(samplerType)) continue;
const String name = (*it)[2].str();
samplerNames.emplace(name, String(LOD_BIAS_UNIFORM_PREFIX) + name);
}
if (samplerNames.empty()) {
return glslCode;
}
// Rewrite the lookups. Right-to-left so earlier offsets stay valid, and only for
// samplers named directly as the first argument (SPIRV-Cross never produces an
// expression there for ES output, which has no separate sampler objects).
String result = glslCode;
Vector<String> usedSamplers;
for (SizeT scan = result.size(); scan-- > 0;) {
if (result[scan] != 't') continue;
if (scan > 0 && IsIdentifierChar(result[scan - 1])) continue;
const LodLookupForm* form = nullptr;
SizeT openParen = 0;
for (const auto& candidate : LOD_LOOKUP_FORMS) {
const SizeT nameLength = std::strlen(candidate.name);
if (result.compare(scan, nameLength, candidate.name) != 0) continue;
SizeT after = result.find_first_not_of(" \t", scan + nameLength);
if (after == String::npos || result[after] != '(') continue;
form = &candidate;
openParen = after;
break;
}
if (form == nullptr) continue;
const Vector<SizeT> marks = SplitCallArguments(result, openParen);
if (marks.empty()) continue;
const SizeT argCount = marks.size();
const SizeT closeParen = marks.back();
// First argument must be one of our samplers.
const SizeT firstArgStart = result.find_first_not_of(" \t", openParen + 1);
SizeT firstArgEnd = marks.front();
while (firstArgEnd > firstArgStart && (result[firstArgEnd - 1] == ' ' || result[firstArgEnd - 1] == '\t')) {
--firstArgEnd;
}
if (firstArgStart == String::npos || firstArgEnd <= firstArgStart) continue;
const String samplerName = result.substr(firstArgStart, firstArgEnd - firstArgStart);
const auto samplerIt = samplerNames.find(samplerName);
if (samplerIt == samplerNames.end()) continue;
const String& biasName = samplerIt->second;
if (form->explicitLodArg >= 0) {
// Explicit LOD: the bias adds to it, as Vulkan does for
// OpImageSampleExplicitLod and as the CTS reference expects.
const SizeT lodIndex = static_cast<SizeT>(form->explicitLodArg);
if (argCount <= lodIndex) continue;
const SizeT lodStart = marks[lodIndex - 1] + 1;
const SizeT lodEnd = marks[lodIndex];
result.insert(lodEnd, String(") + ") + biasName + ")");
result.insert(lodStart, "((");
} else {
const SizeT required = static_cast<SizeT>(form->requiredArgs);
if (argCount == required) {
result.insert(closeParen, String(", ") + biasName);
} else if (argCount == required + 1) {
const SizeT biasStart = marks[argCount - 2] + 1;
result.insert(closeParen, String(") + ") + biasName + ")");
result.insert(biasStart, "((");
} else {
continue;
}
}
usedSamplers.push_back(samplerName);
}
if (usedSamplers.empty()) {
return glslCode;
}
// Declare the bias uniforms that were actually referenced, right after the
// sampler declaration line they belong to.
for (const auto& samplerName : usedSamplers) {
const String& biasName = samplerNames[samplerName];
if (result.find(String("float ") + biasName + ";") != String::npos) continue;
const std::regex declRegex(
R"(uniform\s+(?:(?:highp|mediump|lowp)\s+)?[iu]?sampler[A-Za-z0-9]*\s+)" + samplerName + R"(\s*;)");
std::smatch match;
if (!std::regex_search(result, match, declRegex)) continue;
const SizeT declEnd = static_cast<SizeT>(match.position(0)) + match[0].str().size();
result.insert(declEnd, String("\nuniform highp float ") + biasName + ";");
}
return result;
}
} // namespace PrgramImpl
namespace Utils {
+24
View File
@@ -40,6 +40,11 @@ namespace MobileGL::MG_Backend::DirectGLES {
void GenerateRenderbufferFormatInfo(TextureInternalFormat internalFormat, GLenum* outInternalFormat,
GLenum* outFormat, GLenum* outType);
Bool ShouldUseCaveatTextureFormat(TextureInternalFormat internalFormat, TextureTarget target);
// True when the format the texture is actually created with has an alpha channel the
// frontend format does not (the three-channel multisample widening). GL reads such a
// channel back as 1.0, so any swizzle source of ALPHA has to be answered with ONE.
Bool BackendTextureFormatAddsAlpha(TextureInternalFormat internalFormat, TextureTarget target);
Bool ShouldUseCaveatRenderbufferFormat(TextureInternalFormat internalFormat);
} // namespace TextureImpl
@@ -104,7 +109,26 @@ namespace MobileGL::MG_Backend::DirectGLES {
String ClampNormFallbackOutputs(String glslCode, GLenum shaderType, Uint32 snormOutputMask,
Uint32 unormOutputMask);
String ForceFlatIntegerVaryings(const String& glslCode, GLenum shaderType);
// Legacy GLSL's gl_FragColor is broadcast to every enabled draw buffer (GL 4.6
// 15.2.3), but ShaderSourceProcessor lowers it to the single output mg_FragColor,
// which only ever reaches draw buffer 0. Replicates it across `drawBufferCount`
// outputs and copies the value into them at the end of main. A no-op for
// drawBufferCount <= 1, i.e. for everything but a framebuffer that actually
// enables several draw buffers, so the ordinary single-target shader is untouched.
String BroadcastLegacyFragColor(String glslCode, GLenum shaderType, Uint drawBufferCount);
String RemoveLayoutBinding(const String& glslCode);
// Prefix of the per-sampler float uniform that carries GL_TEXTURE_LOD_BIAS into
// the shader (see EmulateTextureLodBias); the suffix is the sampler's own name.
constexpr const char* LOD_BIAS_UNIFORM_PREFIX = "mg_lodBias_";
// ES has no per-texture/sampler LOD bias at all (GL_TEXTURE_LOD_BIAS is desktop
// only; Vulkan spells it VkSamplerCreateInfo::mipLodBias), so it has to reach the
// shader as a uniform and be folded into every lookup's level of detail. Declares
// one `uniform highp float mg_lodBias_<sampler>;` per mip-capable sampler and adds
// it to the bias / explicit-LOD argument of every lookup that takes one. Draws push
// the bound texture's (or sampler object's) value into it; a shader whose samplers
// all have a zero bias is therefore unaffected. Returns the source unchanged when
// there is nothing to rewrite.
String EmulateTextureLodBias(const String& glslCode);
} // namespace PrgramImpl
namespace Utils {
@@ -578,6 +578,9 @@ namespace MobileGL::MG_Impl::GLImpl {
}
}
MG_State::pGLContext->BeginTransformFeedback(primitiveMode, program);
if (const auto beginXfb = MG_Backend::gBackendFunctionsTable.GL.BeginTransformFeedback) {
beginXfb(primitiveMode);
}
}
// Vulkan transform feedback captures triangle strips in plain (i, i+1, i+2)
@@ -587,6 +590,12 @@ namespace MobileGL::MG_Impl::GLImpl {
// vertex records of every odd triangle within each emitted strip.
static void FixupGsStripCaptureOrder(const SharedPtr<MG_State::GLState::ProgramObject>& program,
Uint64 inputPrimitives) {
// Only Vulkan-order captures need this. A backend that runs the capture on its
// own GL/ES driver (it owns the span, hence the EndTransformFeedback entry) has
// already produced GL's vertex order, and reordering it again would corrupt it.
if (MG_Backend::gBackendFunctionsTable.GL.EndTransformFeedback != nullptr) {
return;
}
if (program == nullptr || !program->HasGsTriangleStripCaptureFixup() || inputPrimitives == 0) {
return;
}
@@ -649,6 +658,11 @@ namespace MobileGL::MG_Impl::GLImpl {
}
const auto capturedProgram = MG_State::pGLContext->GetTransformFeedbackProgram();
const Uint64 inputPrimitives = MG_State::pGLContext->GetTransformFeedbackInputPrimitives();
// Closed while the capture state is still active: a backend that captures
// through its own driver reads the capture program and buffer bindings here.
if (const auto endXfb = MG_Backend::gBackendFunctionsTable.GL.EndTransformFeedback) {
endXfb();
}
MG_State::pGLContext->EndTransformFeedback();
// Captured results must be visible to MapBuffer/GetBufferSubData after
// End; the capture targets are host-coherent GPU memory, so completing
@@ -22,9 +22,21 @@
namespace MobileGL::MG_Impl::GLImpl {
namespace {
Bool IsActiveBackendDirectVulkan() {
// GL only requires support for framebuffers whose depth and stencil attachments
// are the same image; anything else may be reported GL_FRAMEBUFFER_UNSUPPORTED.
// DirectVulkan cannot form two separate attachments at all, and the real ES
// drivers behind DirectGLES answer UNSUPPORTED for it too - so saying COMPLETE
// and then rendering into a framebuffer the driver refuses produced silently
// empty results (KHR-GL3x.packed_depth_stencil.verify_mixed_attachments).
Bool ActiveBackendRejectsDistinctDepthStencil() {
auto* activeBackend = MG_Backend::pActiveBackendObject.get();
return activeBackend != nullptr && activeBackend->GetBackendType() == BackendType::DirectVulkan;
if (activeBackend == nullptr) {
return false;
}
if (activeBackend->GetBackendType() == BackendType::DirectVulkan) {
return true;
}
return !activeBackend->GetDynamicParameters().SupportsDistinctDepthStencilAttachments;
}
Bool HasDistinctCompleteDepthStencilTextureAttachments(
@@ -66,7 +78,7 @@ namespace MobileGL::MG_Impl::GLImpl {
(depthAttachment.IsTexture() || stencilAttachment.IsTexture());
}
Bool IsUnsupportedFramebufferForDirectVulkan(
Bool HasUnsupportedDistinctDepthStencilAttachments(
const MG_State::GLState::FramebufferObject& framebufferObject) {
// TODO: Keep this in sync with DirectVulkan renderbuffer support as color renderbuffer rendering lands.
return HasDistinctCompleteDepthStencilTextureAttachments(framebufferObject) ||
@@ -89,7 +101,14 @@ namespace MobileGL::MG_Impl::GLImpl {
// shared-exponent, SNORM, three-channel norm16/float32/sRGB and three-channel integer formats.
// Desktop GL treats those as texture-only too (not in the GL 3.3 required-renderable list), so
// reporting GL_FRAMEBUFFER_UNSUPPORTED for them is legal.
Bool IsColorInternalFormatRenderable(TextureInternalFormat format) {
//
// `capabilityTargetIndex` is the row of the cache the attachment actually lives in;
// kFormatCapabilityTargetCount asks about the format in general. Asking per target matters
// because a capability recorded for one of them says nothing about the others: DirectGLES
// widens three-channel formats to four channels to keep them renderable as *multisample*
// storage, and a format that survives only through that substitution is still texture-only
// on every ordinary target.
Bool IsColorInternalFormatRenderable(TextureInternalFormat format, SizeT capabilityTargetIndex) {
const SizeT formatIndex = static_cast<SizeT>(format);
if (MG_Backend::pActiveBackendObject && formatIndex < MG_Backend::kFormatCapabilityFormatCount) {
const auto& cache = MG_Backend::pActiveBackendObject->GetFormatCapabilities();
@@ -101,8 +120,11 @@ namespace MobileGL::MG_Impl::GLImpl {
MG_Backend::FormatCapability::Creatable);
}
if (cachePopulated) {
for (SizeT targetIndex = 0; targetIndex < MG_Backend::kFormatCapabilityTargetCount;
++targetIndex) {
const Bool singleTarget = capabilityTargetIndex < MG_Backend::kFormatCapabilityTargetCount;
const SizeT firstTarget = singleTarget ? capabilityTargetIndex : 0;
const SizeT lastTarget =
singleTarget ? capabilityTargetIndex + 1 : MG_Backend::kFormatCapabilityTargetCount;
for (SizeT targetIndex = firstTarget; targetIndex < lastTarget; ++targetIndex) {
if (MG_Backend::HasFormatCapability(cache.FullCaps[targetIndex][formatIndex],
MG_Backend::FormatCapability::FramebufferRenderable) ||
MG_Backend::HasFormatCapability(cache.CaveatCaps[targetIndex][formatIndex],
@@ -151,12 +173,17 @@ namespace MobileGL::MG_Impl::GLImpl {
const auto& attachment = attachments[i];
if (!attachment.IsValid()) continue;
TextureInternalFormat format = TextureInternalFormat::Unknown;
SizeT capabilityTargetIndex = MG_Backend::kFormatCapabilityTargetCount;
if (attachment.IsTexture() && attachment.GetTexture()) {
format = attachment.GetTexture()->GetFormat();
capabilityTargetIndex =
MG_Backend::GetFormatCapabilityTargetIndex(attachment.GetTexture()->GetTarget());
} else if (attachment.IsRenderbuffer() && attachment.GetRenderbuffer()) {
format = attachment.GetRenderbuffer()->GetInternalFormat();
capabilityTargetIndex = MG_Backend::GetRenderbufferFormatCapabilityTargetIndex();
}
if (format != TextureInternalFormat::Unknown && !IsColorInternalFormatRenderable(format)) {
if (format != TextureInternalFormat::Unknown &&
!IsColorInternalFormatRenderable(format, capabilityTargetIndex)) {
return true;
}
}
@@ -1631,8 +1658,8 @@ namespace MobileGL::MG_Impl::GLImpl {
if (HasNonRenderableColorAttachment(*framebufferObject)) {
return GL_FRAMEBUFFER_UNSUPPORTED;
}
if (IsActiveBackendDirectVulkan() &&
IsUnsupportedFramebufferForDirectVulkan(*framebufferObject)) {
if (ActiveBackendRejectsDistinctDepthStencil() &&
HasUnsupportedDistinctDepthStencilAttachments(*framebufferObject)) {
return GL_FRAMEBUFFER_UNSUPPORTED;
}
return GL_FRAMEBUFFER_COMPLETE;
@@ -1659,8 +1686,8 @@ namespace MobileGL::MG_Impl::GLImpl {
if (HasNonRenderableColorAttachment(*framebufferObject)) {
return GL_FRAMEBUFFER_UNSUPPORTED;
}
if (IsActiveBackendDirectVulkan() &&
IsUnsupportedFramebufferForDirectVulkan(*framebufferObject)) {
if (ActiveBackendRejectsDistinctDepthStencil() &&
HasUnsupportedDistinctDepthStencilAttachments(*framebufferObject)) {
return GL_FRAMEBUFFER_UNSUPPORTED;
}
return GL_FRAMEBUFFER_COMPLETE;
@@ -824,6 +824,12 @@ namespace MobileGL::MG_Util::BackendLoader {
if (std::strcmp(extension, "GL_EXT_texture_norm16") == 0) {
caps.SupportsNorm16Texture = true;
}
if (std::strcmp(extension, "GL_EXT_render_snorm") == 0) {
caps.SupportsRenderSnorm = true;
}
if (std::strcmp(extension, "GL_EXT_sRGB_write_control") == 0) {
caps.SupportsSrgbWriteControl = true;
}
if (std::strcmp(extension, "GL_EXT_texture_filter_anisotropic") == 0) {
caps.SupportsTextureFilterAnisotropy = true;
}
@@ -1031,6 +1031,13 @@ namespace MobileGL {
String GLESShadingLanguageVersionString;
Bool SupportsPersistentMapping = false;
Bool SupportsNorm16Texture = false;
// GL_EXT_render_snorm is present, so the signed-normalized formats are colour-renderable
// (and usable as multisample texture storage) rather than texture-only.
Bool SupportsRenderSnorm = false;
// GL_EXT_sRGB_write_control is present, so GL_FRAMEBUFFER_SRGB can be turned off.
// GLES has no such switch in core: writes into an sRGB attachment are ALWAYS encoded,
// while desktop GL leaves GL_FRAMEBUFFER_SRGB disabled by default and writes raw.
Bool SupportsSrgbWriteControl = false;
// GL_EXT_texture_filter_anisotropic is present, so sampler/texture
// anisotropy may be forwarded without raising GL_INVALID_ENUM in GLES.
Bool SupportsTextureFilterAnisotropy = false;
@@ -363,6 +363,86 @@ namespace MobileGL {
return optimizer.Run(inputBinary.data(), inputBinary.size(), &outputBinary, options);
}
bool ShaderCompiler::LowerRectImagesForEssl(const Vector<Uint32>& inputBinary,
Vector<uint32_t>& outputBinary) {
constexpr SizeT kSpirvHeaderWordCount = 5;
// OpTypeImage: [0] opcode/wordcount, [1] result id, [2] sampled type, [3] Dim, ...
constexpr SizeT kTypeImageDimWordIndex = 3;
constexpr SizeT kTypeImageMinWordCount = 9;
outputBinary.clear();
if (inputBinary.size() < kSpirvHeaderWordCount || inputBinary[0] != spv::MagicNumber) {
return false;
}
Vector<SizeT> rectDimWordOffsets;
Vector<SizeT> rectCapabilityWordOffsets;
Bool hasNormalizedCoordinateLookup = false;
for (SizeT offset = kSpirvHeaderWordCount; offset < inputBinary.size();) {
const Uint32 instructionWord = inputBinary[offset];
const SizeT wordCount = instructionWord >> 16u;
const auto opcode = static_cast<spv::Op>(instructionWord & 0xffffu);
if (wordCount == 0 || offset + wordCount > inputBinary.size()) {
return false;
}
if (opcode == spv::Op::OpTypeImage && wordCount >= kTypeImageMinWordCount) {
if (static_cast<spv::Dim>(inputBinary[offset + kTypeImageDimWordIndex]) == spv::Dim::Rect) {
rectDimWordOffsets.push_back(offset + kTypeImageDimWordIndex);
}
} else if (opcode == spv::Op::OpCapability && wordCount >= 2) {
const auto capability = static_cast<spv::Capability>(inputBinary[offset + 1]);
if (capability == spv::Capability::SampledRect ||
capability == spv::Capability::ImageRect) {
rectCapabilityWordOffsets.push_back(offset + 1);
}
} else {
switch (opcode) {
// Everything that takes normalized coordinates. Tracing each one back to
// its image type would let a module mix a normalized 2D lookup with a
// rectangle fetch, but the extra reach is not worth the risk of getting
// the trace wrong: decline the whole module instead.
case spv::Op::OpImageSampleImplicitLod:
case spv::Op::OpImageSampleExplicitLod:
case spv::Op::OpImageSampleDrefImplicitLod:
case spv::Op::OpImageSampleDrefExplicitLod:
case spv::Op::OpImageSampleProjImplicitLod:
case spv::Op::OpImageSampleProjExplicitLod:
case spv::Op::OpImageSampleProjDrefImplicitLod:
case spv::Op::OpImageSampleProjDrefExplicitLod:
case spv::Op::OpImageGather:
case spv::Op::OpImageDrefGather:
case spv::Op::OpImageSparseSampleImplicitLod:
case spv::Op::OpImageSparseSampleExplicitLod:
case spv::Op::OpImageSparseSampleDrefImplicitLod:
case spv::Op::OpImageSparseSampleDrefExplicitLod:
case spv::Op::OpImageSparseGather:
case spv::Op::OpImageSparseDrefGather:
hasNormalizedCoordinateLookup = true;
break;
default:
break;
}
}
offset += wordCount;
}
if (rectDimWordOffsets.empty() || hasNormalizedCoordinateLookup) {
return false;
}
outputBinary.assign(inputBinary.begin(), inputBinary.end());
for (const SizeT dimWordOffset : rectDimWordOffsets) {
outputBinary[dimWordOffset] = static_cast<Uint32>(spv::Dim::Dim2D);
}
// The rectangle capabilities describe types that no longer exist. Shader is always
// declared by a graphics module, so restating it keeps the word count intact
// without leaving a capability SPIRV-Cross would key off.
for (const SizeT capabilityWordOffset : rectCapabilityWordOffsets) {
outputBinary[capabilityWordOffset] = static_cast<Uint32>(spv::Capability::Shader);
}
return true;
}
bool ShaderCompiler::RebaseInstanceIndexForVulkan(const Vector<Uint32>& inputBinary,
Vector<uint32_t>& outputBinary) {
using namespace spvtools;
@@ -43,6 +43,16 @@ namespace MobileGL {
// devices lacking GL_NV_shader_noperspective_interpolation. See EmulateNoPerspectivePass.
static bool EmulateNoPerspectiveForEssl(const Vector<Uint32>& inputBinary,
Vector<uint32_t>& outputBinary);
// Rewrites rectangle images (Dim::Rect) to plain 2D so SPIRV-Cross can emit ESSL
// for them at all - it refuses outright ("Rectangle textures are not supported on
// OpenGL ES"), which left the whole program unlinkable. Only valid while every use
// of the image takes integer texel coordinates (texelFetch / textureSize), where a
// rectangle target and a 2D target are indistinguishable; a normalized-coordinate
// lookup would also need its coordinates divided by the texture size, so the pass
// declines those modules instead of emitting something subtly wrong. Returns false
// when it changed nothing or cannot safely convert. DirectGLES only.
static bool LowerRectImagesForEssl(const Vector<Uint32>& inputBinary,
Vector<uint32_t>& outputBinary);
// Rebases loads of the InstanceIndex builtin to (InstanceIndex - BaseInstance) so
// shaders see GL's zero-based gl_InstanceID. Vertex shaders only; DirectVulkan
// backend only (glslang's relaxed mode aliases gl_InstanceID to gl_InstanceIndex,
@@ -29,11 +29,16 @@ namespace MobileGL::MG_Util::TextureFormatProcessor {
case GL_RGB12: // stored as RGB16 (see NormalizePixelFormat)
applicableOptions |= options & PixelFormatNormalizeOptionBit::NoNorm16;
applicableOptions |= options & PixelFormatNormalizeOptionBit::NoRgb16;
applicableOptions |= options & PixelFormatNormalizeOptionBit::NoThreeChannelRenderTarget;
break;
case GL_RGB16_SNORM:
applicableOptions |= options & PixelFormatNormalizeOptionBit::NoRGB16Snorm;
applicableOptions |= options & PixelFormatNormalizeOptionBit::NoNorm16;
applicableOptions |= options & PixelFormatNormalizeOptionBit::NoSnorm16;
applicableOptions |= options & PixelFormatNormalizeOptionBit::NoThreeChannelRenderTarget;
if (options & PixelFormatNormalizeOptionBit::NoThreeChannelRenderTarget) {
applicableOptions |= options & PixelFormatNormalizeOptionBit::NoSnorm16RenderTarget;
}
break;
case GL_RGBA16_SNORM:
case GL_RG16_SNORM:
@@ -46,6 +51,9 @@ namespace MobileGL::MG_Util::TextureFormatProcessor {
applicableOptions |= options & PixelFormatNormalizeOptionBit::NoRGBA8Snorm;
break;
case GL_RGB8_SNORM:
applicableOptions |= options & PixelFormatNormalizeOptionBit::NoSnorm8;
applicableOptions |= options & PixelFormatNormalizeOptionBit::NoThreeChannelRenderTarget;
break;
case GL_RG8_SNORM:
case GL_R8_SNORM:
applicableOptions |= options & PixelFormatNormalizeOptionBit::NoSnorm8;
@@ -66,7 +74,15 @@ namespace MobileGL::MG_Util::TextureFormatProcessor {
switch (internalFormat) {
case GL_DEPTH_COMPONENT32:
if (options & PixelFormatNormalizeOptionBit::NoDepthComponent32) {
*outInternalFormat = GL_DEPTH_COMPONENT;
// The unsized GL_DEPTH_COMPONENT base format is not a legal
// glTexStorage/glRenderbufferStorage internal format on ES, which left
// the attachment with no storage at all (KHR-GL3x.framebuffer_blit's
// GL_DEPTH_COMPONENT32 config then read an incomplete framebuffer).
// GL_DEPTH_COMPONENT24 is the nearest sized ES format that keeps the
// same fixed-point encoding, so the GL_UNSIGNED_INT transfer type below
// still describes the data; GL_DEPTH_COMPONENT32F would need a float
// conversion the upload path does not apply.
*outInternalFormat = GL_DEPTH_COMPONENT24;
break;
}
*outInternalFormat = internalFormat;
@@ -79,6 +95,13 @@ namespace MobileGL::MG_Util::TextureFormatProcessor {
*outInternalFormat = internalFormat;
break;
case GL_RGB16:
if (options & PixelFormatNormalizeOptionBit::NoThreeChannelRenderTarget) {
// GL_RGB32F is a legal ES texture format but is not colour-renderable, so
// glTexStorage2DMultisample rejects it and the attachment ends up with no
// storage at all.
*outInternalFormat = GL_RGBA32F;
break;
}
if ((options & PixelFormatNormalizeOptionBit::NoNorm16) ||
(options & PixelFormatNormalizeOptionBit::NoRgb16)) {
*outInternalFormat = GL_RGB32F;
@@ -109,6 +132,14 @@ namespace MobileGL::MG_Util::TextureFormatProcessor {
*outInternalFormat = internalFormat;
break;
case GL_RGB16_SNORM:
if (options & PixelFormatNormalizeOptionBit::NoThreeChannelRenderTarget) {
// A half float loses the low bits of a 16-bit SNORM channel, so keep the
// signed-normalized encoding whenever the driver can render to it.
*outInternalFormat = (options & PixelFormatNormalizeOptionBit::NoSnorm16RenderTarget)
? GL_RGBA16F
: GL_RGBA16_SNORM;
break;
}
if ((options & PixelFormatNormalizeOptionBit::NoNorm16) ||
(options & PixelFormatNormalizeOptionBit::NoRGB16Snorm) ||
(options & PixelFormatNormalizeOptionBit::NoSnorm16)) {
@@ -142,6 +173,10 @@ namespace MobileGL::MG_Util::TextureFormatProcessor {
*outInternalFormat = internalFormat;
break;
case GL_RGB8_SNORM:
if (options & PixelFormatNormalizeOptionBit::NoThreeChannelRenderTarget) {
*outInternalFormat = GL_RGBA16F;
break;
}
if (options & PixelFormatNormalizeOptionBit::NoSnorm8) {
*outInternalFormat = GL_RGB16F;
break;
@@ -552,6 +587,8 @@ namespace MobileGL::MG_Util::TextureFormatProcessor {
*outType = GL_UNSIGNED_INT;
break;
case GL_DEPTH_COMPONENT32:
// Follows the internal-format normalization above: ES only accepts
// GL_FLOAT data for a GL_DEPTH_COMPONENT32F store.
*outType = GL_UNSIGNED_INT;
break;
case GL_DEPTH_COMPONENT32F:
@@ -18,6 +18,17 @@ namespace MobileGL {
NoDepthComponent32 = 1 << 4,
NoRGBA8Snorm = 1 << 5,
NoRGB16Snorm = 1 << 6,
// The target must be colour-renderable and ES has no renderable three-channel
// form of the requested format, so it has to be widened to the four-channel one.
// Only meaningful for multisample textures: those can never be uploaded to, only
// rendered into, so the extra alpha comes from the draw (1.0 for an RGB source)
// and no transfer path has to expand three-channel client data.
NoThreeChannelRenderTarget = 1 << 7,
// Pairs with the bit above: the widened four-channel format has to stay renderable AND
// keep 16-bit signed-normalized precision, which needs both EXT_texture_norm16 and
// EXT_render_snorm. Without them the only renderable widening left is a half float, whose
// 11-bit mantissa cannot represent a 16-bit SNORM channel exactly.
NoSnorm16RenderTarget = 1 << 8,
None = 0,
};
namespace MG_Util::TextureFormatProcessor {
+13 -1
View File
@@ -181,7 +181,19 @@ namespace MobileGL {
explicit BindingSlotRange1D(TargetEnum target, const Range1D& range = Range1D())
: BindingSlot<ObjectType>(target), m_range(range) {}
Range1D GetRange() const { return m_range; }
// The range the binding actually covers right now. A whole-buffer binding
// (glBindBufferBase) does not freeze anything: GL resolves it against the
// object's size at every use, so a glBufferData issued after the bind has to
// be visible here - binding an empty buffer and giving it storage afterwards
// is ordinary application code. Only glBindBufferRange pins a fixed window.
Range1D GetRange() const {
if (!m_hasExplicitRange) {
if (const auto& object = this->GetBoundObject()) {
return Range1D(0, object->GetSize());
}
}
return m_range;
}
Bool HasExplicitRange() const { return m_hasExplicitRange; }
+18 -3
View File
@@ -58,11 +58,26 @@ def main():
# explode (a 4-sample 16K depth texture alone is 4 GiB).
ap.add_argument("--surface-size", type=int, default=256,
help="--deqp-surface-width/height value")
# With DONT_CARE depth/stencil bits dEQP's FboRenderContext picks the first entry of
# its own format list, GL_DEPTH32F_STENCIL8. framebuffer_blit meanwhile hardcodes
# GL_DEPTH24_STENCIL8 for its own buffers whenever it detects an FBO surface, then
# blits depth between the two - which the spec forbids for mismatched formats, so a
# conformant driver has to fail it. Asking for a config the test agrees with avoids
# the contradiction instead of papering over it.
ap.add_argument("--gl-config-name", default="rgba8888d24s8",
help="--deqp-gl-config-name value (empty string to leave it unset)")
ap.add_argument("--max-rounds", type=int, default=4000)
ap.add_argument("--max-empty-streak", type=int, default=64,
help="abort after this many consecutive chunks that produce no log at all")
ap.add_argument("--chunk-timeout", type=int, default=1800,
help="seconds before killing one glcts invocation (a wedged case never returns)")
# dEQP's watchdog aborts the process when a single case exceeds a hardcoded 30s
# (framework/common/tcuApp.hpp), which is not a hang on a CPU rasterizer - some
# texture_swizzle cases legitimately take ~17s each and cross it once the process is
# warm, so they came back as spurious Timeouts. dEQP's own default is off; the
# chunk-timeout above is what actually rescues a genuinely wedged case.
ap.add_argument("--watchdog", default="disable", choices=["enable", "disable"],
help="--deqp-watchdog value")
ap.add_argument("--skip-file", default=None,
help="file of case names to exclude, e.g. cases known to wedge the host")
ap.add_argument("--waiver-file", default=None,
@@ -130,13 +145,13 @@ def main():
f"--deqp-surface-width={args.surface_size}",
f"--deqp-surface-height={args.surface_size}",
"--deqp-terminate-on-device-lost=disable",
# A wedged case aborts the process instead of stalling the chunk;
# the runner then records it as Crash and resumes past it.
"--deqp-watchdog=enable",
f"--deqp-watchdog={args.watchdog}",
"--deqp-log-images=disable",
"--deqp-log-shader-sources=disable",
f"--deqp-log-filename={qpa}",
]
if args.gl_config_name:
cmd.append(f"--deqp-gl-config-name={args.gl_config_name}")
if args.waiver_file:
cmd.append(f"--deqp-waiver-file={os.path.abspath(args.waiver_file)}")
timed_out = False