Context.cpp revision f1f127931fb01049a986e4733e43ff4bbc6f5a50
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		UNIMPLEMENTED();
2121		*params = IMPLEMENTATION_MAX_COLOR_ATTACHMENTS;
2122		break;
2123	case GL_MAX_COMBINED_FRAGMENT_UNIFORM_COMPONENTS: // integer, at least 50048
2124		*params = MAX_COMBINED_FRAGMENT_UNIFORM_COMPONENTS;
2125		break;
2126	case GL_MAX_COMBINED_UNIFORM_BLOCKS: // integer, at least 70
2127		UNIMPLEMENTED();
2128		*params = 70;
2129		break;
2130	case GL_MAX_COMBINED_VERTEX_UNIFORM_COMPONENTS: // integer, at least 50176
2131		*params = MAX_COMBINED_VERTEX_UNIFORM_COMPONENTS;
2132		break;
2133	case GL_MAX_DRAW_BUFFERS: // integer, at least 8
2134		UNIMPLEMENTED();
2135		*params = IMPLEMENTATION_MAX_DRAW_BUFFERS;
2136		break;
2137	case GL_MAX_ELEMENT_INDEX:
2138		*params = MAX_ELEMENT_INDEX;
2139		break;
2140	case GL_MAX_ELEMENTS_INDICES:
2141		*params = MAX_ELEMENTS_INDICES;
2142		break;
2143	case GL_MAX_ELEMENTS_VERTICES:
2144		*params = MAX_ELEMENTS_VERTICES;
2145		break;
2146	case GL_MAX_FRAGMENT_INPUT_COMPONENTS: // integer, at least 128
2147		UNIMPLEMENTED();
2148		*params = 128;
2149		break;
2150	case GL_MAX_FRAGMENT_UNIFORM_BLOCKS: // integer, at least 12
2151		*params = MAX_FRAGMENT_UNIFORM_BLOCKS;
2152		break;
2153	case GL_MAX_FRAGMENT_UNIFORM_COMPONENTS: // integer, at least 896
2154		*params = MAX_FRAGMENT_UNIFORM_COMPONENTS;
2155		break;
2156	case GL_MAX_PROGRAM_TEXEL_OFFSET: // integer, minimum is 7
2157		UNIMPLEMENTED();
2158		*params = 7;
2159		break;
2160	case GL_MAX_SERVER_WAIT_TIMEOUT: // integer
2161		UNIMPLEMENTED();
2162		*params = 0;
2163		break;
2164	case GL_MAX_TEXTURE_LOD_BIAS: // integer,  at least 2.0
2165		UNIMPLEMENTED();
2166		*params = 2;
2167		break;
2168	case GL_MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS: // integer, at least 64
2169		UNIMPLEMENTED();
2170		*params = 64;
2171		break;
2172	case GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS: // integer, at least 4
2173		UNIMPLEMENTED();
2174		*params = IMPLEMENTATION_MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS;
2175		break;
2176	case GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS: // integer, at least 4
2177		UNIMPLEMENTED();
2178		*params = 4;
2179		break;
2180	case GL_MAX_UNIFORM_BLOCK_SIZE: // integer, at least 16384
2181		*params = MAX_UNIFORM_BLOCK_SIZE;
2182		break;
2183	case GL_MAX_UNIFORM_BUFFER_BINDINGS: // integer, at least 24
2184		*params = IMPLEMENTATION_MAX_UNIFORM_BUFFER_BINDINGS;
2185		break;
2186	case GL_MAX_VARYING_COMPONENTS: // integer, at least 60
2187		UNIMPLEMENTED();
2188		*params = 60;
2189		break;
2190	case GL_MAX_VERTEX_OUTPUT_COMPONENTS: // integer,  at least 64
2191		UNIMPLEMENTED();
2192		*params = 64;
2193		break;
2194	case GL_MAX_VERTEX_UNIFORM_BLOCKS: // integer,  at least 12
2195		*params = MAX_VERTEX_UNIFORM_BLOCKS;
2196		break;
2197	case GL_MAX_VERTEX_UNIFORM_COMPONENTS: // integer,  at least 1024
2198		*params = MAX_VERTEX_UNIFORM_COMPONENTS;
2199		break;
2200	case GL_MIN_PROGRAM_TEXEL_OFFSET: // integer, maximum is -8
2201		UNIMPLEMENTED();
2202		*params = -8;
2203		break;
2204	case GL_MINOR_VERSION: // integer
2205		UNIMPLEMENTED();
2206		*params = 0;
2207		break;
2208	case GL_NUM_EXTENSIONS: // integer
2209		GLuint numExtensions;
2210		getExtensions(0, &numExtensions);
2211		*params = numExtensions;
2212		break;
2213	case GL_NUM_PROGRAM_BINARY_FORMATS: // integer, at least 0
2214		UNIMPLEMENTED();
2215		*params = 0;
2216		break;
2217	case GL_PACK_ROW_LENGTH: // integer, initially 0
2218		*params = mState.packRowLength;
2219		break;
2220	case GL_PACK_SKIP_PIXELS: // integer, initially 0
2221		*params = mState.packSkipPixels;
2222		break;
2223	case GL_PACK_SKIP_ROWS: // integer, initially 0
2224		*params = mState.packSkipRows;
2225		break;
2226	case GL_PIXEL_PACK_BUFFER_BINDING: // integer, initially 0
2227		if(clientVersion >= 3)
2228		{
2229			*params = mState.pixelPackBuffer.name();
2230		}
2231		else
2232		{
2233			return false;
2234		}
2235		break;
2236	case GL_PIXEL_UNPACK_BUFFER_BINDING: // integer, initially 0
2237		if(clientVersion >= 3)
2238		{
2239			*params = mState.pixelUnpackBuffer.name();
2240		}
2241		else
2242		{
2243			return false;
2244		}
2245		break;
2246	case GL_PROGRAM_BINARY_FORMATS: // integer[GL_NUM_PROGRAM_BINARY_FORMATS​]
2247		UNIMPLEMENTED();
2248		*params = 0;
2249		break;
2250	case GL_READ_BUFFER: // symbolic constant,  initial value is GL_BACK​
2251		*params = getReadFramebuffer()->getReadBuffer();
2252		break;
2253	case GL_SAMPLER_BINDING: // GLint, default 0
2254		*params = mState.sampler[mState.activeSampler].name();
2255		break;
2256	case GL_UNIFORM_BUFFER_BINDING: // name, initially 0
2257		if(clientVersion >= 3)
2258		{
2259			*params = mState.genericUniformBuffer.name();
2260		}
2261		else
2262		{
2263			return false;
2264		}
2265		break;
2266	case GL_UNIFORM_BUFFER_OFFSET_ALIGNMENT: // integer, defaults to 1
2267		*params = IMPLEMENTATION_UNIFORM_BUFFER_OFFSET_ALIGNMENT;
2268		break;
2269	case GL_UNIFORM_BUFFER_SIZE: // indexed[n] 64-bit integer, initially 0
2270		if(clientVersion >= 3)
2271		{
2272			*params = mState.genericUniformBuffer->size();
2273		}
2274		else
2275		{
2276			return false;
2277		}
2278		break;
2279	case GL_UNIFORM_BUFFER_START: // indexed[n] 64-bit integer, initially 0
2280		if(clientVersion >= 3)
2281		{
2282			*params = mState.genericUniformBuffer->offset();
2283		}
2284		else
2285		{
2286			return false;
2287		}
2288		*params = 0;
2289		break;
2290	case GL_UNPACK_IMAGE_HEIGHT: // integer, initially 0
2291		*params = mState.unpackInfo.imageHeight;
2292		break;
2293	case GL_UNPACK_ROW_LENGTH: // integer, initially 0
2294		*params = mState.unpackInfo.rowLength;
2295		break;
2296	case GL_UNPACK_SKIP_IMAGES: // integer, initially 0
2297		*params = mState.unpackInfo.skipImages;
2298		break;
2299	case GL_UNPACK_SKIP_PIXELS: // integer, initially 0
2300		*params = mState.unpackInfo.skipPixels;
2301		break;
2302	case GL_UNPACK_SKIP_ROWS: // integer, initially 0
2303		*params = mState.unpackInfo.skipRows;
2304		break;
2305	case GL_VERTEX_ARRAY_BINDING: // GLint, initially 0
2306		*params = getCurrentVertexArray()->name;
2307		break;
2308	case GL_TRANSFORM_FEEDBACK_BINDING:
2309		{
2310			TransformFeedback* transformFeedback = getTransformFeedback(mState.transformFeedback);
2311			if(transformFeedback)
2312			{
2313				*params = transformFeedback->name;
2314			}
2315			else
2316			{
2317				return false;
2318			}
2319		}
2320		break;
2321	case GL_TRANSFORM_FEEDBACK_BUFFER_BINDING:
2322		{
2323			TransformFeedback* transformFeedback = getTransformFeedback(mState.transformFeedback);
2324			if(transformFeedback)
2325			{
2326				*params = transformFeedback->getGenericBufferName();
2327			}
2328			else
2329			{
2330				return false;
2331			}
2332		}
2333		break;
2334	default:
2335        return false;
2336    }
2337
2338    return true;
2339}
2340
2341template bool Context::getTransformFeedbackiv<GLint>(GLuint index, GLenum pname, GLint *param) const;
2342template bool Context::getTransformFeedbackiv<GLint64>(GLuint index, GLenum pname, GLint64 *param) const;
2343
2344template<typename T> bool Context::getTransformFeedbackiv(GLuint index, GLenum pname, T *param) const
2345{
2346	TransformFeedback* transformFeedback = getTransformFeedback(mState.transformFeedback);
2347	if(!transformFeedback)
2348	{
2349		return false;
2350	}
2351
2352	switch(pname)
2353	{
2354	case GL_TRANSFORM_FEEDBACK_BINDING: // GLint, initially 0
2355		*param = transformFeedback->name;
2356		break;
2357	case GL_TRANSFORM_FEEDBACK_ACTIVE: // boolean, initially GL_FALSE
2358		*param = transformFeedback->isActive();
2359		break;
2360	case GL_TRANSFORM_FEEDBACK_BUFFER_BINDING: // name, initially 0
2361		*param = transformFeedback->getBufferName(index);
2362		break;
2363	case GL_TRANSFORM_FEEDBACK_PAUSED: // boolean, initially GL_FALSE
2364		*param = transformFeedback->isPaused();
2365		break;
2366	case GL_TRANSFORM_FEEDBACK_BUFFER_SIZE: // indexed[n] 64-bit integer, initially 0
2367		if(transformFeedback->getBuffer(index))
2368		{
2369			*param = transformFeedback->getSize(index);
2370			break;
2371		}
2372		else return false;
2373	case GL_TRANSFORM_FEEDBACK_BUFFER_START: // indexed[n] 64-bit integer, initially 0
2374		if(transformFeedback->getBuffer(index))
2375		{
2376			*param = transformFeedback->getOffset(index);
2377		break;
2378		}
2379		else return false;
2380	default:
2381		return false;
2382	}
2383
2384	return true;
2385}
2386
2387template bool Context::getUniformBufferiv<GLint>(GLuint index, GLenum pname, GLint *param) const;
2388template bool Context::getUniformBufferiv<GLint64>(GLuint index, GLenum pname, GLint64 *param) const;
2389
2390template<typename T> bool Context::getUniformBufferiv(GLuint index, GLenum pname, T *param) const
2391{
2392	const BufferBinding& uniformBuffer = mState.uniformBuffers[index];
2393
2394	switch(pname)
2395	{
2396	case GL_UNIFORM_BUFFER_BINDING: // name, initially 0
2397		*param = uniformBuffer.get().name();
2398		break;
2399	case GL_UNIFORM_BUFFER_SIZE: // indexed[n] 64-bit integer, initially 0
2400		*param = uniformBuffer.getSize();
2401		break;
2402	case GL_UNIFORM_BUFFER_START: // indexed[n] 64-bit integer, initially 0
2403		*param = uniformBuffer.getOffset();
2404		break;
2405	default:
2406		return false;
2407	}
2408
2409	return true;
2410}
2411
2412bool Context::getQueryParameterInfo(GLenum pname, GLenum *type, unsigned int *numParams) const
2413{
2414    // Please note: the query type returned for DEPTH_CLEAR_VALUE in this implementation
2415    // is FLOAT rather than INT, as would be suggested by the GL ES 2.0 spec. This is due
2416    // to the fact that it is stored internally as a float, and so would require conversion
2417    // if returned from Context::getIntegerv. Since this conversion is already implemented
2418    // in the case that one calls glGetIntegerv to retrieve a float-typed state variable, we
2419    // place DEPTH_CLEAR_VALUE with the floats. This should make no difference to the calling
2420    // application.
2421    switch(pname)
2422    {
2423    case GL_COMPRESSED_TEXTURE_FORMATS:
2424		{
2425            *type = GL_INT;
2426			*numParams = NUM_COMPRESSED_TEXTURE_FORMATS;
2427        }
2428		break;
2429    case GL_SHADER_BINARY_FORMATS:
2430        {
2431            *type = GL_INT;
2432            *numParams = 0;
2433        }
2434        break;
2435    case GL_MAX_VERTEX_ATTRIBS:
2436    case GL_MAX_VERTEX_UNIFORM_VECTORS:
2437    case GL_MAX_VARYING_VECTORS:
2438    case GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS:
2439    case GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS:
2440    case GL_MAX_TEXTURE_IMAGE_UNITS:
2441    case GL_MAX_FRAGMENT_UNIFORM_VECTORS:
2442    case GL_MAX_RENDERBUFFER_SIZE:
2443    case GL_NUM_SHADER_BINARY_FORMATS:
2444    case GL_NUM_COMPRESSED_TEXTURE_FORMATS:
2445    case GL_ARRAY_BUFFER_BINDING:
2446    case GL_FRAMEBUFFER_BINDING: // Same as GL_DRAW_FRAMEBUFFER_BINDING_ANGLE
2447    case GL_READ_FRAMEBUFFER_BINDING_ANGLE:
2448    case GL_RENDERBUFFER_BINDING:
2449    case GL_CURRENT_PROGRAM:
2450    case GL_PACK_ALIGNMENT:
2451    case GL_UNPACK_ALIGNMENT:
2452    case GL_GENERATE_MIPMAP_HINT:
2453    case GL_FRAGMENT_SHADER_DERIVATIVE_HINT_OES:
2454    case GL_RED_BITS:
2455    case GL_GREEN_BITS:
2456    case GL_BLUE_BITS:
2457    case GL_ALPHA_BITS:
2458    case GL_DEPTH_BITS:
2459    case GL_STENCIL_BITS:
2460    case GL_ELEMENT_ARRAY_BUFFER_BINDING:
2461    case GL_CULL_FACE_MODE:
2462    case GL_FRONT_FACE:
2463    case GL_ACTIVE_TEXTURE:
2464    case GL_STENCIL_FUNC:
2465    case GL_STENCIL_VALUE_MASK:
2466    case GL_STENCIL_REF:
2467    case GL_STENCIL_FAIL:
2468    case GL_STENCIL_PASS_DEPTH_FAIL:
2469    case GL_STENCIL_PASS_DEPTH_PASS:
2470    case GL_STENCIL_BACK_FUNC:
2471    case GL_STENCIL_BACK_VALUE_MASK:
2472    case GL_STENCIL_BACK_REF:
2473    case GL_STENCIL_BACK_FAIL:
2474    case GL_STENCIL_BACK_PASS_DEPTH_FAIL:
2475    case GL_STENCIL_BACK_PASS_DEPTH_PASS:
2476    case GL_DEPTH_FUNC:
2477    case GL_BLEND_SRC_RGB:
2478    case GL_BLEND_SRC_ALPHA:
2479    case GL_BLEND_DST_RGB:
2480    case GL_BLEND_DST_ALPHA:
2481    case GL_BLEND_EQUATION_RGB:
2482    case GL_BLEND_EQUATION_ALPHA:
2483    case GL_STENCIL_WRITEMASK:
2484    case GL_STENCIL_BACK_WRITEMASK:
2485    case GL_STENCIL_CLEAR_VALUE:
2486    case GL_SUBPIXEL_BITS:
2487    case GL_MAX_TEXTURE_SIZE:
2488    case GL_MAX_CUBE_MAP_TEXTURE_SIZE:
2489    case GL_SAMPLE_BUFFERS:
2490    case GL_SAMPLES:
2491    case GL_IMPLEMENTATION_COLOR_READ_TYPE:
2492    case GL_IMPLEMENTATION_COLOR_READ_FORMAT:
2493    case GL_TEXTURE_BINDING_2D:
2494    case GL_TEXTURE_BINDING_CUBE_MAP:
2495    case GL_TEXTURE_BINDING_EXTERNAL_OES:
2496    case GL_TEXTURE_BINDING_3D_OES:
2497    case GL_COPY_READ_BUFFER_BINDING:
2498    case GL_COPY_WRITE_BUFFER_BINDING:
2499    case GL_DRAW_BUFFER0:
2500    case GL_DRAW_BUFFER1:
2501    case GL_DRAW_BUFFER2:
2502    case GL_DRAW_BUFFER3:
2503    case GL_DRAW_BUFFER4:
2504    case GL_DRAW_BUFFER5:
2505    case GL_DRAW_BUFFER6:
2506    case GL_DRAW_BUFFER7:
2507    case GL_DRAW_BUFFER8:
2508    case GL_DRAW_BUFFER9:
2509    case GL_DRAW_BUFFER10:
2510    case GL_DRAW_BUFFER11:
2511    case GL_DRAW_BUFFER12:
2512    case GL_DRAW_BUFFER13:
2513    case GL_DRAW_BUFFER14:
2514    case GL_DRAW_BUFFER15:
2515    case GL_MAJOR_VERSION:
2516    case GL_MAX_3D_TEXTURE_SIZE:
2517    case GL_MAX_ARRAY_TEXTURE_LAYERS:
2518    case GL_MAX_COLOR_ATTACHMENTS:
2519    case GL_MAX_COMBINED_FRAGMENT_UNIFORM_COMPONENTS:
2520    case GL_MAX_COMBINED_UNIFORM_BLOCKS:
2521    case GL_MAX_COMBINED_VERTEX_UNIFORM_COMPONENTS:
2522    case GL_MAX_DRAW_BUFFERS:
2523    case GL_MAX_ELEMENT_INDEX:
2524    case GL_MAX_ELEMENTS_INDICES:
2525    case GL_MAX_ELEMENTS_VERTICES:
2526    case GL_MAX_FRAGMENT_INPUT_COMPONENTS:
2527    case GL_MAX_FRAGMENT_UNIFORM_BLOCKS:
2528    case GL_MAX_FRAGMENT_UNIFORM_COMPONENTS:
2529    case GL_MAX_PROGRAM_TEXEL_OFFSET:
2530    case GL_MAX_SERVER_WAIT_TIMEOUT:
2531    case GL_MAX_TEXTURE_LOD_BIAS:
2532    case GL_MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS:
2533    case GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS:
2534    case GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS:
2535    case GL_MAX_UNIFORM_BLOCK_SIZE:
2536    case GL_MAX_UNIFORM_BUFFER_BINDINGS:
2537    case GL_MAX_VARYING_COMPONENTS:
2538    case GL_MAX_VERTEX_OUTPUT_COMPONENTS:
2539    case GL_MAX_VERTEX_UNIFORM_BLOCKS:
2540    case GL_MAX_VERTEX_UNIFORM_COMPONENTS:
2541    case GL_MIN_PROGRAM_TEXEL_OFFSET:
2542    case GL_MINOR_VERSION:
2543    case GL_NUM_EXTENSIONS:
2544    case GL_NUM_PROGRAM_BINARY_FORMATS:
2545    case GL_PACK_ROW_LENGTH:
2546    case GL_PACK_SKIP_PIXELS:
2547    case GL_PACK_SKIP_ROWS:
2548    case GL_PIXEL_PACK_BUFFER_BINDING:
2549    case GL_PIXEL_UNPACK_BUFFER_BINDING:
2550    case GL_PROGRAM_BINARY_FORMATS:
2551    case GL_READ_BUFFER:
2552    case GL_SAMPLER_BINDING:
2553    case GL_TEXTURE_BINDING_2D_ARRAY:
2554    case GL_UNIFORM_BUFFER_BINDING:
2555    case GL_UNIFORM_BUFFER_OFFSET_ALIGNMENT:
2556    case GL_UNIFORM_BUFFER_SIZE:
2557    case GL_UNIFORM_BUFFER_START:
2558    case GL_UNPACK_IMAGE_HEIGHT:
2559    case GL_UNPACK_ROW_LENGTH:
2560    case GL_UNPACK_SKIP_IMAGES:
2561    case GL_UNPACK_SKIP_PIXELS:
2562    case GL_UNPACK_SKIP_ROWS:
2563    case GL_VERTEX_ARRAY_BINDING:
2564	case GL_TRANSFORM_FEEDBACK_BINDING:
2565	case GL_TRANSFORM_FEEDBACK_BUFFER_BINDING:
2566        {
2567            *type = GL_INT;
2568            *numParams = 1;
2569        }
2570        break;
2571    case GL_MAX_SAMPLES_ANGLE:
2572        {
2573            *type = GL_INT;
2574            *numParams = 1;
2575        }
2576        break;
2577    case GL_MAX_VIEWPORT_DIMS:
2578        {
2579            *type = GL_INT;
2580            *numParams = 2;
2581        }
2582        break;
2583    case GL_VIEWPORT:
2584    case GL_SCISSOR_BOX:
2585        {
2586            *type = GL_INT;
2587            *numParams = 4;
2588        }
2589        break;
2590    case GL_SHADER_COMPILER:
2591    case GL_SAMPLE_COVERAGE_INVERT:
2592    case GL_DEPTH_WRITEMASK:
2593    case GL_CULL_FACE:                // CULL_FACE through DITHER are natural to IsEnabled,
2594    case GL_POLYGON_OFFSET_FILL:      // but can be retrieved through the Get{Type}v queries.
2595    case GL_SAMPLE_ALPHA_TO_COVERAGE: // For this purpose, they are treated here as bool-natural
2596    case GL_SAMPLE_COVERAGE:
2597    case GL_SCISSOR_TEST:
2598    case GL_STENCIL_TEST:
2599    case GL_DEPTH_TEST:
2600    case GL_BLEND:
2601    case GL_DITHER:
2602    case GL_PRIMITIVE_RESTART_FIXED_INDEX:
2603    case GL_RASTERIZER_DISCARD:
2604    case GL_TRANSFORM_FEEDBACK_ACTIVE:
2605    case GL_TRANSFORM_FEEDBACK_PAUSED:
2606        {
2607            *type = GL_BOOL;
2608            *numParams = 1;
2609        }
2610        break;
2611    case GL_COLOR_WRITEMASK:
2612        {
2613            *type = GL_BOOL;
2614            *numParams = 4;
2615        }
2616        break;
2617    case GL_POLYGON_OFFSET_FACTOR:
2618    case GL_POLYGON_OFFSET_UNITS:
2619    case GL_SAMPLE_COVERAGE_VALUE:
2620    case GL_DEPTH_CLEAR_VALUE:
2621    case GL_LINE_WIDTH:
2622        {
2623            *type = GL_FLOAT;
2624            *numParams = 1;
2625        }
2626        break;
2627    case GL_ALIASED_LINE_WIDTH_RANGE:
2628    case GL_ALIASED_POINT_SIZE_RANGE:
2629    case GL_DEPTH_RANGE:
2630        {
2631            *type = GL_FLOAT;
2632            *numParams = 2;
2633        }
2634        break;
2635    case GL_COLOR_CLEAR_VALUE:
2636    case GL_BLEND_COLOR:
2637        {
2638            *type = GL_FLOAT;
2639            *numParams = 4;
2640        }
2641        break;
2642	case GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT:
2643        *type = GL_FLOAT;
2644        *numParams = 1;
2645        break;
2646    default:
2647        return false;
2648    }
2649
2650    return true;
2651}
2652
2653void Context::applyScissor(int width, int height)
2654{
2655	if(mState.scissorTestEnabled)
2656	{
2657		sw::Rect scissor = { mState.scissorX, mState.scissorY, mState.scissorX + mState.scissorWidth, mState.scissorY + mState.scissorHeight };
2658		scissor.clip(0, 0, width, height);
2659
2660		device->setScissorRect(scissor);
2661		device->setScissorEnable(true);
2662	}
2663	else
2664	{
2665		device->setScissorEnable(false);
2666	}
2667}
2668
2669// Applies the render target surface, depth stencil surface, viewport rectangle and scissor rectangle
2670bool Context::applyRenderTarget()
2671{
2672    Framebuffer *framebuffer = getDrawFramebuffer();
2673	int width, height, samples;
2674
2675    if(!framebuffer || framebuffer->completeness(width, height, samples) != GL_FRAMEBUFFER_COMPLETE)
2676    {
2677        return error(GL_INVALID_FRAMEBUFFER_OPERATION, false);
2678    }
2679
2680	for(int i = 0; i < MAX_DRAW_BUFFERS; ++i)
2681	{
2682		egl::Image *renderTarget = framebuffer->getRenderTarget(i);
2683		device->setRenderTarget(i, renderTarget);
2684		if(renderTarget) renderTarget->release();
2685	}
2686
2687    egl::Image *depthBuffer = framebuffer->getDepthBuffer();
2688    device->setDepthBuffer(depthBuffer);
2689	if(depthBuffer) depthBuffer->release();
2690
2691	egl::Image *stencilBuffer = framebuffer->getStencilBuffer();
2692	device->setStencilBuffer(stencilBuffer);
2693	if(stencilBuffer) stencilBuffer->release();
2694
2695    Viewport viewport;
2696    float zNear = clamp01(mState.zNear);
2697    float zFar = clamp01(mState.zFar);
2698
2699    viewport.x0 = mState.viewportX;
2700    viewport.y0 = mState.viewportY;
2701    viewport.width = mState.viewportWidth;
2702    viewport.height = mState.viewportHeight;
2703    viewport.minZ = zNear;
2704    viewport.maxZ = zFar;
2705
2706    device->setViewport(viewport);
2707
2708	applyScissor(width, height);
2709
2710	Program *program = getCurrentProgram();
2711
2712	if(program)
2713	{
2714		GLfloat nearFarDiff[3] = {zNear, zFar, zFar - zNear};
2715        program->setUniform1fv(program->getUniformLocation("gl_DepthRange.near"), 1, &nearFarDiff[0]);
2716		program->setUniform1fv(program->getUniformLocation("gl_DepthRange.far"), 1, &nearFarDiff[1]);
2717		program->setUniform1fv(program->getUniformLocation("gl_DepthRange.diff"), 1, &nearFarDiff[2]);
2718    }
2719
2720    return true;
2721}
2722
2723// Applies the fixed-function state (culling, depth test, alpha blending, stenciling, etc)
2724void Context::applyState(GLenum drawMode)
2725{
2726    Framebuffer *framebuffer = getDrawFramebuffer();
2727
2728    if(mState.cullFaceEnabled)
2729    {
2730        device->setCullMode(es2sw::ConvertCullMode(mState.cullMode, mState.frontFace));
2731    }
2732    else
2733    {
2734		device->setCullMode(sw::CULL_NONE);
2735    }
2736
2737    if(mDepthStateDirty)
2738    {
2739        if(mState.depthTestEnabled)
2740        {
2741			device->setDepthBufferEnable(true);
2742			device->setDepthCompare(es2sw::ConvertDepthComparison(mState.depthFunc));
2743        }
2744        else
2745        {
2746            device->setDepthBufferEnable(false);
2747        }
2748
2749        mDepthStateDirty = false;
2750    }
2751
2752    if(mBlendStateDirty)
2753    {
2754        if(mState.blendEnabled)
2755        {
2756			device->setAlphaBlendEnable(true);
2757			device->setSeparateAlphaBlendEnable(true);
2758
2759            device->setBlendConstant(es2sw::ConvertColor(mState.blendColor));
2760
2761			device->setSourceBlendFactor(es2sw::ConvertBlendFunc(mState.sourceBlendRGB));
2762			device->setDestBlendFactor(es2sw::ConvertBlendFunc(mState.destBlendRGB));
2763			device->setBlendOperation(es2sw::ConvertBlendOp(mState.blendEquationRGB));
2764
2765            device->setSourceBlendFactorAlpha(es2sw::ConvertBlendFunc(mState.sourceBlendAlpha));
2766			device->setDestBlendFactorAlpha(es2sw::ConvertBlendFunc(mState.destBlendAlpha));
2767			device->setBlendOperationAlpha(es2sw::ConvertBlendOp(mState.blendEquationAlpha));
2768        }
2769        else
2770        {
2771			device->setAlphaBlendEnable(false);
2772        }
2773
2774        mBlendStateDirty = false;
2775    }
2776
2777    if(mStencilStateDirty || mFrontFaceDirty)
2778    {
2779        if(mState.stencilTestEnabled && framebuffer->hasStencil())
2780        {
2781			device->setStencilEnable(true);
2782			device->setTwoSidedStencil(true);
2783
2784            // get the maximum size of the stencil ref
2785            Renderbuffer *stencilbuffer = framebuffer->getStencilbuffer();
2786            GLuint maxStencil = (1 << stencilbuffer->getStencilSize()) - 1;
2787
2788			if(mState.frontFace == GL_CCW)
2789			{
2790				device->setStencilWriteMask(mState.stencilWritemask);
2791				device->setStencilCompare(es2sw::ConvertStencilComparison(mState.stencilFunc));
2792
2793				device->setStencilReference((mState.stencilRef < (GLint)maxStencil) ? mState.stencilRef : maxStencil);
2794				device->setStencilMask(mState.stencilMask);
2795
2796				device->setStencilFailOperation(es2sw::ConvertStencilOp(mState.stencilFail));
2797				device->setStencilZFailOperation(es2sw::ConvertStencilOp(mState.stencilPassDepthFail));
2798				device->setStencilPassOperation(es2sw::ConvertStencilOp(mState.stencilPassDepthPass));
2799
2800				device->setStencilWriteMaskCCW(mState.stencilBackWritemask);
2801				device->setStencilCompareCCW(es2sw::ConvertStencilComparison(mState.stencilBackFunc));
2802
2803				device->setStencilReferenceCCW((mState.stencilBackRef < (GLint)maxStencil) ? mState.stencilBackRef : maxStencil);
2804				device->setStencilMaskCCW(mState.stencilBackMask);
2805
2806				device->setStencilFailOperationCCW(es2sw::ConvertStencilOp(mState.stencilBackFail));
2807				device->setStencilZFailOperationCCW(es2sw::ConvertStencilOp(mState.stencilBackPassDepthFail));
2808				device->setStencilPassOperationCCW(es2sw::ConvertStencilOp(mState.stencilBackPassDepthPass));
2809			}
2810			else
2811			{
2812				device->setStencilWriteMaskCCW(mState.stencilWritemask);
2813				device->setStencilCompareCCW(es2sw::ConvertStencilComparison(mState.stencilFunc));
2814
2815				device->setStencilReferenceCCW((mState.stencilRef < (GLint)maxStencil) ? mState.stencilRef : maxStencil);
2816				device->setStencilMaskCCW(mState.stencilMask);
2817
2818				device->setStencilFailOperationCCW(es2sw::ConvertStencilOp(mState.stencilFail));
2819				device->setStencilZFailOperationCCW(es2sw::ConvertStencilOp(mState.stencilPassDepthFail));
2820				device->setStencilPassOperationCCW(es2sw::ConvertStencilOp(mState.stencilPassDepthPass));
2821
2822				device->setStencilWriteMask(mState.stencilBackWritemask);
2823				device->setStencilCompare(es2sw::ConvertStencilComparison(mState.stencilBackFunc));
2824
2825				device->setStencilReference((mState.stencilBackRef < (GLint)maxStencil) ? mState.stencilBackRef : maxStencil);
2826				device->setStencilMask(mState.stencilBackMask);
2827
2828				device->setStencilFailOperation(es2sw::ConvertStencilOp(mState.stencilBackFail));
2829				device->setStencilZFailOperation(es2sw::ConvertStencilOp(mState.stencilBackPassDepthFail));
2830				device->setStencilPassOperation(es2sw::ConvertStencilOp(mState.stencilBackPassDepthPass));
2831			}
2832        }
2833        else
2834        {
2835			device->setStencilEnable(false);
2836        }
2837
2838        mStencilStateDirty = false;
2839        mFrontFaceDirty = false;
2840    }
2841
2842    if(mMaskStateDirty)
2843    {
2844		device->setColorWriteMask(0, es2sw::ConvertColorMask(mState.colorMaskRed, mState.colorMaskGreen, mState.colorMaskBlue, mState.colorMaskAlpha));
2845		device->setDepthWriteEnable(mState.depthMask);
2846
2847        mMaskStateDirty = false;
2848    }
2849
2850    if(mPolygonOffsetStateDirty)
2851    {
2852        if(mState.polygonOffsetFillEnabled)
2853        {
2854            Renderbuffer *depthbuffer = framebuffer->getDepthbuffer();
2855            if(depthbuffer)
2856            {
2857				device->setSlopeDepthBias(mState.polygonOffsetFactor);
2858                float depthBias = ldexp(mState.polygonOffsetUnits, -(int)(depthbuffer->getDepthSize()));
2859				device->setDepthBias(depthBias);
2860            }
2861        }
2862        else
2863        {
2864            device->setSlopeDepthBias(0);
2865            device->setDepthBias(0);
2866        }
2867
2868        mPolygonOffsetStateDirty = false;
2869    }
2870
2871    if(mSampleStateDirty)
2872    {
2873        if(mState.sampleAlphaToCoverageEnabled)
2874        {
2875            device->setTransparencyAntialiasing(sw::TRANSPARENCY_ALPHA_TO_COVERAGE);
2876        }
2877		else
2878		{
2879			device->setTransparencyAntialiasing(sw::TRANSPARENCY_NONE);
2880		}
2881
2882        if(mState.sampleCoverageEnabled)
2883        {
2884            unsigned int mask = 0;
2885            if(mState.sampleCoverageValue != 0)
2886            {
2887				int width, height, samples;
2888				framebuffer->completeness(width, height, samples);
2889
2890                float threshold = 0.5f;
2891
2892                for(int i = 0; i < samples; i++)
2893                {
2894                    mask <<= 1;
2895
2896                    if((i + 1) * mState.sampleCoverageValue >= threshold)
2897                    {
2898                        threshold += 1.0f;
2899                        mask |= 1;
2900                    }
2901                }
2902            }
2903
2904            if(mState.sampleCoverageInvert)
2905            {
2906                mask = ~mask;
2907            }
2908
2909			device->setMultiSampleMask(mask);
2910        }
2911        else
2912        {
2913			device->setMultiSampleMask(0xFFFFFFFF);
2914        }
2915
2916        mSampleStateDirty = false;
2917    }
2918
2919    if(mDitherStateDirty)
2920    {
2921    //	UNIMPLEMENTED();   // FIXME
2922
2923        mDitherStateDirty = false;
2924    }
2925
2926	device->setRasterizerDiscard(mState.rasterizerDiscardEnabled);
2927}
2928
2929GLenum Context::applyVertexBuffer(GLint base, GLint first, GLsizei count, GLsizei instanceId)
2930{
2931    TranslatedAttribute attributes[MAX_VERTEX_ATTRIBS];
2932
2933    GLenum err = mVertexDataManager->prepareVertexData(first, count, attributes, instanceId);
2934    if(err != GL_NO_ERROR)
2935    {
2936        return err;
2937    }
2938
2939	Program *program = getCurrentProgram();
2940
2941	device->resetInputStreams(false);
2942
2943    for(int i = 0; i < MAX_VERTEX_ATTRIBS; i++)
2944	{
2945		if(program->getAttributeStream(i) == -1)
2946		{
2947			continue;
2948		}
2949
2950		sw::Resource *resource = attributes[i].vertexBuffer;
2951		const void *buffer = (char*)resource->data() + attributes[i].offset;
2952
2953		int stride = attributes[i].stride;
2954
2955		buffer = (char*)buffer + stride * base;
2956
2957		sw::Stream attribute(resource, buffer, stride);
2958
2959		attribute.type = attributes[i].type;
2960		attribute.count = attributes[i].count;
2961		attribute.normalized = attributes[i].normalized;
2962
2963		int stream = program->getAttributeStream(i);
2964		device->setInputStream(stream, attribute);
2965	}
2966
2967	return GL_NO_ERROR;
2968}
2969
2970// Applies the indices and element array bindings
2971GLenum Context::applyIndexBuffer(const void *indices, GLuint start, GLuint end, GLsizei count, GLenum mode, GLenum type, TranslatedIndexData *indexInfo)
2972{
2973	GLenum err = mIndexDataManager->prepareIndexData(type, start, end, count, getCurrentVertexArray()->getElementArrayBuffer(), indices, indexInfo);
2974
2975    if(err == GL_NO_ERROR)
2976    {
2977        device->setIndexBuffer(indexInfo->indexBuffer);
2978    }
2979
2980    return err;
2981}
2982
2983// Applies the shaders and shader constants
2984void Context::applyShaders()
2985{
2986    Program *programObject = getCurrentProgram();
2987    sw::VertexShader *vertexShader = programObject->getVertexShader();
2988	sw::PixelShader *pixelShader = programObject->getPixelShader();
2989
2990    device->setVertexShader(vertexShader);
2991    device->setPixelShader(pixelShader);
2992
2993    if(programObject->getSerial() != mAppliedProgramSerial)
2994    {
2995        programObject->dirtyAllUniforms();
2996        mAppliedProgramSerial = programObject->getSerial();
2997    }
2998
2999    programObject->applyUniformBuffers(mState.uniformBuffers);
3000    programObject->applyUniforms();
3001}
3002
3003void Context::applyTextures()
3004{
3005    applyTextures(sw::SAMPLER_PIXEL);
3006	applyTextures(sw::SAMPLER_VERTEX);
3007}
3008
3009void Context::applyTextures(sw::SamplerType samplerType)
3010{
3011    Program *programObject = getCurrentProgram();
3012
3013    int samplerCount = (samplerType == sw::SAMPLER_PIXEL) ? MAX_TEXTURE_IMAGE_UNITS : MAX_VERTEX_TEXTURE_IMAGE_UNITS;   // Range of samplers of given sampler type
3014
3015    for(int samplerIndex = 0; samplerIndex < samplerCount; samplerIndex++)
3016    {
3017        int textureUnit = programObject->getSamplerMapping(samplerType, samplerIndex);   // OpenGL texture image unit index
3018
3019        if(textureUnit != -1)
3020        {
3021            TextureType textureType = programObject->getSamplerTextureType(samplerType, samplerIndex);
3022
3023            Texture *texture = getSamplerTexture(textureUnit, textureType);
3024
3025			if(texture->isSamplerComplete())
3026            {
3027				GLenum wrapS, wrapT, wrapR, minFilter, magFilter;
3028
3029				Sampler *samplerObject = mState.sampler[textureUnit];
3030				if(samplerObject)
3031				{
3032					wrapS = samplerObject->getWrapS();
3033					wrapT = samplerObject->getWrapT();
3034					wrapR = samplerObject->getWrapR();
3035					minFilter = samplerObject->getMinFilter();
3036					magFilter = samplerObject->getMagFilter();
3037				}
3038				else
3039				{
3040					wrapS = texture->getWrapS();
3041					wrapT = texture->getWrapT();
3042					wrapR = texture->getWrapR();
3043					minFilter = texture->getMinFilter();
3044					magFilter = texture->getMagFilter();
3045				}
3046				GLfloat maxAnisotropy = texture->getMaxAnisotropy();
3047
3048				GLenum swizzleR = texture->getSwizzleR();
3049				GLenum swizzleG = texture->getSwizzleG();
3050				GLenum swizzleB = texture->getSwizzleB();
3051				GLenum swizzleA = texture->getSwizzleA();
3052
3053				device->setAddressingModeU(samplerType, samplerIndex, es2sw::ConvertTextureWrap(wrapS));
3054				device->setAddressingModeV(samplerType, samplerIndex, es2sw::ConvertTextureWrap(wrapT));
3055				device->setAddressingModeW(samplerType, samplerIndex, es2sw::ConvertTextureWrap(wrapR));
3056				device->setSwizzleR(samplerType, samplerIndex, es2sw::ConvertSwizzleType(swizzleR));
3057				device->setSwizzleG(samplerType, samplerIndex, es2sw::ConvertSwizzleType(swizzleG));
3058				device->setSwizzleB(samplerType, samplerIndex, es2sw::ConvertSwizzleType(swizzleB));
3059				device->setSwizzleA(samplerType, samplerIndex, es2sw::ConvertSwizzleType(swizzleA));
3060
3061				device->setTextureFilter(samplerType, samplerIndex, es2sw::ConvertTextureFilter(minFilter, magFilter, maxAnisotropy));
3062				device->setMipmapFilter(samplerType, samplerIndex, es2sw::ConvertMipMapFilter(minFilter));
3063				device->setMaxAnisotropy(samplerType, samplerIndex, maxAnisotropy);
3064
3065				applyTexture(samplerType, samplerIndex, texture);
3066            }
3067            else
3068            {
3069                applyTexture(samplerType, samplerIndex, nullptr);
3070            }
3071        }
3072        else
3073        {
3074            applyTexture(samplerType, samplerIndex, nullptr);
3075        }
3076    }
3077}
3078
3079void Context::applyTexture(sw::SamplerType type, int index, Texture *baseTexture)
3080{
3081	Program *program = getCurrentProgram();
3082	int sampler = (type == sw::SAMPLER_PIXEL) ? index : 16 + index;
3083	bool textureUsed = false;
3084
3085	if(type == sw::SAMPLER_PIXEL)
3086	{
3087		textureUsed = program->getPixelShader()->usesSampler(index);
3088	}
3089	else if(type == sw::SAMPLER_VERTEX)
3090	{
3091		textureUsed = program->getVertexShader()->usesSampler(index);
3092	}
3093	else UNREACHABLE(type);
3094
3095	sw::Resource *resource = 0;
3096
3097	if(baseTexture && textureUsed)
3098	{
3099		resource = baseTexture->getResource();
3100	}
3101
3102	device->setTextureResource(sampler, resource);
3103
3104	if(baseTexture && textureUsed)
3105	{
3106		int levelCount = baseTexture->getLevelCount();
3107
3108		if(baseTexture->getTarget() == GL_TEXTURE_2D || baseTexture->getTarget() == GL_TEXTURE_EXTERNAL_OES)
3109		{
3110			Texture2D *texture = static_cast<Texture2D*>(baseTexture);
3111
3112			for(int mipmapLevel = 0; mipmapLevel < MIPMAP_LEVELS; mipmapLevel++)
3113			{
3114				int surfaceLevel = mipmapLevel;
3115
3116				if(surfaceLevel < 0)
3117				{
3118					surfaceLevel = 0;
3119				}
3120				else if(surfaceLevel >= levelCount)
3121				{
3122					surfaceLevel = levelCount - 1;
3123				}
3124
3125				egl::Image *surface = texture->getImage(surfaceLevel);
3126				device->setTextureLevel(sampler, 0, mipmapLevel, surface, sw::TEXTURE_2D);
3127			}
3128		}
3129		else if(baseTexture->getTarget() == GL_TEXTURE_3D_OES)
3130		{
3131			Texture3D *texture = static_cast<Texture3D*>(baseTexture);
3132
3133			for(int mipmapLevel = 0; mipmapLevel < MIPMAP_LEVELS; mipmapLevel++)
3134			{
3135				int surfaceLevel = mipmapLevel;
3136
3137				if(surfaceLevel < 0)
3138				{
3139					surfaceLevel = 0;
3140				}
3141				else if(surfaceLevel >= levelCount)
3142				{
3143					surfaceLevel = levelCount - 1;
3144				}
3145
3146				egl::Image *surface = texture->getImage(surfaceLevel);
3147				device->setTextureLevel(sampler, 0, mipmapLevel, surface, sw::TEXTURE_3D);
3148			}
3149		}
3150		else if(baseTexture->getTarget() == GL_TEXTURE_2D_ARRAY)
3151		{
3152			Texture2DArray *texture = static_cast<Texture2DArray*>(baseTexture);
3153
3154			for(int mipmapLevel = 0; mipmapLevel < MIPMAP_LEVELS; mipmapLevel++)
3155			{
3156				int surfaceLevel = mipmapLevel;
3157
3158				if(surfaceLevel < 0)
3159				{
3160					surfaceLevel = 0;
3161				}
3162				else if(surfaceLevel >= levelCount)
3163				{
3164					surfaceLevel = levelCount - 1;
3165				}
3166
3167				egl::Image *surface = texture->getImage(surfaceLevel);
3168				device->setTextureLevel(sampler, 0, mipmapLevel, surface, sw::TEXTURE_2D_ARRAY);
3169			}
3170		}
3171		else if(baseTexture->getTarget() == GL_TEXTURE_CUBE_MAP)
3172		{
3173			for(int face = 0; face < 6; face++)
3174			{
3175				TextureCubeMap *cubeTexture = static_cast<TextureCubeMap*>(baseTexture);
3176
3177				for(int mipmapLevel = 0; mipmapLevel < MIPMAP_LEVELS; mipmapLevel++)
3178				{
3179					int surfaceLevel = mipmapLevel;
3180
3181					if(surfaceLevel < 0)
3182					{
3183						surfaceLevel = 0;
3184					}
3185					else if(surfaceLevel >= levelCount)
3186					{
3187						surfaceLevel = levelCount - 1;
3188					}
3189
3190					egl::Image *surface = cubeTexture->getImage(face, surfaceLevel);
3191					device->setTextureLevel(sampler, face, mipmapLevel, surface, sw::TEXTURE_CUBE);
3192				}
3193			}
3194		}
3195		else UNIMPLEMENTED();
3196	}
3197	else
3198	{
3199		device->setTextureLevel(sampler, 0, 0, 0, sw::TEXTURE_NULL);
3200	}
3201}
3202
3203void Context::readPixels(GLint x, GLint y, GLsizei width, GLsizei height,
3204                         GLenum format, GLenum type, GLsizei *bufSize, void* pixels)
3205{
3206    Framebuffer *framebuffer = getReadFramebuffer();
3207	int framebufferWidth, framebufferHeight, framebufferSamples;
3208
3209    if(framebuffer->completeness(framebufferWidth, framebufferHeight, framebufferSamples) != GL_FRAMEBUFFER_COMPLETE)
3210    {
3211        return error(GL_INVALID_FRAMEBUFFER_OPERATION);
3212    }
3213
3214    if(getReadFramebufferName() != 0 && framebufferSamples != 0)
3215    {
3216        return error(GL_INVALID_OPERATION);
3217    }
3218
3219	GLenum readFormat = framebuffer->getImplementationColorReadFormat();
3220	GLenum readType = framebuffer->getImplementationColorReadType();
3221
3222	if(!(readFormat == format && readType == type) && !ValidReadPixelsFormatType(readFormat, readType, format, type, clientVersion))
3223	{
3224		return error(GL_INVALID_OPERATION);
3225	}
3226
3227	GLsizei outputWidth = (mState.packRowLength > 0) ? mState.packRowLength : width;
3228	GLsizei outputPitch = egl::ComputePitch(outputWidth, format, type, mState.packAlignment);
3229	GLsizei outputHeight = (mState.packImageHeight == 0) ? height : mState.packImageHeight;
3230	pixels = getPixelPackBuffer() ? (unsigned char*)getPixelPackBuffer()->data() + (ptrdiff_t)pixels : (unsigned char*)pixels;
3231	pixels = ((char*)pixels) + egl::ComputePackingOffset(format, type, outputWidth, outputHeight, mState.packAlignment, mState.packSkipImages, mState.packSkipRows, mState.packSkipPixels);
3232
3233	// Sized query sanity check
3234    if(bufSize)
3235    {
3236        int requiredSize = outputPitch * height;
3237        if(requiredSize > *bufSize)
3238        {
3239            return error(GL_INVALID_OPERATION);
3240        }
3241    }
3242
3243    egl::Image *renderTarget = framebuffer->getReadRenderTarget();
3244
3245    if(!renderTarget)
3246    {
3247        return error(GL_OUT_OF_MEMORY);
3248    }
3249
3250	sw::Rect rect = {x, y, x + width, y + height};
3251	sw::Rect dstRect = { 0, 0, width, height };
3252	rect.clip(0, 0, renderTarget->getWidth(), renderTarget->getHeight());
3253
3254	sw::Surface externalSurface(width, height, 1, egl::ConvertFormatType(format, type), pixels, outputPitch, outputPitch * outputHeight);
3255	sw::SliceRect sliceRect(rect);
3256	sw::SliceRect dstSliceRect(dstRect);
3257	device->blit(renderTarget, sliceRect, &externalSurface, dstSliceRect, false);
3258
3259	renderTarget->release();
3260}
3261
3262void Context::clear(GLbitfield mask)
3263{
3264	if(mState.rasterizerDiscardEnabled)
3265	{
3266		return;
3267	}
3268
3269    Framebuffer *framebuffer = getDrawFramebuffer();
3270
3271    if(!framebuffer || framebuffer->completeness() != GL_FRAMEBUFFER_COMPLETE)
3272    {
3273        return error(GL_INVALID_FRAMEBUFFER_OPERATION);
3274    }
3275
3276    if(!applyRenderTarget())
3277    {
3278        return;
3279    }
3280
3281	if(mask & GL_COLOR_BUFFER_BIT)
3282	{
3283		unsigned int rgbaMask = getColorMask();
3284
3285		if(rgbaMask != 0)
3286		{
3287			device->clearColor(mState.colorClearValue.red, mState.colorClearValue.green, mState.colorClearValue.blue, mState.colorClearValue.alpha, rgbaMask);
3288		}
3289	}
3290
3291	if(mask & GL_DEPTH_BUFFER_BIT)
3292	{
3293		if(mState.depthMask != 0)
3294		{
3295			float depth = clamp01(mState.depthClearValue);
3296			device->clearDepth(depth);
3297		}
3298	}
3299
3300	if(mask & GL_STENCIL_BUFFER_BIT)
3301	{
3302		if(mState.stencilWritemask != 0)
3303		{
3304			int stencil = mState.stencilClearValue & 0x000000FF;
3305			device->clearStencil(stencil, mState.stencilWritemask);
3306		}
3307	}
3308}
3309
3310void Context::clearColorBuffer(GLint drawbuffer, void *value, sw::Format format)
3311{
3312	unsigned int rgbaMask = getColorMask();
3313	if(rgbaMask && !mState.rasterizerDiscardEnabled)
3314	{
3315		Framebuffer *framebuffer = getDrawFramebuffer();
3316		egl::Image *colorbuffer = framebuffer->getRenderTarget(drawbuffer);
3317
3318		if(colorbuffer)
3319		{
3320			sw::SliceRect clearRect = colorbuffer->getRect();
3321
3322			if(mState.scissorTestEnabled)
3323			{
3324				clearRect.clip(mState.scissorX, mState.scissorY, mState.scissorX + mState.scissorWidth, mState.scissorY + mState.scissorHeight);
3325			}
3326
3327			device->clear(value, format, colorbuffer, clearRect, rgbaMask);
3328
3329			colorbuffer->release();
3330		}
3331	}
3332}
3333
3334void Context::clearColorBuffer(GLint drawbuffer, const GLint *value)
3335{
3336	clearColorBuffer(drawbuffer, (void*)value, sw::FORMAT_A32B32G32R32I);
3337}
3338
3339void Context::clearColorBuffer(GLint drawbuffer, const GLuint *value)
3340{
3341	clearColorBuffer(drawbuffer, (void*)value, sw::FORMAT_A32B32G32R32UI);
3342}
3343
3344void Context::clearColorBuffer(GLint drawbuffer, const GLfloat *value)
3345{
3346	clearColorBuffer(drawbuffer, (void*)value, sw::FORMAT_A32B32G32R32F);
3347}
3348
3349void Context::clearDepthBuffer(const GLfloat value)
3350{
3351	if(mState.depthMask && !mState.rasterizerDiscardEnabled)
3352	{
3353		Framebuffer *framebuffer = getDrawFramebuffer();
3354		egl::Image *depthbuffer = framebuffer->getDepthBuffer();
3355
3356		if(depthbuffer)
3357		{
3358			float depth = clamp01(value);
3359			sw::SliceRect clearRect = depthbuffer->getRect();
3360
3361			if(mState.scissorTestEnabled)
3362			{
3363				clearRect.clip(mState.scissorX, mState.scissorY, mState.scissorX + mState.scissorWidth, mState.scissorY + mState.scissorHeight);
3364			}
3365
3366			depthbuffer->clearDepth(depth, clearRect.x0, clearRect.y0, clearRect.width(), clearRect.height());
3367
3368			depthbuffer->release();
3369		}
3370	}
3371}
3372
3373void Context::clearStencilBuffer(const GLint value)
3374{
3375	if(mState.stencilWritemask && !mState.rasterizerDiscardEnabled)
3376	{
3377		Framebuffer *framebuffer = getDrawFramebuffer();
3378		egl::Image *stencilbuffer = framebuffer->getStencilBuffer();
3379
3380		if(stencilbuffer)
3381		{
3382			unsigned char stencil = value < 0 ? 0 : static_cast<unsigned char>(value & 0x000000FF);
3383			sw::SliceRect clearRect = stencilbuffer->getRect();
3384
3385			if(mState.scissorTestEnabled)
3386			{
3387				clearRect.clip(mState.scissorX, mState.scissorY, mState.scissorX + mState.scissorWidth, mState.scissorY + mState.scissorHeight);
3388			}
3389
3390			stencilbuffer->clearStencil(stencil, static_cast<unsigned char>(mState.stencilWritemask), clearRect.x0, clearRect.y0, clearRect.width(), clearRect.height());
3391
3392			stencilbuffer->release();
3393		}
3394	}
3395}
3396
3397void Context::drawArrays(GLenum mode, GLint first, GLsizei count, GLsizei instanceCount)
3398{
3399    if(!mState.currentProgram)
3400    {
3401        return error(GL_INVALID_OPERATION);
3402    }
3403
3404    sw::DrawType primitiveType;
3405    int primitiveCount;
3406
3407    if(!es2sw::ConvertPrimitiveType(mode, count, GL_NONE, primitiveType, primitiveCount))
3408        return error(GL_INVALID_ENUM);
3409
3410    if(primitiveCount <= 0)
3411    {
3412        return;
3413    }
3414
3415    if(!applyRenderTarget())
3416    {
3417        return;
3418    }
3419
3420    applyState(mode);
3421
3422	for(int i = 0; i < instanceCount; ++i)
3423	{
3424		device->setInstanceID(i);
3425
3426		GLenum err = applyVertexBuffer(0, first, count, i);
3427		if(err != GL_NO_ERROR)
3428		{
3429			return error(err);
3430		}
3431
3432		applyShaders();
3433		applyTextures();
3434
3435		if(!getCurrentProgram()->validateSamplers(false))
3436		{
3437			return error(GL_INVALID_OPERATION);
3438		}
3439
3440		if(!cullSkipsDraw(mode))
3441		{
3442			device->drawPrimitive(primitiveType, primitiveCount);
3443		}
3444	}
3445}
3446
3447void Context::drawElements(GLenum mode, GLuint start, GLuint end, GLsizei count, GLenum type, const void *indices, GLsizei instanceCount)
3448{
3449    if(!mState.currentProgram)
3450    {
3451        return error(GL_INVALID_OPERATION);
3452    }
3453
3454	if(!indices && !getCurrentVertexArray()->getElementArrayBuffer())
3455    {
3456        return error(GL_INVALID_OPERATION);
3457    }
3458
3459    sw::DrawType primitiveType;
3460    int primitiveCount;
3461
3462    if(!es2sw::ConvertPrimitiveType(mode, count, type, primitiveType, primitiveCount))
3463        return error(GL_INVALID_ENUM);
3464
3465    if(primitiveCount <= 0)
3466    {
3467        return;
3468    }
3469
3470    if(!applyRenderTarget())
3471    {
3472        return;
3473    }
3474
3475    applyState(mode);
3476
3477	for(int i = 0; i < instanceCount; ++i)
3478	{
3479		device->setInstanceID(i);
3480
3481		TranslatedIndexData indexInfo;
3482		GLenum err = applyIndexBuffer(indices, start, end, count, mode, type, &indexInfo);
3483		if(err != GL_NO_ERROR)
3484		{
3485			return error(err);
3486		}
3487
3488		GLsizei vertexCount = indexInfo.maxIndex - indexInfo.minIndex + 1;
3489		err = applyVertexBuffer(-(int)indexInfo.minIndex, indexInfo.minIndex, vertexCount, i);
3490		if(err != GL_NO_ERROR)
3491		{
3492			return error(err);
3493		}
3494
3495		applyShaders();
3496		applyTextures();
3497
3498		if(!getCurrentProgram()->validateSamplers(false))
3499		{
3500			return error(GL_INVALID_OPERATION);
3501		}
3502
3503		if(!cullSkipsDraw(mode))
3504		{
3505			device->drawIndexedPrimitive(primitiveType, indexInfo.indexOffset, primitiveCount);
3506		}
3507	}
3508}
3509
3510void Context::finish()
3511{
3512	device->finish();
3513}
3514
3515void Context::flush()
3516{
3517    // We don't queue anything without processing it as fast as possible
3518}
3519
3520void Context::recordInvalidEnum()
3521{
3522    mInvalidEnum = true;
3523}
3524
3525void Context::recordInvalidValue()
3526{
3527    mInvalidValue = true;
3528}
3529
3530void Context::recordInvalidOperation()
3531{
3532    mInvalidOperation = true;
3533}
3534
3535void Context::recordOutOfMemory()
3536{
3537    mOutOfMemory = true;
3538}
3539
3540void Context::recordInvalidFramebufferOperation()
3541{
3542    mInvalidFramebufferOperation = true;
3543}
3544
3545// Get one of the recorded errors and clear its flag, if any.
3546// [OpenGL ES 2.0.24] section 2.5 page 13.
3547GLenum Context::getError()
3548{
3549    if(mInvalidEnum)
3550    {
3551        mInvalidEnum = false;
3552
3553        return GL_INVALID_ENUM;
3554    }
3555
3556    if(mInvalidValue)
3557    {
3558        mInvalidValue = false;
3559
3560        return GL_INVALID_VALUE;
3561    }
3562
3563    if(mInvalidOperation)
3564    {
3565        mInvalidOperation = false;
3566
3567        return GL_INVALID_OPERATION;
3568    }
3569
3570    if(mOutOfMemory)
3571    {
3572        mOutOfMemory = false;
3573
3574        return GL_OUT_OF_MEMORY;
3575    }
3576
3577    if(mInvalidFramebufferOperation)
3578    {
3579        mInvalidFramebufferOperation = false;
3580
3581        return GL_INVALID_FRAMEBUFFER_OPERATION;
3582    }
3583
3584    return GL_NO_ERROR;
3585}
3586
3587int Context::getSupportedMultisampleCount(int requested)
3588{
3589	int supported = 0;
3590
3591	for(int i = NUM_MULTISAMPLE_COUNTS - 1; i >= 0; i--)
3592	{
3593		if(supported >= requested)
3594		{
3595			return supported;
3596		}
3597
3598		supported = multisampleCount[i];
3599	}
3600
3601	return supported;
3602}
3603
3604void Context::detachBuffer(GLuint buffer)
3605{
3606	// [OpenGL ES 2.0.24] section 2.9 page 22:
3607	// If a buffer object is deleted while it is bound, all bindings to that object in the current context
3608	// (i.e. in the thread that called Delete-Buffers) are reset to zero.
3609
3610	if(mState.copyReadBuffer.name() == buffer)
3611	{
3612		mState.copyReadBuffer = nullptr;
3613	}
3614
3615	if(mState.copyWriteBuffer.name() == buffer)
3616	{
3617		mState.copyWriteBuffer = nullptr;
3618	}
3619
3620	if(mState.pixelPackBuffer.name() == buffer)
3621	{
3622		mState.pixelPackBuffer = nullptr;
3623	}
3624
3625	if(mState.pixelUnpackBuffer.name() == buffer)
3626	{
3627		mState.pixelUnpackBuffer = nullptr;
3628	}
3629
3630	if(mState.genericUniformBuffer.name() == buffer)
3631	{
3632		mState.genericUniformBuffer = nullptr;
3633	}
3634
3635	if(getArrayBufferName() == buffer)
3636	{
3637		mState.arrayBuffer = nullptr;
3638	}
3639
3640	// Only detach from the current transform feedback
3641	TransformFeedback* currentTransformFeedback = getTransformFeedback();
3642	if(currentTransformFeedback)
3643	{
3644		currentTransformFeedback->detachBuffer(buffer);
3645	}
3646
3647	// Only detach from the current vertex array
3648	VertexArray* currentVertexArray = getCurrentVertexArray();
3649	if(currentVertexArray)
3650	{
3651		currentVertexArray->detachBuffer(buffer);
3652	}
3653
3654	for(int attribute = 0; attribute < MAX_VERTEX_ATTRIBS; attribute++)
3655	{
3656		if(mState.vertexAttribute[attribute].mBoundBuffer.name() == buffer)
3657		{
3658			mState.vertexAttribute[attribute].mBoundBuffer = nullptr;
3659		}
3660	}
3661}
3662
3663void Context::detachTexture(GLuint texture)
3664{
3665    // [OpenGL ES 2.0.24] section 3.8 page 84:
3666    // If a texture object is deleted, it is as if all texture units which are bound to that texture object are
3667    // rebound to texture object zero
3668
3669    for(int type = 0; type < TEXTURE_TYPE_COUNT; type++)
3670    {
3671        for(int sampler = 0; sampler < MAX_COMBINED_TEXTURE_IMAGE_UNITS; sampler++)
3672        {
3673            if(mState.samplerTexture[type][sampler].name() == texture)
3674            {
3675                mState.samplerTexture[type][sampler] = nullptr;
3676            }
3677        }
3678    }
3679
3680    // [OpenGL ES 2.0.24] section 4.4 page 112:
3681    // If a texture object is deleted while its image is attached to the currently bound framebuffer, then it is
3682    // as if FramebufferTexture2D had been called, with a texture of 0, for each attachment point to which this
3683    // image was attached in the currently bound framebuffer.
3684
3685    Framebuffer *readFramebuffer = getReadFramebuffer();
3686    Framebuffer *drawFramebuffer = getDrawFramebuffer();
3687
3688    if(readFramebuffer)
3689    {
3690        readFramebuffer->detachTexture(texture);
3691    }
3692
3693    if(drawFramebuffer && drawFramebuffer != readFramebuffer)
3694    {
3695        drawFramebuffer->detachTexture(texture);
3696    }
3697}
3698
3699void Context::detachFramebuffer(GLuint framebuffer)
3700{
3701    // [OpenGL ES 2.0.24] section 4.4 page 107:
3702    // If a framebuffer that is currently bound to the target FRAMEBUFFER is deleted, it is as though
3703    // BindFramebuffer had been executed with the target of FRAMEBUFFER and framebuffer of zero.
3704
3705    if(mState.readFramebuffer == framebuffer)
3706    {
3707        bindReadFramebuffer(0);
3708    }
3709
3710    if(mState.drawFramebuffer == framebuffer)
3711    {
3712        bindDrawFramebuffer(0);
3713    }
3714}
3715
3716void Context::detachRenderbuffer(GLuint renderbuffer)
3717{
3718    // [OpenGL ES 2.0.24] section 4.4 page 109:
3719    // If a renderbuffer that is currently bound to RENDERBUFFER is deleted, it is as though BindRenderbuffer
3720    // had been executed with the target RENDERBUFFER and name of zero.
3721
3722    if(mState.renderbuffer.name() == renderbuffer)
3723    {
3724        bindRenderbuffer(0);
3725    }
3726
3727    // [OpenGL ES 2.0.24] section 4.4 page 111:
3728    // If a renderbuffer object is deleted while its image is attached to the currently bound framebuffer,
3729    // then it is as if FramebufferRenderbuffer had been called, with a renderbuffer of 0, for each attachment
3730    // point to which this image was attached in the currently bound framebuffer.
3731
3732    Framebuffer *readFramebuffer = getReadFramebuffer();
3733    Framebuffer *drawFramebuffer = getDrawFramebuffer();
3734
3735    if(readFramebuffer)
3736    {
3737        readFramebuffer->detachRenderbuffer(renderbuffer);
3738    }
3739
3740    if(drawFramebuffer && drawFramebuffer != readFramebuffer)
3741    {
3742        drawFramebuffer->detachRenderbuffer(renderbuffer);
3743    }
3744}
3745
3746void Context::detachSampler(GLuint sampler)
3747{
3748	// [OpenGL ES 3.0.2] section 3.8.2 pages 123-124:
3749	// If a sampler object that is currently bound to one or more texture units is
3750	// deleted, it is as though BindSampler is called once for each texture unit to
3751	// which the sampler is bound, with unit set to the texture unit and sampler set to zero.
3752	for(size_t textureUnit = 0; textureUnit < MAX_COMBINED_TEXTURE_IMAGE_UNITS; ++textureUnit)
3753	{
3754		gl::BindingPointer<Sampler> &samplerBinding = mState.sampler[textureUnit];
3755		if(samplerBinding.name() == sampler)
3756		{
3757			samplerBinding = nullptr;
3758		}
3759	}
3760}
3761
3762bool Context::cullSkipsDraw(GLenum drawMode)
3763{
3764    return mState.cullFaceEnabled && mState.cullMode == GL_FRONT_AND_BACK && isTriangleMode(drawMode);
3765}
3766
3767bool Context::isTriangleMode(GLenum drawMode)
3768{
3769    switch (drawMode)
3770    {
3771      case GL_TRIANGLES:
3772      case GL_TRIANGLE_FAN:
3773      case GL_TRIANGLE_STRIP:
3774        return true;
3775      case GL_POINTS:
3776      case GL_LINES:
3777      case GL_LINE_LOOP:
3778      case GL_LINE_STRIP:
3779        return false;
3780      default: UNREACHABLE(drawMode);
3781    }
3782
3783    return false;
3784}
3785
3786void Context::setVertexAttrib(GLuint index, const GLfloat *values)
3787{
3788    ASSERT(index < MAX_VERTEX_ATTRIBS);
3789
3790    mState.vertexAttribute[index].setCurrentValue(values);
3791
3792    mVertexDataManager->dirtyCurrentValue(index);
3793}
3794
3795void Context::setVertexAttrib(GLuint index, const GLint *values)
3796{
3797	ASSERT(index < MAX_VERTEX_ATTRIBS);
3798
3799	mState.vertexAttribute[index].setCurrentValue(values);
3800
3801	mVertexDataManager->dirtyCurrentValue(index);
3802}
3803
3804void Context::setVertexAttrib(GLuint index, const GLuint *values)
3805{
3806	ASSERT(index < MAX_VERTEX_ATTRIBS);
3807
3808	mState.vertexAttribute[index].setCurrentValue(values);
3809
3810	mVertexDataManager->dirtyCurrentValue(index);
3811}
3812
3813void Context::blitFramebuffer(GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1,
3814                              GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1,
3815                              GLbitfield mask)
3816{
3817    Framebuffer *readFramebuffer = getReadFramebuffer();
3818    Framebuffer *drawFramebuffer = getDrawFramebuffer();
3819
3820	int readBufferWidth, readBufferHeight, readBufferSamples;
3821    int drawBufferWidth, drawBufferHeight, drawBufferSamples;
3822
3823    if(!readFramebuffer || readFramebuffer->completeness(readBufferWidth, readBufferHeight, readBufferSamples) != GL_FRAMEBUFFER_COMPLETE ||
3824       !drawFramebuffer || drawFramebuffer->completeness(drawBufferWidth, drawBufferHeight, drawBufferSamples) != GL_FRAMEBUFFER_COMPLETE)
3825    {
3826        return error(GL_INVALID_FRAMEBUFFER_OPERATION);
3827    }
3828
3829    if(drawBufferSamples > 1)
3830    {
3831        return error(GL_INVALID_OPERATION);
3832    }
3833
3834    sw::SliceRect sourceRect;
3835    sw::SliceRect destRect;
3836	bool flipX = (srcX0 < srcX1) ^ (dstX0 < dstX1);
3837	bool flipy = (srcY0 < srcY1) ^ (dstY0 < dstY1);
3838
3839    if(srcX0 < srcX1)
3840    {
3841        sourceRect.x0 = srcX0;
3842        sourceRect.x1 = srcX1;
3843    }
3844    else
3845    {
3846        sourceRect.x0 = srcX1;
3847        sourceRect.x1 = srcX0;
3848    }
3849
3850	if(dstX0 < dstX1)
3851	{
3852		destRect.x0 = dstX0;
3853		destRect.x1 = dstX1;
3854	}
3855	else
3856	{
3857		destRect.x0 = dstX1;
3858		destRect.x1 = dstX0;
3859	}
3860
3861    if(srcY0 < srcY1)
3862    {
3863        sourceRect.y0 = srcY0;
3864        sourceRect.y1 = srcY1;
3865    }
3866    else
3867    {
3868        sourceRect.y0 = srcY1;
3869        sourceRect.y1 = srcY0;
3870    }
3871
3872	if(dstY0 < dstY1)
3873	{
3874		destRect.y0 = dstY0;
3875		destRect.y1 = dstY1;
3876	}
3877	else
3878	{
3879		destRect.y0 = dstY1;
3880		destRect.y1 = dstY0;
3881	}
3882
3883	sw::Rect sourceScissoredRect = sourceRect;
3884    sw::Rect destScissoredRect = destRect;
3885
3886    if(mState.scissorTestEnabled)   // Only write to parts of the destination framebuffer which pass the scissor test
3887    {
3888        if(destRect.x0 < mState.scissorX)
3889        {
3890            int xDiff = mState.scissorX - destRect.x0;
3891            destScissoredRect.x0 = mState.scissorX;
3892            sourceScissoredRect.x0 += xDiff;
3893        }
3894
3895        if(destRect.x1 > mState.scissorX + mState.scissorWidth)
3896        {
3897            int xDiff = destRect.x1 - (mState.scissorX + mState.scissorWidth);
3898            destScissoredRect.x1 = mState.scissorX + mState.scissorWidth;
3899            sourceScissoredRect.x1 -= xDiff;
3900        }
3901
3902        if(destRect.y0 < mState.scissorY)
3903        {
3904            int yDiff = mState.scissorY - destRect.y0;
3905            destScissoredRect.y0 = mState.scissorY;
3906            sourceScissoredRect.y0 += yDiff;
3907        }
3908
3909        if(destRect.y1 > mState.scissorY + mState.scissorHeight)
3910        {
3911            int yDiff = destRect.y1 - (mState.scissorY + mState.scissorHeight);
3912            destScissoredRect.y1 = mState.scissorY + mState.scissorHeight;
3913            sourceScissoredRect.y1 -= yDiff;
3914        }
3915    }
3916
3917    sw::Rect sourceTrimmedRect = sourceScissoredRect;
3918    sw::Rect destTrimmedRect = destScissoredRect;
3919
3920    // The source & destination rectangles also may need to be trimmed if they fall out of the bounds of
3921    // the actual draw and read surfaces.
3922    if(sourceTrimmedRect.x0 < 0)
3923    {
3924        int xDiff = 0 - sourceTrimmedRect.x0;
3925        sourceTrimmedRect.x0 = 0;
3926        destTrimmedRect.x0 += xDiff;
3927    }
3928
3929    if(sourceTrimmedRect.x1 > readBufferWidth)
3930    {
3931        int xDiff = sourceTrimmedRect.x1 - readBufferWidth;
3932        sourceTrimmedRect.x1 = readBufferWidth;
3933        destTrimmedRect.x1 -= xDiff;
3934    }
3935
3936    if(sourceTrimmedRect.y0 < 0)
3937    {
3938        int yDiff = 0 - sourceTrimmedRect.y0;
3939        sourceTrimmedRect.y0 = 0;
3940        destTrimmedRect.y0 += yDiff;
3941    }
3942
3943    if(sourceTrimmedRect.y1 > readBufferHeight)
3944    {
3945        int yDiff = sourceTrimmedRect.y1 - readBufferHeight;
3946        sourceTrimmedRect.y1 = readBufferHeight;
3947        destTrimmedRect.y1 -= yDiff;
3948    }
3949
3950    if(destTrimmedRect.x0 < 0)
3951    {
3952        int xDiff = 0 - destTrimmedRect.x0;
3953        destTrimmedRect.x0 = 0;
3954        sourceTrimmedRect.x0 += xDiff;
3955    }
3956
3957    if(destTrimmedRect.x1 > drawBufferWidth)
3958    {
3959        int xDiff = destTrimmedRect.x1 - drawBufferWidth;
3960        destTrimmedRect.x1 = drawBufferWidth;
3961        sourceTrimmedRect.x1 -= xDiff;
3962    }
3963
3964    if(destTrimmedRect.y0 < 0)
3965    {
3966        int yDiff = 0 - destTrimmedRect.y0;
3967        destTrimmedRect.y0 = 0;
3968        sourceTrimmedRect.y0 += yDiff;
3969    }
3970
3971    if(destTrimmedRect.y1 > drawBufferHeight)
3972    {
3973        int yDiff = destTrimmedRect.y1 - drawBufferHeight;
3974        destTrimmedRect.y1 = drawBufferHeight;
3975        sourceTrimmedRect.y1 -= yDiff;
3976    }
3977
3978    bool partialBufferCopy = false;
3979
3980    if(sourceTrimmedRect.y1 - sourceTrimmedRect.y0 < readBufferHeight ||
3981       sourceTrimmedRect.x1 - sourceTrimmedRect.x0 < readBufferWidth ||
3982       destTrimmedRect.y1 - destTrimmedRect.y0 < drawBufferHeight ||
3983       destTrimmedRect.x1 - destTrimmedRect.x0 < drawBufferWidth ||
3984       sourceTrimmedRect.y0 != 0 || destTrimmedRect.y0 != 0 || sourceTrimmedRect.x0 != 0 || destTrimmedRect.x0 != 0)
3985    {
3986        partialBufferCopy = true;
3987    }
3988
3989	bool blitRenderTarget = false;
3990    bool blitDepthStencil = false;
3991
3992    if(mask & GL_COLOR_BUFFER_BIT)
3993    {
3994		GLenum readColorbufferType = readFramebuffer->getColorbufferType(getReadFramebufferColorIndex());
3995		GLenum drawColorbufferType = drawFramebuffer->getColorbufferType(0);
3996		const bool validReadType = readColorbufferType == GL_TEXTURE_2D || Framebuffer::IsRenderbuffer(readColorbufferType);
3997		const bool validDrawType = drawColorbufferType == GL_TEXTURE_2D || Framebuffer::IsRenderbuffer(drawColorbufferType);
3998        if(!validReadType || !validDrawType)
3999        {
4000            return error(GL_INVALID_OPERATION);
4001        }
4002
4003        if(partialBufferCopy && readBufferSamples > 1)
4004        {
4005            return error(GL_INVALID_OPERATION);
4006        }
4007
4008        blitRenderTarget = true;
4009    }
4010
4011    if(mask & (GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT))
4012    {
4013        Renderbuffer *readDSBuffer = nullptr;
4014        Renderbuffer *drawDSBuffer = nullptr;
4015
4016        if(mask & GL_DEPTH_BUFFER_BIT)
4017        {
4018            if(readFramebuffer->getDepthbuffer() && drawFramebuffer->getDepthbuffer())
4019            {
4020                if(readFramebuffer->getDepthbufferType() != drawFramebuffer->getDepthbufferType())
4021                {
4022                    return error(GL_INVALID_OPERATION);
4023                }
4024
4025                blitDepthStencil = true;
4026                readDSBuffer = readFramebuffer->getDepthbuffer();
4027                drawDSBuffer = drawFramebuffer->getDepthbuffer();
4028            }
4029        }
4030
4031        if(mask & GL_STENCIL_BUFFER_BIT)
4032        {
4033            if(readFramebuffer->getStencilbuffer() && drawFramebuffer->getStencilbuffer())
4034            {
4035                if(readFramebuffer->getStencilbufferType() != drawFramebuffer->getStencilbufferType())
4036                {
4037                    return error(GL_INVALID_OPERATION);
4038                }
4039
4040                blitDepthStencil = true;
4041                readDSBuffer = readFramebuffer->getStencilbuffer();
4042                drawDSBuffer = drawFramebuffer->getStencilbuffer();
4043            }
4044        }
4045
4046        if(partialBufferCopy)
4047        {
4048            ERR("Only whole-buffer depth and stencil blits are supported by this implementation.");
4049            return error(GL_INVALID_OPERATION);   // Only whole-buffer copies are permitted
4050        }
4051
4052        if((drawDSBuffer && drawDSBuffer->getSamples() > 1) ||
4053           (readDSBuffer && readDSBuffer->getSamples() > 1))
4054        {
4055            return error(GL_INVALID_OPERATION);
4056        }
4057    }
4058
4059    if(blitRenderTarget || blitDepthStencil)
4060    {
4061        if(blitRenderTarget)
4062        {
4063            egl::Image *readRenderTarget = readFramebuffer->getReadRenderTarget();
4064            egl::Image *drawRenderTarget = drawFramebuffer->getRenderTarget(0);
4065
4066			if(flipX)
4067			{
4068				swap(destRect.x0, destRect.x1);
4069			}
4070			if(flipy)
4071			{
4072				swap(destRect.y0, destRect.y1);
4073			}
4074
4075            bool success = device->stretchRect(readRenderTarget, &sourceRect, drawRenderTarget, &destRect, false);
4076
4077            readRenderTarget->release();
4078            drawRenderTarget->release();
4079
4080            if(!success)
4081            {
4082                ERR("BlitFramebuffer failed.");
4083                return;
4084            }
4085        }
4086
4087        if(blitDepthStencil)
4088        {
4089            bool success = device->stretchRect(readFramebuffer->getDepthBuffer(), nullptr, drawFramebuffer->getDepthBuffer(), nullptr, false);
4090
4091            if(!success)
4092            {
4093                ERR("BlitFramebuffer failed.");
4094                return;
4095            }
4096        }
4097    }
4098}
4099
4100void Context::bindTexImage(egl::Surface *surface)
4101{
4102	es2::Texture2D *textureObject = getTexture2D();
4103
4104    if(textureObject)
4105    {
4106		textureObject->bindTexImage(surface);
4107	}
4108}
4109
4110EGLenum Context::validateSharedImage(EGLenum target, GLuint name, GLuint textureLevel)
4111{
4112    GLenum textureTarget = GL_NONE;
4113
4114    switch(target)
4115    {
4116    case EGL_GL_TEXTURE_2D_KHR:
4117        textureTarget = GL_TEXTURE_2D;
4118        break;
4119    case EGL_GL_TEXTURE_CUBE_MAP_POSITIVE_X_KHR:
4120    case EGL_GL_TEXTURE_CUBE_MAP_NEGATIVE_X_KHR:
4121    case EGL_GL_TEXTURE_CUBE_MAP_POSITIVE_Y_KHR:
4122    case EGL_GL_TEXTURE_CUBE_MAP_NEGATIVE_Y_KHR:
4123    case EGL_GL_TEXTURE_CUBE_MAP_POSITIVE_Z_KHR:
4124    case EGL_GL_TEXTURE_CUBE_MAP_NEGATIVE_Z_KHR:
4125        textureTarget = GL_TEXTURE_CUBE_MAP;
4126        break;
4127    case EGL_GL_RENDERBUFFER_KHR:
4128        break;
4129    default:
4130        return EGL_BAD_PARAMETER;
4131    }
4132
4133    if(textureLevel >= es2::IMPLEMENTATION_MAX_TEXTURE_LEVELS)
4134    {
4135        return EGL_BAD_MATCH;
4136    }
4137
4138    if(textureTarget != GL_NONE)
4139    {
4140        es2::Texture *texture = getTexture(name);
4141
4142        if(!texture || texture->getTarget() != textureTarget)
4143        {
4144            return EGL_BAD_PARAMETER;
4145        }
4146
4147        if(texture->isShared(textureTarget, textureLevel))   // Bound to an EGLSurface or already an EGLImage sibling
4148        {
4149            return EGL_BAD_ACCESS;
4150        }
4151
4152        if(textureLevel != 0 && !texture->isSamplerComplete())
4153        {
4154            return EGL_BAD_PARAMETER;
4155        }
4156
4157        if(textureLevel == 0 && !(texture->isSamplerComplete() && texture->getLevelCount() == 1))
4158        {
4159            return EGL_BAD_PARAMETER;
4160        }
4161    }
4162    else if(target == EGL_GL_RENDERBUFFER_KHR)
4163    {
4164        es2::Renderbuffer *renderbuffer = getRenderbuffer(name);
4165
4166        if(!renderbuffer)
4167        {
4168            return EGL_BAD_PARAMETER;
4169        }
4170
4171        if(renderbuffer->isShared())   // Already an EGLImage sibling
4172        {
4173            return EGL_BAD_ACCESS;
4174        }
4175    }
4176    else UNREACHABLE(target);
4177
4178	return EGL_SUCCESS;
4179}
4180
4181egl::Image *Context::createSharedImage(EGLenum target, GLuint name, GLuint textureLevel)
4182{
4183	GLenum textureTarget = GL_NONE;
4184
4185    switch(target)
4186    {
4187    case EGL_GL_TEXTURE_2D_KHR:                  textureTarget = GL_TEXTURE_2D;                  break;
4188    case EGL_GL_TEXTURE_CUBE_MAP_POSITIVE_X_KHR: textureTarget = GL_TEXTURE_CUBE_MAP_POSITIVE_X; break;
4189    case EGL_GL_TEXTURE_CUBE_MAP_NEGATIVE_X_KHR: textureTarget = GL_TEXTURE_CUBE_MAP_NEGATIVE_X; break;
4190    case EGL_GL_TEXTURE_CUBE_MAP_POSITIVE_Y_KHR: textureTarget = GL_TEXTURE_CUBE_MAP_POSITIVE_Y; break;
4191    case EGL_GL_TEXTURE_CUBE_MAP_NEGATIVE_Y_KHR: textureTarget = GL_TEXTURE_CUBE_MAP_NEGATIVE_Y; break;
4192    case EGL_GL_TEXTURE_CUBE_MAP_POSITIVE_Z_KHR: textureTarget = GL_TEXTURE_CUBE_MAP_POSITIVE_Z; break;
4193    case EGL_GL_TEXTURE_CUBE_MAP_NEGATIVE_Z_KHR: textureTarget = GL_TEXTURE_CUBE_MAP_NEGATIVE_Z; break;
4194    }
4195
4196    if(textureTarget != GL_NONE)
4197    {
4198        es2::Texture *texture = getTexture(name);
4199
4200        return texture->createSharedImage(textureTarget, textureLevel);
4201    }
4202    else if(target == EGL_GL_RENDERBUFFER_KHR)
4203    {
4204        es2::Renderbuffer *renderbuffer = getRenderbuffer(name);
4205
4206        return renderbuffer->createSharedImage();
4207    }
4208    else UNREACHABLE(target);
4209
4210	return 0;
4211}
4212
4213Device *Context::getDevice()
4214{
4215	return device;
4216}
4217
4218const GLubyte* Context::getExtensions(GLuint index, GLuint* numExt) const
4219{
4220	// Keep list sorted in following order:
4221	// OES extensions
4222	// EXT extensions
4223	// Vendor extensions
4224	static const GLubyte* extensions[] = {
4225		(const GLubyte*)"GL_OES_compressed_ETC1_RGB8_texture",
4226		(const GLubyte*)"GL_OES_depth24",
4227		(const GLubyte*)"GL_OES_depth32",
4228		(const GLubyte*)"GL_OES_depth_texture",
4229		(const GLubyte*)"GL_OES_depth_texture_cube_map",
4230		(const GLubyte*)"GL_OES_EGL_image",
4231		(const GLubyte*)"GL_OES_EGL_image_external",
4232		(const GLubyte*)"GL_OES_EGL_sync",
4233		(const GLubyte*)"GL_OES_element_index_uint",
4234		(const GLubyte*)"GL_OES_framebuffer_object",
4235		(const GLubyte*)"GL_OES_packed_depth_stencil",
4236		(const GLubyte*)"GL_OES_rgb8_rgba8",
4237		(const GLubyte*)"GL_OES_standard_derivatives",
4238		(const GLubyte*)"GL_OES_texture_float",
4239		(const GLubyte*)"GL_OES_texture_float_linear",
4240		(const GLubyte*)"GL_OES_texture_half_float",
4241		(const GLubyte*)"GL_OES_texture_half_float_linear",
4242		(const GLubyte*)"GL_OES_texture_npot",
4243		(const GLubyte*)"GL_OES_texture_3D",
4244		(const GLubyte*)"GL_EXT_blend_minmax",
4245		(const GLubyte*)"GL_EXT_color_buffer_half_float",
4246		(const GLubyte*)"GL_EXT_occlusion_query_boolean",
4247		(const GLubyte*)"GL_EXT_read_format_bgra",
4248#if (S3TC_SUPPORT)
4249		(const GLubyte*)"GL_EXT_texture_compression_dxt1",
4250#endif
4251		(const GLubyte*)"GL_EXT_texture_filter_anisotropic",
4252		(const GLubyte*)"GL_EXT_texture_format_BGRA8888",
4253		(const GLubyte*)"GL_ANGLE_framebuffer_blit",
4254		(const GLubyte*)"GL_NV_framebuffer_blit",
4255		(const GLubyte*)"GL_ANGLE_framebuffer_multisample",
4256#if (S3TC_SUPPORT)
4257		(const GLubyte*)"GL_ANGLE_texture_compression_dxt3",
4258		(const GLubyte*)"GL_ANGLE_texture_compression_dxt5",
4259#endif
4260		(const GLubyte*)"GL_NV_fence",
4261		(const GLubyte*)"GL_EXT_instanced_arrays",
4262		(const GLubyte*)"GL_ANGLE_instanced_arrays",
4263	};
4264	static const GLuint numExtensions = sizeof(extensions) / sizeof(*extensions);
4265
4266	if(numExt)
4267	{
4268		*numExt = numExtensions;
4269		return nullptr;
4270	}
4271
4272	if(index == GL_INVALID_INDEX)
4273	{
4274		static GLubyte* extensionsCat = nullptr;
4275		if(!extensionsCat && (numExtensions > 0))
4276		{
4277			int totalLength = numExtensions; // 1 space between each extension name + terminating null
4278			for(unsigned int i = 0; i < numExtensions; i++)
4279			{
4280				totalLength += strlen(reinterpret_cast<const char*>(extensions[i]));
4281			}
4282			extensionsCat = new GLubyte[totalLength];
4283			extensionsCat[0] = '\0';
4284			for(unsigned int i = 0; i < numExtensions; i++)
4285			{
4286				if(i != 0)
4287				{
4288					strcat(reinterpret_cast<char*>(extensionsCat), " ");
4289				}
4290				strcat(reinterpret_cast<char*>(extensionsCat), reinterpret_cast<const char*>(extensions[i]));
4291			}
4292		}
4293		return extensionsCat;
4294	}
4295
4296	if(index >= numExtensions)
4297	{
4298		return nullptr;
4299	}
4300
4301	return extensions[index];
4302}
4303
4304}
4305
4306egl::Context *es2CreateContext(const egl::Config *config, const egl::Context *shareContext, int clientVersion)
4307{
4308	ASSERT(!shareContext || shareContext->getClientVersion() == clientVersion);   // Should be checked by eglCreateContext
4309	return new es2::Context(config, static_cast<const es2::Context*>(shareContext), clientVersion);
4310}
4311