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