Backed out 4 changesets (bug 1879154) for causing bustage on nsUserCharacteristics...
[gecko.git] / dom / canvas / WebGLContextGL.cpp
blobef068c8999428c58a6de276400a24ea3993adb9e
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);
869 const auto& pi = desc.pi;
871 // On at least Win+NV, we'll get PBO errors if we don't have at least
872 // `rowStride * height` bytes available to read into.
873 const auto naiveBytesNeeded = CheckedInt<uint64_t>(rowStride) * size.y;
874 const bool isDangerCloseToEdge =
875 (!naiveBytesNeeded.isValid() || naiveBytesNeeded.value() > destSize);
876 const bool useParanoidHandling =
877 (gl->WorkAroundDriverBugs() && isDangerCloseToEdge &&
878 mBoundPixelPackBuffer);
879 if (!useParanoidHandling) {
880 gl->fReadPixels(x, y, size.x, size.y, pi.format, pi.type,
881 reinterpret_cast<void*>(dest));
882 return true;
885 // Read everything but the last row.
886 const auto bodyHeight = size.y - 1;
887 if (bodyHeight) {
888 gl->fReadPixels(x, y, size.x, bodyHeight, pi.format, pi.type,
889 reinterpret_cast<void*>(dest));
892 // Now read the last row.
893 gl->fPixelStorei(LOCAL_GL_PACK_ALIGNMENT, 1);
894 gl->fPixelStorei(LOCAL_GL_PACK_ROW_LENGTH, 0);
895 gl->fPixelStorei(LOCAL_GL_PACK_SKIP_ROWS, 0);
897 const auto tailRowOffset =
898 reinterpret_cast<uint8_t*>(dest) + rowStride * bodyHeight;
899 gl->fReadPixels(x, y + bodyHeight, size.x, 1, pi.format, pi.type,
900 tailRowOffset);
902 return true;
905 webgl::ReadPixelsResult WebGLContext::ReadPixelsInto(
906 const webgl::ReadPixelsDesc& desc, const Range<uint8_t>& dest) {
907 const FuncScope funcScope(*this, "readPixels");
908 if (IsContextLost()) return {};
910 if (mBoundPixelPackBuffer) {
911 ErrorInvalidOperation("PIXEL_PACK_BUFFER must be null.");
912 return {};
915 return ReadPixelsImpl(desc, reinterpret_cast<uintptr_t>(dest.begin().get()),
916 dest.length());
919 void WebGLContext::ReadPixelsPbo(const webgl::ReadPixelsDesc& desc,
920 const uint64_t offset) {
921 const FuncScope funcScope(*this, "readPixels");
922 if (IsContextLost()) return;
924 const auto& buffer = ValidateBufferSelection(LOCAL_GL_PIXEL_PACK_BUFFER);
925 if (!buffer) return;
927 //////
930 const auto pii = webgl::PackingInfoInfo::For(desc.pi);
931 if (!pii) {
932 GLenum err = LOCAL_GL_INVALID_OPERATION;
933 if (!desc.pi.format || !desc.pi.type) {
934 err = LOCAL_GL_INVALID_ENUM;
936 GenerateError(err, "`format` (%s) and/or `type` (%s) not acceptable.",
937 EnumString(desc.pi.format).c_str(),
938 EnumString(desc.pi.type).c_str());
939 return;
942 if (offset % pii->bytesPerElement != 0) {
943 ErrorInvalidOperation(
944 "`offset` must be divisible by the size of `type`"
945 " in bytes.");
946 return;
950 //////
952 auto bytesAvailable = buffer->ByteLength();
953 if (offset > bytesAvailable) {
954 ErrorInvalidOperation("`offset` too large for bound PIXEL_PACK_BUFFER.");
955 return;
957 bytesAvailable -= offset;
959 // -
961 const ScopedLazyBind lazyBind(gl, LOCAL_GL_PIXEL_PACK_BUFFER, buffer);
963 ReadPixelsImpl(desc, offset, bytesAvailable);
965 buffer->ResetLastUpdateFenceId();
968 static webgl::PackingInfo DefaultReadPixelPI(
969 const webgl::FormatUsageInfo* usage) {
970 MOZ_ASSERT(usage->IsRenderable());
971 const auto& format = *usage->format;
972 switch (format.componentType) {
973 case webgl::ComponentType::NormUInt:
974 if (format.r == 16) {
975 return {LOCAL_GL_RGBA, LOCAL_GL_UNSIGNED_SHORT};
977 return {LOCAL_GL_RGBA, LOCAL_GL_UNSIGNED_BYTE};
979 case webgl::ComponentType::Int:
980 return {LOCAL_GL_RGBA_INTEGER, LOCAL_GL_INT};
982 case webgl::ComponentType::UInt:
983 return {LOCAL_GL_RGBA_INTEGER, LOCAL_GL_UNSIGNED_INT};
985 case webgl::ComponentType::Float:
986 return {LOCAL_GL_RGBA, LOCAL_GL_FLOAT};
988 default:
989 MOZ_CRASH();
993 static bool ArePossiblePackEnums(const WebGLContext* webgl,
994 const webgl::PackingInfo& pi) {
995 // OpenGL ES 2.0 $4.3.1 - IMPLEMENTATION_COLOR_READ_{TYPE/FORMAT} is a valid
996 // combination for glReadPixels()...
998 // Only valid when pulled from:
999 // * GLES 2.0.25 p105:
1000 // "table 3.4, excluding formats LUMINANCE and LUMINANCE_ALPHA."
1001 // * GLES 3.0.4 p193:
1002 // "table 3.2, excluding formats DEPTH_COMPONENT and DEPTH_STENCIL."
1003 switch (pi.format) {
1004 case LOCAL_GL_LUMINANCE:
1005 case LOCAL_GL_LUMINANCE_ALPHA:
1006 case LOCAL_GL_DEPTH_COMPONENT:
1007 case LOCAL_GL_DEPTH_STENCIL:
1008 return false;
1011 if (pi.type == LOCAL_GL_UNSIGNED_INT_24_8) return false;
1013 const auto pii = webgl::PackingInfoInfo::For(pi);
1014 if (!pii) return false;
1016 return true;
1019 webgl::PackingInfo WebGLContext::ValidImplementationColorReadPI(
1020 const webgl::FormatUsageInfo* usage) const {
1021 const auto defaultPI = DefaultReadPixelPI(usage);
1023 // ES2_compatibility always returns RGBA/UNSIGNED_BYTE, so branch on actual
1024 // IsGLES(). Also OSX+NV generates an error here.
1025 if (!gl->IsGLES()) return defaultPI;
1027 webgl::PackingInfo implPI;
1028 gl->fGetIntegerv(LOCAL_GL_IMPLEMENTATION_COLOR_READ_FORMAT,
1029 (GLint*)&implPI.format);
1030 gl->fGetIntegerv(LOCAL_GL_IMPLEMENTATION_COLOR_READ_TYPE,
1031 (GLint*)&implPI.type);
1033 if (!ArePossiblePackEnums(this, implPI)) return defaultPI;
1035 return implPI;
1038 static bool ValidateReadPixelsFormatAndType(
1039 const webgl::FormatUsageInfo* srcUsage, const webgl::PackingInfo& pi,
1040 gl::GLContext* gl, WebGLContext* webgl) {
1041 if (!ArePossiblePackEnums(webgl, pi)) {
1042 webgl->ErrorInvalidEnum("Unexpected format or type.");
1043 return false;
1046 const auto defaultPI = DefaultReadPixelPI(srcUsage);
1047 if (pi == defaultPI) return true;
1049 ////
1051 // OpenGL ES 3.0.4 p194 - When the internal format of the rendering surface is
1052 // RGB10_A2, a third combination of format RGBA and type
1053 // UNSIGNED_INT_2_10_10_10_REV is accepted.
1055 if (webgl->IsWebGL2() &&
1056 srcUsage->format->effectiveFormat == webgl::EffectiveFormat::RGB10_A2 &&
1057 pi.format == LOCAL_GL_RGBA &&
1058 pi.type == LOCAL_GL_UNSIGNED_INT_2_10_10_10_REV) {
1059 return true;
1062 ////
1064 const auto implPI = webgl->ValidImplementationColorReadPI(srcUsage);
1065 if (pi == implPI) return true;
1067 ////
1069 // clang-format off
1070 webgl->ErrorInvalidOperation(
1071 "Format and type %s/%s incompatible with this %s attachment."
1072 " This framebuffer requires either %s/%s or"
1073 " getParameter(IMPLEMENTATION_COLOR_READ_FORMAT/_TYPE) %s/%s.",
1074 EnumString(pi.format).c_str(), EnumString(pi.type).c_str(),
1075 srcUsage->format->name,
1076 EnumString(defaultPI.format).c_str(), EnumString(defaultPI.type).c_str(),
1077 EnumString(implPI.format).c_str(), EnumString(implPI.type).c_str());
1078 // clang-format on
1080 return false;
1083 webgl::ReadPixelsResult WebGLContext::ReadPixelsImpl(
1084 const webgl::ReadPixelsDesc& desc, const uintptr_t dest,
1085 const uint64_t availBytes) {
1086 const webgl::FormatUsageInfo* srcFormat;
1087 uint32_t srcWidth;
1088 uint32_t srcHeight;
1089 if (!BindCurFBForColorRead(&srcFormat, &srcWidth, &srcHeight)) return {};
1091 //////
1093 if (!ValidateReadPixelsFormatAndType(srcFormat, desc.pi, gl, this)) return {};
1095 //////
1097 const auto& srcOffset = desc.srcOffset;
1098 const auto& size = desc.size;
1100 if (!ivec2::From(size)) {
1101 ErrorInvalidValue("width and height must be non-negative.");
1102 return {};
1105 const auto& packing = desc.packState;
1106 const auto explicitPackingRes = webgl::ExplicitPixelPackingState::ForUseWith(
1107 packing, LOCAL_GL_TEXTURE_2D, {size.x, size.y, 1}, desc.pi, {});
1108 if (!explicitPackingRes.isOk()) {
1109 ErrorInvalidOperation("%s", explicitPackingRes.inspectErr().c_str());
1110 return {};
1112 const auto& explicitPacking = explicitPackingRes.inspect();
1113 const auto& rowStride = explicitPacking.metrics.bytesPerRowStride;
1114 const auto& bytesNeeded = explicitPacking.metrics.totalBytesUsed;
1115 if (bytesNeeded > availBytes) {
1116 ErrorInvalidOperation("buffer too small");
1117 return {};
1120 ////
1122 int32_t readX, readY;
1123 int32_t writeX, writeY;
1124 int32_t rwWidth, rwHeight;
1125 if (!Intersect(srcWidth, srcOffset.x, size.x, &readX, &writeX, &rwWidth) ||
1126 !Intersect(srcHeight, srcOffset.y, size.y, &readY, &writeY, &rwHeight)) {
1127 ErrorOutOfMemory("Bad subrect selection.");
1128 return {};
1131 ////////////////
1132 // Now that the errors are out of the way, on to actually reading!
1134 gl->fPixelStorei(LOCAL_GL_PACK_ALIGNMENT, packing.alignmentInTypeElems);
1135 if (IsWebGL2()) {
1136 gl->fPixelStorei(LOCAL_GL_PACK_ROW_LENGTH, packing.rowLength);
1137 gl->fPixelStorei(LOCAL_GL_PACK_SKIP_PIXELS, packing.skipPixels);
1138 gl->fPixelStorei(LOCAL_GL_PACK_SKIP_ROWS, packing.skipRows);
1141 if (!rwWidth || !rwHeight) {
1142 // Disjoint rects, so we're done already.
1143 DummyReadFramebufferOperation();
1144 return {};
1146 const auto rwSize = *uvec2::From(rwWidth, rwHeight);
1148 const auto res = webgl::ReadPixelsResult{
1149 {{writeX, writeY}, {rwSize.x, rwSize.y}}, rowStride};
1151 if (rwSize == size) {
1152 DoReadPixelsAndConvert(srcFormat->format, desc, dest, bytesNeeded,
1153 rowStride);
1154 return res;
1157 // Read request contains out-of-bounds pixels. Unfortunately:
1158 // GLES 3.0.4 p194 "Obtaining Pixels from the Framebuffer":
1159 // "If any of these pixels lies outside of the window allocated to the current
1160 // GL context, or outside of the image attached to the currently bound
1161 // framebuffer object, then the values obtained for those pixels are
1162 // undefined."
1164 // This is a slow-path, so warn people away!
1165 GenerateWarning(
1166 "Out-of-bounds reads with readPixels are deprecated, and"
1167 " may be slow.");
1169 ////////////////////////////////////
1170 // Read only the in-bounds pixels.
1172 if (IsWebGL2()) {
1173 if (!packing.rowLength) {
1174 gl->fPixelStorei(LOCAL_GL_PACK_ROW_LENGTH, packing.skipPixels + size.x);
1176 gl->fPixelStorei(LOCAL_GL_PACK_SKIP_PIXELS, packing.skipPixels + writeX);
1177 gl->fPixelStorei(LOCAL_GL_PACK_SKIP_ROWS, packing.skipRows + writeY);
1179 auto desc2 = desc;
1180 desc2.srcOffset = {readX, readY};
1181 desc2.size = rwSize;
1183 DoReadPixelsAndConvert(srcFormat->format, desc2, dest, bytesNeeded,
1184 rowStride);
1185 } else {
1186 // I *did* say "hilariously slow".
1188 auto desc2 = desc;
1189 desc2.srcOffset = {readX, readY};
1190 desc2.size = {rwSize.x, 1};
1192 const auto skipBytes = writeX * explicitPacking.metrics.bytesPerPixel;
1193 const auto usedRowBytes = rwSize.x * explicitPacking.metrics.bytesPerPixel;
1194 for (const auto j : IntegerRange(rwSize.y)) {
1195 desc2.srcOffset.y = readY + j;
1196 const auto destWriteBegin = dest + skipBytes + (writeY + j) * rowStride;
1197 MOZ_RELEASE_ASSERT(dest <= destWriteBegin);
1198 MOZ_RELEASE_ASSERT(destWriteBegin <= dest + availBytes);
1200 const auto destWriteEnd = destWriteBegin + usedRowBytes;
1201 MOZ_RELEASE_ASSERT(dest <= destWriteEnd);
1202 MOZ_RELEASE_ASSERT(destWriteEnd <= dest + availBytes);
1204 DoReadPixelsAndConvert(srcFormat->format, desc2, destWriteBegin,
1205 destWriteEnd - destWriteBegin, rowStride);
1209 return res;
1212 void WebGLContext::RenderbufferStorageMultisample(WebGLRenderbuffer& rb,
1213 uint32_t samples,
1214 GLenum internalFormat,
1215 uint32_t width,
1216 uint32_t height) const {
1217 const FuncScope funcScope(*this, "renderbufferStorage(Multisample)?");
1218 if (IsContextLost()) return;
1220 rb.RenderbufferStorage(samples, internalFormat, width, height);
1223 void WebGLContext::Scissor(GLint x, GLint y, GLsizei width, GLsizei height) {
1224 const FuncScope funcScope(*this, "scissor");
1225 if (IsContextLost()) return;
1227 if (!ValidateNonNegative("width", width) ||
1228 !ValidateNonNegative("height", height)) {
1229 return;
1232 mScissorRect = {x, y, width, height};
1233 mScissorRect.Apply(*gl);
1236 void WebGLContext::StencilFuncSeparate(GLenum face, GLenum func, GLint ref,
1237 GLuint mask) {
1238 const FuncScope funcScope(*this, "stencilFuncSeparate");
1239 if (IsContextLost()) return;
1241 if (!ValidateFaceEnum(face) || !ValidateComparisonEnum(*this, func)) {
1242 return;
1245 switch (face) {
1246 case LOCAL_GL_FRONT_AND_BACK:
1247 mStencilRefFront = ref;
1248 mStencilRefBack = ref;
1249 mStencilValueMaskFront = mask;
1250 mStencilValueMaskBack = mask;
1251 break;
1252 case LOCAL_GL_FRONT:
1253 mStencilRefFront = ref;
1254 mStencilValueMaskFront = mask;
1255 break;
1256 case LOCAL_GL_BACK:
1257 mStencilRefBack = ref;
1258 mStencilValueMaskBack = mask;
1259 break;
1262 gl->fStencilFuncSeparate(face, func, ref, mask);
1265 void WebGLContext::StencilOpSeparate(GLenum face, GLenum sfail, GLenum dpfail,
1266 GLenum dppass) {
1267 const FuncScope funcScope(*this, "stencilOpSeparate");
1268 if (IsContextLost()) return;
1270 if (!ValidateFaceEnum(face) || !ValidateStencilOpEnum(sfail, "sfail") ||
1271 !ValidateStencilOpEnum(dpfail, "dpfail") ||
1272 !ValidateStencilOpEnum(dppass, "dppass"))
1273 return;
1275 gl->fStencilOpSeparate(face, sfail, dpfail, dppass);
1278 ////////////////////////////////////////////////////////////////////////////////
1279 // Uniform setters.
1281 void WebGLContext::UniformData(
1282 const uint32_t loc, const bool transpose,
1283 const Span<const webgl::UniformDataVal>& data) const {
1284 const FuncScope funcScope(*this, "uniform setter");
1286 if (!IsWebGL2() && transpose) {
1287 GenerateError(LOCAL_GL_INVALID_VALUE, "`transpose`:true requires WebGL 2.");
1288 return;
1291 // -
1293 const auto& link = mActiveProgramLinkInfo;
1294 if (!link) return;
1296 const auto locInfo = MaybeFind(link->locationMap, loc);
1297 if (!locInfo) {
1298 // Null WebGLUniformLocations become -1, which will end up here.
1299 return;
1302 const auto& validationInfo = locInfo->info;
1303 const auto& activeInfo = validationInfo.info;
1304 const auto& channels = validationInfo.channelsPerElem;
1305 const auto& pfn = validationInfo.pfn;
1307 // -
1309 const auto lengthInType = data.size();
1310 const auto elemCount = lengthInType / channels;
1311 if (elemCount > 1 && !validationInfo.isArray) {
1312 GenerateError(
1313 LOCAL_GL_INVALID_OPERATION,
1314 "(uniform %s) `values` length (%u) must exactly match size of %s.",
1315 activeInfo.name.c_str(), (uint32_t)lengthInType,
1316 EnumString(activeInfo.elemType).c_str());
1317 return;
1320 // -
1322 const auto& samplerInfo = locInfo->samplerInfo;
1323 if (samplerInfo) {
1324 const auto idata = ReinterpretToSpan<const uint32_t>::From(data);
1325 const auto maxTexUnits = GLMaxTextureUnits();
1326 for (const auto& val : idata) {
1327 if (val >= maxTexUnits) {
1328 ErrorInvalidValue(
1329 "This uniform location is a sampler, but %d"
1330 " is not a valid texture unit.",
1331 val);
1332 return;
1337 // -
1339 // This is a little galaxy-brain, sorry!
1340 const auto ptr = static_cast<const void*>(data.data());
1341 (*pfn)(*gl, static_cast<GLint>(loc), elemCount, transpose, ptr);
1343 // -
1345 if (samplerInfo) {
1346 auto& texUnits = samplerInfo->texUnits;
1348 const auto srcBegin = reinterpret_cast<const uint32_t*>(data.data());
1349 auto destIndex = locInfo->indexIntoUniform;
1350 if (destIndex < texUnits.length()) {
1351 // Only sample as many indexes as available tex units allow.
1352 const auto destCount = std::min(elemCount, texUnits.length() - destIndex);
1353 for (const auto& val : Span<const uint32_t>(srcBegin, destCount)) {
1354 texUnits[destIndex] = AssertedCast<uint8_t>(val);
1355 destIndex += 1;
1361 ////////////////////////////////////////////////////////////////////////////////
1363 void WebGLContext::UseProgram(WebGLProgram* prog) {
1364 FuncScope funcScope(*this, "useProgram");
1365 if (IsContextLost()) return;
1366 funcScope.mBindFailureGuard = true;
1368 if (!prog) {
1369 mCurrentProgram = nullptr;
1370 mActiveProgramLinkInfo = nullptr;
1371 funcScope.mBindFailureGuard = false;
1372 return;
1375 if (!ValidateObject("prog", *prog)) return;
1377 if (!prog->UseProgram()) return;
1379 mCurrentProgram = prog;
1380 mActiveProgramLinkInfo = mCurrentProgram->LinkInfo();
1382 funcScope.mBindFailureGuard = false;
1385 bool WebGLContext::ValidateProgram(const WebGLProgram& prog) const {
1386 const FuncScope funcScope(*this, "validateProgram");
1387 if (IsContextLost()) return false;
1389 return prog.ValidateProgram();
1392 RefPtr<WebGLFramebuffer> WebGLContext::CreateFramebuffer() {
1393 const FuncScope funcScope(*this, "createFramebuffer");
1394 if (IsContextLost()) return nullptr;
1396 GLuint fbo = 0;
1397 gl->fGenFramebuffers(1, &fbo);
1399 return new WebGLFramebuffer(this, fbo);
1402 RefPtr<WebGLFramebuffer> WebGLContext::CreateOpaqueFramebuffer(
1403 const webgl::OpaqueFramebufferOptions& options) {
1404 const FuncScope funcScope(*this, "createOpaqueFramebuffer");
1405 if (IsContextLost()) return nullptr;
1407 uint32_t samples = options.antialias ? StaticPrefs::webgl_msaa_samples() : 0;
1408 samples = std::min(samples, gl->MaxSamples());
1409 const gfx::IntSize size = {options.width, options.height};
1411 auto fbo =
1412 gl::MozFramebuffer::Create(gl, size, samples, options.depthStencil);
1413 if (!fbo) {
1414 return nullptr;
1417 return new WebGLFramebuffer(this, std::move(fbo));
1420 RefPtr<WebGLRenderbuffer> WebGLContext::CreateRenderbuffer() {
1421 const FuncScope funcScope(*this, "createRenderbuffer");
1422 if (IsContextLost()) return nullptr;
1424 return new WebGLRenderbuffer(this);
1427 void WebGLContext::Viewport(GLint x, GLint y, GLsizei width, GLsizei height) {
1428 const FuncScope funcScope(*this, "viewport");
1429 if (IsContextLost()) return;
1431 if (!ValidateNonNegative("width", width) ||
1432 !ValidateNonNegative("height", height)) {
1433 return;
1436 const auto& limits = Limits();
1437 width = std::min(width, static_cast<GLsizei>(limits.maxViewportDim));
1438 height = std::min(height, static_cast<GLsizei>(limits.maxViewportDim));
1440 gl->fViewport(x, y, width, height);
1442 mViewportX = x;
1443 mViewportY = y;
1444 mViewportWidth = width;
1445 mViewportHeight = height;
1448 void WebGLContext::CompileShader(WebGLShader& shader) {
1449 const FuncScope funcScope(*this, "compileShader");
1450 if (IsContextLost()) return;
1452 if (!ValidateObject("shader", shader)) return;
1454 shader.CompileShader();
1457 Maybe<webgl::ShaderPrecisionFormat> WebGLContext::GetShaderPrecisionFormat(
1458 GLenum shadertype, GLenum precisiontype) const {
1459 const FuncScope funcScope(*this, "getShaderPrecisionFormat");
1460 if (IsContextLost()) return Nothing();
1462 switch (shadertype) {
1463 case LOCAL_GL_FRAGMENT_SHADER:
1464 case LOCAL_GL_VERTEX_SHADER:
1465 break;
1466 default:
1467 ErrorInvalidEnumInfo("shadertype", shadertype);
1468 return Nothing();
1471 switch (precisiontype) {
1472 case LOCAL_GL_LOW_FLOAT:
1473 case LOCAL_GL_MEDIUM_FLOAT:
1474 case LOCAL_GL_HIGH_FLOAT:
1475 case LOCAL_GL_LOW_INT:
1476 case LOCAL_GL_MEDIUM_INT:
1477 case LOCAL_GL_HIGH_INT:
1478 break;
1479 default:
1480 ErrorInvalidEnumInfo("precisiontype", precisiontype);
1481 return Nothing();
1484 GLint range[2], precision;
1486 if (mDisableFragHighP && shadertype == LOCAL_GL_FRAGMENT_SHADER &&
1487 (precisiontype == LOCAL_GL_HIGH_FLOAT ||
1488 precisiontype == LOCAL_GL_HIGH_INT)) {
1489 precision = 0;
1490 range[0] = 0;
1491 range[1] = 0;
1492 } else {
1493 gl->fGetShaderPrecisionFormat(shadertype, precisiontype, range, &precision);
1496 return Some(webgl::ShaderPrecisionFormat{range[0], range[1], precision});
1499 void WebGLContext::ShaderSource(WebGLShader& shader,
1500 const std::string& source) const {
1501 const FuncScope funcScope(*this, "shaderSource");
1502 if (IsContextLost()) return;
1504 shader.ShaderSource(source);
1507 void WebGLContext::BlendColor(GLfloat r, GLfloat g, GLfloat b, GLfloat a) {
1508 const FuncScope funcScope(*this, "blendColor");
1509 if (IsContextLost()) return;
1511 gl->fBlendColor(r, g, b, a);
1514 void WebGLContext::Flush() {
1515 const FuncScope funcScope(*this, "flush");
1516 if (IsContextLost()) return;
1518 gl->fFlush();
1521 void WebGLContext::Finish() {
1522 const FuncScope funcScope(*this, "finish");
1523 if (IsContextLost()) return;
1525 gl->fFinish();
1527 mCompletedFenceId = mNextFenceId;
1528 mNextFenceId += 1;
1531 void WebGLContext::LineWidth(GLfloat width) {
1532 const FuncScope funcScope(*this, "lineWidth");
1533 if (IsContextLost()) return;
1535 // Doing it this way instead of `if (width <= 0.0)` handles NaNs.
1536 const bool isValid = width > 0.0;
1537 if (!isValid) {
1538 ErrorInvalidValue("`width` must be positive and non-zero.");
1539 return;
1542 mLineWidth = width;
1544 if (gl->IsCoreProfile() && width > 1.0) {
1545 width = 1.0;
1548 gl->fLineWidth(width);
1551 void WebGLContext::PolygonOffset(GLfloat factor, GLfloat units) {
1552 const FuncScope funcScope(*this, "polygonOffset");
1553 if (IsContextLost()) return;
1555 gl->fPolygonOffset(factor, units);
1558 void WebGLContext::ProvokingVertex(const webgl::ProvokingVertex mode) const {
1559 const FuncScope funcScope(*this, "provokingVertex");
1560 if (IsContextLost()) return;
1561 MOZ_RELEASE_ASSERT(
1562 IsExtensionEnabled(WebGLExtensionID::WEBGL_provoking_vertex));
1564 gl->fProvokingVertex(UnderlyingValue(mode));
1567 void WebGLContext::SampleCoverage(GLclampf value, WebGLboolean invert) {
1568 const FuncScope funcScope(*this, "sampleCoverage");
1569 if (IsContextLost()) return;
1571 gl->fSampleCoverage(value, invert);
1574 } // namespace mozilla