Bug 1850713: remove duplicated setting of early hint preloader id in `ScriptLoader...
[gecko.git] / dom / canvas / WebGLContextGL.cpp
blob23c45779a8586b5cbdcec7972ff2fa6961beadd9
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 // needed to check if current OS is lower than 10.7
43 #if defined(MOZ_WIDGET_COCOA)
44 # include "nsCocoaFeatures.h"
45 #endif
47 #include "mozilla/DebugOnly.h"
48 #include "mozilla/dom/BindingUtils.h"
49 #include "mozilla/dom/ImageData.h"
50 #include "mozilla/dom/WebGLRenderingContextBinding.h"
51 #include "mozilla/EndianUtils.h"
52 #include "mozilla/RefPtr.h"
53 #include "mozilla/UniquePtrExtensions.h"
54 #include "mozilla/StaticPrefs_webgl.h"
56 namespace mozilla {
58 using namespace mozilla::dom;
59 using namespace mozilla::gfx;
60 using namespace mozilla::gl;
63 // WebGL API
66 void WebGLContext::ActiveTexture(uint32_t texUnit) {
67 FuncScope funcScope(*this, "activeTexture");
68 if (IsContextLost()) return;
69 funcScope.mBindFailureGuard = true;
71 if (texUnit >= Limits().maxTexUnits) {
72 return ErrorInvalidEnum("Texture unit %u out of range (%u).", texUnit,
73 Limits().maxTexUnits);
76 mActiveTexture = texUnit;
77 gl->fActiveTexture(LOCAL_GL_TEXTURE0 + texUnit);
79 funcScope.mBindFailureGuard = false;
82 void WebGLContext::AttachShader(WebGLProgram& prog, WebGLShader& shader) {
83 FuncScope funcScope(*this, "attachShader");
84 if (IsContextLost()) return;
85 funcScope.mBindFailureGuard = true;
87 prog.AttachShader(shader);
89 funcScope.mBindFailureGuard = false;
92 void WebGLContext::BindAttribLocation(WebGLProgram& prog, GLuint location,
93 const std::string& name) const {
94 const FuncScope funcScope(*this, "bindAttribLocation");
95 if (IsContextLost()) return;
97 prog.BindAttribLocation(location, name);
100 void WebGLContext::BindFramebuffer(GLenum target, WebGLFramebuffer* wfb) {
101 FuncScope funcScope(*this, "bindFramebuffer");
102 if (IsContextLost()) return;
103 funcScope.mBindFailureGuard = true;
105 if (!ValidateFramebufferTarget(target)) return;
107 if (!wfb) {
108 gl->fBindFramebuffer(target, 0);
109 } else {
110 GLuint framebuffername = wfb->mGLName;
111 gl->fBindFramebuffer(target, framebuffername);
112 wfb->mHasBeenBound = true;
115 switch (target) {
116 case LOCAL_GL_FRAMEBUFFER:
117 mBoundDrawFramebuffer = wfb;
118 mBoundReadFramebuffer = wfb;
119 break;
120 case LOCAL_GL_DRAW_FRAMEBUFFER:
121 mBoundDrawFramebuffer = wfb;
122 break;
123 case LOCAL_GL_READ_FRAMEBUFFER:
124 mBoundReadFramebuffer = wfb;
125 break;
126 default:
127 return;
129 funcScope.mBindFailureGuard = false;
132 void WebGLContext::BlendEquationSeparate(Maybe<GLuint> i, GLenum modeRGB,
133 GLenum modeAlpha) {
134 const FuncScope funcScope(*this, "blendEquationSeparate");
135 if (IsContextLost()) return;
137 if (!ValidateBlendEquationEnum(modeRGB, "modeRGB") ||
138 !ValidateBlendEquationEnum(modeAlpha, "modeAlpha")) {
139 return;
142 if (i) {
143 MOZ_RELEASE_ASSERT(
144 IsExtensionEnabled(WebGLExtensionID::OES_draw_buffers_indexed));
145 const auto limit = MaxValidDrawBuffers();
146 if (*i >= limit) {
147 ErrorInvalidValue("`index` (%u) must be < %s (%u)", *i,
148 "MAX_DRAW_BUFFERS", limit);
149 return;
152 gl->fBlendEquationSeparatei(*i, modeRGB, modeAlpha);
153 } else {
154 gl->fBlendEquationSeparate(modeRGB, modeAlpha);
158 static bool ValidateBlendFuncEnum(WebGLContext* webgl, GLenum factor,
159 const char* varName) {
160 switch (factor) {
161 case LOCAL_GL_ZERO:
162 case LOCAL_GL_ONE:
163 case LOCAL_GL_SRC_COLOR:
164 case LOCAL_GL_ONE_MINUS_SRC_COLOR:
165 case LOCAL_GL_DST_COLOR:
166 case LOCAL_GL_ONE_MINUS_DST_COLOR:
167 case LOCAL_GL_SRC_ALPHA:
168 case LOCAL_GL_ONE_MINUS_SRC_ALPHA:
169 case LOCAL_GL_DST_ALPHA:
170 case LOCAL_GL_ONE_MINUS_DST_ALPHA:
171 case LOCAL_GL_CONSTANT_COLOR:
172 case LOCAL_GL_ONE_MINUS_CONSTANT_COLOR:
173 case LOCAL_GL_CONSTANT_ALPHA:
174 case LOCAL_GL_ONE_MINUS_CONSTANT_ALPHA:
175 case LOCAL_GL_SRC_ALPHA_SATURATE:
176 return true;
178 default:
179 webgl->ErrorInvalidEnumInfo(varName, factor);
180 return false;
184 static bool ValidateBlendFuncEnums(WebGLContext* webgl, GLenum srcRGB,
185 GLenum srcAlpha, GLenum dstRGB,
186 GLenum dstAlpha) {
187 if (!webgl->IsWebGL2()) {
188 if (dstRGB == LOCAL_GL_SRC_ALPHA_SATURATE ||
189 dstAlpha == LOCAL_GL_SRC_ALPHA_SATURATE) {
190 webgl->ErrorInvalidEnum(
191 "LOCAL_GL_SRC_ALPHA_SATURATE as a destination"
192 " blend function is disallowed in WebGL 1 (dstRGB ="
193 " 0x%04x, dstAlpha = 0x%04x).",
194 dstRGB, dstAlpha);
195 return false;
199 if (!ValidateBlendFuncEnum(webgl, srcRGB, "srcRGB") ||
200 !ValidateBlendFuncEnum(webgl, srcAlpha, "srcAlpha") ||
201 !ValidateBlendFuncEnum(webgl, dstRGB, "dstRGB") ||
202 !ValidateBlendFuncEnum(webgl, dstAlpha, "dstAlpha")) {
203 return false;
206 return true;
209 void WebGLContext::BlendFuncSeparate(Maybe<GLuint> i, GLenum srcRGB,
210 GLenum dstRGB, GLenum srcAlpha,
211 GLenum dstAlpha) {
212 const FuncScope funcScope(*this, "blendFuncSeparate");
213 if (IsContextLost()) return;
215 if (!ValidateBlendFuncEnums(this, srcRGB, srcAlpha, dstRGB, dstAlpha)) return;
217 // note that we only check compatibity for the RGB enums, no need to for the
218 // Alpha enums, see "Section 6.8 forgetting to mention alpha factors?" thread
219 // on the public_webgl mailing list
220 if (!ValidateBlendFuncEnumsCompatibility(srcRGB, dstRGB, "srcRGB and dstRGB"))
221 return;
223 if (i) {
224 MOZ_RELEASE_ASSERT(
225 IsExtensionEnabled(WebGLExtensionID::OES_draw_buffers_indexed));
226 const auto limit = MaxValidDrawBuffers();
227 if (*i >= limit) {
228 ErrorInvalidValue("`index` (%u) must be < %s (%u)", *i,
229 "MAX_DRAW_BUFFERS", limit);
230 return;
233 gl->fBlendFuncSeparatei(*i, srcRGB, dstRGB, srcAlpha, dstAlpha);
234 } else {
235 gl->fBlendFuncSeparate(srcRGB, dstRGB, srcAlpha, dstAlpha);
239 GLenum WebGLContext::CheckFramebufferStatus(GLenum target) {
240 const FuncScope funcScope(*this, "checkFramebufferStatus");
241 if (IsContextLost()) return LOCAL_GL_FRAMEBUFFER_UNSUPPORTED;
243 if (!ValidateFramebufferTarget(target)) return 0;
245 WebGLFramebuffer* fb;
246 switch (target) {
247 case LOCAL_GL_FRAMEBUFFER:
248 case LOCAL_GL_DRAW_FRAMEBUFFER:
249 fb = mBoundDrawFramebuffer;
250 break;
252 case LOCAL_GL_READ_FRAMEBUFFER:
253 fb = mBoundReadFramebuffer;
254 break;
256 default:
257 MOZ_CRASH("GFX: Bad target.");
260 if (!fb) return LOCAL_GL_FRAMEBUFFER_COMPLETE;
262 return fb->CheckFramebufferStatus().get();
265 RefPtr<WebGLProgram> WebGLContext::CreateProgram() {
266 const FuncScope funcScope(*this, "createProgram");
267 if (IsContextLost()) return nullptr;
269 return new WebGLProgram(this);
272 RefPtr<WebGLShader> WebGLContext::CreateShader(GLenum type) {
273 const FuncScope funcScope(*this, "createShader");
274 if (IsContextLost()) return nullptr;
276 if (type != LOCAL_GL_VERTEX_SHADER && type != LOCAL_GL_FRAGMENT_SHADER) {
277 ErrorInvalidEnumInfo("type", type);
278 return nullptr;
281 return new WebGLShader(this, type);
284 void WebGLContext::CullFace(GLenum face) {
285 const FuncScope funcScope(*this, "cullFace");
286 if (IsContextLost()) return;
288 if (!ValidateFaceEnum(face)) return;
290 gl->fCullFace(face);
293 void WebGLContext::DetachShader(WebGLProgram& prog, const WebGLShader& shader) {
294 FuncScope funcScope(*this, "detachShader");
295 if (IsContextLost()) return;
296 funcScope.mBindFailureGuard = true;
298 prog.DetachShader(shader);
300 funcScope.mBindFailureGuard = false;
303 static bool ValidateComparisonEnum(WebGLContext& webgl, const GLenum func) {
304 switch (func) {
305 case LOCAL_GL_NEVER:
306 case LOCAL_GL_LESS:
307 case LOCAL_GL_LEQUAL:
308 case LOCAL_GL_GREATER:
309 case LOCAL_GL_GEQUAL:
310 case LOCAL_GL_EQUAL:
311 case LOCAL_GL_NOTEQUAL:
312 case LOCAL_GL_ALWAYS:
313 return true;
315 default:
316 webgl.ErrorInvalidEnumInfo("func", func);
317 return false;
321 void WebGLContext::DepthFunc(GLenum func) {
322 const FuncScope funcScope(*this, "depthFunc");
323 if (IsContextLost()) return;
325 if (!ValidateComparisonEnum(*this, func)) return;
327 gl->fDepthFunc(func);
330 void WebGLContext::DepthRange(GLfloat zNear, GLfloat zFar) {
331 const FuncScope funcScope(*this, "depthRange");
332 if (IsContextLost()) return;
334 if (zNear > zFar)
335 return ErrorInvalidOperation(
336 "the near value is greater than the far value!");
338 gl->fDepthRange(zNear, zFar);
341 // -
343 void WebGLContext::FramebufferAttach(const GLenum target,
344 const GLenum attachSlot,
345 const GLenum bindImageTarget,
346 const webgl::FbAttachInfo& toAttach) {
347 FuncScope funcScope(*this, "framebufferAttach");
348 funcScope.mBindFailureGuard = true;
349 const auto& limits = *mLimits;
351 if (!ValidateFramebufferTarget(target)) return;
353 auto fb = mBoundDrawFramebuffer;
354 if (target == LOCAL_GL_READ_FRAMEBUFFER) {
355 fb = mBoundReadFramebuffer;
357 if (!fb) return;
359 // `rb` needs no validation.
361 // `tex`
362 const auto& tex = toAttach.tex;
363 if (tex) {
364 const auto err = CheckFramebufferAttach(bindImageTarget, tex->mTarget.get(),
365 toAttach.mipLevel, toAttach.zLayer,
366 toAttach.zLayerCount, limits);
367 if (err) return;
370 auto safeToAttach = toAttach;
371 if (!toAttach.rb && !toAttach.tex) {
372 safeToAttach = {};
374 if (!IsWebGL2() &&
375 !IsExtensionEnabled(WebGLExtensionID::OES_fbo_render_mipmap)) {
376 safeToAttach.mipLevel = 0;
378 if (!IsExtensionEnabled(WebGLExtensionID::OVR_multiview2)) {
379 safeToAttach.isMultiview = false;
382 if (!fb->FramebufferAttach(attachSlot, safeToAttach)) return;
384 funcScope.mBindFailureGuard = false;
387 // -
389 void WebGLContext::FrontFace(GLenum mode) {
390 const FuncScope funcScope(*this, "frontFace");
391 if (IsContextLost()) return;
393 switch (mode) {
394 case LOCAL_GL_CW:
395 case LOCAL_GL_CCW:
396 break;
397 default:
398 return ErrorInvalidEnumInfo("mode", mode);
401 gl->fFrontFace(mode);
404 Maybe<double> WebGLContext::GetBufferParameter(GLenum target, GLenum pname) {
405 const FuncScope funcScope(*this, "getBufferParameter");
406 if (IsContextLost()) return Nothing();
408 const auto& slot = ValidateBufferSlot(target);
409 if (!slot) return Nothing();
410 const auto& buffer = *slot;
412 if (!buffer) {
413 ErrorInvalidOperation("Buffer for `target` is null.");
414 return Nothing();
417 switch (pname) {
418 case LOCAL_GL_BUFFER_SIZE:
419 return Some(buffer->ByteLength());
421 case LOCAL_GL_BUFFER_USAGE:
422 return Some(buffer->Usage());
424 default:
425 ErrorInvalidEnumInfo("pname", pname);
426 return Nothing();
430 Maybe<double> WebGLContext::GetFramebufferAttachmentParameter(
431 WebGLFramebuffer* const fb, GLenum attachment, GLenum pname) const {
432 const FuncScope funcScope(*this, "getFramebufferAttachmentParameter");
433 if (IsContextLost()) return Nothing();
435 if (fb) return fb->GetAttachmentParameter(attachment, pname);
437 ////////////////////////////////////
439 if (!IsWebGL2()) {
440 ErrorInvalidOperation(
441 "Querying against the default framebuffer is not"
442 " allowed in WebGL 1.");
443 return Nothing();
446 switch (attachment) {
447 case LOCAL_GL_BACK:
448 case LOCAL_GL_DEPTH:
449 case LOCAL_GL_STENCIL:
450 break;
452 default:
453 ErrorInvalidEnum(
454 "For the default framebuffer, can only query COLOR, DEPTH,"
455 " or STENCIL.");
456 return Nothing();
459 switch (pname) {
460 case LOCAL_GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE:
461 switch (attachment) {
462 case LOCAL_GL_BACK:
463 break;
464 case LOCAL_GL_DEPTH:
465 if (!mOptions.depth) {
466 return Some(LOCAL_GL_NONE);
468 break;
469 case LOCAL_GL_STENCIL:
470 if (!mOptions.stencil) {
471 return Some(LOCAL_GL_NONE);
473 break;
474 default:
475 ErrorInvalidEnum(
476 "With the default framebuffer, can only query COLOR, DEPTH,"
477 " or STENCIL for GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE");
478 return Nothing();
480 return Some(LOCAL_GL_FRAMEBUFFER_DEFAULT);
482 ////////////////
484 case LOCAL_GL_FRAMEBUFFER_ATTACHMENT_RED_SIZE:
485 case LOCAL_GL_FRAMEBUFFER_ATTACHMENT_GREEN_SIZE:
486 case LOCAL_GL_FRAMEBUFFER_ATTACHMENT_BLUE_SIZE:
487 if (attachment == LOCAL_GL_BACK) return Some(8);
488 return Some(0);
490 case LOCAL_GL_FRAMEBUFFER_ATTACHMENT_ALPHA_SIZE:
491 if (attachment == LOCAL_GL_BACK) {
492 if (mOptions.alpha) {
493 return Some(8);
495 ErrorInvalidOperation(
496 "The default framebuffer doesn't contain an alpha buffer");
497 return Nothing();
499 return Some(0);
501 case LOCAL_GL_FRAMEBUFFER_ATTACHMENT_DEPTH_SIZE:
502 if (attachment == LOCAL_GL_DEPTH) {
503 if (mOptions.depth) {
504 return Some(24);
506 ErrorInvalidOperation(
507 "The default framebuffer doesn't contain an depth buffer");
508 return Nothing();
510 return Some(0);
512 case LOCAL_GL_FRAMEBUFFER_ATTACHMENT_STENCIL_SIZE:
513 if (attachment == LOCAL_GL_STENCIL) {
514 if (mOptions.stencil) {
515 return Some(8);
517 ErrorInvalidOperation(
518 "The default framebuffer doesn't contain an stencil buffer");
519 return Nothing();
521 return Some(0);
523 case LOCAL_GL_FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE:
524 if (attachment == LOCAL_GL_STENCIL) {
525 if (mOptions.stencil) {
526 return Some(LOCAL_GL_UNSIGNED_INT);
528 ErrorInvalidOperation(
529 "The default framebuffer doesn't contain an stencil buffer");
530 } else if (attachment == LOCAL_GL_DEPTH) {
531 if (mOptions.depth) {
532 return Some(LOCAL_GL_UNSIGNED_NORMALIZED);
534 ErrorInvalidOperation(
535 "The default framebuffer doesn't contain an depth buffer");
536 } else { // LOCAL_GL_BACK
537 return Some(LOCAL_GL_UNSIGNED_NORMALIZED);
539 return Nothing();
541 case LOCAL_GL_FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING:
542 if (attachment == LOCAL_GL_STENCIL) {
543 if (!mOptions.stencil) {
544 ErrorInvalidOperation(
545 "The default framebuffer doesn't contain an stencil buffer");
546 return Nothing();
548 } else if (attachment == LOCAL_GL_DEPTH) {
549 if (!mOptions.depth) {
550 ErrorInvalidOperation(
551 "The default framebuffer doesn't contain an depth buffer");
552 return Nothing();
555 return Some(LOCAL_GL_LINEAR);
558 ErrorInvalidEnumInfo("pname", pname);
559 return Nothing();
562 Maybe<double> WebGLContext::GetRenderbufferParameter(
563 const WebGLRenderbuffer& rb, GLenum pname) const {
564 const FuncScope funcScope(*this, "getRenderbufferParameter");
565 if (IsContextLost()) return Nothing();
567 switch (pname) {
568 case LOCAL_GL_RENDERBUFFER_SAMPLES:
569 if (!IsWebGL2()) break;
570 [[fallthrough]];
572 case LOCAL_GL_RENDERBUFFER_WIDTH:
573 case LOCAL_GL_RENDERBUFFER_HEIGHT:
574 case LOCAL_GL_RENDERBUFFER_RED_SIZE:
575 case LOCAL_GL_RENDERBUFFER_GREEN_SIZE:
576 case LOCAL_GL_RENDERBUFFER_BLUE_SIZE:
577 case LOCAL_GL_RENDERBUFFER_ALPHA_SIZE:
578 case LOCAL_GL_RENDERBUFFER_DEPTH_SIZE:
579 case LOCAL_GL_RENDERBUFFER_STENCIL_SIZE:
580 case LOCAL_GL_RENDERBUFFER_INTERNAL_FORMAT: {
581 // RB emulation means we have to ask the RB itself.
582 GLint i = rb.GetRenderbufferParameter(pname);
583 return Some(i);
586 default:
587 break;
590 ErrorInvalidEnumInfo("pname", pname);
591 return Nothing();
594 RefPtr<WebGLTexture> WebGLContext::CreateTexture() {
595 const FuncScope funcScope(*this, "createTexture");
596 if (IsContextLost()) return nullptr;
598 GLuint tex = 0;
599 gl->fGenTextures(1, &tex);
601 return new WebGLTexture(this, tex);
604 GLenum WebGLContext::GetError() {
605 const FuncScope funcScope(*this, "getError");
607 /* WebGL 1.0: Section 5.14.3: Setting and getting state:
608 * If the context's webgl context lost flag is set, returns
609 * CONTEXT_LOST_WEBGL the first time this method is called.
610 * Afterward, returns NO_ERROR until the context has been
611 * restored.
613 * WEBGL_lose_context:
614 * [When this extension is enabled: ] loseContext and
615 * restoreContext are allowed to generate INVALID_OPERATION errors
616 * even when the context is lost.
619 auto err = mWebGLError;
620 mWebGLError = 0;
621 if (IsContextLost() || err) // Must check IsContextLost in all flow paths.
622 return err;
624 // Either no WebGL-side error, or it's already been cleared.
625 // UnderlyingGL-side errors, now.
626 err = gl->fGetError();
627 if (gl->IsContextLost()) {
628 CheckForContextLoss();
629 return GetError();
631 MOZ_ASSERT(err != LOCAL_GL_CONTEXT_LOST);
633 if (err) {
634 GenerateWarning("Driver error unexpected by WebGL: 0x%04x", err);
635 // This might be:
636 // - INVALID_OPERATION from ANGLE due to incomplete RBAB implementation for
637 // DrawElements
638 // with DYNAMIC_DRAW index buffer.
640 return err;
643 webgl::GetUniformData WebGLContext::GetUniform(const WebGLProgram& prog,
644 const uint32_t loc) const {
645 const FuncScope funcScope(*this, "getUniform");
646 webgl::GetUniformData ret;
647 [&]() {
648 if (IsContextLost()) return;
650 const auto& info = prog.LinkInfo();
651 if (!info) return;
653 const auto locInfo = MaybeFind(info->locationMap, loc);
654 if (!locInfo) return;
656 ret.type = locInfo->info.info.elemType;
657 switch (ret.type) {
658 case LOCAL_GL_FLOAT:
659 case LOCAL_GL_FLOAT_VEC2:
660 case LOCAL_GL_FLOAT_VEC3:
661 case LOCAL_GL_FLOAT_VEC4:
662 case LOCAL_GL_FLOAT_MAT2:
663 case LOCAL_GL_FLOAT_MAT3:
664 case LOCAL_GL_FLOAT_MAT4:
665 case LOCAL_GL_FLOAT_MAT2x3:
666 case LOCAL_GL_FLOAT_MAT2x4:
667 case LOCAL_GL_FLOAT_MAT3x2:
668 case LOCAL_GL_FLOAT_MAT3x4:
669 case LOCAL_GL_FLOAT_MAT4x2:
670 case LOCAL_GL_FLOAT_MAT4x3:
671 gl->fGetUniformfv(prog.mGLName, loc,
672 reinterpret_cast<float*>(ret.data));
673 break;
675 case LOCAL_GL_INT:
676 case LOCAL_GL_INT_VEC2:
677 case LOCAL_GL_INT_VEC3:
678 case LOCAL_GL_INT_VEC4:
679 case LOCAL_GL_SAMPLER_2D:
680 case LOCAL_GL_SAMPLER_3D:
681 case LOCAL_GL_SAMPLER_CUBE:
682 case LOCAL_GL_SAMPLER_2D_SHADOW:
683 case LOCAL_GL_SAMPLER_2D_ARRAY:
684 case LOCAL_GL_SAMPLER_2D_ARRAY_SHADOW:
685 case LOCAL_GL_SAMPLER_CUBE_SHADOW:
686 case LOCAL_GL_INT_SAMPLER_2D:
687 case LOCAL_GL_INT_SAMPLER_3D:
688 case LOCAL_GL_INT_SAMPLER_CUBE:
689 case LOCAL_GL_INT_SAMPLER_2D_ARRAY:
690 case LOCAL_GL_UNSIGNED_INT_SAMPLER_2D:
691 case LOCAL_GL_UNSIGNED_INT_SAMPLER_3D:
692 case LOCAL_GL_UNSIGNED_INT_SAMPLER_CUBE:
693 case LOCAL_GL_UNSIGNED_INT_SAMPLER_2D_ARRAY:
694 case LOCAL_GL_BOOL:
695 case LOCAL_GL_BOOL_VEC2:
696 case LOCAL_GL_BOOL_VEC3:
697 case LOCAL_GL_BOOL_VEC4:
698 gl->fGetUniformiv(prog.mGLName, loc,
699 reinterpret_cast<int32_t*>(ret.data));
700 break;
702 case LOCAL_GL_UNSIGNED_INT:
703 case LOCAL_GL_UNSIGNED_INT_VEC2:
704 case LOCAL_GL_UNSIGNED_INT_VEC3:
705 case LOCAL_GL_UNSIGNED_INT_VEC4:
706 gl->fGetUniformuiv(prog.mGLName, loc,
707 reinterpret_cast<uint32_t*>(ret.data));
708 break;
710 default:
711 MOZ_CRASH("GFX: Invalid elemType.");
713 }();
714 return ret;
717 void WebGLContext::Hint(GLenum target, GLenum mode) {
718 const FuncScope funcScope(*this, "hint");
719 if (IsContextLost()) return;
721 switch (mode) {
722 case LOCAL_GL_FASTEST:
723 case LOCAL_GL_NICEST:
724 case LOCAL_GL_DONT_CARE:
725 break;
726 default:
727 return ErrorInvalidEnumArg("mode", mode);
730 // -
732 bool isValid = false;
734 switch (target) {
735 case LOCAL_GL_GENERATE_MIPMAP_HINT:
736 mGenerateMipmapHint = mode;
737 isValid = true;
739 // Deprecated and removed in desktop GL Core profiles.
740 if (gl->IsCoreProfile()) return;
742 break;
744 case LOCAL_GL_FRAGMENT_SHADER_DERIVATIVE_HINT:
745 if (IsWebGL2() ||
746 IsExtensionEnabled(WebGLExtensionID::OES_standard_derivatives)) {
747 isValid = true;
749 break;
751 if (!isValid) return ErrorInvalidEnumInfo("target", target);
753 // -
755 gl->fHint(target, mode);
758 // -
760 void WebGLContext::LinkProgram(WebGLProgram& prog) {
761 const FuncScope funcScope(*this, "linkProgram");
762 if (IsContextLost()) return;
764 prog.LinkProgram();
766 if (&prog == mCurrentProgram) {
767 if (!prog.IsLinked()) {
768 // We use to simply early-out here, and preserve the GL behavior that
769 // failed relink doesn't invalidate the current active program link info.
770 // The new behavior was changed for WebGL here:
771 // https://github.com/KhronosGroup/WebGL/pull/3371
772 mActiveProgramLinkInfo = nullptr;
773 gl->fUseProgram(0); // Shouldn't be needed, but let's be safe.
774 return;
776 mActiveProgramLinkInfo = prog.LinkInfo();
777 gl->fUseProgram(prog.mGLName); // Uncontionally re-use.
778 // Previously, we needed this re-use on nvidia as a driver workaround,
779 // but we might as well do it unconditionally.
783 Maybe<webgl::ErrorInfo> SetPixelUnpack(
784 const bool isWebgl2, webgl::PixelUnpackStateWebgl* const unpacking,
785 const GLenum pname, const GLint param) {
786 if (isWebgl2) {
787 uint32_t* pValueSlot = nullptr;
788 switch (pname) {
789 case LOCAL_GL_UNPACK_IMAGE_HEIGHT:
790 pValueSlot = &unpacking->imageHeight;
791 break;
793 case LOCAL_GL_UNPACK_SKIP_IMAGES:
794 pValueSlot = &unpacking->skipImages;
795 break;
797 case LOCAL_GL_UNPACK_ROW_LENGTH:
798 pValueSlot = &unpacking->rowLength;
799 break;
801 case LOCAL_GL_UNPACK_SKIP_ROWS:
802 pValueSlot = &unpacking->skipRows;
803 break;
805 case LOCAL_GL_UNPACK_SKIP_PIXELS:
806 pValueSlot = &unpacking->skipPixels;
807 break;
810 if (pValueSlot) {
811 *pValueSlot = static_cast<uint32_t>(param);
812 return {};
816 switch (pname) {
817 case dom::WebGLRenderingContext_Binding::UNPACK_FLIP_Y_WEBGL:
818 unpacking->flipY = bool(param);
819 return {};
821 case dom::WebGLRenderingContext_Binding::UNPACK_PREMULTIPLY_ALPHA_WEBGL:
822 unpacking->premultiplyAlpha = bool(param);
823 return {};
825 case dom::WebGLRenderingContext_Binding::UNPACK_COLORSPACE_CONVERSION_WEBGL:
826 switch (param) {
827 case LOCAL_GL_NONE:
828 case dom::WebGLRenderingContext_Binding::BROWSER_DEFAULT_WEBGL:
829 break;
831 default: {
832 const nsPrintfCString text("Bad UNPACK_COLORSPACE_CONVERSION: %s",
833 EnumString(param).c_str());
834 return Some(webgl::ErrorInfo{LOCAL_GL_INVALID_VALUE, ToString(text)});
837 unpacking->colorspaceConversion = param;
838 return {};
840 case dom::MOZ_debug_Binding::UNPACK_REQUIRE_FASTPATH:
841 unpacking->requireFastPath = bool(param);
842 return {};
844 case LOCAL_GL_UNPACK_ALIGNMENT:
845 switch (param) {
846 case 1:
847 case 2:
848 case 4:
849 case 8:
850 break;
852 default: {
853 const nsPrintfCString text(
854 "UNPACK_ALIGNMENT must be [1,2,4,8], was %i", param);
855 return Some(webgl::ErrorInfo{LOCAL_GL_INVALID_VALUE, ToString(text)});
858 unpacking->alignmentInTypeElems = param;
859 return {};
861 default:
862 break;
864 const nsPrintfCString text("Bad `pname`: %s", EnumString(pname).c_str());
865 return Some(webgl::ErrorInfo{LOCAL_GL_INVALID_ENUM, ToString(text)});
868 bool WebGLContext::DoReadPixelsAndConvert(
869 const webgl::FormatInfo* const srcFormat, const webgl::ReadPixelsDesc& desc,
870 const uintptr_t dest, const uint64_t destSize, const uint32_t rowStride) {
871 const auto& x = desc.srcOffset.x;
872 const auto& y = desc.srcOffset.y;
873 const auto size = *ivec2::From(desc.size);
874 const auto& pi = desc.pi;
876 // On at least Win+NV, we'll get PBO errors if we don't have at least
877 // `rowStride * height` bytes available to read into.
878 const auto naiveBytesNeeded = CheckedInt<uint64_t>(rowStride) * size.y;
879 const bool isDangerCloseToEdge =
880 (!naiveBytesNeeded.isValid() || naiveBytesNeeded.value() > destSize);
881 const bool useParanoidHandling =
882 (gl->WorkAroundDriverBugs() && isDangerCloseToEdge &&
883 mBoundPixelPackBuffer);
884 if (!useParanoidHandling) {
885 gl->fReadPixels(x, y, size.x, size.y, pi.format, pi.type,
886 reinterpret_cast<void*>(dest));
887 return true;
890 // Read everything but the last row.
891 const auto bodyHeight = size.y - 1;
892 if (bodyHeight) {
893 gl->fReadPixels(x, y, size.x, bodyHeight, pi.format, pi.type,
894 reinterpret_cast<void*>(dest));
897 // Now read the last row.
898 gl->fPixelStorei(LOCAL_GL_PACK_ALIGNMENT, 1);
899 gl->fPixelStorei(LOCAL_GL_PACK_ROW_LENGTH, 0);
900 gl->fPixelStorei(LOCAL_GL_PACK_SKIP_ROWS, 0);
902 const auto tailRowOffset =
903 reinterpret_cast<uint8_t*>(dest) + rowStride * bodyHeight;
904 gl->fReadPixels(x, y + bodyHeight, size.x, 1, pi.format, pi.type,
905 tailRowOffset);
907 return true;
910 webgl::ReadPixelsResult WebGLContext::ReadPixelsInto(
911 const webgl::ReadPixelsDesc& desc, const Range<uint8_t>& dest) {
912 const FuncScope funcScope(*this, "readPixels");
913 if (IsContextLost()) return {};
915 if (mBoundPixelPackBuffer) {
916 ErrorInvalidOperation("PIXEL_PACK_BUFFER must be null.");
917 return {};
920 return ReadPixelsImpl(desc, reinterpret_cast<uintptr_t>(dest.begin().get()),
921 dest.length());
924 void WebGLContext::ReadPixelsPbo(const webgl::ReadPixelsDesc& desc,
925 const uint64_t offset) {
926 const FuncScope funcScope(*this, "readPixels");
927 if (IsContextLost()) return;
929 const auto& buffer = ValidateBufferSelection(LOCAL_GL_PIXEL_PACK_BUFFER);
930 if (!buffer) return;
932 //////
935 const auto pii = webgl::PackingInfoInfo::For(desc.pi);
936 if (!pii) {
937 GLenum err = LOCAL_GL_INVALID_OPERATION;
938 if (!desc.pi.format || !desc.pi.type) {
939 err = LOCAL_GL_INVALID_ENUM;
941 GenerateError(err, "`format` (%s) and/or `type` (%s) not acceptable.",
942 EnumString(desc.pi.format).c_str(),
943 EnumString(desc.pi.type).c_str());
944 return;
947 if (offset % pii->bytesPerElement != 0) {
948 ErrorInvalidOperation(
949 "`offset` must be divisible by the size of `type`"
950 " in bytes.");
951 return;
955 //////
957 auto bytesAvailable = buffer->ByteLength();
958 if (offset > bytesAvailable) {
959 ErrorInvalidOperation("`offset` too large for bound PIXEL_PACK_BUFFER.");
960 return;
962 bytesAvailable -= offset;
964 // -
966 const ScopedLazyBind lazyBind(gl, LOCAL_GL_PIXEL_PACK_BUFFER, buffer);
968 ReadPixelsImpl(desc, offset, bytesAvailable);
970 buffer->ResetLastUpdateFenceId();
973 static webgl::PackingInfo DefaultReadPixelPI(
974 const webgl::FormatUsageInfo* usage) {
975 MOZ_ASSERT(usage->IsRenderable());
976 const auto& format = *usage->format;
977 switch (format.componentType) {
978 case webgl::ComponentType::NormUInt:
979 if (format.r == 16) {
980 return {LOCAL_GL_RGBA, LOCAL_GL_UNSIGNED_SHORT};
982 return {LOCAL_GL_RGBA, LOCAL_GL_UNSIGNED_BYTE};
984 case webgl::ComponentType::Int:
985 return {LOCAL_GL_RGBA_INTEGER, LOCAL_GL_INT};
987 case webgl::ComponentType::UInt:
988 return {LOCAL_GL_RGBA_INTEGER, LOCAL_GL_UNSIGNED_INT};
990 case webgl::ComponentType::Float:
991 return {LOCAL_GL_RGBA, LOCAL_GL_FLOAT};
993 default:
994 MOZ_CRASH();
998 static bool ArePossiblePackEnums(const WebGLContext* webgl,
999 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 (!ArePossiblePackEnums(this, implPI)) return defaultPI;
1040 return implPI;
1043 static bool ValidateReadPixelsFormatAndType(
1044 const webgl::FormatUsageInfo* srcUsage, const webgl::PackingInfo& pi,
1045 gl::GLContext* gl, WebGLContext* webgl) {
1046 if (!ArePossiblePackEnums(webgl, pi)) {
1047 webgl->ErrorInvalidEnum("Unexpected format or type.");
1048 return false;
1051 const auto defaultPI = DefaultReadPixelPI(srcUsage);
1052 if (pi == defaultPI) return true;
1054 ////
1056 // OpenGL ES 3.0.4 p194 - When the internal format of the rendering surface is
1057 // RGB10_A2, a third combination of format RGBA and type
1058 // UNSIGNED_INT_2_10_10_10_REV is accepted.
1060 if (webgl->IsWebGL2() &&
1061 srcUsage->format->effectiveFormat == webgl::EffectiveFormat::RGB10_A2 &&
1062 pi.format == LOCAL_GL_RGBA &&
1063 pi.type == LOCAL_GL_UNSIGNED_INT_2_10_10_10_REV) {
1064 return true;
1067 ////
1069 MOZ_ASSERT(gl->IsCurrent());
1070 const auto implPI = webgl->ValidImplementationColorReadPI(srcUsage);
1071 if (pi == implPI) return true;
1073 ////
1075 // clang-format off
1076 webgl->ErrorInvalidOperation(
1077 "Format and type %s/%s incompatible with this %s attachment."
1078 " This framebuffer requires either %s/%s or"
1079 " getParameter(IMPLEMENTATION_COLOR_READ_FORMAT/_TYPE) %s/%s.",
1080 EnumString(pi.format).c_str(), EnumString(pi.type).c_str(),
1081 srcUsage->format->name,
1082 EnumString(defaultPI.format).c_str(), EnumString(defaultPI.type).c_str(),
1083 EnumString(implPI.format).c_str(), EnumString(implPI.type).c_str());
1084 // clang-format on
1086 return false;
1089 webgl::ReadPixelsResult WebGLContext::ReadPixelsImpl(
1090 const webgl::ReadPixelsDesc& desc, const uintptr_t dest,
1091 const uint64_t availBytes) {
1092 const webgl::FormatUsageInfo* srcFormat;
1093 uint32_t srcWidth;
1094 uint32_t srcHeight;
1095 if (!BindCurFBForColorRead(&srcFormat, &srcWidth, &srcHeight)) return {};
1097 //////
1099 if (!ValidateReadPixelsFormatAndType(srcFormat, desc.pi, gl, this)) return {};
1101 //////
1103 const auto& srcOffset = desc.srcOffset;
1104 const auto& size = desc.size;
1106 if (!ivec2::From(size)) {
1107 ErrorInvalidValue("width and height must be non-negative.");
1108 return {};
1111 const auto& packing = desc.packState;
1112 const auto explicitPackingRes = webgl::ExplicitPixelPackingState::ForUseWith(
1113 packing, LOCAL_GL_TEXTURE_2D, {size.x, size.y, 1}, desc.pi, {});
1114 if (!explicitPackingRes.isOk()) {
1115 ErrorInvalidOperation("%s", explicitPackingRes.inspectErr().c_str());
1116 return {};
1118 const auto& explicitPacking = explicitPackingRes.inspect();
1119 const auto& rowStride = explicitPacking.metrics.bytesPerRowStride;
1120 const auto& bytesNeeded = explicitPacking.metrics.totalBytesUsed;
1121 if (bytesNeeded > availBytes) {
1122 ErrorInvalidOperation("buffer too small");
1123 return {};
1126 ////
1128 int32_t readX, readY;
1129 int32_t writeX, writeY;
1130 int32_t rwWidth, rwHeight;
1131 if (!Intersect(srcWidth, srcOffset.x, size.x, &readX, &writeX, &rwWidth) ||
1132 !Intersect(srcHeight, srcOffset.y, size.y, &readY, &writeY, &rwHeight)) {
1133 ErrorOutOfMemory("Bad subrect selection.");
1134 return {};
1137 ////////////////
1138 // Now that the errors are out of the way, on to actually reading!
1140 gl->fPixelStorei(LOCAL_GL_PACK_ALIGNMENT, packing.alignmentInTypeElems);
1141 if (IsWebGL2()) {
1142 gl->fPixelStorei(LOCAL_GL_PACK_ROW_LENGTH, packing.rowLength);
1143 gl->fPixelStorei(LOCAL_GL_PACK_SKIP_PIXELS, packing.skipPixels);
1144 gl->fPixelStorei(LOCAL_GL_PACK_SKIP_ROWS, packing.skipRows);
1147 if (!rwWidth || !rwHeight) {
1148 // Disjoint rects, so we're done already.
1149 DummyReadFramebufferOperation();
1150 return {};
1152 const auto rwSize = *uvec2::From(rwWidth, rwHeight);
1154 const auto res = webgl::ReadPixelsResult{
1155 {{writeX, writeY}, {rwSize.x, rwSize.y}}, rowStride};
1157 if (rwSize == size) {
1158 DoReadPixelsAndConvert(srcFormat->format, desc, dest, bytesNeeded,
1159 rowStride);
1160 return res;
1163 // Read request contains out-of-bounds pixels. Unfortunately:
1164 // GLES 3.0.4 p194 "Obtaining Pixels from the Framebuffer":
1165 // "If any of these pixels lies outside of the window allocated to the current
1166 // GL context, or outside of the image attached to the currently bound
1167 // framebuffer object, then the values obtained for those pixels are
1168 // undefined."
1170 // This is a slow-path, so warn people away!
1171 GenerateWarning(
1172 "Out-of-bounds reads with readPixels are deprecated, and"
1173 " may be slow.");
1175 ////////////////////////////////////
1176 // Read only the in-bounds pixels.
1178 if (IsWebGL2()) {
1179 if (!packing.rowLength) {
1180 gl->fPixelStorei(LOCAL_GL_PACK_ROW_LENGTH, packing.skipPixels + size.x);
1182 gl->fPixelStorei(LOCAL_GL_PACK_SKIP_PIXELS, packing.skipPixels + writeX);
1183 gl->fPixelStorei(LOCAL_GL_PACK_SKIP_ROWS, packing.skipRows + writeY);
1185 auto desc2 = desc;
1186 desc2.srcOffset = {readX, readY};
1187 desc2.size = rwSize;
1189 DoReadPixelsAndConvert(srcFormat->format, desc2, dest, bytesNeeded,
1190 rowStride);
1191 } else {
1192 // I *did* say "hilariously slow".
1194 auto desc2 = desc;
1195 desc2.srcOffset = {readX, readY};
1196 desc2.size = {rwSize.x, 1};
1198 const auto skipBytes = writeX * explicitPacking.metrics.bytesPerPixel;
1199 const auto usedRowBytes = rwSize.x * explicitPacking.metrics.bytesPerPixel;
1200 for (const auto j : IntegerRange(rwSize.y)) {
1201 desc2.srcOffset.y = readY + j;
1202 const auto destWriteBegin = dest + skipBytes + (writeY + j) * rowStride;
1203 MOZ_RELEASE_ASSERT(dest <= destWriteBegin);
1204 MOZ_RELEASE_ASSERT(destWriteBegin <= dest + availBytes);
1206 const auto destWriteEnd = destWriteBegin + usedRowBytes;
1207 MOZ_RELEASE_ASSERT(dest <= destWriteEnd);
1208 MOZ_RELEASE_ASSERT(destWriteEnd <= dest + availBytes);
1210 DoReadPixelsAndConvert(srcFormat->format, desc2, destWriteBegin,
1211 destWriteEnd - destWriteBegin, rowStride);
1215 return res;
1218 void WebGLContext::RenderbufferStorageMultisample(WebGLRenderbuffer& rb,
1219 uint32_t samples,
1220 GLenum internalFormat,
1221 uint32_t width,
1222 uint32_t height) const {
1223 const FuncScope funcScope(*this, "renderbufferStorage(Multisample)?");
1224 if (IsContextLost()) return;
1226 rb.RenderbufferStorage(samples, internalFormat, width, height);
1229 void WebGLContext::Scissor(GLint x, GLint y, GLsizei width, GLsizei height) {
1230 const FuncScope funcScope(*this, "scissor");
1231 if (IsContextLost()) return;
1233 if (!ValidateNonNegative("width", width) ||
1234 !ValidateNonNegative("height", height)) {
1235 return;
1238 mScissorRect = {x, y, width, height};
1239 mScissorRect.Apply(*gl);
1242 void WebGLContext::StencilFuncSeparate(GLenum face, GLenum func, GLint ref,
1243 GLuint mask) {
1244 const FuncScope funcScope(*this, "stencilFuncSeparate");
1245 if (IsContextLost()) return;
1247 if (!ValidateFaceEnum(face) || !ValidateComparisonEnum(*this, func)) {
1248 return;
1251 switch (face) {
1252 case LOCAL_GL_FRONT_AND_BACK:
1253 mStencilRefFront = ref;
1254 mStencilRefBack = ref;
1255 mStencilValueMaskFront = mask;
1256 mStencilValueMaskBack = mask;
1257 break;
1258 case LOCAL_GL_FRONT:
1259 mStencilRefFront = ref;
1260 mStencilValueMaskFront = mask;
1261 break;
1262 case LOCAL_GL_BACK:
1263 mStencilRefBack = ref;
1264 mStencilValueMaskBack = mask;
1265 break;
1268 gl->fStencilFuncSeparate(face, func, ref, mask);
1271 void WebGLContext::StencilOpSeparate(GLenum face, GLenum sfail, GLenum dpfail,
1272 GLenum dppass) {
1273 const FuncScope funcScope(*this, "stencilOpSeparate");
1274 if (IsContextLost()) return;
1276 if (!ValidateFaceEnum(face) || !ValidateStencilOpEnum(sfail, "sfail") ||
1277 !ValidateStencilOpEnum(dpfail, "dpfail") ||
1278 !ValidateStencilOpEnum(dppass, "dppass"))
1279 return;
1281 gl->fStencilOpSeparate(face, sfail, dpfail, dppass);
1284 ////////////////////////////////////////////////////////////////////////////////
1285 // Uniform setters.
1287 void WebGLContext::UniformData(
1288 const uint32_t loc, const bool transpose,
1289 const Range<const webgl::UniformDataVal>& data) const {
1290 const FuncScope funcScope(*this, "uniform setter");
1292 if (!IsWebGL2() && transpose) {
1293 GenerateError(LOCAL_GL_INVALID_VALUE, "`transpose`:true requires WebGL 2.");
1294 return;
1297 // -
1299 const auto& link = mActiveProgramLinkInfo;
1300 if (!link) return;
1302 const auto locInfo = MaybeFind(link->locationMap, loc);
1303 if (!locInfo) {
1304 // Null WebGLUniformLocations become -1, which will end up here.
1305 return;
1308 const auto& validationInfo = locInfo->info;
1309 const auto& activeInfo = validationInfo.info;
1310 const auto& channels = validationInfo.channelsPerElem;
1311 const auto& pfn = validationInfo.pfn;
1313 // -
1315 const auto lengthInType = data.length();
1316 const auto elemCount = lengthInType / channels;
1317 if (elemCount > 1 && !validationInfo.isArray) {
1318 GenerateError(
1319 LOCAL_GL_INVALID_OPERATION,
1320 "(uniform %s) `values` length (%u) must exactly match size of %s.",
1321 activeInfo.name.c_str(), lengthInType,
1322 EnumString(activeInfo.elemType).c_str());
1323 return;
1326 // -
1328 const auto& samplerInfo = locInfo->samplerInfo;
1329 if (samplerInfo) {
1330 const auto idata = reinterpret_cast<const uint32_t*>(data.begin().get());
1331 const auto maxTexUnits = GLMaxTextureUnits();
1332 for (const auto& val : Range<const uint32_t>(idata, elemCount)) {
1333 if (val >= maxTexUnits) {
1334 ErrorInvalidValue(
1335 "This uniform location is a sampler, but %d"
1336 " is not a valid texture unit.",
1337 val);
1338 return;
1343 // -
1345 // This is a little galaxy-brain, sorry!
1346 const auto ptr = static_cast<const void*>(data.begin().get());
1347 (*pfn)(*gl, static_cast<GLint>(loc), elemCount, transpose, ptr);
1349 // -
1351 if (samplerInfo) {
1352 auto& texUnits = samplerInfo->texUnits;
1354 const auto srcBegin = reinterpret_cast<const uint32_t*>(data.begin().get());
1355 auto destIndex = locInfo->indexIntoUniform;
1356 if (destIndex < texUnits.length()) {
1357 // Only sample as many indexes as available tex units allow.
1358 const auto destCount = std::min(elemCount, texUnits.length() - destIndex);
1359 for (const auto& val : Range<const uint32_t>(srcBegin, destCount)) {
1360 texUnits[destIndex] = AssertedCast<uint8_t>(val);
1361 destIndex += 1;
1367 ////////////////////////////////////////////////////////////////////////////////
1369 void WebGLContext::UseProgram(WebGLProgram* prog) {
1370 FuncScope funcScope(*this, "useProgram");
1371 if (IsContextLost()) return;
1372 funcScope.mBindFailureGuard = true;
1374 if (!prog) {
1375 mCurrentProgram = nullptr;
1376 mActiveProgramLinkInfo = nullptr;
1377 funcScope.mBindFailureGuard = false;
1378 return;
1381 if (!ValidateObject("prog", *prog)) return;
1383 if (!prog->UseProgram()) return;
1385 mCurrentProgram = prog;
1386 mActiveProgramLinkInfo = mCurrentProgram->LinkInfo();
1388 funcScope.mBindFailureGuard = false;
1391 bool WebGLContext::ValidateProgram(const WebGLProgram& prog) const {
1392 const FuncScope funcScope(*this, "validateProgram");
1393 if (IsContextLost()) return false;
1395 return prog.ValidateProgram();
1398 RefPtr<WebGLFramebuffer> WebGLContext::CreateFramebuffer() {
1399 const FuncScope funcScope(*this, "createFramebuffer");
1400 if (IsContextLost()) return nullptr;
1402 GLuint fbo = 0;
1403 gl->fGenFramebuffers(1, &fbo);
1405 return new WebGLFramebuffer(this, fbo);
1408 RefPtr<WebGLFramebuffer> WebGLContext::CreateOpaqueFramebuffer(
1409 const webgl::OpaqueFramebufferOptions& options) {
1410 const FuncScope funcScope(*this, "createOpaqueFramebuffer");
1411 if (IsContextLost()) return nullptr;
1413 uint32_t samples = options.antialias ? StaticPrefs::webgl_msaa_samples() : 0;
1414 samples = std::min(samples, gl->MaxSamples());
1415 const gfx::IntSize size = {options.width, options.height};
1417 auto fbo =
1418 gl::MozFramebuffer::Create(gl, size, samples, options.depthStencil);
1419 if (!fbo) {
1420 return nullptr;
1423 return new WebGLFramebuffer(this, std::move(fbo));
1426 RefPtr<WebGLRenderbuffer> WebGLContext::CreateRenderbuffer() {
1427 const FuncScope funcScope(*this, "createRenderbuffer");
1428 if (IsContextLost()) return nullptr;
1430 return new WebGLRenderbuffer(this);
1433 void WebGLContext::Viewport(GLint x, GLint y, GLsizei width, GLsizei height) {
1434 const FuncScope funcScope(*this, "viewport");
1435 if (IsContextLost()) return;
1437 if (!ValidateNonNegative("width", width) ||
1438 !ValidateNonNegative("height", height)) {
1439 return;
1442 const auto& limits = Limits();
1443 width = std::min(width, static_cast<GLsizei>(limits.maxViewportDim));
1444 height = std::min(height, static_cast<GLsizei>(limits.maxViewportDim));
1446 gl->fViewport(x, y, width, height);
1448 mViewportX = x;
1449 mViewportY = y;
1450 mViewportWidth = width;
1451 mViewportHeight = height;
1454 void WebGLContext::CompileShader(WebGLShader& shader) {
1455 const FuncScope funcScope(*this, "compileShader");
1456 if (IsContextLost()) return;
1458 if (!ValidateObject("shader", shader)) return;
1460 shader.CompileShader();
1463 Maybe<webgl::ShaderPrecisionFormat> WebGLContext::GetShaderPrecisionFormat(
1464 GLenum shadertype, GLenum precisiontype) const {
1465 const FuncScope funcScope(*this, "getShaderPrecisionFormat");
1466 if (IsContextLost()) return Nothing();
1468 switch (shadertype) {
1469 case LOCAL_GL_FRAGMENT_SHADER:
1470 case LOCAL_GL_VERTEX_SHADER:
1471 break;
1472 default:
1473 ErrorInvalidEnumInfo("shadertype", shadertype);
1474 return Nothing();
1477 switch (precisiontype) {
1478 case LOCAL_GL_LOW_FLOAT:
1479 case LOCAL_GL_MEDIUM_FLOAT:
1480 case LOCAL_GL_HIGH_FLOAT:
1481 case LOCAL_GL_LOW_INT:
1482 case LOCAL_GL_MEDIUM_INT:
1483 case LOCAL_GL_HIGH_INT:
1484 break;
1485 default:
1486 ErrorInvalidEnumInfo("precisiontype", precisiontype);
1487 return Nothing();
1490 GLint range[2], precision;
1492 if (mDisableFragHighP && shadertype == LOCAL_GL_FRAGMENT_SHADER &&
1493 (precisiontype == LOCAL_GL_HIGH_FLOAT ||
1494 precisiontype == LOCAL_GL_HIGH_INT)) {
1495 precision = 0;
1496 range[0] = 0;
1497 range[1] = 0;
1498 } else {
1499 gl->fGetShaderPrecisionFormat(shadertype, precisiontype, range, &precision);
1502 return Some(webgl::ShaderPrecisionFormat{range[0], range[1], precision});
1505 void WebGLContext::ShaderSource(WebGLShader& shader,
1506 const std::string& source) const {
1507 const FuncScope funcScope(*this, "shaderSource");
1508 if (IsContextLost()) return;
1510 shader.ShaderSource(source);
1513 void WebGLContext::BlendColor(GLfloat r, GLfloat g, GLfloat b, GLfloat a) {
1514 const FuncScope funcScope(*this, "blendColor");
1515 if (IsContextLost()) return;
1517 gl->fBlendColor(r, g, b, a);
1520 void WebGLContext::Flush() {
1521 const FuncScope funcScope(*this, "flush");
1522 if (IsContextLost()) return;
1524 gl->fFlush();
1527 void WebGLContext::Finish() {
1528 const FuncScope funcScope(*this, "finish");
1529 if (IsContextLost()) return;
1531 gl->fFinish();
1533 mCompletedFenceId = mNextFenceId;
1534 mNextFenceId += 1;
1537 void WebGLContext::LineWidth(GLfloat width) {
1538 const FuncScope funcScope(*this, "lineWidth");
1539 if (IsContextLost()) return;
1541 // Doing it this way instead of `if (width <= 0.0)` handles NaNs.
1542 const bool isValid = width > 0.0;
1543 if (!isValid) {
1544 ErrorInvalidValue("`width` must be positive and non-zero.");
1545 return;
1548 mLineWidth = width;
1550 if (gl->IsCoreProfile() && width > 1.0) {
1551 width = 1.0;
1554 gl->fLineWidth(width);
1557 void WebGLContext::PolygonOffset(GLfloat factor, GLfloat units) {
1558 const FuncScope funcScope(*this, "polygonOffset");
1559 if (IsContextLost()) return;
1561 gl->fPolygonOffset(factor, units);
1564 void WebGLContext::ProvokingVertex(const webgl::ProvokingVertex mode) const {
1565 const FuncScope funcScope(*this, "provokingVertex");
1566 if (IsContextLost()) return;
1567 MOZ_RELEASE_ASSERT(
1568 IsExtensionEnabled(WebGLExtensionID::WEBGL_provoking_vertex));
1570 gl->fProvokingVertex(UnderlyingValue(mode));
1573 void WebGLContext::SampleCoverage(GLclampf value, WebGLboolean invert) {
1574 const FuncScope funcScope(*this, "sampleCoverage");
1575 if (IsContextLost()) return;
1577 gl->fSampleCoverage(value, invert);
1580 } // namespace mozilla