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