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