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