Bug 1700051: part 26) Correct typo in comment of `mozInlineSpellWordUtil::BuildSoftTe...
[gecko.git] / dom / canvas / WebGLContextGL.cpp
blob6f4085f36fbe35b2254e3dea9adf99494403b958
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 "WebGLExtensions.h"
19 #include "WebGLVertexArray.h"
21 #include "nsDebug.h"
22 #include "nsReadableUtils.h"
23 #include "nsString.h"
25 #include "gfxContext.h"
26 #include "gfxPlatform.h"
27 #include "GLContext.h"
29 #include "nsContentUtils.h"
30 #include "nsError.h"
31 #include "nsLayoutUtils.h"
33 #include "CanvasUtils.h"
34 #include "gfxUtils.h"
35 #include "MozFramebuffer.h"
37 #include "jsfriendapi.h"
39 #include "WebGLTexelConversions.h"
40 #include "WebGLValidateStrings.h"
41 #include <algorithm>
43 // needed to check if current OS is lower than 10.7
44 #if defined(MOZ_WIDGET_COCOA)
45 # include "nsCocoaFeatures.h"
46 #endif
48 #include "mozilla/DebugOnly.h"
49 #include "mozilla/dom/BindingUtils.h"
50 #include "mozilla/dom/ImageData.h"
51 #include "mozilla/dom/WebGLRenderingContextBinding.h"
52 #include "mozilla/EndianUtils.h"
53 #include "mozilla/RefPtr.h"
54 #include "mozilla/UniquePtrExtensions.h"
55 #include "mozilla/StaticPrefs_webgl.h"
57 namespace mozilla {
59 using namespace mozilla::dom;
60 using namespace mozilla::gfx;
61 using namespace mozilla::gl;
64 // WebGL API
67 void WebGLContext::ActiveTexture(uint32_t texUnit) {
68 FuncScope funcScope(*this, "activeTexture");
69 if (IsContextLost()) return;
70 funcScope.mBindFailureGuard = true;
72 if (texUnit >= Limits().maxTexUnits) {
73 return ErrorInvalidEnum("Texture unit %u out of range (%u).", texUnit,
74 Limits().maxTexUnits);
77 mActiveTexture = texUnit;
78 gl->fActiveTexture(LOCAL_GL_TEXTURE0 + texUnit);
80 funcScope.mBindFailureGuard = false;
83 void WebGLContext::AttachShader(WebGLProgram& prog, WebGLShader& shader) {
84 FuncScope funcScope(*this, "attachShader");
85 if (IsContextLost()) return;
86 funcScope.mBindFailureGuard = true;
88 prog.AttachShader(shader);
90 funcScope.mBindFailureGuard = false;
93 void WebGLContext::BindAttribLocation(WebGLProgram& prog, GLuint location,
94 const std::string& name) const {
95 const FuncScope funcScope(*this, "bindAttribLocation");
96 if (IsContextLost()) return;
98 prog.BindAttribLocation(location, name);
101 void WebGLContext::BindFramebuffer(GLenum target, WebGLFramebuffer* wfb) {
102 FuncScope funcScope(*this, "bindFramebuffer");
103 if (IsContextLost()) return;
104 funcScope.mBindFailureGuard = true;
106 if (!ValidateFramebufferTarget(target)) return;
108 if (!wfb) {
109 gl->fBindFramebuffer(target, 0);
110 } else {
111 GLuint framebuffername = wfb->mGLName;
112 gl->fBindFramebuffer(target, framebuffername);
113 wfb->mHasBeenBound = true;
116 switch (target) {
117 case LOCAL_GL_FRAMEBUFFER:
118 mBoundDrawFramebuffer = wfb;
119 mBoundReadFramebuffer = wfb;
120 break;
121 case LOCAL_GL_DRAW_FRAMEBUFFER:
122 mBoundDrawFramebuffer = wfb;
123 break;
124 case LOCAL_GL_READ_FRAMEBUFFER:
125 mBoundReadFramebuffer = wfb;
126 break;
127 default:
128 return;
130 funcScope.mBindFailureGuard = false;
133 void WebGLContext::BlendEquationSeparate(GLenum modeRGB, GLenum modeAlpha) {
134 const FuncScope funcScope(*this, "blendEquationSeparate");
135 if (IsContextLost()) return;
137 if (!ValidateBlendEquationEnum(modeRGB, "modeRGB") ||
138 !ValidateBlendEquationEnum(modeAlpha, "modeAlpha")) {
139 return;
142 gl->fBlendEquationSeparate(modeRGB, modeAlpha);
145 static bool ValidateBlendFuncEnum(WebGLContext* webgl, GLenum factor,
146 const char* varName) {
147 switch (factor) {
148 case LOCAL_GL_ZERO:
149 case LOCAL_GL_ONE:
150 case LOCAL_GL_SRC_COLOR:
151 case LOCAL_GL_ONE_MINUS_SRC_COLOR:
152 case LOCAL_GL_DST_COLOR:
153 case LOCAL_GL_ONE_MINUS_DST_COLOR:
154 case LOCAL_GL_SRC_ALPHA:
155 case LOCAL_GL_ONE_MINUS_SRC_ALPHA:
156 case LOCAL_GL_DST_ALPHA:
157 case LOCAL_GL_ONE_MINUS_DST_ALPHA:
158 case LOCAL_GL_CONSTANT_COLOR:
159 case LOCAL_GL_ONE_MINUS_CONSTANT_COLOR:
160 case LOCAL_GL_CONSTANT_ALPHA:
161 case LOCAL_GL_ONE_MINUS_CONSTANT_ALPHA:
162 case LOCAL_GL_SRC_ALPHA_SATURATE:
163 return true;
165 default:
166 webgl->ErrorInvalidEnumInfo(varName, factor);
167 return false;
171 static bool ValidateBlendFuncEnums(WebGLContext* webgl, GLenum srcRGB,
172 GLenum srcAlpha, GLenum dstRGB,
173 GLenum dstAlpha) {
174 if (!webgl->IsWebGL2()) {
175 if (dstRGB == LOCAL_GL_SRC_ALPHA_SATURATE ||
176 dstAlpha == LOCAL_GL_SRC_ALPHA_SATURATE) {
177 webgl->ErrorInvalidEnum(
178 "LOCAL_GL_SRC_ALPHA_SATURATE as a destination"
179 " blend function is disallowed in WebGL 1 (dstRGB ="
180 " 0x%04x, dstAlpha = 0x%04x).",
181 dstRGB, dstAlpha);
182 return false;
186 if (!ValidateBlendFuncEnum(webgl, srcRGB, "srcRGB") ||
187 !ValidateBlendFuncEnum(webgl, srcAlpha, "srcAlpha") ||
188 !ValidateBlendFuncEnum(webgl, dstRGB, "dstRGB") ||
189 !ValidateBlendFuncEnum(webgl, dstAlpha, "dstAlpha")) {
190 return false;
193 return true;
196 void WebGLContext::BlendFuncSeparate(GLenum srcRGB, GLenum dstRGB,
197 GLenum srcAlpha, GLenum dstAlpha) {
198 const FuncScope funcScope(*this, "blendFuncSeparate");
199 if (IsContextLost()) return;
201 if (!ValidateBlendFuncEnums(this, srcRGB, srcAlpha, dstRGB, dstAlpha)) return;
203 // note that we only check compatibity for the RGB enums, no need to for the
204 // Alpha enums, see "Section 6.8 forgetting to mention alpha factors?" thread
205 // on the public_webgl mailing list
206 if (!ValidateBlendFuncEnumsCompatibility(srcRGB, dstRGB, "srcRGB and dstRGB"))
207 return;
209 gl->fBlendFuncSeparate(srcRGB, dstRGB, srcAlpha, dstAlpha);
212 GLenum WebGLContext::CheckFramebufferStatus(GLenum target) {
213 const FuncScope funcScope(*this, "checkFramebufferStatus");
214 if (IsContextLost()) return LOCAL_GL_FRAMEBUFFER_UNSUPPORTED;
216 if (!ValidateFramebufferTarget(target)) return 0;
218 WebGLFramebuffer* fb;
219 switch (target) {
220 case LOCAL_GL_FRAMEBUFFER:
221 case LOCAL_GL_DRAW_FRAMEBUFFER:
222 fb = mBoundDrawFramebuffer;
223 break;
225 case LOCAL_GL_READ_FRAMEBUFFER:
226 fb = mBoundReadFramebuffer;
227 break;
229 default:
230 MOZ_CRASH("GFX: Bad target.");
233 if (!fb) return LOCAL_GL_FRAMEBUFFER_COMPLETE;
235 return fb->CheckFramebufferStatus().get();
238 RefPtr<WebGLProgram> WebGLContext::CreateProgram() {
239 const FuncScope funcScope(*this, "createProgram");
240 if (IsContextLost()) return nullptr;
242 return new WebGLProgram(this);
245 RefPtr<WebGLShader> WebGLContext::CreateShader(GLenum type) {
246 const FuncScope funcScope(*this, "createShader");
247 if (IsContextLost()) return nullptr;
249 if (type != LOCAL_GL_VERTEX_SHADER && type != LOCAL_GL_FRAGMENT_SHADER) {
250 ErrorInvalidEnumInfo("type", type);
251 return nullptr;
254 return new WebGLShader(this, type);
257 void WebGLContext::CullFace(GLenum face) {
258 const FuncScope funcScope(*this, "cullFace");
259 if (IsContextLost()) return;
261 if (!ValidateFaceEnum(face)) return;
263 gl->fCullFace(face);
266 void WebGLContext::DetachShader(WebGLProgram& prog, const WebGLShader& shader) {
267 FuncScope funcScope(*this, "detachShader");
268 if (IsContextLost()) return;
269 funcScope.mBindFailureGuard = true;
271 prog.DetachShader(shader);
273 funcScope.mBindFailureGuard = false;
276 static bool ValidateComparisonEnum(WebGLContext& webgl, const GLenum func) {
277 switch (func) {
278 case LOCAL_GL_NEVER:
279 case LOCAL_GL_LESS:
280 case LOCAL_GL_LEQUAL:
281 case LOCAL_GL_GREATER:
282 case LOCAL_GL_GEQUAL:
283 case LOCAL_GL_EQUAL:
284 case LOCAL_GL_NOTEQUAL:
285 case LOCAL_GL_ALWAYS:
286 return true;
288 default:
289 webgl.ErrorInvalidEnumInfo("func", func);
290 return false;
294 void WebGLContext::DepthFunc(GLenum func) {
295 const FuncScope funcScope(*this, "depthFunc");
296 if (IsContextLost()) return;
298 if (!ValidateComparisonEnum(*this, func)) return;
300 gl->fDepthFunc(func);
303 void WebGLContext::DepthRange(GLfloat zNear, GLfloat zFar) {
304 const FuncScope funcScope(*this, "depthRange");
305 if (IsContextLost()) return;
307 if (zNear > zFar)
308 return ErrorInvalidOperation(
309 "the near value is greater than the far value!");
311 gl->fDepthRange(zNear, zFar);
314 // -
316 void WebGLContext::FramebufferAttach(const GLenum target,
317 const GLenum attachSlot,
318 const GLenum bindImageTarget,
319 const webgl::FbAttachInfo& toAttach) {
320 FuncScope funcScope(*this, "framebufferAttach");
321 funcScope.mBindFailureGuard = true;
322 const auto& limits = *mLimits;
324 if (!ValidateFramebufferTarget(target)) return;
326 auto fb = mBoundDrawFramebuffer;
327 if (target == LOCAL_GL_READ_FRAMEBUFFER) {
328 fb = mBoundReadFramebuffer;
330 if (!fb) return;
332 // `rb` needs no validation.
334 // `tex`
335 const auto& tex = toAttach.tex;
336 if (tex) {
337 const auto err = CheckFramebufferAttach(bindImageTarget, tex->mTarget.get(),
338 toAttach.mipLevel, toAttach.zLayer,
339 toAttach.zLayerCount, limits);
340 if (err) return;
343 auto safeToAttach = toAttach;
344 if (!toAttach.rb && !toAttach.tex) {
345 safeToAttach = {};
347 if (!IsWebGL2() &&
348 !IsExtensionEnabled(WebGLExtensionID::OES_fbo_render_mipmap)) {
349 safeToAttach.mipLevel = 0;
351 if (!IsExtensionEnabled(WebGLExtensionID::OVR_multiview2)) {
352 safeToAttach.isMultiview = false;
355 if (!fb->FramebufferAttach(attachSlot, safeToAttach)) return;
357 funcScope.mBindFailureGuard = false;
360 // -
362 void WebGLContext::FrontFace(GLenum mode) {
363 const FuncScope funcScope(*this, "frontFace");
364 if (IsContextLost()) return;
366 switch (mode) {
367 case LOCAL_GL_CW:
368 case LOCAL_GL_CCW:
369 break;
370 default:
371 return ErrorInvalidEnumInfo("mode", mode);
374 gl->fFrontFace(mode);
377 Maybe<double> WebGLContext::GetBufferParameter(GLenum target, GLenum pname) {
378 const FuncScope funcScope(*this, "getBufferParameter");
379 if (IsContextLost()) return Nothing();
381 const auto& slot = ValidateBufferSlot(target);
382 if (!slot) return Nothing();
383 const auto& buffer = *slot;
385 if (!buffer) {
386 ErrorInvalidOperation("Buffer for `target` is null.");
387 return Nothing();
390 switch (pname) {
391 case LOCAL_GL_BUFFER_SIZE:
392 return Some(buffer->ByteLength());
394 case LOCAL_GL_BUFFER_USAGE:
395 return Some(buffer->Usage());
397 default:
398 ErrorInvalidEnumInfo("pname", pname);
399 return Nothing();
403 Maybe<double> WebGLContext::GetFramebufferAttachmentParameter(
404 WebGLFramebuffer* const fb, GLenum attachment, GLenum pname) const {
405 const FuncScope funcScope(*this, "getFramebufferAttachmentParameter");
406 if (IsContextLost()) return Nothing();
408 if (fb) return fb->GetAttachmentParameter(attachment, pname);
410 ////////////////////////////////////
412 if (!IsWebGL2()) {
413 ErrorInvalidOperation(
414 "Querying against the default framebuffer is not"
415 " allowed in WebGL 1.");
416 return Nothing();
419 switch (attachment) {
420 case LOCAL_GL_BACK:
421 case LOCAL_GL_DEPTH:
422 case LOCAL_GL_STENCIL:
423 break;
425 default:
426 ErrorInvalidEnum(
427 "For the default framebuffer, can only query COLOR, DEPTH,"
428 " or STENCIL.");
429 return Nothing();
432 switch (pname) {
433 case LOCAL_GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE:
434 switch (attachment) {
435 case LOCAL_GL_BACK:
436 break;
437 case LOCAL_GL_DEPTH:
438 if (!mOptions.depth) {
439 return Some(LOCAL_GL_NONE);
441 break;
442 case LOCAL_GL_STENCIL:
443 if (!mOptions.stencil) {
444 return Some(LOCAL_GL_NONE);
446 break;
447 default:
448 ErrorInvalidEnum(
449 "With the default framebuffer, can only query COLOR, DEPTH,"
450 " or STENCIL for GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE");
451 return Nothing();
453 return Some(LOCAL_GL_FRAMEBUFFER_DEFAULT);
455 ////////////////
457 case LOCAL_GL_FRAMEBUFFER_ATTACHMENT_RED_SIZE:
458 case LOCAL_GL_FRAMEBUFFER_ATTACHMENT_GREEN_SIZE:
459 case LOCAL_GL_FRAMEBUFFER_ATTACHMENT_BLUE_SIZE:
460 if (attachment == LOCAL_GL_BACK) return Some(8);
461 return Some(0);
463 case LOCAL_GL_FRAMEBUFFER_ATTACHMENT_ALPHA_SIZE:
464 if (attachment == LOCAL_GL_BACK) {
465 if (mOptions.alpha) {
466 return Some(8);
468 ErrorInvalidOperation(
469 "The default framebuffer doesn't contain an alpha buffer");
470 return Nothing();
472 return Some(0);
474 case LOCAL_GL_FRAMEBUFFER_ATTACHMENT_DEPTH_SIZE:
475 if (attachment == LOCAL_GL_DEPTH) {
476 if (mOptions.depth) {
477 return Some(24);
479 ErrorInvalidOperation(
480 "The default framebuffer doesn't contain an depth buffer");
481 return Nothing();
483 return Some(0);
485 case LOCAL_GL_FRAMEBUFFER_ATTACHMENT_STENCIL_SIZE:
486 if (attachment == LOCAL_GL_STENCIL) {
487 if (mOptions.stencil) {
488 return Some(8);
490 ErrorInvalidOperation(
491 "The default framebuffer doesn't contain an stencil buffer");
492 return Nothing();
494 return Some(0);
496 case LOCAL_GL_FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE:
497 if (attachment == LOCAL_GL_STENCIL) {
498 if (mOptions.stencil) {
499 return Some(LOCAL_GL_UNSIGNED_INT);
501 ErrorInvalidOperation(
502 "The default framebuffer doesn't contain an stencil buffer");
503 } else if (attachment == LOCAL_GL_DEPTH) {
504 if (mOptions.depth) {
505 return Some(LOCAL_GL_UNSIGNED_NORMALIZED);
507 ErrorInvalidOperation(
508 "The default framebuffer doesn't contain an depth buffer");
509 } else { // LOCAL_GL_BACK
510 return Some(LOCAL_GL_UNSIGNED_NORMALIZED);
512 return Nothing();
514 case LOCAL_GL_FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING:
515 if (attachment == LOCAL_GL_STENCIL) {
516 if (!mOptions.stencil) {
517 ErrorInvalidOperation(
518 "The default framebuffer doesn't contain an stencil buffer");
519 return Nothing();
521 } else if (attachment == LOCAL_GL_DEPTH) {
522 if (!mOptions.depth) {
523 ErrorInvalidOperation(
524 "The default framebuffer doesn't contain an depth buffer");
525 return Nothing();
528 return Some(LOCAL_GL_LINEAR);
531 ErrorInvalidEnumInfo("pname", pname);
532 return Nothing();
535 Maybe<double> WebGLContext::GetRenderbufferParameter(
536 const WebGLRenderbuffer& rb, GLenum pname) const {
537 const FuncScope funcScope(*this, "getRenderbufferParameter");
538 if (IsContextLost()) return Nothing();
540 switch (pname) {
541 case LOCAL_GL_RENDERBUFFER_SAMPLES:
542 if (!IsWebGL2()) break;
543 [[fallthrough]];
545 case LOCAL_GL_RENDERBUFFER_WIDTH:
546 case LOCAL_GL_RENDERBUFFER_HEIGHT:
547 case LOCAL_GL_RENDERBUFFER_RED_SIZE:
548 case LOCAL_GL_RENDERBUFFER_GREEN_SIZE:
549 case LOCAL_GL_RENDERBUFFER_BLUE_SIZE:
550 case LOCAL_GL_RENDERBUFFER_ALPHA_SIZE:
551 case LOCAL_GL_RENDERBUFFER_DEPTH_SIZE:
552 case LOCAL_GL_RENDERBUFFER_STENCIL_SIZE:
553 case LOCAL_GL_RENDERBUFFER_INTERNAL_FORMAT: {
554 // RB emulation means we have to ask the RB itself.
555 GLint i = rb.GetRenderbufferParameter(pname);
556 return Some(i);
559 default:
560 break;
563 ErrorInvalidEnumInfo("pname", pname);
564 return Nothing();
567 RefPtr<WebGLTexture> WebGLContext::CreateTexture() {
568 const FuncScope funcScope(*this, "createTexture");
569 if (IsContextLost()) return nullptr;
571 GLuint tex = 0;
572 gl->fGenTextures(1, &tex);
574 return new WebGLTexture(this, tex);
577 GLenum WebGLContext::GetError() {
578 const FuncScope funcScope(*this, "getError");
580 /* WebGL 1.0: Section 5.14.3: Setting and getting state:
581 * If the context's webgl context lost flag is set, returns
582 * CONTEXT_LOST_WEBGL the first time this method is called.
583 * Afterward, returns NO_ERROR until the context has been
584 * restored.
586 * WEBGL_lose_context:
587 * [When this extension is enabled: ] loseContext and
588 * restoreContext are allowed to generate INVALID_OPERATION errors
589 * even when the context is lost.
592 auto err = mWebGLError;
593 mWebGLError = 0;
594 if (IsContextLost() || err) // Must check IsContextLost in all flow paths.
595 return err;
597 // Either no WebGL-side error, or it's already been cleared.
598 // UnderlyingGL-side errors, now.
599 err = gl->fGetError();
600 if (gl->IsContextLost()) {
601 CheckForContextLoss();
602 return GetError();
604 MOZ_ASSERT(err != LOCAL_GL_CONTEXT_LOST);
606 if (err) {
607 GenerateWarning("Driver error unexpected by WebGL: 0x%04x", err);
608 // This might be:
609 // - INVALID_OPERATION from ANGLE due to incomplete RBAB implementation for
610 // DrawElements
611 // with DYNAMIC_DRAW index buffer.
613 return err;
616 webgl::GetUniformData WebGLContext::GetUniform(const WebGLProgram& prog,
617 const uint32_t loc) const {
618 const FuncScope funcScope(*this, "getUniform");
619 webgl::GetUniformData ret;
620 [&]() {
621 if (IsContextLost()) return;
623 const auto& info = prog.LinkInfo();
624 if (!info) return;
626 const auto locInfo = MaybeFind(info->locationMap, loc);
627 if (!locInfo) return;
629 ret.type = locInfo->info.info.elemType;
630 switch (ret.type) {
631 case LOCAL_GL_FLOAT:
632 case LOCAL_GL_FLOAT_VEC2:
633 case LOCAL_GL_FLOAT_VEC3:
634 case LOCAL_GL_FLOAT_VEC4:
635 case LOCAL_GL_FLOAT_MAT2:
636 case LOCAL_GL_FLOAT_MAT3:
637 case LOCAL_GL_FLOAT_MAT4:
638 case LOCAL_GL_FLOAT_MAT2x3:
639 case LOCAL_GL_FLOAT_MAT2x4:
640 case LOCAL_GL_FLOAT_MAT3x2:
641 case LOCAL_GL_FLOAT_MAT3x4:
642 case LOCAL_GL_FLOAT_MAT4x2:
643 case LOCAL_GL_FLOAT_MAT4x3:
644 gl->fGetUniformfv(prog.mGLName, loc,
645 reinterpret_cast<float*>(ret.data));
646 break;
648 case LOCAL_GL_INT:
649 case LOCAL_GL_INT_VEC2:
650 case LOCAL_GL_INT_VEC3:
651 case LOCAL_GL_INT_VEC4:
652 case LOCAL_GL_SAMPLER_2D:
653 case LOCAL_GL_SAMPLER_3D:
654 case LOCAL_GL_SAMPLER_CUBE:
655 case LOCAL_GL_SAMPLER_2D_SHADOW:
656 case LOCAL_GL_SAMPLER_2D_ARRAY:
657 case LOCAL_GL_SAMPLER_2D_ARRAY_SHADOW:
658 case LOCAL_GL_SAMPLER_CUBE_SHADOW:
659 case LOCAL_GL_INT_SAMPLER_2D:
660 case LOCAL_GL_INT_SAMPLER_3D:
661 case LOCAL_GL_INT_SAMPLER_CUBE:
662 case LOCAL_GL_INT_SAMPLER_2D_ARRAY:
663 case LOCAL_GL_UNSIGNED_INT_SAMPLER_2D:
664 case LOCAL_GL_UNSIGNED_INT_SAMPLER_3D:
665 case LOCAL_GL_UNSIGNED_INT_SAMPLER_CUBE:
666 case LOCAL_GL_UNSIGNED_INT_SAMPLER_2D_ARRAY:
667 case LOCAL_GL_BOOL:
668 case LOCAL_GL_BOOL_VEC2:
669 case LOCAL_GL_BOOL_VEC3:
670 case LOCAL_GL_BOOL_VEC4:
671 gl->fGetUniformiv(prog.mGLName, loc,
672 reinterpret_cast<int32_t*>(ret.data));
673 break;
675 case LOCAL_GL_UNSIGNED_INT:
676 case LOCAL_GL_UNSIGNED_INT_VEC2:
677 case LOCAL_GL_UNSIGNED_INT_VEC3:
678 case LOCAL_GL_UNSIGNED_INT_VEC4:
679 gl->fGetUniformuiv(prog.mGLName, loc,
680 reinterpret_cast<uint32_t*>(ret.data));
681 break;
683 default:
684 MOZ_CRASH("GFX: Invalid elemType.");
686 }();
687 return ret;
690 void WebGLContext::Hint(GLenum target, GLenum mode) {
691 const FuncScope funcScope(*this, "hint");
692 if (IsContextLost()) return;
694 bool isValid = false;
696 switch (target) {
697 case LOCAL_GL_GENERATE_MIPMAP_HINT:
698 mGenerateMipmapHint = mode;
699 isValid = true;
701 // Deprecated and removed in desktop GL Core profiles.
702 if (gl->IsCoreProfile()) return;
704 break;
706 case LOCAL_GL_FRAGMENT_SHADER_DERIVATIVE_HINT:
707 if (IsWebGL2() ||
708 IsExtensionEnabled(WebGLExtensionID::OES_standard_derivatives)) {
709 isValid = true;
711 break;
714 if (!isValid) return ErrorInvalidEnumInfo("target", target);
716 gl->fHint(target, mode);
719 // -
721 void WebGLContext::LinkProgram(WebGLProgram& prog) {
722 const FuncScope funcScope(*this, "linkProgram");
723 if (IsContextLost()) return;
725 prog.LinkProgram();
727 if (!prog.IsLinked()) {
728 // If we failed to link, but `prog == mCurrentProgram`, we are *not*
729 // supposed to null out mActiveProgramLinkInfo.
730 return;
733 if (&prog == mCurrentProgram) {
734 mActiveProgramLinkInfo = prog.LinkInfo();
736 if (gl->WorkAroundDriverBugs() && gl->Vendor() == gl::GLVendor::NVIDIA) {
737 gl->fUseProgram(prog.mGLName);
742 Maybe<webgl::ErrorInfo> SetPixelUnpack(const bool isWebgl2,
743 WebGLPixelStore* const unpacking,
744 const GLenum pname, const GLint param) {
745 if (isWebgl2) {
746 uint32_t* pValueSlot = nullptr;
747 switch (pname) {
748 case LOCAL_GL_UNPACK_IMAGE_HEIGHT:
749 pValueSlot = &unpacking->mUnpackImageHeight;
750 break;
752 case LOCAL_GL_UNPACK_SKIP_IMAGES:
753 pValueSlot = &unpacking->mUnpackSkipImages;
754 break;
756 case LOCAL_GL_UNPACK_ROW_LENGTH:
757 pValueSlot = &unpacking->mUnpackRowLength;
758 break;
760 case LOCAL_GL_UNPACK_SKIP_ROWS:
761 pValueSlot = &unpacking->mUnpackSkipRows;
762 break;
764 case LOCAL_GL_UNPACK_SKIP_PIXELS:
765 pValueSlot = &unpacking->mUnpackSkipPixels;
766 break;
769 if (pValueSlot) {
770 *pValueSlot = static_cast<uint32_t>(param);
771 return {};
775 switch (pname) {
776 case dom::WebGLRenderingContext_Binding::UNPACK_FLIP_Y_WEBGL:
777 unpacking->mFlipY = bool(param);
778 return {};
780 case dom::WebGLRenderingContext_Binding::UNPACK_PREMULTIPLY_ALPHA_WEBGL:
781 unpacking->mPremultiplyAlpha = bool(param);
782 return {};
784 case dom::WebGLRenderingContext_Binding::UNPACK_COLORSPACE_CONVERSION_WEBGL:
785 switch (param) {
786 case LOCAL_GL_NONE:
787 case dom::WebGLRenderingContext_Binding::BROWSER_DEFAULT_WEBGL:
788 break;
790 default: {
791 const nsPrintfCString text("Bad UNPACK_COLORSPACE_CONVERSION: %s",
792 EnumString(param).c_str());
793 return Some(webgl::ErrorInfo{LOCAL_GL_INVALID_VALUE, ToString(text)});
796 unpacking->mColorspaceConversion = param;
797 return {};
799 case dom::MOZ_debug_Binding::UNPACK_REQUIRE_FASTPATH:
800 unpacking->mRequireFastPath = bool(param);
801 return {};
803 case LOCAL_GL_UNPACK_ALIGNMENT:
804 switch (param) {
805 case 1:
806 case 2:
807 case 4:
808 case 8:
809 break;
811 default: {
812 const nsPrintfCString text(
813 "UNPACK_ALIGNMENT must be [1,2,4,8], was %i", param);
814 return Some(webgl::ErrorInfo{LOCAL_GL_INVALID_VALUE, ToString(text)});
817 unpacking->mUnpackAlignment = param;
818 return {};
820 default:
821 break;
823 const nsPrintfCString text("Bad `pname`: %s", EnumString(pname).c_str());
824 return Some(webgl::ErrorInfo{LOCAL_GL_INVALID_ENUM, ToString(text)});
827 bool WebGLContext::DoReadPixelsAndConvert(
828 const webgl::FormatInfo* const srcFormat, const webgl::ReadPixelsDesc& desc,
829 const uintptr_t dest, const uint64_t destSize, const uint32_t rowStride) {
830 const auto& x = desc.srcOffset.x;
831 const auto& y = desc.srcOffset.y;
832 const auto size = *ivec2::From(desc.size);
833 const auto& pi = desc.pi;
835 // On at least Win+NV, we'll get PBO errors if we don't have at least
836 // `rowStride * height` bytes available to read into.
837 const auto naiveBytesNeeded = CheckedInt<uint64_t>(rowStride) * size.y;
838 const bool isDangerCloseToEdge =
839 (!naiveBytesNeeded.isValid() || naiveBytesNeeded.value() > destSize);
840 const bool useParanoidHandling =
841 (gl->WorkAroundDriverBugs() && isDangerCloseToEdge &&
842 mBoundPixelPackBuffer);
843 if (!useParanoidHandling) {
844 gl->fReadPixels(x, y, size.x, size.y, pi.format, pi.type,
845 reinterpret_cast<void*>(dest));
846 return true;
849 // Read everything but the last row.
850 const auto bodyHeight = size.y - 1;
851 if (bodyHeight) {
852 gl->fReadPixels(x, y, size.x, bodyHeight, pi.format, pi.type,
853 reinterpret_cast<void*>(dest));
856 // Now read the last row.
857 gl->fPixelStorei(LOCAL_GL_PACK_ALIGNMENT, 1);
858 gl->fPixelStorei(LOCAL_GL_PACK_ROW_LENGTH, 0);
859 gl->fPixelStorei(LOCAL_GL_PACK_SKIP_ROWS, 0);
861 const auto tailRowOffset =
862 reinterpret_cast<uint8_t*>(dest) + rowStride * bodyHeight;
863 gl->fReadPixels(x, y + bodyHeight, size.x, 1, pi.format, pi.type,
864 tailRowOffset);
866 return true;
869 static bool ValidatePackSize(const WebGLContext& webgl,
870 const webgl::PixelPackState& packing,
871 const uvec2& size, uint8_t bytesPerPixel,
872 uint32_t* const out_rowStride,
873 uint32_t* const out_endOffset) {
874 const auto alignment = packing.alignment;
875 switch (alignment) {
876 case 1:
877 case 2:
878 case 4:
879 case 8:
880 break;
881 default:
882 MOZ_ASSERT(false);
883 webgl.ErrorImplementationBug("Invalid PACK_ALIGNMENT.");
884 return false;
887 if (!size.x || !size.y) {
888 *out_rowStride = 0;
889 *out_endOffset = 0;
890 return true;
893 // GLES 3.0.4, p116 (PACK_ functions like UNPACK_)
895 const auto rowLength = (packing.rowLength ? packing.rowLength : size.x);
896 const auto skipPixels = packing.skipPixels;
897 const auto skipRows = packing.skipRows;
899 const auto usedPixelsPerRow = CheckedUint32(skipPixels) + size.x;
900 const auto usedRowsPerImage = CheckedUint32(skipRows) + size.y;
902 if (!usedPixelsPerRow.isValid() || usedPixelsPerRow.value() > rowLength) {
903 webgl.ErrorInvalidOperation("SKIP_PIXELS + width > ROW_LENGTH.");
904 return false;
907 const auto rowLengthBytes = CheckedUint32(rowLength) * bytesPerPixel;
908 const auto rowStride = RoundUpToMultipleOf(rowLengthBytes, alignment);
910 const auto usedBytesPerRow = usedPixelsPerRow * bytesPerPixel;
911 const auto usedBytesPerImage =
912 (usedRowsPerImage - 1) * rowStride + usedBytesPerRow;
914 if (!rowStride.isValid() || !usedBytesPerImage.isValid()) {
915 webgl.ErrorInvalidOperation("Invalid UNPACK_ params.");
916 return false;
919 *out_rowStride = rowStride.value();
920 *out_endOffset = usedBytesPerImage.value();
921 return true;
924 webgl::ReadPixelsResult WebGLContext::ReadPixelsInto(
925 const webgl::ReadPixelsDesc& desc, const Range<uint8_t>& dest) {
926 const FuncScope funcScope(*this, "readPixels");
927 if (IsContextLost()) return {};
929 if (mBoundPixelPackBuffer) {
930 ErrorInvalidOperation("PIXEL_PACK_BUFFER must be null.");
931 return {};
934 return ReadPixelsImpl(desc, reinterpret_cast<uintptr_t>(dest.begin().get()),
935 dest.length());
938 void WebGLContext::ReadPixelsPbo(const webgl::ReadPixelsDesc& desc,
939 const uint64_t offset) {
940 const FuncScope funcScope(*this, "readPixels");
941 if (IsContextLost()) return;
943 const auto& buffer = ValidateBufferSelection(LOCAL_GL_PIXEL_PACK_BUFFER);
944 if (!buffer) return;
946 //////
949 const auto bytesPerType =
950 webgl::BytesPerPixel({LOCAL_GL_RED, desc.pi.type});
952 if (offset % bytesPerType != 0) {
953 ErrorInvalidOperation(
954 "`offset` must be divisible by the size of `type`"
955 " in bytes.");
956 return;
960 //////
962 auto bytesAvailable = buffer->ByteLength();
963 if (offset > bytesAvailable) {
964 ErrorInvalidOperation("`offset` too large for bound PIXEL_PACK_BUFFER.");
965 return;
967 bytesAvailable -= offset;
969 // -
971 const ScopedLazyBind lazyBind(gl, LOCAL_GL_PIXEL_PACK_BUFFER, buffer);
973 ReadPixelsImpl(desc, offset, bytesAvailable);
975 buffer->ResetLastUpdateFenceId();
978 static webgl::PackingInfo DefaultReadPixelPI(
979 const webgl::FormatUsageInfo* usage) {
980 MOZ_ASSERT(usage->IsRenderable());
981 const auto& format = *usage->format;
982 switch (format.componentType) {
983 case webgl::ComponentType::NormUInt:
984 if (format.r == 16) {
985 return {LOCAL_GL_RGBA, LOCAL_GL_UNSIGNED_SHORT};
987 return {LOCAL_GL_RGBA, LOCAL_GL_UNSIGNED_BYTE};
989 case webgl::ComponentType::Int:
990 return {LOCAL_GL_RGBA_INTEGER, LOCAL_GL_INT};
992 case webgl::ComponentType::UInt:
993 return {LOCAL_GL_RGBA_INTEGER, LOCAL_GL_UNSIGNED_INT};
995 case webgl::ComponentType::Float:
996 return {LOCAL_GL_RGBA, LOCAL_GL_FLOAT};
998 default:
999 MOZ_CRASH();
1003 static bool ArePossiblePackEnums(const WebGLContext* webgl,
1004 const webgl::PackingInfo& pi) {
1005 // OpenGL ES 2.0 $4.3.1 - IMPLEMENTATION_COLOR_READ_{TYPE/FORMAT} is a valid
1006 // combination for glReadPixels()...
1008 // Only valid when pulled from:
1009 // * GLES 2.0.25 p105:
1010 // "table 3.4, excluding formats LUMINANCE and LUMINANCE_ALPHA."
1011 // * GLES 3.0.4 p193:
1012 // "table 3.2, excluding formats DEPTH_COMPONENT and DEPTH_STENCIL."
1013 switch (pi.format) {
1014 case LOCAL_GL_LUMINANCE:
1015 case LOCAL_GL_LUMINANCE_ALPHA:
1016 case LOCAL_GL_DEPTH_COMPONENT:
1017 case LOCAL_GL_DEPTH_STENCIL:
1018 return false;
1021 if (pi.type == LOCAL_GL_UNSIGNED_INT_24_8) return false;
1023 uint8_t bytes;
1024 if (!GetBytesPerPixel(pi, &bytes)) return false;
1026 return true;
1029 webgl::PackingInfo WebGLContext::ValidImplementationColorReadPI(
1030 const webgl::FormatUsageInfo* usage) const {
1031 const auto defaultPI = DefaultReadPixelPI(usage);
1033 // ES2_compatibility always returns RGBA/UNSIGNED_BYTE, so branch on actual
1034 // IsGLES(). Also OSX+NV generates an error here.
1035 if (!gl->IsGLES()) return defaultPI;
1037 webgl::PackingInfo implPI;
1038 gl->fGetIntegerv(LOCAL_GL_IMPLEMENTATION_COLOR_READ_FORMAT,
1039 (GLint*)&implPI.format);
1040 gl->fGetIntegerv(LOCAL_GL_IMPLEMENTATION_COLOR_READ_TYPE,
1041 (GLint*)&implPI.type);
1043 if (!ArePossiblePackEnums(this, implPI)) return defaultPI;
1045 return implPI;
1048 static bool ValidateReadPixelsFormatAndType(
1049 const webgl::FormatUsageInfo* srcUsage, const webgl::PackingInfo& pi,
1050 gl::GLContext* gl, WebGLContext* webgl) {
1051 if (!ArePossiblePackEnums(webgl, pi)) {
1052 webgl->ErrorInvalidEnum("Unexpected format or type.");
1053 return false;
1056 const auto defaultPI = DefaultReadPixelPI(srcUsage);
1057 if (pi == defaultPI) return true;
1059 ////
1061 // OpenGL ES 3.0.4 p194 - When the internal format of the rendering surface is
1062 // RGB10_A2, a third combination of format RGBA and type
1063 // UNSIGNED_INT_2_10_10_10_REV is accepted.
1065 if (webgl->IsWebGL2() &&
1066 srcUsage->format->effectiveFormat == webgl::EffectiveFormat::RGB10_A2 &&
1067 pi.format == LOCAL_GL_RGBA &&
1068 pi.type == LOCAL_GL_UNSIGNED_INT_2_10_10_10_REV) {
1069 return true;
1072 ////
1074 MOZ_ASSERT(gl->IsCurrent());
1075 const auto implPI = webgl->ValidImplementationColorReadPI(srcUsage);
1076 if (pi == implPI) return true;
1078 ////
1080 // clang-format off
1081 webgl->ErrorInvalidOperation(
1082 "Format and type %s/%s incompatible with this %s attachment."
1083 " This framebuffer requires either %s/%s or"
1084 " getParameter(IMPLEMENTATION_COLOR_READ_FORMAT/_TYPE) %s/%s.",
1085 EnumString(pi.format).c_str(), EnumString(pi.type).c_str(),
1086 srcUsage->format->name,
1087 EnumString(defaultPI.format).c_str(), EnumString(defaultPI.type).c_str(),
1088 EnumString(implPI.format).c_str(), EnumString(implPI.type).c_str());
1089 // clang-format on
1091 return false;
1094 webgl::ReadPixelsResult WebGLContext::ReadPixelsImpl(
1095 const webgl::ReadPixelsDesc& desc, const uintptr_t dest,
1096 const uint64_t availBytes) {
1097 const webgl::FormatUsageInfo* srcFormat;
1098 uint32_t srcWidth;
1099 uint32_t srcHeight;
1100 if (!BindCurFBForColorRead(&srcFormat, &srcWidth, &srcHeight)) return {};
1102 //////
1104 if (!ValidateReadPixelsFormatAndType(srcFormat, desc.pi, gl, this)) return {};
1106 uint8_t bytesPerPixel;
1107 if (!webgl::GetBytesPerPixel(desc.pi, &bytesPerPixel)) {
1108 ErrorInvalidOperation("Unsupported format and type.");
1109 return {};
1112 //////
1114 const auto& srcOffset = desc.srcOffset;
1115 const auto& size = desc.size;
1117 if (!ivec2::From(size)) {
1118 ErrorInvalidValue("width and height must be non-negative.");
1119 return {};
1122 const auto& packing = desc.packState;
1123 uint32_t rowStride;
1124 uint32_t bytesNeeded;
1125 if (!ValidatePackSize(*this, packing, size, bytesPerPixel, &rowStride,
1126 &bytesNeeded))
1127 return {};
1129 if (bytesNeeded > availBytes) {
1130 ErrorInvalidOperation("buffer too small");
1131 return {};
1134 ////
1136 int32_t readX, readY;
1137 int32_t writeX, writeY;
1138 int32_t rwWidth, rwHeight;
1139 if (!Intersect(srcWidth, srcOffset.x, size.x, &readX, &writeX, &rwWidth) ||
1140 !Intersect(srcHeight, srcOffset.y, size.y, &readY, &writeY, &rwHeight)) {
1141 ErrorOutOfMemory("Bad subrect selection.");
1142 return {};
1145 ////////////////
1146 // Now that the errors are out of the way, on to actually reading!
1148 gl->fPixelStorei(LOCAL_GL_PACK_ALIGNMENT, packing.alignment);
1149 if (IsWebGL2()) {
1150 gl->fPixelStorei(LOCAL_GL_PACK_ROW_LENGTH, packing.rowLength);
1151 gl->fPixelStorei(LOCAL_GL_PACK_SKIP_PIXELS, packing.skipPixels);
1152 gl->fPixelStorei(LOCAL_GL_PACK_SKIP_ROWS, packing.skipRows);
1155 if (!rwWidth || !rwHeight) {
1156 // Disjoint rects, so we're done already.
1157 DummyReadFramebufferOperation();
1158 return {};
1160 const auto rwSize = *uvec2::From(rwWidth, rwHeight);
1162 const auto res = webgl::ReadPixelsResult{
1163 {{writeX, writeY}, {rwSize.x, rwSize.y}}, rowStride};
1165 if (rwSize == size) {
1166 DoReadPixelsAndConvert(srcFormat->format, desc, dest, bytesNeeded,
1167 rowStride);
1168 return res;
1171 // Read request contains out-of-bounds pixels. Unfortunately:
1172 // GLES 3.0.4 p194 "Obtaining Pixels from the Framebuffer":
1173 // "If any of these pixels lies outside of the window allocated to the current
1174 // GL context, or outside of the image attached to the currently bound
1175 // framebuffer object, then the values obtained for those pixels are
1176 // undefined."
1178 // This is a slow-path, so warn people away!
1179 GenerateWarning(
1180 "Out-of-bounds reads with readPixels are deprecated, and"
1181 " may be slow.");
1183 ////////////////////////////////////
1184 // Read only the in-bounds pixels.
1186 if (IsWebGL2()) {
1187 if (!packing.rowLength) {
1188 gl->fPixelStorei(LOCAL_GL_PACK_ROW_LENGTH, packing.skipPixels + size.x);
1190 gl->fPixelStorei(LOCAL_GL_PACK_SKIP_PIXELS, packing.skipPixels + writeX);
1191 gl->fPixelStorei(LOCAL_GL_PACK_SKIP_ROWS, packing.skipRows + writeY);
1193 auto desc2 = desc;
1194 desc2.srcOffset = {readX, readY};
1195 desc2.size = rwSize;
1197 DoReadPixelsAndConvert(srcFormat->format, desc2, dest, bytesNeeded,
1198 rowStride);
1199 } else {
1200 // I *did* say "hilariously slow".
1202 auto desc2 = desc;
1203 desc2.srcOffset = {readX, readY};
1204 desc2.size = {rwSize.x, 1};
1206 auto row = dest + writeX * bytesPerPixel;
1207 row += writeY * rowStride;
1208 for (const auto j : IntegerRange(size.y)) {
1209 desc2.srcOffset.y = readY + j;
1210 DoReadPixelsAndConvert(srcFormat->format, desc2, row, bytesNeeded,
1211 rowStride);
1212 row += rowStride;
1216 return res;
1219 void WebGLContext::RenderbufferStorageMultisample(WebGLRenderbuffer& rb,
1220 uint32_t samples,
1221 GLenum internalFormat,
1222 uint32_t width,
1223 uint32_t height) const {
1224 const FuncScope funcScope(*this, "renderbufferStorage(Multisample)?");
1225 if (IsContextLost()) return;
1227 rb.RenderbufferStorage(samples, internalFormat, width, height);
1230 void WebGLContext::Scissor(GLint x, GLint y, GLsizei width, GLsizei height) {
1231 const FuncScope funcScope(*this, "scissor");
1232 if (IsContextLost()) return;
1234 if (!ValidateNonNegative("width", width) ||
1235 !ValidateNonNegative("height", height)) {
1236 return;
1239 mScissorRect = {x, y, width, height};
1240 mScissorRect.Apply(*gl);
1243 void WebGLContext::StencilFuncSeparate(GLenum face, GLenum func, GLint ref,
1244 GLuint mask) {
1245 const FuncScope funcScope(*this, "stencilFuncSeparate");
1246 if (IsContextLost()) return;
1248 if (!ValidateFaceEnum(face) || !ValidateComparisonEnum(*this, func)) {
1249 return;
1252 switch (face) {
1253 case LOCAL_GL_FRONT_AND_BACK:
1254 mStencilRefFront = ref;
1255 mStencilRefBack = ref;
1256 mStencilValueMaskFront = mask;
1257 mStencilValueMaskBack = mask;
1258 break;
1259 case LOCAL_GL_FRONT:
1260 mStencilRefFront = ref;
1261 mStencilValueMaskFront = mask;
1262 break;
1263 case LOCAL_GL_BACK:
1264 mStencilRefBack = ref;
1265 mStencilValueMaskBack = mask;
1266 break;
1269 gl->fStencilFuncSeparate(face, func, ref, mask);
1272 void WebGLContext::StencilOpSeparate(GLenum face, GLenum sfail, GLenum dpfail,
1273 GLenum dppass) {
1274 const FuncScope funcScope(*this, "stencilOpSeparate");
1275 if (IsContextLost()) return;
1277 if (!ValidateFaceEnum(face) || !ValidateStencilOpEnum(sfail, "sfail") ||
1278 !ValidateStencilOpEnum(dpfail, "dpfail") ||
1279 !ValidateStencilOpEnum(dppass, "dppass"))
1280 return;
1282 gl->fStencilOpSeparate(face, sfail, dpfail, dppass);
1285 ////////////////////////////////////////////////////////////////////////////////
1286 // Uniform setters.
1288 void WebGLContext::UniformData(const uint32_t loc, const bool transpose,
1289 const Range<const uint8_t>& 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() / sizeof(float);
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 for (const auto& val : Range<const uint32_t>(srcBegin, elemCount)) {
1357 if (destIndex >= texUnits.size()) break;
1358 texUnits[destIndex] = val;
1359 destIndex += 1;
1364 ////////////////////////////////////////////////////////////////////////////////
1366 void WebGLContext::UseProgram(WebGLProgram* prog) {
1367 FuncScope funcScope(*this, "useProgram");
1368 if (IsContextLost()) return;
1369 funcScope.mBindFailureGuard = true;
1371 if (!prog) {
1372 mCurrentProgram = nullptr;
1373 mActiveProgramLinkInfo = nullptr;
1374 funcScope.mBindFailureGuard = false;
1375 return;
1378 if (!ValidateObject("prog", *prog)) return;
1380 if (!prog->UseProgram()) return;
1382 mCurrentProgram = prog;
1383 mActiveProgramLinkInfo = mCurrentProgram->LinkInfo();
1385 funcScope.mBindFailureGuard = false;
1388 bool WebGLContext::ValidateProgram(const WebGLProgram& prog) const {
1389 const FuncScope funcScope(*this, "validateProgram");
1390 if (IsContextLost()) return false;
1392 return prog.ValidateProgram();
1395 RefPtr<WebGLFramebuffer> WebGLContext::CreateFramebuffer() {
1396 const FuncScope funcScope(*this, "createFramebuffer");
1397 if (IsContextLost()) return nullptr;
1399 GLuint fbo = 0;
1400 gl->fGenFramebuffers(1, &fbo);
1402 return new WebGLFramebuffer(this, fbo);
1405 RefPtr<WebGLFramebuffer> WebGLContext::CreateOpaqueFramebuffer(
1406 const webgl::OpaqueFramebufferOptions& options) {
1407 const FuncScope funcScope(*this, "createOpaqueFramebuffer");
1408 if (IsContextLost()) return nullptr;
1410 uint32_t samples = options.antialias ? StaticPrefs::webgl_msaa_samples() : 0;
1411 samples = std::min(samples, gl->MaxSamples());
1412 const gfx::IntSize size = {options.width, options.height};
1414 auto fbo =
1415 gl::MozFramebuffer::Create(gl, size, samples, options.depthStencil);
1416 if (!fbo) {
1417 return nullptr;
1420 return new WebGLFramebuffer(this, std::move(fbo));
1423 RefPtr<WebGLRenderbuffer> WebGLContext::CreateRenderbuffer() {
1424 const FuncScope funcScope(*this, "createRenderbuffer");
1425 if (IsContextLost()) return nullptr;
1427 return new WebGLRenderbuffer(this);
1430 void WebGLContext::Viewport(GLint x, GLint y, GLsizei width, GLsizei height) {
1431 const FuncScope funcScope(*this, "viewport");
1432 if (IsContextLost()) return;
1434 if (!ValidateNonNegative("width", width) ||
1435 !ValidateNonNegative("height", height)) {
1436 return;
1439 const auto& limits = Limits();
1440 width = std::min(width, static_cast<GLsizei>(limits.maxViewportDims[0]));
1441 height = std::min(height, static_cast<GLsizei>(limits.maxViewportDims[1]));
1443 gl->fViewport(x, y, width, height);
1445 mViewportX = x;
1446 mViewportY = y;
1447 mViewportWidth = width;
1448 mViewportHeight = height;
1451 void WebGLContext::CompileShader(WebGLShader& shader) {
1452 const FuncScope funcScope(*this, "compileShader");
1453 if (IsContextLost()) return;
1455 if (!ValidateObject("shader", shader)) return;
1457 shader.CompileShader();
1460 Maybe<webgl::ShaderPrecisionFormat> WebGLContext::GetShaderPrecisionFormat(
1461 GLenum shadertype, GLenum precisiontype) const {
1462 const FuncScope funcScope(*this, "getShaderPrecisionFormat");
1463 if (IsContextLost()) return Nothing();
1465 switch (shadertype) {
1466 case LOCAL_GL_FRAGMENT_SHADER:
1467 case LOCAL_GL_VERTEX_SHADER:
1468 break;
1469 default:
1470 ErrorInvalidEnumInfo("shadertype", shadertype);
1471 return Nothing();
1474 switch (precisiontype) {
1475 case LOCAL_GL_LOW_FLOAT:
1476 case LOCAL_GL_MEDIUM_FLOAT:
1477 case LOCAL_GL_HIGH_FLOAT:
1478 case LOCAL_GL_LOW_INT:
1479 case LOCAL_GL_MEDIUM_INT:
1480 case LOCAL_GL_HIGH_INT:
1481 break;
1482 default:
1483 ErrorInvalidEnumInfo("precisiontype", precisiontype);
1484 return Nothing();
1487 GLint range[2], precision;
1489 if (mDisableFragHighP && shadertype == LOCAL_GL_FRAGMENT_SHADER &&
1490 (precisiontype == LOCAL_GL_HIGH_FLOAT ||
1491 precisiontype == LOCAL_GL_HIGH_INT)) {
1492 precision = 0;
1493 range[0] = 0;
1494 range[1] = 0;
1495 } else {
1496 gl->fGetShaderPrecisionFormat(shadertype, precisiontype, range, &precision);
1499 return Some(webgl::ShaderPrecisionFormat{range[0], range[1], precision});
1502 void WebGLContext::ShaderSource(WebGLShader& shader,
1503 const std::string& source) const {
1504 const FuncScope funcScope(*this, "shaderSource");
1505 if (IsContextLost()) return;
1507 shader.ShaderSource(source);
1510 void WebGLContext::BlendColor(GLfloat r, GLfloat g, GLfloat b, GLfloat a) {
1511 const FuncScope funcScope(*this, "blendColor");
1512 if (IsContextLost()) return;
1514 gl->fBlendColor(r, g, b, a);
1517 void WebGLContext::Flush() {
1518 const FuncScope funcScope(*this, "flush");
1519 if (IsContextLost()) return;
1521 gl->fFlush();
1524 void WebGLContext::Finish() {
1525 const FuncScope funcScope(*this, "finish");
1526 if (IsContextLost()) return;
1528 gl->fFinish();
1530 mCompletedFenceId = mNextFenceId;
1531 mNextFenceId += 1;
1534 void WebGLContext::LineWidth(GLfloat width) {
1535 const FuncScope funcScope(*this, "lineWidth");
1536 if (IsContextLost()) return;
1538 // Doing it this way instead of `if (width <= 0.0)` handles NaNs.
1539 const bool isValid = width > 0.0;
1540 if (!isValid) {
1541 ErrorInvalidValue("`width` must be positive and non-zero.");
1542 return;
1545 mLineWidth = width;
1547 if (gl->IsCoreProfile() && width > 1.0) {
1548 width = 1.0;
1551 gl->fLineWidth(width);
1554 void WebGLContext::PolygonOffset(GLfloat factor, GLfloat units) {
1555 const FuncScope funcScope(*this, "polygonOffset");
1556 if (IsContextLost()) return;
1558 gl->fPolygonOffset(factor, units);
1561 void WebGLContext::SampleCoverage(GLclampf value, WebGLboolean invert) {
1562 const FuncScope funcScope(*this, "sampleCoverage");
1563 if (IsContextLost()) return;
1565 gl->fSampleCoverage(value, invert);
1568 } // namespace mozilla