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