Context.cpp revision 3ff330f7e55dfc1dbd9bacb0972aef47f1be8b00
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:
2483    case GL_RENDERBUFFER_BINDING:
2484    case GL_CURRENT_PROGRAM:
2485    case GL_PACK_ALIGNMENT:
2486    case GL_UNPACK_ALIGNMENT:
2487    case GL_GENERATE_MIPMAP_HINT:
2488    case GL_FRAGMENT_SHADER_DERIVATIVE_HINT_OES:
2489    case GL_RED_BITS:
2490    case GL_GREEN_BITS:
2491    case GL_BLUE_BITS:
2492    case GL_ALPHA_BITS:
2493    case GL_DEPTH_BITS:
2494    case GL_STENCIL_BITS:
2495    case GL_ELEMENT_ARRAY_BUFFER_BINDING:
2496    case GL_CULL_FACE_MODE:
2497    case GL_FRONT_FACE:
2498    case GL_ACTIVE_TEXTURE:
2499    case GL_STENCIL_FUNC:
2500    case GL_STENCIL_VALUE_MASK:
2501    case GL_STENCIL_REF:
2502    case GL_STENCIL_FAIL:
2503    case GL_STENCIL_PASS_DEPTH_FAIL:
2504    case GL_STENCIL_PASS_DEPTH_PASS:
2505    case GL_STENCIL_BACK_FUNC:
2506    case GL_STENCIL_BACK_VALUE_MASK:
2507    case GL_STENCIL_BACK_REF:
2508    case GL_STENCIL_BACK_FAIL:
2509    case GL_STENCIL_BACK_PASS_DEPTH_FAIL:
2510    case GL_STENCIL_BACK_PASS_DEPTH_PASS:
2511    case GL_DEPTH_FUNC:
2512    case GL_BLEND_SRC_RGB:
2513    case GL_BLEND_SRC_ALPHA:
2514    case GL_BLEND_DST_RGB:
2515    case GL_BLEND_DST_ALPHA:
2516    case GL_BLEND_EQUATION_RGB:
2517    case GL_BLEND_EQUATION_ALPHA:
2518    case GL_STENCIL_WRITEMASK:
2519    case GL_STENCIL_BACK_WRITEMASK:
2520    case GL_STENCIL_CLEAR_VALUE:
2521    case GL_SUBPIXEL_BITS:
2522    case GL_MAX_TEXTURE_SIZE:
2523    case GL_MAX_CUBE_MAP_TEXTURE_SIZE:
2524    case GL_SAMPLE_BUFFERS:
2525    case GL_SAMPLES:
2526    case GL_IMPLEMENTATION_COLOR_READ_TYPE:
2527    case GL_IMPLEMENTATION_COLOR_READ_FORMAT:
2528    case GL_TEXTURE_BINDING_2D:
2529    case GL_TEXTURE_BINDING_CUBE_MAP:
2530    case GL_TEXTURE_BINDING_EXTERNAL_OES:
2531    case GL_TEXTURE_BINDING_3D_OES:
2532    case GL_COPY_READ_BUFFER_BINDING:
2533    case GL_COPY_WRITE_BUFFER_BINDING:
2534    case GL_DRAW_BUFFER0:
2535    case GL_DRAW_BUFFER1:
2536    case GL_DRAW_BUFFER2:
2537    case GL_DRAW_BUFFER3:
2538    case GL_DRAW_BUFFER4:
2539    case GL_DRAW_BUFFER5:
2540    case GL_DRAW_BUFFER6:
2541    case GL_DRAW_BUFFER7:
2542    case GL_DRAW_BUFFER8:
2543    case GL_DRAW_BUFFER9:
2544    case GL_DRAW_BUFFER10:
2545    case GL_DRAW_BUFFER11:
2546    case GL_DRAW_BUFFER12:
2547    case GL_DRAW_BUFFER13:
2548    case GL_DRAW_BUFFER14:
2549    case GL_DRAW_BUFFER15:
2550    case GL_MAJOR_VERSION:
2551    case GL_MAX_3D_TEXTURE_SIZE:
2552    case GL_MAX_ARRAY_TEXTURE_LAYERS:
2553    case GL_MAX_COLOR_ATTACHMENTS:
2554    case GL_MAX_COMBINED_FRAGMENT_UNIFORM_COMPONENTS:
2555    case GL_MAX_COMBINED_UNIFORM_BLOCKS:
2556    case GL_MAX_COMBINED_VERTEX_UNIFORM_COMPONENTS:
2557    case GL_MAX_DRAW_BUFFERS:
2558    case GL_MAX_ELEMENT_INDEX:
2559    case GL_MAX_ELEMENTS_INDICES:
2560    case GL_MAX_ELEMENTS_VERTICES:
2561    case GL_MAX_FRAGMENT_INPUT_COMPONENTS:
2562    case GL_MAX_FRAGMENT_UNIFORM_BLOCKS:
2563    case GL_MAX_FRAGMENT_UNIFORM_COMPONENTS:
2564    case GL_MAX_PROGRAM_TEXEL_OFFSET:
2565    case GL_MAX_SERVER_WAIT_TIMEOUT:
2566    case GL_MAX_TEXTURE_LOD_BIAS:
2567    case GL_MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS:
2568    case GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS:
2569    case GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS:
2570    case GL_MAX_UNIFORM_BLOCK_SIZE:
2571    case GL_MAX_UNIFORM_BUFFER_BINDINGS:
2572    case GL_MAX_VARYING_COMPONENTS:
2573    case GL_MAX_VERTEX_OUTPUT_COMPONENTS:
2574    case GL_MAX_VERTEX_UNIFORM_BLOCKS:
2575    case GL_MAX_VERTEX_UNIFORM_COMPONENTS:
2576    case GL_MIN_PROGRAM_TEXEL_OFFSET:
2577    case GL_MINOR_VERSION:
2578    case GL_NUM_EXTENSIONS:
2579    case GL_NUM_PROGRAM_BINARY_FORMATS:
2580    case GL_PACK_ROW_LENGTH:
2581    case GL_PACK_SKIP_PIXELS:
2582    case GL_PACK_SKIP_ROWS:
2583    case GL_PIXEL_PACK_BUFFER_BINDING:
2584    case GL_PIXEL_UNPACK_BUFFER_BINDING:
2585    case GL_PROGRAM_BINARY_FORMATS:
2586    case GL_READ_BUFFER:
2587    case GL_SAMPLER_BINDING:
2588    case GL_TEXTURE_BINDING_2D_ARRAY:
2589    case GL_UNIFORM_BUFFER_BINDING:
2590    case GL_UNIFORM_BUFFER_OFFSET_ALIGNMENT:
2591    case GL_UNIFORM_BUFFER_SIZE:
2592    case GL_UNIFORM_BUFFER_START:
2593    case GL_UNPACK_IMAGE_HEIGHT:
2594    case GL_UNPACK_ROW_LENGTH:
2595    case GL_UNPACK_SKIP_IMAGES:
2596    case GL_UNPACK_SKIP_PIXELS:
2597    case GL_UNPACK_SKIP_ROWS:
2598    case GL_VERTEX_ARRAY_BINDING:
2599        {
2600            *type = GL_INT;
2601            *numParams = 1;
2602        }
2603        break;
2604    case GL_MAX_SAMPLES_ANGLE:
2605        {
2606            *type = GL_INT;
2607            *numParams = 1;
2608        }
2609        break;
2610    case GL_MAX_VIEWPORT_DIMS:
2611        {
2612            *type = GL_INT;
2613            *numParams = 2;
2614        }
2615        break;
2616    case GL_VIEWPORT:
2617    case GL_SCISSOR_BOX:
2618        {
2619            *type = GL_INT;
2620            *numParams = 4;
2621        }
2622        break;
2623    case GL_SHADER_COMPILER:
2624    case GL_SAMPLE_COVERAGE_INVERT:
2625    case GL_DEPTH_WRITEMASK:
2626    case GL_CULL_FACE:                // CULL_FACE through DITHER are natural to IsEnabled,
2627    case GL_POLYGON_OFFSET_FILL:      // but can be retrieved through the Get{Type}v queries.
2628    case GL_SAMPLE_ALPHA_TO_COVERAGE: // For this purpose, they are treated here as bool-natural
2629    case GL_SAMPLE_COVERAGE:
2630    case GL_SCISSOR_TEST:
2631    case GL_STENCIL_TEST:
2632    case GL_DEPTH_TEST:
2633    case GL_BLEND:
2634    case GL_DITHER:
2635    case GL_PRIMITIVE_RESTART_FIXED_INDEX:
2636    case GL_RASTERIZER_DISCARD:
2637        {
2638            *type = GL_BOOL;
2639            *numParams = 1;
2640        }
2641        break;
2642    case GL_COLOR_WRITEMASK:
2643        {
2644            *type = GL_BOOL;
2645            *numParams = 4;
2646        }
2647        break;
2648    case GL_POLYGON_OFFSET_FACTOR:
2649    case GL_POLYGON_OFFSET_UNITS:
2650    case GL_SAMPLE_COVERAGE_VALUE:
2651    case GL_DEPTH_CLEAR_VALUE:
2652    case GL_LINE_WIDTH:
2653        {
2654            *type = GL_FLOAT;
2655            *numParams = 1;
2656        }
2657        break;
2658    case GL_ALIASED_LINE_WIDTH_RANGE:
2659    case GL_ALIASED_POINT_SIZE_RANGE:
2660    case GL_DEPTH_RANGE:
2661        {
2662            *type = GL_FLOAT;
2663            *numParams = 2;
2664        }
2665        break;
2666    case GL_COLOR_CLEAR_VALUE:
2667    case GL_BLEND_COLOR:
2668        {
2669            *type = GL_FLOAT;
2670            *numParams = 4;
2671        }
2672        break;
2673	case GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT:
2674        *type = GL_FLOAT;
2675        *numParams = 1;
2676        break;
2677    default:
2678        return false;
2679    }
2680
2681    return true;
2682}
2683
2684void Context::applyScissor(int width, int height)
2685{
2686	if(mState.scissorTestEnabled)
2687	{
2688		sw::Rect scissor = { mState.scissorX, mState.scissorY, mState.scissorX + mState.scissorWidth, mState.scissorY + mState.scissorHeight };
2689		scissor.clip(0, 0, width, height);
2690
2691		device->setScissorRect(scissor);
2692		device->setScissorEnable(true);
2693	}
2694	else
2695	{
2696		device->setScissorEnable(false);
2697	}
2698}
2699
2700egl::Image *Context::getScissoredImage(GLint drawbuffer, int &x0, int &y0, int &width, int &height, bool depthStencil)
2701{
2702	Framebuffer* framebuffer = getFramebuffer(drawbuffer);
2703	egl::Image* image = depthStencil ? framebuffer->getDepthStencil() : framebuffer->getRenderTarget(0);
2704
2705	applyScissor(image->getWidth(), image->getHeight());
2706
2707	device->getScissoredRegion(image, x0, y0, width, height);
2708
2709	return image;
2710}
2711
2712// Applies the render target surface, depth stencil surface, viewport rectangle and scissor rectangle
2713bool Context::applyRenderTarget()
2714{
2715    Framebuffer *framebuffer = getDrawFramebuffer();
2716	int width, height, samples;
2717
2718    if(!framebuffer || framebuffer->completeness(width, height, samples) != GL_FRAMEBUFFER_COMPLETE)
2719    {
2720        return error(GL_INVALID_FRAMEBUFFER_OPERATION, false);
2721    }
2722
2723	egl::Image *renderTarget = framebuffer->getRenderTarget(0);
2724	device->setRenderTarget(renderTarget);
2725	if(renderTarget) renderTarget->release();
2726
2727    egl::Image *depthStencil = framebuffer->getDepthStencil();
2728    device->setDepthStencilSurface(depthStencil);
2729	if(depthStencil) depthStencil->release();
2730
2731    Viewport viewport;
2732    float zNear = clamp01(mState.zNear);
2733    float zFar = clamp01(mState.zFar);
2734
2735    viewport.x0 = mState.viewportX;
2736    viewport.y0 = mState.viewportY;
2737    viewport.width = mState.viewportWidth;
2738    viewport.height = mState.viewportHeight;
2739    viewport.minZ = zNear;
2740    viewport.maxZ = zFar;
2741
2742    device->setViewport(viewport);
2743
2744	applyScissor(width, height);
2745
2746	Program *program = getCurrentProgram();
2747
2748	if(program)
2749	{
2750		GLfloat nearFarDiff[3] = {zNear, zFar, zFar - zNear};
2751        program->setUniform1fv(program->getUniformLocation("gl_DepthRange.near"), 1, &nearFarDiff[0]);
2752		program->setUniform1fv(program->getUniformLocation("gl_DepthRange.far"), 1, &nearFarDiff[1]);
2753		program->setUniform1fv(program->getUniformLocation("gl_DepthRange.diff"), 1, &nearFarDiff[2]);
2754    }
2755
2756    return true;
2757}
2758
2759// Applies the fixed-function state (culling, depth test, alpha blending, stenciling, etc)
2760void Context::applyState(GLenum drawMode)
2761{
2762    Framebuffer *framebuffer = getDrawFramebuffer();
2763
2764    if(mState.cullFaceEnabled)
2765    {
2766        device->setCullMode(es2sw::ConvertCullMode(mState.cullMode, mState.frontFace));
2767    }
2768    else
2769    {
2770		device->setCullMode(sw::CULL_NONE);
2771    }
2772
2773    if(mDepthStateDirty)
2774    {
2775        if(mState.depthTestEnabled)
2776        {
2777			device->setDepthBufferEnable(true);
2778			device->setDepthCompare(es2sw::ConvertDepthComparison(mState.depthFunc));
2779        }
2780        else
2781        {
2782            device->setDepthBufferEnable(false);
2783        }
2784
2785        mDepthStateDirty = false;
2786    }
2787
2788    if(mBlendStateDirty)
2789    {
2790        if(mState.blendEnabled)
2791        {
2792			device->setAlphaBlendEnable(true);
2793			device->setSeparateAlphaBlendEnable(true);
2794
2795            device->setBlendConstant(es2sw::ConvertColor(mState.blendColor));
2796
2797			device->setSourceBlendFactor(es2sw::ConvertBlendFunc(mState.sourceBlendRGB));
2798			device->setDestBlendFactor(es2sw::ConvertBlendFunc(mState.destBlendRGB));
2799			device->setBlendOperation(es2sw::ConvertBlendOp(mState.blendEquationRGB));
2800
2801            device->setSourceBlendFactorAlpha(es2sw::ConvertBlendFunc(mState.sourceBlendAlpha));
2802			device->setDestBlendFactorAlpha(es2sw::ConvertBlendFunc(mState.destBlendAlpha));
2803			device->setBlendOperationAlpha(es2sw::ConvertBlendOp(mState.blendEquationAlpha));
2804        }
2805        else
2806        {
2807			device->setAlphaBlendEnable(false);
2808        }
2809
2810        mBlendStateDirty = false;
2811    }
2812
2813    if(mStencilStateDirty || mFrontFaceDirty)
2814    {
2815        if(mState.stencilTestEnabled && framebuffer->hasStencil())
2816        {
2817			device->setStencilEnable(true);
2818			device->setTwoSidedStencil(true);
2819
2820            // get the maximum size of the stencil ref
2821            Renderbuffer *stencilbuffer = framebuffer->getStencilbuffer();
2822            GLuint maxStencil = (1 << stencilbuffer->getStencilSize()) - 1;
2823
2824			if(mState.frontFace == GL_CCW)
2825			{
2826				device->setStencilWriteMask(mState.stencilWritemask);
2827				device->setStencilCompare(es2sw::ConvertStencilComparison(mState.stencilFunc));
2828
2829				device->setStencilReference((mState.stencilRef < (GLint)maxStencil) ? mState.stencilRef : maxStencil);
2830				device->setStencilMask(mState.stencilMask);
2831
2832				device->setStencilFailOperation(es2sw::ConvertStencilOp(mState.stencilFail));
2833				device->setStencilZFailOperation(es2sw::ConvertStencilOp(mState.stencilPassDepthFail));
2834				device->setStencilPassOperation(es2sw::ConvertStencilOp(mState.stencilPassDepthPass));
2835
2836				device->setStencilWriteMaskCCW(mState.stencilBackWritemask);
2837				device->setStencilCompareCCW(es2sw::ConvertStencilComparison(mState.stencilBackFunc));
2838
2839				device->setStencilReferenceCCW((mState.stencilBackRef < (GLint)maxStencil) ? mState.stencilBackRef : maxStencil);
2840				device->setStencilMaskCCW(mState.stencilBackMask);
2841
2842				device->setStencilFailOperationCCW(es2sw::ConvertStencilOp(mState.stencilBackFail));
2843				device->setStencilZFailOperationCCW(es2sw::ConvertStencilOp(mState.stencilBackPassDepthFail));
2844				device->setStencilPassOperationCCW(es2sw::ConvertStencilOp(mState.stencilBackPassDepthPass));
2845			}
2846			else
2847			{
2848				device->setStencilWriteMaskCCW(mState.stencilWritemask);
2849				device->setStencilCompareCCW(es2sw::ConvertStencilComparison(mState.stencilFunc));
2850
2851				device->setStencilReferenceCCW((mState.stencilRef < (GLint)maxStencil) ? mState.stencilRef : maxStencil);
2852				device->setStencilMaskCCW(mState.stencilMask);
2853
2854				device->setStencilFailOperationCCW(es2sw::ConvertStencilOp(mState.stencilFail));
2855				device->setStencilZFailOperationCCW(es2sw::ConvertStencilOp(mState.stencilPassDepthFail));
2856				device->setStencilPassOperationCCW(es2sw::ConvertStencilOp(mState.stencilPassDepthPass));
2857
2858				device->setStencilWriteMask(mState.stencilBackWritemask);
2859				device->setStencilCompare(es2sw::ConvertStencilComparison(mState.stencilBackFunc));
2860
2861				device->setStencilReference((mState.stencilBackRef < (GLint)maxStencil) ? mState.stencilBackRef : maxStencil);
2862				device->setStencilMask(mState.stencilBackMask);
2863
2864				device->setStencilFailOperation(es2sw::ConvertStencilOp(mState.stencilBackFail));
2865				device->setStencilZFailOperation(es2sw::ConvertStencilOp(mState.stencilBackPassDepthFail));
2866				device->setStencilPassOperation(es2sw::ConvertStencilOp(mState.stencilBackPassDepthPass));
2867			}
2868        }
2869        else
2870        {
2871			device->setStencilEnable(false);
2872        }
2873
2874        mStencilStateDirty = false;
2875        mFrontFaceDirty = false;
2876    }
2877
2878    if(mMaskStateDirty)
2879    {
2880		device->setColorWriteMask(0, es2sw::ConvertColorMask(mState.colorMaskRed, mState.colorMaskGreen, mState.colorMaskBlue, mState.colorMaskAlpha));
2881		device->setDepthWriteEnable(mState.depthMask);
2882
2883        mMaskStateDirty = false;
2884    }
2885
2886    if(mPolygonOffsetStateDirty)
2887    {
2888        if(mState.polygonOffsetFillEnabled)
2889        {
2890            Renderbuffer *depthbuffer = framebuffer->getDepthbuffer();
2891            if(depthbuffer)
2892            {
2893				device->setSlopeDepthBias(mState.polygonOffsetFactor);
2894                float depthBias = ldexp(mState.polygonOffsetUnits, -(int)(depthbuffer->getDepthSize()));
2895				device->setDepthBias(depthBias);
2896            }
2897        }
2898        else
2899        {
2900            device->setSlopeDepthBias(0);
2901            device->setDepthBias(0);
2902        }
2903
2904        mPolygonOffsetStateDirty = false;
2905    }
2906
2907    if(mSampleStateDirty)
2908    {
2909        if(mState.sampleAlphaToCoverageEnabled)
2910        {
2911            device->setTransparencyAntialiasing(sw::TRANSPARENCY_ALPHA_TO_COVERAGE);
2912        }
2913		else
2914		{
2915			device->setTransparencyAntialiasing(sw::TRANSPARENCY_NONE);
2916		}
2917
2918        if(mState.sampleCoverageEnabled)
2919        {
2920            unsigned int mask = 0;
2921            if(mState.sampleCoverageValue != 0)
2922            {
2923				int width, height, samples;
2924				framebuffer->completeness(width, height, samples);
2925
2926                float threshold = 0.5f;
2927
2928                for(int i = 0; i < samples; i++)
2929                {
2930                    mask <<= 1;
2931
2932                    if((i + 1) * mState.sampleCoverageValue >= threshold)
2933                    {
2934                        threshold += 1.0f;
2935                        mask |= 1;
2936                    }
2937                }
2938            }
2939
2940            if(mState.sampleCoverageInvert)
2941            {
2942                mask = ~mask;
2943            }
2944
2945			device->setMultiSampleMask(mask);
2946        }
2947        else
2948        {
2949			device->setMultiSampleMask(0xFFFFFFFF);
2950        }
2951
2952        mSampleStateDirty = false;
2953    }
2954
2955    if(mDitherStateDirty)
2956    {
2957    //	UNIMPLEMENTED();   // FIXME
2958
2959        mDitherStateDirty = false;
2960    }
2961}
2962
2963GLenum Context::applyVertexBuffer(GLint base, GLint first, GLsizei count, GLsizei instanceId)
2964{
2965    TranslatedAttribute attributes[MAX_VERTEX_ATTRIBS];
2966
2967    GLenum err = mVertexDataManager->prepareVertexData(first, count, attributes, instanceId);
2968    if(err != GL_NO_ERROR)
2969    {
2970        return err;
2971    }
2972
2973	Program *program = getCurrentProgram();
2974
2975	device->resetInputStreams(false);
2976
2977    for(int i = 0; i < MAX_VERTEX_ATTRIBS; i++)
2978	{
2979		if(program->getAttributeStream(i) == -1)
2980		{
2981			continue;
2982		}
2983
2984		sw::Resource *resource = attributes[i].vertexBuffer;
2985		const void *buffer = (char*)resource->data() + attributes[i].offset;
2986
2987		int stride = attributes[i].stride;
2988
2989		buffer = (char*)buffer + stride * base;
2990
2991		sw::Stream attribute(resource, buffer, stride);
2992
2993		attribute.type = attributes[i].type;
2994		attribute.count = attributes[i].count;
2995		attribute.normalized = attributes[i].normalized;
2996
2997		int stream = program->getAttributeStream(i);
2998		device->setInputStream(stream, attribute);
2999	}
3000
3001	return GL_NO_ERROR;
3002}
3003
3004// Applies the indices and element array bindings
3005GLenum Context::applyIndexBuffer(const void *indices, GLuint start, GLuint end, GLsizei count, GLenum mode, GLenum type, TranslatedIndexData *indexInfo)
3006{
3007	GLenum err = mIndexDataManager->prepareIndexData(type, start, end, count, getCurrentVertexArray()->getElementArrayBuffer(), indices, indexInfo);
3008
3009    if(err == GL_NO_ERROR)
3010    {
3011        device->setIndexBuffer(indexInfo->indexBuffer);
3012    }
3013
3014    return err;
3015}
3016
3017// Applies the shaders and shader constants
3018void Context::applyShaders()
3019{
3020    Program *programObject = getCurrentProgram();
3021    sw::VertexShader *vertexShader = programObject->getVertexShader();
3022	sw::PixelShader *pixelShader = programObject->getPixelShader();
3023
3024    device->setVertexShader(vertexShader);
3025    device->setPixelShader(pixelShader);
3026
3027    if(programObject->getSerial() != mAppliedProgramSerial)
3028    {
3029        programObject->dirtyAllUniforms();
3030        mAppliedProgramSerial = programObject->getSerial();
3031    }
3032
3033    programObject->applyUniforms();
3034    programObject->applyUniformBuffers();
3035}
3036
3037void Context::applyTextures()
3038{
3039    applyTextures(sw::SAMPLER_PIXEL);
3040	applyTextures(sw::SAMPLER_VERTEX);
3041}
3042
3043void Context::applyTextures(sw::SamplerType samplerType)
3044{
3045    Program *programObject = getCurrentProgram();
3046
3047    int samplerCount = (samplerType == sw::SAMPLER_PIXEL) ? MAX_TEXTURE_IMAGE_UNITS : MAX_VERTEX_TEXTURE_IMAGE_UNITS;   // Range of samplers of given sampler type
3048
3049    for(int samplerIndex = 0; samplerIndex < samplerCount; samplerIndex++)
3050    {
3051        int textureUnit = programObject->getSamplerMapping(samplerType, samplerIndex);   // OpenGL texture image unit index
3052
3053        if(textureUnit != -1)
3054        {
3055            TextureType textureType = programObject->getSamplerTextureType(samplerType, samplerIndex);
3056
3057            Texture *texture = getSamplerTexture(textureUnit, textureType);
3058
3059			if(texture->isSamplerComplete())
3060            {
3061                GLenum wrapS = texture->getWrapS();
3062                GLenum wrapT = texture->getWrapT();
3063				GLenum wrapR = texture->getWrapR();
3064                GLenum texFilter = texture->getMinFilter();
3065                GLenum magFilter = texture->getMagFilter();
3066				GLfloat maxAnisotropy = texture->getMaxAnisotropy();
3067
3068				device->setAddressingModeU(samplerType, samplerIndex, es2sw::ConvertTextureWrap(wrapS));
3069				device->setAddressingModeV(samplerType, samplerIndex, es2sw::ConvertTextureWrap(wrapT));
3070				device->setAddressingModeW(samplerType, samplerIndex, es2sw::ConvertTextureWrap(wrapR));
3071
3072				sw::FilterType minFilter;
3073				sw::MipmapType mipFilter;
3074                es2sw::ConvertMinFilter(texFilter, &minFilter, &mipFilter, maxAnisotropy);
3075			//	ASSERT(minFilter == es2sw::ConvertMagFilter(magFilter));
3076
3077				device->setTextureFilter(samplerType, samplerIndex, minFilter);
3078			//	device->setTextureFilter(samplerType, samplerIndex, es2sw::ConvertMagFilter(magFilter));
3079				device->setMipmapFilter(samplerType, samplerIndex, mipFilter);
3080				device->setMaxAnisotropy(samplerType, samplerIndex, maxAnisotropy);
3081
3082				applyTexture(samplerType, samplerIndex, texture);
3083            }
3084            else
3085            {
3086                applyTexture(samplerType, samplerIndex, nullptr);
3087            }
3088        }
3089        else
3090        {
3091            applyTexture(samplerType, samplerIndex, nullptr);
3092        }
3093    }
3094}
3095
3096void Context::applyTexture(sw::SamplerType type, int index, Texture *baseTexture)
3097{
3098	Program *program = getCurrentProgram();
3099	int sampler = (type == sw::SAMPLER_PIXEL) ? index : 16 + index;
3100	bool textureUsed = false;
3101
3102	if(type == sw::SAMPLER_PIXEL)
3103	{
3104		textureUsed = program->getPixelShader()->usesSampler(index);
3105	}
3106	else if(type == sw::SAMPLER_VERTEX)
3107	{
3108		textureUsed = program->getVertexShader()->usesSampler(index);
3109	}
3110	else UNREACHABLE(type);
3111
3112	sw::Resource *resource = 0;
3113
3114	if(baseTexture && textureUsed)
3115	{
3116		resource = baseTexture->getResource();
3117	}
3118
3119	device->setTextureResource(sampler, resource);
3120
3121	if(baseTexture && textureUsed)
3122	{
3123		int levelCount = baseTexture->getLevelCount();
3124
3125		if(baseTexture->getTarget() == GL_TEXTURE_2D || baseTexture->getTarget() == GL_TEXTURE_EXTERNAL_OES)
3126		{
3127			Texture2D *texture = static_cast<Texture2D*>(baseTexture);
3128
3129			for(int mipmapLevel = 0; mipmapLevel < MIPMAP_LEVELS; mipmapLevel++)
3130			{
3131				int surfaceLevel = mipmapLevel;
3132
3133				if(surfaceLevel < 0)
3134				{
3135					surfaceLevel = 0;
3136				}
3137				else if(surfaceLevel >= levelCount)
3138				{
3139					surfaceLevel = levelCount - 1;
3140				}
3141
3142				egl::Image *surface = texture->getImage(surfaceLevel);
3143				device->setTextureLevel(sampler, 0, mipmapLevel, surface, sw::TEXTURE_2D);
3144			}
3145		}
3146		else if(baseTexture->getTarget() == GL_TEXTURE_3D_OES)
3147		{
3148			Texture3D *texture = static_cast<Texture3D*>(baseTexture);
3149
3150			for(int mipmapLevel = 0; mipmapLevel < MIPMAP_LEVELS; mipmapLevel++)
3151			{
3152				int surfaceLevel = mipmapLevel;
3153
3154				if(surfaceLevel < 0)
3155				{
3156					surfaceLevel = 0;
3157				}
3158				else if(surfaceLevel >= levelCount)
3159				{
3160					surfaceLevel = levelCount - 1;
3161				}
3162
3163				egl::Image *surface = texture->getImage(surfaceLevel);
3164				device->setTextureLevel(sampler, 0, mipmapLevel, surface, sw::TEXTURE_3D);
3165			}
3166		}
3167		else if(baseTexture->getTarget() == GL_TEXTURE_2D_ARRAY)
3168		{
3169			Texture2DArray *texture = static_cast<Texture2DArray*>(baseTexture);
3170
3171			for(int mipmapLevel = 0; mipmapLevel < MIPMAP_LEVELS; mipmapLevel++)
3172			{
3173				int surfaceLevel = mipmapLevel;
3174
3175				if(surfaceLevel < 0)
3176				{
3177					surfaceLevel = 0;
3178				}
3179				else if(surfaceLevel >= levelCount)
3180				{
3181					surfaceLevel = levelCount - 1;
3182				}
3183
3184				egl::Image *surface = texture->getImage(surfaceLevel);
3185				device->setTextureLevel(sampler, 0, mipmapLevel, surface, sw::TEXTURE_2D_ARRAY);
3186			}
3187		}
3188		else if(baseTexture->getTarget() == GL_TEXTURE_CUBE_MAP)
3189		{
3190			for(int face = 0; face < 6; face++)
3191			{
3192				TextureCubeMap *cubeTexture = static_cast<TextureCubeMap*>(baseTexture);
3193
3194				for(int mipmapLevel = 0; mipmapLevel < MIPMAP_LEVELS; mipmapLevel++)
3195				{
3196					int surfaceLevel = mipmapLevel;
3197
3198					if(surfaceLevel < 0)
3199					{
3200						surfaceLevel = 0;
3201					}
3202					else if(surfaceLevel >= levelCount)
3203					{
3204						surfaceLevel = levelCount - 1;
3205					}
3206
3207					egl::Image *surface = cubeTexture->getImage(face, surfaceLevel);
3208					device->setTextureLevel(sampler, face, mipmapLevel, surface, sw::TEXTURE_CUBE);
3209				}
3210			}
3211		}
3212		else UNIMPLEMENTED();
3213	}
3214	else
3215	{
3216		device->setTextureLevel(sampler, 0, 0, 0, sw::TEXTURE_NULL);
3217	}
3218}
3219
3220void Context::readPixels(GLint x, GLint y, GLsizei width, GLsizei height,
3221                         GLenum format, GLenum type, GLsizei *bufSize, void* pixels)
3222{
3223    Framebuffer *framebuffer = getReadFramebuffer();
3224	int framebufferWidth, framebufferHeight, framebufferSamples;
3225
3226    if(framebuffer->completeness(framebufferWidth, framebufferHeight, framebufferSamples) != GL_FRAMEBUFFER_COMPLETE)
3227    {
3228        return error(GL_INVALID_FRAMEBUFFER_OPERATION);
3229    }
3230
3231    if(getReadFramebufferName() != 0 && framebufferSamples != 0)
3232    {
3233        return error(GL_INVALID_OPERATION);
3234    }
3235
3236	if(format != GL_RGBA || type != GL_UNSIGNED_BYTE)
3237	{
3238		if(format != framebuffer->getImplementationColorReadFormat() || type != framebuffer->getImplementationColorReadType())
3239		{
3240			return error(GL_INVALID_OPERATION);
3241		}
3242	}
3243
3244	GLsizei outputPitch = (mState.packRowLength > 0) ? mState.packRowLength : egl::ComputePitch(width, format, type, mState.packAlignment);
3245
3246	// Sized query sanity check
3247    if(bufSize)
3248    {
3249        int requiredSize = outputPitch * height;
3250        if(requiredSize > *bufSize)
3251        {
3252            return error(GL_INVALID_OPERATION);
3253        }
3254    }
3255
3256    egl::Image *renderTarget = framebuffer->getRenderTarget(0);
3257
3258    if(!renderTarget)
3259    {
3260        return error(GL_OUT_OF_MEMORY);
3261    }
3262
3263	x += mState.packSkipPixels;
3264	y += mState.packSkipRows;
3265	sw::Rect rect = {x, y, x + width, y + height};
3266	rect.clip(0, 0, renderTarget->getWidth(), renderTarget->getHeight());
3267
3268    unsigned char *source = (unsigned char*)renderTarget->lock(rect.x0, rect.y0, sw::LOCK_READONLY);
3269    unsigned char *dest = getPixelPackBuffer() ? (unsigned char*)getPixelPackBuffer()->data() + (ptrdiff_t)pixels : (unsigned char*)pixels;
3270    int inputPitch = (int)renderTarget->getPitch();
3271
3272    for(int j = 0; j < rect.y1 - rect.y0; j++)
3273    {
3274		unsigned short *dest16 = (unsigned short*)dest;
3275		unsigned int *dest32 = (unsigned int*)dest;
3276
3277		if(renderTarget->getInternalFormat() == sw::FORMAT_A8B8G8R8 &&
3278           format == GL_RGBA && type == GL_UNSIGNED_BYTE)
3279        {
3280            memcpy(dest, source, (rect.x1 - rect.x0) * 4);
3281        }
3282		else if(renderTarget->getInternalFormat() == sw::FORMAT_A8R8G8B8 &&
3283                format == GL_RGBA && type == GL_UNSIGNED_BYTE)
3284        {
3285            for(int i = 0; i < rect.x1 - rect.x0; i++)
3286			{
3287				unsigned int argb = *(unsigned int*)(source + 4 * i);
3288
3289				dest32[i] = (argb & 0xFF00FF00) | ((argb & 0x000000FF) << 16) | ((argb & 0x00FF0000) >> 16);
3290			}
3291        }
3292		else if(renderTarget->getInternalFormat() == sw::FORMAT_X8R8G8B8 &&
3293                format == GL_RGBA && type == GL_UNSIGNED_BYTE)
3294        {
3295            for(int i = 0; i < rect.x1 - rect.x0; i++)
3296			{
3297				unsigned int xrgb = *(unsigned int*)(source + 4 * i);
3298
3299				dest32[i] = (xrgb & 0xFF00FF00) | ((xrgb & 0x000000FF) << 16) | ((xrgb & 0x00FF0000) >> 16) | 0xFF000000;
3300			}
3301        }
3302		else if(renderTarget->getInternalFormat() == sw::FORMAT_X8R8G8B8 &&
3303                format == GL_BGRA_EXT && type == GL_UNSIGNED_BYTE)
3304        {
3305            for(int i = 0; i < rect.x1 - rect.x0; i++)
3306			{
3307				unsigned int xrgb = *(unsigned int*)(source + 4 * i);
3308
3309				dest32[i] = xrgb | 0xFF000000;
3310			}
3311        }
3312        else if(renderTarget->getInternalFormat() == sw::FORMAT_A8R8G8B8 &&
3313                format == GL_BGRA_EXT && type == GL_UNSIGNED_BYTE)
3314        {
3315            memcpy(dest, source, (rect.x1 - rect.x0) * 4);
3316        }
3317		else if(renderTarget->getInternalFormat() == sw::FORMAT_A16B16G16R16F &&
3318                format == GL_RGBA && (type == GL_HALF_FLOAT || type == GL_HALF_FLOAT_OES))
3319        {
3320            memcpy(dest, source, (rect.x1 - rect.x0) * 8);
3321        }
3322		else if(renderTarget->getInternalFormat() == sw::FORMAT_A32B32G32R32F &&
3323                format == GL_RGBA && type == GL_FLOAT)
3324        {
3325            memcpy(dest, source, (rect.x1 - rect.x0) * 16);
3326        }
3327		else if(renderTarget->getInternalFormat() == sw::FORMAT_A1R5G5B5 &&
3328                format == GL_BGRA_EXT && type == GL_UNSIGNED_SHORT_1_5_5_5_REV_EXT)
3329        {
3330            memcpy(dest, source, (rect.x1 - rect.x0) * 2);
3331        }
3332		else if(renderTarget->getInternalFormat() == sw::FORMAT_R5G6B5 &&
3333                format == 0x80E0 && type == GL_UNSIGNED_SHORT_5_6_5)   // GL_BGR_EXT
3334        {
3335            memcpy(dest, source, (rect.x1 - rect.x0) * 2);
3336        }
3337		else
3338		{
3339			for(int i = 0; i < rect.x1 - rect.x0; i++)
3340			{
3341				float r;
3342				float g;
3343				float b;
3344				float a;
3345
3346				switch(renderTarget->getInternalFormat())
3347				{
3348				case sw::FORMAT_R5G6B5:
3349					{
3350						unsigned short rgb = *(unsigned short*)(source + 2 * i);
3351
3352						a = 1.0f;
3353						b = (rgb & 0x001F) * (1.0f / 0x001F);
3354						g = (rgb & 0x07E0) * (1.0f / 0x07E0);
3355						r = (rgb & 0xF800) * (1.0f / 0xF800);
3356					}
3357					break;
3358				case sw::FORMAT_A1R5G5B5:
3359					{
3360						unsigned short argb = *(unsigned short*)(source + 2 * i);
3361
3362						a = (argb & 0x8000) ? 1.0f : 0.0f;
3363						b = (argb & 0x001F) * (1.0f / 0x001F);
3364						g = (argb & 0x03E0) * (1.0f / 0x03E0);
3365						r = (argb & 0x7C00) * (1.0f / 0x7C00);
3366					}
3367					break;
3368				case sw::FORMAT_A8R8G8B8:
3369					{
3370						unsigned int argb = *(unsigned int*)(source + 4 * i);
3371
3372						a = (argb & 0xFF000000) * (1.0f / 0xFF000000);
3373						b = (argb & 0x000000FF) * (1.0f / 0x000000FF);
3374						g = (argb & 0x0000FF00) * (1.0f / 0x0000FF00);
3375						r = (argb & 0x00FF0000) * (1.0f / 0x00FF0000);
3376					}
3377					break;
3378				case sw::FORMAT_A8B8G8R8:
3379					{
3380						unsigned int abgr = *(unsigned int*)(source + 4 * i);
3381
3382						a = (abgr & 0xFF000000) * (1.0f / 0xFF000000);
3383						b = (abgr & 0x00FF0000) * (1.0f / 0x00FF0000);
3384						g = (abgr & 0x0000FF00) * (1.0f / 0x0000FF00);
3385						r = (abgr & 0x000000FF) * (1.0f / 0x000000FF);
3386					}
3387					break;
3388				case sw::FORMAT_X8R8G8B8:
3389					{
3390						unsigned int xrgb = *(unsigned int*)(source + 4 * i);
3391
3392						a = 1.0f;
3393						b = (xrgb & 0x000000FF) * (1.0f / 0x000000FF);
3394						g = (xrgb & 0x0000FF00) * (1.0f / 0x0000FF00);
3395						r = (xrgb & 0x00FF0000) * (1.0f / 0x00FF0000);
3396					}
3397					break;
3398				case sw::FORMAT_X8B8G8R8:
3399					{
3400						unsigned int xbgr = *(unsigned int*)(source + 4 * i);
3401
3402						a = 1.0f;
3403						b = (xbgr & 0x00FF0000) * (1.0f / 0x00FF0000);
3404						g = (xbgr & 0x0000FF00) * (1.0f / 0x0000FF00);
3405						r = (xbgr & 0x000000FF) * (1.0f / 0x000000FF);
3406					}
3407					break;
3408				case sw::FORMAT_A2R10G10B10:
3409					{
3410						unsigned int argb = *(unsigned int*)(source + 4 * i);
3411
3412						a = (argb & 0xC0000000) * (1.0f / 0xC0000000);
3413						b = (argb & 0x000003FF) * (1.0f / 0x000003FF);
3414						g = (argb & 0x000FFC00) * (1.0f / 0x000FFC00);
3415						r = (argb & 0x3FF00000) * (1.0f / 0x3FF00000);
3416					}
3417					break;
3418				case sw::FORMAT_A32B32G32R32F:
3419					{
3420						r = *((float*)(source + 16 * i) + 0);
3421						g = *((float*)(source + 16 * i) + 1);
3422						b = *((float*)(source + 16 * i) + 2);
3423						a = *((float*)(source + 16 * i) + 3);
3424					}
3425					break;
3426				case sw::FORMAT_A16B16G16R16F:
3427					{
3428						r = (float)*((sw::half*)(source + 8 * i) + 0);
3429						g = (float)*((sw::half*)(source + 8 * i) + 1);
3430						b = (float)*((sw::half*)(source + 8 * i) + 2);
3431						a = (float)*((sw::half*)(source + 8 * i) + 3);
3432					}
3433					break;
3434				default:
3435					UNIMPLEMENTED();   // FIXME
3436					UNREACHABLE(renderTarget->getInternalFormat());
3437				}
3438
3439				switch(format)
3440				{
3441				case GL_RGBA:
3442					switch(type)
3443					{
3444					case GL_UNSIGNED_BYTE:
3445						dest[4 * i + 0] = (unsigned char)(255 * r + 0.5f);
3446						dest[4 * i + 1] = (unsigned char)(255 * g + 0.5f);
3447						dest[4 * i + 2] = (unsigned char)(255 * b + 0.5f);
3448						dest[4 * i + 3] = (unsigned char)(255 * a + 0.5f);
3449						break;
3450					default: UNREACHABLE(type);
3451					}
3452					break;
3453				case GL_BGRA_EXT:
3454					switch(type)
3455					{
3456					case GL_UNSIGNED_BYTE:
3457						dest[4 * i + 0] = (unsigned char)(255 * b + 0.5f);
3458						dest[4 * i + 1] = (unsigned char)(255 * g + 0.5f);
3459						dest[4 * i + 2] = (unsigned char)(255 * r + 0.5f);
3460						dest[4 * i + 3] = (unsigned char)(255 * a + 0.5f);
3461						break;
3462					case GL_UNSIGNED_SHORT_4_4_4_4_REV_EXT:
3463						// According to the desktop GL spec in the "Transfer of Pixel Rectangles" section
3464						// this type is packed as follows:
3465						//   15   14   13   12   11   10    9    8    7    6    5    4    3    2    1    0
3466						//  --------------------------------------------------------------------------------
3467						// |       4th         |        3rd         |        2nd        |   1st component   |
3468						//  --------------------------------------------------------------------------------
3469						// in the case of BGRA_EXT, B is the first component, G the second, and so forth.
3470						dest16[i] =
3471							((unsigned short)(15 * a + 0.5f) << 12)|
3472							((unsigned short)(15 * r + 0.5f) << 8) |
3473							((unsigned short)(15 * g + 0.5f) << 4) |
3474							((unsigned short)(15 * b + 0.5f) << 0);
3475						break;
3476					case GL_UNSIGNED_SHORT_1_5_5_5_REV_EXT:
3477						// According to the desktop GL spec in the "Transfer of Pixel Rectangles" section
3478						// this type is packed as follows:
3479						//   15   14   13   12   11   10    9    8    7    6    5    4    3    2    1    0
3480						//  --------------------------------------------------------------------------------
3481						// | 4th |          3rd           |           2nd          |      1st component     |
3482						//  --------------------------------------------------------------------------------
3483						// in the case of BGRA_EXT, B is the first component, G the second, and so forth.
3484						dest16[i] =
3485							((unsigned short)(     a + 0.5f) << 15) |
3486							((unsigned short)(31 * r + 0.5f) << 10) |
3487							((unsigned short)(31 * g + 0.5f) << 5) |
3488							((unsigned short)(31 * b + 0.5f) << 0);
3489						break;
3490					default: UNREACHABLE(type);
3491					}
3492					break;
3493				case GL_RGB:
3494					switch(type)
3495					{
3496					case GL_UNSIGNED_SHORT_5_6_5:
3497						dest16[i] =
3498							((unsigned short)(31 * b + 0.5f) << 0) |
3499							((unsigned short)(63 * g + 0.5f) << 5) |
3500							((unsigned short)(31 * r + 0.5f) << 11);
3501						break;
3502					default: UNREACHABLE(type);
3503					}
3504					break;
3505				default: UNREACHABLE(format);
3506				}
3507			}
3508        }
3509
3510		source += inputPitch;
3511		dest += outputPitch;
3512    }
3513
3514	renderTarget->unlock();
3515	renderTarget->release();
3516}
3517
3518void Context::clear(GLbitfield mask)
3519{
3520    Framebuffer *framebuffer = getDrawFramebuffer();
3521
3522    if(!framebuffer || framebuffer->completeness() != GL_FRAMEBUFFER_COMPLETE)
3523    {
3524        return error(GL_INVALID_FRAMEBUFFER_OPERATION);
3525    }
3526
3527    if(!applyRenderTarget())
3528    {
3529        return;
3530    }
3531
3532	if(mask & GL_COLOR_BUFFER_BIT)
3533	{
3534		unsigned int rgbaMask = getColorMask();
3535
3536		if(rgbaMask != 0)
3537		{
3538			unsigned int color = (unorm<8>(mState.colorClearValue.alpha) << 24) |
3539			                     (unorm<8>(mState.colorClearValue.red) << 16) |
3540			                     (unorm<8>(mState.colorClearValue.green) << 8) |
3541			                     (unorm<8>(mState.colorClearValue.blue) << 0);
3542			device->clearColor(color, rgbaMask);
3543		}
3544	}
3545
3546	if(mask & GL_DEPTH_BUFFER_BIT)
3547	{
3548		if(mState.depthMask != 0)
3549		{
3550			float depth = clamp01(mState.depthClearValue);
3551			device->clearDepth(depth);
3552		}
3553	}
3554
3555	if(mask & GL_STENCIL_BUFFER_BIT)
3556	{
3557		if(mState.stencilWritemask != 0)
3558		{
3559			int stencil = mState.stencilClearValue & 0x000000FF;
3560			device->clearStencil(stencil, mState.stencilWritemask);
3561		}
3562	}
3563}
3564
3565void Context::clearColorBuffer(GLint drawbuffer, const GLint *value)
3566{
3567	unsigned int rgbaMask = getColorMask();
3568	if(device && rgbaMask)
3569	{
3570		int x0(0), y0(0), width(0), height(0);
3571		egl::Image* image = getScissoredImage(drawbuffer, x0, y0, width, height, false);
3572
3573		unsigned int color = (value[0] < 0 ? 0 : (value[0] & 0x7F800000) << 1) |
3574		                     (value[1] < 0 ? 0 : (value[1] & 0x7F800000) >> 7) |
3575		                     (value[2] < 0 ? 0 : (value[2] & 0x7F800000) >> 15) |
3576		                     (value[3] < 0 ? 0 : (value[3] & 0x7F800000) >> 23);
3577		image->clearColorBuffer(color, rgbaMask, x0, y0, width, height);
3578	}
3579}
3580
3581void Context::clearColorBuffer(GLint drawbuffer, const GLuint *value)
3582{
3583	unsigned int rgbaMask = getColorMask();
3584	if(device && rgbaMask)
3585	{
3586		int x0(0), y0(0), width(0), height(0);
3587		egl::Image* image = getScissoredImage(drawbuffer, x0, y0, width, height, false);
3588
3589		unsigned int color = (value[0] & 0xFF000000) >> 0 |
3590		                     (value[1] & 0xFF000000) >> 8 |
3591		                     (value[2] & 0xFF000000) >> 16 |
3592		                     (value[3] & 0xFF000000) >> 24;
3593		image->clearColorBuffer(color, rgbaMask, x0, y0, width, height);
3594	}
3595}
3596
3597void Context::clearColorBuffer(GLint drawbuffer, const GLfloat *value)
3598{
3599	unsigned int rgbaMask = getColorMask();
3600	if(device && rgbaMask)
3601	{
3602		int x0(0), y0(0), width(0), height(0);
3603		egl::Image* image = getScissoredImage(drawbuffer, x0, y0, width, height, false);
3604
3605		unsigned int color = (unorm<8>(value[0]) << 24) |
3606		                     (unorm<8>(value[1]) << 16) |
3607		                     (unorm<8>(value[2]) << 8) |
3608		                     (unorm<8>(value[3]) << 0);
3609		image->clearColorBuffer(color, rgbaMask, x0, y0, width, height);
3610	}
3611}
3612
3613void Context::clearDepthBuffer(GLint drawbuffer, const GLfloat *value)
3614{
3615	if(device && mState.depthMask)
3616	{
3617		int x0(0), y0(0), width(0), height(0);
3618		egl::Image* image = getScissoredImage(drawbuffer, x0, y0, width, height, true);
3619
3620		float depth = clamp01(value[0]);
3621		image->clearDepthBuffer(depth, x0, y0, width, height);
3622	}
3623}
3624
3625void Context::clearStencilBuffer(GLint drawbuffer, const GLint *value)
3626{
3627	if(device && mState.stencilWritemask)
3628	{
3629		int x0(0), y0(0), width(0), height(0);
3630		egl::Image* image = getScissoredImage(drawbuffer, x0, y0, width, height, true);
3631
3632		unsigned char stencil = value[0] < 0 ? 0 : static_cast<unsigned char>(value[0] & 0x000000FF);
3633		image->clearStencilBuffer(stencil, static_cast<unsigned char>(mState.stencilWritemask), x0, y0, width, height);
3634	}
3635}
3636
3637void Context::clearDepthStencilBuffer(GLint drawbuffer, GLfloat depth, GLint stencil)
3638{
3639	if(device && (mState.depthMask || mState.stencilWritemask))
3640	{
3641		int x0(0), y0(0), width(0), height(0);
3642		egl::Image* image = getScissoredImage(drawbuffer, x0, y0, width, height, true);
3643
3644		if(mState.stencilWritemask)
3645		{
3646			image->clearStencilBuffer(static_cast<unsigned char>(stencil & 0x000000FF), static_cast<unsigned char>(mState.stencilWritemask), x0, y0, width, height);
3647		}
3648
3649		if(mState.depthMask)
3650		{
3651			image->clearDepthBuffer(clamp01(depth), x0, y0, width, height);
3652		}
3653	}
3654}
3655
3656void Context::drawArrays(GLenum mode, GLint first, GLsizei count, GLsizei instanceCount)
3657{
3658    if(!mState.currentProgram)
3659    {
3660        return error(GL_INVALID_OPERATION);
3661    }
3662
3663    PrimitiveType primitiveType;
3664    int primitiveCount;
3665
3666    if(!es2sw::ConvertPrimitiveType(mode, count, primitiveType, primitiveCount))
3667        return error(GL_INVALID_ENUM);
3668
3669    if(primitiveCount <= 0)
3670    {
3671        return;
3672    }
3673
3674    if(!applyRenderTarget())
3675    {
3676        return;
3677    }
3678
3679    applyState(mode);
3680
3681	for(int i = 0; i < instanceCount; ++i)
3682	{
3683		device->setInstanceID(i);
3684
3685		GLenum err = applyVertexBuffer(0, first, count, i);
3686		if(err != GL_NO_ERROR)
3687		{
3688			return error(err);
3689		}
3690
3691		applyShaders();
3692		applyTextures();
3693
3694		if(!getCurrentProgram()->validateSamplers(false))
3695		{
3696			return error(GL_INVALID_OPERATION);
3697		}
3698
3699		if(!cullSkipsDraw(mode))
3700		{
3701			device->drawPrimitive(primitiveType, primitiveCount);
3702		}
3703	}
3704}
3705
3706void Context::drawElements(GLenum mode, GLuint start, GLuint end, GLsizei count, GLenum type, const void *indices, GLsizei instanceCount)
3707{
3708    if(!mState.currentProgram)
3709    {
3710        return error(GL_INVALID_OPERATION);
3711    }
3712
3713	if(!indices && !getCurrentVertexArray()->getElementArrayBuffer())
3714    {
3715        return error(GL_INVALID_OPERATION);
3716    }
3717
3718    PrimitiveType primitiveType;
3719    int primitiveCount;
3720
3721    if(!es2sw::ConvertPrimitiveType(mode, count, primitiveType, primitiveCount))
3722        return error(GL_INVALID_ENUM);
3723
3724    if(primitiveCount <= 0)
3725    {
3726        return;
3727    }
3728
3729    if(!applyRenderTarget())
3730    {
3731        return;
3732    }
3733
3734    applyState(mode);
3735
3736	for(int i = 0; i < instanceCount; ++i)
3737	{
3738		device->setInstanceID(i);
3739
3740		TranslatedIndexData indexInfo;
3741		GLenum err = applyIndexBuffer(indices, start, end, count, mode, type, &indexInfo);
3742		if(err != GL_NO_ERROR)
3743		{
3744			return error(err);
3745		}
3746
3747		GLsizei vertexCount = indexInfo.maxIndex - indexInfo.minIndex + 1;
3748		err = applyVertexBuffer(-(int)indexInfo.minIndex, indexInfo.minIndex, vertexCount, i);
3749		if(err != GL_NO_ERROR)
3750		{
3751			return error(err);
3752		}
3753
3754		applyShaders();
3755		applyTextures();
3756
3757		if(!getCurrentProgram()->validateSamplers(false))
3758		{
3759			return error(GL_INVALID_OPERATION);
3760		}
3761
3762		if(!cullSkipsDraw(mode))
3763		{
3764			device->drawIndexedPrimitive(primitiveType, indexInfo.indexOffset, primitiveCount, IndexDataManager::typeSize(type));
3765		}
3766	}
3767}
3768
3769void Context::finish()
3770{
3771	device->finish();
3772}
3773
3774void Context::flush()
3775{
3776    // We don't queue anything without processing it as fast as possible
3777}
3778
3779void Context::recordInvalidEnum()
3780{
3781    mInvalidEnum = true;
3782}
3783
3784void Context::recordInvalidValue()
3785{
3786    mInvalidValue = true;
3787}
3788
3789void Context::recordInvalidOperation()
3790{
3791    mInvalidOperation = true;
3792}
3793
3794void Context::recordOutOfMemory()
3795{
3796    mOutOfMemory = true;
3797}
3798
3799void Context::recordInvalidFramebufferOperation()
3800{
3801    mInvalidFramebufferOperation = true;
3802}
3803
3804// Get one of the recorded errors and clear its flag, if any.
3805// [OpenGL ES 2.0.24] section 2.5 page 13.
3806GLenum Context::getError()
3807{
3808    if(mInvalidEnum)
3809    {
3810        mInvalidEnum = false;
3811
3812        return GL_INVALID_ENUM;
3813    }
3814
3815    if(mInvalidValue)
3816    {
3817        mInvalidValue = false;
3818
3819        return GL_INVALID_VALUE;
3820    }
3821
3822    if(mInvalidOperation)
3823    {
3824        mInvalidOperation = false;
3825
3826        return GL_INVALID_OPERATION;
3827    }
3828
3829    if(mOutOfMemory)
3830    {
3831        mOutOfMemory = false;
3832
3833        return GL_OUT_OF_MEMORY;
3834    }
3835
3836    if(mInvalidFramebufferOperation)
3837    {
3838        mInvalidFramebufferOperation = false;
3839
3840        return GL_INVALID_FRAMEBUFFER_OPERATION;
3841    }
3842
3843    return GL_NO_ERROR;
3844}
3845
3846int Context::getSupportedMultisampleCount(int requested)
3847{
3848	int supported = 0;
3849
3850	for(int i = NUM_MULTISAMPLE_COUNTS - 1; i >= 0; i--)
3851	{
3852		if(supported >= requested)
3853		{
3854			return supported;
3855		}
3856
3857		supported = multisampleCount[i];
3858	}
3859
3860	return supported;
3861}
3862
3863void Context::detachBuffer(GLuint buffer)
3864{
3865    // [OpenGL ES 2.0.24] section 2.9 page 22:
3866    // If a buffer object is deleted while it is bound, all bindings to that object in the current context
3867    // (i.e. in the thread that called Delete-Buffers) are reset to zero.
3868
3869    if(getArrayBufferName() == buffer)
3870    {
3871        mState.arrayBuffer = NULL;
3872    }
3873
3874	for(auto vaoIt = mVertexArrayMap.begin(); vaoIt != mVertexArrayMap.end(); vaoIt++)
3875	{
3876		vaoIt->second->detachBuffer(buffer);
3877	}
3878
3879    for(int attribute = 0; attribute < MAX_VERTEX_ATTRIBS; attribute++)
3880    {
3881        if(mState.vertexAttribute[attribute].mBoundBuffer.name() == buffer)
3882        {
3883            mState.vertexAttribute[attribute].mBoundBuffer = NULL;
3884        }
3885    }
3886}
3887
3888void Context::detachTexture(GLuint texture)
3889{
3890    // [OpenGL ES 2.0.24] section 3.8 page 84:
3891    // If a texture object is deleted, it is as if all texture units which are bound to that texture object are
3892    // rebound to texture object zero
3893
3894    for(int type = 0; type < TEXTURE_TYPE_COUNT; type++)
3895    {
3896        for(int sampler = 0; sampler < MAX_COMBINED_TEXTURE_IMAGE_UNITS; sampler++)
3897        {
3898            if(mState.samplerTexture[type][sampler].name() == texture)
3899            {
3900                mState.samplerTexture[type][sampler] = NULL;
3901            }
3902        }
3903    }
3904
3905    // [OpenGL ES 2.0.24] section 4.4 page 112:
3906    // If a texture object is deleted while its image is attached to the currently bound framebuffer, then it is
3907    // as if FramebufferTexture2D had been called, with a texture of 0, for each attachment point to which this
3908    // image was attached in the currently bound framebuffer.
3909
3910    Framebuffer *readFramebuffer = getReadFramebuffer();
3911    Framebuffer *drawFramebuffer = getDrawFramebuffer();
3912
3913    if(readFramebuffer)
3914    {
3915        readFramebuffer->detachTexture(texture);
3916    }
3917
3918    if(drawFramebuffer && drawFramebuffer != readFramebuffer)
3919    {
3920        drawFramebuffer->detachTexture(texture);
3921    }
3922}
3923
3924void Context::detachFramebuffer(GLuint framebuffer)
3925{
3926    // [OpenGL ES 2.0.24] section 4.4 page 107:
3927    // If a framebuffer that is currently bound to the target FRAMEBUFFER is deleted, it is as though
3928    // BindFramebuffer had been executed with the target of FRAMEBUFFER and framebuffer of zero.
3929
3930    if(mState.readFramebuffer == framebuffer)
3931    {
3932        bindReadFramebuffer(0);
3933    }
3934
3935    if(mState.drawFramebuffer == framebuffer)
3936    {
3937        bindDrawFramebuffer(0);
3938    }
3939}
3940
3941void Context::detachRenderbuffer(GLuint renderbuffer)
3942{
3943    // [OpenGL ES 2.0.24] section 4.4 page 109:
3944    // If a renderbuffer that is currently bound to RENDERBUFFER is deleted, it is as though BindRenderbuffer
3945    // had been executed with the target RENDERBUFFER and name of zero.
3946
3947    if(mState.renderbuffer.name() == renderbuffer)
3948    {
3949        bindRenderbuffer(0);
3950    }
3951
3952    // [OpenGL ES 2.0.24] section 4.4 page 111:
3953    // If a renderbuffer object is deleted while its image is attached to the currently bound framebuffer,
3954    // then it is as if FramebufferRenderbuffer had been called, with a renderbuffer of 0, for each attachment
3955    // point to which this image was attached in the currently bound framebuffer.
3956
3957    Framebuffer *readFramebuffer = getReadFramebuffer();
3958    Framebuffer *drawFramebuffer = getDrawFramebuffer();
3959
3960    if(readFramebuffer)
3961    {
3962        readFramebuffer->detachRenderbuffer(renderbuffer);
3963    }
3964
3965    if(drawFramebuffer && drawFramebuffer != readFramebuffer)
3966    {
3967        drawFramebuffer->detachRenderbuffer(renderbuffer);
3968    }
3969}
3970
3971void Context::detachSampler(GLuint sampler)
3972{
3973	// [OpenGL ES 3.0.2] section 3.8.2 pages 123-124:
3974	// If a sampler object that is currently bound to one or more texture units is
3975	// deleted, it is as though BindSampler is called once for each texture unit to
3976	// which the sampler is bound, with unit set to the texture unit and sampler set to zero.
3977	for(size_t textureUnit = 0; textureUnit < MAX_COMBINED_TEXTURE_IMAGE_UNITS; ++textureUnit)
3978	{
3979		gl::BindingPointer<Sampler> &samplerBinding = mState.sampler[textureUnit];
3980		if(samplerBinding.name() == sampler)
3981		{
3982			samplerBinding = NULL;
3983		}
3984	}
3985}
3986
3987bool Context::cullSkipsDraw(GLenum drawMode)
3988{
3989    return mState.cullFaceEnabled && mState.cullMode == GL_FRONT_AND_BACK && isTriangleMode(drawMode);
3990}
3991
3992bool Context::isTriangleMode(GLenum drawMode)
3993{
3994    switch (drawMode)
3995    {
3996      case GL_TRIANGLES:
3997      case GL_TRIANGLE_FAN:
3998      case GL_TRIANGLE_STRIP:
3999        return true;
4000      case GL_POINTS:
4001      case GL_LINES:
4002      case GL_LINE_LOOP:
4003      case GL_LINE_STRIP:
4004        return false;
4005      default: UNREACHABLE(drawMode);
4006    }
4007
4008    return false;
4009}
4010
4011void Context::setVertexAttrib(GLuint index, const GLfloat *values)
4012{
4013    ASSERT(index < MAX_VERTEX_ATTRIBS);
4014
4015    mState.vertexAttribute[index].setCurrentValue(values);
4016
4017    mVertexDataManager->dirtyCurrentValue(index);
4018}
4019
4020void Context::setVertexAttrib(GLuint index, const GLint *values)
4021{
4022	ASSERT(index < MAX_VERTEX_ATTRIBS);
4023
4024	mState.vertexAttribute[index].setCurrentValue(values);
4025
4026	mVertexDataManager->dirtyCurrentValue(index);
4027}
4028
4029void Context::setVertexAttrib(GLuint index, const GLuint *values)
4030{
4031	ASSERT(index < MAX_VERTEX_ATTRIBS);
4032
4033	mState.vertexAttribute[index].setCurrentValue(values);
4034
4035	mVertexDataManager->dirtyCurrentValue(index);
4036}
4037
4038void Context::blitFramebuffer(GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1,
4039                              GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1,
4040                              GLbitfield mask)
4041{
4042    Framebuffer *readFramebuffer = getReadFramebuffer();
4043    Framebuffer *drawFramebuffer = getDrawFramebuffer();
4044
4045	int readBufferWidth, readBufferHeight, readBufferSamples;
4046    int drawBufferWidth, drawBufferHeight, drawBufferSamples;
4047
4048    if(!readFramebuffer || readFramebuffer->completeness(readBufferWidth, readBufferHeight, readBufferSamples) != GL_FRAMEBUFFER_COMPLETE ||
4049       !drawFramebuffer || drawFramebuffer->completeness(drawBufferWidth, drawBufferHeight, drawBufferSamples) != GL_FRAMEBUFFER_COMPLETE)
4050    {
4051        return error(GL_INVALID_FRAMEBUFFER_OPERATION);
4052    }
4053
4054    if(drawBufferSamples > 1)
4055    {
4056        return error(GL_INVALID_OPERATION);
4057    }
4058
4059    sw::SliceRect sourceRect;
4060    sw::SliceRect destRect;
4061	bool flipX = (srcX0 < srcX1) ^ (dstX0 < dstX1);
4062	bool flipy = (srcY0 < srcY1) ^ (dstY0 < dstY1);
4063
4064    if(srcX0 < srcX1)
4065    {
4066        sourceRect.x0 = srcX0;
4067        sourceRect.x1 = srcX1;
4068    }
4069    else
4070    {
4071        sourceRect.x0 = srcX1;
4072        sourceRect.x1 = srcX0;
4073    }
4074
4075	if(dstX0 < dstX1)
4076	{
4077		destRect.x0 = dstX0;
4078		destRect.x1 = dstX1;
4079	}
4080	else
4081	{
4082		destRect.x0 = dstX1;
4083		destRect.x1 = dstX0;
4084	}
4085
4086    if(srcY0 < srcY1)
4087    {
4088        sourceRect.y0 = srcY0;
4089        sourceRect.y1 = srcY1;
4090    }
4091    else
4092    {
4093        sourceRect.y0 = srcY1;
4094        sourceRect.y1 = srcY0;
4095    }
4096
4097	if(dstY0 < dstY1)
4098	{
4099		destRect.y0 = dstY0;
4100		destRect.y1 = dstY1;
4101	}
4102	else
4103	{
4104		destRect.y0 = dstY1;
4105		destRect.y1 = dstY0;
4106	}
4107
4108	sw::Rect sourceScissoredRect = sourceRect;
4109    sw::Rect destScissoredRect = destRect;
4110
4111    if(mState.scissorTestEnabled)   // Only write to parts of the destination framebuffer which pass the scissor test
4112    {
4113        if(destRect.x0 < mState.scissorX)
4114        {
4115            int xDiff = mState.scissorX - destRect.x0;
4116            destScissoredRect.x0 = mState.scissorX;
4117            sourceScissoredRect.x0 += xDiff;
4118        }
4119
4120        if(destRect.x1 > mState.scissorX + mState.scissorWidth)
4121        {
4122            int xDiff = destRect.x1 - (mState.scissorX + mState.scissorWidth);
4123            destScissoredRect.x1 = mState.scissorX + mState.scissorWidth;
4124            sourceScissoredRect.x1 -= xDiff;
4125        }
4126
4127        if(destRect.y0 < mState.scissorY)
4128        {
4129            int yDiff = mState.scissorY - destRect.y0;
4130            destScissoredRect.y0 = mState.scissorY;
4131            sourceScissoredRect.y0 += yDiff;
4132        }
4133
4134        if(destRect.y1 > mState.scissorY + mState.scissorHeight)
4135        {
4136            int yDiff = destRect.y1 - (mState.scissorY + mState.scissorHeight);
4137            destScissoredRect.y1 = mState.scissorY + mState.scissorHeight;
4138            sourceScissoredRect.y1 -= yDiff;
4139        }
4140    }
4141
4142    sw::Rect sourceTrimmedRect = sourceScissoredRect;
4143    sw::Rect destTrimmedRect = destScissoredRect;
4144
4145    // The source & destination rectangles also may need to be trimmed if they fall out of the bounds of
4146    // the actual draw and read surfaces.
4147    if(sourceTrimmedRect.x0 < 0)
4148    {
4149        int xDiff = 0 - sourceTrimmedRect.x0;
4150        sourceTrimmedRect.x0 = 0;
4151        destTrimmedRect.x0 += xDiff;
4152    }
4153
4154    if(sourceTrimmedRect.x1 > readBufferWidth)
4155    {
4156        int xDiff = sourceTrimmedRect.x1 - readBufferWidth;
4157        sourceTrimmedRect.x1 = readBufferWidth;
4158        destTrimmedRect.x1 -= xDiff;
4159    }
4160
4161    if(sourceTrimmedRect.y0 < 0)
4162    {
4163        int yDiff = 0 - sourceTrimmedRect.y0;
4164        sourceTrimmedRect.y0 = 0;
4165        destTrimmedRect.y0 += yDiff;
4166    }
4167
4168    if(sourceTrimmedRect.y1 > readBufferHeight)
4169    {
4170        int yDiff = sourceTrimmedRect.y1 - readBufferHeight;
4171        sourceTrimmedRect.y1 = readBufferHeight;
4172        destTrimmedRect.y1 -= yDiff;
4173    }
4174
4175    if(destTrimmedRect.x0 < 0)
4176    {
4177        int xDiff = 0 - destTrimmedRect.x0;
4178        destTrimmedRect.x0 = 0;
4179        sourceTrimmedRect.x0 += xDiff;
4180    }
4181
4182    if(destTrimmedRect.x1 > drawBufferWidth)
4183    {
4184        int xDiff = destTrimmedRect.x1 - drawBufferWidth;
4185        destTrimmedRect.x1 = drawBufferWidth;
4186        sourceTrimmedRect.x1 -= xDiff;
4187    }
4188
4189    if(destTrimmedRect.y0 < 0)
4190    {
4191        int yDiff = 0 - destTrimmedRect.y0;
4192        destTrimmedRect.y0 = 0;
4193        sourceTrimmedRect.y0 += yDiff;
4194    }
4195
4196    if(destTrimmedRect.y1 > drawBufferHeight)
4197    {
4198        int yDiff = destTrimmedRect.y1 - drawBufferHeight;
4199        destTrimmedRect.y1 = drawBufferHeight;
4200        sourceTrimmedRect.y1 -= yDiff;
4201    }
4202
4203    bool partialBufferCopy = false;
4204
4205    if(sourceTrimmedRect.y1 - sourceTrimmedRect.y0 < readBufferHeight ||
4206       sourceTrimmedRect.x1 - sourceTrimmedRect.x0 < readBufferWidth ||
4207       destTrimmedRect.y1 - destTrimmedRect.y0 < drawBufferHeight ||
4208       destTrimmedRect.x1 - destTrimmedRect.x0 < drawBufferWidth ||
4209       sourceTrimmedRect.y0 != 0 || destTrimmedRect.y0 != 0 || sourceTrimmedRect.x0 != 0 || destTrimmedRect.x0 != 0)
4210    {
4211        partialBufferCopy = true;
4212    }
4213
4214	bool blitRenderTarget = false;
4215    bool blitDepthStencil = false;
4216
4217    if(mask & GL_COLOR_BUFFER_BIT)
4218    {
4219        const bool validReadType = readFramebuffer->getColorbufferType(getReadFramebufferColorIndex()) == GL_TEXTURE_2D ||
4220                                   readFramebuffer->getColorbufferType(getReadFramebufferColorIndex()) == GL_RENDERBUFFER;
4221        const bool validDrawType = drawFramebuffer->getColorbufferType(0) == GL_TEXTURE_2D ||
4222                                   drawFramebuffer->getColorbufferType(0) == GL_RENDERBUFFER;
4223        if(!validReadType || !validDrawType)
4224        {
4225            return error(GL_INVALID_OPERATION);
4226        }
4227
4228        if(partialBufferCopy && readBufferSamples > 1)
4229        {
4230            return error(GL_INVALID_OPERATION);
4231        }
4232
4233        blitRenderTarget = true;
4234    }
4235
4236    if(mask & (GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT))
4237    {
4238        Renderbuffer *readDSBuffer = NULL;
4239        Renderbuffer *drawDSBuffer = NULL;
4240
4241        // We support OES_packed_depth_stencil, and do not support a separately attached depth and stencil buffer, so if we have
4242        // both a depth and stencil buffer, it will be the same buffer.
4243
4244        if(mask & GL_DEPTH_BUFFER_BIT)
4245        {
4246            if(readFramebuffer->getDepthbuffer() && drawFramebuffer->getDepthbuffer())
4247            {
4248                if(readFramebuffer->getDepthbufferType() != drawFramebuffer->getDepthbufferType())
4249                {
4250                    return error(GL_INVALID_OPERATION);
4251                }
4252
4253                blitDepthStencil = true;
4254                readDSBuffer = readFramebuffer->getDepthbuffer();
4255                drawDSBuffer = drawFramebuffer->getDepthbuffer();
4256            }
4257        }
4258
4259        if(mask & GL_STENCIL_BUFFER_BIT)
4260        {
4261            if(readFramebuffer->getStencilbuffer() && drawFramebuffer->getStencilbuffer())
4262            {
4263                if(readFramebuffer->getStencilbufferType() != drawFramebuffer->getStencilbufferType())
4264                {
4265                    return error(GL_INVALID_OPERATION);
4266                }
4267
4268                blitDepthStencil = true;
4269                readDSBuffer = readFramebuffer->getStencilbuffer();
4270                drawDSBuffer = drawFramebuffer->getStencilbuffer();
4271            }
4272        }
4273
4274        if(partialBufferCopy)
4275        {
4276            ERR("Only whole-buffer depth and stencil blits are supported by this implementation.");
4277            return error(GL_INVALID_OPERATION);   // Only whole-buffer copies are permitted
4278        }
4279
4280        if((drawDSBuffer && drawDSBuffer->getSamples() > 1) ||
4281           (readDSBuffer && readDSBuffer->getSamples() > 1))
4282        {
4283            return error(GL_INVALID_OPERATION);
4284        }
4285    }
4286
4287    if(blitRenderTarget || blitDepthStencil)
4288    {
4289        if(blitRenderTarget)
4290        {
4291            egl::Image *readRenderTarget = readFramebuffer->getReadRenderTarget();
4292            egl::Image *drawRenderTarget = drawFramebuffer->getRenderTarget(0);
4293
4294			if(flipX)
4295			{
4296				swap(destRect.x0, destRect.x1);
4297			}
4298			if(flipy)
4299			{
4300				swap(destRect.y0, destRect.y1);
4301			}
4302
4303            bool success = device->stretchRect(readRenderTarget, &sourceRect, drawRenderTarget, &destRect, false);
4304
4305            readRenderTarget->release();
4306            drawRenderTarget->release();
4307
4308            if(!success)
4309            {
4310                ERR("BlitFramebuffer failed.");
4311                return;
4312            }
4313        }
4314
4315        if(blitDepthStencil)
4316        {
4317            bool success = device->stretchRect(readFramebuffer->getDepthStencil(), NULL, drawFramebuffer->getDepthStencil(), NULL, false);
4318
4319            if(!success)
4320            {
4321                ERR("BlitFramebuffer failed.");
4322                return;
4323            }
4324        }
4325    }
4326}
4327
4328void Context::bindTexImage(egl::Surface *surface)
4329{
4330	es2::Texture2D *textureObject = getTexture2D();
4331
4332    if(textureObject)
4333    {
4334		textureObject->bindTexImage(surface);
4335	}
4336}
4337
4338EGLenum Context::validateSharedImage(EGLenum target, GLuint name, GLuint textureLevel)
4339{
4340    GLenum textureTarget = GL_NONE;
4341
4342    switch(target)
4343    {
4344    case EGL_GL_TEXTURE_2D_KHR:
4345        textureTarget = GL_TEXTURE_2D;
4346        break;
4347    case EGL_GL_TEXTURE_CUBE_MAP_POSITIVE_X_KHR:
4348    case EGL_GL_TEXTURE_CUBE_MAP_NEGATIVE_X_KHR:
4349    case EGL_GL_TEXTURE_CUBE_MAP_POSITIVE_Y_KHR:
4350    case EGL_GL_TEXTURE_CUBE_MAP_NEGATIVE_Y_KHR:
4351    case EGL_GL_TEXTURE_CUBE_MAP_POSITIVE_Z_KHR:
4352    case EGL_GL_TEXTURE_CUBE_MAP_NEGATIVE_Z_KHR:
4353        textureTarget = GL_TEXTURE_CUBE_MAP;
4354        break;
4355    case EGL_GL_RENDERBUFFER_KHR:
4356        break;
4357    default:
4358        return EGL_BAD_PARAMETER;
4359    }
4360
4361    if(textureLevel >= es2::IMPLEMENTATION_MAX_TEXTURE_LEVELS)
4362    {
4363        return EGL_BAD_MATCH;
4364    }
4365
4366    if(textureTarget != GL_NONE)
4367    {
4368        es2::Texture *texture = getTexture(name);
4369
4370        if(!texture || texture->getTarget() != textureTarget)
4371        {
4372            return EGL_BAD_PARAMETER;
4373        }
4374
4375        if(texture->isShared(textureTarget, textureLevel))   // Bound to an EGLSurface or already an EGLImage sibling
4376        {
4377            return EGL_BAD_ACCESS;
4378        }
4379
4380        if(textureLevel != 0 && !texture->isSamplerComplete())
4381        {
4382            return EGL_BAD_PARAMETER;
4383        }
4384
4385        if(textureLevel == 0 && !(texture->isSamplerComplete() && texture->getLevelCount() == 1))
4386        {
4387            return EGL_BAD_PARAMETER;
4388        }
4389    }
4390    else if(target == EGL_GL_RENDERBUFFER_KHR)
4391    {
4392        es2::Renderbuffer *renderbuffer = getRenderbuffer(name);
4393
4394        if(!renderbuffer)
4395        {
4396            return EGL_BAD_PARAMETER;
4397        }
4398
4399        if(renderbuffer->isShared())   // Already an EGLImage sibling
4400        {
4401            return EGL_BAD_ACCESS;
4402        }
4403    }
4404    else UNREACHABLE(target);
4405
4406	return EGL_SUCCESS;
4407}
4408
4409egl::Image *Context::createSharedImage(EGLenum target, GLuint name, GLuint textureLevel)
4410{
4411	GLenum textureTarget = GL_NONE;
4412
4413    switch(target)
4414    {
4415    case EGL_GL_TEXTURE_2D_KHR:                  textureTarget = GL_TEXTURE_2D;                  break;
4416    case EGL_GL_TEXTURE_CUBE_MAP_POSITIVE_X_KHR: textureTarget = GL_TEXTURE_CUBE_MAP_POSITIVE_X; break;
4417    case EGL_GL_TEXTURE_CUBE_MAP_NEGATIVE_X_KHR: textureTarget = GL_TEXTURE_CUBE_MAP_NEGATIVE_X; break;
4418    case EGL_GL_TEXTURE_CUBE_MAP_POSITIVE_Y_KHR: textureTarget = GL_TEXTURE_CUBE_MAP_POSITIVE_Y; break;
4419    case EGL_GL_TEXTURE_CUBE_MAP_NEGATIVE_Y_KHR: textureTarget = GL_TEXTURE_CUBE_MAP_NEGATIVE_Y; break;
4420    case EGL_GL_TEXTURE_CUBE_MAP_POSITIVE_Z_KHR: textureTarget = GL_TEXTURE_CUBE_MAP_POSITIVE_Z; break;
4421    case EGL_GL_TEXTURE_CUBE_MAP_NEGATIVE_Z_KHR: textureTarget = GL_TEXTURE_CUBE_MAP_NEGATIVE_Z; break;
4422    }
4423
4424    if(textureTarget != GL_NONE)
4425    {
4426        es2::Texture *texture = getTexture(name);
4427
4428        return texture->createSharedImage(textureTarget, textureLevel);
4429    }
4430    else if(target == EGL_GL_RENDERBUFFER_KHR)
4431    {
4432        es2::Renderbuffer *renderbuffer = getRenderbuffer(name);
4433
4434        return renderbuffer->createSharedImage();
4435    }
4436    else UNREACHABLE(target);
4437
4438	return 0;
4439}
4440
4441Device *Context::getDevice()
4442{
4443	return device;
4444}
4445
4446const GLubyte* Context::getExtensions(GLuint index, GLuint* numExt) const
4447{
4448	// Keep list sorted in following order:
4449	// OES extensions
4450	// EXT extensions
4451	// Vendor extensions
4452	static const GLubyte* extensions[] = {
4453		(const GLubyte*)"GL_OES_compressed_ETC1_RGB8_texture",
4454		(const GLubyte*)"GL_OES_depth_texture",
4455		(const GLubyte*)"GL_OES_depth_texture_cube_map",
4456		(const GLubyte*)"GL_OES_EGL_image",
4457		(const GLubyte*)"GL_OES_EGL_image_external",
4458		(const GLubyte*)"GL_OES_element_index_uint",
4459		(const GLubyte*)"GL_OES_packed_depth_stencil",
4460		(const GLubyte*)"GL_OES_rgb8_rgba8",
4461		(const GLubyte*)"GL_OES_standard_derivatives",
4462		(const GLubyte*)"GL_OES_texture_float",
4463		(const GLubyte*)"GL_OES_texture_float_linear",
4464		(const GLubyte*)"GL_OES_texture_half_float",
4465		(const GLubyte*)"GL_OES_texture_half_float_linear",
4466		(const GLubyte*)"GL_OES_texture_npot",
4467		(const GLubyte*)"GL_OES_texture_3D",
4468		(const GLubyte*)"GL_EXT_blend_minmax",
4469		(const GLubyte*)"GL_EXT_occlusion_query_boolean",
4470		(const GLubyte*)"GL_EXT_read_format_bgra",
4471#if (S3TC_SUPPORT)
4472		(const GLubyte*)"GL_EXT_texture_compression_dxt1",
4473#endif
4474		(const GLubyte*)"GL_EXT_texture_filter_anisotropic",
4475		(const GLubyte*)"GL_EXT_texture_format_BGRA8888",
4476		(const GLubyte*)"GL_ANGLE_framebuffer_blit",
4477		(const GLubyte*)"GL_NV_framebuffer_blit",
4478		(const GLubyte*)"GL_ANGLE_framebuffer_multisample",
4479#if (S3TC_SUPPORT)
4480		(const GLubyte*)"GL_ANGLE_texture_compression_dxt3",
4481		(const GLubyte*)"GL_ANGLE_texture_compression_dxt5",
4482#endif
4483		(const GLubyte*)"GL_NV_fence",
4484		(const GLubyte*)"GL_EXT_instanced_arrays",
4485		(const GLubyte*)"GL_ANGLE_instanced_arrays",
4486	};
4487	static const GLuint numExtensions = sizeof(extensions) / sizeof(*extensions);
4488
4489	if(numExt)
4490	{
4491		*numExt = numExtensions;
4492		return nullptr;
4493	}
4494
4495	if(index == GL_INVALID_INDEX)
4496	{
4497		static GLubyte* extensionsCat = nullptr;
4498		if((extensionsCat == nullptr) && (numExtensions > 0))
4499		{
4500			int totalLength = numExtensions; // 1 space between each extension name + terminating null
4501			for(int i = 0; i < numExtensions; ++i)
4502			{
4503				totalLength += strlen(reinterpret_cast<const char*>(extensions[i]));
4504			}
4505			extensionsCat = new GLubyte[totalLength];
4506			extensionsCat[0] = '\0';
4507			for(int i = 0; i < numExtensions; ++i)
4508			{
4509				if(i != 0)
4510				{
4511					strcat(reinterpret_cast<char*>(extensionsCat), " ");
4512				}
4513				strcat(reinterpret_cast<char*>(extensionsCat), reinterpret_cast<const char*>(extensions[i]));
4514			}
4515		}
4516		return extensionsCat;
4517	}
4518
4519	if(index >= numExtensions)
4520	{
4521		return nullptr;
4522	}
4523
4524	return extensions[index];
4525}
4526
4527}
4528
4529egl::Context *es2CreateContext(const egl::Config *config, const egl::Context *shareContext, int clientVersion)
4530{
4531	ASSERT(!shareContext || shareContext->getClientVersion() == clientVersion);   // Should be checked by eglCreateContext
4532	return new es2::Context(config, static_cast<const es2::Context*>(shareContext), clientVersion);
4533}
4534