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