Context.cpp revision ae05d655e9b64966bef23c6631955bd8d2808c84
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] = NULL;
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
1271bool 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	return !!vertexArray;
1284}
1285
1286void Context::bindGenericUniformBuffer(GLuint buffer)
1287{
1288	mResourceManager->checkBufferAllocation(buffer);
1289
1290	mState.genericUniformBuffer = getBuffer(buffer);
1291}
1292
1293void Context::bindIndexedUniformBuffer(GLuint buffer, GLuint index, GLintptr offset, GLsizeiptr size)
1294{
1295	mResourceManager->checkBufferAllocation(buffer);
1296
1297	Buffer* bufferObject = getBuffer(buffer);
1298	if(bufferObject)
1299	{
1300		bufferObject->setOffset(offset);
1301		bufferObject->setSize(size);
1302	}
1303	mState.uniformBuffers[index] = bufferObject;
1304}
1305
1306void Context::bindGenericTransformFeedbackBuffer(GLuint buffer)
1307{
1308	mResourceManager->checkBufferAllocation(buffer);
1309
1310	getTransformFeedback()->setGenericBuffer(getBuffer(buffer));
1311}
1312
1313void Context::bindIndexedTransformFeedbackBuffer(GLuint buffer, GLuint index, GLintptr offset, GLsizeiptr size)
1314{
1315	mResourceManager->checkBufferAllocation(buffer);
1316
1317	Buffer* bufferObject = getBuffer(buffer);
1318	if(bufferObject)
1319	{
1320		bufferObject->setOffset(offset);
1321		bufferObject->setSize(size);
1322	}
1323	getTransformFeedback()->setBuffer(index, bufferObject);
1324}
1325
1326bool Context::bindTransformFeedback(GLuint id)
1327{
1328	if(!getTransformFeedback(id))
1329	{
1330		mTransformFeedbackMap[id] = new TransformFeedback(id);
1331	}
1332
1333	mState.transformFeedback = id;
1334
1335	return true;
1336}
1337
1338bool Context::bindSampler(GLuint unit, GLuint sampler)
1339{
1340	mResourceManager->checkSamplerAllocation(sampler);
1341
1342	Sampler* samplerObject = getSampler(sampler);
1343
1344	if(sampler)
1345	{
1346		mState.sampler[unit] = samplerObject;
1347	}
1348
1349	return !!samplerObject;
1350}
1351
1352void Context::useProgram(GLuint program)
1353{
1354    GLuint priorProgram = mState.currentProgram;
1355    mState.currentProgram = program;               // Must switch before trying to delete, otherwise it only gets flagged.
1356
1357    if(priorProgram != program)
1358    {
1359        Program *newProgram = mResourceManager->getProgram(program);
1360        Program *oldProgram = mResourceManager->getProgram(priorProgram);
1361
1362        if(newProgram)
1363        {
1364            newProgram->addRef();
1365        }
1366
1367        if(oldProgram)
1368        {
1369            oldProgram->release();
1370        }
1371    }
1372}
1373
1374void Context::beginQuery(GLenum target, GLuint query)
1375{
1376    // From EXT_occlusion_query_boolean: If BeginQueryEXT is called with an <id>
1377    // of zero, if the active query object name for <target> is non-zero (for the
1378    // targets ANY_SAMPLES_PASSED_EXT and ANY_SAMPLES_PASSED_CONSERVATIVE_EXT, if
1379    // the active query for either target is non-zero), if <id> is the name of an
1380    // existing query object whose type does not match <target>, or if <id> is the
1381    // active query object name for any query type, the error INVALID_OPERATION is
1382    // generated.
1383
1384    // Ensure no other queries are active
1385    // NOTE: If other queries than occlusion are supported, we will need to check
1386    // separately that:
1387    //    a) The query ID passed is not the current active query for any target/type
1388    //    b) There are no active queries for the requested target (and in the case
1389    //       of GL_ANY_SAMPLES_PASSED_EXT and GL_ANY_SAMPLES_PASSED_CONSERVATIVE_EXT,
1390    //       no query may be active for either if glBeginQuery targets either.
1391    for(int i = 0; i < QUERY_TYPE_COUNT; i++)
1392    {
1393        if(mState.activeQuery[i] != NULL)
1394        {
1395            return error(GL_INVALID_OPERATION);
1396        }
1397    }
1398
1399    QueryType qType;
1400    switch(target)
1401    {
1402    case GL_ANY_SAMPLES_PASSED_EXT:
1403        qType = QUERY_ANY_SAMPLES_PASSED;
1404        break;
1405    case GL_ANY_SAMPLES_PASSED_CONSERVATIVE_EXT:
1406        qType = QUERY_ANY_SAMPLES_PASSED_CONSERVATIVE;
1407        break;
1408    case GL_TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN:
1409        qType = QUERY_TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN;
1410        break;
1411    default:
1412        ASSERT(false);
1413    }
1414
1415    Query *queryObject = createQuery(query, target);
1416
1417    // Check that name was obtained with glGenQueries
1418    if(!queryObject)
1419    {
1420        return error(GL_INVALID_OPERATION);
1421    }
1422
1423    // Check for type mismatch
1424    if(queryObject->getType() != target)
1425    {
1426        return error(GL_INVALID_OPERATION);
1427    }
1428
1429    // Set query as active for specified target
1430    mState.activeQuery[qType] = queryObject;
1431
1432    // Begin query
1433    queryObject->begin();
1434}
1435
1436void Context::endQuery(GLenum target)
1437{
1438    QueryType qType;
1439
1440    switch(target)
1441    {
1442    case GL_ANY_SAMPLES_PASSED_EXT:                qType = QUERY_ANY_SAMPLES_PASSED;                    break;
1443    case GL_ANY_SAMPLES_PASSED_CONSERVATIVE_EXT:   qType = QUERY_ANY_SAMPLES_PASSED_CONSERVATIVE;       break;
1444    case GL_TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN: qType = QUERY_TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN; break;
1445    default: UNREACHABLE(target); return;
1446    }
1447
1448    Query *queryObject = mState.activeQuery[qType];
1449
1450    if(queryObject == NULL)
1451    {
1452        return error(GL_INVALID_OPERATION);
1453    }
1454
1455    queryObject->end();
1456
1457    mState.activeQuery[qType] = NULL;
1458}
1459
1460void Context::setFramebufferZero(Framebuffer *buffer)
1461{
1462    delete mFramebufferMap[0];
1463    mFramebufferMap[0] = buffer;
1464}
1465
1466void Context::setRenderbufferStorage(RenderbufferStorage *renderbuffer)
1467{
1468    Renderbuffer *renderbufferObject = mState.renderbuffer;
1469    renderbufferObject->setStorage(renderbuffer);
1470}
1471
1472Framebuffer *Context::getFramebuffer(unsigned int handle) const
1473{
1474    FramebufferMap::const_iterator framebuffer = mFramebufferMap.find(handle);
1475
1476    if(framebuffer == mFramebufferMap.end())
1477    {
1478        return NULL;
1479    }
1480    else
1481    {
1482        return framebuffer->second;
1483    }
1484}
1485
1486Fence *Context::getFence(unsigned int handle) const
1487{
1488    FenceMap::const_iterator fence = mFenceMap.find(handle);
1489
1490    if(fence == mFenceMap.end())
1491    {
1492        return NULL;
1493    }
1494    else
1495    {
1496        return fence->second;
1497    }
1498}
1499
1500FenceSync *Context::getFenceSync(GLsync handle) const
1501{
1502	return mResourceManager->getFenceSync(static_cast<GLuint>(reinterpret_cast<uintptr_t>(handle)));
1503}
1504
1505Query *Context::getQuery(unsigned int handle) const
1506{
1507	QueryMap::const_iterator query = mQueryMap.find(handle);
1508
1509	if(query == mQueryMap.end())
1510	{
1511		return NULL;
1512	}
1513	else
1514	{
1515		return query->second;
1516	}
1517}
1518
1519Query *Context::createQuery(unsigned int handle, GLenum type)
1520{
1521	QueryMap::iterator query = mQueryMap.find(handle);
1522
1523	if(query == mQueryMap.end())
1524	{
1525		return NULL;
1526	}
1527	else
1528	{
1529		if(!query->second)
1530		{
1531			query->second = new Query(handle, type);
1532			query->second->addRef();
1533		}
1534
1535		return query->second;
1536	}
1537}
1538
1539VertexArray *Context::getVertexArray(GLuint array) const
1540{
1541	VertexArrayMap::const_iterator vertexArray = mVertexArrayMap.find(array);
1542
1543	return (vertexArray == mVertexArrayMap.end()) ? NULL : vertexArray->second;
1544}
1545
1546VertexArray *Context::getCurrentVertexArray() const
1547{
1548	return getVertexArray(mState.vertexArray);
1549}
1550
1551bool Context::hasZeroDivisor() const
1552{
1553	// Verify there is at least one active attribute with a divisor of zero
1554	es2::Program *programObject = getCurrentProgram();
1555	for(int attributeIndex = 0; attributeIndex < MAX_VERTEX_ATTRIBS; attributeIndex++)
1556	{
1557		bool active = (programObject->getAttributeStream(attributeIndex) != -1);
1558		if(active && getCurrentVertexArray()->getVertexAttribute(attributeIndex).mDivisor == 0)
1559		{
1560			return true;
1561		}
1562	}
1563
1564	return false;
1565}
1566
1567TransformFeedback *Context::getTransformFeedback(GLuint transformFeedback) const
1568{
1569	TransformFeedbackMap::const_iterator transformFeedbackObject = mTransformFeedbackMap.find(transformFeedback);
1570
1571	return (transformFeedbackObject == mTransformFeedbackMap.end()) ? NULL : transformFeedbackObject->second;
1572}
1573
1574Sampler *Context::getSampler(GLuint sampler) const
1575{
1576	return mResourceManager->getSampler(sampler);
1577}
1578
1579bool Context::isSampler(GLuint sampler) const
1580{
1581	return mResourceManager->isSampler(sampler);
1582}
1583
1584Buffer *Context::getArrayBuffer() const
1585{
1586    return mState.arrayBuffer;
1587}
1588
1589Buffer *Context::getElementArrayBuffer() const
1590{
1591	return getCurrentVertexArray()->getElementArrayBuffer();
1592}
1593
1594Buffer *Context::getCopyReadBuffer() const
1595{
1596	return mState.copyReadBuffer;
1597}
1598
1599Buffer *Context::getCopyWriteBuffer() const
1600{
1601	return mState.copyWriteBuffer;
1602}
1603
1604Buffer *Context::getPixelPackBuffer() const
1605{
1606	return mState.pixelPackBuffer;
1607}
1608
1609Buffer *Context::getPixelUnpackBuffer() const
1610{
1611	return mState.pixelUnpackBuffer;
1612}
1613
1614Buffer *Context::getGenericUniformBuffer() const
1615{
1616	return mState.genericUniformBuffer;
1617}
1618
1619bool Context::getBuffer(GLenum target, es2::Buffer **buffer) const
1620{
1621	switch(target)
1622	{
1623	case GL_ARRAY_BUFFER:
1624		*buffer = getArrayBuffer();
1625		break;
1626	case GL_ELEMENT_ARRAY_BUFFER:
1627		*buffer = getElementArrayBuffer();
1628		break;
1629	case GL_COPY_READ_BUFFER:
1630		if(clientVersion >= 3)
1631		{
1632			*buffer = getCopyReadBuffer();
1633			break;
1634		}
1635		else return false;
1636	case GL_COPY_WRITE_BUFFER:
1637		if(clientVersion >= 3)
1638		{
1639			*buffer = getCopyWriteBuffer();
1640			break;
1641		}
1642		else return false;
1643	case GL_PIXEL_PACK_BUFFER:
1644		if(clientVersion >= 3)
1645		{
1646			*buffer = getPixelPackBuffer();
1647			break;
1648		}
1649		else return false;
1650	case GL_PIXEL_UNPACK_BUFFER:
1651		if(clientVersion >= 3)
1652		{
1653			*buffer = getPixelUnpackBuffer();
1654			break;
1655		}
1656		else return false;
1657	case GL_TRANSFORM_FEEDBACK_BUFFER:
1658		if(clientVersion >= 3)
1659		{
1660			TransformFeedback* transformFeedback = getTransformFeedback();
1661			*buffer = transformFeedback ? static_cast<es2::Buffer*>(transformFeedback->getGenericBuffer()) : nullptr;
1662			break;
1663		}
1664		else return false;
1665	case GL_UNIFORM_BUFFER:
1666		if(clientVersion >= 3)
1667		{
1668			*buffer = getGenericUniformBuffer();
1669			break;
1670		}
1671		else return false;
1672	default:
1673		return false;
1674	}
1675	return true;
1676}
1677
1678TransformFeedback *Context::getTransformFeedback() const
1679{
1680	return getTransformFeedback(mState.transformFeedback);
1681}
1682
1683Program *Context::getCurrentProgram() const
1684{
1685    return mResourceManager->getProgram(mState.currentProgram);
1686}
1687
1688Texture2D *Context::getTexture2D() const
1689{
1690	return static_cast<Texture2D*>(getSamplerTexture(mState.activeSampler, TEXTURE_2D));
1691}
1692
1693Texture3D *Context::getTexture3D() const
1694{
1695	return static_cast<Texture3D*>(getSamplerTexture(mState.activeSampler, TEXTURE_3D));
1696}
1697
1698Texture2DArray *Context::getTexture2DArray() const
1699{
1700	return static_cast<Texture2DArray*>(getSamplerTexture(mState.activeSampler, TEXTURE_2D_ARRAY));
1701}
1702
1703TextureCubeMap *Context::getTextureCubeMap() const
1704{
1705    return static_cast<TextureCubeMap*>(getSamplerTexture(mState.activeSampler, TEXTURE_CUBE));
1706}
1707
1708TextureExternal *Context::getTextureExternal() const
1709{
1710    return static_cast<TextureExternal*>(getSamplerTexture(mState.activeSampler, TEXTURE_EXTERNAL));
1711}
1712
1713Texture *Context::getSamplerTexture(unsigned int sampler, TextureType type) const
1714{
1715    GLuint texid = mState.samplerTexture[type][sampler].name();
1716
1717    if(texid == 0)   // Special case: 0 refers to different initial textures based on the target
1718    {
1719        switch (type)
1720        {
1721        case TEXTURE_2D: return mTexture2DZero;
1722		case TEXTURE_3D: return mTexture3DZero;
1723		case TEXTURE_2D_ARRAY: return mTexture2DArrayZero;
1724        case TEXTURE_CUBE: return mTextureCubeMapZero;
1725        case TEXTURE_EXTERNAL: return mTextureExternalZero;
1726        default: UNREACHABLE(type);
1727        }
1728    }
1729
1730    return mState.samplerTexture[type][sampler];
1731}
1732
1733void Context::samplerParameteri(GLuint sampler, GLenum pname, GLint param)
1734{
1735	mResourceManager->checkSamplerAllocation(sampler);
1736
1737	Sampler *samplerObject = getSampler(sampler);
1738	ASSERT(samplerObject);
1739
1740	switch(pname)
1741	{
1742	case GL_TEXTURE_MIN_FILTER:    samplerObject->setMinFilter(static_cast<GLenum>(param));       break;
1743	case GL_TEXTURE_MAG_FILTER:    samplerObject->setMagFilter(static_cast<GLenum>(param));       break;
1744	case GL_TEXTURE_WRAP_S:        samplerObject->setWrapS(static_cast<GLenum>(param));           break;
1745	case GL_TEXTURE_WRAP_T:        samplerObject->setWrapT(static_cast<GLenum>(param));           break;
1746	case GL_TEXTURE_WRAP_R:        samplerObject->setWrapR(static_cast<GLenum>(param));           break;
1747	case GL_TEXTURE_MIN_LOD:       samplerObject->setMinLod(static_cast<GLfloat>(param));         break;
1748	case GL_TEXTURE_MAX_LOD:       samplerObject->setMaxLod(static_cast<GLfloat>(param));         break;
1749	case GL_TEXTURE_COMPARE_MODE:  samplerObject->setComparisonMode(static_cast<GLenum>(param));  break;
1750	case GL_TEXTURE_COMPARE_FUNC:  samplerObject->setComparisonFunc(static_cast<GLenum>(param));  break;
1751	default:                       UNREACHABLE(pname); break;
1752	}
1753}
1754
1755void Context::samplerParameterf(GLuint sampler, GLenum pname, GLfloat param)
1756{
1757	mResourceManager->checkSamplerAllocation(sampler);
1758
1759	Sampler *samplerObject = getSampler(sampler);
1760	ASSERT(samplerObject);
1761
1762	switch(pname)
1763	{
1764	case GL_TEXTURE_MIN_FILTER:    samplerObject->setMinFilter(static_cast<GLenum>(roundf(param)));       break;
1765	case GL_TEXTURE_MAG_FILTER:    samplerObject->setMagFilter(static_cast<GLenum>(roundf(param)));       break;
1766	case GL_TEXTURE_WRAP_S:        samplerObject->setWrapS(static_cast<GLenum>(roundf(param)));           break;
1767	case GL_TEXTURE_WRAP_T:        samplerObject->setWrapT(static_cast<GLenum>(roundf(param)));           break;
1768	case GL_TEXTURE_WRAP_R:        samplerObject->setWrapR(static_cast<GLenum>(roundf(param)));           break;
1769	case GL_TEXTURE_MIN_LOD:       samplerObject->setMinLod(param);                                       break;
1770	case GL_TEXTURE_MAX_LOD:       samplerObject->setMaxLod(param);                                       break;
1771	case GL_TEXTURE_COMPARE_MODE:  samplerObject->setComparisonMode(static_cast<GLenum>(roundf(param)));  break;
1772	case GL_TEXTURE_COMPARE_FUNC:  samplerObject->setComparisonFunc(static_cast<GLenum>(roundf(param)));  break;
1773	default:                       UNREACHABLE(pname); break;
1774	}
1775}
1776
1777GLint Context::getSamplerParameteri(GLuint sampler, GLenum pname)
1778{
1779	mResourceManager->checkSamplerAllocation(sampler);
1780
1781	Sampler *samplerObject = getSampler(sampler);
1782	ASSERT(samplerObject);
1783
1784	switch(pname)
1785	{
1786	case GL_TEXTURE_MIN_FILTER:    return static_cast<GLint>(samplerObject->getMinFilter());
1787	case GL_TEXTURE_MAG_FILTER:    return static_cast<GLint>(samplerObject->getMagFilter());
1788	case GL_TEXTURE_WRAP_S:        return static_cast<GLint>(samplerObject->getWrapS());
1789	case GL_TEXTURE_WRAP_T:        return static_cast<GLint>(samplerObject->getWrapT());
1790	case GL_TEXTURE_WRAP_R:        return static_cast<GLint>(samplerObject->getWrapR());
1791	case GL_TEXTURE_MIN_LOD:       return static_cast<GLint>(roundf(samplerObject->getMinLod()));
1792	case GL_TEXTURE_MAX_LOD:       return static_cast<GLint>(roundf(samplerObject->getMaxLod()));
1793	case GL_TEXTURE_COMPARE_MODE:  return static_cast<GLint>(samplerObject->getComparisonMode());
1794	case GL_TEXTURE_COMPARE_FUNC:  return static_cast<GLint>(samplerObject->getComparisonFunc());
1795	default:                       UNREACHABLE(pname); return 0;
1796	}
1797}
1798
1799GLfloat Context::getSamplerParameterf(GLuint sampler, GLenum pname)
1800{
1801	mResourceManager->checkSamplerAllocation(sampler);
1802
1803	Sampler *samplerObject = getSampler(sampler);
1804	ASSERT(samplerObject);
1805
1806	switch(pname)
1807	{
1808	case GL_TEXTURE_MIN_FILTER:    return static_cast<GLfloat>(samplerObject->getMinFilter());
1809	case GL_TEXTURE_MAG_FILTER:    return static_cast<GLfloat>(samplerObject->getMagFilter());
1810	case GL_TEXTURE_WRAP_S:        return static_cast<GLfloat>(samplerObject->getWrapS());
1811	case GL_TEXTURE_WRAP_T:        return static_cast<GLfloat>(samplerObject->getWrapT());
1812	case GL_TEXTURE_WRAP_R:        return static_cast<GLfloat>(samplerObject->getWrapR());
1813	case GL_TEXTURE_MIN_LOD:       return samplerObject->getMinLod();
1814	case GL_TEXTURE_MAX_LOD:       return samplerObject->getMaxLod();
1815	case GL_TEXTURE_COMPARE_MODE:  return static_cast<GLfloat>(samplerObject->getComparisonMode());
1816	case GL_TEXTURE_COMPARE_FUNC:  return static_cast<GLfloat>(samplerObject->getComparisonFunc());
1817	default:                       UNREACHABLE(pname); return 0;
1818	}
1819}
1820
1821bool Context::getBooleanv(GLenum pname, GLboolean *params) const
1822{
1823    switch(pname)
1824    {
1825    case GL_SHADER_COMPILER:          *params = GL_TRUE;                          break;
1826    case GL_SAMPLE_COVERAGE_INVERT:   *params = mState.sampleCoverageInvert;      break;
1827    case GL_DEPTH_WRITEMASK:          *params = mState.depthMask;                 break;
1828    case GL_COLOR_WRITEMASK:
1829        params[0] = mState.colorMaskRed;
1830        params[1] = mState.colorMaskGreen;
1831        params[2] = mState.colorMaskBlue;
1832        params[3] = mState.colorMaskAlpha;
1833        break;
1834    case GL_CULL_FACE:                *params = mState.cullFaceEnabled;                  break;
1835    case GL_POLYGON_OFFSET_FILL:      *params = mState.polygonOffsetFillEnabled;         break;
1836    case GL_SAMPLE_ALPHA_TO_COVERAGE: *params = mState.sampleAlphaToCoverageEnabled;     break;
1837    case GL_SAMPLE_COVERAGE:          *params = mState.sampleCoverageEnabled;            break;
1838    case GL_SCISSOR_TEST:             *params = mState.scissorTestEnabled;               break;
1839    case GL_STENCIL_TEST:             *params = mState.stencilTestEnabled;               break;
1840    case GL_DEPTH_TEST:               *params = mState.depthTestEnabled;                 break;
1841    case GL_BLEND:                    *params = mState.blendEnabled;                     break;
1842    case GL_DITHER:                   *params = mState.ditherEnabled;                    break;
1843    case GL_PRIMITIVE_RESTART_FIXED_INDEX: *params = mState.primitiveRestartFixedIndexEnabled; break;
1844    case GL_RASTERIZER_DISCARD:       *params = mState.rasterizerDiscardEnabled;         break;
1845	case GL_TRANSFORM_FEEDBACK_ACTIVE:
1846		{
1847			TransformFeedback* transformFeedback = getTransformFeedback(mState.transformFeedback);
1848			if(transformFeedback)
1849			{
1850				*params = transformFeedback->isActive();
1851				break;
1852			}
1853			else return false;
1854		}
1855     case GL_TRANSFORM_FEEDBACK_PAUSED:
1856		{
1857			TransformFeedback* transformFeedback = getTransformFeedback(mState.transformFeedback);
1858			if(transformFeedback)
1859			{
1860				*params = transformFeedback->isPaused();
1861				break;
1862			}
1863			else return false;
1864		}
1865    default:
1866        return false;
1867    }
1868
1869    return true;
1870}
1871
1872bool Context::getFloatv(GLenum pname, GLfloat *params) const
1873{
1874    // Please note: DEPTH_CLEAR_VALUE is included in our internal getFloatv implementation
1875    // because it is stored as a float, despite the fact that the GL ES 2.0 spec names
1876    // GetIntegerv as its native query function. As it would require conversion in any
1877    // case, this should make no difference to the calling application.
1878    switch(pname)
1879    {
1880    case GL_LINE_WIDTH:               *params = mState.lineWidth;            break;
1881    case GL_SAMPLE_COVERAGE_VALUE:    *params = mState.sampleCoverageValue;  break;
1882    case GL_DEPTH_CLEAR_VALUE:        *params = mState.depthClearValue;      break;
1883    case GL_POLYGON_OFFSET_FACTOR:    *params = mState.polygonOffsetFactor;  break;
1884    case GL_POLYGON_OFFSET_UNITS:     *params = mState.polygonOffsetUnits;   break;
1885    case GL_ALIASED_LINE_WIDTH_RANGE:
1886        params[0] = ALIASED_LINE_WIDTH_RANGE_MIN;
1887        params[1] = ALIASED_LINE_WIDTH_RANGE_MAX;
1888        break;
1889    case GL_ALIASED_POINT_SIZE_RANGE:
1890        params[0] = ALIASED_POINT_SIZE_RANGE_MIN;
1891        params[1] = ALIASED_POINT_SIZE_RANGE_MAX;
1892        break;
1893    case GL_DEPTH_RANGE:
1894        params[0] = mState.zNear;
1895        params[1] = mState.zFar;
1896        break;
1897    case GL_COLOR_CLEAR_VALUE:
1898        params[0] = mState.colorClearValue.red;
1899        params[1] = mState.colorClearValue.green;
1900        params[2] = mState.colorClearValue.blue;
1901        params[3] = mState.colorClearValue.alpha;
1902        break;
1903    case GL_BLEND_COLOR:
1904        params[0] = mState.blendColor.red;
1905        params[1] = mState.blendColor.green;
1906        params[2] = mState.blendColor.blue;
1907        params[3] = mState.blendColor.alpha;
1908        break;
1909	case GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT:
1910        *params = MAX_TEXTURE_MAX_ANISOTROPY;
1911		break;
1912    default:
1913        return false;
1914    }
1915
1916    return true;
1917}
1918
1919template bool Context::getIntegerv<GLint>(GLenum pname, GLint *params) const;
1920template bool Context::getIntegerv<GLint64>(GLenum pname, GLint64 *params) const;
1921
1922template<typename T> bool Context::getIntegerv(GLenum pname, T *params) const
1923{
1924    // Please note: DEPTH_CLEAR_VALUE is not included in our internal getIntegerv implementation
1925    // because it is stored as a float, despite the fact that the GL ES 2.0 spec names
1926    // GetIntegerv as its native query function. As it would require conversion in any
1927    // case, this should make no difference to the calling application. You may find it in
1928    // Context::getFloatv.
1929    switch(pname)
1930    {
1931    case GL_MAX_VERTEX_ATTRIBS:               *params = MAX_VERTEX_ATTRIBS;               break;
1932    case GL_MAX_VERTEX_UNIFORM_VECTORS:       *params = MAX_VERTEX_UNIFORM_VECTORS;       break;
1933    case GL_MAX_VARYING_VECTORS:              *params = MAX_VARYING_VECTORS;              break;
1934    case GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS: *params = MAX_COMBINED_TEXTURE_IMAGE_UNITS; break;
1935    case GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS:   *params = MAX_VERTEX_TEXTURE_IMAGE_UNITS;   break;
1936    case GL_MAX_TEXTURE_IMAGE_UNITS:          *params = MAX_TEXTURE_IMAGE_UNITS;          break;
1937	case GL_MAX_FRAGMENT_UNIFORM_VECTORS:     *params = MAX_FRAGMENT_UNIFORM_VECTORS;     break;
1938	case GL_MAX_RENDERBUFFER_SIZE:            *params = IMPLEMENTATION_MAX_RENDERBUFFER_SIZE; break;
1939    case GL_NUM_SHADER_BINARY_FORMATS:        *params = 0;                                    break;
1940    case GL_SHADER_BINARY_FORMATS:      /* no shader binary formats are supported */          break;
1941    case GL_ARRAY_BUFFER_BINDING:             *params = getArrayBufferName();                 break;
1942    case GL_ELEMENT_ARRAY_BUFFER_BINDING:     *params = getElementArrayBufferName();          break;
1943//	case GL_FRAMEBUFFER_BINDING:            // now equivalent to GL_DRAW_FRAMEBUFFER_BINDING_ANGLE
1944    case GL_DRAW_FRAMEBUFFER_BINDING_ANGLE:   *params = mState.drawFramebuffer;               break;
1945    case GL_READ_FRAMEBUFFER_BINDING_ANGLE:   *params = mState.readFramebuffer;               break;
1946    case GL_RENDERBUFFER_BINDING:             *params = mState.renderbuffer.name();           break;
1947    case GL_CURRENT_PROGRAM:                  *params = mState.currentProgram;                break;
1948    case GL_PACK_ALIGNMENT:                   *params = mState.packAlignment;                 break;
1949    case GL_UNPACK_ALIGNMENT:                 *params = mState.unpackInfo.alignment;          break;
1950    case GL_GENERATE_MIPMAP_HINT:             *params = mState.generateMipmapHint;            break;
1951    case GL_FRAGMENT_SHADER_DERIVATIVE_HINT_OES: *params = mState.fragmentShaderDerivativeHint; break;
1952    case GL_ACTIVE_TEXTURE:                   *params = (mState.activeSampler + GL_TEXTURE0); break;
1953    case GL_STENCIL_FUNC:                     *params = mState.stencilFunc;                   break;
1954    case GL_STENCIL_REF:                      *params = mState.stencilRef;                    break;
1955    case GL_STENCIL_VALUE_MASK:               *params = mState.stencilMask;                   break;
1956    case GL_STENCIL_BACK_FUNC:                *params = mState.stencilBackFunc;               break;
1957    case GL_STENCIL_BACK_REF:                 *params = mState.stencilBackRef;                break;
1958    case GL_STENCIL_BACK_VALUE_MASK:          *params = mState.stencilBackMask;               break;
1959    case GL_STENCIL_FAIL:                     *params = mState.stencilFail;                   break;
1960    case GL_STENCIL_PASS_DEPTH_FAIL:          *params = mState.stencilPassDepthFail;          break;
1961    case GL_STENCIL_PASS_DEPTH_PASS:          *params = mState.stencilPassDepthPass;          break;
1962    case GL_STENCIL_BACK_FAIL:                *params = mState.stencilBackFail;               break;
1963    case GL_STENCIL_BACK_PASS_DEPTH_FAIL:     *params = mState.stencilBackPassDepthFail;      break;
1964    case GL_STENCIL_BACK_PASS_DEPTH_PASS:     *params = mState.stencilBackPassDepthPass;      break;
1965    case GL_DEPTH_FUNC:                       *params = mState.depthFunc;                     break;
1966    case GL_BLEND_SRC_RGB:                    *params = mState.sourceBlendRGB;                break;
1967    case GL_BLEND_SRC_ALPHA:                  *params = mState.sourceBlendAlpha;              break;
1968    case GL_BLEND_DST_RGB:                    *params = mState.destBlendRGB;                  break;
1969    case GL_BLEND_DST_ALPHA:                  *params = mState.destBlendAlpha;                break;
1970    case GL_BLEND_EQUATION_RGB:               *params = mState.blendEquationRGB;              break;
1971    case GL_BLEND_EQUATION_ALPHA:             *params = mState.blendEquationAlpha;            break;
1972    case GL_STENCIL_WRITEMASK:                *params = mState.stencilWritemask;              break;
1973    case GL_STENCIL_BACK_WRITEMASK:           *params = mState.stencilBackWritemask;          break;
1974    case GL_STENCIL_CLEAR_VALUE:              *params = mState.stencilClearValue;             break;
1975    case GL_SUBPIXEL_BITS:                    *params = 4;                                    break;
1976	case GL_MAX_TEXTURE_SIZE:                 *params = IMPLEMENTATION_MAX_TEXTURE_SIZE;          break;
1977	case GL_MAX_CUBE_MAP_TEXTURE_SIZE:        *params = IMPLEMENTATION_MAX_CUBE_MAP_TEXTURE_SIZE; break;
1978    case GL_NUM_COMPRESSED_TEXTURE_FORMATS:   *params = NUM_COMPRESSED_TEXTURE_FORMATS;           break;
1979	case GL_MAX_SAMPLES_ANGLE:                *params = IMPLEMENTATION_MAX_SAMPLES;               break;
1980    case GL_SAMPLE_BUFFERS:
1981    case GL_SAMPLES:
1982        {
1983            Framebuffer *framebuffer = getDrawFramebuffer();
1984			int width, height, samples;
1985
1986            if(framebuffer->completeness(width, height, samples) == GL_FRAMEBUFFER_COMPLETE)
1987            {
1988                switch(pname)
1989                {
1990                case GL_SAMPLE_BUFFERS:
1991                    if(samples > 1)
1992                    {
1993                        *params = 1;
1994                    }
1995                    else
1996                    {
1997                        *params = 0;
1998                    }
1999                    break;
2000                case GL_SAMPLES:
2001                    *params = samples;
2002                    break;
2003                }
2004            }
2005            else
2006            {
2007                *params = 0;
2008            }
2009        }
2010        break;
2011    case GL_IMPLEMENTATION_COLOR_READ_TYPE:
2012		{
2013			Framebuffer *framebuffer = getReadFramebuffer();
2014			*params = framebuffer->getImplementationColorReadType();
2015		}
2016		break;
2017    case GL_IMPLEMENTATION_COLOR_READ_FORMAT:
2018		{
2019			Framebuffer *framebuffer = getReadFramebuffer();
2020			*params = framebuffer->getImplementationColorReadFormat();
2021		}
2022		break;
2023    case GL_MAX_VIEWPORT_DIMS:
2024        {
2025			int maxDimension = IMPLEMENTATION_MAX_RENDERBUFFER_SIZE;
2026            params[0] = maxDimension;
2027            params[1] = maxDimension;
2028        }
2029        break;
2030    case GL_COMPRESSED_TEXTURE_FORMATS:
2031        {
2032			for(int i = 0; i < NUM_COMPRESSED_TEXTURE_FORMATS; i++)
2033            {
2034                params[i] = compressedTextureFormats[i];
2035            }
2036        }
2037        break;
2038    case GL_VIEWPORT:
2039        params[0] = mState.viewportX;
2040        params[1] = mState.viewportY;
2041        params[2] = mState.viewportWidth;
2042        params[3] = mState.viewportHeight;
2043        break;
2044    case GL_SCISSOR_BOX:
2045        params[0] = mState.scissorX;
2046        params[1] = mState.scissorY;
2047        params[2] = mState.scissorWidth;
2048        params[3] = mState.scissorHeight;
2049        break;
2050    case GL_CULL_FACE_MODE:                   *params = mState.cullMode;                 break;
2051    case GL_FRONT_FACE:                       *params = mState.frontFace;                break;
2052    case GL_RED_BITS:
2053    case GL_GREEN_BITS:
2054    case GL_BLUE_BITS:
2055    case GL_ALPHA_BITS:
2056        {
2057            Framebuffer *framebuffer = getDrawFramebuffer();
2058            Renderbuffer *colorbuffer = framebuffer->getColorbuffer(0);
2059
2060            if(colorbuffer)
2061            {
2062                switch (pname)
2063                {
2064                  case GL_RED_BITS:   *params = colorbuffer->getRedSize();   break;
2065                  case GL_GREEN_BITS: *params = colorbuffer->getGreenSize(); break;
2066                  case GL_BLUE_BITS:  *params = colorbuffer->getBlueSize();  break;
2067                  case GL_ALPHA_BITS: *params = colorbuffer->getAlphaSize(); break;
2068                }
2069            }
2070            else
2071            {
2072                *params = 0;
2073            }
2074        }
2075        break;
2076    case GL_DEPTH_BITS:
2077        {
2078            Framebuffer *framebuffer = getDrawFramebuffer();
2079            Renderbuffer *depthbuffer = framebuffer->getDepthbuffer();
2080
2081            if(depthbuffer)
2082            {
2083                *params = depthbuffer->getDepthSize();
2084            }
2085            else
2086            {
2087                *params = 0;
2088            }
2089        }
2090        break;
2091    case GL_STENCIL_BITS:
2092        {
2093            Framebuffer *framebuffer = getDrawFramebuffer();
2094            Renderbuffer *stencilbuffer = framebuffer->getStencilbuffer();
2095
2096            if(stencilbuffer)
2097            {
2098                *params = stencilbuffer->getStencilSize();
2099            }
2100            else
2101            {
2102                *params = 0;
2103            }
2104        }
2105        break;
2106    case GL_TEXTURE_BINDING_2D:
2107        {
2108            if(mState.activeSampler > MAX_COMBINED_TEXTURE_IMAGE_UNITS - 1)
2109            {
2110                error(GL_INVALID_OPERATION);
2111                return false;
2112            }
2113
2114            *params = mState.samplerTexture[TEXTURE_2D][mState.activeSampler].name();
2115        }
2116        break;
2117    case GL_TEXTURE_BINDING_CUBE_MAP:
2118        {
2119            if(mState.activeSampler > MAX_COMBINED_TEXTURE_IMAGE_UNITS - 1)
2120            {
2121                error(GL_INVALID_OPERATION);
2122                return false;
2123            }
2124
2125            *params = mState.samplerTexture[TEXTURE_CUBE][mState.activeSampler].name();
2126        }
2127        break;
2128    case GL_TEXTURE_BINDING_EXTERNAL_OES:
2129        {
2130            if(mState.activeSampler > MAX_COMBINED_TEXTURE_IMAGE_UNITS - 1)
2131            {
2132                error(GL_INVALID_OPERATION);
2133                return false;
2134            }
2135
2136            *params = mState.samplerTexture[TEXTURE_EXTERNAL][mState.activeSampler].name();
2137        }
2138        break;
2139	case GL_TEXTURE_BINDING_3D_OES:
2140	case GL_TEXTURE_BINDING_2D_ARRAY: // GLES 3.0
2141	    {
2142			if(mState.activeSampler > MAX_COMBINED_TEXTURE_IMAGE_UNITS - 1)
2143			{
2144				error(GL_INVALID_OPERATION);
2145				return false;
2146			}
2147
2148			*params = mState.samplerTexture[TEXTURE_3D][mState.activeSampler].name();
2149		}
2150		break;
2151	case GL_COPY_READ_BUFFER_BINDING: // name, initially 0
2152		if(clientVersion >= 3)
2153		{
2154			*params = mState.copyReadBuffer.name();
2155		}
2156		else
2157		{
2158			return false;
2159		}
2160		break;
2161	case GL_COPY_WRITE_BUFFER_BINDING: // name, initially 0
2162		if(clientVersion >= 3)
2163		{
2164			*params = mState.copyWriteBuffer.name();
2165		}
2166		else
2167		{
2168			return false;
2169		}
2170		break;
2171	case GL_DRAW_BUFFER0: // symbolic constant, initial value is GL_BACK​
2172		UNIMPLEMENTED();
2173		*params = GL_BACK;
2174		break;
2175	case GL_DRAW_BUFFER1: // symbolic constant, initial value is GL_NONE
2176	case GL_DRAW_BUFFER2:
2177	case GL_DRAW_BUFFER3:
2178	case GL_DRAW_BUFFER4:
2179	case GL_DRAW_BUFFER5:
2180	case GL_DRAW_BUFFER6:
2181	case GL_DRAW_BUFFER7:
2182	case GL_DRAW_BUFFER8:
2183	case GL_DRAW_BUFFER9:
2184	case GL_DRAW_BUFFER10:
2185	case GL_DRAW_BUFFER11:
2186	case GL_DRAW_BUFFER12:
2187	case GL_DRAW_BUFFER13:
2188	case GL_DRAW_BUFFER14:
2189	case GL_DRAW_BUFFER15:
2190		UNIMPLEMENTED();
2191		*params = GL_NONE;
2192		break;
2193	case GL_MAJOR_VERSION: // integer, at least 3
2194		UNIMPLEMENTED();
2195		*params = 3;
2196		break;
2197	case GL_MAX_3D_TEXTURE_SIZE: // GLint, at least 2048
2198		*params = IMPLEMENTATION_MAX_TEXTURE_SIZE;
2199		break;
2200	case GL_MAX_ARRAY_TEXTURE_LAYERS: // GLint, at least 2048
2201		*params = IMPLEMENTATION_MAX_TEXTURE_SIZE;
2202		break;
2203	case GL_MAX_COLOR_ATTACHMENTS: // integer, at least 8
2204		UNIMPLEMENTED();
2205		*params = IMPLEMENTATION_MAX_COLOR_ATTACHMENTS;
2206		break;
2207	case GL_MAX_COMBINED_FRAGMENT_UNIFORM_COMPONENTS: // integer, at least 50048
2208		UNIMPLEMENTED();
2209		*params = MAX_COMBINED_FRAGMENT_UNIFORM_COMPONENTS;
2210		break;
2211	case GL_MAX_COMBINED_UNIFORM_BLOCKS: // integer, at least 70
2212		UNIMPLEMENTED();
2213		*params = 70;
2214		break;
2215	case GL_MAX_COMBINED_VERTEX_UNIFORM_COMPONENTS: // integer, at least 50176
2216		UNIMPLEMENTED();
2217		*params = MAX_COMBINED_VERTEX_UNIFORM_COMPONENTS;
2218		break;
2219	case GL_MAX_DRAW_BUFFERS: // integer, at least 8
2220		UNIMPLEMENTED();
2221		*params = IMPLEMENTATION_MAX_DRAW_BUFFERS;
2222		break;
2223	case GL_MAX_ELEMENT_INDEX:
2224		*params = MAX_ELEMENT_INDEX;
2225		break;
2226	case GL_MAX_ELEMENTS_INDICES:
2227		*params = MAX_ELEMENTS_INDICES;
2228		break;
2229	case GL_MAX_ELEMENTS_VERTICES:
2230		*params = MAX_ELEMENTS_VERTICES;
2231		break;
2232	case GL_MAX_FRAGMENT_INPUT_COMPONENTS: // integer, at least 128
2233		UNIMPLEMENTED();
2234		*params = 128;
2235		break;
2236	case GL_MAX_FRAGMENT_UNIFORM_BLOCKS: // integer, at least 12
2237		UNIMPLEMENTED();
2238		*params = 12;
2239		break;
2240	case GL_MAX_FRAGMENT_UNIFORM_COMPONENTS: // integer, at least 1024
2241		UNIMPLEMENTED();
2242		*params = 1024;
2243		break;
2244	case GL_MAX_PROGRAM_TEXEL_OFFSET: // integer, minimum is 7
2245		UNIMPLEMENTED();
2246		*params = 7;
2247		break;
2248	case GL_MAX_SERVER_WAIT_TIMEOUT: // integer
2249		UNIMPLEMENTED();
2250		*params = 0;
2251		break;
2252	case GL_MAX_TEXTURE_LOD_BIAS: // integer,  at least 2.0
2253		UNIMPLEMENTED();
2254		*params = 2;
2255		break;
2256	case GL_MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS: // integer, at least 64
2257		UNIMPLEMENTED();
2258		*params = 64;
2259		break;
2260	case GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS: // integer, at least 4
2261		UNIMPLEMENTED();
2262		*params = IMPLEMENTATION_MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS;
2263		break;
2264	case GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS: // integer, at least 4
2265		UNIMPLEMENTED();
2266		*params = 4;
2267		break;
2268	case GL_MAX_UNIFORM_BLOCK_SIZE: // integer, at least 16384
2269		UNIMPLEMENTED();
2270		*params = 16384;
2271		break;
2272	case GL_MAX_UNIFORM_BUFFER_BINDINGS: // integer, at least 36
2273		*params = IMPLEMENTATION_MAX_UNIFORM_BUFFER_BINDINGS;
2274		break;
2275	case GL_MAX_VARYING_COMPONENTS: // integer, at least 60
2276		UNIMPLEMENTED();
2277		*params = 60;
2278		break;
2279	case GL_MAX_VERTEX_OUTPUT_COMPONENTS: // integer,  at least 64
2280		UNIMPLEMENTED();
2281		*params = 64;
2282		break;
2283	case GL_MAX_VERTEX_UNIFORM_BLOCKS: // integer,  at least 12
2284		UNIMPLEMENTED();
2285		*params = 12;
2286		break;
2287	case GL_MAX_VERTEX_UNIFORM_COMPONENTS: // integer,  at least 1024
2288		UNIMPLEMENTED();
2289		*params = 1024;
2290		break;
2291	case GL_MIN_PROGRAM_TEXEL_OFFSET: // integer, maximum is -8
2292		UNIMPLEMENTED();
2293		*params = -8;
2294		break;
2295	case GL_MINOR_VERSION: // integer
2296		UNIMPLEMENTED();
2297		*params = 0;
2298		break;
2299	case GL_NUM_EXTENSIONS: // integer
2300		GLuint numExtensions;
2301		getExtensions(0, &numExtensions);
2302		*params = numExtensions;
2303		break;
2304	case GL_NUM_PROGRAM_BINARY_FORMATS: // integer, at least 0
2305		UNIMPLEMENTED();
2306		*params = 0;
2307		break;
2308	case GL_PACK_ROW_LENGTH: // integer, initially 0
2309		*params = mState.packRowLength;
2310		break;
2311	case GL_PACK_SKIP_PIXELS: // integer, initially 0
2312		*params = mState.packSkipPixels;
2313		break;
2314	case GL_PACK_SKIP_ROWS: // integer, initially 0
2315		*params = mState.packSkipRows;
2316		break;
2317	case GL_PIXEL_PACK_BUFFER_BINDING: // integer, initially 0
2318		if(clientVersion >= 3)
2319		{
2320			*params = mState.pixelPackBuffer.name();
2321		}
2322		else
2323		{
2324			return false;
2325		}
2326		break;
2327	case GL_PIXEL_UNPACK_BUFFER_BINDING: // integer, initially 0
2328		if(clientVersion >= 3)
2329		{
2330			*params = mState.pixelUnpackBuffer.name();
2331		}
2332		else
2333		{
2334			return false;
2335		}
2336		break;
2337	case GL_PROGRAM_BINARY_FORMATS: // integer[GL_NUM_PROGRAM_BINARY_FORMATS​]
2338		UNIMPLEMENTED();
2339		*params = 0;
2340		break;
2341	case GL_READ_BUFFER: // symbolic constant,  initial value is GL_BACK​
2342		UNIMPLEMENTED();
2343		*params = GL_BACK;
2344		break;
2345	case GL_SAMPLER_BINDING: // GLint, default 0
2346		UNIMPLEMENTED();
2347		*params = 0;
2348		break;
2349	case GL_UNIFORM_BUFFER_BINDING: // name, initially 0
2350		if(clientVersion >= 3)
2351		{
2352			*params = mState.genericUniformBuffer.name();
2353		}
2354		else
2355		{
2356			return false;
2357		}
2358		break;
2359	case GL_UNIFORM_BUFFER_OFFSET_ALIGNMENT: // integer, defaults to 1
2360		*params = IMPLEMENTATION_UNIFORM_BUFFER_OFFSET_ALIGNMENT;
2361		break;
2362	case GL_UNIFORM_BUFFER_SIZE: // indexed[n] 64-bit integer, initially 0
2363		if(clientVersion >= 3)
2364		{
2365			*params = mState.genericUniformBuffer->size();
2366		}
2367		else
2368		{
2369			return false;
2370		}
2371		break;
2372	case GL_UNIFORM_BUFFER_START: // indexed[n] 64-bit integer, initially 0
2373		if(clientVersion >= 3)
2374		{
2375			*params = mState.genericUniformBuffer->offset();
2376		}
2377		else
2378		{
2379			return false;
2380		}
2381		*params = 0;
2382		break;
2383	case GL_UNPACK_IMAGE_HEIGHT: // integer, initially 0
2384		*params = mState.unpackInfo.imageHeight;
2385		break;
2386	case GL_UNPACK_ROW_LENGTH: // integer, initially 0
2387		*params = mState.unpackInfo.rowLength;
2388		break;
2389	case GL_UNPACK_SKIP_IMAGES: // integer, initially 0
2390		*params = mState.unpackInfo.skipImages;
2391		break;
2392	case GL_UNPACK_SKIP_PIXELS: // integer, initially 0
2393		*params = mState.unpackInfo.skipPixels;
2394		break;
2395	case GL_UNPACK_SKIP_ROWS: // integer, initially 0
2396		*params = mState.unpackInfo.skipRows;
2397		break;
2398	case GL_VERTEX_ARRAY_BINDING: // GLint, initially 0
2399		*params = getCurrentVertexArray()->name;
2400		break;
2401	default:
2402        return false;
2403    }
2404
2405    return true;
2406}
2407
2408template bool Context::getTransformFeedbackiv<GLint>(GLuint xfb, GLenum pname, GLint *param) const;
2409template bool Context::getTransformFeedbackiv<GLint64>(GLuint xfb, GLenum pname, GLint64 *param) const;
2410
2411template<typename T> bool Context::getTransformFeedbackiv(GLuint xfb, GLenum pname, T *param) const
2412{
2413	UNIMPLEMENTED();
2414
2415	TransformFeedback* transformFeedback = getTransformFeedback(mState.transformFeedback);
2416	if(!transformFeedback)
2417	{
2418		return false;
2419	}
2420
2421	switch(pname)
2422	{
2423	case GL_TRANSFORM_FEEDBACK_BINDING: // GLint, initially 0
2424		*param = 0;
2425		break;
2426	case GL_TRANSFORM_FEEDBACK_ACTIVE: // boolean, initially GL_FALSE
2427		*param = transformFeedback->isActive();
2428		break;
2429	case GL_TRANSFORM_FEEDBACK_BUFFER_BINDING: // name, initially 0
2430		*param = transformFeedback->name;
2431		break;
2432	case GL_TRANSFORM_FEEDBACK_PAUSED: // boolean, initially GL_FALSE
2433		*param = transformFeedback->isPaused();
2434		break;
2435	case GL_TRANSFORM_FEEDBACK_BUFFER_SIZE: // indexed[n] 64-bit integer, initially 0
2436		if(transformFeedback->getGenericBuffer())
2437		{
2438			*param = transformFeedback->getGenericBuffer()->size();
2439			break;
2440		}
2441		else return false;
2442	case GL_TRANSFORM_FEEDBACK_BUFFER_START: // indexed[n] 64-bit integer, initially 0
2443		*param = 0;
2444		break;
2445	default:
2446		return false;
2447	}
2448
2449	return true;
2450}
2451
2452bool Context::getQueryParameterInfo(GLenum pname, GLenum *type, unsigned int *numParams) const
2453{
2454    // Please note: the query type returned for DEPTH_CLEAR_VALUE in this implementation
2455    // is FLOAT rather than INT, as would be suggested by the GL ES 2.0 spec. This is due
2456    // to the fact that it is stored internally as a float, and so would require conversion
2457    // if returned from Context::getIntegerv. Since this conversion is already implemented
2458    // in the case that one calls glGetIntegerv to retrieve a float-typed state variable, we
2459    // place DEPTH_CLEAR_VALUE with the floats. This should make no difference to the calling
2460    // application.
2461    switch(pname)
2462    {
2463    case GL_COMPRESSED_TEXTURE_FORMATS:
2464		{
2465            *type = GL_INT;
2466			*numParams = NUM_COMPRESSED_TEXTURE_FORMATS;
2467        }
2468		break;
2469    case GL_SHADER_BINARY_FORMATS:
2470        {
2471            *type = GL_INT;
2472            *numParams = 0;
2473        }
2474        break;
2475    case GL_MAX_VERTEX_ATTRIBS:
2476    case GL_MAX_VERTEX_UNIFORM_VECTORS:
2477    case GL_MAX_VARYING_VECTORS:
2478    case GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS:
2479    case GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS:
2480    case GL_MAX_TEXTURE_IMAGE_UNITS:
2481    case GL_MAX_FRAGMENT_UNIFORM_VECTORS:
2482    case GL_MAX_RENDERBUFFER_SIZE:
2483    case GL_NUM_SHADER_BINARY_FORMATS:
2484    case GL_NUM_COMPRESSED_TEXTURE_FORMATS:
2485    case GL_ARRAY_BUFFER_BINDING:
2486    case GL_FRAMEBUFFER_BINDING: // Same as GL_DRAW_FRAMEBUFFER_BINDING_ANGLE
2487    case GL_READ_FRAMEBUFFER_BINDING_ANGLE:
2488    case GL_RENDERBUFFER_BINDING:
2489    case GL_CURRENT_PROGRAM:
2490    case GL_PACK_ALIGNMENT:
2491    case GL_UNPACK_ALIGNMENT:
2492    case GL_GENERATE_MIPMAP_HINT:
2493    case GL_FRAGMENT_SHADER_DERIVATIVE_HINT_OES:
2494    case GL_RED_BITS:
2495    case GL_GREEN_BITS:
2496    case GL_BLUE_BITS:
2497    case GL_ALPHA_BITS:
2498    case GL_DEPTH_BITS:
2499    case GL_STENCIL_BITS:
2500    case GL_ELEMENT_ARRAY_BUFFER_BINDING:
2501    case GL_CULL_FACE_MODE:
2502    case GL_FRONT_FACE:
2503    case GL_ACTIVE_TEXTURE:
2504    case GL_STENCIL_FUNC:
2505    case GL_STENCIL_VALUE_MASK:
2506    case GL_STENCIL_REF:
2507    case GL_STENCIL_FAIL:
2508    case GL_STENCIL_PASS_DEPTH_FAIL:
2509    case GL_STENCIL_PASS_DEPTH_PASS:
2510    case GL_STENCIL_BACK_FUNC:
2511    case GL_STENCIL_BACK_VALUE_MASK:
2512    case GL_STENCIL_BACK_REF:
2513    case GL_STENCIL_BACK_FAIL:
2514    case GL_STENCIL_BACK_PASS_DEPTH_FAIL:
2515    case GL_STENCIL_BACK_PASS_DEPTH_PASS:
2516    case GL_DEPTH_FUNC:
2517    case GL_BLEND_SRC_RGB:
2518    case GL_BLEND_SRC_ALPHA:
2519    case GL_BLEND_DST_RGB:
2520    case GL_BLEND_DST_ALPHA:
2521    case GL_BLEND_EQUATION_RGB:
2522    case GL_BLEND_EQUATION_ALPHA:
2523    case GL_STENCIL_WRITEMASK:
2524    case GL_STENCIL_BACK_WRITEMASK:
2525    case GL_STENCIL_CLEAR_VALUE:
2526    case GL_SUBPIXEL_BITS:
2527    case GL_MAX_TEXTURE_SIZE:
2528    case GL_MAX_CUBE_MAP_TEXTURE_SIZE:
2529    case GL_SAMPLE_BUFFERS:
2530    case GL_SAMPLES:
2531    case GL_IMPLEMENTATION_COLOR_READ_TYPE:
2532    case GL_IMPLEMENTATION_COLOR_READ_FORMAT:
2533    case GL_TEXTURE_BINDING_2D:
2534    case GL_TEXTURE_BINDING_CUBE_MAP:
2535    case GL_TEXTURE_BINDING_EXTERNAL_OES:
2536    case GL_TEXTURE_BINDING_3D_OES:
2537    case GL_COPY_READ_BUFFER_BINDING:
2538    case GL_COPY_WRITE_BUFFER_BINDING:
2539    case GL_DRAW_BUFFER0:
2540    case GL_DRAW_BUFFER1:
2541    case GL_DRAW_BUFFER2:
2542    case GL_DRAW_BUFFER3:
2543    case GL_DRAW_BUFFER4:
2544    case GL_DRAW_BUFFER5:
2545    case GL_DRAW_BUFFER6:
2546    case GL_DRAW_BUFFER7:
2547    case GL_DRAW_BUFFER8:
2548    case GL_DRAW_BUFFER9:
2549    case GL_DRAW_BUFFER10:
2550    case GL_DRAW_BUFFER11:
2551    case GL_DRAW_BUFFER12:
2552    case GL_DRAW_BUFFER13:
2553    case GL_DRAW_BUFFER14:
2554    case GL_DRAW_BUFFER15:
2555    case GL_MAJOR_VERSION:
2556    case GL_MAX_3D_TEXTURE_SIZE:
2557    case GL_MAX_ARRAY_TEXTURE_LAYERS:
2558    case GL_MAX_COLOR_ATTACHMENTS:
2559    case GL_MAX_COMBINED_FRAGMENT_UNIFORM_COMPONENTS:
2560    case GL_MAX_COMBINED_UNIFORM_BLOCKS:
2561    case GL_MAX_COMBINED_VERTEX_UNIFORM_COMPONENTS:
2562    case GL_MAX_DRAW_BUFFERS:
2563    case GL_MAX_ELEMENT_INDEX:
2564    case GL_MAX_ELEMENTS_INDICES:
2565    case GL_MAX_ELEMENTS_VERTICES:
2566    case GL_MAX_FRAGMENT_INPUT_COMPONENTS:
2567    case GL_MAX_FRAGMENT_UNIFORM_BLOCKS:
2568    case GL_MAX_FRAGMENT_UNIFORM_COMPONENTS:
2569    case GL_MAX_PROGRAM_TEXEL_OFFSET:
2570    case GL_MAX_SERVER_WAIT_TIMEOUT:
2571    case GL_MAX_TEXTURE_LOD_BIAS:
2572    case GL_MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS:
2573    case GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS:
2574    case GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS:
2575    case GL_MAX_UNIFORM_BLOCK_SIZE:
2576    case GL_MAX_UNIFORM_BUFFER_BINDINGS:
2577    case GL_MAX_VARYING_COMPONENTS:
2578    case GL_MAX_VERTEX_OUTPUT_COMPONENTS:
2579    case GL_MAX_VERTEX_UNIFORM_BLOCKS:
2580    case GL_MAX_VERTEX_UNIFORM_COMPONENTS:
2581    case GL_MIN_PROGRAM_TEXEL_OFFSET:
2582    case GL_MINOR_VERSION:
2583    case GL_NUM_EXTENSIONS:
2584    case GL_NUM_PROGRAM_BINARY_FORMATS:
2585    case GL_PACK_ROW_LENGTH:
2586    case GL_PACK_SKIP_PIXELS:
2587    case GL_PACK_SKIP_ROWS:
2588    case GL_PIXEL_PACK_BUFFER_BINDING:
2589    case GL_PIXEL_UNPACK_BUFFER_BINDING:
2590    case GL_PROGRAM_BINARY_FORMATS:
2591    case GL_READ_BUFFER:
2592    case GL_SAMPLER_BINDING:
2593    case GL_TEXTURE_BINDING_2D_ARRAY:
2594    case GL_UNIFORM_BUFFER_BINDING:
2595    case GL_UNIFORM_BUFFER_OFFSET_ALIGNMENT:
2596    case GL_UNIFORM_BUFFER_SIZE:
2597    case GL_UNIFORM_BUFFER_START:
2598    case GL_UNPACK_IMAGE_HEIGHT:
2599    case GL_UNPACK_ROW_LENGTH:
2600    case GL_UNPACK_SKIP_IMAGES:
2601    case GL_UNPACK_SKIP_PIXELS:
2602    case GL_UNPACK_SKIP_ROWS:
2603    case GL_VERTEX_ARRAY_BINDING:
2604        {
2605            *type = GL_INT;
2606            *numParams = 1;
2607        }
2608        break;
2609    case GL_MAX_SAMPLES_ANGLE:
2610        {
2611            *type = GL_INT;
2612            *numParams = 1;
2613        }
2614        break;
2615    case GL_MAX_VIEWPORT_DIMS:
2616        {
2617            *type = GL_INT;
2618            *numParams = 2;
2619        }
2620        break;
2621    case GL_VIEWPORT:
2622    case GL_SCISSOR_BOX:
2623        {
2624            *type = GL_INT;
2625            *numParams = 4;
2626        }
2627        break;
2628    case GL_SHADER_COMPILER:
2629    case GL_SAMPLE_COVERAGE_INVERT:
2630    case GL_DEPTH_WRITEMASK:
2631    case GL_CULL_FACE:                // CULL_FACE through DITHER are natural to IsEnabled,
2632    case GL_POLYGON_OFFSET_FILL:      // but can be retrieved through the Get{Type}v queries.
2633    case GL_SAMPLE_ALPHA_TO_COVERAGE: // For this purpose, they are treated here as bool-natural
2634    case GL_SAMPLE_COVERAGE:
2635    case GL_SCISSOR_TEST:
2636    case GL_STENCIL_TEST:
2637    case GL_DEPTH_TEST:
2638    case GL_BLEND:
2639    case GL_DITHER:
2640    case GL_PRIMITIVE_RESTART_FIXED_INDEX:
2641    case GL_RASTERIZER_DISCARD:
2642    case GL_TRANSFORM_FEEDBACK_ACTIVE:
2643    case GL_TRANSFORM_FEEDBACK_PAUSED:
2644        {
2645            *type = GL_BOOL;
2646            *numParams = 1;
2647        }
2648        break;
2649    case GL_COLOR_WRITEMASK:
2650        {
2651            *type = GL_BOOL;
2652            *numParams = 4;
2653        }
2654        break;
2655    case GL_POLYGON_OFFSET_FACTOR:
2656    case GL_POLYGON_OFFSET_UNITS:
2657    case GL_SAMPLE_COVERAGE_VALUE:
2658    case GL_DEPTH_CLEAR_VALUE:
2659    case GL_LINE_WIDTH:
2660        {
2661            *type = GL_FLOAT;
2662            *numParams = 1;
2663        }
2664        break;
2665    case GL_ALIASED_LINE_WIDTH_RANGE:
2666    case GL_ALIASED_POINT_SIZE_RANGE:
2667    case GL_DEPTH_RANGE:
2668        {
2669            *type = GL_FLOAT;
2670            *numParams = 2;
2671        }
2672        break;
2673    case GL_COLOR_CLEAR_VALUE:
2674    case GL_BLEND_COLOR:
2675        {
2676            *type = GL_FLOAT;
2677            *numParams = 4;
2678        }
2679        break;
2680	case GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT:
2681        *type = GL_FLOAT;
2682        *numParams = 1;
2683        break;
2684    default:
2685        return false;
2686    }
2687
2688    return true;
2689}
2690
2691void Context::applyScissor(int width, int height)
2692{
2693	if(mState.scissorTestEnabled)
2694	{
2695		sw::Rect scissor = { mState.scissorX, mState.scissorY, mState.scissorX + mState.scissorWidth, mState.scissorY + mState.scissorHeight };
2696		scissor.clip(0, 0, width, height);
2697
2698		device->setScissorRect(scissor);
2699		device->setScissorEnable(true);
2700	}
2701	else
2702	{
2703		device->setScissorEnable(false);
2704	}
2705}
2706
2707egl::Image *Context::getScissoredImage(GLint drawbuffer, int &x0, int &y0, int &width, int &height, bool depthStencil)
2708{
2709	Framebuffer* framebuffer = getDrawFramebuffer();
2710	egl::Image* image = depthStencil ? framebuffer->getDepthStencil() : framebuffer->getRenderTarget(drawbuffer);
2711
2712	applyScissor(image->getWidth(), image->getHeight());
2713
2714	device->getScissoredRegion(image, x0, y0, width, height);
2715
2716	return image;
2717}
2718
2719// Applies the render target surface, depth stencil surface, viewport rectangle and scissor rectangle
2720bool Context::applyRenderTarget()
2721{
2722    Framebuffer *framebuffer = getDrawFramebuffer();
2723	int width, height, samples;
2724
2725    if(!framebuffer || framebuffer->completeness(width, height, samples) != GL_FRAMEBUFFER_COMPLETE)
2726    {
2727        return error(GL_INVALID_FRAMEBUFFER_OPERATION, false);
2728    }
2729
2730	for(int i = 0; i < MAX_DRAW_BUFFERS; ++i)
2731	{
2732		egl::Image *renderTarget = framebuffer->getRenderTarget(i);
2733		device->setRenderTarget(i, renderTarget);
2734		if(renderTarget) renderTarget->release();
2735	}
2736
2737    egl::Image *depthStencil = framebuffer->getDepthStencil();
2738    device->setDepthStencilSurface(depthStencil);
2739	if(depthStencil) depthStencil->release();
2740
2741    Viewport viewport;
2742    float zNear = clamp01(mState.zNear);
2743    float zFar = clamp01(mState.zFar);
2744
2745    viewport.x0 = mState.viewportX;
2746    viewport.y0 = mState.viewportY;
2747    viewport.width = mState.viewportWidth;
2748    viewport.height = mState.viewportHeight;
2749    viewport.minZ = zNear;
2750    viewport.maxZ = zFar;
2751
2752    device->setViewport(viewport);
2753
2754	applyScissor(width, height);
2755
2756	Program *program = getCurrentProgram();
2757
2758	if(program)
2759	{
2760		GLfloat nearFarDiff[3] = {zNear, zFar, zFar - zNear};
2761        program->setUniform1fv(program->getUniformLocation("gl_DepthRange.near"), 1, &nearFarDiff[0]);
2762		program->setUniform1fv(program->getUniformLocation("gl_DepthRange.far"), 1, &nearFarDiff[1]);
2763		program->setUniform1fv(program->getUniformLocation("gl_DepthRange.diff"), 1, &nearFarDiff[2]);
2764    }
2765
2766    return true;
2767}
2768
2769// Applies the fixed-function state (culling, depth test, alpha blending, stenciling, etc)
2770void Context::applyState(GLenum drawMode)
2771{
2772    Framebuffer *framebuffer = getDrawFramebuffer();
2773
2774    if(mState.cullFaceEnabled)
2775    {
2776        device->setCullMode(es2sw::ConvertCullMode(mState.cullMode, mState.frontFace));
2777    }
2778    else
2779    {
2780		device->setCullMode(sw::CULL_NONE);
2781    }
2782
2783    if(mDepthStateDirty)
2784    {
2785        if(mState.depthTestEnabled)
2786        {
2787			device->setDepthBufferEnable(true);
2788			device->setDepthCompare(es2sw::ConvertDepthComparison(mState.depthFunc));
2789        }
2790        else
2791        {
2792            device->setDepthBufferEnable(false);
2793        }
2794
2795        mDepthStateDirty = false;
2796    }
2797
2798    if(mBlendStateDirty)
2799    {
2800        if(mState.blendEnabled)
2801        {
2802			device->setAlphaBlendEnable(true);
2803			device->setSeparateAlphaBlendEnable(true);
2804
2805            device->setBlendConstant(es2sw::ConvertColor(mState.blendColor));
2806
2807			device->setSourceBlendFactor(es2sw::ConvertBlendFunc(mState.sourceBlendRGB));
2808			device->setDestBlendFactor(es2sw::ConvertBlendFunc(mState.destBlendRGB));
2809			device->setBlendOperation(es2sw::ConvertBlendOp(mState.blendEquationRGB));
2810
2811            device->setSourceBlendFactorAlpha(es2sw::ConvertBlendFunc(mState.sourceBlendAlpha));
2812			device->setDestBlendFactorAlpha(es2sw::ConvertBlendFunc(mState.destBlendAlpha));
2813			device->setBlendOperationAlpha(es2sw::ConvertBlendOp(mState.blendEquationAlpha));
2814        }
2815        else
2816        {
2817			device->setAlphaBlendEnable(false);
2818        }
2819
2820        mBlendStateDirty = false;
2821    }
2822
2823    if(mStencilStateDirty || mFrontFaceDirty)
2824    {
2825        if(mState.stencilTestEnabled && framebuffer->hasStencil())
2826        {
2827			device->setStencilEnable(true);
2828			device->setTwoSidedStencil(true);
2829
2830            // get the maximum size of the stencil ref
2831            Renderbuffer *stencilbuffer = framebuffer->getStencilbuffer();
2832            GLuint maxStencil = (1 << stencilbuffer->getStencilSize()) - 1;
2833
2834			if(mState.frontFace == GL_CCW)
2835			{
2836				device->setStencilWriteMask(mState.stencilWritemask);
2837				device->setStencilCompare(es2sw::ConvertStencilComparison(mState.stencilFunc));
2838
2839				device->setStencilReference((mState.stencilRef < (GLint)maxStencil) ? mState.stencilRef : maxStencil);
2840				device->setStencilMask(mState.stencilMask);
2841
2842				device->setStencilFailOperation(es2sw::ConvertStencilOp(mState.stencilFail));
2843				device->setStencilZFailOperation(es2sw::ConvertStencilOp(mState.stencilPassDepthFail));
2844				device->setStencilPassOperation(es2sw::ConvertStencilOp(mState.stencilPassDepthPass));
2845
2846				device->setStencilWriteMaskCCW(mState.stencilBackWritemask);
2847				device->setStencilCompareCCW(es2sw::ConvertStencilComparison(mState.stencilBackFunc));
2848
2849				device->setStencilReferenceCCW((mState.stencilBackRef < (GLint)maxStencil) ? mState.stencilBackRef : maxStencil);
2850				device->setStencilMaskCCW(mState.stencilBackMask);
2851
2852				device->setStencilFailOperationCCW(es2sw::ConvertStencilOp(mState.stencilBackFail));
2853				device->setStencilZFailOperationCCW(es2sw::ConvertStencilOp(mState.stencilBackPassDepthFail));
2854				device->setStencilPassOperationCCW(es2sw::ConvertStencilOp(mState.stencilBackPassDepthPass));
2855			}
2856			else
2857			{
2858				device->setStencilWriteMaskCCW(mState.stencilWritemask);
2859				device->setStencilCompareCCW(es2sw::ConvertStencilComparison(mState.stencilFunc));
2860
2861				device->setStencilReferenceCCW((mState.stencilRef < (GLint)maxStencil) ? mState.stencilRef : maxStencil);
2862				device->setStencilMaskCCW(mState.stencilMask);
2863
2864				device->setStencilFailOperationCCW(es2sw::ConvertStencilOp(mState.stencilFail));
2865				device->setStencilZFailOperationCCW(es2sw::ConvertStencilOp(mState.stencilPassDepthFail));
2866				device->setStencilPassOperationCCW(es2sw::ConvertStencilOp(mState.stencilPassDepthPass));
2867
2868				device->setStencilWriteMask(mState.stencilBackWritemask);
2869				device->setStencilCompare(es2sw::ConvertStencilComparison(mState.stencilBackFunc));
2870
2871				device->setStencilReference((mState.stencilBackRef < (GLint)maxStencil) ? mState.stencilBackRef : maxStencil);
2872				device->setStencilMask(mState.stencilBackMask);
2873
2874				device->setStencilFailOperation(es2sw::ConvertStencilOp(mState.stencilBackFail));
2875				device->setStencilZFailOperation(es2sw::ConvertStencilOp(mState.stencilBackPassDepthFail));
2876				device->setStencilPassOperation(es2sw::ConvertStencilOp(mState.stencilBackPassDepthPass));
2877			}
2878        }
2879        else
2880        {
2881			device->setStencilEnable(false);
2882        }
2883
2884        mStencilStateDirty = false;
2885        mFrontFaceDirty = false;
2886    }
2887
2888    if(mMaskStateDirty)
2889    {
2890		device->setColorWriteMask(0, es2sw::ConvertColorMask(mState.colorMaskRed, mState.colorMaskGreen, mState.colorMaskBlue, mState.colorMaskAlpha));
2891		device->setDepthWriteEnable(mState.depthMask);
2892
2893        mMaskStateDirty = false;
2894    }
2895
2896    if(mPolygonOffsetStateDirty)
2897    {
2898        if(mState.polygonOffsetFillEnabled)
2899        {
2900            Renderbuffer *depthbuffer = framebuffer->getDepthbuffer();
2901            if(depthbuffer)
2902            {
2903				device->setSlopeDepthBias(mState.polygonOffsetFactor);
2904                float depthBias = ldexp(mState.polygonOffsetUnits, -(int)(depthbuffer->getDepthSize()));
2905				device->setDepthBias(depthBias);
2906            }
2907        }
2908        else
2909        {
2910            device->setSlopeDepthBias(0);
2911            device->setDepthBias(0);
2912        }
2913
2914        mPolygonOffsetStateDirty = false;
2915    }
2916
2917    if(mSampleStateDirty)
2918    {
2919        if(mState.sampleAlphaToCoverageEnabled)
2920        {
2921            device->setTransparencyAntialiasing(sw::TRANSPARENCY_ALPHA_TO_COVERAGE);
2922        }
2923		else
2924		{
2925			device->setTransparencyAntialiasing(sw::TRANSPARENCY_NONE);
2926		}
2927
2928        if(mState.sampleCoverageEnabled)
2929        {
2930            unsigned int mask = 0;
2931            if(mState.sampleCoverageValue != 0)
2932            {
2933				int width, height, samples;
2934				framebuffer->completeness(width, height, samples);
2935
2936                float threshold = 0.5f;
2937
2938                for(int i = 0; i < samples; i++)
2939                {
2940                    mask <<= 1;
2941
2942                    if((i + 1) * mState.sampleCoverageValue >= threshold)
2943                    {
2944                        threshold += 1.0f;
2945                        mask |= 1;
2946                    }
2947                }
2948            }
2949
2950            if(mState.sampleCoverageInvert)
2951            {
2952                mask = ~mask;
2953            }
2954
2955			device->setMultiSampleMask(mask);
2956        }
2957        else
2958        {
2959			device->setMultiSampleMask(0xFFFFFFFF);
2960        }
2961
2962        mSampleStateDirty = false;
2963    }
2964
2965    if(mDitherStateDirty)
2966    {
2967    //	UNIMPLEMENTED();   // FIXME
2968
2969        mDitherStateDirty = false;
2970    }
2971}
2972
2973GLenum Context::applyVertexBuffer(GLint base, GLint first, GLsizei count, GLsizei instanceId)
2974{
2975    TranslatedAttribute attributes[MAX_VERTEX_ATTRIBS];
2976
2977    GLenum err = mVertexDataManager->prepareVertexData(first, count, attributes, instanceId);
2978    if(err != GL_NO_ERROR)
2979    {
2980        return err;
2981    }
2982
2983	Program *program = getCurrentProgram();
2984
2985	device->resetInputStreams(false);
2986
2987    for(int i = 0; i < MAX_VERTEX_ATTRIBS; i++)
2988	{
2989		if(program->getAttributeStream(i) == -1)
2990		{
2991			continue;
2992		}
2993
2994		sw::Resource *resource = attributes[i].vertexBuffer;
2995		const void *buffer = (char*)resource->data() + attributes[i].offset;
2996
2997		int stride = attributes[i].stride;
2998
2999		buffer = (char*)buffer + stride * base;
3000
3001		sw::Stream attribute(resource, buffer, stride);
3002
3003		attribute.type = attributes[i].type;
3004		attribute.count = attributes[i].count;
3005		attribute.normalized = attributes[i].normalized;
3006
3007		int stream = program->getAttributeStream(i);
3008		device->setInputStream(stream, attribute);
3009	}
3010
3011	return GL_NO_ERROR;
3012}
3013
3014// Applies the indices and element array bindings
3015GLenum Context::applyIndexBuffer(const void *indices, GLuint start, GLuint end, GLsizei count, GLenum mode, GLenum type, TranslatedIndexData *indexInfo)
3016{
3017	GLenum err = mIndexDataManager->prepareIndexData(type, start, end, count, getCurrentVertexArray()->getElementArrayBuffer(), indices, indexInfo);
3018
3019    if(err == GL_NO_ERROR)
3020    {
3021        device->setIndexBuffer(indexInfo->indexBuffer);
3022    }
3023
3024    return err;
3025}
3026
3027// Applies the shaders and shader constants
3028void Context::applyShaders()
3029{
3030    Program *programObject = getCurrentProgram();
3031    sw::VertexShader *vertexShader = programObject->getVertexShader();
3032	sw::PixelShader *pixelShader = programObject->getPixelShader();
3033
3034    device->setVertexShader(vertexShader);
3035    device->setPixelShader(pixelShader);
3036
3037    if(programObject->getSerial() != mAppliedProgramSerial)
3038    {
3039        programObject->dirtyAllUniforms();
3040        mAppliedProgramSerial = programObject->getSerial();
3041    }
3042
3043    programObject->applyUniforms();
3044    programObject->applyUniformBuffers();
3045}
3046
3047void Context::applyTextures()
3048{
3049    applyTextures(sw::SAMPLER_PIXEL);
3050	applyTextures(sw::SAMPLER_VERTEX);
3051}
3052
3053void Context::applyTextures(sw::SamplerType samplerType)
3054{
3055    Program *programObject = getCurrentProgram();
3056
3057    int samplerCount = (samplerType == sw::SAMPLER_PIXEL) ? MAX_TEXTURE_IMAGE_UNITS : MAX_VERTEX_TEXTURE_IMAGE_UNITS;   // Range of samplers of given sampler type
3058
3059    for(int samplerIndex = 0; samplerIndex < samplerCount; samplerIndex++)
3060    {
3061        int textureUnit = programObject->getSamplerMapping(samplerType, samplerIndex);   // OpenGL texture image unit index
3062
3063        if(textureUnit != -1)
3064        {
3065            TextureType textureType = programObject->getSamplerTextureType(samplerType, samplerIndex);
3066
3067            Texture *texture = getSamplerTexture(textureUnit, textureType);
3068
3069			if(texture->isSamplerComplete())
3070            {
3071				GLenum wrapS, wrapT, wrapR, minFilter, magFilter;
3072
3073				Sampler *samplerObject = mState.sampler[textureUnit];
3074				if(samplerObject)
3075				{
3076					wrapS = samplerObject->getWrapS();
3077					wrapT = samplerObject->getWrapT();
3078					wrapR = samplerObject->getWrapR();
3079					minFilter = samplerObject->getMinFilter();
3080					magFilter = samplerObject->getMagFilter();
3081				}
3082				else
3083				{
3084					wrapS = texture->getWrapS();
3085					wrapT = texture->getWrapT();
3086					wrapR = texture->getWrapR();
3087					minFilter = texture->getMinFilter();
3088					magFilter = texture->getMagFilter();
3089				}
3090				GLfloat maxAnisotropy = texture->getMaxAnisotropy();
3091
3092				GLenum swizzleR = texture->getSwizzleR();
3093				GLenum swizzleG = texture->getSwizzleG();
3094				GLenum swizzleB = texture->getSwizzleB();
3095				GLenum swizzleA = texture->getSwizzleA();
3096
3097				device->setAddressingModeU(samplerType, samplerIndex, es2sw::ConvertTextureWrap(wrapS));
3098				device->setAddressingModeV(samplerType, samplerIndex, es2sw::ConvertTextureWrap(wrapT));
3099				device->setAddressingModeW(samplerType, samplerIndex, es2sw::ConvertTextureWrap(wrapR));
3100				device->setSwizzleR(samplerType, samplerIndex, es2sw::ConvertSwizzleType(swizzleR));
3101				device->setSwizzleG(samplerType, samplerIndex, es2sw::ConvertSwizzleType(swizzleG));
3102				device->setSwizzleB(samplerType, samplerIndex, es2sw::ConvertSwizzleType(swizzleB));
3103				device->setSwizzleA(samplerType, samplerIndex, es2sw::ConvertSwizzleType(swizzleA));
3104
3105				device->setTextureFilter(samplerType, samplerIndex, es2sw::ConvertTextureFilter(minFilter, magFilter, maxAnisotropy));
3106				device->setMipmapFilter(samplerType, samplerIndex, es2sw::ConvertMipMapFilter(minFilter));
3107				device->setMaxAnisotropy(samplerType, samplerIndex, maxAnisotropy);
3108
3109				applyTexture(samplerType, samplerIndex, texture);
3110            }
3111            else
3112            {
3113                applyTexture(samplerType, samplerIndex, nullptr);
3114            }
3115        }
3116        else
3117        {
3118            applyTexture(samplerType, samplerIndex, nullptr);
3119        }
3120    }
3121}
3122
3123void Context::applyTexture(sw::SamplerType type, int index, Texture *baseTexture)
3124{
3125	Program *program = getCurrentProgram();
3126	int sampler = (type == sw::SAMPLER_PIXEL) ? index : 16 + index;
3127	bool textureUsed = false;
3128
3129	if(type == sw::SAMPLER_PIXEL)
3130	{
3131		textureUsed = program->getPixelShader()->usesSampler(index);
3132	}
3133	else if(type == sw::SAMPLER_VERTEX)
3134	{
3135		textureUsed = program->getVertexShader()->usesSampler(index);
3136	}
3137	else UNREACHABLE(type);
3138
3139	sw::Resource *resource = 0;
3140
3141	if(baseTexture && textureUsed)
3142	{
3143		resource = baseTexture->getResource();
3144	}
3145
3146	device->setTextureResource(sampler, resource);
3147
3148	if(baseTexture && textureUsed)
3149	{
3150		int levelCount = baseTexture->getLevelCount();
3151
3152		if(baseTexture->getTarget() == GL_TEXTURE_2D || baseTexture->getTarget() == GL_TEXTURE_EXTERNAL_OES)
3153		{
3154			Texture2D *texture = static_cast<Texture2D*>(baseTexture);
3155
3156			for(int mipmapLevel = 0; mipmapLevel < MIPMAP_LEVELS; mipmapLevel++)
3157			{
3158				int surfaceLevel = mipmapLevel;
3159
3160				if(surfaceLevel < 0)
3161				{
3162					surfaceLevel = 0;
3163				}
3164				else if(surfaceLevel >= levelCount)
3165				{
3166					surfaceLevel = levelCount - 1;
3167				}
3168
3169				egl::Image *surface = texture->getImage(surfaceLevel);
3170				device->setTextureLevel(sampler, 0, mipmapLevel, surface, sw::TEXTURE_2D);
3171			}
3172		}
3173		else if(baseTexture->getTarget() == GL_TEXTURE_3D_OES)
3174		{
3175			Texture3D *texture = static_cast<Texture3D*>(baseTexture);
3176
3177			for(int mipmapLevel = 0; mipmapLevel < MIPMAP_LEVELS; mipmapLevel++)
3178			{
3179				int surfaceLevel = mipmapLevel;
3180
3181				if(surfaceLevel < 0)
3182				{
3183					surfaceLevel = 0;
3184				}
3185				else if(surfaceLevel >= levelCount)
3186				{
3187					surfaceLevel = levelCount - 1;
3188				}
3189
3190				egl::Image *surface = texture->getImage(surfaceLevel);
3191				device->setTextureLevel(sampler, 0, mipmapLevel, surface, sw::TEXTURE_3D);
3192			}
3193		}
3194		else if(baseTexture->getTarget() == GL_TEXTURE_2D_ARRAY)
3195		{
3196			Texture2DArray *texture = static_cast<Texture2DArray*>(baseTexture);
3197
3198			for(int mipmapLevel = 0; mipmapLevel < MIPMAP_LEVELS; mipmapLevel++)
3199			{
3200				int surfaceLevel = mipmapLevel;
3201
3202				if(surfaceLevel < 0)
3203				{
3204					surfaceLevel = 0;
3205				}
3206				else if(surfaceLevel >= levelCount)
3207				{
3208					surfaceLevel = levelCount - 1;
3209				}
3210
3211				egl::Image *surface = texture->getImage(surfaceLevel);
3212				device->setTextureLevel(sampler, 0, mipmapLevel, surface, sw::TEXTURE_2D_ARRAY);
3213			}
3214		}
3215		else if(baseTexture->getTarget() == GL_TEXTURE_CUBE_MAP)
3216		{
3217			for(int face = 0; face < 6; face++)
3218			{
3219				TextureCubeMap *cubeTexture = static_cast<TextureCubeMap*>(baseTexture);
3220
3221				for(int mipmapLevel = 0; mipmapLevel < MIPMAP_LEVELS; mipmapLevel++)
3222				{
3223					int surfaceLevel = mipmapLevel;
3224
3225					if(surfaceLevel < 0)
3226					{
3227						surfaceLevel = 0;
3228					}
3229					else if(surfaceLevel >= levelCount)
3230					{
3231						surfaceLevel = levelCount - 1;
3232					}
3233
3234					egl::Image *surface = cubeTexture->getImage(face, surfaceLevel);
3235					device->setTextureLevel(sampler, face, mipmapLevel, surface, sw::TEXTURE_CUBE);
3236				}
3237			}
3238		}
3239		else UNIMPLEMENTED();
3240	}
3241	else
3242	{
3243		device->setTextureLevel(sampler, 0, 0, 0, sw::TEXTURE_NULL);
3244	}
3245}
3246
3247void Context::readPixels(GLint x, GLint y, GLsizei width, GLsizei height,
3248                         GLenum format, GLenum type, GLsizei *bufSize, void* pixels)
3249{
3250    Framebuffer *framebuffer = getReadFramebuffer();
3251	int framebufferWidth, framebufferHeight, framebufferSamples;
3252
3253    if(framebuffer->completeness(framebufferWidth, framebufferHeight, framebufferSamples) != GL_FRAMEBUFFER_COMPLETE)
3254    {
3255        return error(GL_INVALID_FRAMEBUFFER_OPERATION);
3256    }
3257
3258    if(getReadFramebufferName() != 0 && framebufferSamples != 0)
3259    {
3260        return error(GL_INVALID_OPERATION);
3261    }
3262
3263	GLenum readFormat = framebuffer->getImplementationColorReadFormat();
3264	GLenum readType = framebuffer->getImplementationColorReadType();
3265
3266	if(!(readFormat == format && readType == type) && !ValidReadPixelsFormatType(readFormat, readType, format, type, clientVersion))
3267	{
3268		return error(GL_INVALID_OPERATION);
3269	}
3270
3271	GLsizei outputPitch = egl::ComputePitch((mState.packRowLength > 0) ? mState.packRowLength : width, format, type, mState.packAlignment);
3272	GLsizei outputHeight = (mState.packImageHeight == 0) ? height : mState.packImageHeight;
3273	pixels = getPixelPackBuffer() ? (unsigned char*)getPixelPackBuffer()->data() + (ptrdiff_t)pixels : (unsigned char*)pixels;
3274	pixels = ((char*)pixels) + (mState.packSkipImages * outputHeight + mState.packSkipRows) * outputPitch + mState.packSkipPixels;
3275
3276	// Sized query sanity check
3277    if(bufSize)
3278    {
3279        int requiredSize = outputPitch * height;
3280        if(requiredSize > *bufSize)
3281        {
3282            return error(GL_INVALID_OPERATION);
3283        }
3284    }
3285
3286    egl::Image *renderTarget = framebuffer->getReadRenderTarget();
3287
3288    if(!renderTarget)
3289    {
3290        return error(GL_OUT_OF_MEMORY);
3291    }
3292
3293	x += mState.packSkipPixels;
3294	y += mState.packSkipRows;
3295	sw::Rect rect = {x, y, x + width, y + height};
3296	sw::Rect dstRect = { 0, 0, width, height };
3297	rect.clip(0, 0, renderTarget->getWidth(), renderTarget->getHeight());
3298
3299	sw::Surface externalSurface(width, height, 1, egl::ConvertFormatType(format, type), pixels, outputPitch, outputPitch * outputHeight);
3300	sw::SliceRect sliceRect(rect);
3301	sw::SliceRect dstSliceRect(dstRect);
3302	device->blit(renderTarget, sliceRect, &externalSurface, dstSliceRect, false);
3303
3304	renderTarget->release();
3305}
3306
3307void Context::clear(GLbitfield mask)
3308{
3309    Framebuffer *framebuffer = getDrawFramebuffer();
3310
3311    if(!framebuffer || framebuffer->completeness() != GL_FRAMEBUFFER_COMPLETE)
3312    {
3313        return error(GL_INVALID_FRAMEBUFFER_OPERATION);
3314    }
3315
3316    if(!applyRenderTarget())
3317    {
3318        return;
3319    }
3320
3321	if(mask & GL_COLOR_BUFFER_BIT)
3322	{
3323		unsigned int rgbaMask = getColorMask();
3324
3325		if(rgbaMask != 0)
3326		{
3327			device->clearColor(mState.colorClearValue.red, mState.colorClearValue.green, mState.colorClearValue.blue, mState.colorClearValue.alpha, rgbaMask);
3328		}
3329	}
3330
3331	if(mask & GL_DEPTH_BUFFER_BIT)
3332	{
3333		if(mState.depthMask != 0)
3334		{
3335			float depth = clamp01(mState.depthClearValue);
3336			device->clearDepth(depth);
3337		}
3338	}
3339
3340	if(mask & GL_STENCIL_BUFFER_BIT)
3341	{
3342		if(mState.stencilWritemask != 0)
3343		{
3344			int stencil = mState.stencilClearValue & 0x000000FF;
3345			device->clearStencil(stencil, mState.stencilWritemask);
3346		}
3347	}
3348}
3349
3350void Context::clearColorBuffer(GLint drawbuffer, void *value, sw::Format format)
3351{
3352	unsigned int rgbaMask = getColorMask();
3353	if(device && rgbaMask)
3354	{
3355		int x0(0), y0(0), width(0), height(0);
3356		egl::Image* image = getScissoredImage(drawbuffer, x0, y0, width, height, false);
3357
3358		sw::SliceRect sliceRect;
3359		if(image->getClearRect(x0, y0, width, height, sliceRect))
3360		{
3361			device->clear(value, format, image, sliceRect, rgbaMask);
3362		}
3363
3364		image->release();
3365	}
3366}
3367
3368void Context::clearColorBuffer(GLint drawbuffer, const GLint *value)
3369{
3370	clearColorBuffer(drawbuffer, (void*)value, sw::FORMAT_A32B32G32R32I);
3371}
3372
3373void Context::clearColorBuffer(GLint drawbuffer, const GLuint *value)
3374{
3375	clearColorBuffer(drawbuffer, (void*)value, sw::FORMAT_A32B32G32R32UI);
3376}
3377
3378void Context::clearColorBuffer(GLint drawbuffer, const GLfloat *value)
3379{
3380	clearColorBuffer(drawbuffer, (void*)value, sw::FORMAT_A32B32G32R32F);
3381}
3382
3383void Context::clearDepthBuffer(GLint drawbuffer, const GLfloat *value)
3384{
3385	if(device && mState.depthMask)
3386	{
3387		int x0(0), y0(0), width(0), height(0);
3388		egl::Image* image = getScissoredImage(drawbuffer, x0, y0, width, height, true);
3389
3390		float depth = clamp01(value[0]);
3391		image->clearDepthBuffer(depth, x0, y0, width, height);
3392
3393		image->release();
3394	}
3395}
3396
3397void Context::clearStencilBuffer(GLint drawbuffer, const GLint *value)
3398{
3399	if(device && mState.stencilWritemask)
3400	{
3401		int x0(0), y0(0), width(0), height(0);
3402		egl::Image* image = getScissoredImage(drawbuffer, x0, y0, width, height, true);
3403
3404		unsigned char stencil = value[0] < 0 ? 0 : static_cast<unsigned char>(value[0] & 0x000000FF);
3405		image->clearStencilBuffer(stencil, static_cast<unsigned char>(mState.stencilWritemask), x0, y0, width, height);
3406
3407		image->release();
3408	}
3409}
3410
3411void Context::clearDepthStencilBuffer(GLint drawbuffer, GLfloat depth, GLint stencil)
3412{
3413	if(device && (mState.depthMask || mState.stencilWritemask))
3414	{
3415		int x0(0), y0(0), width(0), height(0);
3416		egl::Image* image = getScissoredImage(drawbuffer, x0, y0, width, height, true);
3417
3418		if(mState.stencilWritemask)
3419		{
3420			image->clearStencilBuffer(static_cast<unsigned char>(stencil & 0x000000FF), static_cast<unsigned char>(mState.stencilWritemask), x0, y0, width, height);
3421		}
3422
3423		if(mState.depthMask)
3424		{
3425			image->clearDepthBuffer(clamp01(depth), x0, y0, width, height);
3426		}
3427
3428		image->release();
3429	}
3430}
3431
3432void Context::drawArrays(GLenum mode, GLint first, GLsizei count, GLsizei instanceCount)
3433{
3434    if(!mState.currentProgram)
3435    {
3436        return error(GL_INVALID_OPERATION);
3437    }
3438
3439    PrimitiveType primitiveType;
3440    int primitiveCount;
3441
3442    if(!es2sw::ConvertPrimitiveType(mode, count, primitiveType, primitiveCount))
3443        return error(GL_INVALID_ENUM);
3444
3445    if(primitiveCount <= 0)
3446    {
3447        return;
3448    }
3449
3450    if(!applyRenderTarget())
3451    {
3452        return;
3453    }
3454
3455    applyState(mode);
3456
3457	for(int i = 0; i < instanceCount; ++i)
3458	{
3459		device->setInstanceID(i);
3460
3461		GLenum err = applyVertexBuffer(0, first, count, i);
3462		if(err != GL_NO_ERROR)
3463		{
3464			return error(err);
3465		}
3466
3467		applyShaders();
3468		applyTextures();
3469
3470		if(!getCurrentProgram()->validateSamplers(false))
3471		{
3472			return error(GL_INVALID_OPERATION);
3473		}
3474
3475		if(!cullSkipsDraw(mode))
3476		{
3477			device->drawPrimitive(primitiveType, primitiveCount);
3478		}
3479	}
3480}
3481
3482void Context::drawElements(GLenum mode, GLuint start, GLuint end, GLsizei count, GLenum type, const void *indices, GLsizei instanceCount)
3483{
3484    if(!mState.currentProgram)
3485    {
3486        return error(GL_INVALID_OPERATION);
3487    }
3488
3489	if(!indices && !getCurrentVertexArray()->getElementArrayBuffer())
3490    {
3491        return error(GL_INVALID_OPERATION);
3492    }
3493
3494    PrimitiveType primitiveType;
3495    int primitiveCount;
3496
3497    if(!es2sw::ConvertPrimitiveType(mode, count, primitiveType, primitiveCount))
3498        return error(GL_INVALID_ENUM);
3499
3500    if(primitiveCount <= 0)
3501    {
3502        return;
3503    }
3504
3505    if(!applyRenderTarget())
3506    {
3507        return;
3508    }
3509
3510    applyState(mode);
3511
3512	for(int i = 0; i < instanceCount; ++i)
3513	{
3514		device->setInstanceID(i);
3515
3516		TranslatedIndexData indexInfo;
3517		GLenum err = applyIndexBuffer(indices, start, end, count, mode, type, &indexInfo);
3518		if(err != GL_NO_ERROR)
3519		{
3520			return error(err);
3521		}
3522
3523		GLsizei vertexCount = indexInfo.maxIndex - indexInfo.minIndex + 1;
3524		err = applyVertexBuffer(-(int)indexInfo.minIndex, indexInfo.minIndex, vertexCount, i);
3525		if(err != GL_NO_ERROR)
3526		{
3527			return error(err);
3528		}
3529
3530		applyShaders();
3531		applyTextures();
3532
3533		if(!getCurrentProgram()->validateSamplers(false))
3534		{
3535			return error(GL_INVALID_OPERATION);
3536		}
3537
3538		if(!cullSkipsDraw(mode))
3539		{
3540			device->drawIndexedPrimitive(primitiveType, indexInfo.indexOffset, primitiveCount, IndexDataManager::typeSize(type));
3541		}
3542	}
3543}
3544
3545void Context::finish()
3546{
3547	device->finish();
3548}
3549
3550void Context::flush()
3551{
3552    // We don't queue anything without processing it as fast as possible
3553}
3554
3555void Context::recordInvalidEnum()
3556{
3557    mInvalidEnum = true;
3558}
3559
3560void Context::recordInvalidValue()
3561{
3562    mInvalidValue = true;
3563}
3564
3565void Context::recordInvalidOperation()
3566{
3567    mInvalidOperation = true;
3568}
3569
3570void Context::recordOutOfMemory()
3571{
3572    mOutOfMemory = true;
3573}
3574
3575void Context::recordInvalidFramebufferOperation()
3576{
3577    mInvalidFramebufferOperation = true;
3578}
3579
3580// Get one of the recorded errors and clear its flag, if any.
3581// [OpenGL ES 2.0.24] section 2.5 page 13.
3582GLenum Context::getError()
3583{
3584    if(mInvalidEnum)
3585    {
3586        mInvalidEnum = false;
3587
3588        return GL_INVALID_ENUM;
3589    }
3590
3591    if(mInvalidValue)
3592    {
3593        mInvalidValue = false;
3594
3595        return GL_INVALID_VALUE;
3596    }
3597
3598    if(mInvalidOperation)
3599    {
3600        mInvalidOperation = false;
3601
3602        return GL_INVALID_OPERATION;
3603    }
3604
3605    if(mOutOfMemory)
3606    {
3607        mOutOfMemory = false;
3608
3609        return GL_OUT_OF_MEMORY;
3610    }
3611
3612    if(mInvalidFramebufferOperation)
3613    {
3614        mInvalidFramebufferOperation = false;
3615
3616        return GL_INVALID_FRAMEBUFFER_OPERATION;
3617    }
3618
3619    return GL_NO_ERROR;
3620}
3621
3622int Context::getSupportedMultisampleCount(int requested)
3623{
3624	int supported = 0;
3625
3626	for(int i = NUM_MULTISAMPLE_COUNTS - 1; i >= 0; i--)
3627	{
3628		if(supported >= requested)
3629		{
3630			return supported;
3631		}
3632
3633		supported = multisampleCount[i];
3634	}
3635
3636	return supported;
3637}
3638
3639void Context::detachBuffer(GLuint buffer)
3640{
3641    // [OpenGL ES 2.0.24] section 2.9 page 22:
3642    // If a buffer object is deleted while it is bound, all bindings to that object in the current context
3643    // (i.e. in the thread that called Delete-Buffers) are reset to zero.
3644
3645    if(getArrayBufferName() == buffer)
3646    {
3647        mState.arrayBuffer = NULL;
3648    }
3649
3650	for(auto tfIt = mTransformFeedbackMap.begin(); tfIt != mTransformFeedbackMap.end(); tfIt++)
3651	{
3652		tfIt->second->detachBuffer(buffer);
3653	}
3654
3655	for(auto vaoIt = mVertexArrayMap.begin(); vaoIt != mVertexArrayMap.end(); vaoIt++)
3656	{
3657		vaoIt->second->detachBuffer(buffer);
3658	}
3659
3660    for(int attribute = 0; attribute < MAX_VERTEX_ATTRIBS; attribute++)
3661    {
3662        if(mState.vertexAttribute[attribute].mBoundBuffer.name() == buffer)
3663        {
3664            mState.vertexAttribute[attribute].mBoundBuffer = NULL;
3665        }
3666    }
3667}
3668
3669void Context::detachTexture(GLuint texture)
3670{
3671    // [OpenGL ES 2.0.24] section 3.8 page 84:
3672    // If a texture object is deleted, it is as if all texture units which are bound to that texture object are
3673    // rebound to texture object zero
3674
3675    for(int type = 0; type < TEXTURE_TYPE_COUNT; type++)
3676    {
3677        for(int sampler = 0; sampler < MAX_COMBINED_TEXTURE_IMAGE_UNITS; sampler++)
3678        {
3679            if(mState.samplerTexture[type][sampler].name() == texture)
3680            {
3681                mState.samplerTexture[type][sampler] = NULL;
3682            }
3683        }
3684    }
3685
3686    // [OpenGL ES 2.0.24] section 4.4 page 112:
3687    // If a texture object is deleted while its image is attached to the currently bound framebuffer, then it is
3688    // as if FramebufferTexture2D had been called, with a texture of 0, for each attachment point to which this
3689    // image was attached in the currently bound framebuffer.
3690
3691    Framebuffer *readFramebuffer = getReadFramebuffer();
3692    Framebuffer *drawFramebuffer = getDrawFramebuffer();
3693
3694    if(readFramebuffer)
3695    {
3696        readFramebuffer->detachTexture(texture);
3697    }
3698
3699    if(drawFramebuffer && drawFramebuffer != readFramebuffer)
3700    {
3701        drawFramebuffer->detachTexture(texture);
3702    }
3703}
3704
3705void Context::detachFramebuffer(GLuint framebuffer)
3706{
3707    // [OpenGL ES 2.0.24] section 4.4 page 107:
3708    // If a framebuffer that is currently bound to the target FRAMEBUFFER is deleted, it is as though
3709    // BindFramebuffer had been executed with the target of FRAMEBUFFER and framebuffer of zero.
3710
3711    if(mState.readFramebuffer == framebuffer)
3712    {
3713        bindReadFramebuffer(0);
3714    }
3715
3716    if(mState.drawFramebuffer == framebuffer)
3717    {
3718        bindDrawFramebuffer(0);
3719    }
3720}
3721
3722void Context::detachRenderbuffer(GLuint renderbuffer)
3723{
3724    // [OpenGL ES 2.0.24] section 4.4 page 109:
3725    // If a renderbuffer that is currently bound to RENDERBUFFER is deleted, it is as though BindRenderbuffer
3726    // had been executed with the target RENDERBUFFER and name of zero.
3727
3728    if(mState.renderbuffer.name() == renderbuffer)
3729    {
3730        bindRenderbuffer(0);
3731    }
3732
3733    // [OpenGL ES 2.0.24] section 4.4 page 111:
3734    // If a renderbuffer object is deleted while its image is attached to the currently bound framebuffer,
3735    // then it is as if FramebufferRenderbuffer had been called, with a renderbuffer of 0, for each attachment
3736    // point to which this image was attached in the currently bound framebuffer.
3737
3738    Framebuffer *readFramebuffer = getReadFramebuffer();
3739    Framebuffer *drawFramebuffer = getDrawFramebuffer();
3740
3741    if(readFramebuffer)
3742    {
3743        readFramebuffer->detachRenderbuffer(renderbuffer);
3744    }
3745
3746    if(drawFramebuffer && drawFramebuffer != readFramebuffer)
3747    {
3748        drawFramebuffer->detachRenderbuffer(renderbuffer);
3749    }
3750}
3751
3752void Context::detachSampler(GLuint sampler)
3753{
3754	// [OpenGL ES 3.0.2] section 3.8.2 pages 123-124:
3755	// If a sampler object that is currently bound to one or more texture units is
3756	// deleted, it is as though BindSampler is called once for each texture unit to
3757	// which the sampler is bound, with unit set to the texture unit and sampler set to zero.
3758	for(size_t textureUnit = 0; textureUnit < MAX_COMBINED_TEXTURE_IMAGE_UNITS; ++textureUnit)
3759	{
3760		gl::BindingPointer<Sampler> &samplerBinding = mState.sampler[textureUnit];
3761		if(samplerBinding.name() == sampler)
3762		{
3763			samplerBinding = NULL;
3764		}
3765	}
3766}
3767
3768bool Context::cullSkipsDraw(GLenum drawMode)
3769{
3770    return mState.cullFaceEnabled && mState.cullMode == GL_FRONT_AND_BACK && isTriangleMode(drawMode);
3771}
3772
3773bool Context::isTriangleMode(GLenum drawMode)
3774{
3775    switch (drawMode)
3776    {
3777      case GL_TRIANGLES:
3778      case GL_TRIANGLE_FAN:
3779      case GL_TRIANGLE_STRIP:
3780        return true;
3781      case GL_POINTS:
3782      case GL_LINES:
3783      case GL_LINE_LOOP:
3784      case GL_LINE_STRIP:
3785        return false;
3786      default: UNREACHABLE(drawMode);
3787    }
3788
3789    return false;
3790}
3791
3792void Context::setVertexAttrib(GLuint index, const GLfloat *values)
3793{
3794    ASSERT(index < MAX_VERTEX_ATTRIBS);
3795
3796    mState.vertexAttribute[index].setCurrentValue(values);
3797
3798    mVertexDataManager->dirtyCurrentValue(index);
3799}
3800
3801void Context::setVertexAttrib(GLuint index, const GLint *values)
3802{
3803	ASSERT(index < MAX_VERTEX_ATTRIBS);
3804
3805	mState.vertexAttribute[index].setCurrentValue(values);
3806
3807	mVertexDataManager->dirtyCurrentValue(index);
3808}
3809
3810void Context::setVertexAttrib(GLuint index, const GLuint *values)
3811{
3812	ASSERT(index < MAX_VERTEX_ATTRIBS);
3813
3814	mState.vertexAttribute[index].setCurrentValue(values);
3815
3816	mVertexDataManager->dirtyCurrentValue(index);
3817}
3818
3819void Context::blitFramebuffer(GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1,
3820                              GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1,
3821                              GLbitfield mask)
3822{
3823    Framebuffer *readFramebuffer = getReadFramebuffer();
3824    Framebuffer *drawFramebuffer = getDrawFramebuffer();
3825
3826	int readBufferWidth, readBufferHeight, readBufferSamples;
3827    int drawBufferWidth, drawBufferHeight, drawBufferSamples;
3828
3829    if(!readFramebuffer || readFramebuffer->completeness(readBufferWidth, readBufferHeight, readBufferSamples) != GL_FRAMEBUFFER_COMPLETE ||
3830       !drawFramebuffer || drawFramebuffer->completeness(drawBufferWidth, drawBufferHeight, drawBufferSamples) != GL_FRAMEBUFFER_COMPLETE)
3831    {
3832        return error(GL_INVALID_FRAMEBUFFER_OPERATION);
3833    }
3834
3835    if(drawBufferSamples > 1)
3836    {
3837        return error(GL_INVALID_OPERATION);
3838    }
3839
3840    sw::SliceRect sourceRect;
3841    sw::SliceRect destRect;
3842	bool flipX = (srcX0 < srcX1) ^ (dstX0 < dstX1);
3843	bool flipy = (srcY0 < srcY1) ^ (dstY0 < dstY1);
3844
3845    if(srcX0 < srcX1)
3846    {
3847        sourceRect.x0 = srcX0;
3848        sourceRect.x1 = srcX1;
3849    }
3850    else
3851    {
3852        sourceRect.x0 = srcX1;
3853        sourceRect.x1 = srcX0;
3854    }
3855
3856	if(dstX0 < dstX1)
3857	{
3858		destRect.x0 = dstX0;
3859		destRect.x1 = dstX1;
3860	}
3861	else
3862	{
3863		destRect.x0 = dstX1;
3864		destRect.x1 = dstX0;
3865	}
3866
3867    if(srcY0 < srcY1)
3868    {
3869        sourceRect.y0 = srcY0;
3870        sourceRect.y1 = srcY1;
3871    }
3872    else
3873    {
3874        sourceRect.y0 = srcY1;
3875        sourceRect.y1 = srcY0;
3876    }
3877
3878	if(dstY0 < dstY1)
3879	{
3880		destRect.y0 = dstY0;
3881		destRect.y1 = dstY1;
3882	}
3883	else
3884	{
3885		destRect.y0 = dstY1;
3886		destRect.y1 = dstY0;
3887	}
3888
3889	sw::Rect sourceScissoredRect = sourceRect;
3890    sw::Rect destScissoredRect = destRect;
3891
3892    if(mState.scissorTestEnabled)   // Only write to parts of the destination framebuffer which pass the scissor test
3893    {
3894        if(destRect.x0 < mState.scissorX)
3895        {
3896            int xDiff = mState.scissorX - destRect.x0;
3897            destScissoredRect.x0 = mState.scissorX;
3898            sourceScissoredRect.x0 += xDiff;
3899        }
3900
3901        if(destRect.x1 > mState.scissorX + mState.scissorWidth)
3902        {
3903            int xDiff = destRect.x1 - (mState.scissorX + mState.scissorWidth);
3904            destScissoredRect.x1 = mState.scissorX + mState.scissorWidth;
3905            sourceScissoredRect.x1 -= xDiff;
3906        }
3907
3908        if(destRect.y0 < mState.scissorY)
3909        {
3910            int yDiff = mState.scissorY - destRect.y0;
3911            destScissoredRect.y0 = mState.scissorY;
3912            sourceScissoredRect.y0 += yDiff;
3913        }
3914
3915        if(destRect.y1 > mState.scissorY + mState.scissorHeight)
3916        {
3917            int yDiff = destRect.y1 - (mState.scissorY + mState.scissorHeight);
3918            destScissoredRect.y1 = mState.scissorY + mState.scissorHeight;
3919            sourceScissoredRect.y1 -= yDiff;
3920        }
3921    }
3922
3923    sw::Rect sourceTrimmedRect = sourceScissoredRect;
3924    sw::Rect destTrimmedRect = destScissoredRect;
3925
3926    // The source & destination rectangles also may need to be trimmed if they fall out of the bounds of
3927    // the actual draw and read surfaces.
3928    if(sourceTrimmedRect.x0 < 0)
3929    {
3930        int xDiff = 0 - sourceTrimmedRect.x0;
3931        sourceTrimmedRect.x0 = 0;
3932        destTrimmedRect.x0 += xDiff;
3933    }
3934
3935    if(sourceTrimmedRect.x1 > readBufferWidth)
3936    {
3937        int xDiff = sourceTrimmedRect.x1 - readBufferWidth;
3938        sourceTrimmedRect.x1 = readBufferWidth;
3939        destTrimmedRect.x1 -= xDiff;
3940    }
3941
3942    if(sourceTrimmedRect.y0 < 0)
3943    {
3944        int yDiff = 0 - sourceTrimmedRect.y0;
3945        sourceTrimmedRect.y0 = 0;
3946        destTrimmedRect.y0 += yDiff;
3947    }
3948
3949    if(sourceTrimmedRect.y1 > readBufferHeight)
3950    {
3951        int yDiff = sourceTrimmedRect.y1 - readBufferHeight;
3952        sourceTrimmedRect.y1 = readBufferHeight;
3953        destTrimmedRect.y1 -= yDiff;
3954    }
3955
3956    if(destTrimmedRect.x0 < 0)
3957    {
3958        int xDiff = 0 - destTrimmedRect.x0;
3959        destTrimmedRect.x0 = 0;
3960        sourceTrimmedRect.x0 += xDiff;
3961    }
3962
3963    if(destTrimmedRect.x1 > drawBufferWidth)
3964    {
3965        int xDiff = destTrimmedRect.x1 - drawBufferWidth;
3966        destTrimmedRect.x1 = drawBufferWidth;
3967        sourceTrimmedRect.x1 -= xDiff;
3968    }
3969
3970    if(destTrimmedRect.y0 < 0)
3971    {
3972        int yDiff = 0 - destTrimmedRect.y0;
3973        destTrimmedRect.y0 = 0;
3974        sourceTrimmedRect.y0 += yDiff;
3975    }
3976
3977    if(destTrimmedRect.y1 > drawBufferHeight)
3978    {
3979        int yDiff = destTrimmedRect.y1 - drawBufferHeight;
3980        destTrimmedRect.y1 = drawBufferHeight;
3981        sourceTrimmedRect.y1 -= yDiff;
3982    }
3983
3984    bool partialBufferCopy = false;
3985
3986    if(sourceTrimmedRect.y1 - sourceTrimmedRect.y0 < readBufferHeight ||
3987       sourceTrimmedRect.x1 - sourceTrimmedRect.x0 < readBufferWidth ||
3988       destTrimmedRect.y1 - destTrimmedRect.y0 < drawBufferHeight ||
3989       destTrimmedRect.x1 - destTrimmedRect.x0 < drawBufferWidth ||
3990       sourceTrimmedRect.y0 != 0 || destTrimmedRect.y0 != 0 || sourceTrimmedRect.x0 != 0 || destTrimmedRect.x0 != 0)
3991    {
3992        partialBufferCopy = true;
3993    }
3994
3995	bool blitRenderTarget = false;
3996    bool blitDepthStencil = false;
3997
3998    if(mask & GL_COLOR_BUFFER_BIT)
3999    {
4000        const bool validReadType = readFramebuffer->getColorbufferType(getReadFramebufferColorIndex()) == GL_TEXTURE_2D ||
4001                                   readFramebuffer->getColorbufferType(getReadFramebufferColorIndex()) == GL_RENDERBUFFER;
4002        const bool validDrawType = drawFramebuffer->getColorbufferType(0) == GL_TEXTURE_2D ||
4003                                   drawFramebuffer->getColorbufferType(0) == GL_RENDERBUFFER;
4004        if(!validReadType || !validDrawType)
4005        {
4006            return error(GL_INVALID_OPERATION);
4007        }
4008
4009        if(partialBufferCopy && readBufferSamples > 1)
4010        {
4011            return error(GL_INVALID_OPERATION);
4012        }
4013
4014        blitRenderTarget = true;
4015    }
4016
4017    if(mask & (GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT))
4018    {
4019        Renderbuffer *readDSBuffer = NULL;
4020        Renderbuffer *drawDSBuffer = NULL;
4021
4022        // We support OES_packed_depth_stencil, and do not support a separately attached depth and stencil buffer, so if we have
4023        // both a depth and stencil buffer, it will be the same buffer.
4024
4025        if(mask & GL_DEPTH_BUFFER_BIT)
4026        {
4027            if(readFramebuffer->getDepthbuffer() && drawFramebuffer->getDepthbuffer())
4028            {
4029                if(readFramebuffer->getDepthbufferType() != drawFramebuffer->getDepthbufferType())
4030                {
4031                    return error(GL_INVALID_OPERATION);
4032                }
4033
4034                blitDepthStencil = true;
4035                readDSBuffer = readFramebuffer->getDepthbuffer();
4036                drawDSBuffer = drawFramebuffer->getDepthbuffer();
4037            }
4038        }
4039
4040        if(mask & GL_STENCIL_BUFFER_BIT)
4041        {
4042            if(readFramebuffer->getStencilbuffer() && drawFramebuffer->getStencilbuffer())
4043            {
4044                if(readFramebuffer->getStencilbufferType() != drawFramebuffer->getStencilbufferType())
4045                {
4046                    return error(GL_INVALID_OPERATION);
4047                }
4048
4049                blitDepthStencil = true;
4050                readDSBuffer = readFramebuffer->getStencilbuffer();
4051                drawDSBuffer = drawFramebuffer->getStencilbuffer();
4052            }
4053        }
4054
4055        if(partialBufferCopy)
4056        {
4057            ERR("Only whole-buffer depth and stencil blits are supported by this implementation.");
4058            return error(GL_INVALID_OPERATION);   // Only whole-buffer copies are permitted
4059        }
4060
4061        if((drawDSBuffer && drawDSBuffer->getSamples() > 1) ||
4062           (readDSBuffer && readDSBuffer->getSamples() > 1))
4063        {
4064            return error(GL_INVALID_OPERATION);
4065        }
4066    }
4067
4068    if(blitRenderTarget || blitDepthStencil)
4069    {
4070        if(blitRenderTarget)
4071        {
4072            egl::Image *readRenderTarget = readFramebuffer->getReadRenderTarget();
4073            egl::Image *drawRenderTarget = drawFramebuffer->getRenderTarget(0);
4074
4075			if(flipX)
4076			{
4077				swap(destRect.x0, destRect.x1);
4078			}
4079			if(flipy)
4080			{
4081				swap(destRect.y0, destRect.y1);
4082			}
4083
4084            bool success = device->stretchRect(readRenderTarget, &sourceRect, drawRenderTarget, &destRect, false);
4085
4086            readRenderTarget->release();
4087            drawRenderTarget->release();
4088
4089            if(!success)
4090            {
4091                ERR("BlitFramebuffer failed.");
4092                return;
4093            }
4094        }
4095
4096        if(blitDepthStencil)
4097        {
4098            bool success = device->stretchRect(readFramebuffer->getDepthStencil(), NULL, drawFramebuffer->getDepthStencil(), NULL, false);
4099
4100            if(!success)
4101            {
4102                ERR("BlitFramebuffer failed.");
4103                return;
4104            }
4105        }
4106    }
4107}
4108
4109void Context::bindTexImage(egl::Surface *surface)
4110{
4111	es2::Texture2D *textureObject = getTexture2D();
4112
4113    if(textureObject)
4114    {
4115		textureObject->bindTexImage(surface);
4116	}
4117}
4118
4119EGLenum Context::validateSharedImage(EGLenum target, GLuint name, GLuint textureLevel)
4120{
4121    GLenum textureTarget = GL_NONE;
4122
4123    switch(target)
4124    {
4125    case EGL_GL_TEXTURE_2D_KHR:
4126        textureTarget = GL_TEXTURE_2D;
4127        break;
4128    case EGL_GL_TEXTURE_CUBE_MAP_POSITIVE_X_KHR:
4129    case EGL_GL_TEXTURE_CUBE_MAP_NEGATIVE_X_KHR:
4130    case EGL_GL_TEXTURE_CUBE_MAP_POSITIVE_Y_KHR:
4131    case EGL_GL_TEXTURE_CUBE_MAP_NEGATIVE_Y_KHR:
4132    case EGL_GL_TEXTURE_CUBE_MAP_POSITIVE_Z_KHR:
4133    case EGL_GL_TEXTURE_CUBE_MAP_NEGATIVE_Z_KHR:
4134        textureTarget = GL_TEXTURE_CUBE_MAP;
4135        break;
4136    case EGL_GL_RENDERBUFFER_KHR:
4137        break;
4138    default:
4139        return EGL_BAD_PARAMETER;
4140    }
4141
4142    if(textureLevel >= es2::IMPLEMENTATION_MAX_TEXTURE_LEVELS)
4143    {
4144        return EGL_BAD_MATCH;
4145    }
4146
4147    if(textureTarget != GL_NONE)
4148    {
4149        es2::Texture *texture = getTexture(name);
4150
4151        if(!texture || texture->getTarget() != textureTarget)
4152        {
4153            return EGL_BAD_PARAMETER;
4154        }
4155
4156        if(texture->isShared(textureTarget, textureLevel))   // Bound to an EGLSurface or already an EGLImage sibling
4157        {
4158            return EGL_BAD_ACCESS;
4159        }
4160
4161        if(textureLevel != 0 && !texture->isSamplerComplete())
4162        {
4163            return EGL_BAD_PARAMETER;
4164        }
4165
4166        if(textureLevel == 0 && !(texture->isSamplerComplete() && texture->getLevelCount() == 1))
4167        {
4168            return EGL_BAD_PARAMETER;
4169        }
4170    }
4171    else if(target == EGL_GL_RENDERBUFFER_KHR)
4172    {
4173        es2::Renderbuffer *renderbuffer = getRenderbuffer(name);
4174
4175        if(!renderbuffer)
4176        {
4177            return EGL_BAD_PARAMETER;
4178        }
4179
4180        if(renderbuffer->isShared())   // Already an EGLImage sibling
4181        {
4182            return EGL_BAD_ACCESS;
4183        }
4184    }
4185    else UNREACHABLE(target);
4186
4187	return EGL_SUCCESS;
4188}
4189
4190egl::Image *Context::createSharedImage(EGLenum target, GLuint name, GLuint textureLevel)
4191{
4192	GLenum textureTarget = GL_NONE;
4193
4194    switch(target)
4195    {
4196    case EGL_GL_TEXTURE_2D_KHR:                  textureTarget = GL_TEXTURE_2D;                  break;
4197    case EGL_GL_TEXTURE_CUBE_MAP_POSITIVE_X_KHR: textureTarget = GL_TEXTURE_CUBE_MAP_POSITIVE_X; break;
4198    case EGL_GL_TEXTURE_CUBE_MAP_NEGATIVE_X_KHR: textureTarget = GL_TEXTURE_CUBE_MAP_NEGATIVE_X; break;
4199    case EGL_GL_TEXTURE_CUBE_MAP_POSITIVE_Y_KHR: textureTarget = GL_TEXTURE_CUBE_MAP_POSITIVE_Y; break;
4200    case EGL_GL_TEXTURE_CUBE_MAP_NEGATIVE_Y_KHR: textureTarget = GL_TEXTURE_CUBE_MAP_NEGATIVE_Y; break;
4201    case EGL_GL_TEXTURE_CUBE_MAP_POSITIVE_Z_KHR: textureTarget = GL_TEXTURE_CUBE_MAP_POSITIVE_Z; break;
4202    case EGL_GL_TEXTURE_CUBE_MAP_NEGATIVE_Z_KHR: textureTarget = GL_TEXTURE_CUBE_MAP_NEGATIVE_Z; break;
4203    }
4204
4205    if(textureTarget != GL_NONE)
4206    {
4207        es2::Texture *texture = getTexture(name);
4208
4209        return texture->createSharedImage(textureTarget, textureLevel);
4210    }
4211    else if(target == EGL_GL_RENDERBUFFER_KHR)
4212    {
4213        es2::Renderbuffer *renderbuffer = getRenderbuffer(name);
4214
4215        return renderbuffer->createSharedImage();
4216    }
4217    else UNREACHABLE(target);
4218
4219	return 0;
4220}
4221
4222Device *Context::getDevice()
4223{
4224	return device;
4225}
4226
4227const GLubyte* Context::getExtensions(GLuint index, GLuint* numExt) const
4228{
4229	// Keep list sorted in following order:
4230	// OES extensions
4231	// EXT extensions
4232	// Vendor extensions
4233	static const GLubyte* extensions[] = {
4234		(const GLubyte*)"GL_OES_compressed_ETC1_RGB8_texture",
4235		(const GLubyte*)"GL_OES_depth24",
4236		(const GLubyte*)"GL_OES_depth32",
4237		(const GLubyte*)"GL_OES_depth_texture",
4238		(const GLubyte*)"GL_OES_depth_texture_cube_map",
4239		(const GLubyte*)"GL_OES_EGL_image",
4240		(const GLubyte*)"GL_OES_EGL_image_external",
4241		(const GLubyte*)"GL_OES_EGL_sync",
4242		(const GLubyte*)"GL_OES_element_index_uint",
4243		(const GLubyte*)"GL_OES_framebuffer_object",
4244		(const GLubyte*)"GL_OES_packed_depth_stencil",
4245		(const GLubyte*)"GL_OES_rgb8_rgba8",
4246		(const GLubyte*)"GL_OES_standard_derivatives",
4247		(const GLubyte*)"GL_OES_texture_float",
4248		(const GLubyte*)"GL_OES_texture_float_linear",
4249		(const GLubyte*)"GL_OES_texture_half_float",
4250		(const GLubyte*)"GL_OES_texture_half_float_linear",
4251		(const GLubyte*)"GL_OES_texture_npot",
4252		(const GLubyte*)"GL_OES_texture_3D",
4253		(const GLubyte*)"GL_EXT_blend_minmax",
4254		(const GLubyte*)"GL_EXT_color_buffer_half_float",
4255		(const GLubyte*)"GL_EXT_occlusion_query_boolean",
4256		(const GLubyte*)"GL_EXT_read_format_bgra",
4257#if (S3TC_SUPPORT)
4258		(const GLubyte*)"GL_EXT_texture_compression_dxt1",
4259#endif
4260		(const GLubyte*)"GL_EXT_texture_filter_anisotropic",
4261		(const GLubyte*)"GL_EXT_texture_format_BGRA8888",
4262		(const GLubyte*)"GL_ANGLE_framebuffer_blit",
4263		(const GLubyte*)"GL_NV_framebuffer_blit",
4264		(const GLubyte*)"GL_ANGLE_framebuffer_multisample",
4265#if (S3TC_SUPPORT)
4266		(const GLubyte*)"GL_ANGLE_texture_compression_dxt3",
4267		(const GLubyte*)"GL_ANGLE_texture_compression_dxt5",
4268#endif
4269		(const GLubyte*)"GL_NV_fence",
4270		(const GLubyte*)"GL_EXT_instanced_arrays",
4271		(const GLubyte*)"GL_ANGLE_instanced_arrays",
4272	};
4273	static const GLuint numExtensions = sizeof(extensions) / sizeof(*extensions);
4274
4275	if(numExt)
4276	{
4277		*numExt = numExtensions;
4278		return nullptr;
4279	}
4280
4281	if(index == GL_INVALID_INDEX)
4282	{
4283		static GLubyte* extensionsCat = nullptr;
4284		if((extensionsCat == nullptr) && (numExtensions > 0))
4285		{
4286			int totalLength = numExtensions; // 1 space between each extension name + terminating null
4287			for(int i = 0; i < numExtensions; ++i)
4288			{
4289				totalLength += strlen(reinterpret_cast<const char*>(extensions[i]));
4290			}
4291			extensionsCat = new GLubyte[totalLength];
4292			extensionsCat[0] = '\0';
4293			for(int i = 0; i < numExtensions; ++i)
4294			{
4295				if(i != 0)
4296				{
4297					strcat(reinterpret_cast<char*>(extensionsCat), " ");
4298				}
4299				strcat(reinterpret_cast<char*>(extensionsCat), reinterpret_cast<const char*>(extensions[i]));
4300			}
4301		}
4302		return extensionsCat;
4303	}
4304
4305	if(index >= numExtensions)
4306	{
4307		return nullptr;
4308	}
4309
4310	return extensions[index];
4311}
4312
4313}
4314
4315egl::Context *es2CreateContext(const egl::Config *config, const egl::Context *shareContext, int clientVersion)
4316{
4317	ASSERT(!shareContext || shareContext->getClientVersion() == clientVersion);   // Should be checked by eglCreateContext
4318	return new es2::Context(config, static_cast<const es2::Context*>(shareContext), clientVersion);
4319}
4320