[Feat] (...): advertise GL_OVR_multiview and GL_OVR_multiview2 on DirectGLES

- Each string follows the driver's own extension; DirectVulkan advertises neither yet
- The attachment's view count crosses the wire in MGPSurface, and num_views reaches
  the ESSL after a capability strip, outside the translation memo
This commit is contained in:
swung0x48 committed 2026-11-24 01:37:51 -04:00
1 parent 2bdbe052c6
commit bf87d75d70
45 files changed
+1450 -101

No files matched your search

+1
View File
@@ -480,6 +480,7 @@ set(SOURCE_FILES
MobileGL/MG_Impl/GLImpl/RenderState/GL_RenderState.cpp MobileGL/MG_Impl/GLImpl/RenderState/GL_RenderState.cpp
MobileGL/MG_Impl/GLImpl/Framebuffer/Validators.cpp MobileGL/MG_Impl/GLImpl/Framebuffer/Validators.cpp
MobileGL/MG_Impl/GLImpl/Framebuffer/GL_Framebuffer.cpp MobileGL/MG_Impl/GLImpl/Framebuffer/GL_Framebuffer.cpp
MobileGL/MG_Impl/GLImpl/Framebuffer/GL_FramebufferMultiview.cpp
MobileGL/MG_Impl/GLImpl/Program/GL_Program.cpp MobileGL/MG_Impl/GLImpl/Program/GL_Program.cpp
MobileGL/MG_Impl/GLImpl/Program/GL_ShaderObjectsARB.cpp MobileGL/MG_Impl/GLImpl/Program/GL_ShaderObjectsARB.cpp
MobileGL/MG_Impl/GLImpl/Program/ProgramInterface.cpp MobileGL/MG_Impl/GLImpl/Program/ProgramInterface.cpp
+8
View File
@@ -103,6 +103,11 @@ namespace MobileGL {
// GL_EXT_clip_control on DirectGLES. DirectVulkan applies clip control in its own // GL_EXT_clip_control on DirectGLES. DirectVulkan applies clip control in its own
// position fixup and does not read this. // position fixup and does not read this.
Bool ClipControl = false; Bool ClipControl = false;
// GL_OVR_multiview and GL_OVR_multiview2, each only where the driver has that same
// extension (and, for the first, glFramebufferTextureMultiviewOVR). DirectGLES only:
// DirectVulkan has no multiview render pass route and leaves both false.
Bool Multiview = false;
Bool Multiview2 = false;
}; };
// Coarse GPU vendor identity for gating device-specific quirks. Detected from the // Coarse GPU vendor identity for gating device-specific quirks. Detected from the
@@ -411,6 +416,9 @@ namespace MobileGL {
Int MaxFragmentShadingRateAttachmentTexelHeight = 0; Int MaxFragmentShadingRateAttachmentTexelHeight = 0;
Int MaxFragmentShadingRateAttachmentTexelAspectRatio = 0; Int MaxFragmentShadingRateAttachmentTexelAspectRatio = 0;
Int MaxFragmentShadingRateAttachmentLayers = 0; Int MaxFragmentShadingRateAttachmentLayers = 0;
// GL_MAX_VIEWS_OVR. Zero means no multiview, which is also why GL_OVR_multiview is not
// advertised then; a backend that has it reports at least the spec minimum of 2.
Int MaxViews = 0;
static constexpr Bool IsSamplePositionCount(Int samples) { static constexpr Bool IsSamplePositionCount(Int samples) {
return samples >= 2 && samples <= kMaxSamplePositionCount && (samples & (samples - 1)) == 0; return samples >= 2 && samples <= kMaxSamplePositionCount && (samples & (samples - 1)) == 0;
@@ -903,7 +903,9 @@ namespace MobileGL::MG_Backend::DirectGLES {
capabilities.SupportsTextureView, capabilities.SupportsTextureCubeMapArray, capabilities.SupportsTextureView, capabilities.SupportsTextureCubeMapArray,
AdvertisedFeatureSupport{.TessellationShader = capabilities.SupportsTessellationShader, AdvertisedFeatureSupport{.TessellationShader = capabilities.SupportsTessellationShader,
.CullDistance = capabilities.MaxCullDistances > 0, .CullDistance = capabilities.MaxCullDistances > 0,
.ClipControl = capabilities.SupportsClipControl}); .ClipControl = capabilities.SupportsClipControl,
.Multiview = capabilities.SupportsMultiview,
.Multiview2 = capabilities.SupportsMultiview2});
// Exactly what InitCapabilities forwards into the dynamic parameters: the base // Exactly what InitCapabilities forwards into the dynamic parameters: the base
// extension and _primitive when the driver has them, _attachment not yet. // extension and _primitive when the driver has them, _attachment not yet.
auto& extensions = MutableRendererInfo().RendererGLInfo.Extensions; auto& extensions = MutableRendererInfo().RendererGLInfo.Extensions;
@@ -1585,6 +1587,14 @@ namespace MobileGL::MG_Backend::DirectGLES {
if (features.ClipControl) { if (features.ClipControl) {
extensions.push_back(E_GL_ARB_clip_control); extensions.push_back(E_GL_ARB_clip_control);
} }
// Multiview attachments go to the driver's glFramebufferTextureMultiviewOVR and
// gl_ViewID_OVR to its own built-in, so each string follows the driver's.
if (features.Multiview) {
extensions.push_back(E_GL_OVR_multiview);
if (features.Multiview2) {
extensions.push_back(E_GL_OVR_multiview2);
}
}
// Minecraft 26.3 checks this prerequisite before it even considers // Minecraft 26.3 checks this prerequisite before it even considers
// GL_ARB_multi_draw_indirect. ES 3.1 supplies both single-draw entry points; the loader // GL_ARB_multi_draw_indirect. ES 3.1 supplies both single-draw entry points; the loader
// folds the version and pointer checks into SupportsDrawIndirect. // folds the version and pointer checks into SupportsDrawIndirect.
@@ -2022,6 +2032,7 @@ namespace MobileGL::MG_Backend::DirectGLES {
// the device answers every query. The attachment is not forwarded yet, so it is not // the device answers every query. The attachment is not forwarded yet, so it is not
// claimed, whatever the driver offers. // claimed, whatever the driver offers.
m_dynamicParameters.SupportsFragmentShadingRate = m_GLESCapabilities.SupportsFragmentShadingRate; m_dynamicParameters.SupportsFragmentShadingRate = m_GLESCapabilities.SupportsFragmentShadingRate;
m_dynamicParameters.MaxViews = m_GLESCapabilities.SupportsMultiview ? m_GLESCapabilities.MaxViews : 0;
m_dynamicParameters.SupportsPrimitiveFragmentShadingRate = m_dynamicParameters.SupportsPrimitiveFragmentShadingRate =
m_GLESCapabilities.SupportsFragmentShadingRatePrimitive; m_GLESCapabilities.SupportsFragmentShadingRatePrimitive;
m_dynamicParameters.SupportsAttachmentFragmentShadingRate = false; m_dynamicParameters.SupportsAttachmentFragmentShadingRate = false;
@@ -1045,7 +1045,8 @@ namespace MobileGL::MG_Backend::DirectGLES {
const auto& color = record.Color[i]; const auto& color = record.Color[i];
if (color.Res == record.ReadSurface.Res && color.Kind == record.ReadSurface.Kind && if (color.Res == record.ReadSurface.Res && color.Kind == record.ReadSurface.Kind &&
color.Layered == record.ReadSurface.Layered && color.Level == record.ReadSurface.Level && color.Layered == record.ReadSurface.Layered && color.Level == record.ReadSurface.Level &&
color.Layer == record.ReadSurface.Layer && color.UploadTarget == record.ReadSurface.UploadTarget) { color.NumViews == record.ReadSurface.NumViews && color.Layer == record.ReadSurface.Layer &&
color.UploadTarget == record.ReadSurface.UploadTarget) {
return static_cast<FramebufferAttachmentType>(static_cast<Int>(FramebufferAttachmentType::Color0) + return static_cast<FramebufferAttachmentType>(static_cast<Int>(FramebufferAttachmentType::Color0) +
static_cast<Int>(i)); static_cast<Int>(i));
} }
@@ -2673,6 +2673,8 @@ namespace MobileGL::MG_Backend::DirectGLES {
// build's (ProgramBuildSource), so the pull build compiles the very same text // build's (ProgramBuildSource), so the pull build compiles the very same text
// against a ProgramObject and G1's byte identity survives. // against a ProgramObject and G1's byte identity survives.
Uint GetExternalIndex() const { return Identity; } Uint GetExternalIndex() const { return Identity; }
// GL_OVR_multiview's num_views of the vertex stage, 0 without one.
Int GetVertexNumViews() const { return Link ? Link->vsNumViews : 0; }
Bool GetLinkStatus() const { return Linked; } Bool GetLinkStatus() const { return Linked; }
Bool GetSpirvStatus() const { return SpirvUsable; } Bool GetSpirvStatus() const { return SpirvUsable; }
Bool GetSpirvValidationEnabled() const { return SpirvValidationEnabled; } Bool GetSpirvValidationEnabled() const { return SpirvValidationEnabled; }
@@ -409,7 +409,21 @@ namespace MobileGL::MG_Backend::DirectGLES {
// texture behind the staged shadow's back (the frontend arm's note, by handle). // texture behind the staged shadow's back (the frontend arm's note, by handle).
TextureImpl::NoteDriverSideTextureWriteByHandle(surface.Res); TextureImpl::NoteDriverSideTextureWriteByHandle(surface.Res);
const auto uploadTarget = static_cast<TextureUploadTarget>(surface.UploadTarget); const auto uploadTarget = static_cast<TextureUploadTarget>(surface.UploadTarget);
if (surface.Layered != 0) { if (surface.NumViews != 0) {
// GL_OVR_multiview. The frontend only builds one where the driver has the
// extension, but the record is the untrusted half: a multiview surface on a
// driver without the entry point is refused by name, never called through.
if (!g_GLESCapabilities.SupportsMultiview) {
MGLOG_E_ONCE("MGPipe: attachment surface {%u, %u} is multiview, but this driver has no "
"GL_OVR_multiview - refusing to attach it",
surface.Res.Slot, surface.Res.Gen);
return false;
}
g_GLESFuncs.glFramebufferTextureMultiviewOVR(
glFBOTarget, glBackendAttachment, backendTextureObject->GetBackendTextureId(),
static_cast<GLint>(surface.Level), static_cast<GLint>(surface.Layer),
static_cast<GLsizei>(surface.NumViews));
} else if (surface.Layered != 0) {
g_GLESFuncs.glFramebufferTexture(glFBOTarget, glBackendAttachment, g_GLESFuncs.glFramebufferTexture(glFBOTarget, glBackendAttachment,
backendTextureObject->GetBackendTextureId(), backendTextureObject->GetBackendTextureId(),
static_cast<GLint>(surface.Level)); static_cast<GLint>(surface.Level));
@@ -580,7 +594,7 @@ namespace MobileGL::MG_Backend::DirectGLES {
const auto& color = record.Color[i]; const auto& color = record.Color[i];
if (color.Res == record.ReadSurface.Res && color.Kind == record.ReadSurface.Kind && if (color.Res == record.ReadSurface.Res && color.Kind == record.ReadSurface.Kind &&
color.Layered == record.ReadSurface.Layered && color.Level == record.ReadSurface.Level && color.Layered == record.ReadSurface.Layered && color.Level == record.ReadSurface.Level &&
color.Layer == record.ReadSurface.Layer && color.NumViews == record.ReadSurface.NumViews && color.Layer == record.ReadSurface.Layer &&
color.UploadTarget == record.ReadSurface.UploadTarget) { color.UploadTarget == record.ReadSurface.UploadTarget) {
pushedReadBuf = static_cast<FramebufferAttachmentType>( pushedReadBuf = static_cast<FramebufferAttachmentType>(
static_cast<Int>(FramebufferAttachmentType::Color0) + static_cast<Int>(i)); static_cast<Int>(FramebufferAttachmentType::Color0) + static_cast<Int>(i));
@@ -1371,6 +1371,14 @@ namespace MobileGL::MG_Backend::DirectGLES {
} }
} }
// After every validating pass: the module that comes back names ViewIndex without the
// capability, which only SPIRV-Cross reads (see StripMultiviewCapabilityForEssl).
Vector<unsigned int> multiviewStrippedSpirv;
if (MG_Util::ShaderTranspiler::ShaderCompiler::StripMultiviewCapabilityForEssl(*effectiveSpirv,
multiviewStrippedSpirv)) {
effectiveSpirv = &multiviewStrippedSpirv;
}
MG_Util::ShaderTranspiler::SpvcSession spvcSession(*effectiveSpirv, MG_Util::ShaderTranspiler::SpvcSession spvcSession(*effectiveSpirv,
MG_Util::ShaderTranspiler::SessionUsageBit::Transpile); MG_Util::ShaderTranspiler::SessionUsageBit::Transpile);
@@ -2155,6 +2163,9 @@ namespace MobileGL::MG_Backend::DirectGLES {
!(ViewportArrayEmulationEnabled() && programRoutesViewportIndex) && !(ViewportArrayEmulationEnabled() && programRoutesViewportIndex) &&
source.find("gl_ViewportIndex") != String::npos; source.find("gl_ViewportIndex") != String::npos;
source = RequestViewportArrayExtension(std::move(source), needsViewportArrayExtension); source = RequestViewportArrayExtension(std::move(source), needsViewportArrayExtension);
// GL_OVR_multiview's directive and num_views, which the memoized ESSL leaves out.
source = RequestMultiviewExtension(std::move(source), glShaderType, src.GetVertexNumViews(),
g_GLESCapabilities.SupportsMultiview2);
// The fourth header-level rewrite, and the same shape as the third: ESSL has no // The fourth header-level rewrite, and the same shape as the third: ESSL has no
// gl_PointSize in a tessellation or geometry stage at ANY version - 320 makes the // gl_PointSize in a tessellation or geometry stage at ANY version - 320 makes the
+30
View File
@@ -741,6 +741,36 @@ namespace MobileGL::MG_Backend::DirectGLES {
return glslCode; return glslCode;
} }
String RequestMultiviewExtension(String glslCode, GLenum shaderType, Int numViews, Bool driverHasMultiview2) {
const Bool declaresViews = shaderType == GL_VERTEX_SHADER && numViews > 0;
if (!declaresViews && glslCode.find("gl_ViewID_OVR") == String::npos) return glslCode;
const String directive = std::format("#extension {} : require\n",
driverHasMultiview2 ? "GL_OVR_multiview2" : "GL_OVR_multiview");
// The directive goes right after #version; num_views is a declaration, so it goes after
// the LAST directive, where ESSL lets non-preprocessor tokens start.
const SizeT versionPos = glslCode.find("#version");
const SizeT versionEnd = versionPos == String::npos ? String::npos : glslCode.find('\n', versionPos);
glslCode.insert(versionEnd == String::npos ? 0 : versionEnd + 1, directive);
if (!declaresViews) return glslCode;
SizeT insertAt = 0;
for (SizeT lineStart = 0; lineStart < glslCode.size();) {
const SizeT lineEnd = glslCode.find('\n', lineStart);
const SizeT next = lineEnd == String::npos ? glslCode.size() : lineEnd + 1;
const SizeT first = glslCode.find_first_not_of(" \t\r\n", lineStart);
if (first == String::npos) break;
if (first >= next) {
lineStart = next; // a blank line
continue;
}
if (glslCode[first] != '#') break;
insertAt = next;
lineStart = next;
}
if (insertAt > 0 && glslCode[insertAt - 1] != '\n') glslCode.insert(insertAt++, "\n");
glslCode.insert(insertAt, std::format("layout(num_views = {}) in;\n", numViews));
return glslCode;
}
String RequestViewportArrayExtension(String glslCode, Bool needed) { String RequestViewportArrayExtension(String glslCode, Bool needed) {
#ifdef TRACY_ENABLE #ifdef TRACY_ENABLE
ZoneScopedC(TRACY_ZONECOLOR_BACKEND); ZoneScopedC(TRACY_ZONECOLOR_BACKEND);
+9
View File
@@ -229,6 +229,15 @@ namespace MobileGL::MG_Backend::DirectGLES {
// error, so this is never emitted speculatively. A no-op when not needed or already // error, so this is never emitted speculatively. A no-op when not needed or already
// present. // present.
String RequestViewportArrayExtension(String glslCode, Bool needed); String RequestViewportArrayExtension(String glslCode, Bool needed);
// GL_OVR_multiview: adds `#extension GL_OVR_multiview2 : require` (GL_OVR_multiview where
// the driver has only that one) to a stage that names gl_ViewID_OVR or, in the vertex
// stage, declares `numViews`, and `layout(num_views = numViews) in;` to that vertex stage.
// The SPIR-V reaching SPIRV-Cross carries neither (StripMultiviewCapabilityForEssl), so the
// translation it memoizes stays independent of the view count. Frontend shaders that
// declare only GL_OVR_multiview already keep gl_ViewID_OVR out of every output but
// gl_Position, so asking for the smaller extension on such a driver is honest. A no-op
// for every other stage.
String RequestMultiviewExtension(String glslCode, GLenum shaderType, Int numViews, Bool driverHasMultiview2);
// Adds `#extension <extensionName> : require` when a TESSELLATION or GEOMETRY stage's // Adds `#extension <extensionName> : require` when a TESSELLATION or GEOMETRY stage's
// emitted ESSL names gl_PointSize. Desktop GL has that built-in in gl_PerVertex for every // emitted ESSL names gl_PointSize. Desktop GL has that built-in in gl_PerVertex for every
// vertex-processing stage; ESSL does NOT have it in those two at any version - not even // vertex-processing stage; ESSL does NOT have it in those two at any version - not even
@@ -2298,7 +2298,7 @@ namespace MobileGL::MG_Backend::DirectVulkan {
MG_Pipe::MGPSurface surface{}; MG_Pipe::MGPSurface surface{};
surface.Kind = MG_Pipe::kMGPipeSurfaceKindTexture; surface.Kind = MG_Pipe::kMGPipeSurfaceKindTexture;
surface.Res = state.VerbCopyTexDst; surface.Res = state.VerbCopyTexDst;
surface.Level = static_cast<Uint16>(level); surface.Level = static_cast<Uint8>(level);
WireImage source = ResolveWireImage(*read, WireImage source = ResolveWireImage(*read,
aspect & VK_IMAGE_ASPECT_DEPTH_BIT ? read->Depth aspect & VK_IMAGE_ASPECT_DEPTH_BIT ? read->Depth
: aspect & VK_IMAGE_ASPECT_STENCIL_BIT ? read->Stencil : aspect & VK_IMAGE_ASPECT_STENCIL_BIT ? read->Stencil
@@ -21,6 +21,7 @@
// in FixupGsStripCaptureOrder - for the reason CONTRACT-P5B.md §6.5 gives. // in FixupGsStripCaptureOrder - for the reason CONTRACT-P5B.md §6.5 gives.
#include <MG_Remote/Client/SlotCaps.h> #include <MG_Remote/Client/SlotCaps.h>
#include "../Getter/GL_Getter.h" #include "../Getter/GL_Getter.h"
#include "../Framebuffer/GL_Framebuffer.h"
namespace MobileGL::MG_Impl::GLImpl { namespace MobileGL::MG_Impl::GLImpl {
static Bool ValidateProgramForExecution(const SharedPtr<MG_State::GLState::ProgramObject>& currentProgram, static Bool ValidateProgramForExecution(const SharedPtr<MG_State::GLState::ProgramObject>& currentProgram,
@@ -87,7 +88,7 @@ namespace MobileGL::MG_Impl::GLImpl {
return false; return false;
} }
return true; return ValidateMultiviewDraw(*currentProgram, functionName);
} }
// gl_NumSamples has no SPIR-V built-in, so the source pipeline lowers it onto a reserved // gl_NumSamples has no SPIR-V built-in, so the source pipeline lowers it onto a reserved
@@ -2041,6 +2041,8 @@ DECLARE_GL_FUNCTION_STUB_HEAD(void, GetPixelTransformParameterivEXT, GLenum targ
DECLARE_GL_FUNCTION_STUB_HEAD(void, GetPixelTransformParameterfvEXT, GLenum target, GLenum pname, GLfloat* params) DECLARE_GL_FUNCTION_STUB_END_NO_RETURN(void, GetPixelTransformParameterfvEXT, target, pname, params) DECLARE_GL_FUNCTION_STUB_HEAD(void, GetPixelTransformParameterfvEXT, GLenum target, GLenum pname, GLfloat* params) DECLARE_GL_FUNCTION_STUB_END_NO_RETURN(void, GetPixelTransformParameterfvEXT, target, pname, params)
DECLARE_GL_FUNCTION_STUB_HEAD(void, PointParameterfEXT, GLenum pname, GLfloat param) DECLARE_GL_FUNCTION_STUB_END_NO_RETURN(void, PointParameterfEXT, pname, param) DECLARE_GL_FUNCTION_STUB_HEAD(void, PointParameterfEXT, GLenum pname, GLfloat param) DECLARE_GL_FUNCTION_STUB_END_NO_RETURN(void, PointParameterfEXT, pname, param)
DECLARE_GL_FUNCTION_STUB_HEAD(void, PointParameterfvEXT, GLenum pname, const GLfloat* params) DECLARE_GL_FUNCTION_STUB_END_NO_RETURN(void, PointParameterfvEXT, pname, params) DECLARE_GL_FUNCTION_STUB_HEAD(void, PointParameterfvEXT, GLenum pname, const GLfloat* params) DECLARE_GL_FUNCTION_STUB_END_NO_RETURN(void, PointParameterfvEXT, pname, params)
DECLARE_GL_FUNCTION_HEAD(void, FramebufferTextureMultiviewOVR, GLenum target, GLenum attachment, GLuint texture, GLint level, GLint baseViewIndex, GLsizei numViews) DECLARE_GL_FUNCTION_END_NO_RETURN(void, FramebufferTextureMultiviewOVR, target, attachment, texture, level, baseViewIndex, numViews)
DECLARE_GL_FUNCTION_HEAD(void, NamedFramebufferTextureMultiviewOVR, GLuint framebuffer, GLenum attachment, GLuint texture, GLint level, GLint baseViewIndex, GLsizei numViews) DECLARE_GL_FUNCTION_END_NO_RETURN(void, NamedFramebufferTextureMultiviewOVR, framebuffer, attachment, texture, level, baseViewIndex, numViews)
DECLARE_GL_FUNCTION_HEAD(void, GetFragmentShadingRatesEXT, GLsizei samples, GLsizei maxCount, GLsizei* count, GLenum* shadingRates) DECLARE_GL_FUNCTION_END_NO_RETURN(void, GetFragmentShadingRatesEXT, samples, maxCount, count, shadingRates) DECLARE_GL_FUNCTION_HEAD(void, GetFragmentShadingRatesEXT, GLsizei samples, GLsizei maxCount, GLsizei* count, GLenum* shadingRates) DECLARE_GL_FUNCTION_END_NO_RETURN(void, GetFragmentShadingRatesEXT, samples, maxCount, count, shadingRates)
DECLARE_GL_FUNCTION_HEAD(void, ShadingRateEXT, GLenum rate) DECLARE_GL_FUNCTION_END_NO_RETURN(void, ShadingRateEXT, rate) DECLARE_GL_FUNCTION_HEAD(void, ShadingRateEXT, GLenum rate) DECLARE_GL_FUNCTION_END_NO_RETURN(void, ShadingRateEXT, rate)
DECLARE_GL_FUNCTION_HEAD(void, ShadingRateCombinerOpsEXT, GLenum combinerOp0, GLenum combinerOp1) DECLARE_GL_FUNCTION_END_NO_RETURN(void, ShadingRateCombinerOpsEXT, combinerOp0, combinerOp1) DECLARE_GL_FUNCTION_HEAD(void, ShadingRateCombinerOpsEXT, GLenum combinerOp0, GLenum combinerOp1) DECLARE_GL_FUNCTION_END_NO_RETURN(void, ShadingRateCombinerOpsEXT, combinerOp0, combinerOp1)
@@ -2694,7 +2696,6 @@ DECLARE_GL_FUNCTION_STUB_HEAD(void, VideoCaptureStreamParameterivNV, GLuint vide
DECLARE_GL_FUNCTION_STUB_HEAD(void, VideoCaptureStreamParameterfvNV, GLuint video_capture_slot, GLuint stream, GLenum pname, const GLfloat* params) DECLARE_GL_FUNCTION_STUB_END_NO_RETURN(void, VideoCaptureStreamParameterfvNV, video_capture_slot, stream, pname, params) DECLARE_GL_FUNCTION_STUB_HEAD(void, VideoCaptureStreamParameterfvNV, GLuint video_capture_slot, GLuint stream, GLenum pname, const GLfloat* params) DECLARE_GL_FUNCTION_STUB_END_NO_RETURN(void, VideoCaptureStreamParameterfvNV, video_capture_slot, stream, pname, params)
DECLARE_GL_FUNCTION_STUB_HEAD(void, VideoCaptureStreamParameterdvNV, GLuint video_capture_slot, GLuint stream, GLenum pname, const GLdouble* params) DECLARE_GL_FUNCTION_STUB_END_NO_RETURN(void, VideoCaptureStreamParameterdvNV, video_capture_slot, stream, pname, params) DECLARE_GL_FUNCTION_STUB_HEAD(void, VideoCaptureStreamParameterdvNV, GLuint video_capture_slot, GLuint stream, GLenum pname, const GLdouble* params) DECLARE_GL_FUNCTION_STUB_END_NO_RETURN(void, VideoCaptureStreamParameterdvNV, video_capture_slot, stream, pname, params)
DECLARE_GL_FUNCTION_STUB_HEAD(void, ViewportSwizzleNV, GLuint index, GLenum swizzlex, GLenum swizzley, GLenum swizzlez, GLenum swizzlew) DECLARE_GL_FUNCTION_STUB_END_NO_RETURN(void, ViewportSwizzleNV, index, swizzlex, swizzley, swizzlez, swizzlew) DECLARE_GL_FUNCTION_STUB_HEAD(void, ViewportSwizzleNV, GLuint index, GLenum swizzlex, GLenum swizzley, GLenum swizzlez, GLenum swizzlew) DECLARE_GL_FUNCTION_STUB_END_NO_RETURN(void, ViewportSwizzleNV, index, swizzlex, swizzley, swizzlez, swizzlew)
DECLARE_GL_FUNCTION_STUB_HEAD(void, FramebufferTextureMultiviewOVR, GLenum target, GLenum attachment, GLuint texture, GLint level, GLint baseViewIndex, GLsizei numViews) DECLARE_GL_FUNCTION_STUB_END_NO_RETURN(void, FramebufferTextureMultiviewOVR, target, attachment, texture, level, baseViewIndex, numViews)
DECLARE_GL_FUNCTION_STUB_HEAD(void, HintPGI, GLenum target, GLint mode) DECLARE_GL_FUNCTION_STUB_END_NO_RETURN(void, HintPGI, target, mode) DECLARE_GL_FUNCTION_STUB_HEAD(void, HintPGI, GLenum target, GLint mode) DECLARE_GL_FUNCTION_STUB_END_NO_RETURN(void, HintPGI, target, mode)
DECLARE_GL_FUNCTION_STUB_HEAD(void, DetailTexFuncSGIS, GLenum target, GLsizei n, const GLfloat* points) DECLARE_GL_FUNCTION_STUB_END_NO_RETURN(void, DetailTexFuncSGIS, target, n, points) DECLARE_GL_FUNCTION_STUB_HEAD(void, DetailTexFuncSGIS, GLenum target, GLsizei n, const GLfloat* points) DECLARE_GL_FUNCTION_STUB_END_NO_RETURN(void, DetailTexFuncSGIS, target, n, points)
DECLARE_GL_FUNCTION_STUB_HEAD(void, GetDetailTexFuncSGIS, GLenum target, GLfloat* points) DECLARE_GL_FUNCTION_STUB_END_NO_RETURN(void, GetDetailTexFuncSGIS, target, points) DECLARE_GL_FUNCTION_STUB_HEAD(void, GetDetailTexFuncSGIS, GLenum target, GLfloat* points) DECLARE_GL_FUNCTION_STUB_END_NO_RETURN(void, GetDetailTexFuncSGIS, target, points)
@@ -111,6 +111,7 @@ namespace MobileGL::MG_Impl::GLImpl {
// property no single attachment's state explains. // property no single attachment's state explains.
GLenum IncompleteFramebufferStatus(const MG_State::GLState::FramebufferObject& framebufferObject) { GLenum IncompleteFramebufferStatus(const MG_State::GLState::FramebufferObject& framebufferObject) {
if (framebufferObject.HasLayerTargetMismatch()) return GL_FRAMEBUFFER_INCOMPLETE_LAYER_TARGETS; if (framebufferObject.HasLayerTargetMismatch()) return GL_FRAMEBUFFER_INCOMPLETE_LAYER_TARGETS;
if (framebufferObject.HasViewTargetMismatch()) return GL_FRAMEBUFFER_INCOMPLETE_VIEW_TARGETS_OVR;
return HasDefinedAttachment(framebufferObject) ? GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT return HasDefinedAttachment(framebufferObject) ? GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT
: GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT; : GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT;
} }
@@ -363,6 +364,9 @@ namespace MobileGL::MG_Impl::GLImpl {
Bool TryAnswerAttachmentFormatQuery(const MG_State::GLState::FramebufferAttachmentObject* attachmentObject, Bool TryAnswerAttachmentFormatQuery(const MG_State::GLState::FramebufferAttachmentObject* attachmentObject,
FramebufferAttachmentType attachmentType, Bool depthStencilAlias, FramebufferAttachmentType attachmentType, Bool depthStencilAlias,
GLenum pname, GLint* params, const char* caller) { GLenum pname, GLint* params, const char* caller) {
// The two GL_OVR_multiview pnames take the same fallback out of both query switches.
if (FramebufferImpl::TryAnswerMultiviewAttachmentQuery(attachmentObject, pname, params, caller))
return true;
switch (pname) { switch (pname) {
case GL_FRAMEBUFFER_ATTACHMENT_RED_SIZE: case GL_FRAMEBUFFER_ATTACHMENT_RED_SIZE:
case GL_FRAMEBUFFER_ATTACHMENT_GREEN_SIZE: case GL_FRAMEBUFFER_ATTACHMENT_GREEN_SIZE:
@@ -489,72 +493,8 @@ namespace MobileGL::MG_Impl::GLImpl {
} }
} }
// GL 4.6 core 9.2.8 conditions that depend only on the framebuffer and the attachment using FramebufferImpl::ValidateFramebufferTextureAttachmentPoint;
// point. Shared, because glFramebufferTexture / 1D / 2D / 3D / TextureLayer are aliases of using FramebufferImpl::ValidateFramebufferTextureLevel;
// one another in that section and a CTS case that walks the family must not get five
// different answers - which is exactly what happened when these lived in one helper that
// only two of the five went through.
Bool ValidateFramebufferTextureAttachmentPoint(
const char* functionName, const SharedPtr<MG_State::GLState::FramebufferObject>& framebufferObject,
FramebufferAttachmentType attachmentType) {
// "An INVALID_OPERATION error is generated if COLOR_ATTACHMENTm is used with m greater
// than or equal to MAX_COLOR_ATTACHMENTS."
if (!FramebufferImpl::ValidateColorAttachmentInRange(attachmentType, functionName)) return false;
// "An INVALID_OPERATION error is generated if zero is bound to target." MobileGL keeps
// a real FramebufferObject for framebuffer 0, so a null test can never see this - the
// object is always there, and framebuffer 0 has to be recognized by identity instead,
// the same comparison DrawBuffers_State makes. Without this an attach onto the default
// framebuffer silently REPLACED its color attachment, permanently desynchronizing it
// from what the swapchain keeps publishing.
const auto& defaultFramebufferInfo = FramebufferImpl::pDefaultFramebufferInfo;
if (!framebufferObject ||
(defaultFramebufferInfo && framebufferObject == defaultFramebufferInfo->defaultFBO)) {
MG_State::pGLContext->RecordError(
ErrorCode::InvalidOperation,
MakeUnique<GenericErrorInfo>(
"MG_Impl/GLImpl", functionName,
"No framebuffer object is bound to the target; the default framebuffer's attachments "
"cannot be named."));
return false;
}
return true;
}
// The other half of 9.2.8: "level must be greater than or equal to zero", and for a
// texture with immutable storage it "must be smaller than the number of levels the texture
// has". Split from the attachment-point half because the caller only has a texture object
// once the detach (texture == 0) case is behind it.
Bool ValidateFramebufferTextureLevel(const char* functionName,
const SharedPtr<MG_State::GLState::ITextureObject>& textureObject,
GLint level) {
if (level < 0) {
MG_State::pGLContext->RecordError(ErrorCode::InvalidValue,
MakeUnique<GenericErrorInfo>("MG_Impl/GLImpl", functionName,
"Texture level must be non-negative."));
return false;
}
if (!textureObject || !textureObject->IsImmutable()) {
// A mutable texture has no level bound here: a level it has not specified yet is
// not an error, it just leaves the framebuffer incomplete.
return true;
}
// GetAddressableLevelCount(), NOT GetImmutableLevels(): for a VIEW the latter is
// deliberately the ORIGINAL texture's count (GL 4.6 core 8.18 defines
// TEXTURE_IMMUTABLE_LEVELS on a view that way), which is far too large a bound - a
// two-level view onto a ten-level texture would accept level 5 and attach an image
// nothing can draw into.
const Uint levelBound = textureObject->GetAddressableLevelCount();
if (static_cast<Uint>(level) >= levelBound) {
MG_State::pGLContext->RecordError(
ErrorCode::InvalidValue,
MakeUnique<GenericErrorInfo>(
"MG_Impl/GLImpl", functionName,
std::format("Texture level {} is beyond the {} level(s) this texture has.", level,
levelBound)));
return false;
}
return true;
}
void AttachFramebufferTextureWithUploadTarget(const char* functionName, GLenum target, GLenum attachment, void AttachFramebufferTextureWithUploadTarget(const char* functionName, GLenum target, GLenum attachment,
GLuint texture, GLint level, GLuint texture, GLint level,
@@ -2650,6 +2590,8 @@ namespace MobileGL::MG_Impl::GLImpl {
? FramebufferImpl::pDefaultFramebufferInfo->defaultFBO ? FramebufferImpl::pDefaultFramebufferInfo->defaultFBO
: GetNamedFramebufferObject_State(drawFramebuffer, "BlitNamedFramebuffer_State"); : GetNamedFramebufferObject_State(drawFramebuffer, "BlitNamedFramebuffer_State");
if (!readObject || !drawObject) return; if (!readObject || !drawObject) return;
if (!FramebufferImpl::ValidateReadFramebufferIsSingleView(readObject.get(), "BlitNamedFramebuffer_State"))
return;
BlitNamedFramebuffer_Backend(readObject, drawObject, srcX0, srcY0, srcX1, srcY1, dstX0, dstY0, dstX1, dstY1, BlitNamedFramebuffer_Backend(readObject, drawObject, srcX0, srcY0, srcX1, srcY1, dstX0, dstY0, dstX1, dstY1,
mask, filter); mask, filter);
@@ -2910,6 +2852,8 @@ namespace MobileGL::MG_Impl::GLImpl {
MakeUnique<GenericErrorInfo>("MG_Impl/GLImpl", "ReadPixels_State", "Framebuffer is incomplete")); MakeUnique<GenericErrorInfo>("MG_Impl/GLImpl", "ReadPixels_State", "Framebuffer is incomplete"));
return false; return false;
} }
if (!FramebufferImpl::ValidateReadFramebufferIsSingleView(framebufferObject.get(), "ReadPixels_State"))
return false;
// Check for required buffers // Check for required buffers
if (textureInputFormat == TextureInputFormat::StencilIndex) { if (textureInputFormat == TextureInputFormat::StencilIndex) {
@@ -3364,6 +3308,7 @@ namespace MobileGL::MG_Impl::GLImpl {
void BlitFramebuffer(GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1, GLint dstX0, GLint dstY0, GLint dstX1, void BlitFramebuffer(GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1, GLint dstX0, GLint dstY0, GLint dstX1,
GLint dstY1, GLbitfield mask, GLenum filter) { GLint dstY1, GLbitfield mask, GLenum filter) {
if (!ValidateBlitMaskAndFilter(__func__, mask, filter)) return; if (!ValidateBlitMaskAndFilter(__func__, mask, filter)) return;
if (!FramebufferImpl::ValidateBoundReadFramebufferIsSingleView(__func__)) return;
BlitFramebuffer_Backend(srcX0, srcY0, srcX1, srcY1, dstX0, dstY0, dstX1, dstY1, mask, filter); BlitFramebuffer_Backend(srcX0, srcY0, srcX1, srcY1, dstX0, dstY0, dstX1, dstY1, mask, filter);
} }
@@ -11,6 +11,10 @@
#include <Includes.h> #include <Includes.h>
#include <MG_State/GLState/Core.h> #include <MG_State/GLState/Core.h>
namespace MobileGL::MG_State::GLState {
class ProgramObject;
} // namespace MobileGL::MG_State::GLState
namespace MobileGL::MG_Impl::GLImpl { namespace MobileGL::MG_Impl::GLImpl {
/* @INSERTION_POINT:FUNCTION_DECLARATION@ */ /* @INSERTION_POINT:FUNCTION_DECLARATION@ */
void ReadPixels(GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, void* pixels); void ReadPixels(GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, void* pixels);
@@ -55,6 +59,25 @@ namespace MobileGL::MG_Impl::GLImpl {
void NamedFramebufferTexture3D(GLuint framebuffer, GLenum attachment, GLenum textarget, GLuint texture, GLint level, void NamedFramebufferTexture3D(GLuint framebuffer, GLenum attachment, GLenum textarget, GLuint texture, GLint level,
GLint zoffset); GLint zoffset);
void NamedFramebufferTextureLayer(GLuint framebuffer, GLenum attachment, GLuint texture, GLint level, GLint layer); void NamedFramebufferTextureLayer(GLuint framebuffer, GLenum attachment, GLuint texture, GLint level, GLint layer);
// GL_OVR_multiview (GL_FramebufferMultiview.cpp).
void FramebufferTextureMultiviewOVR(GLenum target, GLenum attachment, GLuint texture, GLint level,
GLint baseViewIndex, GLsizei numViews);
void NamedFramebufferTextureMultiviewOVR(GLuint framebuffer, GLenum attachment, GLuint texture, GLint level,
GLint baseViewIndex, GLsizei numViews);
void FramebufferTextureMultiviewOVR_State(GLenum target, GLenum attachment, GLuint texture, GLint level,
GLint baseViewIndex, GLsizei numViews);
void NamedFramebufferTextureMultiviewOVR_State(GLuint framebuffer, GLenum attachment, GLuint texture, GLint level,
GLint baseViewIndex, GLsizei numViews);
// GL_MAX_VIEWS_OVR as the active backend reports it; zero without a backend or without multiview,
// which is exactly when GL_OVR_multiview is not advertised.
Int GetMaxViews_State();
Bool IsMultiviewSupported_State();
// The draw-time rules of GL_OVR_multiview for `program` against the bound draw framebuffer.
// Records INVALID_OPERATION and returns false when the draw must be dropped.
Bool ValidateMultiviewDraw(const MG_State::GLState::ProgramObject& program, const char* functionName);
// The framebuffer object a DSA entry point names, or null with INVALID_OPERATION recorded.
SharedPtr<MG_State::GLState::FramebufferObject> GetNamedFramebufferObject_State(GLuint framebuffer,
const char* caller);
void NamedFramebufferDrawBuffer(GLuint framebuffer, GLenum buf); void NamedFramebufferDrawBuffer(GLuint framebuffer, GLenum buf);
void NamedFramebufferDrawBuffers(GLuint framebuffer, GLsizei n, const GLenum* bufs); void NamedFramebufferDrawBuffers(GLuint framebuffer, GLsizei n, const GLenum* bufs);
void NamedFramebufferReadBuffer(GLuint framebuffer, GLenum src); void NamedFramebufferReadBuffer(GLuint framebuffer, GLenum src);
@@ -0,0 +1,223 @@
// MobileGL - MobileGL/MG_Impl/GLImpl/Framebuffer/GL_FramebufferMultiview.cpp
// Copyright (c) 2025-2026 MobileGL-Dev
// Licensed under the GNU Lesser General Public License v3.0:
// https://www.gnu.org/licenses/gpl-3.0.txt
// https://www.gnu.org/licenses/lgpl-3.0.txt
// SPDX-License-Identifier: LGPL-3.0-only
// End of Source File Header
// GL_OVR_multiview: the two attaching entry points, the attachment queries and the draw-time rules.
// A multiview attachment is a FramebufferAttachmentObject of a 2D array texture whose layer is the
// base view index and whose view count is non-zero; the rest of the framebuffer code reads it
// through FramebufferObject::GetViewCount() and HasViewTargetMismatch().
#include "GL_Framebuffer.h"
#include "Validators.h"
#include <MG_Backend/BackendObjects.h>
#include <MG_Impl/GLImpl/Texture/Validators.h>
#include <MG_Impl/Pipe/FramebufferEmit.h>
#include <MG_State/GLState/ErrorState/Error.h>
#include <MG_State/GLState/ProgramState/ProgramObject.h>
#include <MG_Util/Converters/GLToMG/FramebufferEnumConverter.h>
namespace MobileGL::MG_Impl::GLImpl {
namespace {
void RecordMultiviewError(ErrorCode code, const char* functionName, String detail) {
MG_State::pGLContext->RecordError(
code, MakeUnique<GenericErrorInfo>("MG_Impl/GLImpl", functionName, Move(detail)));
}
const MG_Backend::DynamicBackendParameters& ActiveBackendLimits() {
static const MG_Backend::DynamicBackendParameters kNoBackend{};
return MG_Backend::pActiveBackendObject ? MG_Backend::pActiveBackendObject->GetDynamicParameters()
: kNoBackend;
}
// The checks of the spec that do not depend on the framebuffer object, in its order:
// FramebufferTextureLayer's own errors other than the layer ones, then numViews against
// MAX_VIEWS_OVR, then the texture-dependent ones. Returns the texture to attach, or null
// with `ok` telling a detach (texture 0) apart from a refusal.
SharedPtr<MG_State::GLState::ITextureObject> ValidateMultiviewTexture(const char* functionName, GLuint texture,
GLint level, GLint baseViewIndex,
GLsizei numViews, Bool& ok) {
ok = false;
const Int maxViews = GetMaxViews_State();
if (numViews < 1 || numViews > maxViews) {
RecordMultiviewError(
ErrorCode::InvalidValue, functionName,
std::format("numViews {} is outside [1, GL_MAX_VIEWS_OVR = {}].", numViews, maxViews));
return nullptr;
}
if (texture == 0) {
ok = true;
return nullptr;
}
const auto& textureObject = MG_State::pGLContext->GetTextureObject(texture);
if (!textureObject) {
RecordMultiviewError(ErrorCode::InvalidOperation, functionName,
std::format("Texture object {} is not valid.", texture));
return nullptr;
}
if (textureObject->GetTarget() != TextureTarget::Texture2DArray) {
RecordMultiviewError(ErrorCode::InvalidOperation, functionName,
"A multiview attachment must be a two-dimensional array texture.");
return nullptr;
}
if (!FramebufferImpl::ValidateFramebufferTextureLevel(functionName, textureObject, level)) return nullptr;
if (baseViewIndex < 0) {
RecordMultiviewError(ErrorCode::InvalidValue, functionName, "baseViewIndex must be non-negative.");
return nullptr;
}
const Int maxLayers = ActiveBackendLimits().MaxArrayTextureLayers;
if (static_cast<Int64>(baseViewIndex) + numViews > maxLayers) {
RecordMultiviewError(ErrorCode::InvalidValue, functionName,
std::format("baseViewIndex {} + numViews {} exceeds GL_MAX_ARRAY_TEXTURE_LAYERS "
"({}).",
baseViewIndex, numViews, maxLayers));
return nullptr;
}
ok = true;
return textureObject;
}
// Shared tail of both entry points once the framebuffer object is known. Returns whether
// the framebuffer changed.
Bool AttachMultiview(const char* functionName,
const SharedPtr<MG_State::GLState::FramebufferObject>& framebufferObject,
GLenum attachment, GLuint texture, GLint level, GLint baseViewIndex, GLsizei numViews) {
if (!IsMultiviewSupported_State()) {
RecordMultiviewError(ErrorCode::InvalidOperation, functionName,
"GL_OVR_multiview is not supported by the active backend.");
return false;
}
const Bool depthStencil = attachment == GL_DEPTH_STENCIL_ATTACHMENT;
const FramebufferAttachmentType attachmentType =
depthStencil ? FramebufferAttachmentType::Depth
: MG_Util::ConvertGLEnumToFramebufferAttachmentType(attachment);
if (!FramebufferImpl::ValidateFramebufferAttachmentType(attachmentType)) return false;
if (!FramebufferImpl::ValidateFramebufferTextureAttachmentPoint(functionName, framebufferObject,
attachmentType)) {
return false;
}
Bool ok = false;
const auto textureObject =
ValidateMultiviewTexture(functionName, texture, level, baseViewIndex, numViews, ok);
if (!ok) return false;
const FramebufferAttachmentType stencil = FramebufferAttachmentType::Stencil;
if (!textureObject) {
framebufferObject->Detach(attachmentType);
if (depthStencil) framebufferObject->Detach(stencil);
return true;
}
const auto attach = [&](FramebufferAttachmentType type) {
framebufferObject->AttachTexture(type, textureObject, TextureUploadTarget::Texture2DArray, level,
baseViewIndex, /*layered=*/false, numViews);
};
attach(attachmentType);
if (depthStencil) attach(stencil);
return true;
}
} // namespace
Int GetMaxViews_State() {
return std::max<Int>(ActiveBackendLimits().MaxViews, 0);
}
Bool IsMultiviewSupported_State() {
return MG_Backend::pActiveBackendObject != nullptr && GetMaxViews_State() > 0;
}
void FramebufferTextureMultiviewOVR_State(GLenum target, GLenum attachment, GLuint texture, GLint level,
GLint baseViewIndex, GLsizei numViews) {
if (target == GL_FRAMEBUFFER) target = GL_DRAW_FRAMEBUFFER;
const FramebufferTarget framebufferTarget = MG_Util::ConvertGLEnumToFramebufferTarget(target);
if (!FramebufferImpl::ValidateFramebufferTarget(framebufferTarget)) return;
if (!TextureImpl::ValidateTextureName(texture, true)) return;
const auto& framebufferObject =
MG_State::pGLContext->GetFramebufferBindingSlot(framebufferTarget).GetBoundObject();
AttachMultiview(__func__, framebufferObject, attachment, texture, level, baseViewIndex, numViews);
}
void NamedFramebufferTextureMultiviewOVR_State(GLuint framebuffer, GLenum attachment, GLuint texture, GLint level,
GLint baseViewIndex, GLsizei numViews) {
const auto framebufferObject = GetNamedFramebufferObject_State(framebuffer, __func__);
if (!framebufferObject) return;
if (AttachMultiview(__func__, framebufferObject, attachment, texture, level, baseViewIndex, numViews)) {
// A DSA mutator has no validate point, so the record goes out now (see
// PipePublishFramebufferByName in GL_Framebuffer.cpp).
MG_Pipe::MGPipeFramebufferEmitterInstance().EmitFramebufferByName(*framebufferObject);
}
}
Bool ValidateMultiviewDraw(const MG_State::GLState::ProgramObject& program, const char* functionName) {
// Without backend multiview no framebuffer can be multiview, so a single-view program
// needs no framebuffer walk on every draw.
if (program.GetMultiviewViewCount() == 1 && !IsMultiviewSupported_State()) return true;
const auto& drawFramebuffer =
MG_State::pGLContext->GetFramebufferBindingSlot(FramebufferTarget::Draw).GetBoundObject();
const Int framebufferViews = drawFramebuffer ? drawFramebuffer->GetViewCount() : 1;
const Int programViews = program.GetMultiviewViewCount();
// GL_OVR_multiview 11.1.3.11 / 16.X: the program's num_views (1 without the qualifier)
// must be the draw framebuffer's view count.
if (framebufferViews != programViews) {
RecordMultiviewError(ErrorCode::InvalidOperation, functionName,
std::format("The program renders {} view(s) but the draw framebuffer has {}.",
programViews, framebufferViews));
return false;
}
if (!drawFramebuffer || !drawFramebuffer->IsMultiview()) return true;
// A multiview draw framebuffer takes no geometry or tessellation stage and no active,
// unpaused transform feedback.
if (program.HasLinkedShaderStage(ShaderStage::Geometry) ||
program.HasLinkedShaderStage(ShaderStage::TessControl) ||
program.HasLinkedShaderStage(ShaderStage::TessEval)) {
RecordMultiviewError(ErrorCode::InvalidOperation, functionName,
"A multiview draw cannot run a geometry or tessellation stage.");
return false;
}
if (MG_State::pGLContext->IsTransformFeedbackActive() && !MG_State::pGLContext->IsTransformFeedbackPaused()) {
RecordMultiviewError(ErrorCode::InvalidOperation, functionName,
"A multiview draw cannot capture transform feedback.");
return false;
}
return true;
}
namespace FramebufferImpl {
Bool TryAnswerMultiviewAttachmentQuery(const MG_State::GLState::FramebufferAttachmentObject* attachmentObject,
GLenum pname, GLint* params, const char* caller) {
if (pname != GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_NUM_VIEWS_OVR &&
pname != GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_BASE_VIEW_INDEX_OVR) {
return false;
}
if (!IsMultiviewSupported_State()) return false;
const Bool nothingAttached =
attachmentObject == nullptr || attachmentObject->IsEmpty() || !attachmentObject->IsValid();
if (!nothingAttached && !attachmentObject->IsTexture()) {
RecordMultiviewError(ErrorCode::InvalidEnum, caller,
std::format("pname {:#x} is only defined for a texture attachment.", pname));
return true;
}
// Zero for a texture attachment that is not multiview, as the spec answers for one
// that is not a two-dimensional array texture; FRAMEBUFFER_ATTACHMENT_TEXTURE_LAYER
// already reads the base view index.
const Bool multiview = !nothingAttached && attachmentObject->IsMultiview();
if (pname == GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_NUM_VIEWS_OVR) {
*params = multiview ? static_cast<GLint>(attachmentObject->GetNumViews()) : 0;
} else {
*params = multiview ? static_cast<GLint>(attachmentObject->GetTextureLayer()) : 0;
}
return true;
}
} // namespace FramebufferImpl
void FramebufferTextureMultiviewOVR(GLenum target, GLenum attachment, GLuint texture, GLint level,
GLint baseViewIndex, GLsizei numViews) {
FramebufferTextureMultiviewOVR_State(target, attachment, texture, level, baseViewIndex, numViews);
}
void NamedFramebufferTextureMultiviewOVR(GLuint framebuffer, GLenum attachment, GLuint texture, GLint level,
GLint baseViewIndex, GLsizei numViews) {
NamedFramebufferTextureMultiviewOVR_State(framebuffer, attachment, texture, level, baseViewIndex, numViews);
}
} // namespace MobileGL::MG_Impl::GLImpl
@@ -7,6 +7,7 @@
// End of Source File Header // End of Source File Header
#include "Validators.h" #include "Validators.h"
#include "GL_Framebuffer.h"
#include <MG_Backend/BackendObjects.h> #include <MG_Backend/BackendObjects.h>
#include <MG_State/GLState/Core.h> #include <MG_State/GLState/Core.h>
#include <MG_State/GLState/ErrorState/Error.h> #include <MG_State/GLState/ErrorState/Error.h>
@@ -178,6 +179,7 @@ namespace MobileGL::MG_Impl::GLImpl::FramebufferImpl {
"Read framebuffer is not framebuffer complete.")); "Read framebuffer is not framebuffer complete."));
return false; return false;
} }
if (!ValidateReadFramebufferIsSingleView(framebufferObject.get(), caller)) return false;
const FramebufferAttachmentType readBuffer = framebufferObject->GetReadBuffer(); const FramebufferAttachmentType readBuffer = framebufferObject->GetReadBuffer();
if (readBuffer == FramebufferAttachmentType::None || !framebufferObject->GetAttachment(readBuffer).IsValid()) { if (readBuffer == FramebufferAttachmentType::None || !framebufferObject->GetAttachment(readBuffer).IsValid()) {
@@ -210,4 +212,87 @@ namespace MobileGL::MG_Impl::GLImpl::FramebufferImpl {
return true; return true;
} }
Bool ValidateReadFramebufferIsSingleView(const MG_State::GLState::FramebufferObject* framebufferObject,
const char* caller) {
// GL_OVR_multiview 9.3 / 18.2 / 18.3: reading, copying or blitting out of a read
// framebuffer with more than one view is INVALID_FRAMEBUFFER_OPERATION.
if (!framebufferObject || framebufferObject->GetViewCount() <= 1) return true;
MG_State::pGLContext->RecordError(
ErrorCode::InvalidFramebufferOperation,
MakeUnique<GenericErrorInfo>("MG_Impl/GLImpl/FramebufferImpl", caller,
"The read framebuffer has more than one view (GL_OVR_multiview)."));
return false;
}
Bool ValidateBoundReadFramebufferIsSingleView(const char* caller) {
const auto& framebufferObject =
MG_State::pGLContext->GetFramebufferBindingSlot(FramebufferTarget::Read).GetBoundObject();
return ValidateReadFramebufferIsSingleView(framebufferObject.get(), caller);
}
// GL 4.6 core 9.2.8 conditions that depend only on the framebuffer and the attachment
// point. Shared, because glFramebufferTexture / 1D / 2D / 3D / TextureLayer are aliases of
// one another in that section and a CTS case that walks the family must not get five
// different answers - which is exactly what happened when these lived in one helper that
// only two of the five went through.
Bool ValidateFramebufferTextureAttachmentPoint(
const char* functionName, const SharedPtr<MG_State::GLState::FramebufferObject>& framebufferObject,
FramebufferAttachmentType attachmentType) {
// "An INVALID_OPERATION error is generated if COLOR_ATTACHMENTm is used with m greater
// than or equal to MAX_COLOR_ATTACHMENTS."
if (!FramebufferImpl::ValidateColorAttachmentInRange(attachmentType, functionName)) return false;
// "An INVALID_OPERATION error is generated if zero is bound to target." MobileGL keeps
// a real FramebufferObject for framebuffer 0, so a null test can never see this - the
// object is always there, and framebuffer 0 has to be recognized by identity instead,
// the same comparison DrawBuffers_State makes. Without this an attach onto the default
// framebuffer silently REPLACED its color attachment, permanently desynchronizing it
// from what the swapchain keeps publishing.
const auto& defaultFramebufferInfo = FramebufferImpl::pDefaultFramebufferInfo;
if (!framebufferObject || (defaultFramebufferInfo && framebufferObject == defaultFramebufferInfo->defaultFBO)) {
MG_State::pGLContext->RecordError(
ErrorCode::InvalidOperation,
MakeUnique<GenericErrorInfo>(
"MG_Impl/GLImpl", functionName,
"No framebuffer object is bound to the target; the default framebuffer's attachments "
"cannot be named."));
return false;
}
return true;
}
// The other half of 9.2.8: "level must be greater than or equal to zero", and for a
// texture with immutable storage it "must be smaller than the number of levels the texture
// has". Split from the attachment-point half because the caller only has a texture object
// once the detach (texture == 0) case is behind it.
Bool ValidateFramebufferTextureLevel(const char* functionName,
const SharedPtr<MG_State::GLState::ITextureObject>& textureObject,
GLint level) {
if (level < 0) {
MG_State::pGLContext->RecordError(
ErrorCode::InvalidValue,
MakeUnique<GenericErrorInfo>("MG_Impl/GLImpl", functionName, "Texture level must be non-negative."));
return false;
}
if (!textureObject || !textureObject->IsImmutable()) {
// A mutable texture has no level bound here: a level it has not specified yet is
// not an error, it just leaves the framebuffer incomplete.
return true;
}
// GetAddressableLevelCount(), NOT GetImmutableLevels(): for a VIEW the latter is
// deliberately the ORIGINAL texture's count (GL 4.6 core 8.18 defines
// TEXTURE_IMMUTABLE_LEVELS on a view that way), which is far too large a bound - a
// two-level view onto a ten-level texture would accept level 5 and attach an image
// nothing can draw into.
const Uint levelBound = textureObject->GetAddressableLevelCount();
if (static_cast<Uint>(level) >= levelBound) {
MG_State::pGLContext->RecordError(
ErrorCode::InvalidValue,
MakeUnique<GenericErrorInfo>(
"MG_Impl/GLImpl", functionName,
std::format("Texture level {} is beyond the {} level(s) this texture has.", level, levelBound)));
return false;
}
return true;
}
} // namespace MobileGL::MG_Impl::GLImpl::FramebufferImpl } // namespace MobileGL::MG_Impl::GLImpl::FramebufferImpl
@@ -30,4 +30,24 @@ namespace MobileGL::MG_Impl::GLImpl::FramebufferImpl {
// DEFAULT framebuffer does not answer INVALID_OPERATION. Testing the framebuffer kind first // DEFAULT framebuffer does not answer INVALID_OPERATION. Testing the framebuffer kind first
// would turn GL_FRAMEBUFFER_DEFAULT_WIDTH on framebuffer zero into the wrong error. // would turn GL_FRAMEBUFFER_DEFAULT_WIDTH on framebuffer zero into the wrong error.
Bool ValidateFramebufferParameterPname(GLenum pname, Bool isDefaultFramebuffer, Bool forSetter, const char* caller); Bool ValidateFramebufferParameterPname(GLenum pname, Bool isDefaultFramebuffer, Bool forSetter, const char* caller);
// GL 4.6 core 9.2.8 conditions on the framebuffer and the attachment point that every
// texture-attaching entry point shares: a color attachment beyond GL_MAX_COLOR_ATTACHMENTS, or
// the default framebuffer bound to the target, is INVALID_OPERATION.
Bool ValidateFramebufferTextureAttachmentPoint(
const char* functionName, const SharedPtr<MG_State::GLState::FramebufferObject>& framebufferObject,
FramebufferAttachmentType attachmentType);
// The level half of 9.2.8: negative, or past an immutable texture's levels, is INVALID_VALUE.
Bool ValidateFramebufferTextureLevel(const char* functionName,
const SharedPtr<MG_State::GLState::ITextureObject>& textureObject,
GLint level);
// GL_OVR_multiview: a read framebuffer with more than one view cannot be read, copied or blitted
// from (INVALID_FRAMEBUFFER_OPERATION). A null framebuffer passes; its caller reports that.
Bool ValidateReadFramebufferIsSingleView(const MG_State::GLState::FramebufferObject* framebufferObject,
const char* caller);
Bool ValidateBoundReadFramebufferIsSingleView(const char* caller);
// GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_NUM_VIEWS_OVR / _BASE_VIEW_INDEX_OVR. False when pname is
// neither or GL_OVR_multiview is not supported, so the caller's INVALID_ENUM stands; true when
// the query was answered or refused here. Defined in GL_FramebufferMultiview.cpp.
Bool TryAnswerMultiviewAttachmentQuery(const MG_State::GLState::FramebufferAttachmentObject* attachmentObject,
GLenum pname, GLint* params, const char* caller);
} // namespace MobileGL::MG_Impl::GLImpl::FramebufferImpl } // namespace MobileGL::MG_Impl::GLImpl::FramebufferImpl
+12 -1
View File
@@ -50,6 +50,9 @@ namespace MobileGL::MG_Impl::GLImpl {
// a free function named BlendEquation, which would hide the ::MobileGL::BlendEquation enum // a free function named BlendEquation, which would hide the ::MobileGL::BlendEquation enum
// this file's blend-state queries name unqualified. // this file's blend-state queries name unqualified.
GLboolean IsEnabledi(GLenum target, GLuint index); GLboolean IsEnabledi(GLenum target, GLuint index);
// GL_Framebuffer.h, declared here for the same reason.
Int GetMaxViews_State();
Bool IsMultiviewSupported_State();
namespace { namespace {
enum class IndexedBufferQueryKind { enum class IndexedBufferQueryKind {
@@ -1631,6 +1634,14 @@ namespace MobileGL::MG_Impl::GLImpl {
} }
} }
// GL_MAX_VIEWS_OVR, answered only where GL_OVR_multiview is advertised; anywhere else it is an
// unknown pname like any other extension's.
static Bool TryGetMultiviewInteger(GLenum pname, GLint* params) {
if (pname != GL_MAX_VIEWS_OVR || !IsMultiviewSupported_State()) return false;
*params = GetMaxViews_State();
return true;
}
// GL_EXT_fragment_shading_rate's state and limits (tables 23.9 / 23.53 of the extension). // GL_EXT_fragment_shading_rate's state and limits (tables 23.9 / 23.53 of the extension).
// Returns false for any other pname. The tokens belong to the extension, so a context whose // Returns false for any other pname. The tokens belong to the extension, so a context whose
// backend cannot back it answers them like any unknown pname, and the attachment limits the // backend cannot back it answers them like any unknown pname, and the attachment limits the
@@ -1762,7 +1773,7 @@ namespace MobileGL::MG_Impl::GLImpl {
return; return;
} }
if (TryGetFragmentShadingRateInteger(pname, params)) return; if (TryGetFragmentShadingRateInteger(pname, params) || TryGetMultiviewInteger(pname, params)) return;
switch (pname) { switch (pname) {
case GL_ACTIVE_TEXTURE: case GL_ACTIVE_TEXTURE:
+1 -1
View File
@@ -1547,7 +1547,7 @@ namespace MobileGL::MG_Impl {
GETPROC(glGetIntegerui64i_vNV, name); GETPROC(glGetIntegerui64i_vNV, name);
GETPROC(glViewportSwizzleNV, name); GETPROC(glViewportSwizzleNV, name);
GETPROC(glFramebufferTextureMultiviewOVR, name); GETPROC(glFramebufferTextureMultiviewOVR, name);
// GETPROC(glNamedFramebufferTextureMultiviewOVR, name); GETPROC(glNamedFramebufferTextureMultiviewOVR, name);
MGLOG_D("GetProcAddress(%s) = nullptr!", name); MGLOG_D("GetProcAddress(%s) = nullptr!", name);
return nullptr; return nullptr;
+4 -1
View File
@@ -109,7 +109,8 @@ namespace MobileGL::MG_Pipe {
surface.Kind = kMGPipeSurfaceKindTexture; surface.Kind = kMGPipeSurfaceKindTexture;
surface.InternalFormat = static_cast<Uint32>(texture->GetFormat()); surface.InternalFormat = static_cast<Uint32>(texture->GetFormat());
surface.Layered = attachment.IsLayered() ? 1 : 0; surface.Layered = attachment.IsLayered() ? 1 : 0;
surface.Level = static_cast<Uint16>(std::max<Int>(attachment.GetTextureLevel(), 0)); surface.Level = static_cast<Uint8>(std::clamp<Int>(attachment.GetTextureLevel(), 0, 0xFF));
surface.NumViews = static_cast<Uint8>(std::clamp<Int>(attachment.GetNumViews(), 0, 0xFF));
surface.Layer = static_cast<Uint32>(std::max<Int>(attachment.GetTextureLayer(), 0)); surface.Layer = static_cast<Uint32>(std::max<Int>(attachment.GetTextureLayer(), 0));
surface.UploadTarget = static_cast<Uint16>(MGPipeResolveAttachmentUploadTarget(attachment)); surface.UploadTarget = static_cast<Uint16>(MGPipeResolveAttachmentUploadTarget(attachment));
// ID-12 DV-5: the field that WAS Pad0, and the size did not move. The four // ID-12 DV-5: the field that WAS Pad0, and the size did not move. The four
@@ -126,6 +127,7 @@ namespace MobileGL::MG_Pipe {
surface.InternalFormat = static_cast<Uint32>(renderbuffer->GetInternalFormat()); surface.InternalFormat = static_cast<Uint32>(renderbuffer->GetInternalFormat());
surface.Layered = 0; surface.Layered = 0;
surface.Level = 0; surface.Level = 0;
surface.NumViews = 0;
surface.Layer = 0; surface.Layer = 0;
return surface; return surface;
} }
@@ -179,6 +181,7 @@ namespace MobileGL::MG_Pipe {
dst.Kind = src.Kind; dst.Kind = src.Kind;
dst.Layered = src.Layered; dst.Layered = src.Layered;
dst.Level = src.Level; dst.Level = src.Level;
dst.NumViews = src.NumViews;
dst.Layer = src.Layer; dst.Layer = src.Layer;
dst.UploadTarget = src.UploadTarget; dst.UploadTarget = src.UploadTarget;
// MANDATORY, not optional: TextureTarget is a PipeFields.def row now, so a // MANDATORY, not optional: TextureTarget is a PipeFields.def row now, so a
+5 -1
View File
@@ -677,7 +677,11 @@ namespace MobileGL::MG_Pipe {
Uint32 InternalFormat; Uint32 InternalFormat;
Uint8 Kind; // kMGPipeSurfaceKind{None,Texture,Renderbuffer}, above Uint8 Kind; // kMGPipeSurfaceKind{None,Texture,Renderbuffer}, above
Uint8 Layered; Uint8 Layered;
Uint16 Level; // A mip level fits a byte: GL_MAX_TEXTURE_SIZE would have to pass 2^255 for it not to.
Uint8 Level;
// GL_OVR_multiview: non-zero on a multiview attachment, which renders views
// [Layer, Layer + NumViews) of a 2D array texture. Layered is then 0.
Uint8 NumViews;
Uint32 Layer; Uint32 Layer;
Uint16 UploadTarget; // static_cast<Uint16>(MobileGL::TextureUploadTarget) Uint16 UploadTarget; // static_cast<Uint16>(MobileGL::TextureUploadTarget)
// static_cast<Uint16>(MobileGL::TextureTarget), or kMGPipeSurfaceNoTextureTarget on a // static_cast<Uint16>(MobileGL::TextureTarget), or kMGPipeSurfaceNoTextureTarget on a
+2 -2
View File
@@ -100,7 +100,7 @@
// Pad<n>, so the rename without this row is a pipe-gates failure, and the row without the // Pad<n>, so the rename without this row is a pipe-gates failure, and the row without the
// rename is one too. A meaning-carrying byte cannot enter this record silently. // rename is one too. A meaning-carrying byte cannot enter this record silently.
#define MGP_FIELDS_MGPSurface(F) \ #define MGP_FIELDS_MGPSurface(F) \
F(Res) F(InternalFormat) F(Kind) F(Layered) F(Level) F(Layer) F(UploadTarget) F(TextureTarget) F(Res) F(InternalFormat) F(Kind) F(Layered) F(Level) F(NumViews) F(Layer) F(UploadTarget) F(TextureTarget)
// P4a, D-C2: Pad0 became Uint8 Target, and gen_pipe.py's PADDING_MEMBER_RE only excludes a // P4a, D-C2: Pad0 became Uint8 Target, and gen_pipe.py's PADDING_MEMBER_RE only excludes a
// member still NAMED Pad<n> - so the rename without this row is a pipe-gates failure, which // member still NAMED Pad<n> - so the rename without this row is a pipe-gates failure, which
@@ -399,7 +399,7 @@
F(FragmentShadingRateAttachmentWithDefaultFramebuffer) F(FragmentShadingRateMasks) \ F(FragmentShadingRateAttachmentWithDefaultFramebuffer) F(FragmentShadingRateMasks) \
F(MinFragmentShadingRateAttachmentTexelWidth) F(MinFragmentShadingRateAttachmentTexelHeight) \ F(MinFragmentShadingRateAttachmentTexelWidth) F(MinFragmentShadingRateAttachmentTexelHeight) \
F(MaxFragmentShadingRateAttachmentTexelWidth) F(MaxFragmentShadingRateAttachmentTexelHeight) \ F(MaxFragmentShadingRateAttachmentTexelWidth) F(MaxFragmentShadingRateAttachmentTexelHeight) \
F(MaxFragmentShadingRateAttachmentTexelAspectRatio) F(MaxFragmentShadingRateAttachmentLayers) F(MaxFragmentShadingRateAttachmentTexelAspectRatio) F(MaxFragmentShadingRateAttachmentLayers) F(MaxViews)
#define MGP_FIELDS_MGHostSpan(F) \ #define MGP_FIELDS_MGHostSpan(F) \
F(Ptr) F(Seg) F(Size) F(Offset) F(Ptr) F(Seg) F(Size) F(Offset)
@@ -142,6 +142,7 @@ inline constexpr WireLayoutMember kMGPipeWireLayoutMembers[] = {
{"MGPSurface.Kind", offsetof(MGPSurface, Kind), sizeof(((MGPSurface*)nullptr)->Kind)}, {"MGPSurface.Kind", offsetof(MGPSurface, Kind), sizeof(((MGPSurface*)nullptr)->Kind)},
{"MGPSurface.Layered", offsetof(MGPSurface, Layered), sizeof(((MGPSurface*)nullptr)->Layered)}, {"MGPSurface.Layered", offsetof(MGPSurface, Layered), sizeof(((MGPSurface*)nullptr)->Layered)},
{"MGPSurface.Level", offsetof(MGPSurface, Level), sizeof(((MGPSurface*)nullptr)->Level)}, {"MGPSurface.Level", offsetof(MGPSurface, Level), sizeof(((MGPSurface*)nullptr)->Level)},
{"MGPSurface.NumViews", offsetof(MGPSurface, NumViews), sizeof(((MGPSurface*)nullptr)->NumViews)},
{"MGPSurface.Layer", offsetof(MGPSurface, Layer), sizeof(((MGPSurface*)nullptr)->Layer)}, {"MGPSurface.Layer", offsetof(MGPSurface, Layer), sizeof(((MGPSurface*)nullptr)->Layer)},
{"MGPSurface.UploadTarget", offsetof(MGPSurface, UploadTarget), sizeof(((MGPSurface*)nullptr)->UploadTarget)}, {"MGPSurface.UploadTarget", offsetof(MGPSurface, UploadTarget), sizeof(((MGPSurface*)nullptr)->UploadTarget)},
{"MGPSurface.TextureTarget", offsetof(MGPSurface, TextureTarget), sizeof(((MGPSurface*)nullptr)->TextureTarget)}, {"MGPSurface.TextureTarget", offsetof(MGPSurface, TextureTarget), sizeof(((MGPSurface*)nullptr)->TextureTarget)},
@@ -685,6 +686,7 @@ inline constexpr WireLayoutMember kMGPipeWireLayoutMembers[] = {
{"DynamicBackendParameters.MaxFragmentShadingRateAttachmentTexelHeight", offsetof(DynamicBackendParameters, MaxFragmentShadingRateAttachmentTexelHeight), sizeof(((DynamicBackendParameters*)nullptr)->MaxFragmentShadingRateAttachmentTexelHeight)}, {"DynamicBackendParameters.MaxFragmentShadingRateAttachmentTexelHeight", offsetof(DynamicBackendParameters, MaxFragmentShadingRateAttachmentTexelHeight), sizeof(((DynamicBackendParameters*)nullptr)->MaxFragmentShadingRateAttachmentTexelHeight)},
{"DynamicBackendParameters.MaxFragmentShadingRateAttachmentTexelAspectRatio", offsetof(DynamicBackendParameters, MaxFragmentShadingRateAttachmentTexelAspectRatio), sizeof(((DynamicBackendParameters*)nullptr)->MaxFragmentShadingRateAttachmentTexelAspectRatio)}, {"DynamicBackendParameters.MaxFragmentShadingRateAttachmentTexelAspectRatio", offsetof(DynamicBackendParameters, MaxFragmentShadingRateAttachmentTexelAspectRatio), sizeof(((DynamicBackendParameters*)nullptr)->MaxFragmentShadingRateAttachmentTexelAspectRatio)},
{"DynamicBackendParameters.MaxFragmentShadingRateAttachmentLayers", offsetof(DynamicBackendParameters, MaxFragmentShadingRateAttachmentLayers), sizeof(((DynamicBackendParameters*)nullptr)->MaxFragmentShadingRateAttachmentLayers)}, {"DynamicBackendParameters.MaxFragmentShadingRateAttachmentLayers", offsetof(DynamicBackendParameters, MaxFragmentShadingRateAttachmentLayers), sizeof(((DynamicBackendParameters*)nullptr)->MaxFragmentShadingRateAttachmentLayers)},
{"DynamicBackendParameters.MaxViews", offsetof(DynamicBackendParameters, MaxViews), sizeof(((DynamicBackendParameters*)nullptr)->MaxViews)},
{"MGHostSpan", 0, sizeof(MGHostSpan)}, {"MGHostSpan", 0, sizeof(MGHostSpan)},
{"MGHostSpan.Ptr", offsetof(MGHostSpan, Ptr), sizeof(((MGHostSpan*)nullptr)->Ptr)}, {"MGHostSpan.Ptr", offsetof(MGHostSpan, Ptr), sizeof(((MGHostSpan*)nullptr)->Ptr)},
{"MGHostSpan.Seg", offsetof(MGHostSpan, Seg), sizeof(((MGHostSpan*)nullptr)->Seg)}, {"MGHostSpan.Seg", offsetof(MGHostSpan, Seg), sizeof(((MGHostSpan*)nullptr)->Seg)},
@@ -45,9 +45,9 @@ namespace MobileGL::MG_State::GLState {
// FramebufferAttachmentObject // FramebufferAttachmentObject
FramebufferAttachmentObject::FramebufferAttachmentObject( FramebufferAttachmentObject::FramebufferAttachmentObject(
const SharedPtr<MG_State::GLState::ITextureObject>& texture, TextureUploadTarget textureUploadTarget, Int level, const SharedPtr<MG_State::GLState::ITextureObject>& texture, TextureUploadTarget textureUploadTarget, Int level,
Int layer, Bool layered) Int layer, Bool layered, Int numViews)
: m_texture(texture), m_textureUploadTarget(textureUploadTarget), m_textureLevel(level), m_textureLayer(layer), : m_texture(texture), m_textureUploadTarget(textureUploadTarget), m_textureLevel(level), m_textureLayer(layer),
m_layered(layered) {} m_layered(layered), m_numViews(numViews) {}
FramebufferAttachmentObject::FramebufferAttachmentObject(const SharedPtr<RenderbufferObject>& renderbuffer) FramebufferAttachmentObject::FramebufferAttachmentObject(const SharedPtr<RenderbufferObject>& renderbuffer)
: m_renderbuffer(renderbuffer) {} : m_renderbuffer(renderbuffer) {}
FramebufferAttachmentObject::FramebufferAttachmentObject(Bool IsValid) FramebufferAttachmentObject::FramebufferAttachmentObject(Bool IsValid)
@@ -87,6 +87,10 @@ namespace MobileGL::MG_State::GLState {
return m_layered; return m_layered;
} }
Int FramebufferAttachmentObject::GetNumViews() const {
return m_numViews;
}
TextureUploadTarget FramebufferAttachmentObject::GetTextureUploadTarget() const { TextureUploadTarget FramebufferAttachmentObject::GetTextureUploadTarget() const {
return m_textureUploadTarget; return m_textureUploadTarget;
} }
@@ -115,7 +119,9 @@ namespace MobileGL::MG_State::GLState {
default: default:
break; break;
} }
if (layerCount >= 0 && m_textureLayer >= layerCount) return false; // GL_OVR_multiview 9.4.1: every view's layer, not only the base one.
const Int lastLayer = m_textureLayer + std::max<Int>(m_numViews, 1) - 1;
if (layerCount >= 0 && lastLayer >= layerCount) return false;
} }
return true; return true;
} else if (IsRenderbuffer()) { } else if (IsRenderbuffer()) {
@@ -163,9 +169,10 @@ namespace MobileGL::MG_State::GLState {
} }
void FramebufferObject::AttachTexture(FramebufferAttachmentType type, const SharedPtr<ITextureObject>& texture, void FramebufferObject::AttachTexture(FramebufferAttachmentType type, const SharedPtr<ITextureObject>& texture,
TextureUploadTarget textureUploadTarget, int level, int layer, Bool layered) { TextureUploadTarget textureUploadTarget, int level, int layer, Bool layered,
int numViews) {
m_attachmentObjects[static_cast<SizeT>(type)] = m_attachmentObjects[static_cast<SizeT>(type)] =
FramebufferAttachmentObject(texture, textureUploadTarget, level, layer, layered); FramebufferAttachmentObject(texture, textureUploadTarget, level, layer, layered, numViews);
BumpAttachmentVersion(type); BumpAttachmentVersion(type);
} }
@@ -217,7 +224,39 @@ namespace MobileGL::MG_State::GLState {
} }
if (validAttachmentCount == 0) return false; if (validAttachmentCount == 0) return false;
return !HasLayerTargetMismatch(); return !HasLayerTargetMismatch() && !HasViewTargetMismatch();
}
Bool FramebufferObject::HasViewTargetMismatch() const {
Bool seen = false;
Int numViews = 0;
for (const auto& attachment : m_attachmentObjects) {
if (!attachment.IsValid() || attachment.IsEmpty()) continue;
const Int views = attachment.IsTexture() ? attachment.GetNumViews() : 0;
if (seen && views != numViews) return true;
seen = true;
numViews = views;
}
return false;
}
Bool FramebufferObject::IsMultiview() const {
for (const auto& attachment : m_attachmentObjects) {
if (attachment.IsValid() && attachment.IsTexture() && attachment.IsMultiview()) return true;
}
return false;
}
Int FramebufferObject::GetViewCount() const {
Int numViews = 0;
for (const auto& attachment : m_attachmentObjects) {
if (!attachment.IsValid() || attachment.IsEmpty()) continue;
const Int views = attachment.IsTexture() ? attachment.GetNumViews() : 0;
if (views == 0) return 1;
if (numViews != 0 && views != numViews) return 1;
numViews = views;
}
return std::max<Int>(numViews, 1);
} }
Bool FramebufferObject::HasLayerTargetMismatch() const { Bool FramebufferObject::HasLayerTargetMismatch() const {
@@ -75,7 +75,7 @@ namespace MobileGL {
public: public:
explicit FramebufferAttachmentObject(const SharedPtr<MG_State::GLState::ITextureObject>& texture, explicit FramebufferAttachmentObject(const SharedPtr<MG_State::GLState::ITextureObject>& texture,
TextureUploadTarget textureUploadTarget, Int level = 0, Int layer = 0, TextureUploadTarget textureUploadTarget, Int level = 0, Int layer = 0,
Bool layered = false); Bool layered = false, Int numViews = 0);
explicit FramebufferAttachmentObject(const SharedPtr<RenderbufferObject>& renderbuffer); explicit FramebufferAttachmentObject(const SharedPtr<RenderbufferObject>& renderbuffer);
explicit FramebufferAttachmentObject(Bool IsValid = true); explicit FramebufferAttachmentObject(Bool IsValid = true);
@@ -87,6 +87,10 @@ namespace MobileGL {
Int GetTextureLevel() const; Int GetTextureLevel() const;
Int GetTextureLayer() const; Int GetTextureLayer() const;
Bool IsLayered() const; Bool IsLayered() const;
// GL_OVR_multiview: the attachment renders views [layer, layer + numViews) of a 2D
// array texture, one per view. Zero for every attachment that is not multiview.
Int GetNumViews() const;
Bool IsMultiview() const { return m_numViews > 0; }
TextureUploadTarget GetTextureUploadTarget() const; TextureUploadTarget GetTextureUploadTarget() const;
Bool IsComplete() const; Bool IsComplete() const;
IntVec3 GetSize() const; IntVec3 GetSize() const;
@@ -99,6 +103,7 @@ namespace MobileGL {
Int m_textureLevel = 0; Int m_textureLevel = 0;
Int m_textureLayer = 0; Int m_textureLayer = 0;
Bool m_layered = false; Bool m_layered = false;
Int m_numViews = 0;
Bool m_isValid = true; Bool m_isValid = true;
}; };
@@ -122,7 +127,7 @@ namespace MobileGL {
void AttachTexture(FramebufferAttachmentType type, const SharedPtr<ITextureObject>& texture, void AttachTexture(FramebufferAttachmentType type, const SharedPtr<ITextureObject>& texture,
TextureUploadTarget textureUploadTarget = TextureUploadTarget::Unknown, int level = 0, TextureUploadTarget textureUploadTarget = TextureUploadTarget::Unknown, int level = 0,
int layer = 0, Bool layered = false); int layer = 0, Bool layered = false, int numViews = 0);
void AttachRenderbuffer(FramebufferAttachmentType type, const SharedPtr<RenderbufferObject>& renderbuffer); void AttachRenderbuffer(FramebufferAttachmentType type, const SharedPtr<RenderbufferObject>& renderbuffer);
void Detach(FramebufferAttachmentType type); void Detach(FramebufferAttachmentType type);
const FramebufferAttachmentObject& GetAttachment(FramebufferAttachmentType type) const; const FramebufferAttachmentObject& GetAttachment(FramebufferAttachmentType type) const;
@@ -132,6 +137,17 @@ namespace MobileGL {
// layered while another is not, or the layered color attachments come from textures of // layered while another is not, or the layered color attachments come from textures of
// different targets. CheckCompleteness() includes it; this tells the status apart. // different targets. CheckCompleteness() includes it; this tells the status apart.
Bool HasLayerTargetMismatch() const; Bool HasLayerTargetMismatch() const;
// GL_OVR_multiview's FRAMEBUFFER_INCOMPLETE_VIEW_TARGETS_OVR: the populated attachments
// do not all have the same number of views. An attachment that is not multiview does
// not match a multiview one, whatever its view count. CheckCompleteness() includes it.
Bool HasViewTargetMismatch() const;
// The number of views a draw into this framebuffer renders: the multiview attachments'
// common count, or 1 when no attachment is multiview (or the counts disagree, which
// leaves the framebuffer incomplete anyway).
Int GetViewCount() const;
// Whether any populated attachment is a multiview one. A multiview framebuffer with a
// single view still takes the multiview draw rules.
Bool IsMultiview() const;
// aka. `buffer` as in glDrawBuffers/glReadBuffers // aka. `buffer` as in glDrawBuffers/glReadBuffers
void SetDrawBuffer(Uint index, FramebufferAttachmentType buffer); void SetDrawBuffer(Uint index, FramebufferAttachmentType buffer);
const FramebufferAttachmentArray& GetDrawBuffers() const; const FramebufferAttachmentArray& GetDrawBuffers() const;
@@ -383,6 +383,9 @@ namespace MobileGL::MG_State::GLState {
GLenum gsOutputPrimitive = GL_NONE; GLenum gsOutputPrimitive = GL_NONE;
Int gsMaxVertices = 0; Int gsMaxVertices = 0;
Int gsInvocations = 0; Int gsInvocations = 0;
// GL_OVR_multiview: the vertex stage's layout(num_views = N) in;, or 0 without one. The
// backend that emits GLSL needs it back, because SPIR-V cannot say it.
Int vsNumViews = 0;
// The tessellation evaluation stage's layout: GL_QUADS / GL_TRIANGLES / GL_ISOLINES, // The tessellation evaluation stage's layout: GL_QUADS / GL_TRIANGLES / GL_ISOLINES,
// GL_EQUAL / GL_FRACTIONAL_EVEN / GL_FRACTIONAL_ODD, GL_CW / GL_CCW, and point mode. // GL_EQUAL / GL_FRACTIONAL_EVEN / GL_FRACTIONAL_ODD, GL_CW / GL_CCW, and point mode.
GLenum tessGenMode = GL_NONE; GLenum tessGenMode = GL_NONE;
@@ -610,6 +613,7 @@ namespace MobileGL::MG_State::GLState {
v("gsOutputPrimitive", a.gsOutputPrimitive); v("gsOutputPrimitive", a.gsOutputPrimitive);
v("gsMaxVertices", a.gsMaxVertices); v("gsMaxVertices", a.gsMaxVertices);
v("gsInvocations", a.gsInvocations); v("gsInvocations", a.gsInvocations);
v("vsNumViews", a.vsNumViews);
v("tessGenMode", a.tessGenMode); v("tessGenMode", a.tessGenMode);
v("tessGenSpacing", a.tessGenSpacing); v("tessGenSpacing", a.tessGenSpacing);
v("tessGenVertexOrder", a.tessGenVertexOrder); v("tessGenVertexOrder", a.tessGenVertexOrder);
@@ -618,7 +622,7 @@ namespace MobileGL::MG_State::GLState {
v("xfbVaryingNameMaxLength", a.xfbVaryingNameMaxLength); v("xfbVaryingNameMaxLength", a.xfbVaryingNameMaxLength);
v("xfbNeedsScatteredCapture", a.xfbNeedsScatteredCapture); v("xfbNeedsScatteredCapture", a.xfbNeedsScatteredCapture);
v("xfbPackedStride", a.xfbPackedStride); v("xfbPackedStride", a.xfbPackedStride);
} // 57 fields (58 members minus `program`) } // 58 fields (59 members minus `program`)
template <class Self, class V> template <class Self, class V>
requires std::same_as<std::remove_const_t<Self>, SpirvArtifacts> requires std::same_as<std::remove_const_t<Self>, SpirvArtifacts>
@@ -650,7 +654,7 @@ namespace MobileGL::MG_State::GLState {
#define MGL_XFBVARYING_SIZE 128 #define MGL_XFBVARYING_SIZE 128
// P7 OQ-8 added storageBlocks, one more Vector, in the disaggregated build ONLY. The pull // P7 OQ-8 added storageBlocks, one more Vector, in the disaggregated build ONLY. The pull
// number below is the one G1 measures and it has not moved. // number below is the one G1 measures and it has not moved.
#define MGL_LINKARTIFACTS_SIZE 1080 #define MGL_LINKARTIFACTS_SIZE 1088
#define MGL_SPIRVARTIFACTS_SIZE 96 #define MGL_SPIRVARTIFACTS_SIZE 96
#elif defined(_LIBCPP_VERSION) && (SIZE_MAX == UINT64_MAX) && defined(MGL_ARTIFACT_SIZES_LIBCXX_PINNED) #elif defined(_LIBCPP_VERSION) && (SIZE_MAX == UINT64_MAX) && defined(MGL_ARTIFACT_SIZES_LIBCXX_PINNED)
// The integrator pins these from the NDK build (brief C.4); until then this branch is inert. // The integrator pins these from the NDK build (brief C.4); until then this branch is inert.
@@ -67,7 +67,8 @@ namespace MobileGL::MG_State::GLState {
// reader checks FIRST and what the refusal names, and CONTRACT-P7 §5.3 asks for the bump // reader checks FIRST and what the refusal names, and CONTRACT-P7 §5.3 asks for the bump
// explicitly. `wireFingerprint` moves with both, which is expected and is what makes a // explicitly. `wireFingerprint` moves with both, which is expected and is what makes a
// mixed-version pair refuse at the handshake instead of at the first program. // mixed-version pair refuse at the handshake instead of at the first program.
inline constexpr Uint32 kProgramArtifactsCodecVersion = 3; // 4: LinkArtifacts gained `vsNumViews` (GL_OVR_multiview), for the same reason.
inline constexpr Uint32 kProgramArtifactsCodecVersion = 4;
// Derived from the actual VisitFields order/names, container element schemas and scalar // Derived from the actual VisitFields order/names, container element schemas and scalar
// representations. No native container size/offset is included. Also checked in Hello. // representations. No native container size/offset is included. Also checked in Hello.
Uint64 ProgramArtifactsSchemaFingerprint(); Uint64 ProgramArtifactsSchemaFingerprint();
@@ -193,6 +193,25 @@ namespace {
// The offsets themselves survive that lowering (reflection and the SPIR-V generator both // The offsets themselves survive that lowering (reflection and the SPIR-V generator both
// honor layoutOffset), so the check belongs here, over the same model the GL queries answer // honor layoutOffset), so the check belongs here, over the same model the GL queries answer
// from. Returns the info-log line for an illegal layout, empty for a legal one. // from. Returns the info-log line for an illegal layout, empty for a legal one.
// GL_OVR_multiview's layout(num_views = N) in; of the linked vertex stage into
// artifacts.vsNumViews, 0 without one. glslang already refused a non-positive count and two
// units that disagree; the upper bound is GL_MAX_VIEWS_OVR, which glslang does not know, so it
// is held here. False, with the link failed and the TProgram dropped, when the count is over it.
static MobileGL::Bool ResolveVertexNumViews(MobileGL::MG_State::GLState::ProgramObject::LinkArtifacts& artifacts,
const MobileGL::MG_Util::ShaderTranspiler::CompileEnv& env) {
artifacts.vsNumViews = 0;
const glslang::TIntermediate* vs = artifacts.program->getIntermediate(EShLangVertex);
if (vs == nullptr) return true;
artifacts.vsNumViews = std::max(vs->getNumViews(), 0);
if (!env.HasBackend() || artifacts.vsNumViews <= env.params.MaxViews) return true;
artifacts.linkStatus = false;
artifacts.program.reset();
artifacts.infoLog =
std::format("Vertex shader declares num_views = {}, more than the {} GL_MAX_VIEWS_OVR allows.",
artifacts.vsNumViews, env.params.MaxViews);
return false;
}
static MobileGL::String ValidateAtomicCounterLayout(glslang::TProgram& reflection) { static MobileGL::String ValidateAtomicCounterLayout(glslang::TProgram& reflection) {
using MobileGL::Bool; using MobileGL::Bool;
using MobileGL::Int; using MobileGL::Int;
@@ -1040,6 +1059,11 @@ namespace MobileGL::MG_State::GLState {
} }
} }
if (!ResolveVertexNumViews(artifacts, env)) {
DeferLog(std::format("ProgramObject {}: Link failed - {}", in.externalIndex, artifacts.infoLog));
return;
}
// ---- everything below this line up to GenerateSpirv() is the GL query surface ---- // ---- everything below this line up to GenerateSpirv() is the GL query surface ----
// //
// ORDERING NOTE (rewritten 2026-08-10; the constraint it records was RETESTED, not // ORDERING NOTE (rewritten 2026-08-10; the constraint it records was RETESTED, not
@@ -1320,6 +1320,9 @@ namespace MobileGL::MG_State::GLState {
GLenum GetGeometryOutputType() const { return Artifacts().gsOutputPrimitive; } GLenum GetGeometryOutputType() const { return Artifacts().gsOutputPrimitive; }
Int GetGeometryVerticesOut() const { return Artifacts().gsMaxVertices; } Int GetGeometryVerticesOut() const { return Artifacts().gsMaxVertices; }
Int GetGeometryShaderInvocations() const { return Artifacts().gsInvocations; } Int GetGeometryShaderInvocations() const { return Artifacts().gsInvocations; }
// GL_OVR_multiview: how many views a draw with this program renders - its vertex stage's
// num_views, or 1 without the qualifier.
Int GetMultiviewViewCount() const { return std::max<Int>(Artifacts().vsNumViews, 1); }
// GL_TESS_CONTROL_OUTPUT_VERTICES of the linked tessellation control stage, or 0 when // GL_TESS_CONTROL_OUTPUT_VERTICES of the linked tessellation control stage, or 0 when
// the program has no such stage. Never greater than GL_MAX_PATCH_VERTICES: a program // the program has no such stage. Never greater than GL_MAX_PATCH_VERTICES: a program
// that declared more does not link at all (GL 4.6 core 11.2.1.1). // that declared more does not link at all (GL 4.6 core 11.2.1.1).
@@ -88,3 +88,9 @@ gtest_discover_tests(NarrowIntegerEsslTest DISCOVERY_TIMEOUT 30 PROPERTIES LABEL
gtest_discover_tests(EsslShaderPassTest DISCOVERY_TIMEOUT 30 PROPERTIES LABELS unit) gtest_discover_tests(EsslShaderPassTest DISCOVERY_TIMEOUT 30 PROPERTIES LABELS unit)
gtest_discover_tests(BaseInstanceInjectionTest DISCOVERY_TIMEOUT 30 PROPERTIES LABELS unit) gtest_discover_tests(BaseInstanceInjectionTest DISCOVERY_TIMEOUT 30 PROPERTIES LABELS unit)
gtest_discover_tests(ViewportIndexRoutingTest DISCOVERY_TIMEOUT 30 PROPERTIES LABELS unit) gtest_discover_tests(ViewportIndexRoutingTest DISCOVERY_TIMEOUT 30 PROPERTIES LABELS unit)
# GL_OVR_multiview's ESSL: num_views through glslang, the capability strip and the text pass.
add_executable(MultiviewEsslTest MultiviewEsslTest.cpp)
target_include_directories(MultiviewEsslTest PRIVATE ${MGL_ROOT}/include ${MGL_ROOT}/MobileGL)
target_link_libraries(MultiviewEsslTest PRIVATE MobileGLTestMain glslang-default-resource-limits ${LINK_LIBRARIES})
gtest_discover_tests(MultiviewEsslTest DISCOVERY_TIMEOUT 30 PROPERTIES LABELS unit)
@@ -0,0 +1,197 @@
// MobileGL - MobileGL/MG_Test/Backend/DirectGLES/MultiviewEsslTest.cpp
// Copyright (c) 2026 MobileGL-Dev
// Licensed under the GNU Lesser General Public License v3.0:
// https://www.gnu.org/licenses/gpl-3.0.txt
// https://www.gnu.org/licenses/lgpl-3.0.txt
// SPDX-License-Identifier: LGPL-3.0-only
// End of Source File Header
//
// GL_OVR_multiview through the steps DirectGLES takes: glslang keeps the vertex stage's num_views,
// the SPIR-V loses its MultiView capability so SPIRV-Cross accepts both stages without a view
// count, and the text pass puts the directive and num_views back. The result has to be ESSL 3.20
// that a compiler accepts, in both stages.
#include <gtest/gtest.h>
#include <MG_Backend/DirectGLES/DirectGLES.h>
#include <MG_Backend/DirectGLES/Utils.h>
#include <MG_Util/ShaderTranspiler/ShaderCompiler.h>
#include <MG_Util/ShaderTranspiler/SpvcSession.h>
#include <MG_Util/ShaderTranspiler/Types.h>
#include "Init.h"
#include <glslang/MachineIndependent/localintermediate.h>
#include <glslang/Public/ResourceLimits.h>
#include <glslang/Public/ShaderLang.h>
using namespace MobileGL;
using MobileGL::MG_Backend::DirectGLES::PrgramImpl::RequestMultiviewExtension;
using MobileGL::MG_Util::ShaderTranspiler::SessionUsageBit;
using MobileGL::MG_Util::ShaderTranspiler::ShaderCompiler;
using MobileGL::MG_Util::ShaderTranspiler::SpvcSession;
namespace {
constexpr const char* kVertex = R"(#version 330 core
#extension GL_OVR_multiview2 : require
layout(num_views = 2) in;
layout(location = 0) in vec2 pos;
out float tint;
void main() {
tint = float(gl_ViewID_OVR);
gl_Position = vec4(pos.x + float(gl_ViewID_OVR), pos.y, 0.0, 1.0);
}
)";
constexpr const char* kFragment = R"(#version 330 core
#extension GL_OVR_multiview2 : require
in float tint;
out vec4 color;
void main() { color = vec4(tint, float(gl_ViewID_OVR), 0.0, 1.0); }
)";
struct LinkedModules {
Int numViews = -1;
Vector<Vector<Uint32>> modules;
};
LinkedModules CompileAndLink(const char* vertex, const char* fragment) {
using namespace MG_Util::ShaderTranspiler;
LinkedModules out;
Vector<SharedPtr<glslang::TShader>> shaders;
for (const auto& [stage, source] :
Vector<Pair<GLenum, const char*>>{{GL_VERTEX_SHADER, vertex}, {GL_FRAGMENT_SHADER, fragment}}) {
ShaderAttrib attrib{.shaderType = stage, .sourceStr = source};
auto shader = ShaderCompiler::CompileShader(attrib);
EXPECT_TRUE(shader) << (shader ? String{} : shader.error().log);
if (!shader) return out;
shaders.push_back(shader.value());
}
ProgramAttrib programAttrib{.shaders = shaders};
auto program = ShaderCompiler::LinkProgram(programAttrib);
EXPECT_TRUE(program) << (program ? String{} : program.error().log);
if (!program) return out;
out.numViews = program.value()->getIntermediate(EShLangVertex)->getNumViews();
ProgramBinaryAttrib binaryAttrib{.shaderTypes = {GL_VERTEX_SHADER, GL_FRAGMENT_SHADER},
.program = *program.value()};
auto binary = ShaderCompiler::GetSpirvBinaryFromProgram(binaryAttrib);
EXPECT_TRUE(binary) << (binary ? String{} : binary.error().log);
if (!binary || binary->size() != 2) return out;
for (auto module : binary.value()) {
EXPECT_TRUE(ShaderCompiler::SanitizeAndOptimizeBinary(module, module, true, true));
out.modules.push_back(Move(module));
}
return out;
}
String EmitEssl320(const Vector<Uint32>& spirv) {
SpvcSession session(spirv, SessionUsageBit::Transpile);
spvc_compiler_options options;
session.CreateOptions(&options);
spvc_compiler_options_set_uint(options, SPVC_COMPILER_OPTION_GLSL_VERSION, 320);
spvc_compiler_options_set_bool(options, SPVC_COMPILER_OPTION_GLSL_ES, SPVC_TRUE);
spvc_compiler_options_set_bool(options, SPVC_COMPILER_OPTION_GLSL_VULKAN_SEMANTICS, SPVC_FALSE);
session.SetOptions(options);
const char* result = nullptr;
session.Compile(&result);
EXPECT_NE(result, nullptr) << (session.GetLastErrorString() ? session.GetLastErrorString() : "");
return result != nullptr ? String(result) : String{};
}
String CompileErrorAsEssl320(const String& source, EShLanguage stage) {
glslang::TShader shader(stage);
const char* strings[] = {source.c_str()};
shader.setStrings(strings, 1);
if (shader.parse(GetDefaultResources(), 320, EEsProfile, false, false, EShMsgDefault)) return {};
return shader.getInfoLog();
}
Bool DeclaresMultiviewCapability(const Vector<Uint32>& module) {
constexpr Uint32 kOpCapability = 17;
constexpr Uint32 kCapabilityMultiView = 4439;
for (SizeT at = 5; at < module.size();) {
const Uint32 wordCount = module[at] >> 16;
if (wordCount == 0) return false;
if ((module[at] & 0xFFFFu) == kOpCapability && module[at + 1] == kCapabilityMultiView) return true;
at += wordCount;
}
return false;
}
} // namespace
TEST(MultiviewEssl, BothStagesComeOutAsMultiviewEsslACompilerAccepts) {
MobileGL::Initialize();
const LinkedModules linked = CompileAndLink(kVertex, kFragment);
ASSERT_EQ(linked.modules.size(), 2u);
EXPECT_EQ(linked.numViews, 2) << "glslang dropped the vertex stage's num_views";
const struct {
GLenum glStage;
EShLanguage stage;
} stages[] = {{GL_VERTEX_SHADER, EShLangVertex}, {GL_FRAGMENT_SHADER, EShLangFragment}};
for (SizeT i = 0; i < 2; ++i) {
ASSERT_TRUE(DeclaresMultiviewCapability(linked.modules[i]));
Vector<Uint32> stripped;
ASSERT_TRUE(ShaderCompiler::StripMultiviewCapabilityForEssl(linked.modules[i], stripped));
EXPECT_FALSE(DeclaresMultiviewCapability(stripped));
const String emitted = EmitEssl320(stripped);
ASSERT_FALSE(emitted.empty());
EXPECT_NE(emitted.find("gl_ViewID_OVR"), String::npos) << emitted;
EXPECT_EQ(emitted.find("GL_OVR_multiview"), String::npos) << "the emission must not depend on the view count";
const String essl = RequestMultiviewExtension(emitted, stages[i].glStage, linked.numViews, true);
EXPECT_NE(essl.find("#extension GL_OVR_multiview2 : require\n"), String::npos) << essl;
const Bool vertex = stages[i].glStage == GL_VERTEX_SHADER;
EXPECT_EQ(essl.find("layout(num_views = 2) in;") != String::npos, vertex) << essl;
EXPECT_EQ(CompileErrorAsEssl320(essl, stages[i].stage), String{}) << essl;
}
}
TEST(MultiviewEssl, TheDirectiveFollowsTheDriversExtensionAndNumViewsFollowsTheDirectives) {
const String source = "#version 320 es\n"
"#extension GL_EXT_clip_cull_distance : require\n"
"\n"
"precision highp float;\n"
"void main() { gl_Position = vec4(float(gl_ViewID_OVR)); }\n";
const String essl = RequestMultiviewExtension(source, GL_VERTEX_SHADER, 3, false);
EXPECT_EQ(essl, "#version 320 es\n"
"#extension GL_OVR_multiview : require\n"
"#extension GL_EXT_clip_cull_distance : require\n"
"layout(num_views = 3) in;\n"
"\n"
"precision highp float;\n"
"void main() { gl_Position = vec4(float(gl_ViewID_OVR)); }\n");
// Neither the built-in nor a view count: nothing to ask for.
const String plain = "#version 320 es\nvoid main() {}\n";
EXPECT_EQ(RequestMultiviewExtension(plain, GL_VERTEX_SHADER, 0, true), plain);
EXPECT_EQ(RequestMultiviewExtension(plain, GL_FRAGMENT_SHADER, 2, true), plain);
}
TEST(MultiviewEssl, AModuleWithoutMultiviewIsLeftAlone) {
MobileGL::Initialize();
const LinkedModules linked = CompileAndLink("#version 330 core\nvoid main() { gl_Position = vec4(0.0); }\n",
"#version 330 core\nout vec4 c;\nvoid main() { c = vec4(1.0); }\n");
ASSERT_EQ(linked.modules.size(), 2u);
EXPECT_LT(linked.numViews, 0) << "no num_views qualifier was declared";
Vector<Uint32> stripped;
EXPECT_FALSE(ShaderCompiler::StripMultiviewCapabilityForEssl(linked.modules[0], stripped));
EXPECT_TRUE(stripped.empty());
}
TEST(MultiviewEssl, NumViewsIsAVertexStageQualifierAboveZero) {
MobileGL::Initialize();
using namespace MG_Util::ShaderTranspiler;
for (const auto& [stage, source] : Vector<Pair<GLenum, const char*>>{
{GL_VERTEX_SHADER, "#version 330 core\n#extension GL_OVR_multiview : require\n"
"layout(num_views = 0) in;\nvoid main() { gl_Position = vec4(0.0); }\n"},
{GL_FRAGMENT_SHADER, "#version 330 core\n#extension GL_OVR_multiview : require\n"
"layout(num_views = 2) in;\nout vec4 c;\nvoid main() { c = vec4(1.0); }\n"},
{GL_VERTEX_SHADER, "#version 330 core\n#extension GL_OVR_multiview : require\n"
"layout(num_views = 2) in;\nlayout(num_views = 3) in;\n"
"void main() { gl_Position = vec4(0.0); }\n"},
}) {
ShaderAttrib attrib{.shaderType = stage, .sourceStr = source};
EXPECT_FALSE(ShaderCompiler::CompileShader(attrib)) << source;
}
}
@@ -96,6 +96,8 @@ namespace {
// baseInstance word and exposes it through gl_InstanceID. // baseInstance word and exposes it through gl_InstanceID.
bool drawLeaksBaseInstanceWord = false; bool drawLeaksBaseInstanceWord = false;
GLenum errorRaisedByDraw = GL_NO_ERROR; GLenum errorRaisedByDraw = GL_NO_ERROR;
// GL_MAX_VIEWS_OVR, a GL_OVR_multiview pname.
GLint maxViews = 4;
GLenum pendingError = GL_NO_ERROR; GLenum pendingError = GL_NO_ERROR;
std::vector<std::string> extensions; std::vector<std::string> extensions;
@@ -270,6 +272,9 @@ namespace {
case GL_NUM_EXTENSIONS: case GL_NUM_EXTENSIONS:
*data = static_cast<GLint>(g_fake.extensions.size()); *data = static_cast<GLint>(g_fake.extensions.size());
break; break;
case GL_MAX_VIEWS_OVR:
*data = g_fake.maxViews;
break;
default: default:
// Leave the caller's defaults for every other capability query. // Leave the caller's defaults for every other capability query.
break; break;
@@ -1387,6 +1392,89 @@ TEST(CoreSurfaceAdvertisement, ClipControlFollowsTheBackendsRoute) {
MobileGL::E_GL_ARB_clip_control)); MobileGL::E_GL_ARB_clip_control));
} }
// GL_OVR_multiview needs the driver's string and glFramebufferTextureMultiviewOVR, and a
// GL_MAX_VIEWS_OVR of at least the spec minimum; GL_OVR_multiview2 only counts on top of it.
TEST(MultiviewCapabilities, NeedTheExtensionTheEntryPointAndTwoViews) {
auto withEntryPoint = MakeFakeGLESFunctions();
withEntryPoint.glFramebufferTextureMultiviewOVR = [](GLenum, GLenum, GLuint, GLint, GLint, GLsizei) {};
ResetFakeDriver();
g_fake.maxVertexSsboBlocks = 0;
g_fake.extensions.emplace_back("GL_OVR_multiview2");
MobileGL::MG_External::GLESCapabilities onlyTheSecond;
ASSERT_TRUE(MobileGL::MG_Util::BackendLoader::FillInGLESCapabilities(onlyTheSecond, withEntryPoint));
EXPECT_FALSE(onlyTheSecond.SupportsMultiview);
EXPECT_FALSE(onlyTheSecond.SupportsMultiview2);
EXPECT_EQ(onlyTheSecond.MaxViews, 0);
ResetFakeDriver();
g_fake.maxVertexSsboBlocks = 0;
g_fake.extensions = {"GL_OVR_multiview", "GL_OVR_multiview2"};
MobileGL::MG_External::GLESCapabilities noEntryPoint;
ASSERT_TRUE(MobileGL::MG_Util::BackendLoader::FillInGLESCapabilities(noEntryPoint, MakeFakeGLESFunctions()));
EXPECT_FALSE(noEntryPoint.SupportsMultiview);
EXPECT_FALSE(noEntryPoint.SupportsMultiview2);
ResetFakeDriver();
g_fake.maxVertexSsboBlocks = 0;
g_fake.extensions = {"GL_OVR_multiview"};
g_fake.maxViews = 1;
MobileGL::MG_External::GLESCapabilities oneView;
ASSERT_TRUE(MobileGL::MG_Util::BackendLoader::FillInGLESCapabilities(oneView, withEntryPoint));
EXPECT_FALSE(oneView.SupportsMultiview);
EXPECT_EQ(oneView.MaxViews, 0);
ResetFakeDriver();
g_fake.maxVertexSsboBlocks = 0;
g_fake.extensions = {"GL_OVR_multiview"};
MobileGL::MG_External::GLESCapabilities firstOnly;
ASSERT_TRUE(MobileGL::MG_Util::BackendLoader::FillInGLESCapabilities(firstOnly, withEntryPoint));
EXPECT_TRUE(firstOnly.SupportsMultiview);
EXPECT_FALSE(firstOnly.SupportsMultiview2);
EXPECT_EQ(firstOnly.MaxViews, 4);
ResetFakeDriver();
g_fake.maxVertexSsboBlocks = 0;
g_fake.extensions = {"GL_OVR_multiview", "GL_OVR_multiview2"};
MobileGL::MG_External::GLESCapabilities both;
ASSERT_TRUE(MobileGL::MG_Util::BackendLoader::FillInGLESCapabilities(both, withEntryPoint));
EXPECT_TRUE(both.SupportsMultiview);
EXPECT_TRUE(both.SupportsMultiview2);
}
// Each multiview string follows the DirectGLES driver's own; DirectVulkan has no multiview route
// and never advertises either.
TEST(CoreSurfaceAdvertisement, MultiviewFollowsTheDriver) {
const auto contains = [](const MobileGL::Vector<MobileGL::GLExtension>& extensions, MobileGL::GLExtension wanted) {
return std::find(extensions.begin(), extensions.end(), wanted) != extensions.end();
};
namespace DirectGLES = MobileGL::MG_Backend::DirectGLES;
namespace DirectVulkan = MobileGL::MG_Backend::DirectVulkan;
const auto none = DirectGLES::BuildAdvertisedExtensions(false, false, false, false, false, false);
EXPECT_FALSE(contains(none, MobileGL::E_GL_OVR_multiview));
EXPECT_FALSE(contains(none, MobileGL::E_GL_OVR_multiview2));
const auto first =
DirectGLES::BuildAdvertisedExtensions(false, false, false, false, false, false, {.Multiview = true});
EXPECT_TRUE(contains(first, MobileGL::E_GL_OVR_multiview));
EXPECT_FALSE(contains(first, MobileGL::E_GL_OVR_multiview2));
const auto both = DirectGLES::BuildAdvertisedExtensions(false, false, false, false, false, false,
{.Multiview = true, .Multiview2 = true});
EXPECT_TRUE(contains(both, MobileGL::E_GL_OVR_multiview));
EXPECT_TRUE(contains(both, MobileGL::E_GL_OVR_multiview2));
// The second string never stands without the first, whatever the flags say.
const auto secondOnly =
DirectGLES::BuildAdvertisedExtensions(false, false, false, false, false, false, {.Multiview2 = true});
EXPECT_FALSE(contains(secondOnly, MobileGL::E_GL_OVR_multiview2));
const auto vulkan = DirectVulkan::BuildAdvertisedExtensions(false, false, false, false, false,
{.Multiview = true, .Multiview2 = true});
EXPECT_FALSE(contains(vulkan, MobileGL::E_GL_OVR_multiview));
EXPECT_FALSE(contains(vulkan, MobileGL::E_GL_OVR_multiview2));
}
// Minecraft 26.3 checks ARB_draw_indirect before it considers the already-advertised // Minecraft 26.3 checks ARB_draw_indirect before it considers the already-advertised
// ARB_multi_draw_indirect, then separately requires ARB_base_instance before enabling its terrain // ARB_multi_draw_indirect, then separately requires ARB_base_instance before enabling its terrain
// indirect path. Pin both strings and, just as importantly, the non-zero firstInstance gate. // indirect path. Pin both strings and, just as importantly, the non-zero firstInstance gate.
@@ -11,6 +11,7 @@ cmake_minimum_required(VERSION 3.14)
add_executable( add_executable(
FramebufferTest FramebufferTest
FramebufferTest.cpp FramebufferTest.cpp
FramebufferMultiviewTest.cpp
) )
target_include_directories(FramebufferTest PRIVATE target_include_directories(FramebufferTest PRIVATE
@@ -0,0 +1,246 @@
// MobileGL - MobileGL/MG_Test/Framebuffer/FramebufferMultiviewTest.cpp
// Copyright (c) 2025-2026 MobileGL-Dev
// Licensed under the GNU Lesser General Public License v3.0:
// https://www.gnu.org/licenses/gpl-3.0.txt
// https://www.gnu.org/licenses/lgpl-3.0.txt
// SPDX-License-Identifier: LGPL-3.0-only
// End of Source File Header
// GL_OVR_multiview on the frontend: the attach errors, both completeness rules, the attachment
// queries, GL_MAX_VIEWS_OVR and the read-side refusal, against a backend whose GL_MAX_VIEWS_OVR the
// test chooses. None of it reaches a driver.
#include <gtest/gtest.h>
#include "Includes.h"
#include "Init.h"
#include <MG_Backend/BackendObjects.h>
#include <MG_Impl/GLImpl/Framebuffer/GL_Framebuffer.h>
#include <MG_Impl/GLImpl/Getter/GL_Getter.h>
#include <MG_Impl/GLImpl/Texture/GL_Texture.h>
#include <MG_State/GLState/Core.h>
using namespace MobileGL;
namespace {
class MultiviewLimitsBackend final : public MG_Backend::BackendObject {
public:
explicit MultiviewLimitsBackend(Int maxViews) {
m_params.MaxViews = maxViews;
m_params.MaxArrayTextureLayers = 8;
}
void Initialize() override {}
Bool InitCapabilities() override { return true; }
Bool InitWindowSurface() override { return true; }
const RendererInfo& GetRendererInfo() const override {
static RendererInfo info = {};
return info;
}
String GetBackendAPIVersionString() const override { return {}; }
const MG_Backend::GlobalBackendFunctionsTable& GetBackendFunctions() const override {
static MG_Backend::GlobalBackendFunctionsTable table = {};
return table;
}
const MG_Backend::DynamicBackendParameters& GetDynamicParameters() const override { return m_params; }
BackendType GetBackendType() const override { return BackendType::Unknown; }
private:
MG_Backend::DynamicBackendParameters m_params{};
};
class ScopedMultiviewBackend {
public:
explicit ScopedMultiviewBackend(Int maxViews) : m_previous(Move(MG_Backend::pActiveBackendObject)) {
MG_Backend::pActiveBackendObject = MakeUnique<MultiviewLimitsBackend>(maxViews);
}
~ScopedMultiviewBackend() { MG_Backend::pActiveBackendObject = Move(m_previous); }
private:
UniquePtr<MG_Backend::BackendObject> m_previous;
};
GLuint MakeArrayTexture(GLsizei layers) {
GLuint texture = 0;
MG_Impl::GLImpl::CreateTextures(GL_TEXTURE_2D_ARRAY, 1, &texture);
MG_Impl::GLImpl::TextureStorage3D(texture, 1, GL_RGBA8, 4, 4, layers);
return texture;
}
GLint AttachmentParameter(GLuint framebuffer, GLenum attachment, GLenum pname) {
GLint value = -1;
MG_Impl::GLImpl::GetNamedFramebufferAttachmentParameteriv(framebuffer, attachment, pname, &value);
return value;
}
} // namespace
class FramebufferMultiviewTest : public ::testing::Test {
protected:
void SetUp() override {
MobileGL::Initialize();
for (Int drained = 0; drained < 16 && MG_Impl::GLImpl::GetError() != GL_NO_ERROR; ++drained) {}
m_defaultFramebuffer = MG_State::pGLContext->GetFramebufferObject(0);
ASSERT_NE(m_defaultFramebuffer, nullptr);
}
void TearDown() override {
MG_State::pGLContext->GetFramebufferBindingSlot(FramebufferTarget::Read).Bind(m_defaultFramebuffer);
MG_State::pGLContext->GetFramebufferBindingSlot(FramebufferTarget::Draw).Bind(m_defaultFramebuffer);
EXPECT_EQ(MG_Impl::GLImpl::GetError(), GL_NO_ERROR) << "test left an unconsumed GL error behind";
}
static void ExpectSingleGlError(GLenum expected) {
EXPECT_EQ(MG_Impl::GLImpl::GetError(), expected);
EXPECT_EQ(MG_Impl::GLImpl::GetError(), GL_NO_ERROR) << "the call recorded more than one error";
}
SharedPtr<MG_State::GLState::FramebufferObject> m_defaultFramebuffer;
};
TEST_F(FramebufferMultiviewTest, WithoutBackendMultiviewTheEntryPointsAndTokensAreRefused) {
ScopedMultiviewBackend backend(0);
GLuint framebuffer = 0;
MG_Impl::GLImpl::CreateFramebuffers(1, &framebuffer);
const GLuint texture = MakeArrayTexture(2);
MG_Impl::GLImpl::NamedFramebufferTextureMultiviewOVR(framebuffer, GL_COLOR_ATTACHMENT0, texture, 0, 0, 2);
ExpectSingleGlError(GL_INVALID_OPERATION);
EXPECT_FALSE(MG_State::pGLContext->GetFramebufferObject(framebuffer)
->GetAttachment(FramebufferAttachmentType::Color0)
.IsTexture());
GLint maxViews = -1;
MG_Impl::GLImpl::GetIntegerv(GL_MAX_VIEWS_OVR, &maxViews);
ExpectSingleGlError(GL_INVALID_ENUM);
MG_Impl::GLImpl::NamedFramebufferTextureLayer(framebuffer, GL_COLOR_ATTACHMENT0, texture, 0, 0);
EXPECT_EQ(MG_Impl::GLImpl::GetError(), GL_NO_ERROR);
AttachmentParameter(framebuffer, GL_COLOR_ATTACHMENT0, GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_NUM_VIEWS_OVR);
ExpectSingleGlError(GL_INVALID_ENUM);
}
TEST_F(FramebufferMultiviewTest, AttachesViewsOfAnArrayTextureAndAnswersTheQueries) {
ScopedMultiviewBackend backend(4);
GLint maxViews = -1;
MG_Impl::GLImpl::GetIntegerv(GL_MAX_VIEWS_OVR, &maxViews);
EXPECT_EQ(maxViews, 4);
GLuint framebuffer = 0;
MG_Impl::GLImpl::CreateFramebuffers(1, &framebuffer);
const GLuint texture = MakeArrayTexture(4);
MG_Impl::GLImpl::NamedFramebufferTextureMultiviewOVR(framebuffer, GL_COLOR_ATTACHMENT0, texture, 0, 1, 2);
ASSERT_EQ(MG_Impl::GLImpl::GetError(), GL_NO_ERROR);
const auto framebufferObject = MG_State::pGLContext->GetFramebufferObject(framebuffer);
const auto& attachment = framebufferObject->GetAttachment(FramebufferAttachmentType::Color0);
EXPECT_TRUE(attachment.IsMultiview());
EXPECT_EQ(attachment.GetNumViews(), 2);
EXPECT_FALSE(attachment.IsLayered());
EXPECT_EQ(framebufferObject->GetViewCount(), 2);
EXPECT_EQ(AttachmentParameter(framebuffer, GL_COLOR_ATTACHMENT0, GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_NUM_VIEWS_OVR),
2);
EXPECT_EQ(
AttachmentParameter(framebuffer, GL_COLOR_ATTACHMENT0, GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_BASE_VIEW_INDEX_OVR),
1);
EXPECT_EQ(AttachmentParameter(framebuffer, GL_COLOR_ATTACHMENT0, GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LAYER), 1);
EXPECT_EQ(MG_Impl::GLImpl::CheckNamedFramebufferStatus(framebuffer, GL_DRAW_FRAMEBUFFER),
static_cast<GLenum>(GL_FRAMEBUFFER_COMPLETE));
// A plain layer attachment is not multiview, and says so. Layer 0, the one every backend backs.
MG_Impl::GLImpl::NamedFramebufferTextureLayer(framebuffer, GL_COLOR_ATTACHMENT0, texture, 0, 0);
ASSERT_EQ(MG_Impl::GLImpl::GetError(), GL_NO_ERROR);
EXPECT_EQ(AttachmentParameter(framebuffer, GL_COLOR_ATTACHMENT0, GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_NUM_VIEWS_OVR),
0);
EXPECT_EQ(framebufferObject->GetViewCount(), 1);
// Texture 0 detaches.
MG_Impl::GLImpl::NamedFramebufferTextureMultiviewOVR(framebuffer, GL_COLOR_ATTACHMENT0, 0, 0, 0, 2);
EXPECT_EQ(MG_Impl::GLImpl::GetError(), GL_NO_ERROR);
EXPECT_FALSE(framebufferObject->GetAttachment(FramebufferAttachmentType::Color0).IsTexture());
}
TEST_F(FramebufferMultiviewTest, AttachRefusesWhatTheSpecRefuses) {
ScopedMultiviewBackend backend(4);
GLuint framebuffer = 0;
MG_Impl::GLImpl::CreateFramebuffers(1, &framebuffer);
const GLuint arrayTexture = MakeArrayTexture(8);
GLuint texture2D = 0;
MG_Impl::GLImpl::CreateTextures(GL_TEXTURE_2D, 1, &texture2D);
MG_Impl::GLImpl::TextureStorage2D(texture2D, 1, GL_RGBA8, 4, 4);
MG_Impl::GLImpl::NamedFramebufferTextureMultiviewOVR(framebuffer, GL_COLOR_ATTACHMENT0, arrayTexture, 0, 0, 0);
ExpectSingleGlError(GL_INVALID_VALUE);
MG_Impl::GLImpl::NamedFramebufferTextureMultiviewOVR(framebuffer, GL_COLOR_ATTACHMENT0, arrayTexture, 0, 0, 5);
ExpectSingleGlError(GL_INVALID_VALUE);
// The view count is checked even when detaching.
MG_Impl::GLImpl::NamedFramebufferTextureMultiviewOVR(framebuffer, GL_COLOR_ATTACHMENT0, 0, 0, 0, 0);
ExpectSingleGlError(GL_INVALID_VALUE);
MG_Impl::GLImpl::NamedFramebufferTextureMultiviewOVR(framebuffer, GL_COLOR_ATTACHMENT0, texture2D, 0, 0, 2);
ExpectSingleGlError(GL_INVALID_OPERATION);
MG_Impl::GLImpl::NamedFramebufferTextureMultiviewOVR(framebuffer, GL_COLOR_ATTACHMENT0, arrayTexture, 0, -1, 2);
ExpectSingleGlError(GL_INVALID_VALUE);
// GL_MAX_ARRAY_TEXTURE_LAYERS is 8: views 7 and 8 do not both exist.
MG_Impl::GLImpl::NamedFramebufferTextureMultiviewOVR(framebuffer, GL_COLOR_ATTACHMENT0, arrayTexture, 0, 7, 2);
ExpectSingleGlError(GL_INVALID_VALUE);
MG_Impl::GLImpl::NamedFramebufferTextureMultiviewOVR(framebuffer, GL_COLOR_ATTACHMENT0, arrayTexture, 0, 6, 2);
EXPECT_EQ(MG_Impl::GLImpl::GetError(), GL_NO_ERROR);
// The default framebuffer has no attachment points to name.
MG_State::pGLContext->GetFramebufferBindingSlot(FramebufferTarget::Draw).Bind(m_defaultFramebuffer);
MG_Impl::GLImpl::FramebufferTextureMultiviewOVR(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, arrayTexture, 0, 0, 2);
ExpectSingleGlError(GL_INVALID_OPERATION);
}
TEST_F(FramebufferMultiviewTest, CompletenessNeedsEveryViewAndOneViewCount) {
ScopedMultiviewBackend backend(4);
const GLuint fourLayers = MakeArrayTexture(4);
const GLuint otherFourLayers = MakeArrayTexture(4);
GLuint pastTheEnd = 0;
MG_Impl::GLImpl::CreateFramebuffers(1, &pastTheEnd);
MG_Impl::GLImpl::NamedFramebufferTextureMultiviewOVR(pastTheEnd, GL_COLOR_ATTACHMENT0, fourLayers, 0, 3, 2);
EXPECT_EQ(MG_Impl::GLImpl::GetError(), GL_NO_ERROR) << "the layer count is a completeness question";
EXPECT_EQ(MG_Impl::GLImpl::CheckNamedFramebufferStatus(pastTheEnd, GL_DRAW_FRAMEBUFFER),
static_cast<GLenum>(GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT));
GLuint mixed = 0;
MG_Impl::GLImpl::CreateFramebuffers(1, &mixed);
MG_Impl::GLImpl::NamedFramebufferTextureMultiviewOVR(mixed, GL_COLOR_ATTACHMENT0, fourLayers, 0, 0, 2);
MG_Impl::GLImpl::NamedFramebufferTextureLayer(mixed, GL_COLOR_ATTACHMENT1, otherFourLayers, 0, 0);
EXPECT_EQ(MG_Impl::GLImpl::CheckNamedFramebufferStatus(mixed, GL_DRAW_FRAMEBUFFER),
static_cast<GLenum>(GL_FRAMEBUFFER_INCOMPLETE_VIEW_TARGETS_OVR));
GLuint differentCounts = 0;
MG_Impl::GLImpl::CreateFramebuffers(1, &differentCounts);
MG_Impl::GLImpl::NamedFramebufferTextureMultiviewOVR(differentCounts, GL_COLOR_ATTACHMENT0, fourLayers, 0, 0, 2);
MG_Impl::GLImpl::NamedFramebufferTextureMultiviewOVR(differentCounts, GL_COLOR_ATTACHMENT1, otherFourLayers, 0, 0,
3);
EXPECT_EQ(MG_Impl::GLImpl::CheckNamedFramebufferStatus(differentCounts, GL_DRAW_FRAMEBUFFER),
static_cast<GLenum>(GL_FRAMEBUFFER_INCOMPLETE_VIEW_TARGETS_OVR));
// Matching counts with different base views are fine.
GLuint matching = 0;
MG_Impl::GLImpl::CreateFramebuffers(1, &matching);
MG_Impl::GLImpl::NamedFramebufferTextureMultiviewOVR(matching, GL_COLOR_ATTACHMENT0, fourLayers, 0, 0, 2);
MG_Impl::GLImpl::NamedFramebufferTextureMultiviewOVR(matching, GL_COLOR_ATTACHMENT1, otherFourLayers, 0, 2, 2);
EXPECT_EQ(MG_Impl::GLImpl::CheckNamedFramebufferStatus(matching, GL_DRAW_FRAMEBUFFER),
static_cast<GLenum>(GL_FRAMEBUFFER_COMPLETE));
EXPECT_EQ(MG_Impl::GLImpl::GetError(), GL_NO_ERROR);
}
TEST_F(FramebufferMultiviewTest, AReadFramebufferWithSeveralViewsCannotBeRead) {
ScopedMultiviewBackend backend(4);
GLuint framebuffer = 0;
MG_Impl::GLImpl::CreateFramebuffers(1, &framebuffer);
MG_Impl::GLImpl::NamedFramebufferTextureMultiviewOVR(framebuffer, GL_COLOR_ATTACHMENT0, MakeArrayTexture(2), 0, 0,
2);
ASSERT_EQ(MG_Impl::GLImpl::GetError(), GL_NO_ERROR);
MG_State::pGLContext->GetFramebufferBindingSlot(FramebufferTarget::Read)
.Bind(MG_State::pGLContext->GetFramebufferObject(framebuffer));
Uint8 pixels[4 * 4 * 4] = {};
MG_Impl::GLImpl::ReadPixels(0, 0, 4, 4, GL_RGBA, GL_UNSIGNED_BYTE, pixels);
ExpectSingleGlError(GL_INVALID_FRAMEBUFFER_OPERATION);
MG_Impl::GLImpl::BlitFramebuffer(0, 0, 4, 4, 0, 0, 4, 4, GL_COLOR_BUFFER_BIT, GL_NEAREST);
ExpectSingleGlError(GL_INVALID_FRAMEBUFFER_OPERATION);
}
+1
View File
@@ -45,6 +45,7 @@ endif()
add_executable( add_executable(
ProgramTest ProgramTest
ProgramTest.cpp ProgramTest.cpp
ProgramMultiviewTest.cpp
) )
add_executable( add_executable(
@@ -165,6 +165,7 @@ namespace {
link.gsOutputPrimitive = GL_TRIANGLE_STRIP; link.gsOutputPrimitive = GL_TRIANGLE_STRIP;
link.gsMaxVertices = 12; link.gsMaxVertices = 12;
link.gsInvocations = 2; link.gsInvocations = 2;
link.vsNumViews = 2;
link.tessGenMode = GL_QUADS; link.tessGenMode = GL_QUADS;
link.tessGenSpacing = GL_FRACTIONAL_ODD; link.tessGenSpacing = GL_FRACTIONAL_ODD;
link.tessGenVertexOrder = GL_CW; link.tessGenVertexOrder = GL_CW;
@@ -529,9 +530,9 @@ TEST(ProgramArtifactsCodec, AVersionMismatchIsRefused) {
// no archive owns. A codec arm for it would be a use-after-free waiting for a cache hit. // no archive owns. A codec arm for it would be a use-after-free waiting for a cache hit.
TEST(ProgramArtifactsCodec, TheTablesVisitEveryMemberExceptTheLiveProgram) { TEST(ProgramArtifactsCodec, TheTablesVisitEveryMemberExceptTheLiveProgram) {
// P7 OQ-8: 59 members, 58 visited. The 59th is still the live TProgram; the 58th is // P7 OQ-8: 59 members, 58 visited. The 59th is still the live TProgram; the 58th is
// storageBlocks, which follows the record arm's guard (ProgramArtifacts.h). esOrigin then // storageBlocks, which follows the record arm's guard (ProgramArtifacts.h). esOrigin and
// made it 60 and 59. // vsNumViews then made it 61 visited.
EXPECT_EQ(ProgramArtifactsVisitedFieldCount<LinkArtifacts>(), 60u); EXPECT_EQ(ProgramArtifactsVisitedFieldCount<LinkArtifacts>(), 61u);
EXPECT_EQ(ProgramArtifactsVisitedFieldCount<StorageBlockReflection>(), 3u); EXPECT_EQ(ProgramArtifactsVisitedFieldCount<StorageBlockReflection>(), 3u);
EXPECT_EQ(ProgramArtifactsVisitedFieldCount<SpirvArtifacts>(), 10u); EXPECT_EQ(ProgramArtifactsVisitedFieldCount<SpirvArtifacts>(), 10u);
EXPECT_EQ(ProgramArtifactsVisitedFieldCount<ResourceReflection>(), 14u); EXPECT_EQ(ProgramArtifactsVisitedFieldCount<ResourceReflection>(), 14u);
@@ -553,7 +554,7 @@ TEST(ProgramArtifactsCodec, PortableHeaderUsesWireSchemaRatherThanNativeContaine
// too - it is derived from the VisitFields tables - and so did `wireFingerprint`, which is // too - it is derived from the VisitFields tables - and so did `wireFingerprint`, which is
// what makes a mixed-version pair refuse at the handshake instead of at the first program. // what makes a mixed-version pair refuse at the handshake instead of at the first program.
EXPECT_EQ(version, kProgramArtifactsCodecVersion); EXPECT_EQ(version, kProgramArtifactsCodecVersion);
EXPECT_EQ(version, 3u); EXPECT_EQ(version, 4u);
EXPECT_EQ(schema, ProgramArtifactsSchemaFingerprint()); EXPECT_EQ(schema, ProgramArtifactsSchemaFingerprint());
EXPECT_NE(schema, 0u); EXPECT_NE(schema, 0u);
EXPECT_NE(schema, sizeof(LinkArtifacts)); EXPECT_NE(schema, sizeof(LinkArtifacts));
@@ -84,7 +84,7 @@ namespace {
// P7 OQ-8 added LinkArtifacts::storageBlocks and its own three-field table; since P13 W5 // P7 OQ-8 added LinkArtifacts::storageBlocks and its own three-field table; since P13 W5
// the member follows the record arm (ProgramArtifacts.h), which every library builds. // the member follows the record arm (ProgramArtifacts.h), which every library builds.
EXPECT_EQ(CountFields<StorageBlockReflection>(), 3u); EXPECT_EQ(CountFields<StorageBlockReflection>(), 3u);
EXPECT_EQ(CountFields<LinkArtifacts>(), 60u); EXPECT_EQ(CountFields<LinkArtifacts>(), 61u);
EXPECT_EQ(CountFields<SpirvArtifacts>(), 10u); EXPECT_EQ(CountFields<SpirvArtifacts>(), 10u);
} }
@@ -0,0 +1,210 @@
// MobileGL - MobileGL/MG_Test/Program/ProgramMultiviewTest.cpp
// Copyright (c) 2026 MobileGL-Dev
// Licensed under the GNU Lesser General Public License v3.0:
// https://www.gnu.org/licenses/gpl-3.0.txt
// https://www.gnu.org/licenses/lgpl-3.0.txt
// SPDX-License-Identifier: LGPL-3.0-only
// End of Source File Header
// GL_OVR_multiview through the GL compile and link entry points: the vertex stage's num_views
// reaches the program (and survives a link memo hit), GL_MAX_VIEWS_OVR bounds it, the shading
// language extension and its macros exist only where the backend advertises the extension, and
// the draw-time rule compares the program with the draw framebuffer.
#include <gtest/gtest.h>
#include "Includes.h"
#include "Init.h"
#include "MG_Backend/BackendObjects.h"
#include "MG_Impl/GLImpl/Framebuffer/GL_Framebuffer.h"
#include "MG_Impl/GLImpl/Getter/GL_Getter.h"
#include "MG_Impl/GLImpl/Program/GL_Program.h"
#include "MG_Impl/GLImpl/Texture/GL_Texture.h"
#include "MG_State/GLState/Core.h"
using namespace MobileGL;
using namespace MobileGL::MG_Impl::GLImpl;
namespace {
// A backend that claims a type, so the compile environment gates extensions against its list.
class MultiviewProgramBackend final : public MG_Backend::BackendObject {
public:
MultiviewProgramBackend(Int maxViews, Vector<GLExtension> extensions) {
m_params.MaxViews = maxViews;
m_params.MaxArrayTextureLayers = 8;
m_info.RendererGLInfo.Extensions = Move(extensions);
}
void Initialize() override {}
Bool InitCapabilities() override { return true; }
Bool InitWindowSurface() override { return true; }
const RendererInfo& GetRendererInfo() const override { return m_info; }
String GetBackendAPIVersionString() const override { return {}; }
const MG_Backend::GlobalBackendFunctionsTable& GetBackendFunctions() const override {
static MG_Backend::GlobalBackendFunctionsTable table = {};
return table;
}
const MG_Backend::DynamicBackendParameters& GetDynamicParameters() const override { return m_params; }
BackendType GetBackendType() const override { return BackendType::DirectGLES; }
private:
MG_Backend::DynamicBackendParameters m_params{};
RendererInfo m_info{};
};
class ScopedProgramBackend {
public:
ScopedProgramBackend(Int maxViews, Vector<GLExtension> extensions)
: m_previous(Move(MG_Backend::pActiveBackendObject)) {
MG_Backend::pActiveBackendObject = MakeUnique<MultiviewProgramBackend>(maxViews, Move(extensions));
// The context re-captures its compile environment when the backend's address changes,
// and a freshly allocated mock can land on the address the previous one had.
MG_State::pGLContext->InvalidateCompileEnv();
}
~ScopedProgramBackend() {
MG_Backend::pActiveBackendObject = Move(m_previous);
MG_State::pGLContext->InvalidateCompileEnv();
}
private:
UniquePtr<MG_Backend::BackendObject> m_previous;
};
const Vector<GLExtension> kBothExtensions = {E_GL_OVR_multiview, E_GL_OVR_multiview2};
GLuint CompiledShader(GLenum type, const char* source, GLint& status) {
const GLuint shader = CreateShader(type);
ShaderSource(shader, 1, &source, nullptr);
CompileShader(shader);
GetShaderiv(shader, GL_COMPILE_STATUS, &status);
return shader;
}
Bool Compiles(GLenum type, const char* source) {
GLint status = GL_FALSE;
CompiledShader(type, source, status);
return status == GL_TRUE;
}
// The linked program, or 0 when it did not link.
GLuint LinkedProgram(const char* vertex, const char* fragment) {
GLint status = GL_FALSE;
const GLuint vs = CompiledShader(GL_VERTEX_SHADER, vertex, status);
EXPECT_EQ(status, GL_TRUE);
const GLuint fs = CompiledShader(GL_FRAGMENT_SHADER, fragment, status);
EXPECT_EQ(status, GL_TRUE);
const GLuint program = CreateProgram();
AttachShader(program, vs);
AttachShader(program, fs);
LinkProgram(program);
GetProgramiv(program, GL_LINK_STATUS, &status);
return status == GL_TRUE ? program : 0;
}
String MultiviewVertex(Int numViews) {
return std::format("#version 330 core\n"
"#extension GL_OVR_multiview2 : require\n"
"layout(num_views = {}) in;\n"
"layout(location = 0) in vec2 pos;\n"
"void main() {{ gl_Position = vec4(pos.x + float(gl_ViewID_OVR), pos.y, 0.0, 1.0); }}\n",
numViews);
}
constexpr const char* kFragment = "#version 330 core\n"
"out vec4 color;\n"
"void main() { color = vec4(1.0); }\n";
} // namespace
class ProgramMultiviewTest : public ::testing::Test {
protected:
void SetUp() override {
MobileGL::Initialize();
for (Int drained = 0; drained < 16 && GetError() != GL_NO_ERROR; ++drained) {}
}
void TearDown() override { EXPECT_EQ(GetError(), GL_NO_ERROR) << "test left an unconsumed GL error behind"; }
};
TEST_F(ProgramMultiviewTest, TheVertexStagesNumViewsReachesTheProgramAndSurvivesAMemoHit) {
const ScopedProgramBackend backend(4, kBothExtensions);
const String vertex = MultiviewVertex(3);
for (Int link = 0; link < 2; ++link) {
const GLuint program = LinkedProgram(vertex.c_str(), kFragment);
ASSERT_NE(program, 0u) << "link " << link;
const auto programObject = MG_State::pGLContext->GetProgramObject(program);
ASSERT_NE(programObject, nullptr);
EXPECT_EQ(programObject->GetMultiviewViewCount(), 3) << "link " << link;
}
const GLuint plain = LinkedProgram("#version 330 core\nvoid main() { gl_Position = vec4(0.0); }\n", kFragment);
ASSERT_NE(plain, 0u);
EXPECT_EQ(MG_State::pGLContext->GetProgramObject(plain)->GetMultiviewViewCount(), 1);
}
TEST_F(ProgramMultiviewTest, MoreViewsThanTheBackendHasFailsTheLink) {
const ScopedProgramBackend backend(4, kBothExtensions);
const String vertex = MultiviewVertex(5);
EXPECT_EQ(LinkedProgram(vertex.c_str(), kFragment), 0u);
}
TEST_F(ProgramMultiviewTest, TheShadingLanguageExtensionFollowsTheAdvertisement) {
constexpr const char* kRequireFirst = "#version 330 core\n#extension GL_OVR_multiview : require\n"
"void main() { gl_Position = vec4(float(gl_ViewID_OVR)); }\n";
constexpr const char* kRequireSecond = "#version 330 core\n#extension GL_OVR_multiview2 : require\n"
"void main() { gl_Position = vec4(float(gl_ViewID_OVR)); }\n";
constexpr const char* kMacroAbsent = "#version 330 core\n#if defined(GL_OVR_multiview) || "
"defined(GL_OVR_multiview2)\n#error the macro is defined\n#endif\n"
"void main() { gl_Position = vec4(0.0); }\n";
constexpr const char* kMacroPresent = "#version 330 core\n#ifndef GL_OVR_multiview\n#error the macro is "
"missing\n#endif\nvoid main() { gl_Position = vec4(0.0); }\n";
{
const ScopedProgramBackend backend(0, {});
EXPECT_FALSE(Compiles(GL_VERTEX_SHADER, kRequireFirst));
EXPECT_FALSE(Compiles(GL_VERTEX_SHADER, kRequireSecond));
EXPECT_TRUE(Compiles(GL_VERTEX_SHADER, kMacroAbsent));
}
{
const ScopedProgramBackend backend(4, {E_GL_OVR_multiview});
EXPECT_TRUE(Compiles(GL_VERTEX_SHADER, kRequireFirst));
EXPECT_FALSE(Compiles(GL_VERTEX_SHADER, kRequireSecond));
EXPECT_TRUE(Compiles(GL_VERTEX_SHADER, kMacroPresent));
}
{
const ScopedProgramBackend backend(4, kBothExtensions);
EXPECT_TRUE(Compiles(GL_VERTEX_SHADER, kRequireFirst));
EXPECT_TRUE(Compiles(GL_VERTEX_SHADER, kRequireSecond));
EXPECT_TRUE(Compiles(GL_VERTEX_SHADER, kMacroPresent));
}
}
TEST_F(ProgramMultiviewTest, ADrawNeedsTheProgramsViewCountInTheDrawFramebuffer) {
const ScopedProgramBackend backend(4, kBothExtensions);
const String vertex = MultiviewVertex(2);
const GLuint multiviewProgram = LinkedProgram(vertex.c_str(), kFragment);
const GLuint plainProgram =
LinkedProgram("#version 330 core\nvoid main() { gl_Position = vec4(0.0); }\n", kFragment);
ASSERT_NE(multiviewProgram, 0u);
ASSERT_NE(plainProgram, 0u);
const auto& multiview = *MG_State::pGLContext->GetProgramObject(multiviewProgram);
const auto& plain = *MG_State::pGLContext->GetProgramObject(plainProgram);
auto& drawSlot = MG_State::pGLContext->GetFramebufferBindingSlot(FramebufferTarget::Draw);
const auto previous = drawSlot.GetBoundObject();
// The default framebuffer has one view.
drawSlot.Bind(MG_State::pGLContext->GetFramebufferObject(0));
EXPECT_TRUE(ValidateMultiviewDraw(plain, "test"));
EXPECT_FALSE(ValidateMultiviewDraw(multiview, "test"));
EXPECT_EQ(GetError(), static_cast<GLenum>(GL_INVALID_OPERATION));
GLuint texture = 0;
CreateTextures(GL_TEXTURE_2D_ARRAY, 1, &texture);
TextureStorage3D(texture, 1, GL_RGBA8, 4, 4, 2);
GLuint framebuffer = 0;
CreateFramebuffers(1, &framebuffer);
NamedFramebufferTextureMultiviewOVR(framebuffer, GL_COLOR_ATTACHMENT0, texture, 0, 0, 2);
ASSERT_EQ(GetError(), static_cast<GLenum>(GL_NO_ERROR));
drawSlot.Bind(MG_State::pGLContext->GetFramebufferObject(framebuffer));
EXPECT_TRUE(ValidateMultiviewDraw(multiview, "test"));
EXPECT_FALSE(ValidateMultiviewDraw(plain, "test"));
EXPECT_EQ(GetError(), static_cast<GLenum>(GL_INVALID_OPERATION));
drawSlot.Bind(previous);
}
@@ -665,6 +665,7 @@ namespace MobileGL::MG_Util::BackendLoader {
INIT_GLES_FUNC_OPTIONAL(glPolygonModeNV) INIT_GLES_FUNC_OPTIONAL(glPolygonModeNV)
INIT_GLES_FUNC_OPTIONAL(glPolygonModeANGLE) INIT_GLES_FUNC_OPTIONAL(glPolygonModeANGLE)
INIT_GLES_FUNC_OPTIONAL(glClipControlEXT) INIT_GLES_FUNC_OPTIONAL(glClipControlEXT)
INIT_GLES_FUNC_OPTIONAL(glFramebufferTextureMultiviewOVR)
INIT_GLES_FUNC_OPTIONAL(glColorMaskiEXT) INIT_GLES_FUNC_OPTIONAL(glColorMaskiEXT)
INIT_GLES_FUNC_OPTIONAL(glColorMaskiOES) INIT_GLES_FUNC_OPTIONAL(glColorMaskiOES)
INIT_GLES_FUNC_OPTIONAL(glPolygonOffsetClampEXT) INIT_GLES_FUNC_OPTIONAL(glPolygonOffsetClampEXT)
@@ -1000,6 +1001,39 @@ namespace MobileGL::MG_Util::BackendLoader {
} }
} }
// GL_OVR_multiview and GL_OVR_multiview2: the strings, the entry point and GL_MAX_VIEWS_OVR. The
// second extension only counts on top of the first, which is the one with the entry point.
static void FillInMultiviewCapabilities(MG_External::GLESCapabilities& caps,
const MG_External::GLESFunctionsTable& glesFuncs, GLint extCount) {
Bool hasMultiview = false;
Bool hasMultiview2 = false;
for (GLint i = 0; i < extCount; ++i) {
const char* extension = reinterpret_cast<const char*>(glesFuncs.glGetStringi(GL_EXTENSIONS, i));
if (!extension) continue;
if (std::strcmp(extension, "GL_OVR_multiview") == 0) hasMultiview = true;
if (std::strcmp(extension, "GL_OVR_multiview2") == 0) hasMultiview2 = true;
}
caps.SupportsMultiview = hasMultiview && glesFuncs.glFramebufferTextureMultiviewOVR != nullptr;
caps.MaxViews = 0;
if (caps.SupportsMultiview) {
GLint maxViews = 0;
while (glesFuncs.glGetError() != GL_NO_ERROR) {}
glesFuncs.glGetIntegerv(GL_MAX_VIEWS_OVR, &maxViews);
// The spec minimum is 2. A driver that rejects the query or answers less cannot back
// the extension, so it is reported absent rather than clamped up.
if (glesFuncs.glGetError() != GL_NO_ERROR || maxViews < 2) {
MGLOG_W("GL_OVR_multiview is advertised but GL_MAX_VIEWS_OVR answered %d; reporting no multiview",
maxViews);
caps.SupportsMultiview = false;
} else {
caps.MaxViews = maxViews;
}
}
caps.SupportsMultiview2 = caps.SupportsMultiview && hasMultiview2;
MGLOG_I(" multiview (OVR_multiview / OVR_multiview2): %s / %s, GL_MAX_VIEWS_OVR %d",
caps.SupportsMultiview ? "yes" : "no", caps.SupportsMultiview2 ? "yes" : "no", caps.MaxViews);
}
// Reads what the driver answers for GL_EXT_fragment_shading_rate once the extension strings have // Reads what the driver answers for GL_EXT_fragment_shading_rate once the extension strings have
// been matched. The per-sample-count rate lists are folded into masks of the packed encoding // been matched. The per-sample-count rate lists are folded into masks of the packed encoding
// ((log2 w << 2) | log2 h), which is what crosses to the frontend. // ((log2 w << 2) | log2 h), which is what crosses to the frontend.
@@ -1338,6 +1372,7 @@ namespace MobileGL::MG_Util::BackendLoader {
// The string AND the pointer: eglGetProcAddress may hand back a stub for a name the // The string AND the pointer: eglGetProcAddress may hand back a stub for a name the
// driver does not implement. // driver does not implement.
caps.SupportsClipControl = hasClipControlExtension && glesFuncs.glClipControlEXT != nullptr; caps.SupportsClipControl = hasClipControlExtension && glesFuncs.glClipControlEXT != nullptr;
FillInMultiviewCapabilities(caps, glesFuncs, extCount);
caps.SupportsComputeShader = esAtLeast31 && glesFuncs.glDispatchCompute != nullptr && caps.SupportsComputeShader = esAtLeast31 && glesFuncs.glDispatchCompute != nullptr &&
glesFuncs.glMemoryBarrier != nullptr && glesFuncs.glCreateShader != nullptr && glesFuncs.glMemoryBarrier != nullptr && glesFuncs.glCreateShader != nullptr &&
glesFuncs.glCreateProgram != nullptr; glesFuncs.glCreateProgram != nullptr;
@@ -650,6 +650,9 @@ namespace MobileGL {
GL_FUNC_TYPEDEF(void, glPolygonModeANGLE, GLenum face, GLenum mode) GL_FUNC_TYPEDEF(void, glPolygonModeANGLE, GLenum face, GLenum mode)
// GL_EXT_clip_control (ES has no core glClipControl). // GL_EXT_clip_control (ES has no core glClipControl).
GL_FUNC_TYPEDEF(void, glClipControlEXT, GLenum origin, GLenum depth) GL_FUNC_TYPEDEF(void, glClipControlEXT, GLenum origin, GLenum depth)
// GL_OVR_multiview.
GL_FUNC_TYPEDEF(void, glFramebufferTextureMultiviewOVR, GLenum target, GLenum attachment, GLuint texture,
GLint level, GLint baseViewIndex, GLsizei numViews)
GL_FUNC_TYPEDEF(void, glColorMaskiEXT, GLuint index, GLboolean r, GLboolean g, GLboolean b, GLboolean a) GL_FUNC_TYPEDEF(void, glColorMaskiEXT, GLuint index, GLboolean r, GLboolean g, GLboolean b, GLboolean a)
GL_FUNC_TYPEDEF(void, glColorMaskiOES, GLuint index, GLboolean r, GLboolean g, GLboolean b, GLboolean a) GL_FUNC_TYPEDEF(void, glColorMaskiOES, GLuint index, GLboolean r, GLboolean g, GLboolean b, GLboolean a)
// GL_EXT_polygon_offset_clamp. ES has no core spelling at any version. // GL_EXT_polygon_offset_clamp. ES has no core spelling at any version.
@@ -1069,6 +1072,7 @@ namespace MobileGL {
GL_FUNC_DECL(glPolygonModeNV) GL_FUNC_DECL(glPolygonModeNV)
GL_FUNC_DECL(glPolygonModeANGLE) GL_FUNC_DECL(glPolygonModeANGLE)
GL_FUNC_DECL(glClipControlEXT) GL_FUNC_DECL(glClipControlEXT)
GL_FUNC_DECL(glFramebufferTextureMultiviewOVR)
GL_FUNC_DECL(glColorMaskiEXT) GL_FUNC_DECL(glColorMaskiEXT)
GL_FUNC_DECL(glColorMaskiOES) GL_FUNC_DECL(glColorMaskiOES)
GL_FUNC_DECL(glPolygonOffsetClampEXT) GL_FUNC_DECL(glPolygonOffsetClampEXT)
@@ -1124,6 +1128,11 @@ namespace MobileGL {
// GL_EXT_clip_control advertised and glClipControlEXT resolved: the driver applies a // GL_EXT_clip_control advertised and glClipControlEXT resolved: the driver applies a
// clip-space origin and depth mode, so the application's glClipControl is forwarded. // clip-space origin and depth mode, so the application's glClipControl is forwarded.
Bool SupportsClipControl = false; Bool SupportsClipControl = false;
// GL_OVR_multiview advertised and glFramebufferTextureMultiviewOVR resolved, with
// GL_MAX_VIEWS_OVR in MaxViews. GL_OVR_multiview2 only counts on top of it.
Bool SupportsMultiview = false;
Bool SupportsMultiview2 = false;
Int MaxViews = 0;
// GL_EXT_texture_view / GL_OES_texture_view: two ES texture names sharing one // GL_EXT_texture_view / GL_OES_texture_view: two ES texture names sharing one
// storage, i.e. the only way DirectGLES can answer glTextureView at all. ES never // storage, i.e. the only way DirectGLES can answer glTextureView at all. ES never
// made this core - not even in 3.2 - so unlike every other capability here there is // made this core - not even in 3.2 - so unlike every other capability here there is
@@ -13,6 +13,7 @@
#include "ShaderCompiler.h" #include "ShaderCompiler.h"
#include <algorithm> #include <algorithm>
#include <cstring>
#include <format> #include <format>
#include <cmath> #include <cmath>
@@ -1570,6 +1571,41 @@ namespace MobileGL {
enableSpirvValidation); enableSpirvValidation);
} }
bool ShaderCompiler::StripMultiviewCapabilityForEssl(const Vector<Uint32>& inputBinary,
Vector<uint32_t>& outputBinary) {
outputBinary.clear();
constexpr SizeT kHeaderWords = 5;
if (inputBinary.size() <= kHeaderWords) return false;
static constexpr char kExtension[] = "SPV_KHR_multiview";
Vector<uint32_t> out(inputBinary.begin(), inputBinary.begin() + kHeaderWords);
out.reserve(inputBinary.size());
Bool stripped = false;
SizeT at = kHeaderWords;
// Capabilities and extensions all precede OpMemoryModel, so the walk stops there.
while (at < inputBinary.size()) {
const Uint32 wordCount = inputBinary[at] >> 16;
const auto opcode = static_cast<spv::Op>(inputBinary[at] & 0xFFFFu);
if (wordCount == 0 || at + wordCount > inputBinary.size()) return false;
if (opcode == spv::Op::OpMemoryModel) break;
Bool drop = false;
if (opcode == spv::Op::OpCapability && wordCount == 2) {
drop = inputBinary[at + 1] == static_cast<Uint32>(spv::Capability::MultiView);
} else if (opcode == spv::Op::OpExtension && (wordCount - 1) * 4 > sizeof(kExtension) - 1) {
drop = std::memcmp(&inputBinary[at + 1], kExtension, sizeof(kExtension)) == 0;
}
if (drop) {
stripped = true;
} else {
out.insert(out.end(), inputBinary.begin() + at, inputBinary.begin() + at + wordCount);
}
at += wordCount;
}
if (!stripped) return false;
out.insert(out.end(), inputBinary.begin() + at, inputBinary.end());
outputBinary = Move(out);
return true;
}
bool ShaderCompiler::LowerViewportIndexForEssl(const Vector<Uint32>& inputBinary, bool ShaderCompiler::LowerViewportIndexForEssl(const Vector<Uint32>& inputBinary,
Vector<uint32_t>& outputBinary, Vector<uint32_t>& outputBinary,
const bool enableSpirvValidation) { const bool enableSpirvValidation) {
@@ -56,6 +56,15 @@ namespace MobileGL {
static bool LowerDrawParametersForEssl(const Vector<Uint32>& inputBinary, static bool LowerDrawParametersForEssl(const Vector<Uint32>& inputBinary,
Vector<uint32_t>& outputBinary, Vector<uint32_t>& outputBinary,
bool enableSpirvValidation = false); bool enableSpirvValidation = false);
// Drops OpCapability MultiView and OpExtension "SPV_KHR_multiview" and leaves the
// ViewIndex built-in, which SPIRV-Cross then prints as gl_ViewID_OVR. Its own route
// for the capability needs the view count, which the module does not carry, and
// refuses every stage but the vertex one, where GL_OVR_multiview also has the
// built-in in the fragment stage; DirectGLES spells the directive and num_views
// itself (RequestMultiviewExtension). True, with `outputBinary` filled, only when
// something was dropped.
static bool StripMultiviewCapabilityForEssl(const Vector<Uint32>& inputBinary,
Vector<uint32_t>& outputBinary);
// Demotes the gl_ViewportIndex OUTPUT builtin to a plain Private global named // Demotes the gl_ViewportIndex OUTPUT builtin to a plain Private global named
// mg_ViewportIndex, so SPIRV-Cross emits an ordinary declaration instead of a bare // mg_ViewportIndex, so SPIRV-Cross emits an ordinary declaration instead of a bare
// gl_ViewportIndex that ESSL has no core spelling for. Multi-viewport routing is // gl_ViewportIndex that ESSL has no core spelling for. Multi-viewport routing is
@@ -967,10 +967,13 @@ namespace {
// this stage is not in GL_SUBGROUP_SUPPORTED_STAGES_KHR, or when that extension's // this stage is not in GL_SUBGROUP_SUPPORTED_STAGES_KHR, or when that extension's
// feature is not in GL_SUBGROUP_SUPPORTED_FEATURES_KHR - the KHR spec's own terms for // feature is not in GL_SUBGROUP_SUPPORTED_FEATURES_KHR - the KHR spec's own terms for
// where each of the eight may be used. The stage and feature tests need a backend: // where each of the eight may be used. The stage and feature tests need a backend:
// with none, every extension reads as available (CompileEnv::IsExtensionAdvertised). // with none, every extension reads as available (CompileEnv::IsExtensionAdvertised);
// * GL_OVR_multiview / GL_OVR_multiview2 when that extension is not advertised.
bool IsUnavailableShaderExtension(const MobileGL::MG_Util::ShaderTranspiler::CompileEnv& env, bool IsUnavailableShaderExtension(const MobileGL::MG_Util::ShaderTranspiler::CompileEnv& env,
MobileGL::ShaderStage stage, const MobileGL::String& name) { MobileGL::ShaderStage stage, const MobileGL::String& name) {
if (name == "GL_ARB_gpu_shader_int64") return !env.IsExtensionAdvertised(MobileGL::E_GL_ARB_gpu_shader_int64); if (name == "GL_ARB_gpu_shader_int64") return !env.IsExtensionAdvertised(MobileGL::E_GL_ARB_gpu_shader_int64);
if (name == "GL_OVR_multiview") return !env.IsExtensionAdvertised(MobileGL::E_GL_OVR_multiview);
if (name == "GL_OVR_multiview2") return !env.IsExtensionAdvertised(MobileGL::E_GL_OVR_multiview2);
const GLbitfield feature = SubgroupFeatureBit(name); const GLbitfield feature = SubgroupFeatureBit(name);
if (feature == 0) return false; if (feature == 0) return false;
if (!env.IsExtensionAdvertised(MobileGL::E_GL_KHR_shader_subgroup)) return true; if (!env.IsExtensionAdvertised(MobileGL::E_GL_KHR_shader_subgroup)) return true;
@@ -1048,10 +1051,13 @@ namespace {
source.replace(it->pos, it->len, it->replacement); source.replace(it->pos, it->len, it->replacement);
} }
// The extension's own feature-test macro, so an `#ifdef` guard takes the fallback branch. // The extension's own feature-test macro, so an `#ifdef` guard takes the fallback branch.
// int64 keeps its historical treatment: hidden whether or not the source names it. // int64 keeps its historical treatment: hidden whether or not the source names it, and the
if (IsUnavailableShaderExtension(env, stage, "GL_ARB_gpu_shader_int64") && // two multiview macros get the same, because glslang predefines them at every 300+ version.
std::find(hiddenNames.begin(), hiddenNames.end(), "GL_ARB_gpu_shader_int64") == hiddenNames.end()) { for (const char* alwaysHidden : {"GL_ARB_gpu_shader_int64", "GL_OVR_multiview", "GL_OVR_multiview2"}) {
hiddenNames.push_back("GL_ARB_gpu_shader_int64"); if (IsUnavailableShaderExtension(env, stage, alwaysHidden) &&
std::find(hiddenNames.begin(), hiddenNames.end(), alwaysHidden) == hiddenNames.end()) {
hiddenNames.push_back(alwaysHidden);
}
} }
for (const auto& name : hiddenNames) { for (const auto& name : hiddenNames) {
ReplaceIdentifier(source, name, "MG_DISABLED_" + name); ReplaceIdentifier(source, name, "MG_DISABLED_" + name);
@@ -324,6 +324,7 @@ public:
source(EShSourceNone), source(EShSourceNone),
useVulkanMemoryModel(false), useVulkanMemoryModel(false),
invocations(TQualifier::layoutNotSet), vertices(TQualifier::layoutNotSet), invocations(TQualifier::layoutNotSet), vertices(TQualifier::layoutNotSet),
numViews(TQualifier::layoutNotSet),
inputPrimitive(ElgNone), outputPrimitive(ElgNone), inputPrimitive(ElgNone), outputPrimitive(ElgNone),
pixelCenterInteger(false), originUpperLeft(false),texCoordBuiltinRedeclared(false), pixelCenterInteger(false), originUpperLeft(false),texCoordBuiltinRedeclared(false),
vertexSpacing(EvsNone), vertexOrder(EvoNone), interlockOrdering(EioNone), pointMode(false), earlyFragmentTests(false), vertexSpacing(EvsNone), vertexOrder(EvoNone), interlockOrdering(EioNone), pointMode(false), earlyFragmentTests(false),
@@ -901,6 +902,16 @@ public:
return true; return true;
} }
int getInvocations() const { return invocations; } int getInvocations() const { return invocations; }
// GL_OVR_multiview's layout(num_views = N) in; of a vertex shader. SPIR-V has no way to say
// it, so a consumer that emits GLSL from the module reads it here.
bool setNumViews(int n)
{
if (numViews != TQualifier::layoutNotSet)
return numViews == n;
numViews = n;
return true;
}
int getNumViews() const { return numViews; }
bool setVertices(int m) bool setVertices(int m)
{ {
if (vertices != TQualifier::layoutNotSet) if (vertices != TQualifier::layoutNotSet)
@@ -1286,6 +1297,7 @@ protected:
bool useVulkanMemoryModel; bool useVulkanMemoryModel;
int invocations; int invocations;
int vertices; int vertices;
int numViews;
TLayoutGeometry inputPrimitive; TLayoutGeometry inputPrimitive;
TLayoutGeometry outputPrimitive; TLayoutGeometry outputPrimitive;
bool pixelCenterInteger; bool pixelCenterInteger;