Bug 1936278 - Prevent search mode chiclet from being dismissed when clicking in page...
[gecko.git] / dom / canvas / WebGLContextGL.cpp
blob5f597f54e806bf5d309c599c69ad62d385bfa72a
1 /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* This Source Code Form is subject to the terms of the Mozilla Public
3 * License, v. 2.0. If a copy of the MPL was not distributed with this
4 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6 #include "WebGLContext.h"
7 #include "WebGL2Context.h"
9 #include "WebGLContextUtils.h"
10 #include "WebGLBuffer.h"
11 #include "WebGLShader.h"
12 #include "WebGLProgram.h"
13 #include "WebGLFormats.h"
14 #include "WebGLFramebuffer.h"
15 #include "WebGLQuery.h"
16 #include "WebGLRenderbuffer.h"
17 #include "WebGLTexture.h"
18 #include "WebGLVertexArray.h"
20 #include "nsDebug.h"
21 #include "nsReadableUtils.h"
22 #include "nsString.h"
24 #include "gfxContext.h"
25 #include "gfxPlatform.h"
26 #include "GLContext.h"
28 #include "nsContentUtils.h"
29 #include "nsError.h"
30 #include "nsLayoutUtils.h"
32 #include "CanvasUtils.h"
33 #include "gfxUtils.h"
34 #include "MozFramebuffer.h"
36 #include "jsfriendapi.h"
38 #include "WebGLTexelConversions.h"
39 #include "WebGLValidateStrings.h"
40 #include <algorithm>
42 #include "mozilla/DebugOnly.h"
43 #include "mozilla/dom/BindingUtils.h"
44 #include "mozilla/dom/ImageData.h"
45 #include "mozilla/dom/WebGLRenderingContextBinding.h"
46 #include "mozilla/EndianUtils.h"
47 #include "mozilla/RefPtr.h"
48 #include "mozilla/UniquePtrExtensions.h"
49 #include "mozilla/StaticPrefs_webgl.h"
51 namespace mozilla {
53 using namespace mozilla::dom;
54 using namespace mozilla::gfx;
55 using namespace mozilla::gl;
58 // WebGL API
61 void WebGLContext::ActiveTexture(uint32_t texUnit) {
62 FuncScope funcScope(*this, "activeTexture");
63 if (IsContextLost()) return;
64 funcScope.mBindFailureGuard = true;
66 if (texUnit >= Limits().maxTexUnits) {
67 return ErrorInvalidEnum("Texture unit %u out of range (%u).", texUnit,
68 Limits().maxTexUnits);
71 mActiveTexture = texUnit;
72 gl->fActiveTexture(LOCAL_GL_TEXTURE0 + texUnit);
74 funcScope.mBindFailureGuard = false;
77 void WebGLContext::AttachShader(WebGLProgram& prog, WebGLShader& shader) {
78 FuncScope funcScope(*this, "attachShader");
79 if (IsContextLost()) return;
80 funcScope.mBindFailureGuard = true;
82 prog.AttachShader(shader);
84 funcScope.mBindFailureGuard = false;
87 void WebGLContext::BindAttribLocation(WebGLProgram& prog, GLuint location,
88 const std::string& name) const {
89 const FuncScope funcScope(*this, "bindAttribLocation");
90 if (IsContextLost()) return;
92 prog.BindAttribLocation(location, name);
95 void WebGLContext::BindFramebuffer(GLenum target, WebGLFramebuffer* wfb) {
96 FuncScope funcScope(*this, "bindFramebuffer");
97 if (IsContextLost()) return;
98 funcScope.mBindFailureGuard = true;
100 if (!ValidateFramebufferTarget(target)) return;
102 if (!wfb) {
103 gl->fBindFramebuffer(target, 0);
104 } else {
105 GLuint framebuffername = wfb->mGLName;
106 gl->fBindFramebuffer(target, framebuffername);
107 wfb->mHasBeenBound = true;
110 switch (target) {
111 case LOCAL_GL_FRAMEBUFFER:
112 mBoundDrawFramebuffer = wfb;
113 mBoundReadFramebuffer = wfb;
114 break;
115 case LOCAL_GL_DRAW_FRAMEBUFFER:
116 mBoundDrawFramebuffer = wfb;
117 break;
118 case LOCAL_GL_READ_FRAMEBUFFER:
119 mBoundReadFramebuffer = wfb;
120 break;
121 default:
122 return;
124 funcScope.mBindFailureGuard = false;
127 void WebGLContext::BlendEquationSeparate(Maybe<GLuint> i, GLenum modeRGB,
128 GLenum modeAlpha) {
129 const FuncScope funcScope(*this, "blendEquationSeparate");
130 if (IsContextLost()) return;
132 if (!ValidateBlendEquationEnum(modeRGB, "modeRGB") ||
133 !ValidateBlendEquationEnum(modeAlpha, "modeAlpha")) {
134 return;
137 if (i) {
138 MOZ_RELEASE_ASSERT(
139 IsExtensionEnabled(WebGLExtensionID::OES_draw_buffers_indexed));
140 const auto limit = MaxValidDrawBuffers();
141 if (*i >= limit) {
142 ErrorInvalidValue("`index` (%u) must be < %s (%u)", *i,
143 "MAX_DRAW_BUFFERS", limit);
144 return;
147 gl->fBlendEquationSeparatei(*i, modeRGB, modeAlpha);
148 } else {
149 gl->fBlendEquationSeparate(modeRGB, modeAlpha);
153 static bool ValidateBlendFuncEnum(WebGLContext* webgl, GLenum factor,
154 const char* varName) {
155 switch (factor) {
156 case LOCAL_GL_ZERO:
157 case LOCAL_GL_ONE:
158 case LOCAL_GL_SRC_COLOR:
159 case LOCAL_GL_ONE_MINUS_SRC_COLOR:
160 case LOCAL_GL_DST_COLOR:
161 case LOCAL_GL_ONE_MINUS_DST_COLOR:
162 case LOCAL_GL_SRC_ALPHA:
163 case LOCAL_GL_ONE_MINUS_SRC_ALPHA:
164 case LOCAL_GL_DST_ALPHA:
165 case LOCAL_GL_ONE_MINUS_DST_ALPHA:
166 case LOCAL_GL_CONSTANT_COLOR:
167 case LOCAL_GL_ONE_MINUS_CONSTANT_COLOR:
168 case LOCAL_GL_CONSTANT_ALPHA:
169 case LOCAL_GL_ONE_MINUS_CONSTANT_ALPHA:
170 case LOCAL_GL_SRC_ALPHA_SATURATE:
171 return true;
173 default:
174 webgl->ErrorInvalidEnumInfo(varName, factor);
175 return false;
179 static bool ValidateBlendFuncEnums(WebGLContext* webgl, GLenum srcRGB,
180 GLenum srcAlpha, GLenum dstRGB,
181 GLenum dstAlpha) {
182 if (!webgl->IsWebGL2()) {
183 if (dstRGB == LOCAL_GL_SRC_ALPHA_SATURATE ||
184 dstAlpha == LOCAL_GL_SRC_ALPHA_SATURATE) {
185 webgl->ErrorInvalidEnum(
186 "LOCAL_GL_SRC_ALPHA_SATURATE as a destination"
187 " blend function is disallowed in WebGL 1 (dstRGB ="
188 " 0x%04x, dstAlpha = 0x%04x).",
189 dstRGB, dstAlpha);
190 return false;
194 if (!ValidateBlendFuncEnum(webgl, srcRGB, "srcRGB") ||
195 !ValidateBlendFuncEnum(webgl, srcAlpha, "srcAlpha") ||
196 !ValidateBlendFuncEnum(webgl, dstRGB, "dstRGB") ||
197 !ValidateBlendFuncEnum(webgl, dstAlpha, "dstAlpha")) {
198 return false;
201 return true;
204 void WebGLContext::BlendFuncSeparate(Maybe<GLuint> i, GLenum srcRGB,
205 GLenum dstRGB, GLenum srcAlpha,
206 GLenum dstAlpha) {
207 const FuncScope funcScope(*this, "blendFuncSeparate");
208 if (IsContextLost()) return;
210 if (!ValidateBlendFuncEnums(this, srcRGB, srcAlpha, dstRGB, dstAlpha)) return;
212 // note that we only check compatibity for the RGB enums, no need to for the
213 // Alpha enums, see "Section 6.8 forgetting to mention alpha factors?" thread
214 // on the public_webgl mailing list
215 if (!ValidateBlendFuncEnumsCompatibility(srcRGB, dstRGB, "srcRGB and dstRGB"))
216 return;
218 if (i) {
219 MOZ_RELEASE_ASSERT(
220 IsExtensionEnabled(WebGLExtensionID::OES_draw_buffers_indexed));
221 const auto limit = MaxValidDrawBuffers();
222 if (*i >= limit) {
223 ErrorInvalidValue("`index` (%u) must be < %s (%u)", *i,
224 "MAX_DRAW_BUFFERS", limit);
225 return;
228 gl->fBlendFuncSeparatei(*i, srcRGB, dstRGB, srcAlpha, dstAlpha);
229 } else {
230 gl->fBlendFuncSeparate(srcRGB, dstRGB, srcAlpha, dstAlpha);
234 GLenum WebGLContext::CheckFramebufferStatus(GLenum target) {
235 const FuncScope funcScope(*this, "checkFramebufferStatus");
236 if (IsContextLost()) return LOCAL_GL_FRAMEBUFFER_UNSUPPORTED;
238 if (!ValidateFramebufferTarget(target)) return 0;
240 WebGLFramebuffer* fb;
241 switch (target) {
242 case LOCAL_GL_FRAMEBUFFER:
243 case LOCAL_GL_DRAW_FRAMEBUFFER:
244 fb = mBoundDrawFramebuffer;
245 break;
247 case LOCAL_GL_READ_FRAMEBUFFER:
248 fb = mBoundReadFramebuffer;
249 break;
251 default:
252 MOZ_CRASH("GFX: Bad target.");
255 if (!fb) return LOCAL_GL_FRAMEBUFFER_COMPLETE;
257 return fb->CheckFramebufferStatus().get();
260 RefPtr<WebGLProgram> WebGLContext::CreateProgram() {
261 const FuncScope funcScope(*this, "createProgram");
262 if (IsContextLost()) return nullptr;
264 return new WebGLProgram(this);
267 RefPtr<WebGLShader> WebGLContext::CreateShader(GLenum type) {
268 const FuncScope funcScope(*this, "createShader");
269 if (IsContextLost()) return nullptr;
271 if (type != LOCAL_GL_VERTEX_SHADER && type != LOCAL_GL_FRAGMENT_SHADER) {
272 ErrorInvalidEnumInfo("type", type);
273 return nullptr;
276 return new WebGLShader(this, type);
279 void WebGLContext::CullFace(GLenum face) {
280 const FuncScope funcScope(*this, "cullFace");
281 if (IsContextLost()) return;
283 if (!ValidateFaceEnum(face)) return;
285 gl->fCullFace(face);
288 void WebGLContext::DetachShader(WebGLProgram& prog, const WebGLShader& shader) {
289 FuncScope funcScope(*this, "detachShader");
290 if (IsContextLost()) return;
291 funcScope.mBindFailureGuard = true;
293 prog.DetachShader(shader);
295 funcScope.mBindFailureGuard = false;
298 static bool ValidateComparisonEnum(WebGLContext& webgl, const GLenum func) {
299 switch (func) {
300 case LOCAL_GL_NEVER:
301 case LOCAL_GL_LESS:
302 case LOCAL_GL_LEQUAL:
303 case LOCAL_GL_GREATER:
304 case LOCAL_GL_GEQUAL:
305 case LOCAL_GL_EQUAL:
306 case LOCAL_GL_NOTEQUAL:
307 case LOCAL_GL_ALWAYS:
308 return true;
310 default:
311 webgl.ErrorInvalidEnumInfo("func", func);
312 return false;
316 void WebGLContext::DepthFunc(GLenum func) {
317 const FuncScope funcScope(*this, "depthFunc");
318 if (IsContextLost()) return;
320 if (!ValidateComparisonEnum(*this, func)) return;
322 gl->fDepthFunc(func);
325 void WebGLContext::DepthRange(GLfloat zNear, GLfloat zFar) {
326 const FuncScope funcScope(*this, "depthRange");
327 if (IsContextLost()) return;
329 if (zNear > zFar)
330 return ErrorInvalidOperation(
331 "the near value is greater than the far value!");
333 gl->fDepthRange(zNear, zFar);
336 // -
338 void WebGLContext::FramebufferAttach(const GLenum target,
339 const GLenum attachSlot,
340 const GLenum bindImageTarget,
341 const webgl::FbAttachInfo& toAttach) {
342 FuncScope funcScope(*this, "framebufferAttach");
343 funcScope.mBindFailureGuard = true;
344 const auto& limits = *mLimits;
346 if (!ValidateFramebufferTarget(target)) return;
348 auto fb = mBoundDrawFramebuffer;
349 if (target == LOCAL_GL_READ_FRAMEBUFFER) {
350 fb = mBoundReadFramebuffer;
352 if (!fb) return;
354 // `rb` needs no validation.
356 // `tex`
357 const auto& tex = toAttach.tex;
358 if (tex) {
359 const auto err = CheckFramebufferAttach(bindImageTarget, tex->mTarget.get(),
360 toAttach.mipLevel, toAttach.zLayer,
361 toAttach.zLayerCount, limits);
362 if (err) return;
365 auto safeToAttach = toAttach;
366 if (!toAttach.rb && !toAttach.tex) {
367 safeToAttach = {};
369 if (!IsWebGL2() &&
370 !IsExtensionEnabled(WebGLExtensionID::OES_fbo_render_mipmap)) {
371 safeToAttach.mipLevel = 0;
373 if (!IsExtensionEnabled(WebGLExtensionID::OVR_multiview2)) {
374 safeToAttach.isMultiview = false;
377 if (!fb->FramebufferAttach(attachSlot, safeToAttach)) return;
379 funcScope.mBindFailureGuard = false;
382 // -
384 void WebGLContext::FrontFace(GLenum mode) {
385 const FuncScope funcScope(*this, "frontFace");
386 if (IsContextLost()) return;
388 switch (mode) {
389 case LOCAL_GL_CW:
390 case LOCAL_GL_CCW:
391 break;
392 default:
393 return ErrorInvalidEnumInfo("mode", mode);
396 gl->fFrontFace(mode);
399 Maybe<double> WebGLContext::GetBufferParameter(GLenum target, GLenum pname) {
400 const FuncScope funcScope(*this, "getBufferParameter");
401 if (IsContextLost()) return Nothing();
403 const auto& slot = ValidateBufferSlot(target);
404 if (!slot) return Nothing();
405 const auto& buffer = *slot;
407 if (!buffer) {
408 ErrorInvalidOperation("Buffer for `target` is null.");
409 return Nothing();
412 switch (pname) {
413 case LOCAL_GL_BUFFER_SIZE:
414 return Some(buffer->ByteLength());
416 case LOCAL_GL_BUFFER_USAGE:
417 return Some(buffer->Usage());
419 default:
420 ErrorInvalidEnumInfo("pname", pname);
421 return Nothing();
425 Maybe<double> WebGLContext::GetFramebufferAttachmentParameter(
426 WebGLFramebuffer* const fb, GLenum attachment, GLenum pname) const {
427 const FuncScope funcScope(*this, "getFramebufferAttachmentParameter");
428 if (IsContextLost()) return Nothing();
430 if (fb) return fb->GetAttachmentParameter(attachment, pname);
432 ////////////////////////////////////
434 if (!IsWebGL2()) {
435 ErrorInvalidOperation(
436 "Querying against the default framebuffer is not"
437 " allowed in WebGL 1.");
438 return Nothing();
441 switch (attachment) {
442 case LOCAL_GL_BACK:
443 case LOCAL_GL_DEPTH:
444 case LOCAL_GL_STENCIL:
445 break;
447 default:
448 ErrorInvalidEnum(
449 "For the default framebuffer, can only query COLOR, DEPTH,"
450 " or STENCIL.");
451 return Nothing();
454 switch (pname) {
455 case LOCAL_GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE:
456 switch (attachment) {
457 case LOCAL_GL_BACK:
458 break;
459 case LOCAL_GL_DEPTH:
460 if (!mOptions.depth) {
461 return Some(LOCAL_GL_NONE);
463 break;
464 case LOCAL_GL_STENCIL:
465 if (!mOptions.stencil) {
466 return Some(LOCAL_GL_NONE);
468 break;
469 default:
470 ErrorInvalidEnum(
471 "With the default framebuffer, can only query COLOR, DEPTH,"
472 " or STENCIL for GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE");
473 return Nothing();
475 return Some(LOCAL_GL_FRAMEBUFFER_DEFAULT);
477 ////////////////
479 case LOCAL_GL_FRAMEBUFFER_ATTACHMENT_RED_SIZE:
480 case LOCAL_GL_FRAMEBUFFER_ATTACHMENT_GREEN_SIZE:
481 case LOCAL_GL_FRAMEBUFFER_ATTACHMENT_BLUE_SIZE:
482 if (attachment == LOCAL_GL_BACK) return Some(8);
483 return Some(0);
485 case LOCAL_GL_FRAMEBUFFER_ATTACHMENT_ALPHA_SIZE:
486 if (attachment == LOCAL_GL_BACK) {
487 if (mOptions.alpha) {
488 return Some(8);
490 ErrorInvalidOperation(
491 "The default framebuffer doesn't contain an alpha buffer");
492 return Nothing();
494 return Some(0);
496 case LOCAL_GL_FRAMEBUFFER_ATTACHMENT_DEPTH_SIZE:
497 if (attachment == LOCAL_GL_DEPTH) {
498 if (mOptions.depth) {
499 return Some(24);
501 ErrorInvalidOperation(
502 "The default framebuffer doesn't contain an depth buffer");
503 return Nothing();
505 return Some(0);
507 case LOCAL_GL_FRAMEBUFFER_ATTACHMENT_STENCIL_SIZE:
508 if (attachment == LOCAL_GL_STENCIL) {
509 if (mOptions.stencil) {
510 return Some(8);
512 ErrorInvalidOperation(
513 "The default framebuffer doesn't contain an stencil buffer");
514 return Nothing();
516 return Some(0);
518 case LOCAL_GL_FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE:
519 if (attachment == LOCAL_GL_STENCIL) {
520 if (mOptions.stencil) {
521 return Some(LOCAL_GL_UNSIGNED_INT);
523 ErrorInvalidOperation(
524 "The default framebuffer doesn't contain an stencil buffer");
525 } else if (attachment == LOCAL_GL_DEPTH) {
526 if (mOptions.depth) {
527 return Some(LOCAL_GL_UNSIGNED_NORMALIZED);
529 ErrorInvalidOperation(
530 "The default framebuffer doesn't contain an depth buffer");
531 } else { // LOCAL_GL_BACK
532 return Some(LOCAL_GL_UNSIGNED_NORMALIZED);
534 return Nothing();
536 case LOCAL_GL_FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING:
537 if (attachment == LOCAL_GL_STENCIL) {
538 if (!mOptions.stencil) {
539 ErrorInvalidOperation(
540 "The default framebuffer doesn't contain an stencil buffer");
541 return Nothing();
543 } else if (attachment == LOCAL_GL_DEPTH) {
544 if (!mOptions.depth) {
545 ErrorInvalidOperation(
546 "The default framebuffer doesn't contain an depth buffer");
547 return Nothing();
550 return Some(LOCAL_GL_LINEAR);
553 ErrorInvalidEnumInfo("pname", pname);
554 return Nothing();
557 Maybe<double> WebGLContext::GetRenderbufferParameter(
558 const WebGLRenderbuffer& rb, GLenum pname) const {
559 const FuncScope funcScope(*this, "getRenderbufferParameter");
560 if (IsContextLost()) return Nothing();
562 switch (pname) {
563 case LOCAL_GL_RENDERBUFFER_SAMPLES:
564 if (!IsWebGL2()) break;
565 [[fallthrough]];
567 case LOCAL_GL_RENDERBUFFER_WIDTH:
568 case LOCAL_GL_RENDERBUFFER_HEIGHT:
569 case LOCAL_GL_RENDERBUFFER_RED_SIZE:
570 case LOCAL_GL_RENDERBUFFER_GREEN_SIZE:
571 case LOCAL_GL_RENDERBUFFER_BLUE_SIZE:
572 case LOCAL_GL_RENDERBUFFER_ALPHA_SIZE:
573 case LOCAL_GL_RENDERBUFFER_DEPTH_SIZE:
574 case LOCAL_GL_RENDERBUFFER_STENCIL_SIZE:
575 case LOCAL_GL_RENDERBUFFER_INTERNAL_FORMAT: {
576 // RB emulation means we have to ask the RB itself.
577 GLint i = rb.GetRenderbufferParameter(pname);
578 return Some(i);
581 default:
582 break;
585 ErrorInvalidEnumInfo("pname", pname);
586 return Nothing();
589 RefPtr<WebGLTexture> WebGLContext::CreateTexture() {
590 const FuncScope funcScope(*this, "createTexture");
591 if (IsContextLost()) return nullptr;
593 GLuint tex = 0;
594 gl->fGenTextures(1, &tex);
596 return new WebGLTexture(this, tex);
599 GLenum WebGLContext::GetError() {
600 const FuncScope funcScope(*this, "getError");
602 /* WebGL 1.0: Section 5.14.3: Setting and getting state:
603 * If the context's webgl context lost flag is set, returns
604 * CONTEXT_LOST_WEBGL the first time this method is called.
605 * Afterward, returns NO_ERROR until the context has been
606 * restored.
608 * WEBGL_lose_context:
609 * [When this extension is enabled: ] loseContext and
610 * restoreContext are allowed to generate INVALID_OPERATION errors
611 * even when the context is lost.
614 auto err = mWebGLError;
615 mWebGLError = 0;
616 if (IsContextLost() || err) // Must check IsContextLost in all flow paths.
617 return err;
619 // Either no WebGL-side error, or it's already been cleared.
620 // UnderlyingGL-side errors, now.
621 err = gl->fGetError();
622 if (gl->IsContextLost()) {
623 CheckForContextLoss();
624 return GetError();
626 MOZ_ASSERT(err != LOCAL_GL_CONTEXT_LOST);
628 if (err) {
629 GenerateWarning("Driver error unexpected by WebGL: 0x%04x", err);
630 // This might be:
631 // - INVALID_OPERATION from ANGLE due to incomplete RBAB implementation for
632 // DrawElements
633 // with DYNAMIC_DRAW index buffer.
635 return err;
638 webgl::GetUniformData WebGLContext::GetUniform(const WebGLProgram& prog,
639 const uint32_t loc) const {
640 const FuncScope funcScope(*this, "getUniform");
641 webgl::GetUniformData ret;
642 [&]() {
643 if (IsContextLost()) return;
645 const auto& info = prog.LinkInfo();
646 if (!info) return;
648 const auto locInfo = MaybeFind(info->locationMap, loc);
649 if (!locInfo) return;
651 ret.type = locInfo->info.info.elemType;
652 switch (ret.type) {
653 case LOCAL_GL_FLOAT:
654 case LOCAL_GL_FLOAT_VEC2:
655 case LOCAL_GL_FLOAT_VEC3:
656 case LOCAL_GL_FLOAT_VEC4:
657 case LOCAL_GL_FLOAT_MAT2:
658 case LOCAL_GL_FLOAT_MAT3:
659 case LOCAL_GL_FLOAT_MAT4:
660 case LOCAL_GL_FLOAT_MAT2x3:
661 case LOCAL_GL_FLOAT_MAT2x4:
662 case LOCAL_GL_FLOAT_MAT3x2:
663 case LOCAL_GL_FLOAT_MAT3x4:
664 case LOCAL_GL_FLOAT_MAT4x2:
665 case LOCAL_GL_FLOAT_MAT4x3:
666 gl->fGetUniformfv(prog.mGLName, loc,
667 reinterpret_cast<float*>(ret.data));
668 break;
670 case LOCAL_GL_INT:
671 case LOCAL_GL_INT_VEC2:
672 case LOCAL_GL_INT_VEC3:
673 case LOCAL_GL_INT_VEC4:
674 case LOCAL_GL_SAMPLER_2D:
675 case LOCAL_GL_SAMPLER_3D:
676 case LOCAL_GL_SAMPLER_CUBE:
677 case LOCAL_GL_SAMPLER_2D_SHADOW:
678 case LOCAL_GL_SAMPLER_2D_ARRAY:
679 case LOCAL_GL_SAMPLER_2D_ARRAY_SHADOW:
680 case LOCAL_GL_SAMPLER_CUBE_SHADOW:
681 case LOCAL_GL_INT_SAMPLER_2D:
682 case LOCAL_GL_INT_SAMPLER_3D:
683 case LOCAL_GL_INT_SAMPLER_CUBE:
684 case LOCAL_GL_INT_SAMPLER_2D_ARRAY:
685 case LOCAL_GL_UNSIGNED_INT_SAMPLER_2D:
686 case LOCAL_GL_UNSIGNED_INT_SAMPLER_3D:
687 case LOCAL_GL_UNSIGNED_INT_SAMPLER_CUBE:
688 case LOCAL_GL_UNSIGNED_INT_SAMPLER_2D_ARRAY:
689 case LOCAL_GL_BOOL:
690 case LOCAL_GL_BOOL_VEC2:
691 case LOCAL_GL_BOOL_VEC3:
692 case LOCAL_GL_BOOL_VEC4:
693 gl->fGetUniformiv(prog.mGLName, loc,
694 reinterpret_cast<int32_t*>(ret.data));
695 break;
697 case LOCAL_GL_UNSIGNED_INT:
698 case LOCAL_GL_UNSIGNED_INT_VEC2:
699 case LOCAL_GL_UNSIGNED_INT_VEC3:
700 case LOCAL_GL_UNSIGNED_INT_VEC4:
701 gl->fGetUniformuiv(prog.mGLName, loc,
702 reinterpret_cast<uint32_t*>(ret.data));
703 break;
705 default:
706 MOZ_CRASH("GFX: Invalid elemType.");
708 }();
709 return ret;
712 void WebGLContext::Hint(GLenum target, GLenum mode) {
713 const FuncScope funcScope(*this, "hint");
714 if (IsContextLost()) return;
716 switch (mode) {
717 case LOCAL_GL_FASTEST:
718 case LOCAL_GL_NICEST:
719 case LOCAL_GL_DONT_CARE:
720 break;
721 default:
722 return ErrorInvalidEnumArg("mode", mode);
725 // -
727 bool isValid = false;
729 switch (target) {
730 case LOCAL_GL_GENERATE_MIPMAP_HINT:
731 mGenerateMipmapHint = mode;
732 isValid = true;
734 // Deprecated and removed in desktop GL Core profiles.
735 if (gl->IsCoreProfile()) return;
737 break;
739 case LOCAL_GL_FRAGMENT_SHADER_DERIVATIVE_HINT:
740 if (IsWebGL2() ||
741 IsExtensionEnabled(WebGLExtensionID::OES_standard_derivatives)) {
742 isValid = true;
744 break;
746 if (!isValid) return ErrorInvalidEnumInfo("target", target);
748 // -
750 gl->fHint(target, mode);
753 // -
755 void WebGLContext::LinkProgram(WebGLProgram& prog) {
756 const FuncScope funcScope(*this, "linkProgram");
757 if (IsContextLost()) return;
759 prog.LinkProgram();
761 if (&prog == mCurrentProgram) {
762 if (!prog.IsLinked()) {
763 // We use to simply early-out here, and preserve the GL behavior that
764 // failed relink doesn't invalidate the current active program link info.
765 // The new behavior was changed for WebGL here:
766 // https://github.com/KhronosGroup/WebGL/pull/3371
767 mActiveProgramLinkInfo = nullptr;
768 gl->fUseProgram(0); // Shouldn't be needed, but let's be safe.
769 return;
771 mActiveProgramLinkInfo = prog.LinkInfo();
772 gl->fUseProgram(prog.mGLName); // Uncontionally re-use.
773 // Previously, we needed this re-use on nvidia as a driver workaround,
774 // but we might as well do it unconditionally.
778 Maybe<webgl::ErrorInfo> SetPixelUnpack(
779 const bool isWebgl2, webgl::PixelUnpackStateWebgl* const unpacking,
780 const GLenum pname, const GLint param) {
781 if (isWebgl2) {
782 uint32_t* pValueSlot = nullptr;
783 switch (pname) {
784 case LOCAL_GL_UNPACK_IMAGE_HEIGHT:
785 pValueSlot = &unpacking->imageHeight;
786 break;
788 case LOCAL_GL_UNPACK_SKIP_IMAGES:
789 pValueSlot = &unpacking->skipImages;
790 break;
792 case LOCAL_GL_UNPACK_ROW_LENGTH:
793 pValueSlot = &unpacking->rowLength;
794 break;
796 case LOCAL_GL_UNPACK_SKIP_ROWS:
797 pValueSlot = &unpacking->skipRows;
798 break;
800 case LOCAL_GL_UNPACK_SKIP_PIXELS:
801 pValueSlot = &unpacking->skipPixels;
802 break;
805 if (pValueSlot) {
806 *pValueSlot = static_cast<uint32_t>(param);
807 return {};
811 switch (pname) {
812 case dom::WebGLRenderingContext_Binding::UNPACK_FLIP_Y_WEBGL:
813 unpacking->flipY = bool(param);
814 return {};
816 case dom::WebGLRenderingContext_Binding::UNPACK_PREMULTIPLY_ALPHA_WEBGL:
817 unpacking->premultiplyAlpha = bool(param);
818 return {};
820 case dom::WebGLRenderingContext_Binding::UNPACK_COLORSPACE_CONVERSION_WEBGL:
821 switch (param) {
822 case LOCAL_GL_NONE:
823 case dom::WebGLRenderingContext_Binding::BROWSER_DEFAULT_WEBGL:
824 break;
826 default: {
827 const nsPrintfCString text("Bad UNPACK_COLORSPACE_CONVERSION: %s",
828 EnumString(param).c_str());
829 return Some(webgl::ErrorInfo{LOCAL_GL_INVALID_VALUE, ToString(text)});
832 unpacking->colorspaceConversion = param;
833 return {};
835 case dom::MOZ_debug_Binding::UNPACK_REQUIRE_FASTPATH:
836 unpacking->requireFastPath = bool(param);
837 return {};
839 case LOCAL_GL_UNPACK_ALIGNMENT:
840 switch (param) {
841 case 1:
842 case 2:
843 case 4:
844 case 8:
845 break;
847 default: {
848 const nsPrintfCString text(
849 "UNPACK_ALIGNMENT must be [1,2,4,8], was %i", param);
850 return Some(webgl::ErrorInfo{LOCAL_GL_INVALID_VALUE, ToString(text)});
853 unpacking->alignmentInTypeElems = param;
854 return {};
856 default:
857 break;
859 const nsPrintfCString text("Bad `pname`: %s", EnumString(pname).c_str());
860 return Some(webgl::ErrorInfo{LOCAL_GL_INVALID_ENUM, ToString(text)});
863 bool WebGLContext::DoReadPixelsAndConvert(
864 const webgl::FormatInfo* const srcFormat, const webgl::ReadPixelsDesc& desc,
865 const uintptr_t dest, const uint64_t destSize, const uint32_t rowStride) {
866 const auto& x = desc.srcOffset.x;
867 const auto& y = desc.srcOffset.y;
868 const auto size = *ivec2::From(desc.size);
870 auto pi = desc.pi;
871 if (mRemapImplReadType_HalfFloatOes) {
872 if (pi.type == LOCAL_GL_HALF_FLOAT_OES) {
873 pi.type = LOCAL_GL_HALF_FLOAT;
877 // On at least Win+NV, we'll get PBO errors if we don't have at least
878 // `rowStride * height` bytes available to read into.
879 const auto naiveBytesNeeded = CheckedInt<uint64_t>(rowStride) * size.y;
880 const bool isDangerCloseToEdge =
881 (!naiveBytesNeeded.isValid() || naiveBytesNeeded.value() > destSize);
882 const bool useParanoidHandling =
883 (gl->WorkAroundDriverBugs() && isDangerCloseToEdge &&
884 mBoundPixelPackBuffer);
885 if (!useParanoidHandling) {
886 gl->fReadPixels(x, y, size.x, size.y, pi.format, pi.type,
887 reinterpret_cast<void*>(dest));
888 return true;
891 // Read everything but the last row.
892 const auto bodyHeight = size.y - 1;
893 if (bodyHeight) {
894 gl->fReadPixels(x, y, size.x, bodyHeight, pi.format, pi.type,
895 reinterpret_cast<void*>(dest));
898 // Now read the last row.
899 gl->fPixelStorei(LOCAL_GL_PACK_ALIGNMENT, 1);
900 gl->fPixelStorei(LOCAL_GL_PACK_ROW_LENGTH, 0);
901 gl->fPixelStorei(LOCAL_GL_PACK_SKIP_ROWS, 0);
903 const auto tailRowOffset =
904 reinterpret_cast<uint8_t*>(dest) + rowStride * bodyHeight;
905 gl->fReadPixels(x, y + bodyHeight, size.x, 1, pi.format, pi.type,
906 tailRowOffset);
908 return true;
911 webgl::ReadPixelsResult WebGLContext::ReadPixelsInto(
912 const webgl::ReadPixelsDesc& desc, const Range<uint8_t>& dest) {
913 const FuncScope funcScope(*this, "readPixels");
914 if (IsContextLost()) return {};
916 if (mBoundPixelPackBuffer) {
917 ErrorInvalidOperation("PIXEL_PACK_BUFFER must be null.");
918 return {};
921 return ReadPixelsImpl(desc, reinterpret_cast<uintptr_t>(dest.begin().get()),
922 dest.length());
925 void WebGLContext::ReadPixelsPbo(const webgl::ReadPixelsDesc& desc,
926 const uint64_t offset) {
927 const FuncScope funcScope(*this, "readPixels");
928 if (IsContextLost()) return;
930 const auto& buffer = ValidateBufferSelection(LOCAL_GL_PIXEL_PACK_BUFFER);
931 if (!buffer) return;
933 //////
936 const auto pii = webgl::PackingInfoInfo::For(desc.pi);
937 if (!pii) {
938 GLenum err = LOCAL_GL_INVALID_OPERATION;
939 if (!desc.pi.format || !desc.pi.type) {
940 err = LOCAL_GL_INVALID_ENUM;
942 GenerateError(err, "`format` (%s) and/or `type` (%s) not acceptable.",
943 EnumString(desc.pi.format).c_str(),
944 EnumString(desc.pi.type).c_str());
945 return;
948 if (offset % pii->bytesPerElement != 0) {
949 ErrorInvalidOperation(
950 "`offset` must be divisible by the size of `type`"
951 " in bytes.");
952 return;
956 //////
958 auto bytesAvailable = buffer->ByteLength();
959 if (offset > bytesAvailable) {
960 ErrorInvalidOperation("`offset` too large for bound PIXEL_PACK_BUFFER.");
961 return;
963 bytesAvailable -= offset;
965 // -
967 const ScopedLazyBind lazyBind(gl, LOCAL_GL_PIXEL_PACK_BUFFER, buffer);
969 ReadPixelsImpl(desc, offset, bytesAvailable);
971 buffer->ResetLastUpdateFenceId();
974 static webgl::PackingInfo DefaultReadPixelPI(
975 const webgl::FormatUsageInfo* usage) {
976 MOZ_ASSERT(usage->IsRenderable());
977 const auto& format = *usage->format;
978 switch (format.componentType) {
979 case webgl::ComponentType::NormUInt:
980 if (format.r == 16) {
981 return {LOCAL_GL_RGBA, LOCAL_GL_UNSIGNED_SHORT};
983 return {LOCAL_GL_RGBA, LOCAL_GL_UNSIGNED_BYTE};
985 case webgl::ComponentType::Int:
986 return {LOCAL_GL_RGBA_INTEGER, LOCAL_GL_INT};
988 case webgl::ComponentType::UInt:
989 return {LOCAL_GL_RGBA_INTEGER, LOCAL_GL_UNSIGNED_INT};
991 case webgl::ComponentType::Float:
992 return {LOCAL_GL_RGBA, LOCAL_GL_FLOAT};
994 default:
995 MOZ_CRASH();
999 static bool ArePossiblePackEnums(const webgl::PackingInfo& pi) {
1000 // OpenGL ES 2.0 $4.3.1 - IMPLEMENTATION_COLOR_READ_{TYPE/FORMAT} is a valid
1001 // combination for glReadPixels()...
1003 // Only valid when pulled from:
1004 // * GLES 2.0.25 p105:
1005 // "table 3.4, excluding formats LUMINANCE and LUMINANCE_ALPHA."
1006 // * GLES 3.0.4 p193:
1007 // "table 3.2, excluding formats DEPTH_COMPONENT and DEPTH_STENCIL."
1008 switch (pi.format) {
1009 case LOCAL_GL_LUMINANCE:
1010 case LOCAL_GL_LUMINANCE_ALPHA:
1011 case LOCAL_GL_DEPTH_COMPONENT:
1012 case LOCAL_GL_DEPTH_STENCIL:
1013 return false;
1016 if (pi.type == LOCAL_GL_UNSIGNED_INT_24_8) return false;
1018 const auto pii = webgl::PackingInfoInfo::For(pi);
1019 if (!pii) return false;
1021 return true;
1024 webgl::PackingInfo WebGLContext::ValidImplementationColorReadPI(
1025 const webgl::FormatUsageInfo* usage) const {
1026 const auto defaultPI = DefaultReadPixelPI(usage);
1028 // ES2_compatibility always returns RGBA/UNSIGNED_BYTE, so branch on actual
1029 // IsGLES(). Also OSX+NV generates an error here.
1030 if (!gl->IsGLES()) return defaultPI;
1032 webgl::PackingInfo implPI;
1033 gl->fGetIntegerv(LOCAL_GL_IMPLEMENTATION_COLOR_READ_FORMAT,
1034 (GLint*)&implPI.format);
1035 gl->fGetIntegerv(LOCAL_GL_IMPLEMENTATION_COLOR_READ_TYPE,
1036 (GLint*)&implPI.type);
1038 if (!IsWebGL2()) {
1039 if (implPI.type == LOCAL_GL_HALF_FLOAT) {
1040 mRemapImplReadType_HalfFloatOes = true;
1041 implPI.type = LOCAL_GL_HALF_FLOAT_OES;
1045 if (!ArePossiblePackEnums(implPI)) return defaultPI;
1047 return implPI;
1050 static bool ValidateReadPixelsFormatAndType(
1051 const webgl::FormatUsageInfo* srcUsage, const webgl::PackingInfo& pi,
1052 gl::GLContext* gl, WebGLContext* webgl) {
1053 if (!ArePossiblePackEnums(pi)) {
1054 webgl->ErrorInvalidEnum("Unexpected format or type.");
1055 return false;
1058 const auto defaultPI = DefaultReadPixelPI(srcUsage);
1059 if (pi == defaultPI) return true;
1061 ////
1063 // OpenGL ES 3.0.4 p194 - When the internal format of the rendering surface is
1064 // RGB10_A2, a third combination of format RGBA and type
1065 // UNSIGNED_INT_2_10_10_10_REV is accepted.
1067 if (webgl->IsWebGL2() &&
1068 srcUsage->format->effectiveFormat == webgl::EffectiveFormat::RGB10_A2 &&
1069 pi.format == LOCAL_GL_RGBA &&
1070 pi.type == LOCAL_GL_UNSIGNED_INT_2_10_10_10_REV) {
1071 return true;
1074 ////
1076 const auto implPI = webgl->ValidImplementationColorReadPI(srcUsage);
1077 if (pi == implPI) return true;
1079 ////
1081 // clang-format off
1082 webgl->ErrorInvalidOperation(
1083 "Format and type %s/%s incompatible with this %s attachment."
1084 " This framebuffer requires either %s/%s or"
1085 " getParameter(IMPLEMENTATION_COLOR_READ_FORMAT/_TYPE) %s/%s.",
1086 EnumString(pi.format).c_str(), EnumString(pi.type).c_str(),
1087 srcUsage->format->name,
1088 EnumString(defaultPI.format).c_str(), EnumString(defaultPI.type).c_str(),
1089 EnumString(implPI.format).c_str(), EnumString(implPI.type).c_str());
1090 // clang-format on
1092 return false;
1095 webgl::ReadPixelsResult WebGLContext::ReadPixelsImpl(
1096 const webgl::ReadPixelsDesc& desc, const uintptr_t dest,
1097 const uint64_t availBytes) {
1098 const webgl::FormatUsageInfo* srcFormat;
1099 uint32_t srcWidth;
1100 uint32_t srcHeight;
1101 if (!BindCurFBForColorRead(&srcFormat, &srcWidth, &srcHeight)) return {};
1103 //////
1105 if (!ValidateReadPixelsFormatAndType(srcFormat, desc.pi, gl, this)) return {};
1107 //////
1109 const auto& srcOffset = desc.srcOffset;
1110 const auto& size = desc.size;
1112 if (!ivec2::From(size)) {
1113 ErrorInvalidValue("width and height must be non-negative.");
1114 return {};
1117 const auto& packing = desc.packState;
1118 const auto explicitPackingRes = webgl::ExplicitPixelPackingState::ForUseWith(
1119 packing, LOCAL_GL_TEXTURE_2D, {size.x, size.y, 1}, desc.pi, {});
1120 if (!explicitPackingRes.isOk()) {
1121 ErrorInvalidOperation("%s", explicitPackingRes.inspectErr().c_str());
1122 return {};
1124 const auto& explicitPacking = explicitPackingRes.inspect();
1125 const auto& rowStride = explicitPacking.metrics.bytesPerRowStride;
1126 const auto& bytesNeeded = explicitPacking.metrics.totalBytesUsed;
1127 if (bytesNeeded > availBytes) {
1128 ErrorInvalidOperation("buffer too small");
1129 return {};
1132 ////
1134 int32_t readX, readY;
1135 int32_t writeX, writeY;
1136 int32_t rwWidth, rwHeight;
1137 if (!Intersect(srcWidth, srcOffset.x, size.x, &readX, &writeX, &rwWidth) ||
1138 !Intersect(srcHeight, srcOffset.y, size.y, &readY, &writeY, &rwHeight)) {
1139 ErrorOutOfMemory("Bad subrect selection.");
1140 return {};
1143 ////////////////
1144 // Now that the errors are out of the way, on to actually reading!
1146 gl->fPixelStorei(LOCAL_GL_PACK_ALIGNMENT, packing.alignmentInTypeElems);
1147 if (IsWebGL2()) {
1148 gl->fPixelStorei(LOCAL_GL_PACK_ROW_LENGTH, packing.rowLength);
1149 gl->fPixelStorei(LOCAL_GL_PACK_SKIP_PIXELS, packing.skipPixels);
1150 gl->fPixelStorei(LOCAL_GL_PACK_SKIP_ROWS, packing.skipRows);
1153 if (!rwWidth || !rwHeight) {
1154 // Disjoint rects, so we're done already.
1155 DummyReadFramebufferOperation();
1156 return {};
1158 const auto rwSize = *uvec2::From(rwWidth, rwHeight);
1160 const auto res = webgl::ReadPixelsResult{
1161 {{writeX, writeY}, {rwSize.x, rwSize.y}}, rowStride};
1163 if (rwSize == size) {
1164 DoReadPixelsAndConvert(srcFormat->format, desc, dest, bytesNeeded,
1165 rowStride);
1166 return res;
1169 // Read request contains out-of-bounds pixels. Unfortunately:
1170 // GLES 3.0.4 p194 "Obtaining Pixels from the Framebuffer":
1171 // "If any of these pixels lies outside of the window allocated to the current
1172 // GL context, or outside of the image attached to the currently bound
1173 // framebuffer object, then the values obtained for those pixels are
1174 // undefined."
1176 // This is a slow-path, so warn people away!
1177 GenerateWarning(
1178 "Out-of-bounds reads with readPixels are deprecated, and"
1179 " may be slow.");
1181 ////////////////////////////////////
1182 // Read only the in-bounds pixels.
1184 if (IsWebGL2()) {
1185 if (!packing.rowLength) {
1186 gl->fPixelStorei(LOCAL_GL_PACK_ROW_LENGTH, packing.skipPixels + size.x);
1188 gl->fPixelStorei(LOCAL_GL_PACK_SKIP_PIXELS, packing.skipPixels + writeX);
1189 gl->fPixelStorei(LOCAL_GL_PACK_SKIP_ROWS, packing.skipRows + writeY);
1191 auto desc2 = desc;
1192 desc2.srcOffset = {readX, readY};
1193 desc2.size = rwSize;
1195 DoReadPixelsAndConvert(srcFormat->format, desc2, dest, bytesNeeded,
1196 rowStride);
1197 } else {
1198 // I *did* say "hilariously slow".
1200 auto desc2 = desc;
1201 desc2.srcOffset = {readX, readY};
1202 desc2.size = {rwSize.x, 1};
1204 const auto skipBytes = writeX * explicitPacking.metrics.bytesPerPixel;
1205 const auto usedRowBytes = rwSize.x * explicitPacking.metrics.bytesPerPixel;
1206 for (const auto j : IntegerRange(rwSize.y)) {
1207 desc2.srcOffset.y = readY + j;
1208 const auto destWriteBegin = dest + skipBytes + (writeY + j) * rowStride;
1209 MOZ_RELEASE_ASSERT(dest <= destWriteBegin);
1210 MOZ_RELEASE_ASSERT(destWriteBegin <= dest + availBytes);
1212 const auto destWriteEnd = destWriteBegin + usedRowBytes;
1213 MOZ_RELEASE_ASSERT(dest <= destWriteEnd);
1214 MOZ_RELEASE_ASSERT(destWriteEnd <= dest + availBytes);
1216 DoReadPixelsAndConvert(srcFormat->format, desc2, destWriteBegin,
1217 destWriteEnd - destWriteBegin, rowStride);
1221 return res;
1224 void WebGLContext::RenderbufferStorageMultisample(WebGLRenderbuffer& rb,
1225 uint32_t samples,
1226 GLenum internalFormat,
1227 uint32_t width,
1228 uint32_t height) const {
1229 const FuncScope funcScope(*this, "renderbufferStorage(Multisample)?");
1230 if (IsContextLost()) return;
1232 rb.RenderbufferStorage(samples, internalFormat, width, height);
1235 void WebGLContext::Scissor(GLint x, GLint y, GLsizei width, GLsizei height) {
1236 const FuncScope funcScope(*this, "scissor");
1237 if (IsContextLost()) return;
1239 if (!ValidateNonNegative("width", width) ||
1240 !ValidateNonNegative("height", height)) {
1241 return;
1244 mScissorRect = {x, y, width, height};
1245 mScissorRect.Apply(*gl);
1248 void WebGLContext::StencilFuncSeparate(GLenum face, GLenum func, GLint ref,
1249 GLuint mask) {
1250 const FuncScope funcScope(*this, "stencilFuncSeparate");
1251 if (IsContextLost()) return;
1253 if (!ValidateFaceEnum(face) || !ValidateComparisonEnum(*this, func)) {
1254 return;
1257 switch (face) {
1258 case LOCAL_GL_FRONT_AND_BACK:
1259 mStencilRefFront = ref;
1260 mStencilRefBack = ref;
1261 mStencilValueMaskFront = mask;
1262 mStencilValueMaskBack = mask;
1263 break;
1264 case LOCAL_GL_FRONT:
1265 mStencilRefFront = ref;
1266 mStencilValueMaskFront = mask;
1267 break;
1268 case LOCAL_GL_BACK:
1269 mStencilRefBack = ref;
1270 mStencilValueMaskBack = mask;
1271 break;
1274 gl->fStencilFuncSeparate(face, func, ref, mask);
1277 void WebGLContext::StencilOpSeparate(GLenum face, GLenum sfail, GLenum dpfail,
1278 GLenum dppass) {
1279 const FuncScope funcScope(*this, "stencilOpSeparate");
1280 if (IsContextLost()) return;
1282 if (!ValidateFaceEnum(face) || !ValidateStencilOpEnum(sfail, "sfail") ||
1283 !ValidateStencilOpEnum(dpfail, "dpfail") ||
1284 !ValidateStencilOpEnum(dppass, "dppass"))
1285 return;
1287 gl->fStencilOpSeparate(face, sfail, dpfail, dppass);
1290 ////////////////////////////////////////////////////////////////////////////////
1291 // Uniform setters.
1293 void WebGLContext::UniformData(
1294 const uint32_t loc, const bool transpose,
1295 const Span<const webgl::UniformDataVal>& data) const {
1296 const FuncScope funcScope(*this, "uniform setter");
1298 if (!IsWebGL2() && transpose) {
1299 GenerateError(LOCAL_GL_INVALID_VALUE, "`transpose`:true requires WebGL 2.");
1300 return;
1303 // -
1305 const auto& link = mActiveProgramLinkInfo;
1306 if (!link) {
1307 GenerateError(LOCAL_GL_INVALID_OPERATION, "Active program is not linked.");
1308 return;
1311 const auto locInfo = MaybeFind(link->locationMap, loc);
1312 if (!locInfo) {
1313 // Null WebGLUniformLocations become -1, which will end up here.
1314 return;
1317 const auto& validationInfo = locInfo->info;
1318 const auto& activeInfo = validationInfo.info;
1319 const auto& channels = validationInfo.channelsPerElem;
1320 const auto& pfn = validationInfo.pfn;
1322 // -
1324 const auto lengthInType = data.size();
1325 const auto elemCount = lengthInType / channels;
1326 if (elemCount > 1 && !validationInfo.isArray) {
1327 GenerateError(
1328 LOCAL_GL_INVALID_OPERATION,
1329 "(uniform %s) `values` length (%u) must exactly match size of %s.",
1330 activeInfo.name.c_str(), (uint32_t)lengthInType,
1331 EnumString(activeInfo.elemType).c_str());
1332 return;
1335 // -
1337 const auto& samplerInfo = locInfo->samplerInfo;
1338 if (samplerInfo) {
1339 const auto idata = ReinterpretToSpan<const uint32_t>::From(data);
1340 const auto maxTexUnits = GLMaxTextureUnits();
1341 for (const auto& val : idata) {
1342 if (val >= maxTexUnits) {
1343 ErrorInvalidValue(
1344 "This uniform location is a sampler, but %d"
1345 " is not a valid texture unit.",
1346 val);
1347 return;
1352 // -
1354 // This is a little galaxy-brain, sorry!
1355 const auto ptr = static_cast<const void*>(data.data());
1356 (*pfn)(*gl, static_cast<GLint>(loc), elemCount, transpose, ptr);
1358 // -
1360 if (samplerInfo) {
1361 auto& texUnits = samplerInfo->texUnits;
1363 const auto srcBegin = reinterpret_cast<const uint32_t*>(data.data());
1364 auto destIndex = locInfo->indexIntoUniform;
1365 if (destIndex < texUnits.length()) {
1366 // Only sample as many indexes as available tex units allow.
1367 const auto destCount = std::min(elemCount, texUnits.length() - destIndex);
1368 for (const auto& val : Span<const uint32_t>(srcBegin, destCount)) {
1369 texUnits[destIndex] = AssertedCast<uint8_t>(val);
1370 destIndex += 1;
1376 ////////////////////////////////////////////////////////////////////////////////
1378 void WebGLContext::UseProgram(WebGLProgram* prog) {
1379 FuncScope funcScope(*this, "useProgram");
1380 if (IsContextLost()) return;
1381 funcScope.mBindFailureGuard = true;
1383 if (!prog) {
1384 mCurrentProgram = nullptr;
1385 mActiveProgramLinkInfo = nullptr;
1386 funcScope.mBindFailureGuard = false;
1387 return;
1390 if (!ValidateObject("prog", *prog)) return;
1392 if (!prog->UseProgram()) return;
1394 mCurrentProgram = prog;
1395 mActiveProgramLinkInfo = mCurrentProgram->LinkInfo();
1397 funcScope.mBindFailureGuard = false;
1400 bool WebGLContext::ValidateProgram(const WebGLProgram& prog) const {
1401 const FuncScope funcScope(*this, "validateProgram");
1402 if (IsContextLost()) return false;
1404 return prog.ValidateProgram();
1407 RefPtr<WebGLFramebuffer> WebGLContext::CreateFramebuffer() {
1408 const FuncScope funcScope(*this, "createFramebuffer");
1409 if (IsContextLost()) return nullptr;
1411 GLuint fbo = 0;
1412 gl->fGenFramebuffers(1, &fbo);
1414 return new WebGLFramebuffer(this, fbo);
1417 RefPtr<WebGLFramebuffer> WebGLContext::CreateOpaqueFramebuffer(
1418 const webgl::OpaqueFramebufferOptions& options) {
1419 const FuncScope funcScope(*this, "createOpaqueFramebuffer");
1420 if (IsContextLost()) return nullptr;
1422 uint32_t samples = options.antialias ? StaticPrefs::webgl_msaa_samples() : 0;
1423 samples = std::min(samples, gl->MaxSamples());
1424 const gfx::IntSize size = {options.width, options.height};
1426 auto fbo =
1427 gl::MozFramebuffer::Create(gl, size, samples, options.depthStencil);
1428 if (!fbo) {
1429 return nullptr;
1432 return new WebGLFramebuffer(this, std::move(fbo));
1435 RefPtr<WebGLRenderbuffer> WebGLContext::CreateRenderbuffer() {
1436 const FuncScope funcScope(*this, "createRenderbuffer");
1437 if (IsContextLost()) return nullptr;
1439 return new WebGLRenderbuffer(this);
1442 void WebGLContext::Viewport(GLint x, GLint y, GLsizei width, GLsizei height) {
1443 const FuncScope funcScope(*this, "viewport");
1444 if (IsContextLost()) return;
1446 if (!ValidateNonNegative("width", width) ||
1447 !ValidateNonNegative("height", height)) {
1448 return;
1451 const auto& limits = Limits();
1452 width = std::min(width, static_cast<GLsizei>(limits.maxViewportDim));
1453 height = std::min(height, static_cast<GLsizei>(limits.maxViewportDim));
1455 gl->fViewport(x, y, width, height);
1457 mViewportX = x;
1458 mViewportY = y;
1459 mViewportWidth = width;
1460 mViewportHeight = height;
1463 void WebGLContext::CompileShader(WebGLShader& shader) {
1464 const FuncScope funcScope(*this, "compileShader");
1465 if (IsContextLost()) return;
1467 if (!ValidateObject("shader", shader)) return;
1469 shader.CompileShader();
1472 Maybe<webgl::ShaderPrecisionFormat> WebGLContext::GetShaderPrecisionFormat(
1473 GLenum shadertype, GLenum precisiontype) const {
1474 const FuncScope funcScope(*this, "getShaderPrecisionFormat");
1475 if (IsContextLost()) return Nothing();
1477 switch (shadertype) {
1478 case LOCAL_GL_FRAGMENT_SHADER:
1479 case LOCAL_GL_VERTEX_SHADER:
1480 break;
1481 default:
1482 ErrorInvalidEnumInfo("shadertype", shadertype);
1483 return Nothing();
1486 switch (precisiontype) {
1487 case LOCAL_GL_LOW_FLOAT:
1488 case LOCAL_GL_MEDIUM_FLOAT:
1489 case LOCAL_GL_HIGH_FLOAT:
1490 case LOCAL_GL_LOW_INT:
1491 case LOCAL_GL_MEDIUM_INT:
1492 case LOCAL_GL_HIGH_INT:
1493 break;
1494 default:
1495 ErrorInvalidEnumInfo("precisiontype", precisiontype);
1496 return Nothing();
1499 GLint range[2], precision;
1501 if (mDisableFragHighP && shadertype == LOCAL_GL_FRAGMENT_SHADER &&
1502 (precisiontype == LOCAL_GL_HIGH_FLOAT ||
1503 precisiontype == LOCAL_GL_HIGH_INT)) {
1504 precision = 0;
1505 range[0] = 0;
1506 range[1] = 0;
1507 } else {
1508 gl->fGetShaderPrecisionFormat(shadertype, precisiontype, range, &precision);
1511 return Some(webgl::ShaderPrecisionFormat{range[0], range[1], precision});
1514 void WebGLContext::ShaderSource(WebGLShader& shader,
1515 const std::string& source) const {
1516 const FuncScope funcScope(*this, "shaderSource");
1517 if (IsContextLost()) return;
1519 shader.ShaderSource(source);
1522 void WebGLContext::BlendColor(GLfloat r, GLfloat g, GLfloat b, GLfloat a) {
1523 const FuncScope funcScope(*this, "blendColor");
1524 if (IsContextLost()) return;
1526 gl->fBlendColor(r, g, b, a);
1529 void WebGLContext::Flush() {
1530 const FuncScope funcScope(*this, "flush");
1531 if (IsContextLost()) return;
1533 gl->fFlush();
1536 void WebGLContext::Finish() {
1537 const FuncScope funcScope(*this, "finish");
1538 if (IsContextLost()) return;
1540 gl->fFinish();
1542 mCompletedFenceId = mNextFenceId;
1543 mNextFenceId += 1;
1546 void WebGLContext::LineWidth(GLfloat width) {
1547 const FuncScope funcScope(*this, "lineWidth");
1548 if (IsContextLost()) return;
1550 // Doing it this way instead of `if (width <= 0.0)` handles NaNs.
1551 const bool isValid = width > 0.0;
1552 if (!isValid) {
1553 ErrorInvalidValue("`width` must be positive and non-zero.");
1554 return;
1557 mLineWidth = width;
1559 if (gl->IsCoreProfile() && width > 1.0) {
1560 width = 1.0;
1563 gl->fLineWidth(width);
1566 void WebGLContext::PolygonOffset(GLfloat factor, GLfloat units) {
1567 const FuncScope funcScope(*this, "polygonOffset");
1568 if (IsContextLost()) return;
1570 gl->fPolygonOffset(factor, units);
1573 void WebGLContext::ProvokingVertex(const webgl::ProvokingVertex mode) const {
1574 const FuncScope funcScope(*this, "provokingVertex");
1575 if (IsContextLost()) return;
1576 MOZ_RELEASE_ASSERT(
1577 IsExtensionEnabled(WebGLExtensionID::WEBGL_provoking_vertex));
1579 gl->fProvokingVertex(UnderlyingValue(mode));
1582 void WebGLContext::SampleCoverage(GLclampf value, WebGLboolean invert) {
1583 const FuncScope funcScope(*this, "sampleCoverage");
1584 if (IsContextLost()) return;
1586 gl->fSampleCoverage(value, invert);
1589 } // namespace mozilla