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