OSDN Git Service

Accept GL_TEXTURE_MAX_ANISOTROPY_EXT for samplers.
[android-x86/external-swiftshader.git] / src / OpenGL / libGLESv2 / Context.cpp
1 // Copyright 2016 The SwiftShader Authors. All Rights Reserved.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 //    http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 // Context.cpp: Implements the es2::Context class, managing all GL state and performing
16 // rendering operations. It is the GLES2 specific implementation of EGLContext.
17
18 #include "Context.h"
19
20 #include "main.h"
21 #include "mathutil.h"
22 #include "utilities.h"
23 #include "ResourceManager.h"
24 #include "Buffer.h"
25 #include "Fence.h"
26 #include "Framebuffer.h"
27 #include "Program.h"
28 #include "Query.h"
29 #include "Renderbuffer.h"
30 #include "Sampler.h"
31 #include "Shader.h"
32 #include "Texture.h"
33 #include "TransformFeedback.h"
34 #include "VertexArray.h"
35 #include "VertexDataManager.h"
36 #include "IndexDataManager.h"
37 #include "libEGL/Display.h"
38 #include "common/Surface.hpp"
39 #include "Common/Half.hpp"
40
41 #include <EGL/eglext.h>
42
43 #include <algorithm>
44 #include <string>
45
46 namespace es2
47 {
48 Context::Context(egl::Display *display, const Context *shareContext, EGLint clientVersion, const egl::Config *config)
49         : egl::Context(display), clientVersion(clientVersion), config(config)
50 {
51         sw::Context *context = new sw::Context();
52         device = new es2::Device(context);
53
54         setClearColor(0.0f, 0.0f, 0.0f, 0.0f);
55
56         mState.depthClearValue = 1.0f;
57         mState.stencilClearValue = 0;
58
59         mState.cullFaceEnabled = false;
60         mState.cullMode = GL_BACK;
61         mState.frontFace = GL_CCW;
62         mState.depthTestEnabled = false;
63         mState.depthFunc = GL_LESS;
64         mState.blendEnabled = false;
65         mState.sourceBlendRGB = GL_ONE;
66         mState.sourceBlendAlpha = GL_ONE;
67         mState.destBlendRGB = GL_ZERO;
68         mState.destBlendAlpha = GL_ZERO;
69         mState.blendEquationRGB = GL_FUNC_ADD;
70         mState.blendEquationAlpha = GL_FUNC_ADD;
71         mState.blendColor.red = 0;
72         mState.blendColor.green = 0;
73         mState.blendColor.blue = 0;
74         mState.blendColor.alpha = 0;
75         mState.stencilTestEnabled = false;
76         mState.stencilFunc = GL_ALWAYS;
77         mState.stencilRef = 0;
78         mState.stencilMask = 0xFFFFFFFFu;
79         mState.stencilWritemask = 0xFFFFFFFFu;
80         mState.stencilBackFunc = GL_ALWAYS;
81         mState.stencilBackRef = 0;
82         mState.stencilBackMask = 0xFFFFFFFFu;
83         mState.stencilBackWritemask = 0xFFFFFFFFu;
84         mState.stencilFail = GL_KEEP;
85         mState.stencilPassDepthFail = GL_KEEP;
86         mState.stencilPassDepthPass = GL_KEEP;
87         mState.stencilBackFail = GL_KEEP;
88         mState.stencilBackPassDepthFail = GL_KEEP;
89         mState.stencilBackPassDepthPass = GL_KEEP;
90         mState.polygonOffsetFillEnabled = false;
91         mState.polygonOffsetFactor = 0.0f;
92         mState.polygonOffsetUnits = 0.0f;
93         mState.sampleAlphaToCoverageEnabled = false;
94         mState.sampleCoverageEnabled = false;
95         mState.sampleCoverageValue = 1.0f;
96         mState.sampleCoverageInvert = false;
97         mState.scissorTestEnabled = false;
98         mState.ditherEnabled = true;
99         mState.primitiveRestartFixedIndexEnabled = false;
100         mState.rasterizerDiscardEnabled = false;
101         mState.generateMipmapHint = GL_DONT_CARE;
102         mState.fragmentShaderDerivativeHint = GL_DONT_CARE;
103         mState.textureFilteringHint = GL_DONT_CARE;
104
105         mState.lineWidth = 1.0f;
106
107         mState.viewportX = 0;
108         mState.viewportY = 0;
109         mState.viewportWidth = 0;
110         mState.viewportHeight = 0;
111         mState.zNear = 0.0f;
112         mState.zFar = 1.0f;
113
114         mState.scissorX = 0;
115         mState.scissorY = 0;
116         mState.scissorWidth = 0;
117         mState.scissorHeight = 0;
118
119         mState.colorMaskRed = true;
120         mState.colorMaskGreen = true;
121         mState.colorMaskBlue = true;
122         mState.colorMaskAlpha = true;
123         mState.depthMask = true;
124
125         if(shareContext)
126         {
127                 mResourceManager = shareContext->mResourceManager;
128                 mResourceManager->addRef();
129         }
130         else
131         {
132                 mResourceManager = new ResourceManager();
133         }
134
135         // [OpenGL ES 2.0.24] section 3.7 page 83:
136         // In the initial state, TEXTURE_2D and TEXTURE_CUBE_MAP have twodimensional
137         // and cube map texture state vectors respectively associated with them.
138         // In order that access to these initial textures not be lost, they are treated as texture
139         // objects all of whose names are 0.
140
141         mTexture2DZero = new Texture2D(0);
142         mTexture3DZero = new Texture3D(0);
143         mTexture2DArrayZero = new Texture2DArray(0);
144         mTextureCubeMapZero = new TextureCubeMap(0);
145         mTexture2DRectZero = new Texture2DRect(0);
146         mTextureExternalZero = new TextureExternal(0);
147
148         mState.activeSampler = 0;
149
150         for(int type = 0; type < TEXTURE_TYPE_COUNT; type++)
151         {
152                 bindTexture((TextureType)type, 0);
153         }
154
155         bindVertexArray(0);
156         bindArrayBuffer(0);
157         bindElementArrayBuffer(0);
158         bindReadFramebuffer(0);
159         bindDrawFramebuffer(0);
160         bindRenderbuffer(0);
161         bindGenericUniformBuffer(0);
162         bindTransformFeedback(0);
163
164         mState.currentProgram = 0;
165
166         mVertexDataManager = nullptr;
167         mIndexDataManager = nullptr;
168
169         mInvalidEnum = false;
170         mInvalidValue = false;
171         mInvalidOperation = false;
172         mOutOfMemory = false;
173         mInvalidFramebufferOperation = false;
174
175         mHasBeenCurrent = false;
176
177         markAllStateDirty();
178 }
179
180 Context::~Context()
181 {
182         if(mState.currentProgram != 0)
183         {
184                 Program *programObject = mResourceManager->getProgram(mState.currentProgram);
185                 if(programObject)
186                 {
187                         programObject->release();
188                 }
189                 mState.currentProgram = 0;
190         }
191
192         while(!mFramebufferNameSpace.empty())
193         {
194                 deleteFramebuffer(mFramebufferNameSpace.firstName());
195         }
196
197         while(!mFenceNameSpace.empty())
198         {
199                 deleteFence(mFenceNameSpace.firstName());
200         }
201
202         while(!mQueryNameSpace.empty())
203         {
204                 deleteQuery(mQueryNameSpace.firstName());
205         }
206
207         while(!mVertexArrayNameSpace.empty())
208         {
209                 deleteVertexArray(mVertexArrayNameSpace.lastName());
210         }
211
212         while(!mTransformFeedbackNameSpace.empty())
213         {
214                 deleteTransformFeedback(mTransformFeedbackNameSpace.firstName());
215         }
216
217         for(int type = 0; type < TEXTURE_TYPE_COUNT; type++)
218         {
219                 for(int sampler = 0; sampler < MAX_COMBINED_TEXTURE_IMAGE_UNITS; sampler++)
220                 {
221                         mState.samplerTexture[type][sampler] = nullptr;
222                 }
223         }
224
225         for(int i = 0; i < MAX_VERTEX_ATTRIBS; i++)
226         {
227                 mState.vertexAttribute[i].mBoundBuffer = nullptr;
228         }
229
230         for(int i = 0; i < QUERY_TYPE_COUNT; i++)
231         {
232                 mState.activeQuery[i] = nullptr;
233         }
234
235         mState.arrayBuffer = nullptr;
236         mState.copyReadBuffer = nullptr;
237         mState.copyWriteBuffer = nullptr;
238         mState.pixelPackBuffer = nullptr;
239         mState.pixelUnpackBuffer = nullptr;
240         mState.genericUniformBuffer = nullptr;
241
242         for(int i = 0; i < MAX_UNIFORM_BUFFER_BINDINGS; i++) {
243                 mState.uniformBuffers[i].set(nullptr, 0, 0);
244         }
245
246         mState.renderbuffer = nullptr;
247
248         for(int i = 0; i < MAX_COMBINED_TEXTURE_IMAGE_UNITS; ++i)
249         {
250                 mState.sampler[i] = nullptr;
251         }
252
253         mTexture2DZero = nullptr;
254         mTexture3DZero = nullptr;
255         mTexture2DArrayZero = nullptr;
256         mTextureCubeMapZero = nullptr;
257         mTexture2DRectZero = nullptr;
258         mTextureExternalZero = nullptr;
259
260         delete mVertexDataManager;
261         delete mIndexDataManager;
262
263         mResourceManager->release();
264         delete device;
265 }
266
267 void Context::makeCurrent(gl::Surface *surface)
268 {
269         if(!mHasBeenCurrent)
270         {
271                 mVertexDataManager = new VertexDataManager(this);
272                 mIndexDataManager = new IndexDataManager();
273
274                 mState.viewportX = 0;
275                 mState.viewportY = 0;
276                 mState.viewportWidth = surface ? surface->getWidth() : 0;
277                 mState.viewportHeight = surface ? surface->getHeight() : 0;
278
279                 mState.scissorX = 0;
280                 mState.scissorY = 0;
281                 mState.scissorWidth = surface ? surface->getWidth() : 0;
282                 mState.scissorHeight = surface ? surface->getHeight() : 0;
283
284                 mHasBeenCurrent = true;
285         }
286
287         if(surface)
288         {
289                 // Wrap the existing resources into GL objects and assign them to the '0' names
290                 egl::Image *defaultRenderTarget = surface->getRenderTarget();
291                 egl::Image *depthStencil = surface->getDepthStencil();
292
293                 Colorbuffer *colorbufferZero = new Colorbuffer(defaultRenderTarget);
294                 DepthStencilbuffer *depthStencilbufferZero = new DepthStencilbuffer(depthStencil);
295                 Framebuffer *framebufferZero = new DefaultFramebuffer(colorbufferZero, depthStencilbufferZero);
296
297                 setFramebufferZero(framebufferZero);
298
299                 if(defaultRenderTarget)
300                 {
301                         defaultRenderTarget->release();
302                 }
303
304                 if(depthStencil)
305                 {
306                         depthStencil->release();
307                 }
308         }
309         else
310         {
311                 setFramebufferZero(nullptr);
312         }
313
314         markAllStateDirty();
315 }
316
317 EGLint Context::getClientVersion() const
318 {
319         return clientVersion;
320 }
321
322 EGLint Context::getConfigID() const
323 {
324         return config->mConfigID;
325 }
326
327 // This function will set all of the state-related dirty flags, so that all state is set during next pre-draw.
328 void Context::markAllStateDirty()
329 {
330         mAppliedProgramSerial = 0;
331
332         mDepthStateDirty = true;
333         mMaskStateDirty = true;
334         mBlendStateDirty = true;
335         mStencilStateDirty = true;
336         mPolygonOffsetStateDirty = true;
337         mSampleStateDirty = true;
338         mDitherStateDirty = true;
339         mFrontFaceDirty = true;
340 }
341
342 void Context::setClearColor(float red, float green, float blue, float alpha)
343 {
344         mState.colorClearValue.red = red;
345         mState.colorClearValue.green = green;
346         mState.colorClearValue.blue = blue;
347         mState.colorClearValue.alpha = alpha;
348 }
349
350 void Context::setClearDepth(float depth)
351 {
352         mState.depthClearValue = depth;
353 }
354
355 void Context::setClearStencil(int stencil)
356 {
357         mState.stencilClearValue = stencil;
358 }
359
360 void Context::setCullFaceEnabled(bool enabled)
361 {
362         mState.cullFaceEnabled = enabled;
363 }
364
365 bool Context::isCullFaceEnabled() const
366 {
367         return mState.cullFaceEnabled;
368 }
369
370 void Context::setCullMode(GLenum mode)
371 {
372    mState.cullMode = mode;
373 }
374
375 void Context::setFrontFace(GLenum front)
376 {
377         if(mState.frontFace != front)
378         {
379                 mState.frontFace = front;
380                 mFrontFaceDirty = true;
381         }
382 }
383
384 void Context::setDepthTestEnabled(bool enabled)
385 {
386         if(mState.depthTestEnabled != enabled)
387         {
388                 mState.depthTestEnabled = enabled;
389                 mDepthStateDirty = true;
390         }
391 }
392
393 bool Context::isDepthTestEnabled() const
394 {
395         return mState.depthTestEnabled;
396 }
397
398 void Context::setDepthFunc(GLenum depthFunc)
399 {
400         if(mState.depthFunc != depthFunc)
401         {
402                 mState.depthFunc = depthFunc;
403                 mDepthStateDirty = true;
404         }
405 }
406
407 void Context::setDepthRange(float zNear, float zFar)
408 {
409         mState.zNear = zNear;
410         mState.zFar = zFar;
411 }
412
413 void Context::setBlendEnabled(bool enabled)
414 {
415         if(mState.blendEnabled != enabled)
416         {
417                 mState.blendEnabled = enabled;
418                 mBlendStateDirty = true;
419         }
420 }
421
422 bool Context::isBlendEnabled() const
423 {
424         return mState.blendEnabled;
425 }
426
427 void Context::setBlendFactors(GLenum sourceRGB, GLenum destRGB, GLenum sourceAlpha, GLenum destAlpha)
428 {
429         if(mState.sourceBlendRGB != sourceRGB ||
430            mState.sourceBlendAlpha != sourceAlpha ||
431            mState.destBlendRGB != destRGB ||
432            mState.destBlendAlpha != destAlpha)
433         {
434                 mState.sourceBlendRGB = sourceRGB;
435                 mState.destBlendRGB = destRGB;
436                 mState.sourceBlendAlpha = sourceAlpha;
437                 mState.destBlendAlpha = destAlpha;
438                 mBlendStateDirty = true;
439         }
440 }
441
442 void Context::setBlendColor(float red, float green, float blue, float alpha)
443 {
444         if(mState.blendColor.red != red ||
445            mState.blendColor.green != green ||
446            mState.blendColor.blue != blue ||
447            mState.blendColor.alpha != alpha)
448         {
449                 mState.blendColor.red = red;
450                 mState.blendColor.green = green;
451                 mState.blendColor.blue = blue;
452                 mState.blendColor.alpha = alpha;
453                 mBlendStateDirty = true;
454         }
455 }
456
457 void Context::setBlendEquation(GLenum rgbEquation, GLenum alphaEquation)
458 {
459         if(mState.blendEquationRGB != rgbEquation ||
460            mState.blendEquationAlpha != alphaEquation)
461         {
462                 mState.blendEquationRGB = rgbEquation;
463                 mState.blendEquationAlpha = alphaEquation;
464                 mBlendStateDirty = true;
465         }
466 }
467
468 void Context::setStencilTestEnabled(bool enabled)
469 {
470         if(mState.stencilTestEnabled != enabled)
471         {
472                 mState.stencilTestEnabled = enabled;
473                 mStencilStateDirty = true;
474         }
475 }
476
477 bool Context::isStencilTestEnabled() const
478 {
479         return mState.stencilTestEnabled;
480 }
481
482 void Context::setStencilParams(GLenum stencilFunc, GLint stencilRef, GLuint stencilMask)
483 {
484         if(mState.stencilFunc != stencilFunc ||
485            mState.stencilRef != stencilRef ||
486            mState.stencilMask != stencilMask)
487         {
488                 mState.stencilFunc = stencilFunc;
489                 mState.stencilRef = (stencilRef > 0) ? stencilRef : 0;
490                 mState.stencilMask = stencilMask;
491                 mStencilStateDirty = true;
492         }
493 }
494
495 void Context::setStencilBackParams(GLenum stencilBackFunc, GLint stencilBackRef, GLuint stencilBackMask)
496 {
497         if(mState.stencilBackFunc != stencilBackFunc ||
498            mState.stencilBackRef != stencilBackRef ||
499            mState.stencilBackMask != stencilBackMask)
500         {
501                 mState.stencilBackFunc = stencilBackFunc;
502                 mState.stencilBackRef = (stencilBackRef > 0) ? stencilBackRef : 0;
503                 mState.stencilBackMask = stencilBackMask;
504                 mStencilStateDirty = true;
505         }
506 }
507
508 void Context::setStencilWritemask(GLuint stencilWritemask)
509 {
510         if(mState.stencilWritemask != stencilWritemask)
511         {
512                 mState.stencilWritemask = stencilWritemask;
513                 mStencilStateDirty = true;
514         }
515 }
516
517 void Context::setStencilBackWritemask(GLuint stencilBackWritemask)
518 {
519         if(mState.stencilBackWritemask != stencilBackWritemask)
520         {
521                 mState.stencilBackWritemask = stencilBackWritemask;
522                 mStencilStateDirty = true;
523         }
524 }
525
526 void Context::setStencilOperations(GLenum stencilFail, GLenum stencilPassDepthFail, GLenum stencilPassDepthPass)
527 {
528         if(mState.stencilFail != stencilFail ||
529            mState.stencilPassDepthFail != stencilPassDepthFail ||
530            mState.stencilPassDepthPass != stencilPassDepthPass)
531         {
532                 mState.stencilFail = stencilFail;
533                 mState.stencilPassDepthFail = stencilPassDepthFail;
534                 mState.stencilPassDepthPass = stencilPassDepthPass;
535                 mStencilStateDirty = true;
536         }
537 }
538
539 void Context::setStencilBackOperations(GLenum stencilBackFail, GLenum stencilBackPassDepthFail, GLenum stencilBackPassDepthPass)
540 {
541         if(mState.stencilBackFail != stencilBackFail ||
542            mState.stencilBackPassDepthFail != stencilBackPassDepthFail ||
543            mState.stencilBackPassDepthPass != stencilBackPassDepthPass)
544         {
545                 mState.stencilBackFail = stencilBackFail;
546                 mState.stencilBackPassDepthFail = stencilBackPassDepthFail;
547                 mState.stencilBackPassDepthPass = stencilBackPassDepthPass;
548                 mStencilStateDirty = true;
549         }
550 }
551
552 void Context::setPolygonOffsetFillEnabled(bool enabled)
553 {
554         if(mState.polygonOffsetFillEnabled != enabled)
555         {
556                 mState.polygonOffsetFillEnabled = enabled;
557                 mPolygonOffsetStateDirty = true;
558         }
559 }
560
561 bool Context::isPolygonOffsetFillEnabled() const
562 {
563         return mState.polygonOffsetFillEnabled;
564 }
565
566 void Context::setPolygonOffsetParams(GLfloat factor, GLfloat units)
567 {
568         if(mState.polygonOffsetFactor != factor ||
569            mState.polygonOffsetUnits != units)
570         {
571                 mState.polygonOffsetFactor = factor;
572                 mState.polygonOffsetUnits = units;
573                 mPolygonOffsetStateDirty = true;
574         }
575 }
576
577 void Context::setSampleAlphaToCoverageEnabled(bool enabled)
578 {
579         if(mState.sampleAlphaToCoverageEnabled != enabled)
580         {
581                 mState.sampleAlphaToCoverageEnabled = enabled;
582                 mSampleStateDirty = true;
583         }
584 }
585
586 bool Context::isSampleAlphaToCoverageEnabled() const
587 {
588         return mState.sampleAlphaToCoverageEnabled;
589 }
590
591 void Context::setSampleCoverageEnabled(bool enabled)
592 {
593         if(mState.sampleCoverageEnabled != enabled)
594         {
595                 mState.sampleCoverageEnabled = enabled;
596                 mSampleStateDirty = true;
597         }
598 }
599
600 bool Context::isSampleCoverageEnabled() const
601 {
602         return mState.sampleCoverageEnabled;
603 }
604
605 void Context::setSampleCoverageParams(GLclampf value, bool invert)
606 {
607         if(mState.sampleCoverageValue != value ||
608            mState.sampleCoverageInvert != invert)
609         {
610                 mState.sampleCoverageValue = value;
611                 mState.sampleCoverageInvert = invert;
612                 mSampleStateDirty = true;
613         }
614 }
615
616 void Context::setScissorTestEnabled(bool enabled)
617 {
618         mState.scissorTestEnabled = enabled;
619 }
620
621 bool Context::isScissorTestEnabled() const
622 {
623         return mState.scissorTestEnabled;
624 }
625
626 void Context::setDitherEnabled(bool enabled)
627 {
628         if(mState.ditherEnabled != enabled)
629         {
630                 mState.ditherEnabled = enabled;
631                 mDitherStateDirty = true;
632         }
633 }
634
635 bool Context::isDitherEnabled() const
636 {
637         return mState.ditherEnabled;
638 }
639
640 void Context::setPrimitiveRestartFixedIndexEnabled(bool enabled)
641 {
642         mState.primitiveRestartFixedIndexEnabled = enabled;
643 }
644
645 bool Context::isPrimitiveRestartFixedIndexEnabled() const
646 {
647         return mState.primitiveRestartFixedIndexEnabled;
648 }
649
650 void Context::setRasterizerDiscardEnabled(bool enabled)
651 {
652         mState.rasterizerDiscardEnabled = enabled;
653 }
654
655 bool Context::isRasterizerDiscardEnabled() const
656 {
657         return mState.rasterizerDiscardEnabled;
658 }
659
660 void Context::setLineWidth(GLfloat width)
661 {
662         mState.lineWidth = width;
663         device->setLineWidth(clamp(width, ALIASED_LINE_WIDTH_RANGE_MIN, ALIASED_LINE_WIDTH_RANGE_MAX));
664 }
665
666 void Context::setGenerateMipmapHint(GLenum hint)
667 {
668         mState.generateMipmapHint = hint;
669 }
670
671 void Context::setFragmentShaderDerivativeHint(GLenum hint)
672 {
673         mState.fragmentShaderDerivativeHint = hint;
674         // TODO: Propagate the hint to shader translator so we can write
675         // ddx, ddx_coarse, or ddx_fine depending on the hint.
676         // Ignore for now. It is valid for implementations to ignore hint.
677 }
678
679 void Context::setTextureFilteringHint(GLenum hint)
680 {
681         mState.textureFilteringHint = hint;
682 }
683
684 void Context::setViewportParams(GLint x, GLint y, GLsizei width, GLsizei height)
685 {
686         mState.viewportX = x;
687         mState.viewportY = y;
688         mState.viewportWidth = std::min<GLsizei>(width, IMPLEMENTATION_MAX_RENDERBUFFER_SIZE);     // GL_MAX_VIEWPORT_DIMS[0]
689         mState.viewportHeight = std::min<GLsizei>(height, IMPLEMENTATION_MAX_RENDERBUFFER_SIZE);   // GL_MAX_VIEWPORT_DIMS[1]
690 }
691
692 void Context::setScissorParams(GLint x, GLint y, GLsizei width, GLsizei height)
693 {
694         mState.scissorX = x;
695         mState.scissorY = y;
696         mState.scissorWidth = width;
697         mState.scissorHeight = height;
698 }
699
700 void Context::setColorMask(bool red, bool green, bool blue, bool alpha)
701 {
702         if(mState.colorMaskRed != red || mState.colorMaskGreen != green ||
703            mState.colorMaskBlue != blue || mState.colorMaskAlpha != alpha)
704         {
705                 mState.colorMaskRed = red;
706                 mState.colorMaskGreen = green;
707                 mState.colorMaskBlue = blue;
708                 mState.colorMaskAlpha = alpha;
709                 mMaskStateDirty = true;
710         }
711 }
712
713 unsigned int Context::getColorMask() const
714 {
715         return (mState.colorMaskRed ? 0x1 : 0) |
716                (mState.colorMaskGreen ? 0x2 : 0) |
717                (mState.colorMaskBlue ? 0x4 : 0) |
718                (mState.colorMaskAlpha ? 0x8 : 0);
719 }
720
721 void Context::setDepthMask(bool mask)
722 {
723         if(mState.depthMask != mask)
724         {
725                 mState.depthMask = mask;
726                 mMaskStateDirty = true;
727         }
728 }
729
730 void Context::setActiveSampler(unsigned int active)
731 {
732         mState.activeSampler = active;
733 }
734
735 GLuint Context::getReadFramebufferName() const
736 {
737         return mState.readFramebuffer;
738 }
739
740 GLuint Context::getDrawFramebufferName() const
741 {
742         return mState.drawFramebuffer;
743 }
744
745 GLuint Context::getRenderbufferName() const
746 {
747         return mState.renderbuffer.name();
748 }
749
750 void Context::setFramebufferReadBuffer(GLuint buf)
751 {
752         Framebuffer *framebuffer = getReadFramebuffer();
753
754         if(framebuffer)
755         {
756                 framebuffer->setReadBuffer(buf);
757         }
758         else
759         {
760                 return error(GL_INVALID_OPERATION);
761         }
762 }
763
764 void Context::setFramebufferDrawBuffers(GLsizei n, const GLenum *bufs)
765 {
766         Framebuffer *drawFramebuffer = getDrawFramebuffer();
767
768         if(drawFramebuffer)
769         {
770                 for(int i = 0; i < MAX_COLOR_ATTACHMENTS; i++)
771                 {
772                         drawFramebuffer->setDrawBuffer(i, (i < n) ? bufs[i] : GL_NONE);
773                 }
774         }
775         else
776         {
777                 return error(GL_INVALID_OPERATION);
778         }
779 }
780
781 GLuint Context::getArrayBufferName() const
782 {
783         return mState.arrayBuffer.name();
784 }
785
786 GLuint Context::getElementArrayBufferName() const
787 {
788         Buffer* elementArrayBuffer = getCurrentVertexArray()->getElementArrayBuffer();
789         return elementArrayBuffer ? elementArrayBuffer->name : 0;
790 }
791
792 GLuint Context::getActiveQuery(GLenum target) const
793 {
794         Query *queryObject = nullptr;
795
796         switch(target)
797         {
798         case GL_ANY_SAMPLES_PASSED_EXT:
799                 queryObject = mState.activeQuery[QUERY_ANY_SAMPLES_PASSED];
800                 break;
801         case GL_ANY_SAMPLES_PASSED_CONSERVATIVE_EXT:
802                 queryObject = mState.activeQuery[QUERY_ANY_SAMPLES_PASSED_CONSERVATIVE];
803                 break;
804         case GL_TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN:
805                 queryObject = mState.activeQuery[QUERY_TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN];
806                 break;
807         default:
808                 ASSERT(false);
809         }
810
811         if(queryObject)
812         {
813                 return queryObject->name;
814         }
815
816         return 0;
817 }
818
819 void Context::setVertexAttribArrayEnabled(unsigned int attribNum, bool enabled)
820 {
821         getCurrentVertexArray()->enableAttribute(attribNum, enabled);
822 }
823
824 void Context::setVertexAttribDivisor(unsigned int attribNum, GLuint divisor)
825 {
826         getCurrentVertexArray()->setVertexAttribDivisor(attribNum, divisor);
827 }
828
829 const VertexAttribute &Context::getVertexAttribState(unsigned int attribNum) const
830 {
831         return getCurrentVertexArray()->getVertexAttribute(attribNum);
832 }
833
834 void Context::setVertexAttribState(unsigned int attribNum, Buffer *boundBuffer, GLint size, GLenum type,
835                                    bool normalized, bool pureInteger, GLsizei stride, const void *pointer)
836 {
837         getCurrentVertexArray()->setAttributeState(attribNum, boundBuffer, size, type, normalized, pureInteger, stride, pointer);
838 }
839
840 const void *Context::getVertexAttribPointer(unsigned int attribNum) const
841 {
842         return getCurrentVertexArray()->getVertexAttribute(attribNum).mPointer;
843 }
844
845 const VertexAttributeArray &Context::getVertexArrayAttributes()
846 {
847         return getCurrentVertexArray()->getVertexAttributes();
848 }
849
850 const VertexAttributeArray &Context::getCurrentVertexAttributes()
851 {
852         return mState.vertexAttribute;
853 }
854
855 void Context::setPackAlignment(GLint alignment)
856 {
857         mState.packParameters.alignment = alignment;
858 }
859
860 void Context::setUnpackAlignment(GLint alignment)
861 {
862         mState.unpackParameters.alignment = alignment;
863 }
864
865 const gl::PixelStorageModes &Context::getUnpackParameters() const
866 {
867         return mState.unpackParameters;
868 }
869
870 void Context::setPackRowLength(GLint rowLength)
871 {
872         mState.packParameters.rowLength = rowLength;
873 }
874
875 void Context::setPackSkipPixels(GLint skipPixels)
876 {
877         mState.packParameters.skipPixels = skipPixels;
878 }
879
880 void Context::setPackSkipRows(GLint skipRows)
881 {
882         mState.packParameters.skipRows = skipRows;
883 }
884
885 void Context::setUnpackRowLength(GLint rowLength)
886 {
887         mState.unpackParameters.rowLength = rowLength;
888 }
889
890 void Context::setUnpackImageHeight(GLint imageHeight)
891 {
892         mState.unpackParameters.imageHeight = imageHeight;
893 }
894
895 void Context::setUnpackSkipPixels(GLint skipPixels)
896 {
897         mState.unpackParameters.skipPixels = skipPixels;
898 }
899
900 void Context::setUnpackSkipRows(GLint skipRows)
901 {
902         mState.unpackParameters.skipRows = skipRows;
903 }
904
905 void Context::setUnpackSkipImages(GLint skipImages)
906 {
907         mState.unpackParameters.skipImages = skipImages;
908 }
909
910 GLuint Context::createBuffer()
911 {
912         return mResourceManager->createBuffer();
913 }
914
915 GLuint Context::createProgram()
916 {
917         return mResourceManager->createProgram();
918 }
919
920 GLuint Context::createShader(GLenum type)
921 {
922         return mResourceManager->createShader(type);
923 }
924
925 GLuint Context::createTexture()
926 {
927         return mResourceManager->createTexture();
928 }
929
930 GLuint Context::createRenderbuffer()
931 {
932         return mResourceManager->createRenderbuffer();
933 }
934
935 // Returns an unused framebuffer name
936 GLuint Context::createFramebuffer()
937 {
938         return mFramebufferNameSpace.allocate();
939 }
940
941 GLuint Context::createFence()
942 {
943         return mFenceNameSpace.allocate(new Fence());
944 }
945
946 // Returns an unused query name
947 GLuint Context::createQuery()
948 {
949         return mQueryNameSpace.allocate();
950 }
951
952 // Returns an unused vertex array name
953 GLuint Context::createVertexArray()
954 {
955         return mVertexArrayNameSpace.allocate();
956 }
957
958 GLsync Context::createFenceSync(GLenum condition, GLbitfield flags)
959 {
960         GLuint handle = mResourceManager->createFenceSync(condition, flags);
961
962         return reinterpret_cast<GLsync>(static_cast<uintptr_t>(handle));
963 }
964
965 // Returns an unused transform feedback name
966 GLuint Context::createTransformFeedback()
967 {
968         return mTransformFeedbackNameSpace.allocate();
969 }
970
971 // Returns an unused sampler name
972 GLuint Context::createSampler()
973 {
974         return mResourceManager->createSampler();
975 }
976
977 void Context::deleteBuffer(GLuint buffer)
978 {
979         detachBuffer(buffer);
980
981         mResourceManager->deleteBuffer(buffer);
982 }
983
984 void Context::deleteShader(GLuint shader)
985 {
986         mResourceManager->deleteShader(shader);
987 }
988
989 void Context::deleteProgram(GLuint program)
990 {
991         mResourceManager->deleteProgram(program);
992 }
993
994 void Context::deleteTexture(GLuint texture)
995 {
996         detachTexture(texture);
997
998         mResourceManager->deleteTexture(texture);
999 }
1000
1001 void Context::deleteRenderbuffer(GLuint renderbuffer)
1002 {
1003         if(mResourceManager->getRenderbuffer(renderbuffer))
1004         {
1005                 detachRenderbuffer(renderbuffer);
1006         }
1007
1008         mResourceManager->deleteRenderbuffer(renderbuffer);
1009 }
1010
1011 void Context::deleteFramebuffer(GLuint framebuffer)
1012 {
1013         detachFramebuffer(framebuffer);
1014
1015         Framebuffer *framebufferObject = mFramebufferNameSpace.remove(framebuffer);
1016
1017         if(framebufferObject)
1018         {
1019                 delete framebufferObject;
1020         }
1021 }
1022
1023 void Context::deleteFence(GLuint fence)
1024 {
1025         Fence *fenceObject = mFenceNameSpace.remove(fence);
1026
1027         if(fenceObject)
1028         {
1029                 delete fenceObject;
1030         }
1031 }
1032
1033 void Context::deleteQuery(GLuint query)
1034 {
1035         Query *queryObject = mQueryNameSpace.remove(query);
1036
1037         if(queryObject)
1038         {
1039                 queryObject->release();
1040         }
1041 }
1042
1043 void Context::deleteVertexArray(GLuint vertexArray)
1044 {
1045         // [OpenGL ES 3.0.2] section 2.10 page 43:
1046         // If a vertex array object that is currently bound is deleted, the binding
1047         // for that object reverts to zero and the default vertex array becomes current.
1048         if(getCurrentVertexArray()->name == vertexArray)
1049         {
1050                 bindVertexArray(0);
1051         }
1052
1053         VertexArray *vertexArrayObject = mVertexArrayNameSpace.remove(vertexArray);
1054
1055         if(vertexArrayObject)
1056         {
1057                 delete vertexArrayObject;
1058         }
1059 }
1060
1061 void Context::deleteFenceSync(GLsync fenceSync)
1062 {
1063         // The spec specifies the underlying Fence object is not deleted until all current
1064         // wait commands finish. However, since the name becomes invalid, we cannot query the fence,
1065         // and since our API is currently designed for being called from a single thread, we can delete
1066         // the fence immediately.
1067         mResourceManager->deleteFenceSync(static_cast<GLuint>(reinterpret_cast<uintptr_t>(fenceSync)));
1068 }
1069
1070 void Context::deleteTransformFeedback(GLuint transformFeedback)
1071 {
1072         TransformFeedback *transformFeedbackObject = mTransformFeedbackNameSpace.remove(transformFeedback);
1073
1074         if(transformFeedbackObject)
1075         {
1076                 delete transformFeedbackObject;
1077         }
1078 }
1079
1080 void Context::deleteSampler(GLuint sampler)
1081 {
1082         detachSampler(sampler);
1083
1084         mResourceManager->deleteSampler(sampler);
1085 }
1086
1087 Buffer *Context::getBuffer(GLuint handle) const
1088 {
1089         return mResourceManager->getBuffer(handle);
1090 }
1091
1092 Shader *Context::getShader(GLuint handle) const
1093 {
1094         return mResourceManager->getShader(handle);
1095 }
1096
1097 Program *Context::getProgram(GLuint handle) const
1098 {
1099         return mResourceManager->getProgram(handle);
1100 }
1101
1102 Texture *Context::getTexture(GLuint handle) const
1103 {
1104         return mResourceManager->getTexture(handle);
1105 }
1106
1107 Renderbuffer *Context::getRenderbuffer(GLuint handle) const
1108 {
1109         return mResourceManager->getRenderbuffer(handle);
1110 }
1111
1112 Framebuffer *Context::getReadFramebuffer() const
1113 {
1114         return getFramebuffer(mState.readFramebuffer);
1115 }
1116
1117 Framebuffer *Context::getDrawFramebuffer() const
1118 {
1119         return getFramebuffer(mState.drawFramebuffer);
1120 }
1121
1122 void Context::bindArrayBuffer(unsigned int buffer)
1123 {
1124         mResourceManager->checkBufferAllocation(buffer);
1125
1126         mState.arrayBuffer = getBuffer(buffer);
1127 }
1128
1129 void Context::bindElementArrayBuffer(unsigned int buffer)
1130 {
1131         mResourceManager->checkBufferAllocation(buffer);
1132
1133         getCurrentVertexArray()->setElementArrayBuffer(getBuffer(buffer));
1134 }
1135
1136 void Context::bindCopyReadBuffer(GLuint buffer)
1137 {
1138         mResourceManager->checkBufferAllocation(buffer);
1139
1140         mState.copyReadBuffer = getBuffer(buffer);
1141 }
1142
1143 void Context::bindCopyWriteBuffer(GLuint buffer)
1144 {
1145         mResourceManager->checkBufferAllocation(buffer);
1146
1147         mState.copyWriteBuffer = getBuffer(buffer);
1148 }
1149
1150 void Context::bindPixelPackBuffer(GLuint buffer)
1151 {
1152         mResourceManager->checkBufferAllocation(buffer);
1153
1154         mState.pixelPackBuffer = getBuffer(buffer);
1155 }
1156
1157 void Context::bindPixelUnpackBuffer(GLuint buffer)
1158 {
1159         mResourceManager->checkBufferAllocation(buffer);
1160
1161         mState.pixelUnpackBuffer = getBuffer(buffer);
1162 }
1163
1164 void Context::bindTransformFeedbackBuffer(GLuint buffer)
1165 {
1166         mResourceManager->checkBufferAllocation(buffer);
1167
1168         TransformFeedback* transformFeedback = getTransformFeedback(mState.transformFeedback);
1169
1170         if(transformFeedback)
1171         {
1172                 transformFeedback->setGenericBuffer(getBuffer(buffer));
1173         }
1174 }
1175
1176 void Context::bindTexture(TextureType type, GLuint texture)
1177 {
1178         mResourceManager->checkTextureAllocation(texture, type);
1179
1180         mState.samplerTexture[type][mState.activeSampler] = getTexture(texture);
1181 }
1182
1183 void Context::bindReadFramebuffer(GLuint framebuffer)
1184 {
1185         if(!getFramebuffer(framebuffer))
1186         {
1187                 if(framebuffer == 0)
1188                 {
1189                         mFramebufferNameSpace.insert(framebuffer, new DefaultFramebuffer());
1190                 }
1191                 else
1192                 {
1193                         mFramebufferNameSpace.insert(framebuffer, new Framebuffer());
1194                 }
1195         }
1196
1197         mState.readFramebuffer = framebuffer;
1198 }
1199
1200 void Context::bindDrawFramebuffer(GLuint framebuffer)
1201 {
1202         if(!getFramebuffer(framebuffer))
1203         {
1204                 if(framebuffer == 0)
1205                 {
1206                         mFramebufferNameSpace.insert(framebuffer, new DefaultFramebuffer());
1207                 }
1208                 else
1209                 {
1210                         mFramebufferNameSpace.insert(framebuffer, new Framebuffer());
1211                 }
1212         }
1213
1214         mState.drawFramebuffer = framebuffer;
1215 }
1216
1217 void Context::bindRenderbuffer(GLuint renderbuffer)
1218 {
1219         mResourceManager->checkRenderbufferAllocation(renderbuffer);
1220
1221         mState.renderbuffer = getRenderbuffer(renderbuffer);
1222 }
1223
1224 void Context::bindVertexArray(GLuint array)
1225 {
1226         VertexArray *vertexArray = getVertexArray(array);
1227
1228         if(!vertexArray)
1229         {
1230                 vertexArray = new VertexArray(array);
1231                 mVertexArrayNameSpace.insert(array, vertexArray);
1232         }
1233
1234         mState.vertexArray = array;
1235 }
1236
1237 void Context::bindGenericUniformBuffer(GLuint buffer)
1238 {
1239         mResourceManager->checkBufferAllocation(buffer);
1240
1241         mState.genericUniformBuffer = getBuffer(buffer);
1242 }
1243
1244 void Context::bindIndexedUniformBuffer(GLuint buffer, GLuint index, GLintptr offset, GLsizeiptr size)
1245 {
1246         mResourceManager->checkBufferAllocation(buffer);
1247
1248         Buffer* bufferObject = getBuffer(buffer);
1249         mState.uniformBuffers[index].set(bufferObject, static_cast<int>(offset), static_cast<int>(size));
1250 }
1251
1252 void Context::bindGenericTransformFeedbackBuffer(GLuint buffer)
1253 {
1254         mResourceManager->checkBufferAllocation(buffer);
1255
1256         getTransformFeedback()->setGenericBuffer(getBuffer(buffer));
1257 }
1258
1259 void Context::bindIndexedTransformFeedbackBuffer(GLuint buffer, GLuint index, GLintptr offset, GLsizeiptr size)
1260 {
1261         mResourceManager->checkBufferAllocation(buffer);
1262
1263         Buffer* bufferObject = getBuffer(buffer);
1264         getTransformFeedback()->setBuffer(index, bufferObject, offset, size);
1265 }
1266
1267 void Context::bindTransformFeedback(GLuint id)
1268 {
1269         if(!getTransformFeedback(id))
1270         {
1271                 mTransformFeedbackNameSpace.insert(id, new TransformFeedback(id));
1272         }
1273
1274         mState.transformFeedback = id;
1275 }
1276
1277 bool Context::bindSampler(GLuint unit, GLuint sampler)
1278 {
1279         mResourceManager->checkSamplerAllocation(sampler);
1280
1281         Sampler* samplerObject = getSampler(sampler);
1282
1283         mState.sampler[unit] = samplerObject;
1284
1285         return !!samplerObject;
1286 }
1287
1288 void Context::useProgram(GLuint program)
1289 {
1290         GLuint priorProgram = mState.currentProgram;
1291         mState.currentProgram = program;               // Must switch before trying to delete, otherwise it only gets flagged.
1292
1293         if(priorProgram != program)
1294         {
1295                 Program *newProgram = mResourceManager->getProgram(program);
1296                 Program *oldProgram = mResourceManager->getProgram(priorProgram);
1297
1298                 if(newProgram)
1299                 {
1300                         newProgram->addRef();
1301                 }
1302
1303                 if(oldProgram)
1304                 {
1305                         oldProgram->release();
1306                 }
1307         }
1308 }
1309
1310 void Context::beginQuery(GLenum target, GLuint query)
1311 {
1312         // From EXT_occlusion_query_boolean: If BeginQueryEXT is called with an <id>
1313         // of zero, if the active query object name for <target> is non-zero (for the
1314         // targets ANY_SAMPLES_PASSED_EXT and ANY_SAMPLES_PASSED_CONSERVATIVE_EXT, if
1315         // the active query for either target is non-zero), if <id> is the name of an
1316         // existing query object whose type does not match <target>, or if <id> is the
1317         // active query object name for any query type, the error INVALID_OPERATION is
1318         // generated.
1319
1320         // Ensure no other queries are active
1321         // NOTE: If other queries than occlusion are supported, we will need to check
1322         // separately that:
1323         //    a) The query ID passed is not the current active query for any target/type
1324         //    b) There are no active queries for the requested target (and in the case
1325         //       of GL_ANY_SAMPLES_PASSED_EXT and GL_ANY_SAMPLES_PASSED_CONSERVATIVE_EXT,
1326         //       no query may be active for either if glBeginQuery targets either.
1327         for(int i = 0; i < QUERY_TYPE_COUNT; i++)
1328         {
1329                 if(mState.activeQuery[i])
1330                 {
1331                         switch(mState.activeQuery[i]->getType())
1332                         {
1333                         case GL_ANY_SAMPLES_PASSED_EXT:
1334                         case GL_ANY_SAMPLES_PASSED_CONSERVATIVE_EXT:
1335                                 if((target == GL_ANY_SAMPLES_PASSED_EXT) ||
1336                                    (target == GL_ANY_SAMPLES_PASSED_CONSERVATIVE_EXT))
1337                                 {
1338                                         return error(GL_INVALID_OPERATION);
1339                                 }
1340                                 break;
1341                         case GL_TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN:
1342                                 if(target == GL_TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN)
1343                                 {
1344                                         return error(GL_INVALID_OPERATION);
1345                                 }
1346                                 break;
1347                         default:
1348                                 break;
1349                         }
1350                 }
1351         }
1352
1353         QueryType qType;
1354         switch(target)
1355         {
1356         case GL_ANY_SAMPLES_PASSED_EXT:
1357                 qType = QUERY_ANY_SAMPLES_PASSED;
1358                 break;
1359         case GL_ANY_SAMPLES_PASSED_CONSERVATIVE_EXT:
1360                 qType = QUERY_ANY_SAMPLES_PASSED_CONSERVATIVE;
1361                 break;
1362         case GL_TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN:
1363                 qType = QUERY_TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN;
1364                 break;
1365         default:
1366                 UNREACHABLE(target);
1367                 return error(GL_INVALID_ENUM);
1368         }
1369
1370         Query *queryObject = createQuery(query, target);
1371
1372         // Check that name was obtained with glGenQueries
1373         if(!queryObject)
1374         {
1375                 return error(GL_INVALID_OPERATION);
1376         }
1377
1378         // Check for type mismatch
1379         if(queryObject->getType() != target)
1380         {
1381                 return error(GL_INVALID_OPERATION);
1382         }
1383
1384         // Set query as active for specified target
1385         mState.activeQuery[qType] = queryObject;
1386
1387         // Begin query
1388         queryObject->begin();
1389 }
1390
1391 void Context::endQuery(GLenum target)
1392 {
1393         QueryType qType;
1394
1395         switch(target)
1396         {
1397         case GL_ANY_SAMPLES_PASSED_EXT:                qType = QUERY_ANY_SAMPLES_PASSED;                    break;
1398         case GL_ANY_SAMPLES_PASSED_CONSERVATIVE_EXT:   qType = QUERY_ANY_SAMPLES_PASSED_CONSERVATIVE;       break;
1399         case GL_TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN: qType = QUERY_TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN; break;
1400         default: UNREACHABLE(target); return;
1401         }
1402
1403         Query *queryObject = mState.activeQuery[qType];
1404
1405         if(!queryObject)
1406         {
1407                 return error(GL_INVALID_OPERATION);
1408         }
1409
1410         queryObject->end();
1411
1412         mState.activeQuery[qType] = nullptr;
1413 }
1414
1415 void Context::setFramebufferZero(Framebuffer *buffer)
1416 {
1417         delete mFramebufferNameSpace.remove(0);
1418         mFramebufferNameSpace.insert(0, buffer);
1419 }
1420
1421 void Context::setRenderbufferStorage(RenderbufferStorage *renderbuffer)
1422 {
1423         Renderbuffer *renderbufferObject = mState.renderbuffer;
1424         renderbufferObject->setStorage(renderbuffer);
1425 }
1426
1427 Framebuffer *Context::getFramebuffer(unsigned int handle) const
1428 {
1429         return mFramebufferNameSpace.find(handle);
1430 }
1431
1432 Fence *Context::getFence(unsigned int handle) const
1433 {
1434         return mFenceNameSpace.find(handle);
1435 }
1436
1437 FenceSync *Context::getFenceSync(GLsync handle) const
1438 {
1439         return mResourceManager->getFenceSync(static_cast<GLuint>(reinterpret_cast<uintptr_t>(handle)));
1440 }
1441
1442 Query *Context::getQuery(unsigned int handle) const
1443 {
1444         return mQueryNameSpace.find(handle);
1445 }
1446
1447 Query *Context::createQuery(unsigned int handle, GLenum type)
1448 {
1449         if(!mQueryNameSpace.isReserved(handle))
1450         {
1451                 return nullptr;
1452         }
1453         else
1454         {
1455                 Query *query = mQueryNameSpace.find(handle);
1456                 if(!query)
1457                 {
1458                         query = new Query(handle, type);
1459                         query->addRef();
1460                         mQueryNameSpace.insert(handle, query);
1461                 }
1462
1463                 return query;
1464         }
1465 }
1466
1467 VertexArray *Context::getVertexArray(GLuint array) const
1468 {
1469         return mVertexArrayNameSpace.find(array);
1470 }
1471
1472 VertexArray *Context::getCurrentVertexArray() const
1473 {
1474         return getVertexArray(mState.vertexArray);
1475 }
1476
1477 bool Context::isVertexArray(GLuint array) const
1478 {
1479         return mVertexArrayNameSpace.isReserved(array);
1480 }
1481
1482 bool Context::hasZeroDivisor() const
1483 {
1484         // Verify there is at least one active attribute with a divisor of zero
1485         es2::Program *programObject = getCurrentProgram();
1486         for(int attributeIndex = 0; attributeIndex < MAX_VERTEX_ATTRIBS; attributeIndex++)
1487         {
1488                 bool active = (programObject->getAttributeStream(attributeIndex) != -1);
1489                 if(active && getCurrentVertexArray()->getVertexAttribute(attributeIndex).mDivisor == 0)
1490                 {
1491                         return true;
1492                 }
1493         }
1494
1495         return false;
1496 }
1497
1498 TransformFeedback *Context::getTransformFeedback(GLuint transformFeedback) const
1499 {
1500         return mTransformFeedbackNameSpace.find(transformFeedback);
1501 }
1502
1503 bool Context::isTransformFeedback(GLuint array) const
1504 {
1505         return mTransformFeedbackNameSpace.isReserved(array);
1506 }
1507
1508 Sampler *Context::getSampler(GLuint sampler) const
1509 {
1510         return mResourceManager->getSampler(sampler);
1511 }
1512
1513 bool Context::isSampler(GLuint sampler) const
1514 {
1515         return mResourceManager->isSampler(sampler);
1516 }
1517
1518 Buffer *Context::getArrayBuffer() const
1519 {
1520         return mState.arrayBuffer;
1521 }
1522
1523 Buffer *Context::getElementArrayBuffer() const
1524 {
1525         return getCurrentVertexArray()->getElementArrayBuffer();
1526 }
1527
1528 Buffer *Context::getCopyReadBuffer() const
1529 {
1530         return mState.copyReadBuffer;
1531 }
1532
1533 Buffer *Context::getCopyWriteBuffer() const
1534 {
1535         return mState.copyWriteBuffer;
1536 }
1537
1538 Buffer *Context::getPixelPackBuffer() const
1539 {
1540         return mState.pixelPackBuffer;
1541 }
1542
1543 Buffer *Context::getPixelUnpackBuffer() const
1544 {
1545         return mState.pixelUnpackBuffer;
1546 }
1547
1548 Buffer *Context::getGenericUniformBuffer() const
1549 {
1550         return mState.genericUniformBuffer;
1551 }
1552
1553 GLsizei Context::getRequiredBufferSize(GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type) const
1554 {
1555         GLsizei inputWidth = (mState.unpackParameters.rowLength == 0) ? width : mState.unpackParameters.rowLength;
1556         GLsizei inputPitch = gl::ComputePitch(inputWidth, format, type, mState.unpackParameters.alignment);
1557         GLsizei inputHeight = (mState.unpackParameters.imageHeight == 0) ? height : mState.unpackParameters.imageHeight;
1558         return inputPitch * inputHeight * depth;
1559 }
1560
1561 GLenum Context::getPixels(const GLvoid **pixels, GLenum type, GLsizei imageSize) const
1562 {
1563         if(mState.pixelUnpackBuffer)
1564         {
1565                 ASSERT(mState.pixelUnpackBuffer->name != 0);
1566
1567                 if(mState.pixelUnpackBuffer->isMapped())
1568                 {
1569                         return GL_INVALID_OPERATION;
1570                 }
1571
1572                 size_t offset = static_cast<size_t>((ptrdiff_t)(*pixels));
1573
1574                 if(offset % GetTypeSize(type) != 0)
1575                 {
1576                         return GL_INVALID_OPERATION;
1577                 }
1578
1579                 if(offset > mState.pixelUnpackBuffer->size())
1580                 {
1581                         return GL_INVALID_OPERATION;
1582                 }
1583
1584                 if(mState.pixelUnpackBuffer->size() - offset < static_cast<size_t>(imageSize))
1585                 {
1586                         return GL_INVALID_OPERATION;
1587                 }
1588
1589                 *pixels = static_cast<const unsigned char*>(mState.pixelUnpackBuffer->data()) + offset;
1590         }
1591
1592         return GL_NO_ERROR;
1593 }
1594
1595 bool Context::getBuffer(GLenum target, es2::Buffer **buffer) const
1596 {
1597         switch(target)
1598         {
1599         case GL_ARRAY_BUFFER:
1600                 *buffer = getArrayBuffer();
1601                 break;
1602         case GL_ELEMENT_ARRAY_BUFFER:
1603                 *buffer = getElementArrayBuffer();
1604                 break;
1605         case GL_COPY_READ_BUFFER:
1606                 if(clientVersion >= 3)
1607                 {
1608                         *buffer = getCopyReadBuffer();
1609                         break;
1610                 }
1611                 else return false;
1612         case GL_COPY_WRITE_BUFFER:
1613                 if(clientVersion >= 3)
1614                 {
1615                         *buffer = getCopyWriteBuffer();
1616                         break;
1617                 }
1618                 else return false;
1619         case GL_PIXEL_PACK_BUFFER:
1620                 if(clientVersion >= 3)
1621                 {
1622                         *buffer = getPixelPackBuffer();
1623                         break;
1624                 }
1625                 else return false;
1626         case GL_PIXEL_UNPACK_BUFFER:
1627                 if(clientVersion >= 3)
1628                 {
1629                         *buffer = getPixelUnpackBuffer();
1630                         break;
1631                 }
1632                 else return false;
1633         case GL_TRANSFORM_FEEDBACK_BUFFER:
1634                 if(clientVersion >= 3)
1635                 {
1636                         TransformFeedback* transformFeedback = getTransformFeedback();
1637                         *buffer = transformFeedback ? static_cast<es2::Buffer*>(transformFeedback->getGenericBuffer()) : nullptr;
1638                         break;
1639                 }
1640                 else return false;
1641         case GL_UNIFORM_BUFFER:
1642                 if(clientVersion >= 3)
1643                 {
1644                         *buffer = getGenericUniformBuffer();
1645                         break;
1646                 }
1647                 else return false;
1648         default:
1649                 return false;
1650         }
1651         return true;
1652 }
1653
1654 TransformFeedback *Context::getTransformFeedback() const
1655 {
1656         return getTransformFeedback(mState.transformFeedback);
1657 }
1658
1659 Program *Context::getCurrentProgram() const
1660 {
1661         return mResourceManager->getProgram(mState.currentProgram);
1662 }
1663
1664 Texture2D *Context::getTexture2D() const
1665 {
1666         return static_cast<Texture2D*>(getSamplerTexture(mState.activeSampler, TEXTURE_2D));
1667 }
1668
1669 Texture2D *Context::getTexture2D(GLenum target) const
1670 {
1671         switch(target)
1672         {
1673         case GL_TEXTURE_2D:            return getTexture2D();
1674         case GL_TEXTURE_RECTANGLE_ARB: return getTexture2DRect();
1675         case GL_TEXTURE_EXTERNAL_OES:  return getTextureExternal();
1676         default:                       UNREACHABLE(target);
1677         }
1678
1679         return nullptr;
1680 }
1681
1682 Texture3D *Context::getTexture3D() const
1683 {
1684         return static_cast<Texture3D*>(getSamplerTexture(mState.activeSampler, TEXTURE_3D));
1685 }
1686
1687 Texture2DArray *Context::getTexture2DArray() const
1688 {
1689         return static_cast<Texture2DArray*>(getSamplerTexture(mState.activeSampler, TEXTURE_2D_ARRAY));
1690 }
1691
1692 TextureCubeMap *Context::getTextureCubeMap() const
1693 {
1694         return static_cast<TextureCubeMap*>(getSamplerTexture(mState.activeSampler, TEXTURE_CUBE));
1695 }
1696
1697 Texture2DRect *Context::getTexture2DRect() const
1698 {
1699         return static_cast<Texture2DRect*>(getSamplerTexture(mState.activeSampler, TEXTURE_2D_RECT));
1700 }
1701
1702 TextureExternal *Context::getTextureExternal() const
1703 {
1704         return static_cast<TextureExternal*>(getSamplerTexture(mState.activeSampler, TEXTURE_EXTERNAL));
1705 }
1706
1707 Texture *Context::getSamplerTexture(unsigned int sampler, TextureType type) const
1708 {
1709         GLuint texid = mState.samplerTexture[type][sampler].name();
1710
1711         if(texid == 0)   // Special case: 0 refers to different initial textures based on the target
1712         {
1713                 switch(type)
1714                 {
1715                 case TEXTURE_2D: return mTexture2DZero;
1716                 case TEXTURE_3D: return mTexture3DZero;
1717                 case TEXTURE_2D_ARRAY: return mTexture2DArrayZero;
1718                 case TEXTURE_CUBE: return mTextureCubeMapZero;
1719                 case TEXTURE_2D_RECT: return mTexture2DRectZero;
1720                 case TEXTURE_EXTERNAL: return mTextureExternalZero;
1721                 default: UNREACHABLE(type);
1722                 }
1723         }
1724
1725         return mState.samplerTexture[type][sampler];
1726 }
1727
1728 void Context::samplerParameteri(GLuint sampler, GLenum pname, GLint param)
1729 {
1730         mResourceManager->checkSamplerAllocation(sampler);
1731
1732         Sampler *samplerObject = getSampler(sampler);
1733         ASSERT(samplerObject);
1734
1735         switch(pname)
1736         {
1737         case GL_TEXTURE_MIN_FILTER:         samplerObject->setMinFilter(static_cast<GLenum>(param));      break;
1738         case GL_TEXTURE_MAG_FILTER:         samplerObject->setMagFilter(static_cast<GLenum>(param));      break;
1739         case GL_TEXTURE_WRAP_S:             samplerObject->setWrapS(static_cast<GLenum>(param));          break;
1740         case GL_TEXTURE_WRAP_T:             samplerObject->setWrapT(static_cast<GLenum>(param));          break;
1741         case GL_TEXTURE_WRAP_R:             samplerObject->setWrapR(static_cast<GLenum>(param));          break;
1742         case GL_TEXTURE_MIN_LOD:            samplerObject->setMinLod(static_cast<GLfloat>(param));        break;
1743         case GL_TEXTURE_MAX_LOD:            samplerObject->setMaxLod(static_cast<GLfloat>(param));        break;
1744         case GL_TEXTURE_COMPARE_MODE:       samplerObject->setCompareMode(static_cast<GLenum>(param));    break;
1745         case GL_TEXTURE_COMPARE_FUNC:       samplerObject->setCompareFunc(static_cast<GLenum>(param));    break;
1746         case GL_TEXTURE_MAX_ANISOTROPY_EXT: samplerObject->setMaxAnisotropy(static_cast<GLfloat>(param)); break;
1747         default:                            UNREACHABLE(pname); break;
1748         }
1749 }
1750
1751 void Context::samplerParameterf(GLuint sampler, GLenum pname, GLfloat param)
1752 {
1753         mResourceManager->checkSamplerAllocation(sampler);
1754
1755         Sampler *samplerObject = getSampler(sampler);
1756         ASSERT(samplerObject);
1757
1758         switch(pname)
1759         {
1760         case GL_TEXTURE_MIN_FILTER:         samplerObject->setMinFilter(static_cast<GLenum>(roundf(param)));   break;
1761         case GL_TEXTURE_MAG_FILTER:         samplerObject->setMagFilter(static_cast<GLenum>(roundf(param)));   break;
1762         case GL_TEXTURE_WRAP_S:             samplerObject->setWrapS(static_cast<GLenum>(roundf(param)));       break;
1763         case GL_TEXTURE_WRAP_T:             samplerObject->setWrapT(static_cast<GLenum>(roundf(param)));       break;
1764         case GL_TEXTURE_WRAP_R:             samplerObject->setWrapR(static_cast<GLenum>(roundf(param)));       break;
1765         case GL_TEXTURE_MIN_LOD:            samplerObject->setMinLod(param);                                   break;
1766         case GL_TEXTURE_MAX_LOD:            samplerObject->setMaxLod(param);                                   break;
1767         case GL_TEXTURE_COMPARE_MODE:       samplerObject->setCompareMode(static_cast<GLenum>(roundf(param))); break;
1768         case GL_TEXTURE_COMPARE_FUNC:       samplerObject->setCompareFunc(static_cast<GLenum>(roundf(param))); break;
1769         case GL_TEXTURE_MAX_ANISOTROPY_EXT: samplerObject->setMaxAnisotropy(param);                            break;
1770         default:                            UNREACHABLE(pname); break;
1771         }
1772 }
1773
1774 GLint Context::getSamplerParameteri(GLuint sampler, GLenum pname)
1775 {
1776         mResourceManager->checkSamplerAllocation(sampler);
1777
1778         Sampler *samplerObject = getSampler(sampler);
1779         ASSERT(samplerObject);
1780
1781         switch(pname)
1782         {
1783         case GL_TEXTURE_MIN_FILTER:         return static_cast<GLint>(samplerObject->getMinFilter());
1784         case GL_TEXTURE_MAG_FILTER:         return static_cast<GLint>(samplerObject->getMagFilter());
1785         case GL_TEXTURE_WRAP_S:             return static_cast<GLint>(samplerObject->getWrapS());
1786         case GL_TEXTURE_WRAP_T:             return static_cast<GLint>(samplerObject->getWrapT());
1787         case GL_TEXTURE_WRAP_R:             return static_cast<GLint>(samplerObject->getWrapR());
1788         case GL_TEXTURE_MIN_LOD:            return static_cast<GLint>(roundf(samplerObject->getMinLod()));
1789         case GL_TEXTURE_MAX_LOD:            return static_cast<GLint>(roundf(samplerObject->getMaxLod()));
1790         case GL_TEXTURE_COMPARE_MODE:       return static_cast<GLint>(samplerObject->getCompareMode());
1791         case GL_TEXTURE_COMPARE_FUNC:       return static_cast<GLint>(samplerObject->getCompareFunc());
1792         case GL_TEXTURE_MAX_ANISOTROPY_EXT: return static_cast<GLint>(samplerObject->getMaxAnisotropy());
1793         default:                            UNREACHABLE(pname); return 0;
1794         }
1795 }
1796
1797 GLfloat Context::getSamplerParameterf(GLuint sampler, GLenum pname)
1798 {
1799         mResourceManager->checkSamplerAllocation(sampler);
1800
1801         Sampler *samplerObject = getSampler(sampler);
1802         ASSERT(samplerObject);
1803
1804         switch(pname)
1805         {
1806         case GL_TEXTURE_MIN_FILTER:         return static_cast<GLfloat>(samplerObject->getMinFilter());
1807         case GL_TEXTURE_MAG_FILTER:         return static_cast<GLfloat>(samplerObject->getMagFilter());
1808         case GL_TEXTURE_WRAP_S:             return static_cast<GLfloat>(samplerObject->getWrapS());
1809         case GL_TEXTURE_WRAP_T:             return static_cast<GLfloat>(samplerObject->getWrapT());
1810         case GL_TEXTURE_WRAP_R:             return static_cast<GLfloat>(samplerObject->getWrapR());
1811         case GL_TEXTURE_MIN_LOD:            return samplerObject->getMinLod();
1812         case GL_TEXTURE_MAX_LOD:            return samplerObject->getMaxLod();
1813         case GL_TEXTURE_COMPARE_MODE:       return static_cast<GLfloat>(samplerObject->getCompareMode());
1814         case GL_TEXTURE_COMPARE_FUNC:       return static_cast<GLfloat>(samplerObject->getCompareFunc());
1815         case GL_TEXTURE_MAX_ANISOTROPY_EXT: return samplerObject->getMaxAnisotropy();
1816         default:                            UNREACHABLE(pname); return 0;
1817         }
1818 }
1819
1820 bool Context::getBooleanv(GLenum pname, GLboolean *params) const
1821 {
1822         switch(pname)
1823         {
1824         case GL_SHADER_COMPILER:          *params = GL_TRUE;                          break;
1825         case GL_SAMPLE_COVERAGE_INVERT:   *params = mState.sampleCoverageInvert;      break;
1826         case GL_DEPTH_WRITEMASK:          *params = mState.depthMask;                 break;
1827         case GL_COLOR_WRITEMASK:
1828                 params[0] = mState.colorMaskRed;
1829                 params[1] = mState.colorMaskGreen;
1830                 params[2] = mState.colorMaskBlue;
1831                 params[3] = mState.colorMaskAlpha;
1832                 break;
1833         case GL_CULL_FACE:                *params = mState.cullFaceEnabled;                  break;
1834         case GL_POLYGON_OFFSET_FILL:      *params = mState.polygonOffsetFillEnabled;         break;
1835         case GL_SAMPLE_ALPHA_TO_COVERAGE: *params = mState.sampleAlphaToCoverageEnabled;     break;
1836         case GL_SAMPLE_COVERAGE:          *params = mState.sampleCoverageEnabled;            break;
1837         case GL_SCISSOR_TEST:             *params = mState.scissorTestEnabled;               break;
1838         case GL_STENCIL_TEST:             *params = mState.stencilTestEnabled;               break;
1839         case GL_DEPTH_TEST:               *params = mState.depthTestEnabled;                 break;
1840         case GL_BLEND:                    *params = mState.blendEnabled;                     break;
1841         case GL_DITHER:                   *params = mState.ditherEnabled;                    break;
1842         case GL_PRIMITIVE_RESTART_FIXED_INDEX: *params = mState.primitiveRestartFixedIndexEnabled; break;
1843         case GL_RASTERIZER_DISCARD:       *params = mState.rasterizerDiscardEnabled;         break;
1844         case GL_TRANSFORM_FEEDBACK_ACTIVE:
1845                 {
1846                         TransformFeedback* transformFeedback = getTransformFeedback(mState.transformFeedback);
1847                         if(transformFeedback)
1848                         {
1849                                 *params = transformFeedback->isActive();
1850                                 break;
1851                         }
1852                         else return false;
1853                 }
1854          case GL_TRANSFORM_FEEDBACK_PAUSED:
1855                 {
1856                         TransformFeedback* transformFeedback = getTransformFeedback(mState.transformFeedback);
1857                         if(transformFeedback)
1858                         {
1859                                 *params = transformFeedback->isPaused();
1860                                 break;
1861                         }
1862                         else return false;
1863                 }
1864         default:
1865                 return false;
1866         }
1867
1868         return true;
1869 }
1870
1871 bool Context::getFloatv(GLenum pname, GLfloat *params) const
1872 {
1873         // Please note: DEPTH_CLEAR_VALUE is included in our internal getFloatv implementation
1874         // because it is stored as a float, despite the fact that the GL ES 2.0 spec names
1875         // GetIntegerv as its native query function. As it would require conversion in any
1876         // case, this should make no difference to the calling application.
1877         switch(pname)
1878         {
1879         case GL_LINE_WIDTH:               *params = mState.lineWidth;            break;
1880         case GL_SAMPLE_COVERAGE_VALUE:    *params = mState.sampleCoverageValue;  break;
1881         case GL_DEPTH_CLEAR_VALUE:        *params = mState.depthClearValue;      break;
1882         case GL_POLYGON_OFFSET_FACTOR:    *params = mState.polygonOffsetFactor;  break;
1883         case GL_POLYGON_OFFSET_UNITS:     *params = mState.polygonOffsetUnits;   break;
1884         case GL_ALIASED_LINE_WIDTH_RANGE:
1885                 params[0] = ALIASED_LINE_WIDTH_RANGE_MIN;
1886                 params[1] = ALIASED_LINE_WIDTH_RANGE_MAX;
1887                 break;
1888         case GL_ALIASED_POINT_SIZE_RANGE:
1889                 params[0] = ALIASED_POINT_SIZE_RANGE_MIN;
1890                 params[1] = ALIASED_POINT_SIZE_RANGE_MAX;
1891                 break;
1892         case GL_DEPTH_RANGE:
1893                 params[0] = mState.zNear;
1894                 params[1] = mState.zFar;
1895                 break;
1896         case GL_COLOR_CLEAR_VALUE:
1897                 params[0] = mState.colorClearValue.red;
1898                 params[1] = mState.colorClearValue.green;
1899                 params[2] = mState.colorClearValue.blue;
1900                 params[3] = mState.colorClearValue.alpha;
1901                 break;
1902         case GL_BLEND_COLOR:
1903                 params[0] = mState.blendColor.red;
1904                 params[1] = mState.blendColor.green;
1905                 params[2] = mState.blendColor.blue;
1906                 params[3] = mState.blendColor.alpha;
1907                 break;
1908         case GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT:
1909                 *params = MAX_TEXTURE_MAX_ANISOTROPY;
1910                 break;
1911         default:
1912                 return false;
1913         }
1914
1915         return true;
1916 }
1917
1918 template bool Context::getIntegerv<GLint>(GLenum pname, GLint *params) const;
1919 template bool Context::getIntegerv<GLint64>(GLenum pname, GLint64 *params) const;
1920
1921 template<typename T> bool Context::getIntegerv(GLenum pname, T *params) const
1922 {
1923         // Please note: DEPTH_CLEAR_VALUE is not included in our internal getIntegerv implementation
1924         // because it is stored as a float, despite the fact that the GL ES 2.0 spec names
1925         // GetIntegerv as its native query function. As it would require conversion in any
1926         // case, this should make no difference to the calling application. You may find it in
1927         // Context::getFloatv.
1928         switch(pname)
1929         {
1930         case GL_MAX_VERTEX_ATTRIBS:               *params = MAX_VERTEX_ATTRIBS;               return true;
1931         case GL_MAX_VERTEX_UNIFORM_VECTORS:       *params = MAX_VERTEX_UNIFORM_VECTORS;       return true;
1932         case GL_MAX_VARYING_VECTORS:              *params = MAX_VARYING_VECTORS;              return true;
1933         case GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS: *params = MAX_COMBINED_TEXTURE_IMAGE_UNITS; return true;
1934         case GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS:   *params = MAX_VERTEX_TEXTURE_IMAGE_UNITS;   return true;
1935         case GL_MAX_TEXTURE_IMAGE_UNITS:          *params = MAX_TEXTURE_IMAGE_UNITS;          return true;
1936         case GL_MAX_FRAGMENT_UNIFORM_VECTORS:     *params = MAX_FRAGMENT_UNIFORM_VECTORS;     return true;
1937         case GL_MAX_RENDERBUFFER_SIZE:            *params = IMPLEMENTATION_MAX_RENDERBUFFER_SIZE; return true;
1938         case GL_NUM_SHADER_BINARY_FORMATS:        *params = 0;                                    return true;
1939         case GL_SHADER_BINARY_FORMATS:      /* no shader binary formats are supported */          return true;
1940         case GL_ARRAY_BUFFER_BINDING:             *params = getArrayBufferName();                 return true;
1941         case GL_ELEMENT_ARRAY_BUFFER_BINDING:     *params = getElementArrayBufferName();          return true;
1942 //      case GL_FRAMEBUFFER_BINDING:            // now equivalent to GL_DRAW_FRAMEBUFFER_BINDING_ANGLE
1943         case GL_DRAW_FRAMEBUFFER_BINDING:         *params = mState.drawFramebuffer;               return true;
1944         case GL_READ_FRAMEBUFFER_BINDING:         *params = mState.readFramebuffer;               return true;
1945         case GL_RENDERBUFFER_BINDING:             *params = mState.renderbuffer.name();           return true;
1946         case GL_CURRENT_PROGRAM:                  *params = mState.currentProgram;                return true;
1947         case GL_PACK_ALIGNMENT:                   *params = mState.packParameters.alignment;                 return true;
1948         case GL_UNPACK_ALIGNMENT:                 *params = mState.unpackParameters.alignment;          return true;
1949         case GL_GENERATE_MIPMAP_HINT:             *params = mState.generateMipmapHint;            return true;
1950         case GL_FRAGMENT_SHADER_DERIVATIVE_HINT_OES: *params = mState.fragmentShaderDerivativeHint; return true;
1951         case GL_TEXTURE_FILTERING_HINT_CHROMIUM:  *params = mState.textureFilteringHint;          return true;
1952         case GL_ACTIVE_TEXTURE:                   *params = (mState.activeSampler + GL_TEXTURE0); return true;
1953         case GL_STENCIL_FUNC:                     *params = mState.stencilFunc;                   return true;
1954         case GL_STENCIL_REF:                      *params = mState.stencilRef;                    return true;
1955         case GL_STENCIL_VALUE_MASK:               *params = sw::clampToSignedInt(mState.stencilMask); return true;
1956         case GL_STENCIL_BACK_FUNC:                *params = mState.stencilBackFunc;               return true;
1957         case GL_STENCIL_BACK_REF:                 *params = mState.stencilBackRef;                return true;
1958         case GL_STENCIL_BACK_VALUE_MASK:          *params = sw::clampToSignedInt(mState.stencilBackMask); return true;
1959         case GL_STENCIL_FAIL:                     *params = mState.stencilFail;                   return true;
1960         case GL_STENCIL_PASS_DEPTH_FAIL:          *params = mState.stencilPassDepthFail;          return true;
1961         case GL_STENCIL_PASS_DEPTH_PASS:          *params = mState.stencilPassDepthPass;          return true;
1962         case GL_STENCIL_BACK_FAIL:                *params = mState.stencilBackFail;               return true;
1963         case GL_STENCIL_BACK_PASS_DEPTH_FAIL:     *params = mState.stencilBackPassDepthFail;      return true;
1964         case GL_STENCIL_BACK_PASS_DEPTH_PASS:     *params = mState.stencilBackPassDepthPass;      return true;
1965         case GL_DEPTH_FUNC:                       *params = mState.depthFunc;                     return true;
1966         case GL_BLEND_SRC_RGB:                    *params = mState.sourceBlendRGB;                return true;
1967         case GL_BLEND_SRC_ALPHA:                  *params = mState.sourceBlendAlpha;              return true;
1968         case GL_BLEND_DST_RGB:                    *params = mState.destBlendRGB;                  return true;
1969         case GL_BLEND_DST_ALPHA:                  *params = mState.destBlendAlpha;                return true;
1970         case GL_BLEND_EQUATION_RGB:               *params = mState.blendEquationRGB;              return true;
1971         case GL_BLEND_EQUATION_ALPHA:             *params = mState.blendEquationAlpha;            return true;
1972         case GL_STENCIL_WRITEMASK:                *params = sw::clampToSignedInt(mState.stencilWritemask); return true;
1973         case GL_STENCIL_BACK_WRITEMASK:           *params = sw::clampToSignedInt(mState.stencilBackWritemask); return true;
1974         case GL_STENCIL_CLEAR_VALUE:              *params = mState.stencilClearValue;             return true;
1975         case GL_SUBPIXEL_BITS:                    *params = 4;                                    return true;
1976         case GL_MAX_RECTANGLE_TEXTURE_SIZE_ARB:
1977         case GL_MAX_TEXTURE_SIZE:                 *params = IMPLEMENTATION_MAX_TEXTURE_SIZE;          return true;
1978         case GL_MAX_CUBE_MAP_TEXTURE_SIZE:        *params = IMPLEMENTATION_MAX_CUBE_MAP_TEXTURE_SIZE; return true;
1979         case GL_NUM_COMPRESSED_TEXTURE_FORMATS:   *params = NUM_COMPRESSED_TEXTURE_FORMATS;           return true;
1980         case GL_MAX_SAMPLES:                      *params = IMPLEMENTATION_MAX_SAMPLES;               return true;
1981         case GL_SAMPLE_BUFFERS:
1982         case GL_SAMPLES:
1983                 {
1984                         Framebuffer *framebuffer = getDrawFramebuffer();
1985                         int width, height, samples;
1986
1987                         if(framebuffer && (framebuffer->completeness(width, height, samples) == GL_FRAMEBUFFER_COMPLETE))
1988                         {
1989                                 switch(pname)
1990                                 {
1991                                 case GL_SAMPLE_BUFFERS:
1992                                         if(samples > 1)
1993                                         {
1994                                                 *params = 1;
1995                                         }
1996                                         else
1997                                         {
1998                                                 *params = 0;
1999                                         }
2000                                         break;
2001                                 case GL_SAMPLES:
2002                                         *params = samples;
2003                                         break;
2004                                 }
2005                         }
2006                         else
2007                         {
2008                                 *params = 0;
2009                         }
2010                 }
2011                 return true;
2012         case GL_IMPLEMENTATION_COLOR_READ_TYPE:
2013                 {
2014                         Framebuffer *framebuffer = getReadFramebuffer();
2015                         if(framebuffer)
2016                         {
2017                                 *params = framebuffer->getImplementationColorReadType();
2018                         }
2019                         else
2020                         {
2021                                 return error(GL_INVALID_OPERATION, true);
2022                         }
2023                 }
2024                 return true;
2025         case GL_IMPLEMENTATION_COLOR_READ_FORMAT:
2026                 {
2027                         Framebuffer *framebuffer = getReadFramebuffer();
2028                         if(framebuffer)
2029                         {
2030                                 *params = framebuffer->getImplementationColorReadFormat();
2031                         }
2032                         else
2033                         {
2034                                 return error(GL_INVALID_OPERATION, true);
2035                         }
2036                 }
2037                 return true;
2038         case GL_MAX_VIEWPORT_DIMS:
2039                 {
2040                         int maxDimension = IMPLEMENTATION_MAX_RENDERBUFFER_SIZE;
2041                         params[0] = maxDimension;
2042                         params[1] = maxDimension;
2043                 }
2044                 return true;
2045         case GL_COMPRESSED_TEXTURE_FORMATS:
2046                 {
2047                         for(int i = 0; i < NUM_COMPRESSED_TEXTURE_FORMATS; i++)
2048                         {
2049                                 params[i] = compressedTextureFormats[i];
2050                         }
2051                 }
2052                 return true;
2053         case GL_VIEWPORT:
2054                 params[0] = mState.viewportX;
2055                 params[1] = mState.viewportY;
2056                 params[2] = mState.viewportWidth;
2057                 params[3] = mState.viewportHeight;
2058                 return true;
2059         case GL_SCISSOR_BOX:
2060                 params[0] = mState.scissorX;
2061                 params[1] = mState.scissorY;
2062                 params[2] = mState.scissorWidth;
2063                 params[3] = mState.scissorHeight;
2064                 return true;
2065         case GL_CULL_FACE_MODE:                   *params = mState.cullMode;                 return true;
2066         case GL_FRONT_FACE:                       *params = mState.frontFace;                return true;
2067         case GL_RED_BITS:
2068         case GL_GREEN_BITS:
2069         case GL_BLUE_BITS:
2070         case GL_ALPHA_BITS:
2071                 {
2072                         Framebuffer *framebuffer = getDrawFramebuffer();
2073                         Renderbuffer *colorbuffer = framebuffer ? framebuffer->getColorbuffer(0) : nullptr;
2074
2075                         if(colorbuffer)
2076                         {
2077                                 switch(pname)
2078                                 {
2079                                 case GL_RED_BITS:   *params = colorbuffer->getRedSize();   return true;
2080                                 case GL_GREEN_BITS: *params = colorbuffer->getGreenSize(); return true;
2081                                 case GL_BLUE_BITS:  *params = colorbuffer->getBlueSize();  return true;
2082                                 case GL_ALPHA_BITS: *params = colorbuffer->getAlphaSize(); return true;
2083                                 }
2084                         }
2085                         else
2086                         {
2087                                 *params = 0;
2088                         }
2089                 }
2090                 return true;
2091         case GL_DEPTH_BITS:
2092                 {
2093                         Framebuffer *framebuffer = getDrawFramebuffer();
2094                         Renderbuffer *depthbuffer = framebuffer ? framebuffer->getDepthbuffer() : nullptr;
2095
2096                         if(depthbuffer)
2097                         {
2098                                 *params = depthbuffer->getDepthSize();
2099                         }
2100                         else
2101                         {
2102                                 *params = 0;
2103                         }
2104                 }
2105                 return true;
2106         case GL_STENCIL_BITS:
2107                 {
2108                         Framebuffer *framebuffer = getDrawFramebuffer();
2109                         Renderbuffer *stencilbuffer = framebuffer ? framebuffer->getStencilbuffer() : nullptr;
2110
2111                         if(stencilbuffer)
2112                         {
2113                                 *params = stencilbuffer->getStencilSize();
2114                         }
2115                         else
2116                         {
2117                                 *params = 0;
2118                         }
2119                 }
2120                 return true;
2121         case GL_TEXTURE_BINDING_2D:
2122                 if(mState.activeSampler > MAX_COMBINED_TEXTURE_IMAGE_UNITS - 1)
2123                 {
2124                         error(GL_INVALID_OPERATION);
2125                         return false;
2126                 }
2127
2128                 *params = mState.samplerTexture[TEXTURE_2D][mState.activeSampler].name();
2129                 return true;
2130         case GL_TEXTURE_BINDING_CUBE_MAP:
2131                 if(mState.activeSampler > MAX_COMBINED_TEXTURE_IMAGE_UNITS - 1)
2132                 {
2133                         error(GL_INVALID_OPERATION);
2134                         return false;
2135                 }
2136
2137                 *params = mState.samplerTexture[TEXTURE_CUBE][mState.activeSampler].name();
2138                 return true;
2139         case GL_TEXTURE_BINDING_RECTANGLE_ARB:
2140                 if(mState.activeSampler > MAX_COMBINED_TEXTURE_IMAGE_UNITS - 1)
2141                 {
2142                         error(GL_INVALID_OPERATION);
2143                         return false;
2144                 }
2145
2146                 *params = mState.samplerTexture[TEXTURE_2D_RECT][mState.activeSampler].name();
2147                 return true;
2148         case GL_TEXTURE_BINDING_EXTERNAL_OES:
2149                 if(mState.activeSampler > MAX_COMBINED_TEXTURE_IMAGE_UNITS - 1)
2150                 {
2151                         error(GL_INVALID_OPERATION);
2152                         return false;
2153                 }
2154
2155                 *params = mState.samplerTexture[TEXTURE_EXTERNAL][mState.activeSampler].name();
2156                 return true;
2157         case GL_TEXTURE_BINDING_3D_OES:
2158                 if(mState.activeSampler > MAX_COMBINED_TEXTURE_IMAGE_UNITS - 1)
2159                 {
2160                         error(GL_INVALID_OPERATION);
2161                         return false;
2162                 }
2163
2164                 *params = mState.samplerTexture[TEXTURE_3D][mState.activeSampler].name();
2165                 return true;
2166         case GL_DRAW_BUFFER0:
2167         case GL_DRAW_BUFFER1:
2168         case GL_DRAW_BUFFER2:
2169         case GL_DRAW_BUFFER3:
2170         case GL_DRAW_BUFFER4:
2171         case GL_DRAW_BUFFER5:
2172         case GL_DRAW_BUFFER6:
2173         case GL_DRAW_BUFFER7:
2174         case GL_DRAW_BUFFER8:
2175         case GL_DRAW_BUFFER9:
2176         case GL_DRAW_BUFFER10:
2177         case GL_DRAW_BUFFER11:
2178         case GL_DRAW_BUFFER12:
2179         case GL_DRAW_BUFFER13:
2180         case GL_DRAW_BUFFER14:
2181         case GL_DRAW_BUFFER15:
2182                 if((pname - GL_DRAW_BUFFER0) < MAX_DRAW_BUFFERS)
2183                 {
2184                         Framebuffer* framebuffer = getDrawFramebuffer();
2185                         *params = framebuffer ? framebuffer->getDrawBuffer(pname - GL_DRAW_BUFFER0) : GL_NONE;
2186                 }
2187                 else
2188                 {
2189                         return false;
2190                 }
2191                 return true;
2192         case GL_MAX_DRAW_BUFFERS:
2193                 *params = MAX_DRAW_BUFFERS;
2194                 return true;
2195         case GL_MAX_COLOR_ATTACHMENTS: // Note: MAX_COLOR_ATTACHMENTS_EXT added by GL_EXT_draw_buffers
2196                 *params = MAX_COLOR_ATTACHMENTS;
2197                 return true;
2198         default:
2199                 break;
2200         }
2201
2202         if(clientVersion >= 3)
2203         {
2204                 switch(pname)
2205                 {
2206                 case GL_TEXTURE_BINDING_2D_ARRAY:
2207                         if(mState.activeSampler > MAX_COMBINED_TEXTURE_IMAGE_UNITS - 1)
2208                         {
2209                                 error(GL_INVALID_OPERATION);
2210                                 return false;
2211                         }
2212
2213                         *params = mState.samplerTexture[TEXTURE_2D_ARRAY][mState.activeSampler].name();
2214                         return true;
2215                 case GL_COPY_READ_BUFFER_BINDING:
2216                         *params = mState.copyReadBuffer.name();
2217                         return true;
2218                 case GL_COPY_WRITE_BUFFER_BINDING:
2219                         *params = mState.copyWriteBuffer.name();
2220                         return true;
2221                 case GL_MAJOR_VERSION:
2222                         *params = clientVersion;
2223                         return true;
2224                 case GL_MAX_3D_TEXTURE_SIZE:
2225                         *params = IMPLEMENTATION_MAX_3D_TEXTURE_SIZE;
2226                         return true;
2227                 case GL_MAX_ARRAY_TEXTURE_LAYERS:
2228                         *params = IMPLEMENTATION_MAX_TEXTURE_SIZE;
2229                         return true;
2230                 case GL_MAX_COMBINED_FRAGMENT_UNIFORM_COMPONENTS:
2231                         *params = MAX_COMBINED_FRAGMENT_UNIFORM_COMPONENTS;
2232                         return true;
2233                 case GL_MAX_COMBINED_UNIFORM_BLOCKS:
2234                         *params = MAX_VERTEX_UNIFORM_BLOCKS + MAX_FRAGMENT_UNIFORM_BLOCKS;
2235                         return true;
2236                 case GL_MAX_COMBINED_VERTEX_UNIFORM_COMPONENTS:
2237                         *params = MAX_COMBINED_VERTEX_UNIFORM_COMPONENTS;
2238                         return true;
2239                 case GL_MAX_ELEMENT_INDEX:
2240                         *params = MAX_ELEMENT_INDEX;
2241                         return true;
2242                 case GL_MAX_ELEMENTS_INDICES:
2243                         *params = MAX_ELEMENTS_INDICES;
2244                         return true;
2245                 case GL_MAX_ELEMENTS_VERTICES:
2246                         *params = MAX_ELEMENTS_VERTICES;
2247                         return true;
2248                 case GL_MAX_FRAGMENT_INPUT_COMPONENTS:
2249                         *params = MAX_FRAGMENT_INPUT_VECTORS * 4;
2250                         return true;
2251                 case GL_MAX_FRAGMENT_UNIFORM_BLOCKS:
2252                         *params = MAX_FRAGMENT_UNIFORM_BLOCKS;
2253                         return true;
2254                 case GL_MAX_FRAGMENT_UNIFORM_COMPONENTS:
2255                         *params = MAX_FRAGMENT_UNIFORM_COMPONENTS;
2256                         return true;
2257                 case GL_MAX_PROGRAM_TEXEL_OFFSET:
2258                         // Note: SwiftShader has no actual texel offset limit, so this limit can be modified if required.
2259                         // In any case, any behavior outside the specified range is valid since the spec mentions:
2260                         // (see OpenGL ES 3.0.5, 3.8.10.1 Scale Factor and Level of Detail, p.153)
2261                         // "If any of the offset values are outside the range of the  implementation-defined values
2262                         //  MIN_PROGRAM_TEXEL_OFFSET and MAX_PROGRAM_TEXEL_OFFSET, results of the texture lookup are
2263                         //  undefined."
2264                         *params = MAX_PROGRAM_TEXEL_OFFSET;
2265                         return true;
2266                 case GL_MAX_SERVER_WAIT_TIMEOUT:
2267                         *params = 0;
2268                         return true;
2269                 case GL_MAX_TEXTURE_LOD_BIAS:
2270                         *params = MAX_TEXTURE_LOD_BIAS;
2271                         return true;
2272                 case GL_MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS:
2273                         *params = sw::MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS;
2274                         return true;
2275                 case GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS:
2276                         *params = MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS;
2277                         return true;
2278                 case GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS:
2279                         *params = sw::MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS;
2280                         return true;
2281                 case GL_MAX_UNIFORM_BLOCK_SIZE:
2282                         *params = MAX_UNIFORM_BLOCK_SIZE;
2283                         return true;
2284                 case GL_MAX_UNIFORM_BUFFER_BINDINGS:
2285                         *params = MAX_UNIFORM_BUFFER_BINDINGS;
2286                         return true;
2287                 case GL_MAX_VARYING_COMPONENTS:
2288                         *params = MAX_VARYING_VECTORS * 4;
2289                         return true;
2290                 case GL_MAX_VERTEX_OUTPUT_COMPONENTS:
2291                         *params = MAX_VERTEX_OUTPUT_VECTORS * 4;
2292                         return true;
2293                 case GL_MAX_VERTEX_UNIFORM_BLOCKS:
2294                         *params = MAX_VERTEX_UNIFORM_BLOCKS;
2295                         return true;
2296                 case GL_MAX_VERTEX_UNIFORM_COMPONENTS:
2297                         *params = MAX_VERTEX_UNIFORM_COMPONENTS;
2298                         return true;
2299                 case GL_MIN_PROGRAM_TEXEL_OFFSET:
2300                         // Note: SwiftShader has no actual texel offset limit, so this limit can be modified if required.
2301                         // In any case, any behavior outside the specified range is valid since the spec mentions:
2302                         // (see OpenGL ES 3.0.5, 3.8.10.1 Scale Factor and Level of Detail, p.153)
2303                         // "If any of the offset values are outside the range of the  implementation-defined values
2304                         //  MIN_PROGRAM_TEXEL_OFFSET and MAX_PROGRAM_TEXEL_OFFSET, results of the texture lookup are
2305                         //  undefined."
2306                         *params = MIN_PROGRAM_TEXEL_OFFSET;
2307                         return true;
2308                 case GL_MINOR_VERSION:
2309                         *params = 0;
2310                         return true;
2311                 case GL_NUM_EXTENSIONS:
2312                         GLuint numExtensions;
2313                         getExtensions(0, &numExtensions);
2314                         *params = numExtensions;
2315                         return true;
2316                 case GL_NUM_PROGRAM_BINARY_FORMATS:
2317                         *params = NUM_PROGRAM_BINARY_FORMATS;
2318                         return true;
2319                 case GL_PACK_ROW_LENGTH:
2320                         *params = mState.packParameters.rowLength;
2321                         return true;
2322                 case GL_PACK_SKIP_PIXELS:
2323                         *params = mState.packParameters.skipPixels;
2324                         return true;
2325                 case GL_PACK_SKIP_ROWS:
2326                         *params = mState.packParameters.skipRows;
2327                         return true;
2328                 case GL_PIXEL_PACK_BUFFER_BINDING:
2329                         *params = mState.pixelPackBuffer.name();
2330                         return true;
2331                 case GL_PIXEL_UNPACK_BUFFER_BINDING:
2332                         *params = mState.pixelUnpackBuffer.name();
2333                         return true;
2334                 case GL_PROGRAM_BINARY_FORMATS:
2335                         // Since NUM_PROGRAM_BINARY_FORMATS is 0, the input
2336                         // should be a 0 sized array, so don't write to params
2337                         return true;
2338                 case GL_READ_BUFFER:
2339                         {
2340                                 Framebuffer* framebuffer = getReadFramebuffer();
2341                                 *params = framebuffer ? framebuffer->getReadBuffer() : GL_NONE;
2342                         }
2343                         return true;
2344                 case GL_SAMPLER_BINDING:
2345                         *params = mState.sampler[mState.activeSampler].name();
2346                         return true;
2347                 case GL_UNIFORM_BUFFER_BINDING:
2348                         *params = mState.genericUniformBuffer.name();
2349                         return true;
2350                 case GL_UNIFORM_BUFFER_OFFSET_ALIGNMENT:
2351                         *params = UNIFORM_BUFFER_OFFSET_ALIGNMENT;
2352                         return true;
2353                 case GL_UNIFORM_BUFFER_SIZE:
2354                         *params = static_cast<T>(mState.genericUniformBuffer->size());
2355                         return true;
2356                 case GL_UNIFORM_BUFFER_START:
2357                         *params = static_cast<T>(mState.genericUniformBuffer->offset());
2358                         return true;
2359                 case GL_UNPACK_IMAGE_HEIGHT:
2360                         *params = mState.unpackParameters.imageHeight;
2361                         return true;
2362                 case GL_UNPACK_ROW_LENGTH:
2363                         *params = mState.unpackParameters.rowLength;
2364                         return true;
2365                 case GL_UNPACK_SKIP_IMAGES:
2366                         *params = mState.unpackParameters.skipImages;
2367                         return true;
2368                 case GL_UNPACK_SKIP_PIXELS:
2369                         *params = mState.unpackParameters.skipPixels;
2370                         return true;
2371                 case GL_UNPACK_SKIP_ROWS:
2372                         *params = mState.unpackParameters.skipRows;
2373                         return true;
2374                 case GL_VERTEX_ARRAY_BINDING:
2375                         *params = getCurrentVertexArray()->name;
2376                         return true;
2377                 case GL_TRANSFORM_FEEDBACK_BINDING:
2378                         {
2379                                 TransformFeedback* transformFeedback = getTransformFeedback(mState.transformFeedback);
2380                                 if(transformFeedback)
2381                                 {
2382                                         *params = transformFeedback->name;
2383                                 }
2384                                 else
2385                                 {
2386                                         return false;
2387                                 }
2388                         }
2389                         return true;
2390                 case GL_TRANSFORM_FEEDBACK_BUFFER_BINDING:
2391                         {
2392                                 TransformFeedback* transformFeedback = getTransformFeedback(mState.transformFeedback);
2393                                 if(transformFeedback)
2394                                 {
2395                                         *params = transformFeedback->getGenericBufferName();
2396                                 }
2397                                 else
2398                                 {
2399                                         return false;
2400                                 }
2401                         }
2402                         return true;
2403                 default:
2404                         break;
2405                 }
2406         }
2407
2408         return false;
2409 }
2410
2411 template bool Context::getTransformFeedbackiv<GLint>(GLuint index, GLenum pname, GLint *param) const;
2412 template bool Context::getTransformFeedbackiv<GLint64>(GLuint index, GLenum pname, GLint64 *param) const;
2413
2414 template<typename T> bool Context::getTransformFeedbackiv(GLuint index, GLenum pname, T *param) const
2415 {
2416         TransformFeedback* transformFeedback = getTransformFeedback(mState.transformFeedback);
2417         if(!transformFeedback)
2418         {
2419                 return false;
2420         }
2421
2422         switch(pname)
2423         {
2424         case GL_TRANSFORM_FEEDBACK_BINDING: // GLint, initially 0
2425                 *param = transformFeedback->name;
2426                 break;
2427         case GL_TRANSFORM_FEEDBACK_ACTIVE: // boolean, initially GL_FALSE
2428                 *param = transformFeedback->isActive();
2429                 break;
2430         case GL_TRANSFORM_FEEDBACK_BUFFER_BINDING: // name, initially 0
2431                 *param = transformFeedback->getBufferName(index);
2432                 break;
2433         case GL_TRANSFORM_FEEDBACK_PAUSED: // boolean, initially GL_FALSE
2434                 *param = transformFeedback->isPaused();
2435                 break;
2436         case GL_TRANSFORM_FEEDBACK_BUFFER_SIZE: // indexed[n] 64-bit integer, initially 0
2437                 if(transformFeedback->getBuffer(index))
2438                 {
2439                         *param = transformFeedback->getSize(index);
2440                         break;
2441                 }
2442                 else return false;
2443         case GL_TRANSFORM_FEEDBACK_BUFFER_START: // indexed[n] 64-bit integer, initially 0
2444                 if(transformFeedback->getBuffer(index))
2445                 {
2446                         *param = transformFeedback->getOffset(index);
2447                 break;
2448                 }
2449                 else return false;
2450         default:
2451                 return false;
2452         }
2453
2454         return true;
2455 }
2456
2457 template bool Context::getUniformBufferiv<GLint>(GLuint index, GLenum pname, GLint *param) const;
2458 template bool Context::getUniformBufferiv<GLint64>(GLuint index, GLenum pname, GLint64 *param) const;
2459
2460 template<typename T> bool Context::getUniformBufferiv(GLuint index, GLenum pname, T *param) const
2461 {
2462         switch(pname)
2463         {
2464         case GL_UNIFORM_BUFFER_BINDING:
2465         case GL_UNIFORM_BUFFER_SIZE:
2466         case GL_UNIFORM_BUFFER_START:
2467                 if(index >= MAX_UNIFORM_BUFFER_BINDINGS)
2468                 {
2469                         return error(GL_INVALID_VALUE, true);
2470                 }
2471                 break;
2472         default:
2473                 break;
2474         }
2475
2476         const BufferBinding& uniformBuffer = mState.uniformBuffers[index];
2477
2478         switch(pname)
2479         {
2480         case GL_UNIFORM_BUFFER_BINDING: // name, initially 0
2481                 *param = uniformBuffer.get().name();
2482                 break;
2483         case GL_UNIFORM_BUFFER_SIZE: // indexed[n] 64-bit integer, initially 0
2484                 *param = uniformBuffer.getSize();
2485                 break;
2486         case GL_UNIFORM_BUFFER_START: // indexed[n] 64-bit integer, initially 0
2487                 *param = uniformBuffer.getOffset();
2488                 break;
2489         default:
2490                 return false;
2491         }
2492
2493         return true;
2494 }
2495
2496 bool Context::getQueryParameterInfo(GLenum pname, GLenum *type, unsigned int *numParams) const
2497 {
2498         // Please note: the query type returned for DEPTH_CLEAR_VALUE in this implementation
2499         // is FLOAT rather than INT, as would be suggested by the GL ES 2.0 spec. This is due
2500         // to the fact that it is stored internally as a float, and so would require conversion
2501         // if returned from Context::getIntegerv. Since this conversion is already implemented
2502         // in the case that one calls glGetIntegerv to retrieve a float-typed state variable, we
2503         // place DEPTH_CLEAR_VALUE with the floats. This should make no difference to the calling
2504         // application.
2505         switch(pname)
2506         {
2507         case GL_COMPRESSED_TEXTURE_FORMATS:
2508                 {
2509                         *type = GL_INT;
2510                         *numParams = NUM_COMPRESSED_TEXTURE_FORMATS;
2511                 }
2512                 break;
2513         case GL_SHADER_BINARY_FORMATS:
2514                 {
2515                         *type = GL_INT;
2516                         *numParams = 0;
2517                 }
2518                 break;
2519         case GL_MAX_VERTEX_ATTRIBS:
2520         case GL_MAX_VERTEX_UNIFORM_VECTORS:
2521         case GL_MAX_VARYING_VECTORS:
2522         case GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS:
2523         case GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS:
2524         case GL_MAX_TEXTURE_IMAGE_UNITS:
2525         case GL_MAX_FRAGMENT_UNIFORM_VECTORS:
2526         case GL_MAX_RENDERBUFFER_SIZE:
2527         case GL_NUM_SHADER_BINARY_FORMATS:
2528         case GL_NUM_COMPRESSED_TEXTURE_FORMATS:
2529         case GL_ARRAY_BUFFER_BINDING:
2530         case GL_FRAMEBUFFER_BINDING:        // Same as GL_DRAW_FRAMEBUFFER_BINDING_ANGLE
2531         case GL_READ_FRAMEBUFFER_BINDING:   // Same as GL_READ_FRAMEBUFFER_BINDING_ANGLE
2532         case GL_RENDERBUFFER_BINDING:
2533         case GL_CURRENT_PROGRAM:
2534         case GL_PACK_ALIGNMENT:
2535         case GL_UNPACK_ALIGNMENT:
2536         case GL_GENERATE_MIPMAP_HINT:
2537         case GL_FRAGMENT_SHADER_DERIVATIVE_HINT_OES:
2538         case GL_TEXTURE_FILTERING_HINT_CHROMIUM:
2539         case GL_RED_BITS:
2540         case GL_GREEN_BITS:
2541         case GL_BLUE_BITS:
2542         case GL_ALPHA_BITS:
2543         case GL_DEPTH_BITS:
2544         case GL_STENCIL_BITS:
2545         case GL_ELEMENT_ARRAY_BUFFER_BINDING:
2546         case GL_CULL_FACE_MODE:
2547         case GL_FRONT_FACE:
2548         case GL_ACTIVE_TEXTURE:
2549         case GL_STENCIL_FUNC:
2550         case GL_STENCIL_VALUE_MASK:
2551         case GL_STENCIL_REF:
2552         case GL_STENCIL_FAIL:
2553         case GL_STENCIL_PASS_DEPTH_FAIL:
2554         case GL_STENCIL_PASS_DEPTH_PASS:
2555         case GL_STENCIL_BACK_FUNC:
2556         case GL_STENCIL_BACK_VALUE_MASK:
2557         case GL_STENCIL_BACK_REF:
2558         case GL_STENCIL_BACK_FAIL:
2559         case GL_STENCIL_BACK_PASS_DEPTH_FAIL:
2560         case GL_STENCIL_BACK_PASS_DEPTH_PASS:
2561         case GL_DEPTH_FUNC:
2562         case GL_BLEND_SRC_RGB:
2563         case GL_BLEND_SRC_ALPHA:
2564         case GL_BLEND_DST_RGB:
2565         case GL_BLEND_DST_ALPHA:
2566         case GL_BLEND_EQUATION_RGB:
2567         case GL_BLEND_EQUATION_ALPHA:
2568         case GL_STENCIL_WRITEMASK:
2569         case GL_STENCIL_BACK_WRITEMASK:
2570         case GL_STENCIL_CLEAR_VALUE:
2571         case GL_SUBPIXEL_BITS:
2572         case GL_MAX_TEXTURE_SIZE:
2573         case GL_MAX_CUBE_MAP_TEXTURE_SIZE:
2574         case GL_MAX_RECTANGLE_TEXTURE_SIZE_ARB:
2575         case GL_SAMPLE_BUFFERS:
2576         case GL_SAMPLES:
2577         case GL_IMPLEMENTATION_COLOR_READ_TYPE:
2578         case GL_IMPLEMENTATION_COLOR_READ_FORMAT:
2579         case GL_TEXTURE_BINDING_2D:
2580         case GL_TEXTURE_BINDING_CUBE_MAP:
2581         case GL_TEXTURE_BINDING_RECTANGLE_ARB:
2582         case GL_TEXTURE_BINDING_EXTERNAL_OES:
2583         case GL_TEXTURE_BINDING_3D_OES:
2584         case GL_COPY_READ_BUFFER_BINDING:
2585         case GL_COPY_WRITE_BUFFER_BINDING:
2586         case GL_DRAW_BUFFER0:
2587         case GL_DRAW_BUFFER1:
2588         case GL_DRAW_BUFFER2:
2589         case GL_DRAW_BUFFER3:
2590         case GL_DRAW_BUFFER4:
2591         case GL_DRAW_BUFFER5:
2592         case GL_DRAW_BUFFER6:
2593         case GL_DRAW_BUFFER7:
2594         case GL_DRAW_BUFFER8:
2595         case GL_DRAW_BUFFER9:
2596         case GL_DRAW_BUFFER10:
2597         case GL_DRAW_BUFFER11:
2598         case GL_DRAW_BUFFER12:
2599         case GL_DRAW_BUFFER13:
2600         case GL_DRAW_BUFFER14:
2601         case GL_DRAW_BUFFER15:
2602         case GL_MAJOR_VERSION:
2603         case GL_MAX_3D_TEXTURE_SIZE:
2604         case GL_MAX_ARRAY_TEXTURE_LAYERS:
2605         case GL_MAX_COLOR_ATTACHMENTS:
2606         case GL_MAX_COMBINED_FRAGMENT_UNIFORM_COMPONENTS:
2607         case GL_MAX_COMBINED_UNIFORM_BLOCKS:
2608         case GL_MAX_COMBINED_VERTEX_UNIFORM_COMPONENTS:
2609         case GL_MAX_DRAW_BUFFERS:
2610         case GL_MAX_ELEMENT_INDEX:
2611         case GL_MAX_ELEMENTS_INDICES:
2612         case GL_MAX_ELEMENTS_VERTICES:
2613         case GL_MAX_FRAGMENT_INPUT_COMPONENTS:
2614         case GL_MAX_FRAGMENT_UNIFORM_BLOCKS:
2615         case GL_MAX_FRAGMENT_UNIFORM_COMPONENTS:
2616         case GL_MAX_PROGRAM_TEXEL_OFFSET:
2617         case GL_MAX_SERVER_WAIT_TIMEOUT:
2618         case GL_MAX_TEXTURE_LOD_BIAS:
2619         case GL_MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS:
2620         case GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS:
2621         case GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS:
2622         case GL_MAX_UNIFORM_BLOCK_SIZE:
2623         case GL_MAX_UNIFORM_BUFFER_BINDINGS:
2624         case GL_MAX_VARYING_COMPONENTS:
2625         case GL_MAX_VERTEX_OUTPUT_COMPONENTS:
2626         case GL_MAX_VERTEX_UNIFORM_BLOCKS:
2627         case GL_MAX_VERTEX_UNIFORM_COMPONENTS:
2628         case GL_MIN_PROGRAM_TEXEL_OFFSET:
2629         case GL_MINOR_VERSION:
2630         case GL_NUM_EXTENSIONS:
2631         case GL_NUM_PROGRAM_BINARY_FORMATS:
2632         case GL_PACK_ROW_LENGTH:
2633         case GL_PACK_SKIP_PIXELS:
2634         case GL_PACK_SKIP_ROWS:
2635         case GL_PIXEL_PACK_BUFFER_BINDING:
2636         case GL_PIXEL_UNPACK_BUFFER_BINDING:
2637         case GL_PROGRAM_BINARY_FORMATS:
2638         case GL_READ_BUFFER:
2639         case GL_SAMPLER_BINDING:
2640         case GL_TEXTURE_BINDING_2D_ARRAY:
2641         case GL_UNIFORM_BUFFER_BINDING:
2642         case GL_UNIFORM_BUFFER_OFFSET_ALIGNMENT:
2643         case GL_UNIFORM_BUFFER_SIZE:
2644         case GL_UNIFORM_BUFFER_START:
2645         case GL_UNPACK_IMAGE_HEIGHT:
2646         case GL_UNPACK_ROW_LENGTH:
2647         case GL_UNPACK_SKIP_IMAGES:
2648         case GL_UNPACK_SKIP_PIXELS:
2649         case GL_UNPACK_SKIP_ROWS:
2650         case GL_VERTEX_ARRAY_BINDING:
2651         case GL_TRANSFORM_FEEDBACK_BINDING:
2652         case GL_TRANSFORM_FEEDBACK_BUFFER_BINDING:
2653                 {
2654                         *type = GL_INT;
2655                         *numParams = 1;
2656                 }
2657                 break;
2658         case GL_MAX_SAMPLES:
2659                 {
2660                         *type = GL_INT;
2661                         *numParams = 1;
2662                 }
2663                 break;
2664         case GL_MAX_VIEWPORT_DIMS:
2665                 {
2666                         *type = GL_INT;
2667                         *numParams = 2;
2668                 }
2669                 break;
2670         case GL_VIEWPORT:
2671         case GL_SCISSOR_BOX:
2672                 {
2673                         *type = GL_INT;
2674                         *numParams = 4;
2675                 }
2676                 break;
2677         case GL_SHADER_COMPILER:
2678         case GL_SAMPLE_COVERAGE_INVERT:
2679         case GL_DEPTH_WRITEMASK:
2680         case GL_CULL_FACE:                // CULL_FACE through DITHER are natural to IsEnabled,
2681         case GL_POLYGON_OFFSET_FILL:      // but can be retrieved through the Get{Type}v queries.
2682         case GL_SAMPLE_ALPHA_TO_COVERAGE: // For this purpose, they are treated here as bool-natural
2683         case GL_SAMPLE_COVERAGE:
2684         case GL_SCISSOR_TEST:
2685         case GL_STENCIL_TEST:
2686         case GL_DEPTH_TEST:
2687         case GL_BLEND:
2688         case GL_DITHER:
2689         case GL_PRIMITIVE_RESTART_FIXED_INDEX:
2690         case GL_RASTERIZER_DISCARD:
2691         case GL_TRANSFORM_FEEDBACK_ACTIVE:
2692         case GL_TRANSFORM_FEEDBACK_PAUSED:
2693                 {
2694                         *type = GL_BOOL;
2695                         *numParams = 1;
2696                 }
2697                 break;
2698         case GL_COLOR_WRITEMASK:
2699                 {
2700                         *type = GL_BOOL;
2701                         *numParams = 4;
2702                 }
2703                 break;
2704         case GL_POLYGON_OFFSET_FACTOR:
2705         case GL_POLYGON_OFFSET_UNITS:
2706         case GL_SAMPLE_COVERAGE_VALUE:
2707         case GL_DEPTH_CLEAR_VALUE:
2708         case GL_LINE_WIDTH:
2709                 {
2710                         *type = GL_FLOAT;
2711                         *numParams = 1;
2712                 }
2713                 break;
2714         case GL_ALIASED_LINE_WIDTH_RANGE:
2715         case GL_ALIASED_POINT_SIZE_RANGE:
2716         case GL_DEPTH_RANGE:
2717                 {
2718                         *type = GL_FLOAT;
2719                         *numParams = 2;
2720                 }
2721                 break;
2722         case GL_COLOR_CLEAR_VALUE:
2723         case GL_BLEND_COLOR:
2724                 {
2725                         *type = GL_FLOAT;
2726                         *numParams = 4;
2727                 }
2728                 break;
2729         case GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT:
2730                 *type = GL_FLOAT;
2731                 *numParams = 1;
2732                 break;
2733         default:
2734                 return false;
2735         }
2736
2737         return true;
2738 }
2739
2740 void Context::applyScissor(int width, int height)
2741 {
2742         if(mState.scissorTestEnabled)
2743         {
2744                 sw::Rect scissor = { mState.scissorX, mState.scissorY, mState.scissorX + mState.scissorWidth, mState.scissorY + mState.scissorHeight };
2745                 scissor.clip(0, 0, width, height);
2746
2747                 device->setScissorRect(scissor);
2748                 device->setScissorEnable(true);
2749         }
2750         else
2751         {
2752                 device->setScissorEnable(false);
2753         }
2754 }
2755
2756 // Applies the render target surface, depth stencil surface, viewport rectangle and scissor rectangle
2757 bool Context::applyRenderTarget()
2758 {
2759         Framebuffer *framebuffer = getDrawFramebuffer();
2760         int width, height, samples;
2761
2762         if(!framebuffer || (framebuffer->completeness(width, height, samples) != GL_FRAMEBUFFER_COMPLETE))
2763         {
2764                 return error(GL_INVALID_FRAMEBUFFER_OPERATION, false);
2765         }
2766
2767         for(int i = 0; i < MAX_DRAW_BUFFERS; i++)
2768         {
2769                 if(framebuffer->getDrawBuffer(i) != GL_NONE)
2770                 {
2771                         egl::Image *renderTarget = framebuffer->getRenderTarget(i);
2772                         GLint layer = framebuffer->getColorbufferLayer(i);
2773                         device->setRenderTarget(i, renderTarget, layer);
2774                         if(renderTarget) renderTarget->release();
2775                 }
2776                 else
2777                 {
2778                         device->setRenderTarget(i, nullptr, 0);
2779                 }
2780         }
2781
2782         egl::Image *depthBuffer = framebuffer->getDepthBuffer();
2783         GLint dLayer = framebuffer->getDepthbufferLayer();
2784         device->setDepthBuffer(depthBuffer, dLayer);
2785         if(depthBuffer) depthBuffer->release();
2786
2787         egl::Image *stencilBuffer = framebuffer->getStencilBuffer();
2788         GLint sLayer = framebuffer->getStencilbufferLayer();
2789         device->setStencilBuffer(stencilBuffer, sLayer);
2790         if(stencilBuffer) stencilBuffer->release();
2791
2792         Viewport viewport;
2793         float zNear = clamp01(mState.zNear);
2794         float zFar = clamp01(mState.zFar);
2795
2796         viewport.x0 = mState.viewportX;
2797         viewport.y0 = mState.viewportY;
2798         viewport.width = mState.viewportWidth;
2799         viewport.height = mState.viewportHeight;
2800         viewport.minZ = zNear;
2801         viewport.maxZ = zFar;
2802
2803         device->setViewport(viewport);
2804
2805         applyScissor(width, height);
2806
2807         Program *program = getCurrentProgram();
2808
2809         if(program)
2810         {
2811                 GLfloat nearFarDiff[3] = {zNear, zFar, zFar - zNear};
2812                 program->setUniform1fv(program->getUniformLocation("gl_DepthRange.near"), 1, &nearFarDiff[0]);
2813                 program->setUniform1fv(program->getUniformLocation("gl_DepthRange.far"), 1, &nearFarDiff[1]);
2814                 program->setUniform1fv(program->getUniformLocation("gl_DepthRange.diff"), 1, &nearFarDiff[2]);
2815         }
2816
2817         return true;
2818 }
2819
2820 // Applies the fixed-function state (culling, depth test, alpha blending, stenciling, etc)
2821 void Context::applyState(GLenum drawMode)
2822 {
2823         Framebuffer *framebuffer = getDrawFramebuffer();
2824
2825         if(mState.cullFaceEnabled)
2826         {
2827                 device->setCullMode(es2sw::ConvertCullMode(mState.cullMode, mState.frontFace));
2828         }
2829         else
2830         {
2831                 device->setCullMode(sw::CULL_NONE);
2832         }
2833
2834         if(mDepthStateDirty)
2835         {
2836                 if(mState.depthTestEnabled)
2837                 {
2838                         device->setDepthBufferEnable(true);
2839                         device->setDepthCompare(es2sw::ConvertDepthComparison(mState.depthFunc));
2840                 }
2841                 else
2842                 {
2843                         device->setDepthBufferEnable(false);
2844                 }
2845
2846                 mDepthStateDirty = false;
2847         }
2848
2849         if(mBlendStateDirty)
2850         {
2851                 if(mState.blendEnabled)
2852                 {
2853                         device->setAlphaBlendEnable(true);
2854                         device->setSeparateAlphaBlendEnable(true);
2855
2856                         device->setBlendConstant(es2sw::ConvertColor(mState.blendColor));
2857
2858                         device->setSourceBlendFactor(es2sw::ConvertBlendFunc(mState.sourceBlendRGB));
2859                         device->setDestBlendFactor(es2sw::ConvertBlendFunc(mState.destBlendRGB));
2860                         device->setBlendOperation(es2sw::ConvertBlendOp(mState.blendEquationRGB));
2861
2862                         device->setSourceBlendFactorAlpha(es2sw::ConvertBlendFunc(mState.sourceBlendAlpha));
2863                         device->setDestBlendFactorAlpha(es2sw::ConvertBlendFunc(mState.destBlendAlpha));
2864                         device->setBlendOperationAlpha(es2sw::ConvertBlendOp(mState.blendEquationAlpha));
2865                 }
2866                 else
2867                 {
2868                         device->setAlphaBlendEnable(false);
2869                 }
2870
2871                 mBlendStateDirty = false;
2872         }
2873
2874         if(mStencilStateDirty || mFrontFaceDirty)
2875         {
2876                 if(mState.stencilTestEnabled && framebuffer->hasStencil())
2877                 {
2878                         device->setStencilEnable(true);
2879                         device->setTwoSidedStencil(true);
2880
2881                         // get the maximum size of the stencil ref
2882                         Renderbuffer *stencilbuffer = framebuffer->getStencilbuffer();
2883                         GLuint maxStencil = (1 << stencilbuffer->getStencilSize()) - 1;
2884
2885                         if(mState.frontFace == GL_CCW)
2886                         {
2887                                 device->setStencilWriteMask(mState.stencilWritemask);
2888                                 device->setStencilCompare(es2sw::ConvertStencilComparison(mState.stencilFunc));
2889
2890                                 device->setStencilReference((mState.stencilRef < (GLint)maxStencil) ? mState.stencilRef : maxStencil);
2891                                 device->setStencilMask(mState.stencilMask);
2892
2893                                 device->setStencilFailOperation(es2sw::ConvertStencilOp(mState.stencilFail));
2894                                 device->setStencilZFailOperation(es2sw::ConvertStencilOp(mState.stencilPassDepthFail));
2895                                 device->setStencilPassOperation(es2sw::ConvertStencilOp(mState.stencilPassDepthPass));
2896
2897                                 device->setStencilWriteMaskCCW(mState.stencilBackWritemask);
2898                                 device->setStencilCompareCCW(es2sw::ConvertStencilComparison(mState.stencilBackFunc));
2899
2900                                 device->setStencilReferenceCCW((mState.stencilBackRef < (GLint)maxStencil) ? mState.stencilBackRef : maxStencil);
2901                                 device->setStencilMaskCCW(mState.stencilBackMask);
2902
2903                                 device->setStencilFailOperationCCW(es2sw::ConvertStencilOp(mState.stencilBackFail));
2904                                 device->setStencilZFailOperationCCW(es2sw::ConvertStencilOp(mState.stencilBackPassDepthFail));
2905                                 device->setStencilPassOperationCCW(es2sw::ConvertStencilOp(mState.stencilBackPassDepthPass));
2906                         }
2907                         else
2908                         {
2909                                 device->setStencilWriteMaskCCW(mState.stencilWritemask);
2910                                 device->setStencilCompareCCW(es2sw::ConvertStencilComparison(mState.stencilFunc));
2911
2912                                 device->setStencilReferenceCCW((mState.stencilRef < (GLint)maxStencil) ? mState.stencilRef : maxStencil);
2913                                 device->setStencilMaskCCW(mState.stencilMask);
2914
2915                                 device->setStencilFailOperationCCW(es2sw::ConvertStencilOp(mState.stencilFail));
2916                                 device->setStencilZFailOperationCCW(es2sw::ConvertStencilOp(mState.stencilPassDepthFail));
2917                                 device->setStencilPassOperationCCW(es2sw::ConvertStencilOp(mState.stencilPassDepthPass));
2918
2919                                 device->setStencilWriteMask(mState.stencilBackWritemask);
2920                                 device->setStencilCompare(es2sw::ConvertStencilComparison(mState.stencilBackFunc));
2921
2922                                 device->setStencilReference((mState.stencilBackRef < (GLint)maxStencil) ? mState.stencilBackRef : maxStencil);
2923                                 device->setStencilMask(mState.stencilBackMask);
2924
2925                                 device->setStencilFailOperation(es2sw::ConvertStencilOp(mState.stencilBackFail));
2926                                 device->setStencilZFailOperation(es2sw::ConvertStencilOp(mState.stencilBackPassDepthFail));
2927                                 device->setStencilPassOperation(es2sw::ConvertStencilOp(mState.stencilBackPassDepthPass));
2928                         }
2929                 }
2930                 else
2931                 {
2932                         device->setStencilEnable(false);
2933                 }
2934
2935                 mStencilStateDirty = false;
2936                 mFrontFaceDirty = false;
2937         }
2938
2939         if(mMaskStateDirty)
2940         {
2941                 for(int i = 0; i < MAX_DRAW_BUFFERS; i++)
2942                 {
2943                         device->setColorWriteMask(i, es2sw::ConvertColorMask(mState.colorMaskRed, mState.colorMaskGreen, mState.colorMaskBlue, mState.colorMaskAlpha));
2944                 }
2945
2946                 device->setDepthWriteEnable(mState.depthMask);
2947
2948                 mMaskStateDirty = false;
2949         }
2950
2951         if(mPolygonOffsetStateDirty)
2952         {
2953                 if(mState.polygonOffsetFillEnabled)
2954                 {
2955                         Renderbuffer *depthbuffer = framebuffer->getDepthbuffer();
2956                         if(depthbuffer)
2957                         {
2958                                 device->setSlopeDepthBias(mState.polygonOffsetFactor);
2959                                 float depthBias = ldexp(mState.polygonOffsetUnits, -23);   // We use 32-bit floating-point for all depth formats, with 23 mantissa bits.
2960                                 device->setDepthBias(depthBias);
2961                         }
2962                 }
2963                 else
2964                 {
2965                         device->setSlopeDepthBias(0);
2966                         device->setDepthBias(0);
2967                 }
2968
2969                 mPolygonOffsetStateDirty = false;
2970         }
2971
2972         if(mSampleStateDirty)
2973         {
2974                 if(mState.sampleAlphaToCoverageEnabled)
2975                 {
2976                         device->setTransparencyAntialiasing(sw::TRANSPARENCY_ALPHA_TO_COVERAGE);
2977                 }
2978                 else
2979                 {
2980                         device->setTransparencyAntialiasing(sw::TRANSPARENCY_NONE);
2981                 }
2982
2983                 if(mState.sampleCoverageEnabled)
2984                 {
2985                         unsigned int mask = 0;
2986                         if(mState.sampleCoverageValue != 0)
2987                         {
2988                                 int width, height, samples;
2989                                 framebuffer->completeness(width, height, samples);
2990
2991                                 float threshold = 0.5f;
2992
2993                                 for(int i = 0; i < samples; i++)
2994                                 {
2995                                         mask <<= 1;
2996
2997                                         if((i + 1) * mState.sampleCoverageValue >= threshold)
2998                                         {
2999                                                 threshold += 1.0f;
3000                                                 mask |= 1;
3001                                         }
3002                                 }
3003                         }
3004
3005                         if(mState.sampleCoverageInvert)
3006                         {
3007                                 mask = ~mask;
3008                         }
3009
3010                         device->setMultiSampleMask(mask);
3011                 }
3012                 else
3013                 {
3014                         device->setMultiSampleMask(0xFFFFFFFF);
3015                 }
3016
3017                 mSampleStateDirty = false;
3018         }
3019
3020         if(mDitherStateDirty)
3021         {
3022         //      UNIMPLEMENTED();   // FIXME
3023
3024                 mDitherStateDirty = false;
3025         }
3026
3027         device->setRasterizerDiscard(mState.rasterizerDiscardEnabled);
3028 }
3029
3030 GLenum Context::applyVertexBuffer(GLint base, GLint first, GLsizei count, GLsizei instanceId)
3031 {
3032         TranslatedAttribute attributes[MAX_VERTEX_ATTRIBS];
3033
3034         GLenum err = mVertexDataManager->prepareVertexData(first, count, attributes, instanceId);
3035         if(err != GL_NO_ERROR)
3036         {
3037                 return err;
3038         }
3039
3040         Program *program = getCurrentProgram();
3041
3042         device->resetInputStreams(false);
3043
3044         for(int i = 0; i < MAX_VERTEX_ATTRIBS; i++)
3045         {
3046                 if(program->getAttributeStream(i) == -1)
3047                 {
3048                         continue;
3049                 }
3050
3051                 sw::Resource *resource = attributes[i].vertexBuffer;
3052                 const void *buffer = (char*)resource->data() + attributes[i].offset;
3053
3054                 int stride = attributes[i].stride;
3055
3056                 buffer = (char*)buffer + stride * base;
3057
3058                 sw::Stream attribute(resource, buffer, stride);
3059
3060                 attribute.type = attributes[i].type;
3061                 attribute.count = attributes[i].count;
3062                 attribute.normalized = attributes[i].normalized;
3063
3064                 int stream = program->getAttributeStream(i);
3065                 device->setInputStream(stream, attribute);
3066         }
3067
3068         return GL_NO_ERROR;
3069 }
3070
3071 // Applies the indices and element array bindings
3072 GLenum Context::applyIndexBuffer(const void *indices, GLuint start, GLuint end, GLsizei count, GLenum mode, GLenum type, TranslatedIndexData *indexInfo)
3073 {
3074         GLenum err = mIndexDataManager->prepareIndexData(mode, type, start, end, count, getCurrentVertexArray()->getElementArrayBuffer(), indices, indexInfo, isPrimitiveRestartFixedIndexEnabled());
3075
3076         if(err == GL_NO_ERROR)
3077         {
3078                 device->setIndexBuffer(indexInfo->indexBuffer);
3079         }
3080
3081         return err;
3082 }
3083
3084 // Applies the shaders and shader constants
3085 void Context::applyShaders()
3086 {
3087         Program *programObject = getCurrentProgram();
3088         sw::VertexShader *vertexShader = programObject->getVertexShader();
3089         sw::PixelShader *pixelShader = programObject->getPixelShader();
3090
3091         device->setVertexShader(vertexShader);
3092         device->setPixelShader(pixelShader);
3093
3094         if(programObject->getSerial() != mAppliedProgramSerial)
3095         {
3096                 programObject->dirtyAllUniforms();
3097                 mAppliedProgramSerial = programObject->getSerial();
3098         }
3099
3100         programObject->applyTransformFeedback(device, getTransformFeedback());
3101         programObject->applyUniformBuffers(device, mState.uniformBuffers);
3102         programObject->applyUniforms(device);
3103 }
3104
3105 void Context::applyTextures()
3106 {
3107         applyTextures(sw::SAMPLER_PIXEL);
3108         applyTextures(sw::SAMPLER_VERTEX);
3109 }
3110
3111 void Context::applyTextures(sw::SamplerType samplerType)
3112 {
3113         Program *programObject = getCurrentProgram();
3114
3115         int samplerCount = (samplerType == sw::SAMPLER_PIXEL) ? MAX_TEXTURE_IMAGE_UNITS : MAX_VERTEX_TEXTURE_IMAGE_UNITS;   // Range of samplers of given sampler type
3116
3117         for(int samplerIndex = 0; samplerIndex < samplerCount; samplerIndex++)
3118         {
3119                 int textureUnit = programObject->getSamplerMapping(samplerType, samplerIndex);   // OpenGL texture image unit index
3120
3121                 if(textureUnit != -1)
3122                 {
3123                         TextureType textureType = programObject->getSamplerTextureType(samplerType, samplerIndex);
3124
3125                         Texture *texture = getSamplerTexture(textureUnit, textureType);
3126
3127                         if(texture->isSamplerComplete())
3128                         {
3129                                 GLenum wrapS, wrapT, wrapR, minFilter, magFilter, compFunc, compMode;
3130                                 GLfloat minLOD, maxLOD, maxAnisotropy;
3131
3132                                 Sampler *samplerObject = mState.sampler[textureUnit];
3133                                 if(samplerObject)
3134                                 {
3135                                         wrapS = samplerObject->getWrapS();
3136                                         wrapT = samplerObject->getWrapT();
3137                                         wrapR = samplerObject->getWrapR();
3138                                         minFilter = samplerObject->getMinFilter();
3139                                         magFilter = samplerObject->getMagFilter();
3140                                         minLOD = samplerObject->getMinLod();
3141                                         maxLOD = samplerObject->getMaxLod();
3142                                         compFunc = samplerObject->getCompareFunc();
3143                                         compMode = samplerObject->getCompareMode();
3144                                         maxAnisotropy = samplerObject->getMaxAnisotropy();
3145                                 }
3146                                 else
3147                                 {
3148                                         wrapS = texture->getWrapS();
3149                                         wrapT = texture->getWrapT();
3150                                         wrapR = texture->getWrapR();
3151                                         minFilter = texture->getMinFilter();
3152                                         magFilter = texture->getMagFilter();
3153                                         minLOD = texture->getMinLOD();
3154                                         maxLOD = texture->getMaxLOD();
3155                                         compFunc = texture->getCompareFunc();
3156                                         compMode = texture->getCompareMode();
3157                                         maxAnisotropy = texture->getMaxAnisotropy();
3158                                 }
3159
3160                                 GLint baseLevel = texture->getBaseLevel();
3161                                 GLint maxLevel = texture->getMaxLevel();
3162                                 GLenum swizzleR = texture->getSwizzleR();
3163                                 GLenum swizzleG = texture->getSwizzleG();
3164                                 GLenum swizzleB = texture->getSwizzleB();
3165                                 GLenum swizzleA = texture->getSwizzleA();
3166
3167                                 device->setAddressingModeU(samplerType, samplerIndex, es2sw::ConvertTextureWrap(wrapS));
3168                                 device->setAddressingModeV(samplerType, samplerIndex, es2sw::ConvertTextureWrap(wrapT));
3169                                 device->setAddressingModeW(samplerType, samplerIndex, es2sw::ConvertTextureWrap(wrapR));
3170                                 device->setCompareFunc(samplerType, samplerIndex, es2sw::ConvertCompareFunc(compFunc, compMode));
3171                                 device->setSwizzleR(samplerType, samplerIndex, es2sw::ConvertSwizzleType(swizzleR));
3172                                 device->setSwizzleG(samplerType, samplerIndex, es2sw::ConvertSwizzleType(swizzleG));
3173                                 device->setSwizzleB(samplerType, samplerIndex, es2sw::ConvertSwizzleType(swizzleB));
3174                                 device->setSwizzleA(samplerType, samplerIndex, es2sw::ConvertSwizzleType(swizzleA));
3175                                 device->setMinLod(samplerType, samplerIndex, minLOD);
3176                                 device->setMaxLod(samplerType, samplerIndex, maxLOD);
3177                                 device->setBaseLevel(samplerType, samplerIndex, baseLevel);
3178                                 device->setMaxLevel(samplerType, samplerIndex, maxLevel);
3179                                 device->setTextureFilter(samplerType, samplerIndex, es2sw::ConvertTextureFilter(minFilter, magFilter, maxAnisotropy));
3180                                 device->setMipmapFilter(samplerType, samplerIndex, es2sw::ConvertMipMapFilter(minFilter));
3181                                 device->setMaxAnisotropy(samplerType, samplerIndex, maxAnisotropy);
3182                                 device->setHighPrecisionFiltering(samplerType, samplerIndex, mState.textureFilteringHint == GL_NICEST);
3183
3184                                 applyTexture(samplerType, samplerIndex, texture);
3185                         }
3186                         else
3187                         {
3188                                 applyTexture(samplerType, samplerIndex, nullptr);
3189                         }
3190                 }
3191                 else
3192                 {
3193                         applyTexture(samplerType, samplerIndex, nullptr);
3194                 }
3195         }
3196 }
3197
3198 void Context::applyTexture(sw::SamplerType type, int index, Texture *baseTexture)
3199 {
3200         Program *program = getCurrentProgram();
3201         int sampler = (type == sw::SAMPLER_PIXEL) ? index : 16 + index;
3202         bool textureUsed = false;
3203
3204         if(type == sw::SAMPLER_PIXEL)
3205         {
3206                 textureUsed = program->getPixelShader()->usesSampler(index);
3207         }
3208         else if(type == sw::SAMPLER_VERTEX)
3209         {
3210                 textureUsed = program->getVertexShader()->usesSampler(index);
3211         }
3212         else UNREACHABLE(type);
3213
3214         sw::Resource *resource = nullptr;
3215
3216         if(baseTexture && textureUsed)
3217         {
3218                 resource = baseTexture->getResource();
3219         }
3220
3221         device->setTextureResource(sampler, resource);
3222
3223         if(baseTexture && textureUsed)
3224         {
3225                 int baseLevel = baseTexture->getBaseLevel();
3226                 int maxLevel = std::min(baseTexture->getTopLevel(), baseTexture->getMaxLevel());
3227                 GLenum target = baseTexture->getTarget();
3228
3229                 switch(target)
3230                 {
3231                 case GL_TEXTURE_2D:
3232                 case GL_TEXTURE_EXTERNAL_OES:
3233                 case GL_TEXTURE_RECTANGLE_ARB:
3234                         {
3235                                 Texture2D *texture = static_cast<Texture2D*>(baseTexture);
3236
3237                                 for(int mipmapLevel = 0; mipmapLevel < sw::MIPMAP_LEVELS; mipmapLevel++)
3238                                 {
3239                                         int surfaceLevel = mipmapLevel + baseLevel;
3240
3241                                         if(surfaceLevel > maxLevel)
3242                                         {
3243                                                 surfaceLevel = maxLevel;
3244                                         }
3245
3246                                         egl::Image *surface = texture->getImage(surfaceLevel);
3247                                         device->setTextureLevel(sampler, 0, mipmapLevel, surface,
3248                                                                 (target == GL_TEXTURE_RECTANGLE_ARB) ? sw::TEXTURE_RECTANGLE : sw::TEXTURE_2D);
3249                                 }
3250                         }
3251                         break;
3252                 case GL_TEXTURE_3D:
3253                         {
3254                                 Texture3D *texture = static_cast<Texture3D*>(baseTexture);
3255
3256                                 for(int mipmapLevel = 0; mipmapLevel < sw::MIPMAP_LEVELS; mipmapLevel++)
3257                                 {
3258                                         int surfaceLevel = mipmapLevel + baseLevel;
3259
3260                                         if(surfaceLevel > maxLevel)
3261                                         {
3262                                                 surfaceLevel = maxLevel;
3263                                         }
3264
3265                                         egl::Image *surface = texture->getImage(surfaceLevel);
3266                                         device->setTextureLevel(sampler, 0, mipmapLevel, surface, sw::TEXTURE_3D);
3267                                 }
3268                         }
3269                         break;
3270                 case GL_TEXTURE_2D_ARRAY:
3271                         {
3272                                 Texture2DArray *texture = static_cast<Texture2DArray*>(baseTexture);
3273
3274                                 for(int mipmapLevel = 0; mipmapLevel < sw::MIPMAP_LEVELS; mipmapLevel++)
3275                                 {
3276                                         int surfaceLevel = mipmapLevel + baseLevel;
3277
3278                                         if(surfaceLevel > maxLevel)
3279                                         {
3280                                                 surfaceLevel = maxLevel;
3281                                         }
3282
3283                                         egl::Image *surface = texture->getImage(surfaceLevel);
3284                                         device->setTextureLevel(sampler, 0, mipmapLevel, surface, sw::TEXTURE_2D_ARRAY);
3285                                 }
3286                         }
3287                         break;
3288                 case GL_TEXTURE_CUBE_MAP:
3289                         {
3290                                 TextureCubeMap *cubeTexture = static_cast<TextureCubeMap*>(baseTexture);
3291
3292                                 for(int mipmapLevel = 0; mipmapLevel < sw::MIPMAP_LEVELS; mipmapLevel++)
3293                                 {
3294                                         cubeTexture->updateBorders(mipmapLevel);
3295
3296                                         for(int face = 0; face < 6; face++)
3297                                         {
3298                                                 int surfaceLevel = mipmapLevel + baseLevel;
3299
3300                                                 if(surfaceLevel > maxLevel)
3301                                                 {
3302                                                         surfaceLevel = maxLevel;
3303                                                 }
3304
3305                                                 egl::Image *surface = cubeTexture->getImage(face, surfaceLevel);
3306                                                 device->setTextureLevel(sampler, face, mipmapLevel, surface, sw::TEXTURE_CUBE);
3307                                         }
3308                                 }
3309                         }
3310                         break;
3311                 default:
3312                         UNIMPLEMENTED();
3313                         break;
3314                 }
3315         }
3316         else
3317         {
3318                 device->setTextureLevel(sampler, 0, 0, 0, sw::TEXTURE_NULL);
3319         }
3320 }
3321
3322 void Context::readPixels(GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, GLsizei *bufSize, void* pixels)
3323 {
3324         Framebuffer *framebuffer = getReadFramebuffer();
3325         int framebufferWidth, framebufferHeight, framebufferSamples;
3326
3327         if(!framebuffer || (framebuffer->completeness(framebufferWidth, framebufferHeight, framebufferSamples) != GL_FRAMEBUFFER_COMPLETE))
3328         {
3329                 return error(GL_INVALID_FRAMEBUFFER_OPERATION);
3330         }
3331
3332         if(getReadFramebufferName() != 0 && framebufferSamples != 0)
3333         {
3334                 return error(GL_INVALID_OPERATION);
3335         }
3336
3337         if(!IsValidReadPixelsFormatType(framebuffer, format, type, clientVersion))
3338         {
3339                 return error(GL_INVALID_OPERATION);
3340         }
3341
3342         GLsizei outputWidth = (mState.packParameters.rowLength > 0) ? mState.packParameters.rowLength : width;
3343         GLsizei outputPitch = gl::ComputePitch(outputWidth, format, type, mState.packParameters.alignment);
3344         GLsizei outputHeight = (mState.packParameters.imageHeight == 0) ? height : mState.packParameters.imageHeight;
3345         pixels = getPixelPackBuffer() ? (unsigned char*)getPixelPackBuffer()->data() + (ptrdiff_t)pixels : (unsigned char*)pixels;
3346         pixels = ((char*)pixels) + gl::ComputePackingOffset(format, type, outputWidth, outputHeight, mState.packParameters);
3347
3348         // Sized query sanity check
3349         if(bufSize)
3350         {
3351                 int requiredSize = outputPitch * height;
3352                 if(requiredSize > *bufSize)
3353                 {
3354                         return error(GL_INVALID_OPERATION);
3355                 }
3356         }
3357
3358         egl::Image *renderTarget = nullptr;
3359         switch(format)
3360         {
3361         case GL_DEPTH_COMPONENT:   // GL_NV_read_depth
3362                 renderTarget = framebuffer->getDepthBuffer();
3363                 break;
3364         default:
3365                 renderTarget = framebuffer->getReadRenderTarget();
3366                 break;
3367         }
3368
3369         if(!renderTarget)
3370         {
3371                 return error(GL_INVALID_OPERATION);
3372         }
3373
3374         sw::RectF rect((float)x, (float)y, (float)(x + width), (float)(y + height));
3375         sw::Rect dstRect(0, 0, width, height);
3376         rect.clip(0.0f, 0.0f, (float)renderTarget->getWidth(), (float)renderTarget->getHeight());
3377
3378         sw::Surface *externalSurface = sw::Surface::create(width, height, 1, gl::ConvertReadFormatType(format, type), pixels, outputPitch, outputPitch * outputHeight);
3379         sw::SliceRectF sliceRect(rect);
3380         sw::SliceRect dstSliceRect(dstRect);
3381         device->blit(renderTarget, sliceRect, externalSurface, dstSliceRect, false, false, false);
3382         delete externalSurface;
3383
3384         renderTarget->release();
3385 }
3386
3387 void Context::clear(GLbitfield mask)
3388 {
3389         if(mState.rasterizerDiscardEnabled)
3390         {
3391                 return;
3392         }
3393
3394         Framebuffer *framebuffer = getDrawFramebuffer();
3395
3396         if(!framebuffer || (framebuffer->completeness() != GL_FRAMEBUFFER_COMPLETE))
3397         {
3398                 return error(GL_INVALID_FRAMEBUFFER_OPERATION);
3399         }
3400
3401         if(!applyRenderTarget())
3402         {
3403                 return;
3404         }
3405
3406         if(mask & GL_COLOR_BUFFER_BIT)
3407         {
3408                 unsigned int rgbaMask = getColorMask();
3409
3410                 if(rgbaMask != 0)
3411                 {
3412                         device->clearColor(mState.colorClearValue.red, mState.colorClearValue.green, mState.colorClearValue.blue, mState.colorClearValue.alpha, rgbaMask);
3413                 }
3414         }
3415
3416         if(mask & GL_DEPTH_BUFFER_BIT)
3417         {
3418                 if(mState.depthMask != 0)
3419                 {
3420                         float depth = clamp01(mState.depthClearValue);
3421                         device->clearDepth(depth);
3422                 }
3423         }
3424
3425         if(mask & GL_STENCIL_BUFFER_BIT)
3426         {
3427                 if(mState.stencilWritemask != 0)
3428                 {
3429                         int stencil = mState.stencilClearValue & 0x000000FF;
3430                         device->clearStencil(stencil, mState.stencilWritemask);
3431                 }
3432         }
3433 }
3434
3435 void Context::clearColorBuffer(GLint drawbuffer, void *value, sw::Format format)
3436 {
3437         unsigned int rgbaMask = getColorMask();
3438         if(rgbaMask && !mState.rasterizerDiscardEnabled)
3439         {
3440                 Framebuffer *framebuffer = getDrawFramebuffer();
3441                 if(!framebuffer)
3442                 {
3443                         return error(GL_INVALID_FRAMEBUFFER_OPERATION);
3444                 }
3445                 egl::Image *colorbuffer = framebuffer->getRenderTarget(drawbuffer);
3446
3447                 if(colorbuffer)
3448                 {
3449                         sw::Rect clearRect = colorbuffer->getRect();
3450
3451                         if(mState.scissorTestEnabled)
3452                         {
3453                                 clearRect.clip(mState.scissorX, mState.scissorY, mState.scissorX + mState.scissorWidth, mState.scissorY + mState.scissorHeight);
3454                         }
3455
3456                         device->clear(value, format, colorbuffer, clearRect, rgbaMask);
3457
3458                         colorbuffer->release();
3459                 }
3460         }
3461 }
3462
3463 void Context::clearColorBuffer(GLint drawbuffer, const GLint *value)
3464 {
3465         clearColorBuffer(drawbuffer, (void*)value, sw::FORMAT_A32B32G32R32I);
3466 }
3467
3468 void Context::clearColorBuffer(GLint drawbuffer, const GLuint *value)
3469 {
3470         clearColorBuffer(drawbuffer, (void*)value, sw::FORMAT_A32B32G32R32UI);
3471 }
3472
3473 void Context::clearColorBuffer(GLint drawbuffer, const GLfloat *value)
3474 {
3475         clearColorBuffer(drawbuffer, (void*)value, sw::FORMAT_A32B32G32R32F);
3476 }
3477
3478 void Context::clearDepthBuffer(const GLfloat value)
3479 {
3480         if(mState.depthMask && !mState.rasterizerDiscardEnabled)
3481         {
3482                 Framebuffer *framebuffer = getDrawFramebuffer();
3483                 if(!framebuffer)
3484                 {
3485                         return error(GL_INVALID_FRAMEBUFFER_OPERATION);
3486                 }
3487                 egl::Image *depthbuffer = framebuffer->getDepthBuffer();
3488
3489                 if(depthbuffer)
3490                 {
3491                         float depth = clamp01(value);
3492                         sw::Rect clearRect = depthbuffer->getRect();
3493
3494                         if(mState.scissorTestEnabled)
3495                         {
3496                                 clearRect.clip(mState.scissorX, mState.scissorY, mState.scissorX + mState.scissorWidth, mState.scissorY + mState.scissorHeight);
3497                         }
3498
3499                         depthbuffer->clearDepth(depth, clearRect.x0, clearRect.y0, clearRect.width(), clearRect.height());
3500
3501                         depthbuffer->release();
3502                 }
3503         }
3504 }
3505
3506 void Context::clearStencilBuffer(const GLint value)
3507 {
3508         if(mState.stencilWritemask && !mState.rasterizerDiscardEnabled)
3509         {
3510                 Framebuffer *framebuffer = getDrawFramebuffer();
3511                 if(!framebuffer)
3512                 {
3513                         return error(GL_INVALID_FRAMEBUFFER_OPERATION);
3514                 }
3515                 egl::Image *stencilbuffer = framebuffer->getStencilBuffer();
3516
3517                 if(stencilbuffer)
3518                 {
3519                         unsigned char stencil = value < 0 ? 0 : static_cast<unsigned char>(value & 0x000000FF);
3520                         sw::Rect clearRect = stencilbuffer->getRect();
3521
3522                         if(mState.scissorTestEnabled)
3523                         {
3524                                 clearRect.clip(mState.scissorX, mState.scissorY, mState.scissorX + mState.scissorWidth, mState.scissorY + mState.scissorHeight);
3525                         }
3526
3527                         stencilbuffer->clearStencil(stencil, static_cast<unsigned char>(mState.stencilWritemask), clearRect.x0, clearRect.y0, clearRect.width(), clearRect.height());
3528
3529                         stencilbuffer->release();
3530                 }
3531         }
3532 }
3533
3534 void Context::drawArrays(GLenum mode, GLint first, GLsizei count, GLsizei instanceCount)
3535 {
3536         if(!applyRenderTarget())
3537         {
3538                 return;
3539         }
3540
3541         if(mState.currentProgram == 0)
3542         {
3543                 return;   // Nothing to process.
3544         }
3545
3546         sw::DrawType primitiveType;
3547         int primitiveCount;
3548         int verticesPerPrimitive;
3549
3550         if(!es2sw::ConvertPrimitiveType(mode, count, GL_NONE, primitiveType, primitiveCount, verticesPerPrimitive))
3551         {
3552                 return error(GL_INVALID_ENUM);
3553         }
3554
3555         applyState(mode);
3556
3557         for(int i = 0; i < instanceCount; ++i)
3558         {
3559                 device->setInstanceID(i);
3560
3561                 GLenum err = applyVertexBuffer(0, first, count, i);
3562                 if(err != GL_NO_ERROR)
3563                 {
3564                         return error(err);
3565                 }
3566
3567                 applyShaders();
3568                 applyTextures();
3569
3570                 if(!getCurrentProgram()->validateSamplers(false))
3571                 {
3572                         return error(GL_INVALID_OPERATION);
3573                 }
3574
3575                 if(primitiveCount <= 0)
3576                 {
3577                         return;
3578                 }
3579
3580                 TransformFeedback* transformFeedback = getTransformFeedback();
3581                 if(!cullSkipsDraw(mode) || (transformFeedback->isActive() && !transformFeedback->isPaused()))
3582                 {
3583                         device->drawPrimitive(primitiveType, primitiveCount);
3584                 }
3585                 if(transformFeedback)
3586                 {
3587                         transformFeedback->addVertexOffset(primitiveCount * verticesPerPrimitive);
3588                 }
3589         }
3590 }
3591
3592 void Context::drawElements(GLenum mode, GLuint start, GLuint end, GLsizei count, GLenum type, const void *indices, GLsizei instanceCount)
3593 {
3594         if(!applyRenderTarget())
3595         {
3596                 return;
3597         }
3598
3599         if(mState.currentProgram == 0)
3600         {
3601                 return;   // Nothing to process.
3602         }
3603
3604         if(!indices && !getCurrentVertexArray()->getElementArrayBuffer())
3605         {
3606                 return error(GL_INVALID_OPERATION);
3607         }
3608
3609         GLenum internalMode = mode;
3610         if(isPrimitiveRestartFixedIndexEnabled())
3611         {
3612                 switch(mode)
3613                 {
3614                 case GL_TRIANGLE_FAN:
3615                 case GL_TRIANGLE_STRIP:
3616                         internalMode = GL_TRIANGLES;
3617                         break;
3618                 case GL_LINE_LOOP:
3619                 case GL_LINE_STRIP:
3620                         internalMode = GL_LINES;
3621                         break;
3622                 default:
3623                         break;
3624                 }
3625         }
3626
3627         sw::DrawType primitiveType;
3628         int primitiveCount;
3629         int verticesPerPrimitive;
3630
3631         if(!es2sw::ConvertPrimitiveType(internalMode, count, type, primitiveType, primitiveCount, verticesPerPrimitive))
3632         {
3633                 return error(GL_INVALID_ENUM);
3634         }
3635
3636         TranslatedIndexData indexInfo(primitiveCount);
3637         GLenum err = applyIndexBuffer(indices, start, end, count, mode, type, &indexInfo);
3638         if(err != GL_NO_ERROR)
3639         {
3640                 return error(err);
3641         }
3642
3643         applyState(internalMode);
3644
3645         for(int i = 0; i < instanceCount; ++i)
3646         {
3647                 device->setInstanceID(i);
3648
3649                 GLsizei vertexCount = indexInfo.maxIndex - indexInfo.minIndex + 1;
3650                 err = applyVertexBuffer(-(int)indexInfo.minIndex, indexInfo.minIndex, vertexCount, i);
3651                 if(err != GL_NO_ERROR)
3652                 {
3653                         return error(err);
3654                 }
3655
3656                 applyShaders();
3657                 applyTextures();
3658
3659                 if(!getCurrentProgram()->validateSamplers(false))
3660                 {
3661                         return error(GL_INVALID_OPERATION);
3662                 }
3663
3664                 if(primitiveCount <= 0)
3665                 {
3666                         return;
3667                 }
3668
3669                 TransformFeedback* transformFeedback = getTransformFeedback();
3670                 if(!cullSkipsDraw(internalMode) || (transformFeedback->isActive() && !transformFeedback->isPaused()))
3671                 {
3672                         device->drawIndexedPrimitive(primitiveType, indexInfo.indexOffset, indexInfo.primitiveCount);
3673                 }
3674                 if(transformFeedback)
3675                 {
3676                         transformFeedback->addVertexOffset(indexInfo.primitiveCount * verticesPerPrimitive);
3677                 }
3678         }
3679 }
3680
3681 void Context::blit(sw::Surface *source, const sw::SliceRect &sRect, sw::Surface *dest, const sw::SliceRect &dRect)
3682 {
3683         sw::SliceRectF sRectF((float)sRect.x0, (float)sRect.y0, (float)sRect.x1, (float)sRect.y1, sRect.slice);
3684         device->blit(source, sRectF, dest, dRect, false);
3685 }
3686
3687 void Context::finish()
3688 {
3689         device->finish();
3690 }
3691
3692 void Context::flush()
3693 {
3694         // We don't queue anything without processing it as fast as possible
3695 }
3696
3697 void Context::recordInvalidEnum()
3698 {
3699         mInvalidEnum = true;
3700 }
3701
3702 void Context::recordInvalidValue()
3703 {
3704         mInvalidValue = true;
3705 }
3706
3707 void Context::recordInvalidOperation()
3708 {
3709         mInvalidOperation = true;
3710 }
3711
3712 void Context::recordOutOfMemory()
3713 {
3714         mOutOfMemory = true;
3715 }
3716
3717 void Context::recordInvalidFramebufferOperation()
3718 {
3719         mInvalidFramebufferOperation = true;
3720 }
3721
3722 // Get one of the recorded errors and clear its flag, if any.
3723 // [OpenGL ES 2.0.24] section 2.5 page 13.
3724 GLenum Context::getError()
3725 {
3726         if(mInvalidEnum)
3727         {
3728                 mInvalidEnum = false;
3729
3730                 return GL_INVALID_ENUM;
3731         }
3732
3733         if(mInvalidValue)
3734         {
3735                 mInvalidValue = false;
3736
3737                 return GL_INVALID_VALUE;
3738         }
3739
3740         if(mInvalidOperation)
3741         {
3742                 mInvalidOperation = false;
3743
3744                 return GL_INVALID_OPERATION;
3745         }
3746
3747         if(mOutOfMemory)
3748         {
3749                 mOutOfMemory = false;
3750
3751                 return GL_OUT_OF_MEMORY;
3752         }
3753
3754         if(mInvalidFramebufferOperation)
3755         {
3756                 mInvalidFramebufferOperation = false;
3757
3758                 return GL_INVALID_FRAMEBUFFER_OPERATION;
3759         }
3760
3761         return GL_NO_ERROR;
3762 }
3763
3764 int Context::getSupportedMultisampleCount(int requested)
3765 {
3766         int supported = 0;
3767
3768         for(int i = NUM_MULTISAMPLE_COUNTS - 1; i >= 0; i--)
3769         {
3770                 if(supported >= requested)
3771                 {
3772                         return supported;
3773                 }
3774
3775                 supported = multisampleCount[i];
3776         }
3777
3778         return supported;
3779 }
3780
3781 void Context::detachBuffer(GLuint buffer)
3782 {
3783         // [OpenGL ES 2.0.24] section 2.9 page 22:
3784         // If a buffer object is deleted while it is bound, all bindings to that object in the current context
3785         // (i.e. in the thread that called Delete-Buffers) are reset to zero.
3786
3787         if(mState.copyReadBuffer.name() == buffer)
3788         {
3789                 mState.copyReadBuffer = nullptr;
3790         }
3791
3792         if(mState.copyWriteBuffer.name() == buffer)
3793         {
3794                 mState.copyWriteBuffer = nullptr;
3795         }
3796
3797         if(mState.pixelPackBuffer.name() == buffer)
3798         {
3799                 mState.pixelPackBuffer = nullptr;
3800         }
3801
3802         if(mState.pixelUnpackBuffer.name() == buffer)
3803         {
3804                 mState.pixelUnpackBuffer = nullptr;
3805         }
3806
3807         if(mState.genericUniformBuffer.name() == buffer)
3808         {
3809                 mState.genericUniformBuffer = nullptr;
3810         }
3811
3812         if(getArrayBufferName() == buffer)
3813         {
3814                 mState.arrayBuffer = nullptr;
3815         }
3816
3817         // Only detach from the current transform feedback
3818         TransformFeedback* currentTransformFeedback = getTransformFeedback();
3819         if(currentTransformFeedback)
3820         {
3821                 currentTransformFeedback->detachBuffer(buffer);
3822         }
3823
3824         // Only detach from the current vertex array
3825         VertexArray* currentVertexArray = getCurrentVertexArray();
3826         if(currentVertexArray)
3827         {
3828                 currentVertexArray->detachBuffer(buffer);
3829         }
3830
3831         for(int attribute = 0; attribute < MAX_VERTEX_ATTRIBS; attribute++)
3832         {
3833                 if(mState.vertexAttribute[attribute].mBoundBuffer.name() == buffer)
3834                 {
3835                         mState.vertexAttribute[attribute].mBoundBuffer = nullptr;
3836                 }
3837         }
3838 }
3839
3840 void Context::detachTexture(GLuint texture)
3841 {
3842         // [OpenGL ES 2.0.24] section 3.8 page 84:
3843         // If a texture object is deleted, it is as if all texture units which are bound to that texture object are
3844         // rebound to texture object zero
3845
3846         for(int type = 0; type < TEXTURE_TYPE_COUNT; type++)
3847         {
3848                 for(int sampler = 0; sampler < MAX_COMBINED_TEXTURE_IMAGE_UNITS; sampler++)
3849                 {
3850                         if(mState.samplerTexture[type][sampler].name() == texture)
3851                         {
3852                                 mState.samplerTexture[type][sampler] = nullptr;
3853                         }
3854                 }
3855         }
3856
3857         // [OpenGL ES 2.0.24] section 4.4 page 112:
3858         // If a texture object is deleted while its image is attached to the currently bound framebuffer, then it is
3859         // as if FramebufferTexture2D had been called, with a texture of 0, for each attachment point to which this
3860         // image was attached in the currently bound framebuffer.
3861
3862         Framebuffer *readFramebuffer = getReadFramebuffer();
3863         Framebuffer *drawFramebuffer = getDrawFramebuffer();
3864
3865         if(readFramebuffer)
3866         {
3867                 readFramebuffer->detachTexture(texture);
3868         }
3869
3870         if(drawFramebuffer && drawFramebuffer != readFramebuffer)
3871         {
3872                 drawFramebuffer->detachTexture(texture);
3873         }
3874 }
3875
3876 void Context::detachFramebuffer(GLuint framebuffer)
3877 {
3878         // [OpenGL ES 2.0.24] section 4.4 page 107:
3879         // If a framebuffer that is currently bound to the target FRAMEBUFFER is deleted, it is as though
3880         // BindFramebuffer had been executed with the target of FRAMEBUFFER and framebuffer of zero.
3881
3882         if(mState.readFramebuffer == framebuffer)
3883         {
3884                 bindReadFramebuffer(0);
3885         }
3886
3887         if(mState.drawFramebuffer == framebuffer)
3888         {
3889                 bindDrawFramebuffer(0);
3890         }
3891 }
3892
3893 void Context::detachRenderbuffer(GLuint renderbuffer)
3894 {
3895         // [OpenGL ES 2.0.24] section 4.4 page 109:
3896         // If a renderbuffer that is currently bound to RENDERBUFFER is deleted, it is as though BindRenderbuffer
3897         // had been executed with the target RENDERBUFFER and name of zero.
3898
3899         if(mState.renderbuffer.name() == renderbuffer)
3900         {
3901                 bindRenderbuffer(0);
3902         }
3903
3904         // [OpenGL ES 2.0.24] section 4.4 page 111:
3905         // If a renderbuffer object is deleted while its image is attached to the currently bound framebuffer,
3906         // then it is as if FramebufferRenderbuffer had been called, with a renderbuffer of 0, for each attachment
3907         // point to which this image was attached in the currently bound framebuffer.
3908
3909         Framebuffer *readFramebuffer = getReadFramebuffer();
3910         Framebuffer *drawFramebuffer = getDrawFramebuffer();
3911
3912         if(readFramebuffer)
3913         {
3914                 readFramebuffer->detachRenderbuffer(renderbuffer);
3915         }
3916
3917         if(drawFramebuffer && drawFramebuffer != readFramebuffer)
3918         {
3919                 drawFramebuffer->detachRenderbuffer(renderbuffer);
3920         }
3921 }
3922
3923 void Context::detachSampler(GLuint sampler)
3924 {
3925         // [OpenGL ES 3.0.2] section 3.8.2 pages 123-124:
3926         // If a sampler object that is currently bound to one or more texture units is
3927         // deleted, it is as though BindSampler is called once for each texture unit to
3928         // which the sampler is bound, with unit set to the texture unit and sampler set to zero.
3929         for(size_t textureUnit = 0; textureUnit < MAX_COMBINED_TEXTURE_IMAGE_UNITS; ++textureUnit)
3930         {
3931                 gl::BindingPointer<Sampler> &samplerBinding = mState.sampler[textureUnit];
3932                 if(samplerBinding.name() == sampler)
3933                 {
3934                         samplerBinding = nullptr;
3935                 }
3936         }
3937 }
3938
3939 bool Context::cullSkipsDraw(GLenum drawMode)
3940 {
3941         return mState.cullFaceEnabled && mState.cullMode == GL_FRONT_AND_BACK && isTriangleMode(drawMode);
3942 }
3943
3944 bool Context::isTriangleMode(GLenum drawMode)
3945 {
3946         switch(drawMode)
3947         {
3948         case GL_TRIANGLES:
3949         case GL_TRIANGLE_FAN:
3950         case GL_TRIANGLE_STRIP:
3951                 return true;
3952         case GL_POINTS:
3953         case GL_LINES:
3954         case GL_LINE_LOOP:
3955         case GL_LINE_STRIP:
3956                 return false;
3957         default: UNREACHABLE(drawMode);
3958         }
3959
3960         return false;
3961 }
3962
3963 void Context::setVertexAttrib(GLuint index, const GLfloat *values)
3964 {
3965         ASSERT(index < MAX_VERTEX_ATTRIBS);
3966
3967         mState.vertexAttribute[index].setCurrentValue(values);
3968
3969         mVertexDataManager->dirtyCurrentValue(index);
3970 }
3971
3972 void Context::setVertexAttrib(GLuint index, const GLint *values)
3973 {
3974         ASSERT(index < MAX_VERTEX_ATTRIBS);
3975
3976         mState.vertexAttribute[index].setCurrentValue(values);
3977
3978         mVertexDataManager->dirtyCurrentValue(index);
3979 }
3980
3981 void Context::setVertexAttrib(GLuint index, const GLuint *values)
3982 {
3983         ASSERT(index < MAX_VERTEX_ATTRIBS);
3984
3985         mState.vertexAttribute[index].setCurrentValue(values);
3986
3987         mVertexDataManager->dirtyCurrentValue(index);
3988 }
3989
3990 void Context::blitFramebuffer(GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1,
3991                               GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1,
3992                               GLbitfield mask, bool filter, bool allowPartialDepthStencilBlit)
3993 {
3994         Framebuffer *readFramebuffer = getReadFramebuffer();
3995         Framebuffer *drawFramebuffer = getDrawFramebuffer();
3996
3997         int readBufferWidth, readBufferHeight, readBufferSamples;
3998         int drawBufferWidth, drawBufferHeight, drawBufferSamples;
3999
4000         if(!readFramebuffer || (readFramebuffer->completeness(readBufferWidth, readBufferHeight, readBufferSamples) != GL_FRAMEBUFFER_COMPLETE) ||
4001            !drawFramebuffer || (drawFramebuffer->completeness(drawBufferWidth, drawBufferHeight, drawBufferSamples) != GL_FRAMEBUFFER_COMPLETE))
4002         {
4003                 return error(GL_INVALID_FRAMEBUFFER_OPERATION);
4004         }
4005
4006         if(drawBufferSamples > 1)
4007         {
4008                 return error(GL_INVALID_OPERATION);
4009         }
4010
4011         sw::SliceRect sourceRect;
4012         sw::SliceRect destRect;
4013         bool flipX = (srcX0 < srcX1) ^ (dstX0 < dstX1);
4014         bool flipY = (srcY0 < srcY1) ^ (dstY0 < dstY1);
4015
4016         if(srcX0 < srcX1)
4017         {
4018                 sourceRect.x0 = srcX0;
4019                 sourceRect.x1 = srcX1;
4020         }
4021         else
4022         {
4023                 sourceRect.x0 = srcX1;
4024                 sourceRect.x1 = srcX0;
4025         }
4026
4027         if(dstX0 < dstX1)
4028         {
4029                 destRect.x0 = dstX0;
4030                 destRect.x1 = dstX1;
4031         }
4032         else
4033         {
4034                 destRect.x0 = dstX1;
4035                 destRect.x1 = dstX0;
4036         }
4037
4038         if(srcY0 < srcY1)
4039         {
4040                 sourceRect.y0 = srcY0;
4041                 sourceRect.y1 = srcY1;
4042         }
4043         else
4044         {
4045                 sourceRect.y0 = srcY1;
4046                 sourceRect.y1 = srcY0;
4047         }
4048
4049         if(dstY0 < dstY1)
4050         {
4051                 destRect.y0 = dstY0;
4052                 destRect.y1 = dstY1;
4053         }
4054         else
4055         {
4056                 destRect.y0 = dstY1;
4057                 destRect.y1 = dstY0;
4058         }
4059
4060         sw::RectF sourceScissoredRect(static_cast<float>(sourceRect.x0), static_cast<float>(sourceRect.y0),
4061                                       static_cast<float>(sourceRect.x1), static_cast<float>(sourceRect.y1));
4062         sw::Rect destScissoredRect = destRect;
4063
4064         if(mState.scissorTestEnabled)   // Only write to parts of the destination framebuffer which pass the scissor test
4065         {
4066                 sw::Rect scissorRect(mState.scissorX, mState.scissorY, mState.scissorX + mState.scissorWidth, mState.scissorY + mState.scissorHeight);
4067                 Device::ClipDstRect(sourceScissoredRect, destScissoredRect, scissorRect, flipX, flipY);
4068         }
4069
4070         sw::SliceRectF sourceTrimmedRect = sourceScissoredRect;
4071         sw::SliceRect destTrimmedRect = destScissoredRect;
4072
4073         // The source & destination rectangles also may need to be trimmed if
4074         // they fall out of the bounds of the actual draw and read surfaces.
4075         sw::Rect sourceTrimRect(0, 0, readBufferWidth, readBufferHeight);
4076         Device::ClipSrcRect(sourceTrimmedRect, destTrimmedRect, sourceTrimRect, flipX, flipY);
4077
4078         sw::Rect destTrimRect(0, 0, drawBufferWidth, drawBufferHeight);
4079         Device::ClipDstRect(sourceTrimmedRect, destTrimmedRect, destTrimRect, flipX, flipY);
4080
4081         bool partialBufferCopy = false;
4082
4083         if(sourceTrimmedRect.y1 - sourceTrimmedRect.y0 < readBufferHeight ||
4084            sourceTrimmedRect.x1 - sourceTrimmedRect.x0 < readBufferWidth ||
4085            destTrimmedRect.y1 - destTrimmedRect.y0 < drawBufferHeight ||
4086            destTrimmedRect.x1 - destTrimmedRect.x0 < drawBufferWidth ||
4087            sourceTrimmedRect.y0 != 0 || destTrimmedRect.y0 != 0 || sourceTrimmedRect.x0 != 0 || destTrimmedRect.x0 != 0)
4088         {
4089                 partialBufferCopy = true;
4090         }
4091
4092         bool sameBounds = (srcX0 == dstX0 && srcY0 == dstY0 && srcX1 == dstX1 && srcY1 == dstY1);
4093         bool blitRenderTarget = false;
4094         bool blitDepth = false;
4095         bool blitStencil = false;
4096
4097         if(mask & GL_COLOR_BUFFER_BIT)
4098         {
4099                 GLenum readColorbufferType = readFramebuffer->getReadBufferType();
4100                 GLenum drawColorbufferType = drawFramebuffer->getColorbufferType(0);
4101                 const bool validReadType = readColorbufferType == GL_TEXTURE_2D || readColorbufferType == GL_TEXTURE_RECTANGLE_ARB || Framebuffer::IsRenderbuffer(readColorbufferType);
4102                 const bool validDrawType = drawColorbufferType == GL_TEXTURE_2D || drawColorbufferType == GL_TEXTURE_RECTANGLE_ARB || Framebuffer::IsRenderbuffer(drawColorbufferType);
4103                 if(!validReadType || !validDrawType)
4104                 {
4105                         return error(GL_INVALID_OPERATION);
4106                 }
4107
4108                 if(partialBufferCopy && readBufferSamples > 1 && !sameBounds)
4109                 {
4110                         return error(GL_INVALID_OPERATION);
4111                 }
4112
4113                 // The GL ES 3.0.2 spec (pg 193) states that:
4114                 // 1) If the read buffer is fixed point format, the draw buffer must be as well
4115                 // 2) If the read buffer is an unsigned integer format, the draw buffer must be
4116                 // as well
4117                 // 3) If the read buffer is a signed integer format, the draw buffer must be as
4118                 // well
4119                 es2::Renderbuffer *readRenderbuffer = readFramebuffer->getReadColorbuffer();
4120                 es2::Renderbuffer *drawRenderbuffer = drawFramebuffer->getColorbuffer(0);
4121                 GLint readFormat = readRenderbuffer->getFormat();
4122                 GLint drawFormat = drawRenderbuffer->getFormat();
4123                 GLenum readComponentType = GetComponentType(readFormat, GL_COLOR_ATTACHMENT0);
4124                 GLenum drawComponentType = GetComponentType(drawFormat, GL_COLOR_ATTACHMENT0);
4125                 bool readFixedPoint = ((readComponentType == GL_UNSIGNED_NORMALIZED) ||
4126                                        (readComponentType == GL_SIGNED_NORMALIZED));
4127                 bool drawFixedPoint = ((drawComponentType == GL_UNSIGNED_NORMALIZED) ||
4128                                        (drawComponentType == GL_SIGNED_NORMALIZED));
4129                 bool readFixedOrFloat = (readFixedPoint || (readComponentType == GL_FLOAT));
4130                 bool drawFixedOrFloat = (drawFixedPoint || (drawComponentType == GL_FLOAT));
4131
4132                 if(readFixedOrFloat != drawFixedOrFloat)
4133                 {
4134                         return error(GL_INVALID_OPERATION);
4135                 }
4136
4137                 if((readComponentType == GL_UNSIGNED_INT) && (drawComponentType != GL_UNSIGNED_INT))
4138                 {
4139                         return error(GL_INVALID_OPERATION);
4140                 }
4141
4142                 if((readComponentType == GL_INT) && (drawComponentType != GL_INT))
4143                 {
4144                         return error(GL_INVALID_OPERATION);
4145                 }
4146
4147                 // Cannot filter integer data
4148                 if(((readComponentType == GL_UNSIGNED_INT) || (readComponentType == GL_INT)) && filter)
4149                 {
4150                         return error(GL_INVALID_OPERATION);
4151                 }
4152
4153                 if((readRenderbuffer->getSamples() > 0) && (readFormat != drawFormat))
4154                 {
4155                         // RGBA8 and BGRA8 should be interchangeable here
4156                         if(!(((readFormat == GL_RGBA8) && (drawFormat == GL_BGRA8_EXT)) ||
4157                                  ((readFormat == GL_BGRA8_EXT) && (drawFormat == GL_RGBA8))))
4158                         {
4159                                 return error(GL_INVALID_OPERATION);
4160                         }
4161                 }
4162
4163                 blitRenderTarget = true;
4164         }
4165
4166         if(mask & (GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT))
4167         {
4168                 Renderbuffer *readDSBuffer = nullptr;
4169                 Renderbuffer *drawDSBuffer = nullptr;
4170
4171                 if(mask & GL_DEPTH_BUFFER_BIT)
4172                 {
4173                         if(readFramebuffer->getDepthbuffer() && drawFramebuffer->getDepthbuffer())
4174                         {
4175                                 GLenum readDepthBufferType = readFramebuffer->getDepthbufferType();
4176                                 GLenum drawDepthBufferType = drawFramebuffer->getDepthbufferType();
4177                                 if((readDepthBufferType != drawDepthBufferType) &&
4178                                    !(Framebuffer::IsRenderbuffer(readDepthBufferType) && Framebuffer::IsRenderbuffer(drawDepthBufferType)))
4179                                 {
4180                                         return error(GL_INVALID_OPERATION);
4181                                 }
4182
4183                                 blitDepth = true;
4184                                 readDSBuffer = readFramebuffer->getDepthbuffer();
4185                                 drawDSBuffer = drawFramebuffer->getDepthbuffer();
4186
4187                                 if(readDSBuffer->getFormat() != drawDSBuffer->getFormat())
4188                                 {
4189                                         return error(GL_INVALID_OPERATION);
4190                                 }
4191                         }
4192                 }
4193
4194                 if(mask & GL_STENCIL_BUFFER_BIT)
4195                 {
4196                         if(readFramebuffer->getStencilbuffer() && drawFramebuffer->getStencilbuffer())
4197                         {
4198                                 GLenum readStencilBufferType = readFramebuffer->getStencilbufferType();
4199                                 GLenum drawStencilBufferType = drawFramebuffer->getStencilbufferType();
4200                                 if((readStencilBufferType != drawStencilBufferType) &&
4201                                    !(Framebuffer::IsRenderbuffer(readStencilBufferType) && Framebuffer::IsRenderbuffer(drawStencilBufferType)))
4202                                 {
4203                                         return error(GL_INVALID_OPERATION);
4204                                 }
4205
4206                                 blitStencil = true;
4207                                 readDSBuffer = readFramebuffer->getStencilbuffer();
4208                                 drawDSBuffer = drawFramebuffer->getStencilbuffer();
4209
4210                                 if(readDSBuffer->getFormat() != drawDSBuffer->getFormat())
4211                                 {
4212                                         return error(GL_INVALID_OPERATION);
4213                                 }
4214                         }
4215                 }
4216
4217                 if(partialBufferCopy && !allowPartialDepthStencilBlit)
4218                 {
4219                         ERR("Only whole-buffer depth and stencil blits are supported by ANGLE_framebuffer_blit.");
4220                         return error(GL_INVALID_OPERATION);   // Only whole-buffer copies are permitted
4221                 }
4222
4223                 // OpenGL ES 3.0.4 spec, p.199:
4224                 // ...an INVALID_OPERATION error is generated if the formats of the read
4225                 // and draw framebuffers are not identical or if the source and destination
4226                 // rectangles are not defined with the same(X0, Y 0) and (X1, Y 1) bounds.
4227                 // If SAMPLE_BUFFERS for the draw framebuffer is greater than zero, an
4228                 // INVALID_OPERATION error is generated.
4229                 if((drawDSBuffer && drawDSBuffer->getSamples() > 1) ||
4230                    ((readDSBuffer && readDSBuffer->getSamples() > 1) &&
4231                     (!sameBounds || (drawDSBuffer->getFormat() != readDSBuffer->getFormat()))))
4232                 {
4233                         return error(GL_INVALID_OPERATION);
4234                 }
4235         }
4236
4237         if(blitRenderTarget || blitDepth || blitStencil)
4238         {
4239                 if(flipX)
4240                 {
4241                         swap(destTrimmedRect.x0, destTrimmedRect.x1);
4242                 }
4243                 if(flipY)
4244                 {
4245                         swap(destTrimmedRect.y0, destTrimmedRect.y1);
4246                 }
4247
4248                 if(blitRenderTarget)
4249                 {
4250                         egl::Image *readRenderTarget = readFramebuffer->getReadRenderTarget();
4251                         egl::Image *drawRenderTarget = drawFramebuffer->getRenderTarget(0);
4252
4253                         bool success = device->stretchRect(readRenderTarget, &sourceTrimmedRect, drawRenderTarget, &destTrimmedRect, (filter ? Device::USE_FILTER : 0) | Device::COLOR_BUFFER);
4254
4255                         readRenderTarget->release();
4256                         drawRenderTarget->release();
4257
4258                         if(!success)
4259                         {
4260                                 ERR("BlitFramebuffer failed.");
4261                                 return;
4262                         }
4263                 }
4264
4265                 if(blitDepth)
4266                 {
4267                         egl::Image *readRenderTarget = readFramebuffer->getDepthBuffer();
4268                         egl::Image *drawRenderTarget = drawFramebuffer->getDepthBuffer();
4269
4270                         bool success = device->stretchRect(readRenderTarget, &sourceTrimmedRect, drawRenderTarget, &destTrimmedRect, (filter ? Device::USE_FILTER : 0) | Device::DEPTH_BUFFER);
4271
4272                         readRenderTarget->release();
4273                         drawRenderTarget->release();
4274
4275                         if(!success)
4276                         {
4277                                 ERR("BlitFramebuffer failed.");
4278                                 return;
4279                         }
4280                 }
4281
4282                 if(blitStencil)
4283                 {
4284                         egl::Image *readRenderTarget = readFramebuffer->getStencilBuffer();
4285                         egl::Image *drawRenderTarget = drawFramebuffer->getStencilBuffer();
4286
4287                         bool success = device->stretchRect(readRenderTarget, &sourceTrimmedRect, drawRenderTarget, &destTrimmedRect, (filter ? Device::USE_FILTER : 0) | Device::STENCIL_BUFFER);
4288
4289                         readRenderTarget->release();
4290                         drawRenderTarget->release();
4291
4292                         if(!success)
4293                         {
4294                                 ERR("BlitFramebuffer failed.");
4295                                 return;
4296                         }
4297                 }
4298         }
4299 }
4300
4301 void Context::bindTexImage(gl::Surface *surface)
4302 {
4303         bool isRect = (surface->getTextureTarget() == EGL_TEXTURE_RECTANGLE_ANGLE);
4304         es2::Texture2D *textureObject = isRect ? getTexture2DRect() : getTexture2D();
4305
4306         if(textureObject)
4307         {
4308                 textureObject->bindTexImage(surface);
4309         }
4310 }
4311
4312 EGLenum Context::validateSharedImage(EGLenum target, GLuint name, GLuint textureLevel)
4313 {
4314         GLenum textureTarget = GL_NONE;
4315
4316         switch(target)
4317         {
4318         case EGL_GL_TEXTURE_2D_KHR:
4319                 textureTarget = GL_TEXTURE_2D;
4320                 break;
4321         case EGL_GL_TEXTURE_CUBE_MAP_POSITIVE_X_KHR:
4322         case EGL_GL_TEXTURE_CUBE_MAP_NEGATIVE_X_KHR:
4323         case EGL_GL_TEXTURE_CUBE_MAP_POSITIVE_Y_KHR:
4324         case EGL_GL_TEXTURE_CUBE_MAP_NEGATIVE_Y_KHR:
4325         case EGL_GL_TEXTURE_CUBE_MAP_POSITIVE_Z_KHR:
4326         case EGL_GL_TEXTURE_CUBE_MAP_NEGATIVE_Z_KHR:
4327                 textureTarget = GL_TEXTURE_CUBE_MAP;
4328                 break;
4329         case EGL_GL_RENDERBUFFER_KHR:
4330                 break;
4331         default:
4332                 return EGL_BAD_PARAMETER;
4333         }
4334
4335         if(textureLevel >= es2::IMPLEMENTATION_MAX_TEXTURE_LEVELS)
4336         {
4337                 return EGL_BAD_MATCH;
4338         }
4339
4340         if(textureTarget != GL_NONE)
4341         {
4342                 es2::Texture *texture = getTexture(name);
4343
4344                 if(!texture || texture->getTarget() != textureTarget)
4345                 {
4346                         return EGL_BAD_PARAMETER;
4347                 }
4348
4349                 if(texture->isShared(textureTarget, textureLevel))   // Bound to an EGLSurface or already an EGLImage sibling
4350                 {
4351                         return EGL_BAD_ACCESS;
4352                 }
4353
4354                 if(textureLevel != 0 && !texture->isSamplerComplete())
4355                 {
4356                         return EGL_BAD_PARAMETER;
4357                 }
4358
4359                 if(textureLevel == 0 && !(texture->isSamplerComplete() && texture->getTopLevel() == 0))
4360                 {
4361                         return EGL_BAD_PARAMETER;
4362                 }
4363         }
4364         else if(target == EGL_GL_RENDERBUFFER_KHR)
4365         {
4366                 es2::Renderbuffer *renderbuffer = getRenderbuffer(name);
4367
4368                 if(!renderbuffer)
4369                 {
4370                         return EGL_BAD_PARAMETER;
4371                 }
4372
4373                 if(renderbuffer->isShared())   // Already an EGLImage sibling
4374                 {
4375                         return EGL_BAD_ACCESS;
4376                 }
4377         }
4378         else UNREACHABLE(target);
4379
4380         return EGL_SUCCESS;
4381 }
4382
4383 egl::Image *Context::createSharedImage(EGLenum target, GLuint name, GLuint textureLevel)
4384 {
4385         GLenum textureTarget = GL_NONE;
4386
4387         switch(target)
4388         {
4389         case EGL_GL_TEXTURE_2D_KHR:                  textureTarget = GL_TEXTURE_2D;                  break;
4390         case EGL_GL_TEXTURE_CUBE_MAP_POSITIVE_X_KHR: textureTarget = GL_TEXTURE_CUBE_MAP_POSITIVE_X; break;
4391         case EGL_GL_TEXTURE_CUBE_MAP_NEGATIVE_X_KHR: textureTarget = GL_TEXTURE_CUBE_MAP_NEGATIVE_X; break;
4392         case EGL_GL_TEXTURE_CUBE_MAP_POSITIVE_Y_KHR: textureTarget = GL_TEXTURE_CUBE_MAP_POSITIVE_Y; break;
4393         case EGL_GL_TEXTURE_CUBE_MAP_NEGATIVE_Y_KHR: textureTarget = GL_TEXTURE_CUBE_MAP_NEGATIVE_Y; break;
4394         case EGL_GL_TEXTURE_CUBE_MAP_POSITIVE_Z_KHR: textureTarget = GL_TEXTURE_CUBE_MAP_POSITIVE_Z; break;
4395         case EGL_GL_TEXTURE_CUBE_MAP_NEGATIVE_Z_KHR: textureTarget = GL_TEXTURE_CUBE_MAP_NEGATIVE_Z; break;
4396         }
4397
4398         if(textureTarget != GL_NONE)
4399         {
4400                 es2::Texture *texture = getTexture(name);
4401
4402                 return texture->createSharedImage(textureTarget, textureLevel);
4403         }
4404         else if(target == EGL_GL_RENDERBUFFER_KHR)
4405         {
4406                 es2::Renderbuffer *renderbuffer = getRenderbuffer(name);
4407
4408                 return renderbuffer->createSharedImage();
4409         }
4410         else UNREACHABLE(target);
4411
4412         return nullptr;
4413 }
4414
4415 egl::Image *Context::getSharedImage(GLeglImageOES image)
4416 {
4417         return display->getSharedImage(image);
4418 }
4419
4420 Device *Context::getDevice()
4421 {
4422         return device;
4423 }
4424
4425 const GLubyte *Context::getExtensions(GLuint index, GLuint *numExt) const
4426 {
4427         // Keep list sorted in following order:
4428         // OES extensions
4429         // EXT extensions
4430         // Vendor extensions
4431         static const char *es2extensions[] =
4432         {
4433                 "GL_OES_compressed_ETC1_RGB8_texture",
4434                 "GL_OES_depth24",
4435                 "GL_OES_depth32",
4436                 "GL_OES_depth_texture",
4437                 "GL_OES_depth_texture_cube_map",
4438                 "GL_OES_EGL_image",
4439                 "GL_OES_EGL_image_external",
4440                 "GL_OES_EGL_sync",
4441                 "GL_OES_element_index_uint",
4442                 "GL_OES_framebuffer_object",
4443                 "GL_OES_packed_depth_stencil",
4444                 "GL_OES_rgb8_rgba8",
4445                 "GL_OES_standard_derivatives",
4446                 "GL_OES_surfaceless_context",
4447                 "GL_OES_texture_float",
4448                 "GL_OES_texture_float_linear",
4449                 "GL_OES_texture_half_float",
4450                 "GL_OES_texture_half_float_linear",
4451                 "GL_OES_texture_npot",
4452                 "GL_OES_texture_3D",
4453                 "GL_OES_vertex_array_object",
4454                 "GL_OES_vertex_half_float",
4455                 "GL_EXT_blend_minmax",
4456                 "GL_EXT_color_buffer_half_float",
4457                 "GL_EXT_draw_buffers",
4458                 "GL_EXT_instanced_arrays",
4459                 "GL_EXT_occlusion_query_boolean",
4460                 "GL_EXT_read_format_bgra",
4461                 "GL_EXT_texture_compression_dxt1",
4462                 "GL_EXT_texture_filter_anisotropic",
4463                 "GL_EXT_texture_format_BGRA8888",
4464                 "GL_EXT_texture_rg",
4465 #if (ASTC_SUPPORT)
4466                 "GL_KHR_texture_compression_astc_hdr",
4467                 "GL_KHR_texture_compression_astc_ldr",
4468 #endif
4469                 "GL_ARB_texture_rectangle",
4470                 "GL_ANGLE_framebuffer_blit",
4471                 "GL_ANGLE_framebuffer_multisample",
4472                 "GL_ANGLE_instanced_arrays",
4473                 "GL_ANGLE_texture_compression_dxt3",
4474                 "GL_ANGLE_texture_compression_dxt5",
4475                 "GL_APPLE_texture_format_BGRA8888",
4476                 "GL_CHROMIUM_color_buffer_float_rgba", // A subset of EXT_color_buffer_float on top of OpenGL ES 2.0
4477                 "GL_CHROMIUM_texture_filtering_hint",
4478                 "GL_NV_fence",
4479                 "GL_NV_framebuffer_blit",
4480                 "GL_NV_read_depth",
4481         };
4482
4483         // Extensions exclusive to OpenGL ES 3.0 and above.
4484         static const char *es3extensions[] =
4485         {
4486                 "GL_EXT_color_buffer_float",
4487         };
4488
4489         GLuint numES2extensions = sizeof(es2extensions) / sizeof(es2extensions[0]);
4490         GLuint numExtensions = numES2extensions;
4491
4492         if(clientVersion >= 3)
4493         {
4494                 numExtensions += sizeof(es3extensions) / sizeof(es3extensions[0]);
4495         }
4496
4497         if(numExt)
4498         {
4499                 *numExt = numExtensions;
4500
4501                 return nullptr;
4502         }
4503
4504         if(index == GL_INVALID_INDEX)
4505         {
4506                 static std::string extensionsCat;
4507
4508                 if(extensionsCat.empty() && (numExtensions > 0))
4509                 {
4510                         for(const char *extension : es2extensions)
4511                         {
4512                                 extensionsCat += std::string(extension) + " ";
4513                         }
4514
4515                         if(clientVersion >= 3)
4516                         {
4517                                 for(const char *extension : es3extensions)
4518                                 {
4519                                         extensionsCat += std::string(extension) + " ";
4520                                 }
4521                         }
4522                 }
4523
4524                 return (const GLubyte*)extensionsCat.c_str();
4525         }
4526
4527         if(index >= numExtensions)
4528         {
4529                 return nullptr;
4530         }
4531
4532         if(index < numES2extensions)
4533         {
4534                 return (const GLubyte*)es2extensions[index];
4535         }
4536         else
4537         {
4538                 return (const GLubyte*)es3extensions[index - numES2extensions];
4539         }
4540 }
4541
4542 }
4543
4544 NO_SANITIZE_FUNCTION egl::Context *es2CreateContext(egl::Display *display, const egl::Context *shareContext, int clientVersion, const egl::Config *config)
4545 {
4546         ASSERT(!shareContext || shareContext->getClientVersion() == clientVersion);   // Should be checked by eglCreateContext
4547         return new es2::Context(display, static_cast<const es2::Context*>(shareContext), clientVersion, config);
4548 }