Context.cpp revision 3b39646417ca060f10a06c634bf9b2f430c375ec
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 es1::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 "Framebuffer.h"
23#include "Renderbuffer.h"
24#include "Texture.h"
25#include "VertexDataManager.h"
26#include "IndexDataManager.h"
27#include "libEGL/Display.h"
28#include "libEGL/Surface.h"
29#include "Common/Half.hpp"
30
31#include <EGL/eglext.h>
32
33using std::abs;
34
35namespace es1
36{
37Context::Context(const egl::Config *config, const Context *shareContext)
38    : modelViewStack(MAX_MODELVIEW_STACK_DEPTH),
39      projectionStack(MAX_PROJECTION_STACK_DEPTH),
40	  textureStack0(MAX_TEXTURE_STACK_DEPTH),
41	  textureStack1(MAX_TEXTURE_STACK_DEPTH)
42{
43	sw::Context *context = new sw::Context();
44	device = new es1::Device(context);
45
46	mVertexDataManager = new VertexDataManager(this);
47    mIndexDataManager = new IndexDataManager();
48
49    setClearColor(0.0f, 0.0f, 0.0f, 0.0f);
50
51    mState.depthClearValue = 1.0f;
52    mState.stencilClearValue = 0;
53
54    mState.cullFaceEnabled = false;
55    mState.cullMode = GL_BACK;
56    mState.frontFace = GL_CCW;
57    mState.depthTestEnabled = false;
58    mState.depthFunc = GL_LESS;
59    mState.blendEnabled = false;
60    mState.sourceBlendRGB = GL_ONE;
61    mState.sourceBlendAlpha = GL_ONE;
62    mState.destBlendRGB = GL_ZERO;
63    mState.destBlendAlpha = GL_ZERO;
64    mState.blendEquationRGB = GL_FUNC_ADD_OES;
65    mState.blendEquationAlpha = GL_FUNC_ADD_OES;
66    mState.stencilTestEnabled = false;
67    mState.stencilFunc = GL_ALWAYS;
68    mState.stencilRef = 0;
69    mState.stencilMask = -1;
70    mState.stencilWritemask = -1;
71    mState.stencilFail = GL_KEEP;
72    mState.stencilPassDepthFail = GL_KEEP;
73    mState.stencilPassDepthPass = GL_KEEP;
74    mState.polygonOffsetFillEnabled = false;
75    mState.polygonOffsetFactor = 0.0f;
76    mState.polygonOffsetUnits = 0.0f;
77    mState.sampleAlphaToCoverageEnabled = false;
78    mState.sampleCoverageEnabled = false;
79    mState.sampleCoverageValue = 1.0f;
80    mState.sampleCoverageInvert = false;
81    mState.scissorTestEnabled = false;
82    mState.ditherEnabled = true;
83	mState.shadeModel = GL_SMOOTH;
84    mState.generateMipmapHint = GL_DONT_CARE;
85	mState.perspectiveCorrectionHint = GL_DONT_CARE;
86	mState.fogHint = GL_DONT_CARE;
87
88    mState.lineWidth = 1.0f;
89
90    mState.viewportX = 0;
91    mState.viewportY = 0;
92    mState.viewportWidth = 0;
93    mState.viewportHeight = 0;
94    mState.zNear = 0.0f;
95    mState.zFar = 1.0f;
96
97    mState.scissorX = 0;
98    mState.scissorY = 0;
99    mState.scissorWidth = 0;
100    mState.scissorHeight = 0;
101
102    mState.colorMaskRed = true;
103    mState.colorMaskGreen = true;
104    mState.colorMaskBlue = true;
105    mState.colorMaskAlpha = true;
106    mState.depthMask = true;
107
108	for(int i = 0; i < MAX_TEXTURE_UNITS; i++)
109	{
110		mState.textureUnit[i].color = {0, 0, 0, 0};
111		mState.textureUnit[i].environmentMode = GL_MODULATE;
112		mState.textureUnit[i].combineRGB = GL_MODULATE;
113		mState.textureUnit[i].combineAlpha = GL_MODULATE;
114		mState.textureUnit[i].src0RGB = GL_TEXTURE;
115		mState.textureUnit[i].src1RGB = GL_PREVIOUS;
116		mState.textureUnit[i].src2RGB = GL_CONSTANT;
117		mState.textureUnit[i].src0Alpha = GL_TEXTURE;
118		mState.textureUnit[i].src1Alpha = GL_PREVIOUS;
119		mState.textureUnit[i].src2Alpha = GL_CONSTANT;
120		mState.textureUnit[i].operand0RGB = GL_SRC_COLOR;
121		mState.textureUnit[i].operand1RGB = GL_SRC_COLOR;
122		mState.textureUnit[i].operand2RGB = GL_SRC_ALPHA;
123		mState.textureUnit[i].operand0Alpha = GL_SRC_ALPHA;
124		mState.textureUnit[i].operand1Alpha = GL_SRC_ALPHA;
125		mState.textureUnit[i].operand2Alpha = GL_SRC_ALPHA;
126	}
127
128    if(shareContext != NULL)
129    {
130        mResourceManager = shareContext->mResourceManager;
131        mResourceManager->addRef();
132    }
133    else
134    {
135        mResourceManager = new ResourceManager();
136    }
137
138    // [OpenGL ES 2.0.24] section 3.7 page 83:
139    // In the initial state, TEXTURE_2D and TEXTURE_CUBE_MAP have twodimensional
140    // and cube map texture state vectors respectively associated with them.
141    // In order that access to these initial textures not be lost, they are treated as texture
142    // objects all of whose names are 0.
143
144    mTexture2DZero = new Texture2D(0);
145    mTextureExternalZero = new TextureExternal(0);
146
147    mState.activeSampler = 0;
148    bindArrayBuffer(0);
149    bindElementArrayBuffer(0);
150    bindTexture2D(0);
151    bindFramebuffer(0);
152    bindRenderbuffer(0);
153
154    mState.packAlignment = 4;
155    mState.unpackAlignment = 4;
156
157    mInvalidEnum = false;
158    mInvalidValue = false;
159    mInvalidOperation = false;
160    mOutOfMemory = false;
161    mInvalidFramebufferOperation = false;
162	mMatrixStackOverflow = false;
163	mMatrixStackUnderflow = false;
164
165	lightingEnabled = false;
166
167	for(int i = 0; i < MAX_LIGHTS; i++)
168	{
169		light[i].enabled = false;
170		light[i].ambient = {0.0f, 0.0f, 0.0f, 1.0f};
171		light[i].diffuse = {0.0f, 0.0f, 0.0f, 1.0f};
172		light[i].specular = {0.0f, 0.0f, 0.0f, 1.0f};
173		light[i].position = {0.0f, 0.0f, 1.0f, 0.0f};
174		light[i].direction = {0.0f, 0.0f, -1.0f};
175		light[i].attenuation = {1.0f, 0.0f, 0.0f};
176		light[i].spotExponent = 0.0f;
177		light[i].spotCutoffAngle = 180.0f;
178	}
179
180	light[0].diffuse = {1.0f, 1.0f, 1.0f, 1.0f};
181	light[0].specular = {1.0f, 1.0f, 1.0f, 1.0f};
182
183	globalAmbient = {0.2f, 0.2f, 0.2f, 1.0f};
184	materialAmbient = {0.2f, 0.2f, 0.2f, 1.0f};
185	materialDiffuse = {0.8f, 0.8f, 0.8f, 1.0f};
186	materialSpecular = {0.0f, 0.0f, 0.0f, 1.0f};
187	materialEmission = {0.0f, 0.0f, 0.0f, 1.0f};
188	materialShininess = 0.0f;
189	lightModelTwoSide = false;
190
191	matrixMode = GL_MODELVIEW;
192
193	for(int i = 0; i < MAX_TEXTURE_UNITS; i++)
194	{
195		texture2Denabled[i] = false;
196		textureExternalEnabled[i] = false;
197	}
198
199	clientTexture = GL_TEXTURE0;
200
201	setVertexAttrib(sw::Color0, 1.0f, 1.0f, 1.0f, 1.0f);
202
203	for(int i = 0; i < MAX_TEXTURE_UNITS; i++)
204	{
205		setVertexAttrib(sw::TexCoord0 + i, 0.0f, 0.0f, 0.0f, 1.0f);
206	}
207
208	setVertexAttrib(sw::Normal, 0.0f, 0.0f, 1.0f, 1.0f);
209	setVertexAttrib(sw::PointSize, 1.0f, 1.0f, 1.0f, 1.0f);
210
211	clipFlags = 0;
212
213	alphaTestEnabled = false;
214	alphaTestFunc = GL_ALWAYS;
215	alphaTestRef = 0;
216
217	fogEnabled = false;
218	fogMode = GL_EXP;
219	fogDensity = 1.0f;
220	fogStart = 0.0f;
221	fogEnd = 1.0f;
222	fogColor = {0, 0, 0, 0};
223
224	lineSmoothEnabled = false;
225	colorMaterialEnabled = false;
226	normalizeEnabled = false;
227	rescaleNormalEnabled = false;
228	multisampleEnabled = true;
229	sampleAlphaToOneEnabled = false;
230
231	colorLogicOpEnabled = false;
232	logicalOperation = GL_COPY;
233
234	pointSpriteEnabled = false;
235	pointSmoothEnabled = false;
236	pointSizeMin = 0.0f;
237	pointSizeMax = 1.0f;
238	pointDistanceAttenuation = {1.0f, 0.0f, 0.0f};
239	pointFadeThresholdSize = 1.0f;
240
241    mHasBeenCurrent = false;
242
243    markAllStateDirty();
244}
245
246Context::~Context()
247{
248    while(!mFramebufferMap.empty())
249    {
250        deleteFramebuffer(mFramebufferMap.begin()->first);
251    }
252
253    for(int type = 0; type < TEXTURE_TYPE_COUNT; type++)
254    {
255        for(int sampler = 0; sampler < MAX_TEXTURE_UNITS; sampler++)
256        {
257            mState.samplerTexture[type][sampler] = NULL;
258        }
259    }
260
261    for(int i = 0; i < MAX_VERTEX_ATTRIBS; i++)
262    {
263        mState.vertexAttribute[i].mBoundBuffer = NULL;
264    }
265
266    mState.arrayBuffer = NULL;
267    mState.elementArrayBuffer = NULL;
268    mState.renderbuffer = NULL;
269
270    mTexture2DZero = NULL;
271    mTextureExternalZero = NULL;
272
273    delete mVertexDataManager;
274    delete mIndexDataManager;
275
276    mResourceManager->release();
277	delete device;
278}
279
280void Context::makeCurrent(egl::Surface *surface)
281{
282    if(!mHasBeenCurrent)
283    {
284        mState.viewportX = 0;
285        mState.viewportY = 0;
286        mState.viewportWidth = surface->getWidth();
287        mState.viewportHeight = surface->getHeight();
288
289        mState.scissorX = 0;
290        mState.scissorY = 0;
291        mState.scissorWidth = surface->getWidth();
292        mState.scissorHeight = surface->getHeight();
293
294        mHasBeenCurrent = true;
295    }
296
297    // Wrap the existing resources into GL objects and assign them to the '0' names
298    egl::Image *defaultRenderTarget = surface->getRenderTarget();
299    egl::Image *depthStencil = surface->getDepthStencil();
300
301    Colorbuffer *colorbufferZero = new Colorbuffer(defaultRenderTarget);
302    DepthStencilbuffer *depthStencilbufferZero = new DepthStencilbuffer(depthStencil);
303    Framebuffer *framebufferZero = new DefaultFramebuffer(colorbufferZero, depthStencilbufferZero);
304
305    setFramebufferZero(framebufferZero);
306
307    if(defaultRenderTarget)
308    {
309        defaultRenderTarget->release();
310    }
311
312    if(depthStencil)
313    {
314        depthStencil->release();
315    }
316
317    markAllStateDirty();
318}
319
320int Context::getClientVersion() const
321{
322	return 1;
323}
324
325// This function will set all of the state-related dirty flags, so that all state is set during next pre-draw.
326void Context::markAllStateDirty()
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::setCullFaceEnabled(bool enabled)
357{
358    mState.cullFaceEnabled = enabled;
359}
360
361bool Context::isCullFaceEnabled() const
362{
363    return mState.cullFaceEnabled;
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::setDepthTestEnabled(bool enabled)
381{
382    if(mState.depthTestEnabled != enabled)
383    {
384        mState.depthTestEnabled = enabled;
385        mDepthStateDirty = true;
386    }
387}
388
389bool Context::isDepthTestEnabled() const
390{
391    return mState.depthTestEnabled;
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::setAlphaTestEnabled(bool enabled)
410{
411	alphaTestEnabled = enabled;
412}
413
414bool Context::isAlphaTestEnabled() const
415{
416	return alphaTestEnabled;
417}
418
419void Context::setAlphaFunc(GLenum alphaFunc, GLclampf reference)
420{
421	alphaTestFunc = alphaFunc;
422	alphaTestRef = reference;
423}
424
425void Context::setBlendEnabled(bool enabled)
426{
427    if(mState.blendEnabled != enabled)
428    {
429        mState.blendEnabled = enabled;
430        mBlendStateDirty = true;
431    }
432}
433
434bool Context::isBlendEnabled() const
435{
436    return mState.blendEnabled;
437}
438
439void Context::setBlendFactors(GLenum sourceRGB, GLenum destRGB, GLenum sourceAlpha, GLenum destAlpha)
440{
441    if(mState.sourceBlendRGB != sourceRGB ||
442       mState.sourceBlendAlpha != sourceAlpha ||
443       mState.destBlendRGB != destRGB ||
444       mState.destBlendAlpha != destAlpha)
445    {
446        mState.sourceBlendRGB = sourceRGB;
447        mState.destBlendRGB = destRGB;
448        mState.sourceBlendAlpha = sourceAlpha;
449        mState.destBlendAlpha = destAlpha;
450        mBlendStateDirty = true;
451    }
452}
453
454void Context::setBlendEquation(GLenum rgbEquation, GLenum alphaEquation)
455{
456    if(mState.blendEquationRGB != rgbEquation ||
457       mState.blendEquationAlpha != alphaEquation)
458    {
459        mState.blendEquationRGB = rgbEquation;
460        mState.blendEquationAlpha = alphaEquation;
461        mBlendStateDirty = true;
462    }
463}
464
465void Context::setStencilTestEnabled(bool enabled)
466{
467    if(mState.stencilTestEnabled != enabled)
468    {
469        mState.stencilTestEnabled = enabled;
470        mStencilStateDirty = true;
471    }
472}
473
474bool Context::isStencilTestEnabled() const
475{
476    return mState.stencilTestEnabled;
477}
478
479void Context::setStencilParams(GLenum stencilFunc, GLint stencilRef, GLuint stencilMask)
480{
481    if(mState.stencilFunc != stencilFunc ||
482       mState.stencilRef != stencilRef ||
483       mState.stencilMask != stencilMask)
484    {
485        mState.stencilFunc = stencilFunc;
486        mState.stencilRef = (stencilRef > 0) ? stencilRef : 0;
487        mState.stencilMask = stencilMask;
488        mStencilStateDirty = true;
489    }
490}
491
492void Context::setStencilWritemask(GLuint stencilWritemask)
493{
494    if(mState.stencilWritemask != stencilWritemask)
495    {
496        mState.stencilWritemask = stencilWritemask;
497        mStencilStateDirty = true;
498    }
499}
500
501void Context::setStencilOperations(GLenum stencilFail, GLenum stencilPassDepthFail, GLenum stencilPassDepthPass)
502{
503    if(mState.stencilFail != stencilFail ||
504       mState.stencilPassDepthFail != stencilPassDepthFail ||
505       mState.stencilPassDepthPass != stencilPassDepthPass)
506    {
507        mState.stencilFail = stencilFail;
508        mState.stencilPassDepthFail = stencilPassDepthFail;
509        mState.stencilPassDepthPass = stencilPassDepthPass;
510        mStencilStateDirty = true;
511    }
512}
513
514void Context::setPolygonOffsetFillEnabled(bool enabled)
515{
516    if(mState.polygonOffsetFillEnabled != enabled)
517    {
518        mState.polygonOffsetFillEnabled = enabled;
519        mPolygonOffsetStateDirty = true;
520    }
521}
522
523bool Context::isPolygonOffsetFillEnabled() const
524{
525    return mState.polygonOffsetFillEnabled;
526}
527
528void Context::setPolygonOffsetParams(GLfloat factor, GLfloat units)
529{
530    if(mState.polygonOffsetFactor != factor ||
531       mState.polygonOffsetUnits != units)
532    {
533        mState.polygonOffsetFactor = factor;
534        mState.polygonOffsetUnits = units;
535        mPolygonOffsetStateDirty = true;
536    }
537}
538
539void Context::setSampleAlphaToCoverageEnabled(bool enabled)
540{
541    if(mState.sampleAlphaToCoverageEnabled != enabled)
542    {
543        mState.sampleAlphaToCoverageEnabled = enabled;
544        mSampleStateDirty = true;
545    }
546}
547
548bool Context::isSampleAlphaToCoverageEnabled() const
549{
550    return mState.sampleAlphaToCoverageEnabled;
551}
552
553void Context::setSampleCoverageEnabled(bool enabled)
554{
555    if(mState.sampleCoverageEnabled != enabled)
556    {
557        mState.sampleCoverageEnabled = enabled;
558        mSampleStateDirty = true;
559    }
560}
561
562bool Context::isSampleCoverageEnabled() const
563{
564    return mState.sampleCoverageEnabled;
565}
566
567void Context::setSampleCoverageParams(GLclampf value, bool invert)
568{
569    if(mState.sampleCoverageValue != value ||
570       mState.sampleCoverageInvert != invert)
571    {
572        mState.sampleCoverageValue = value;
573        mState.sampleCoverageInvert = invert;
574        mSampleStateDirty = true;
575    }
576}
577
578void Context::setScissorTestEnabled(bool enabled)
579{
580    mState.scissorTestEnabled = enabled;
581}
582
583bool Context::isScissorTestEnabled() const
584{
585    return mState.scissorTestEnabled;
586}
587
588void Context::setShadeModel(GLenum mode)
589{
590    mState.shadeModel = mode;
591}
592
593void Context::setDitherEnabled(bool enabled)
594{
595    if(mState.ditherEnabled != enabled)
596    {
597        mState.ditherEnabled = enabled;
598        mDitherStateDirty = true;
599    }
600}
601
602bool Context::isDitherEnabled() const
603{
604    return mState.ditherEnabled;
605}
606
607void Context::setLightingEnabled(bool enable)
608{
609    lightingEnabled = enable;
610}
611
612bool Context::isLightingEnabled() const
613{
614	return lightingEnabled;
615}
616
617void Context::setLightEnabled(int index, bool enable)
618{
619    light[index].enabled = enable;
620}
621
622bool Context::isLightEnabled(int index) const
623{
624	return light[index].enabled;
625}
626
627void Context::setLightAmbient(int index, float r, float g, float b, float a)
628{
629	light[index].ambient = {r, g, b, a};
630}
631
632void Context::setLightDiffuse(int index, float r, float g, float b, float a)
633{
634	light[index].diffuse = {r, g, b, a};
635}
636
637void Context::setLightSpecular(int index, float r, float g, float b, float a)
638{
639	light[index].specular = {r, g, b, a};
640}
641
642void Context::setLightPosition(int index, float x, float y, float z, float w)
643{
644	sw::float4 v = {x, y, z, w};
645
646	// Transform from object coordinates to eye coordinates
647	v = modelViewStack.current() * v;
648
649	light[index].position = {v.x, v.y, v.z, v.w};
650}
651
652void Context::setLightDirection(int index, float x, float y, float z)
653{
654	// FIXME: Transform by inverse of 3x3 model-view matrix
655	light[index].direction = {x, y, z};
656}
657
658void Context::setLightAttenuationConstant(int index, float constant)
659{
660	light[index].attenuation.constant = constant;
661}
662
663void Context::setLightAttenuationLinear(int index, float linear)
664{
665	light[index].attenuation.linear = linear;
666}
667
668void Context::setLightAttenuationQuadratic(int index, float quadratic)
669{
670	light[index].attenuation.quadratic = quadratic;
671}
672
673void Context::setSpotLightExponent(int index, float exponent)
674{
675	light[index].spotExponent = exponent;
676}
677
678void Context::setSpotLightCutoff(int index, float cutoff)
679{
680	light[index].spotCutoffAngle = cutoff;
681}
682
683void Context::setGlobalAmbient(float red, float green, float blue, float alpha)
684{
685	globalAmbient.red = red;
686	globalAmbient.green = green;
687	globalAmbient.blue = blue;
688	globalAmbient.alpha = alpha;
689}
690
691void Context::setMaterialAmbient(float red, float green, float blue, float alpha)
692{
693	materialAmbient.red = red;
694	materialAmbient.green = green;
695	materialAmbient.blue = blue;
696	materialAmbient.alpha = alpha;
697}
698
699void Context::setMaterialDiffuse(float red, float green, float blue, float alpha)
700{
701	materialDiffuse.red = red;
702	materialDiffuse.green = green;
703	materialDiffuse.blue = blue;
704	materialDiffuse.alpha = alpha;
705}
706
707void Context::setMaterialSpecular(float red, float green, float blue, float alpha)
708{
709	materialSpecular.red = red;
710	materialSpecular.green = green;
711	materialSpecular.blue = blue;
712	materialSpecular.alpha = alpha;
713}
714
715void Context::setMaterialEmission(float red, float green, float blue, float alpha)
716{
717	materialEmission.red = red;
718	materialEmission.green = green;
719	materialEmission.blue = blue;
720	materialEmission.alpha = alpha;
721}
722
723void Context::setMaterialShininess(float shininess)
724{
725	materialShininess = shininess;
726}
727
728void Context::setLightModelTwoSide(bool enable)
729{
730	lightModelTwoSide = enable;
731}
732
733void Context::setFogEnabled(bool enable)
734{
735	fogEnabled = enable;
736}
737
738bool Context::isFogEnabled() const
739{
740	return fogEnabled;
741}
742
743void Context::setFogMode(GLenum mode)
744{
745	fogMode = mode;
746}
747
748void Context::setFogDensity(float fogDensity)
749{
750	this->fogDensity = fogDensity;
751}
752
753void Context::setFogStart(float fogStart)
754{
755	this->fogStart = fogStart;
756}
757
758void Context::setFogEnd(float fogEnd)
759{
760	this->fogEnd = fogEnd;
761}
762
763void Context::setFogColor(float r, float g, float b, float a)
764{
765	this->fogColor = {r, g, b, a};
766}
767
768void Context::setTexture2Denabled(bool enable)
769{
770    texture2Denabled[mState.activeSampler] = enable;
771}
772
773bool Context::isTexture2Denabled() const
774{
775	return texture2Denabled[mState.activeSampler];
776}
777
778void Context::setTextureExternalEnabled(bool enable)
779{
780    textureExternalEnabled[mState.activeSampler] = enable;
781}
782
783bool Context::isTextureExternalEnabled() const
784{
785    return textureExternalEnabled[mState.activeSampler];
786}
787
788void Context::setLineWidth(GLfloat width)
789{
790    mState.lineWidth = width;
791	device->setLineWidth(clamp(width, ALIASED_LINE_WIDTH_RANGE_MIN, ALIASED_LINE_WIDTH_RANGE_MAX));
792}
793
794void Context::setGenerateMipmapHint(GLenum hint)
795{
796    mState.generateMipmapHint = hint;
797}
798
799void Context::setPerspectiveCorrectionHint(GLenum hint)
800{
801    mState.perspectiveCorrectionHint = hint;
802}
803
804void Context::setFogHint(GLenum hint)
805{
806    mState.fogHint = hint;
807}
808
809void Context::setViewportParams(GLint x, GLint y, GLsizei width, GLsizei height)
810{
811    mState.viewportX = x;
812    mState.viewportY = y;
813    mState.viewportWidth = width;
814    mState.viewportHeight = height;
815}
816
817void Context::setScissorParams(GLint x, GLint y, GLsizei width, GLsizei height)
818{
819    mState.scissorX = x;
820    mState.scissorY = y;
821    mState.scissorWidth = width;
822    mState.scissorHeight = height;
823}
824
825void Context::setColorMask(bool red, bool green, bool blue, bool alpha)
826{
827    if(mState.colorMaskRed != red || mState.colorMaskGreen != green ||
828       mState.colorMaskBlue != blue || mState.colorMaskAlpha != alpha)
829    {
830        mState.colorMaskRed = red;
831        mState.colorMaskGreen = green;
832        mState.colorMaskBlue = blue;
833        mState.colorMaskAlpha = alpha;
834        mMaskStateDirty = true;
835    }
836}
837
838void Context::setDepthMask(bool mask)
839{
840    if(mState.depthMask != mask)
841    {
842        mState.depthMask = mask;
843        mMaskStateDirty = true;
844    }
845}
846
847void Context::setActiveSampler(unsigned int active)
848{
849    mState.activeSampler = active;
850}
851
852GLuint Context::getFramebufferName() const
853{
854    return mState.framebuffer;
855}
856
857GLuint Context::getRenderbufferName() const
858{
859    return mState.renderbuffer.name();
860}
861
862GLuint Context::getArrayBufferName() const
863{
864    return mState.arrayBuffer.name();
865}
866
867void Context::setVertexAttribArrayEnabled(unsigned int attribNum, bool enabled)
868{
869    mState.vertexAttribute[attribNum].mArrayEnabled = enabled;
870}
871
872const VertexAttribute &Context::getVertexAttribState(unsigned int attribNum)
873{
874    return mState.vertexAttribute[attribNum];
875}
876
877void Context::setVertexAttribState(unsigned int attribNum, Buffer *boundBuffer, GLint size, GLenum type, bool normalized,
878                                   GLsizei stride, const void *pointer)
879{
880    mState.vertexAttribute[attribNum].mBoundBuffer = boundBuffer;
881    mState.vertexAttribute[attribNum].mSize = size;
882    mState.vertexAttribute[attribNum].mType = type;
883    mState.vertexAttribute[attribNum].mNormalized = normalized;
884    mState.vertexAttribute[attribNum].mStride = stride;
885    mState.vertexAttribute[attribNum].mPointer = pointer;
886}
887
888const void *Context::getVertexAttribPointer(unsigned int attribNum) const
889{
890    return mState.vertexAttribute[attribNum].mPointer;
891}
892
893const VertexAttributeArray &Context::getVertexAttributes()
894{
895    return mState.vertexAttribute;
896}
897
898void Context::setPackAlignment(GLint alignment)
899{
900    mState.packAlignment = alignment;
901}
902
903GLint Context::getPackAlignment() const
904{
905    return mState.packAlignment;
906}
907
908void Context::setUnpackAlignment(GLint alignment)
909{
910    mState.unpackAlignment = alignment;
911}
912
913GLint Context::getUnpackAlignment() const
914{
915    return mState.unpackAlignment;
916}
917
918GLuint Context::createBuffer()
919{
920    return mResourceManager->createBuffer();
921}
922
923GLuint Context::createTexture()
924{
925    return mResourceManager->createTexture();
926}
927
928GLuint Context::createRenderbuffer()
929{
930    return mResourceManager->createRenderbuffer();
931}
932
933// Returns an unused framebuffer name
934GLuint Context::createFramebuffer()
935{
936    GLuint handle = mFramebufferNameSpace.allocate();
937
938    mFramebufferMap[handle] = NULL;
939
940    return handle;
941}
942
943void Context::deleteBuffer(GLuint buffer)
944{
945    if(mResourceManager->getBuffer(buffer))
946    {
947        detachBuffer(buffer);
948    }
949
950    mResourceManager->deleteBuffer(buffer);
951}
952
953void Context::deleteTexture(GLuint texture)
954{
955    if(mResourceManager->getTexture(texture))
956    {
957        detachTexture(texture);
958    }
959
960    mResourceManager->deleteTexture(texture);
961}
962
963void Context::deleteRenderbuffer(GLuint renderbuffer)
964{
965    if(mResourceManager->getRenderbuffer(renderbuffer))
966    {
967        detachRenderbuffer(renderbuffer);
968    }
969
970    mResourceManager->deleteRenderbuffer(renderbuffer);
971}
972
973void Context::deleteFramebuffer(GLuint framebuffer)
974{
975    FramebufferMap::iterator framebufferObject = mFramebufferMap.find(framebuffer);
976
977    if(framebufferObject != mFramebufferMap.end())
978    {
979        detachFramebuffer(framebuffer);
980
981        mFramebufferNameSpace.release(framebufferObject->first);
982        delete framebufferObject->second;
983        mFramebufferMap.erase(framebufferObject);
984    }
985}
986
987Buffer *Context::getBuffer(GLuint handle)
988{
989    return mResourceManager->getBuffer(handle);
990}
991
992Texture *Context::getTexture(GLuint handle)
993{
994    return mResourceManager->getTexture(handle);
995}
996
997Renderbuffer *Context::getRenderbuffer(GLuint handle)
998{
999    return mResourceManager->getRenderbuffer(handle);
1000}
1001
1002Framebuffer *Context::getFramebuffer()
1003{
1004    return getFramebuffer(mState.framebuffer);
1005}
1006
1007void Context::bindArrayBuffer(unsigned int buffer)
1008{
1009    mResourceManager->checkBufferAllocation(buffer);
1010
1011    mState.arrayBuffer = getBuffer(buffer);
1012}
1013
1014void Context::bindElementArrayBuffer(unsigned int buffer)
1015{
1016    mResourceManager->checkBufferAllocation(buffer);
1017
1018    mState.elementArrayBuffer = getBuffer(buffer);
1019}
1020
1021void Context::bindTexture2D(GLuint texture)
1022{
1023    mResourceManager->checkTextureAllocation(texture, TEXTURE_2D);
1024
1025    mState.samplerTexture[TEXTURE_2D][mState.activeSampler] = getTexture(texture);
1026}
1027
1028void Context::bindTextureExternal(GLuint texture)
1029{
1030    mResourceManager->checkTextureAllocation(texture, TEXTURE_EXTERNAL);
1031
1032    mState.samplerTexture[TEXTURE_EXTERNAL][mState.activeSampler] = getTexture(texture);
1033}
1034
1035void Context::bindFramebuffer(GLuint framebuffer)
1036{
1037    if(!getFramebuffer(framebuffer))
1038    {
1039        mFramebufferMap[framebuffer] = new Framebuffer();
1040    }
1041
1042    mState.framebuffer = framebuffer;
1043}
1044
1045void Context::bindRenderbuffer(GLuint renderbuffer)
1046{
1047    mState.renderbuffer = getRenderbuffer(renderbuffer);
1048}
1049
1050void Context::setFramebufferZero(Framebuffer *buffer)
1051{
1052    delete mFramebufferMap[0];
1053    mFramebufferMap[0] = buffer;
1054}
1055
1056void Context::setRenderbufferStorage(RenderbufferStorage *renderbuffer)
1057{
1058    Renderbuffer *renderbufferObject = mState.renderbuffer;
1059    renderbufferObject->setStorage(renderbuffer);
1060}
1061
1062Framebuffer *Context::getFramebuffer(unsigned int handle)
1063{
1064    FramebufferMap::iterator framebuffer = mFramebufferMap.find(handle);
1065
1066    if(framebuffer == mFramebufferMap.end())
1067    {
1068        return NULL;
1069    }
1070    else
1071    {
1072        return framebuffer->second;
1073    }
1074}
1075
1076Buffer *Context::getArrayBuffer()
1077{
1078    return mState.arrayBuffer;
1079}
1080
1081Buffer *Context::getElementArrayBuffer()
1082{
1083    return mState.elementArrayBuffer;
1084}
1085
1086Texture2D *Context::getTexture2D()
1087{
1088    return static_cast<Texture2D*>(getSamplerTexture(mState.activeSampler, TEXTURE_2D));
1089}
1090
1091TextureExternal *Context::getTextureExternal()
1092{
1093    return static_cast<TextureExternal*>(getSamplerTexture(mState.activeSampler, TEXTURE_EXTERNAL));
1094}
1095
1096Texture *Context::getSamplerTexture(unsigned int sampler, TextureType type)
1097{
1098    GLuint texid = mState.samplerTexture[type][sampler].name();
1099
1100    if(texid == 0)   // Special case: 0 refers to different initial textures based on the target
1101    {
1102        switch(type)
1103        {
1104        case TEXTURE_2D: return mTexture2DZero;
1105        case TEXTURE_EXTERNAL: return mTextureExternalZero;
1106        default: UNREACHABLE(type);
1107        }
1108    }
1109
1110    return mState.samplerTexture[type][sampler];
1111}
1112
1113bool Context::getBooleanv(GLenum pname, GLboolean *params)
1114{
1115    switch(pname)
1116    {
1117    case GL_SAMPLE_COVERAGE_INVERT:   *params = mState.sampleCoverageInvert;         break;
1118    case GL_DEPTH_WRITEMASK:          *params = mState.depthMask;                    break;
1119    case GL_COLOR_WRITEMASK:
1120        params[0] = mState.colorMaskRed;
1121        params[1] = mState.colorMaskGreen;
1122        params[2] = mState.colorMaskBlue;
1123        params[3] = mState.colorMaskAlpha;
1124        break;
1125    case GL_CULL_FACE:                *params = mState.cullFaceEnabled;              break;
1126    case GL_POLYGON_OFFSET_FILL:      *params = mState.polygonOffsetFillEnabled;     break;
1127    case GL_SAMPLE_ALPHA_TO_COVERAGE: *params = mState.sampleAlphaToCoverageEnabled; break;
1128    case GL_SAMPLE_COVERAGE:          *params = mState.sampleCoverageEnabled;        break;
1129    case GL_SCISSOR_TEST:             *params = mState.scissorTestEnabled;           break;
1130    case GL_STENCIL_TEST:             *params = mState.stencilTestEnabled;           break;
1131    case GL_DEPTH_TEST:               *params = mState.depthTestEnabled;             break;
1132    case GL_BLEND:                    *params = mState.blendEnabled;                 break;
1133    case GL_DITHER:                   *params = mState.ditherEnabled;                break;
1134	case GL_LIGHT_MODEL_TWO_SIDE:     *params = lightModelTwoSide;                   break;
1135    default:
1136        return false;
1137    }
1138
1139    return true;
1140}
1141
1142bool Context::getFloatv(GLenum pname, GLfloat *params)
1143{
1144    // Please note: DEPTH_CLEAR_VALUE is included in our internal getFloatv implementation
1145    // because it is stored as a float, despite the fact that the GL ES 2.0 spec names
1146    // GetIntegerv as its native query function. As it would require conversion in any
1147    // case, this should make no difference to the calling application.
1148    switch(pname)
1149    {
1150    case GL_LINE_WIDTH:               *params = mState.lineWidth;            break;
1151    case GL_SAMPLE_COVERAGE_VALUE:    *params = mState.sampleCoverageValue;  break;
1152    case GL_DEPTH_CLEAR_VALUE:        *params = mState.depthClearValue;      break;
1153    case GL_POLYGON_OFFSET_FACTOR:    *params = mState.polygonOffsetFactor;  break;
1154    case GL_POLYGON_OFFSET_UNITS:     *params = mState.polygonOffsetUnits;   break;
1155    case GL_ALIASED_LINE_WIDTH_RANGE:
1156        params[0] = ALIASED_LINE_WIDTH_RANGE_MIN;
1157        params[1] = ALIASED_LINE_WIDTH_RANGE_MAX;
1158        break;
1159    case GL_ALIASED_POINT_SIZE_RANGE:
1160        params[0] = ALIASED_POINT_SIZE_RANGE_MIN;
1161        params[1] = ALIASED_POINT_SIZE_RANGE_MAX;
1162        break;
1163	case GL_SMOOTH_LINE_WIDTH_RANGE:
1164        params[0] = SMOOTH_LINE_WIDTH_RANGE_MIN;
1165        params[1] = SMOOTH_LINE_WIDTH_RANGE_MAX;
1166        break;
1167    case GL_SMOOTH_POINT_SIZE_RANGE:
1168        params[0] = SMOOTH_POINT_SIZE_RANGE_MIN;
1169        params[1] = SMOOTH_POINT_SIZE_RANGE_MAX;
1170        break;
1171    case GL_DEPTH_RANGE:
1172        params[0] = mState.zNear;
1173        params[1] = mState.zFar;
1174        break;
1175    case GL_COLOR_CLEAR_VALUE:
1176        params[0] = mState.colorClearValue.red;
1177        params[1] = mState.colorClearValue.green;
1178        params[2] = mState.colorClearValue.blue;
1179        params[3] = mState.colorClearValue.alpha;
1180        break;
1181	case GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT:
1182        *params = MAX_TEXTURE_MAX_ANISOTROPY;
1183		break;
1184	case GL_MODELVIEW_MATRIX:
1185		for(int i = 0; i < 16; i++)
1186		{
1187			params[i] = modelViewStack.current()[i % 4][i / 4];
1188		}
1189		break;
1190	case GL_PROJECTION_MATRIX:
1191		for(int i = 0; i < 16; i++)
1192		{
1193			params[i] = projectionStack.current()[i % 4][i / 4];
1194		}
1195		break;
1196    default:
1197        return false;
1198    }
1199
1200    return true;
1201}
1202
1203bool Context::getIntegerv(GLenum pname, GLint *params)
1204{
1205    // Please note: DEPTH_CLEAR_VALUE is not included in our internal getIntegerv implementation
1206    // because it is stored as a float, despite the fact that the GL ES 2.0 spec names
1207    // GetIntegerv as its native query function. As it would require conversion in any
1208    // case, this should make no difference to the calling application. You may find it in
1209    // Context::getFloatv.
1210    switch(pname)
1211    {
1212    case GL_ARRAY_BUFFER_BINDING:             *params = mState.arrayBuffer.name();            break;
1213    case GL_ELEMENT_ARRAY_BUFFER_BINDING:     *params = mState.elementArrayBuffer.name();     break;
1214	case GL_FRAMEBUFFER_BINDING_OES:          *params = mState.framebuffer;                   break;
1215    case GL_RENDERBUFFER_BINDING_OES:         *params = mState.renderbuffer.name();           break;
1216    case GL_PACK_ALIGNMENT:                   *params = mState.packAlignment;                 break;
1217    case GL_UNPACK_ALIGNMENT:                 *params = mState.unpackAlignment;               break;
1218    case GL_GENERATE_MIPMAP_HINT:             *params = mState.generateMipmapHint;            break;
1219	case GL_PERSPECTIVE_CORRECTION_HINT:      *params = mState.perspectiveCorrectionHint;     break;
1220    case GL_ACTIVE_TEXTURE:                   *params = (mState.activeSampler + GL_TEXTURE0); break;
1221    case GL_STENCIL_FUNC:                     *params = mState.stencilFunc;                   break;
1222    case GL_STENCIL_REF:                      *params = mState.stencilRef;                    break;
1223    case GL_STENCIL_VALUE_MASK:               *params = mState.stencilMask;                   break;
1224    case GL_STENCIL_FAIL:                     *params = mState.stencilFail;                   break;
1225    case GL_STENCIL_PASS_DEPTH_FAIL:          *params = mState.stencilPassDepthFail;          break;
1226    case GL_STENCIL_PASS_DEPTH_PASS:          *params = mState.stencilPassDepthPass;          break;
1227    case GL_DEPTH_FUNC:                       *params = mState.depthFunc;                     break;
1228    case GL_BLEND_SRC_RGB_OES:                *params = mState.sourceBlendRGB;                break;
1229    case GL_BLEND_SRC_ALPHA_OES:              *params = mState.sourceBlendAlpha;              break;
1230    case GL_BLEND_DST_RGB_OES:                *params = mState.destBlendRGB;                  break;
1231    case GL_BLEND_DST_ALPHA_OES:              *params = mState.destBlendAlpha;                break;
1232    case GL_BLEND_EQUATION_RGB_OES:           *params = mState.blendEquationRGB;              break;
1233    case GL_BLEND_EQUATION_ALPHA_OES:         *params = mState.blendEquationAlpha;            break;
1234    case GL_STENCIL_WRITEMASK:                *params = mState.stencilWritemask;              break;
1235    case GL_STENCIL_CLEAR_VALUE:              *params = mState.stencilClearValue;             break;
1236    case GL_SUBPIXEL_BITS:                    *params = 4;                                    break;
1237	case GL_MAX_TEXTURE_SIZE:                 *params = IMPLEMENTATION_MAX_TEXTURE_SIZE;      break;
1238	case GL_NUM_COMPRESSED_TEXTURE_FORMATS:   *params = NUM_COMPRESSED_TEXTURE_FORMATS;       break;
1239	case GL_SAMPLE_BUFFERS:
1240    case GL_SAMPLES:
1241        {
1242            Framebuffer *framebuffer = getFramebuffer();
1243			int width, height, samples;
1244
1245            if(framebuffer->completeness(width, height, samples) == GL_FRAMEBUFFER_COMPLETE_OES)
1246            {
1247                switch(pname)
1248                {
1249                case GL_SAMPLE_BUFFERS:
1250                    if(samples > 1)
1251                    {
1252                        *params = 1;
1253                    }
1254                    else
1255                    {
1256                        *params = 0;
1257                    }
1258                    break;
1259                case GL_SAMPLES:
1260                    *params = samples;
1261                    break;
1262                }
1263            }
1264            else
1265            {
1266                *params = 0;
1267            }
1268        }
1269        break;
1270    case GL_IMPLEMENTATION_COLOR_READ_TYPE_OES:
1271		{
1272			Framebuffer *framebuffer = getFramebuffer();
1273			*params = framebuffer->getImplementationColorReadType();
1274		}
1275		break;
1276    case GL_IMPLEMENTATION_COLOR_READ_FORMAT_OES:
1277		{
1278			Framebuffer *framebuffer = getFramebuffer();
1279			*params = framebuffer->getImplementationColorReadFormat();
1280		}
1281		break;
1282    case GL_MAX_VIEWPORT_DIMS:
1283        {
1284			int maxDimension = IMPLEMENTATION_MAX_RENDERBUFFER_SIZE;
1285            params[0] = maxDimension;
1286            params[1] = maxDimension;
1287        }
1288        break;
1289    case GL_COMPRESSED_TEXTURE_FORMATS:
1290        {
1291			for(int i = 0; i < NUM_COMPRESSED_TEXTURE_FORMATS; i++)
1292			{
1293				params[i] = compressedTextureFormats[i];
1294			}
1295        }
1296        break;
1297    case GL_VIEWPORT:
1298        params[0] = mState.viewportX;
1299        params[1] = mState.viewportY;
1300        params[2] = mState.viewportWidth;
1301        params[3] = mState.viewportHeight;
1302        break;
1303    case GL_SCISSOR_BOX:
1304        params[0] = mState.scissorX;
1305        params[1] = mState.scissorY;
1306        params[2] = mState.scissorWidth;
1307        params[3] = mState.scissorHeight;
1308        break;
1309    case GL_CULL_FACE_MODE:                   *params = mState.cullMode;                 break;
1310    case GL_FRONT_FACE:                       *params = mState.frontFace;                break;
1311    case GL_RED_BITS:
1312    case GL_GREEN_BITS:
1313    case GL_BLUE_BITS:
1314    case GL_ALPHA_BITS:
1315        {
1316            Framebuffer *framebuffer = getFramebuffer();
1317            Renderbuffer *colorbuffer = framebuffer->getColorbuffer();
1318
1319            if(colorbuffer)
1320            {
1321                switch(pname)
1322                {
1323                case GL_RED_BITS:   *params = colorbuffer->getRedSize();   break;
1324                case GL_GREEN_BITS: *params = colorbuffer->getGreenSize(); break;
1325                case GL_BLUE_BITS:  *params = colorbuffer->getBlueSize();  break;
1326                case GL_ALPHA_BITS: *params = colorbuffer->getAlphaSize(); break;
1327                }
1328            }
1329            else
1330            {
1331                *params = 0;
1332            }
1333        }
1334        break;
1335    case GL_DEPTH_BITS:
1336        {
1337            Framebuffer *framebuffer = getFramebuffer();
1338            Renderbuffer *depthbuffer = framebuffer->getDepthbuffer();
1339
1340            if(depthbuffer)
1341            {
1342                *params = depthbuffer->getDepthSize();
1343            }
1344            else
1345            {
1346                *params = 0;
1347            }
1348        }
1349        break;
1350    case GL_STENCIL_BITS:
1351        {
1352            Framebuffer *framebuffer = getFramebuffer();
1353            Renderbuffer *stencilbuffer = framebuffer->getStencilbuffer();
1354
1355            if(stencilbuffer)
1356            {
1357                *params = stencilbuffer->getStencilSize();
1358            }
1359            else
1360            {
1361                *params = 0;
1362            }
1363        }
1364        break;
1365    case GL_TEXTURE_BINDING_2D:                  *params = mState.samplerTexture[TEXTURE_2D][mState.activeSampler].name();                   break;
1366    case GL_TEXTURE_BINDING_CUBE_MAP_OES:        *params = mState.samplerTexture[TEXTURE_CUBE][mState.activeSampler].name();                 break;
1367    case GL_TEXTURE_BINDING_EXTERNAL_OES:        *params = mState.samplerTexture[TEXTURE_EXTERNAL][mState.activeSampler].name();             break;
1368	case GL_MAX_LIGHTS:                          *params = MAX_LIGHTS;                                                                       break;
1369    case GL_MAX_MODELVIEW_STACK_DEPTH:           *params = MAX_MODELVIEW_STACK_DEPTH;                                                        break;
1370	case GL_MAX_PROJECTION_STACK_DEPTH:          *params = MAX_PROJECTION_STACK_DEPTH;                                                       break;
1371	case GL_MAX_TEXTURE_STACK_DEPTH:             *params = MAX_TEXTURE_STACK_DEPTH;                                                          break;
1372	case GL_MAX_TEXTURE_UNITS:                   *params = MAX_TEXTURE_UNITS;                                                                break;
1373	case GL_MAX_CLIP_PLANES:                     *params = MAX_CLIP_PLANES;                                                                  break;
1374	case GL_POINT_SIZE_ARRAY_TYPE_OES:           *params = mState.vertexAttribute[sw::PointSize].mType;                                      break;
1375	case GL_POINT_SIZE_ARRAY_STRIDE_OES:         *params = mState.vertexAttribute[sw::PointSize].mStride;                                    break;
1376	case GL_POINT_SIZE_ARRAY_BUFFER_BINDING_OES: *params = mState.vertexAttribute[sw::PointSize].mBoundBuffer.name();                        break;
1377	case GL_VERTEX_ARRAY_TYPE:                   *params = mState.vertexAttribute[sw::Position].mType;                                       break;
1378	case GL_VERTEX_ARRAY_STRIDE:                 *params = mState.vertexAttribute[sw::Position].mStride;                                     break;
1379	case GL_VERTEX_ARRAY_BUFFER_BINDING:         *params = mState.vertexAttribute[sw::Position].mBoundBuffer.name();                         break;
1380	case GL_NORMAL_ARRAY_TYPE:                   *params = mState.vertexAttribute[sw::Normal].mType;                                         break;
1381	case GL_NORMAL_ARRAY_STRIDE:                 *params = mState.vertexAttribute[sw::Normal].mStride;                                       break;
1382	case GL_NORMAL_ARRAY_BUFFER_BINDING:         *params = mState.vertexAttribute[sw::Normal].mBoundBuffer.name();                           break;
1383	case GL_COLOR_ARRAY_TYPE:                    *params = mState.vertexAttribute[sw::Color0].mType;                                         break;
1384	case GL_COLOR_ARRAY_STRIDE:                  *params = mState.vertexAttribute[sw::Color0].mStride;                                       break;
1385	case GL_COLOR_ARRAY_BUFFER_BINDING:          *params = mState.vertexAttribute[sw::Color0].mBoundBuffer.name();                           break;
1386	case GL_TEXTURE_COORD_ARRAY_TYPE:            *params = mState.vertexAttribute[sw::TexCoord0 + mState.activeSampler].mType;               break;
1387	case GL_TEXTURE_COORD_ARRAY_STRIDE:          *params = mState.vertexAttribute[sw::TexCoord0 + mState.activeSampler].mStride;             break;
1388	case GL_TEXTURE_COORD_ARRAY_BUFFER_BINDING:  *params = mState.vertexAttribute[sw::TexCoord0 + mState.activeSampler].mBoundBuffer.name(); break;
1389    default:
1390        return false;
1391    }
1392
1393    return true;
1394}
1395
1396int Context::getQueryParameterNum(GLenum pname)
1397{
1398    // Please note: the query type returned for DEPTH_CLEAR_VALUE in this implementation
1399    // is FLOAT rather than INT, as would be suggested by the GL ES 2.0 spec. This is due
1400    // to the fact that it is stored internally as a float, and so would require conversion
1401    // if returned from Context::getIntegerv. Since this conversion is already implemented
1402    // in the case that one calls glGetIntegerv to retrieve a float-typed state variable, we
1403    // place DEPTH_CLEAR_VALUE with the floats. This should make no difference to the calling
1404    // application.
1405    switch(pname)
1406    {
1407    case GL_COMPRESSED_TEXTURE_FORMATS:
1408		return NUM_COMPRESSED_TEXTURE_FORMATS;
1409    case GL_NUM_COMPRESSED_TEXTURE_FORMATS:
1410    case GL_ARRAY_BUFFER_BINDING:
1411    case GL_FRAMEBUFFER_BINDING_OES:
1412    case GL_RENDERBUFFER_BINDING_OES:
1413    case GL_PACK_ALIGNMENT:
1414    case GL_UNPACK_ALIGNMENT:
1415    case GL_GENERATE_MIPMAP_HINT:
1416    case GL_RED_BITS:
1417    case GL_GREEN_BITS:
1418    case GL_BLUE_BITS:
1419    case GL_ALPHA_BITS:
1420    case GL_DEPTH_BITS:
1421    case GL_STENCIL_BITS:
1422    case GL_ELEMENT_ARRAY_BUFFER_BINDING:
1423    case GL_CULL_FACE_MODE:
1424    case GL_FRONT_FACE:
1425    case GL_ACTIVE_TEXTURE:
1426    case GL_STENCIL_FUNC:
1427    case GL_STENCIL_VALUE_MASK:
1428    case GL_STENCIL_REF:
1429    case GL_STENCIL_FAIL:
1430    case GL_STENCIL_PASS_DEPTH_FAIL:
1431    case GL_STENCIL_PASS_DEPTH_PASS:
1432    case GL_DEPTH_FUNC:
1433    case GL_BLEND_SRC_RGB_OES:
1434    case GL_BLEND_SRC_ALPHA_OES:
1435    case GL_BLEND_DST_RGB_OES:
1436    case GL_BLEND_DST_ALPHA_OES:
1437    case GL_BLEND_EQUATION_RGB_OES:
1438    case GL_BLEND_EQUATION_ALPHA_OES:
1439    case GL_STENCIL_WRITEMASK:
1440    case GL_STENCIL_CLEAR_VALUE:
1441    case GL_SUBPIXEL_BITS:
1442    case GL_MAX_TEXTURE_SIZE:
1443    case GL_MAX_CUBE_MAP_TEXTURE_SIZE_OES:
1444    case GL_SAMPLE_BUFFERS:
1445    case GL_SAMPLES:
1446    case GL_IMPLEMENTATION_COLOR_READ_TYPE_OES:
1447    case GL_IMPLEMENTATION_COLOR_READ_FORMAT_OES:
1448    case GL_TEXTURE_BINDING_2D:
1449    case GL_TEXTURE_BINDING_CUBE_MAP_OES:
1450    case GL_TEXTURE_BINDING_EXTERNAL_OES:
1451        return 1;
1452    case GL_MAX_VIEWPORT_DIMS:
1453        return 2;
1454    case GL_VIEWPORT:
1455    case GL_SCISSOR_BOX:
1456        return 4;
1457    case GL_SAMPLE_COVERAGE_INVERT:
1458    case GL_DEPTH_WRITEMASK:
1459    case GL_CULL_FACE:                // CULL_FACE through DITHER are natural to IsEnabled,
1460    case GL_POLYGON_OFFSET_FILL:      // but can be retrieved through the Get{Type}v queries.
1461    case GL_SAMPLE_ALPHA_TO_COVERAGE: // For this purpose, they are treated here as bool-natural
1462    case GL_SAMPLE_COVERAGE:
1463    case GL_SCISSOR_TEST:
1464    case GL_STENCIL_TEST:
1465    case GL_DEPTH_TEST:
1466    case GL_BLEND:
1467    case GL_DITHER:
1468        return 1;
1469    case GL_COLOR_WRITEMASK:
1470        return 4;
1471    case GL_POLYGON_OFFSET_FACTOR:
1472    case GL_POLYGON_OFFSET_UNITS:
1473    case GL_SAMPLE_COVERAGE_VALUE:
1474    case GL_DEPTH_CLEAR_VALUE:
1475    case GL_LINE_WIDTH:
1476        return 1;
1477    case GL_ALIASED_LINE_WIDTH_RANGE:
1478    case GL_ALIASED_POINT_SIZE_RANGE:
1479    case GL_DEPTH_RANGE:
1480        return 2;
1481    case GL_COLOR_CLEAR_VALUE:
1482        return 4;
1483	case GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT:
1484	case GL_MAX_LIGHTS:
1485	case GL_MAX_MODELVIEW_STACK_DEPTH:
1486	case GL_MAX_PROJECTION_STACK_DEPTH:
1487	case GL_MAX_TEXTURE_STACK_DEPTH:
1488	case GL_MAX_TEXTURE_UNITS:
1489	case GL_MAX_CLIP_PLANES:
1490	case GL_POINT_SIZE_ARRAY_TYPE_OES:
1491	case GL_POINT_SIZE_ARRAY_STRIDE_OES:
1492	case GL_POINT_SIZE_ARRAY_BUFFER_BINDING_OES:
1493        return 1;
1494	case GL_CURRENT_COLOR:
1495		return 4;
1496	case GL_CURRENT_NORMAL:
1497		return 3;
1498	case GL_CURRENT_TEXTURE_COORDS:
1499		return 4;
1500	case GL_POINT_SIZE:
1501	case GL_POINT_SIZE_MIN:
1502	case GL_POINT_SIZE_MAX:
1503	case GL_POINT_FADE_THRESHOLD_SIZE:
1504		return 1;
1505	case GL_POINT_DISTANCE_ATTENUATION:
1506		return 3;
1507	case GL_SMOOTH_POINT_SIZE_RANGE:
1508	case GL_SMOOTH_LINE_WIDTH_RANGE:
1509		return 2;
1510	case GL_SHADE_MODEL:
1511	case GL_MATRIX_MODE:
1512	case GL_MODELVIEW_STACK_DEPTH:
1513	case GL_PROJECTION_STACK_DEPTH:
1514	case GL_TEXTURE_STACK_DEPTH:
1515		return 1;
1516	case GL_MODELVIEW_MATRIX:
1517	case GL_PROJECTION_MATRIX:
1518	case GL_TEXTURE_MATRIX:
1519		return 16;
1520	case GL_ALPHA_TEST_FUNC:
1521	case GL_ALPHA_TEST_REF:
1522	case GL_BLEND_DST:
1523	case GL_BLEND_SRC:
1524	case GL_LOGIC_OP_MODE:
1525	case GL_VERTEX_ARRAY_SIZE:
1526	case GL_VERTEX_ARRAY_TYPE:
1527	case GL_VERTEX_ARRAY_STRIDE:
1528	case GL_NORMAL_ARRAY_TYPE:
1529	case GL_NORMAL_ARRAY_STRIDE:
1530	case GL_COLOR_ARRAY_SIZE:
1531	case GL_COLOR_ARRAY_TYPE:
1532	case GL_COLOR_ARRAY_STRIDE:
1533	case GL_TEXTURE_COORD_ARRAY_SIZE:
1534	case GL_TEXTURE_COORD_ARRAY_TYPE:
1535	case GL_TEXTURE_COORD_ARRAY_STRIDE:
1536	case GL_VERTEX_ARRAY_POINTER:
1537	case GL_NORMAL_ARRAY_POINTER:
1538	case GL_COLOR_ARRAY_POINTER:
1539	case GL_TEXTURE_COORD_ARRAY_POINTER:
1540	case GL_LIGHT_MODEL_TWO_SIDE:
1541		return 1;
1542	default:
1543		UNREACHABLE(pname);
1544    }
1545
1546    return -1;
1547}
1548
1549bool Context::isQueryParameterInt(GLenum pname)
1550{
1551    // Please note: the query type returned for DEPTH_CLEAR_VALUE in this implementation
1552    // is FLOAT rather than INT, as would be suggested by the GL ES 2.0 spec. This is due
1553    // to the fact that it is stored internally as a float, and so would require conversion
1554    // if returned from Context::getIntegerv. Since this conversion is already implemented
1555    // in the case that one calls glGetIntegerv to retrieve a float-typed state variable, we
1556    // place DEPTH_CLEAR_VALUE with the floats. This should make no difference to the calling
1557    // application.
1558    switch(pname)
1559    {
1560    case GL_COMPRESSED_TEXTURE_FORMATS:
1561    case GL_NUM_COMPRESSED_TEXTURE_FORMATS:
1562    case GL_ARRAY_BUFFER_BINDING:
1563    case GL_FRAMEBUFFER_BINDING_OES:
1564    case GL_RENDERBUFFER_BINDING_OES:
1565    case GL_PACK_ALIGNMENT:
1566    case GL_UNPACK_ALIGNMENT:
1567    case GL_GENERATE_MIPMAP_HINT:
1568    case GL_RED_BITS:
1569    case GL_GREEN_BITS:
1570    case GL_BLUE_BITS:
1571    case GL_ALPHA_BITS:
1572    case GL_DEPTH_BITS:
1573    case GL_STENCIL_BITS:
1574    case GL_ELEMENT_ARRAY_BUFFER_BINDING:
1575    case GL_CULL_FACE_MODE:
1576    case GL_FRONT_FACE:
1577    case GL_ACTIVE_TEXTURE:
1578    case GL_STENCIL_FUNC:
1579    case GL_STENCIL_VALUE_MASK:
1580    case GL_STENCIL_REF:
1581    case GL_STENCIL_FAIL:
1582    case GL_STENCIL_PASS_DEPTH_FAIL:
1583    case GL_STENCIL_PASS_DEPTH_PASS:
1584    case GL_DEPTH_FUNC:
1585    case GL_BLEND_SRC_RGB_OES:
1586    case GL_BLEND_SRC_ALPHA_OES:
1587    case GL_BLEND_DST_RGB_OES:
1588    case GL_BLEND_DST_ALPHA_OES:
1589    case GL_BLEND_EQUATION_RGB_OES:
1590    case GL_BLEND_EQUATION_ALPHA_OES:
1591    case GL_STENCIL_WRITEMASK:
1592    case GL_STENCIL_CLEAR_VALUE:
1593    case GL_SUBPIXEL_BITS:
1594    case GL_MAX_TEXTURE_SIZE:
1595    case GL_MAX_CUBE_MAP_TEXTURE_SIZE_OES:
1596    case GL_SAMPLE_BUFFERS:
1597    case GL_SAMPLES:
1598    case GL_IMPLEMENTATION_COLOR_READ_TYPE_OES:
1599    case GL_IMPLEMENTATION_COLOR_READ_FORMAT_OES:
1600    case GL_TEXTURE_BINDING_2D:
1601    case GL_TEXTURE_BINDING_CUBE_MAP_OES:
1602    case GL_TEXTURE_BINDING_EXTERNAL_OES:
1603    case GL_MAX_VIEWPORT_DIMS:
1604    case GL_VIEWPORT:
1605    case GL_SCISSOR_BOX:
1606	case GL_MAX_LIGHTS:
1607	case GL_MAX_MODELVIEW_STACK_DEPTH:
1608	case GL_MAX_PROJECTION_STACK_DEPTH:
1609	case GL_MAX_TEXTURE_STACK_DEPTH:
1610	case GL_MAX_TEXTURE_UNITS:
1611	case GL_MAX_CLIP_PLANES:
1612	case GL_POINT_SIZE_ARRAY_TYPE_OES:
1613	case GL_POINT_SIZE_ARRAY_STRIDE_OES:
1614	case GL_POINT_SIZE_ARRAY_BUFFER_BINDING_OES:
1615        return true;
1616    }
1617
1618    return false;
1619}
1620
1621bool Context::isQueryParameterFloat(GLenum pname)
1622{
1623    // Please note: the query type returned for DEPTH_CLEAR_VALUE in this implementation
1624    // is FLOAT rather than INT, as would be suggested by the GL ES 2.0 spec. This is due
1625    // to the fact that it is stored internally as a float, and so would require conversion
1626    // if returned from Context::getIntegerv. Since this conversion is already implemented
1627    // in the case that one calls glGetIntegerv to retrieve a float-typed state variable, we
1628    // place DEPTH_CLEAR_VALUE with the floats. This should make no difference to the calling
1629    // application.
1630    switch(pname)
1631    {
1632    case GL_POLYGON_OFFSET_FACTOR:
1633    case GL_POLYGON_OFFSET_UNITS:
1634    case GL_SAMPLE_COVERAGE_VALUE:
1635    case GL_DEPTH_CLEAR_VALUE:
1636    case GL_LINE_WIDTH:
1637    case GL_ALIASED_LINE_WIDTH_RANGE:
1638    case GL_ALIASED_POINT_SIZE_RANGE:
1639    case GL_SMOOTH_LINE_WIDTH_RANGE:
1640    case GL_SMOOTH_POINT_SIZE_RANGE:
1641    case GL_DEPTH_RANGE:
1642    case GL_COLOR_CLEAR_VALUE:
1643	case GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT:
1644	case GL_LIGHT_MODEL_AMBIENT:
1645	case GL_POINT_SIZE_MIN:
1646	case GL_POINT_SIZE_MAX:
1647	case GL_POINT_DISTANCE_ATTENUATION:
1648	case GL_POINT_FADE_THRESHOLD_SIZE:
1649        return true;
1650    }
1651
1652    return false;
1653}
1654
1655bool Context::isQueryParameterBool(GLenum pname)
1656{
1657    switch(pname)
1658    {
1659    case GL_SAMPLE_COVERAGE_INVERT:
1660    case GL_DEPTH_WRITEMASK:
1661    case GL_CULL_FACE:                // CULL_FACE through DITHER are natural to IsEnabled,
1662    case GL_POLYGON_OFFSET_FILL:      // but can be retrieved through the Get{Type}v queries.
1663    case GL_SAMPLE_ALPHA_TO_COVERAGE: // For this purpose, they are treated here as bool-natural
1664    case GL_SAMPLE_COVERAGE:
1665    case GL_SCISSOR_TEST:
1666    case GL_STENCIL_TEST:
1667    case GL_DEPTH_TEST:
1668    case GL_BLEND:
1669    case GL_DITHER:
1670    case GL_COLOR_WRITEMASK:
1671	case GL_LIGHT_MODEL_TWO_SIDE:
1672        return true;
1673    }
1674
1675    return false;
1676}
1677
1678bool Context::isQueryParameterPointer(GLenum pname)
1679{
1680    switch(pname)
1681    {
1682	case GL_VERTEX_ARRAY_POINTER:
1683	case GL_NORMAL_ARRAY_POINTER:
1684	case GL_COLOR_ARRAY_POINTER:
1685	case GL_TEXTURE_COORD_ARRAY_POINTER:
1686	case GL_POINT_SIZE_ARRAY_POINTER_OES:
1687        return true;
1688    }
1689
1690    return false;
1691}
1692
1693// Applies the render target surface, depth stencil surface, viewport rectangle and scissor rectangle
1694bool Context::applyRenderTarget()
1695{
1696    Framebuffer *framebuffer = getFramebuffer();
1697	int width, height, samples;
1698
1699    if(!framebuffer || framebuffer->completeness(width, height, samples) != GL_FRAMEBUFFER_COMPLETE_OES)
1700    {
1701        return error(GL_INVALID_FRAMEBUFFER_OPERATION_OES, false);
1702    }
1703
1704    egl::Image *renderTarget = framebuffer->getRenderTarget();
1705	device->setRenderTarget(0, renderTarget);
1706	if(renderTarget) renderTarget->release();
1707
1708    egl::Image *depthStencil = framebuffer->getDepthStencil();
1709    device->setDepthStencilSurface(depthStencil);
1710	if(depthStencil) depthStencil->release();
1711
1712    Viewport viewport;
1713    float zNear = clamp01(mState.zNear);
1714    float zFar = clamp01(mState.zFar);
1715
1716    viewport.x0 = mState.viewportX;
1717    viewport.y0 = mState.viewportY;
1718    viewport.width = mState.viewportWidth;
1719    viewport.height = mState.viewportHeight;
1720    viewport.minZ = zNear;
1721    viewport.maxZ = zFar;
1722
1723    device->setViewport(viewport);
1724
1725    if(mState.scissorTestEnabled)
1726    {
1727		sw::Rect scissor = {mState.scissorX, mState.scissorY, mState.scissorX + mState.scissorWidth, mState.scissorY + mState.scissorHeight};
1728		scissor.clip(0, 0, width, height);
1729
1730		device->setScissorRect(scissor);
1731        device->setScissorEnable(true);
1732    }
1733    else
1734    {
1735        device->setScissorEnable(false);
1736    }
1737
1738    return true;
1739}
1740
1741// Applies the fixed-function state (culling, depth test, alpha blending, stenciling, etc)
1742void Context::applyState(GLenum drawMode)
1743{
1744    Framebuffer *framebuffer = getFramebuffer();
1745
1746    if(mState.cullFaceEnabled)
1747    {
1748        device->setCullMode(es2sw::ConvertCullMode(mState.cullMode, mState.frontFace));
1749    }
1750    else
1751    {
1752		device->setCullMode(sw::CULL_NONE);
1753    }
1754
1755    if(mDepthStateDirty)
1756    {
1757        if(mState.depthTestEnabled)
1758        {
1759			device->setDepthBufferEnable(true);
1760			device->setDepthCompare(es2sw::ConvertDepthComparison(mState.depthFunc));
1761        }
1762        else
1763        {
1764            device->setDepthBufferEnable(false);
1765        }
1766
1767        mDepthStateDirty = false;
1768    }
1769
1770    if(mBlendStateDirty)
1771    {
1772        if(mState.blendEnabled)
1773        {
1774			device->setAlphaBlendEnable(true);
1775			device->setSeparateAlphaBlendEnable(true);
1776
1777			device->setSourceBlendFactor(es2sw::ConvertBlendFunc(mState.sourceBlendRGB));
1778			device->setDestBlendFactor(es2sw::ConvertBlendFunc(mState.destBlendRGB));
1779			device->setBlendOperation(es2sw::ConvertBlendOp(mState.blendEquationRGB));
1780
1781            device->setSourceBlendFactorAlpha(es2sw::ConvertBlendFunc(mState.sourceBlendAlpha));
1782			device->setDestBlendFactorAlpha(es2sw::ConvertBlendFunc(mState.destBlendAlpha));
1783			device->setBlendOperationAlpha(es2sw::ConvertBlendOp(mState.blendEquationAlpha));
1784        }
1785        else
1786        {
1787			device->setAlphaBlendEnable(false);
1788        }
1789
1790        mBlendStateDirty = false;
1791    }
1792
1793    if(mStencilStateDirty || mFrontFaceDirty)
1794    {
1795        if(mState.stencilTestEnabled && framebuffer->hasStencil())
1796        {
1797			device->setStencilEnable(true);
1798			device->setTwoSidedStencil(true);
1799
1800            // get the maximum size of the stencil ref
1801            Renderbuffer *stencilbuffer = framebuffer->getStencilbuffer();
1802            GLuint maxStencil = (1 << stencilbuffer->getStencilSize()) - 1;
1803
1804			device->setStencilWriteMask(mState.stencilWritemask);
1805			device->setStencilCompare(es2sw::ConvertStencilComparison(mState.stencilFunc));
1806
1807			device->setStencilReference((mState.stencilRef < (GLint)maxStencil) ? mState.stencilRef : maxStencil);
1808			device->setStencilMask(mState.stencilMask);
1809
1810			device->setStencilFailOperation(es2sw::ConvertStencilOp(mState.stencilFail));
1811			device->setStencilZFailOperation(es2sw::ConvertStencilOp(mState.stencilPassDepthFail));
1812			device->setStencilPassOperation(es2sw::ConvertStencilOp(mState.stencilPassDepthPass));
1813
1814			device->setStencilWriteMaskCCW(mState.stencilWritemask);
1815			device->setStencilCompareCCW(es2sw::ConvertStencilComparison(mState.stencilFunc));
1816
1817			device->setStencilReferenceCCW((mState.stencilRef < (GLint)maxStencil) ? mState.stencilRef : maxStencil);
1818			device->setStencilMaskCCW(mState.stencilMask);
1819
1820			device->setStencilFailOperationCCW(es2sw::ConvertStencilOp(mState.stencilFail));
1821			device->setStencilZFailOperationCCW(es2sw::ConvertStencilOp(mState.stencilPassDepthFail));
1822			device->setStencilPassOperationCCW(es2sw::ConvertStencilOp(mState.stencilPassDepthPass));
1823        }
1824        else
1825        {
1826			device->setStencilEnable(false);
1827        }
1828
1829        mStencilStateDirty = false;
1830        mFrontFaceDirty = false;
1831    }
1832
1833    if(mMaskStateDirty)
1834    {
1835		device->setColorWriteMask(0, es2sw::ConvertColorMask(mState.colorMaskRed, mState.colorMaskGreen, mState.colorMaskBlue, mState.colorMaskAlpha));
1836		device->setDepthWriteEnable(mState.depthMask);
1837
1838        mMaskStateDirty = false;
1839    }
1840
1841    if(mPolygonOffsetStateDirty)
1842    {
1843        if(mState.polygonOffsetFillEnabled)
1844        {
1845            Renderbuffer *depthbuffer = framebuffer->getDepthbuffer();
1846            if(depthbuffer)
1847            {
1848				device->setSlopeDepthBias(mState.polygonOffsetFactor);
1849                float depthBias = ldexp(mState.polygonOffsetUnits, -(int)(depthbuffer->getDepthSize()));
1850				device->setDepthBias(depthBias);
1851            }
1852        }
1853        else
1854        {
1855            device->setSlopeDepthBias(0);
1856            device->setDepthBias(0);
1857        }
1858
1859        mPolygonOffsetStateDirty = false;
1860    }
1861
1862    if(mSampleStateDirty)
1863    {
1864        if(mState.sampleAlphaToCoverageEnabled)
1865        {
1866            device->setTransparencyAntialiasing(sw::TRANSPARENCY_ALPHA_TO_COVERAGE);
1867        }
1868		else
1869		{
1870			device->setTransparencyAntialiasing(sw::TRANSPARENCY_NONE);
1871		}
1872
1873        if(mState.sampleCoverageEnabled)
1874        {
1875            unsigned int mask = 0;
1876            if(mState.sampleCoverageValue != 0)
1877            {
1878				int width, height, samples;
1879				framebuffer->completeness(width, height, samples);
1880
1881                float threshold = 0.5f;
1882
1883                for(int i = 0; i < samples; i++)
1884                {
1885                    mask <<= 1;
1886
1887                    if((i + 1) * mState.sampleCoverageValue >= threshold)
1888                    {
1889                        threshold += 1.0f;
1890                        mask |= 1;
1891                    }
1892                }
1893            }
1894
1895            if(mState.sampleCoverageInvert)
1896            {
1897                mask = ~mask;
1898            }
1899
1900			device->setMultiSampleMask(mask);
1901        }
1902        else
1903        {
1904			device->setMultiSampleMask(0xFFFFFFFF);
1905        }
1906
1907        mSampleStateDirty = false;
1908    }
1909
1910    if(mDitherStateDirty)
1911    {
1912    //	UNIMPLEMENTED();   // FIXME
1913
1914        mDitherStateDirty = false;
1915    }
1916
1917	switch(mState.shadeModel)
1918	{
1919	default: UNREACHABLE(mState.shadeModel);
1920	case GL_SMOOTH: device->setShadingMode(sw::SHADING_GOURAUD); break;
1921	case GL_FLAT:   device->setShadingMode(sw::SHADING_FLAT);    break;
1922	}
1923
1924	device->setLightingEnable(lightingEnabled);
1925	device->setGlobalAmbient(sw::Color<float>(globalAmbient.red, globalAmbient.green, globalAmbient.blue, globalAmbient.alpha));
1926
1927	for(int i = 0; i < MAX_LIGHTS; i++)
1928	{
1929		device->setLightEnable(i, light[i].enabled);
1930		device->setLightAmbient(i, sw::Color<float>(light[i].ambient.red, light[i].ambient.green, light[i].ambient.blue, light[i].ambient.alpha));
1931		device->setLightDiffuse(i, sw::Color<float>(light[i].diffuse.red, light[i].diffuse.green, light[i].diffuse.blue, light[i].diffuse.alpha));
1932		device->setLightSpecular(i, sw::Color<float>(light[i].specular.red, light[i].specular.green, light[i].specular.blue, light[i].specular.alpha));
1933		device->setLightAttenuation(i, light[i].attenuation.constant, light[i].attenuation.linear, light[i].attenuation.quadratic);
1934
1935		if(light[i].position.w != 0.0f)
1936		{
1937			device->setLightPosition(i, sw::Point(light[i].position.x / light[i].position.w, light[i].position.y / light[i].position.w, light[i].position.z / light[i].position.w));
1938		}
1939		else   // Directional light
1940		{
1941			// Hack: set the position far way
1942			float max = sw::max(abs(light[i].position.x), abs(light[i].position.y), abs(light[i].position.z));
1943			device->setLightPosition(i, sw::Point(1e10f * (light[i].position.x / max), 1e10f * (light[i].position.y / max), 1e10f * (light[i].position.z / max)));
1944		}
1945	}
1946
1947	device->setMaterialAmbient(sw::Color<float>(materialAmbient.red, materialAmbient.green, materialAmbient.blue, materialAmbient.alpha));
1948	device->setMaterialDiffuse(sw::Color<float>(materialDiffuse.red, materialDiffuse.green, materialDiffuse.blue, materialDiffuse.alpha));
1949	device->setMaterialSpecular(sw::Color<float>(materialSpecular.red, materialSpecular.green, materialSpecular.blue, materialSpecular.alpha));
1950	device->setMaterialEmission(sw::Color<float>(materialEmission.red, materialEmission.green, materialEmission.blue, materialEmission.alpha));
1951	device->setMaterialShininess(materialShininess);
1952
1953    device->setDiffuseMaterialSource(sw::MATERIAL_MATERIAL);
1954	device->setSpecularMaterialSource(sw::MATERIAL_MATERIAL);
1955	device->setAmbientMaterialSource(sw::MATERIAL_MATERIAL);
1956	device->setEmissiveMaterialSource(sw::MATERIAL_MATERIAL);
1957
1958	const sw::Matrix Z(1, 0, 0, 0,
1959	                   0, 1, 0, 0,
1960	                   0, 0, 0.5, 0.5,
1961	                   0, 0, 0, 1);   // Map depth range from [-1, 1] to [0, 1]
1962
1963    device->setProjectionMatrix(Z * projectionStack.current());
1964    device->setModelMatrix(modelViewStack.current());
1965    device->setTextureMatrix(0, textureStack0.current());
1966	device->setTextureMatrix(1, textureStack1.current());
1967	device->setTextureTransform(0, textureStack0.isIdentity() ? 0 : 4, false);
1968	device->setTextureTransform(1, textureStack1.isIdentity() ? 0 : 4, false);
1969	device->setTexGen(0, sw::TEXGEN_NONE);
1970	device->setTexGen(1, sw::TEXGEN_NONE);
1971
1972	device->setAlphaTestEnable(alphaTestEnabled);
1973	device->setAlphaCompare(es2sw::ConvertAlphaComparison(alphaTestFunc));
1974	device->setAlphaReference(alphaTestRef * 0xFF);
1975
1976	device->setFogEnable(fogEnabled);
1977	device->setFogColor(sw::Color<float>(fogColor.red, fogColor.green, fogColor.blue, fogColor.alpha));
1978	device->setFogDensity(fogDensity);
1979	device->setFogStart(fogStart);
1980	device->setFogEnd(fogEnd);
1981
1982	switch(fogMode)
1983	{
1984	case GL_LINEAR: device->setVertexFogMode(sw::FOG_LINEAR); break;
1985	case GL_EXP:    device->setVertexFogMode(sw::FOG_EXP);    break;
1986	case GL_EXP2:   device->setVertexFogMode(sw::FOG_EXP2);   break;
1987	default: UNREACHABLE(fogMode);
1988	}
1989
1990	device->setColorLogicOpEnabled(colorLogicOpEnabled);
1991	device->setLogicalOperation(es2sw::ConvertLogicalOperation(logicalOperation));
1992
1993	device->setNormalizeNormals(normalizeEnabled || rescaleNormalEnabled);
1994}
1995
1996GLenum Context::applyVertexBuffer(GLint base, GLint first, GLsizei count)
1997{
1998    TranslatedAttribute attributes[MAX_VERTEX_ATTRIBS];
1999
2000    GLenum err = mVertexDataManager->prepareVertexData(first, count, attributes);
2001    if(err != GL_NO_ERROR)
2002    {
2003        return err;
2004    }
2005
2006	device->resetInputStreams(false);
2007
2008    for(int i = 0; i < MAX_VERTEX_ATTRIBS; i++)
2009	{
2010		sw::Resource *resource = attributes[i].vertexBuffer;
2011		const void *buffer = (char*)resource->data() + attributes[i].offset;
2012
2013		int stride = attributes[i].stride;
2014
2015		buffer = (char*)buffer + stride * base;
2016
2017		sw::Stream attribute(resource, buffer, stride);
2018
2019		attribute.type = attributes[i].type;
2020		attribute.count = attributes[i].count;
2021		attribute.normalized = attributes[i].normalized;
2022
2023		device->setInputStream(i, attribute);
2024	}
2025
2026	return GL_NO_ERROR;
2027}
2028
2029// Applies the indices and element array bindings
2030GLenum Context::applyIndexBuffer(const void *indices, GLsizei count, GLenum mode, GLenum type, TranslatedIndexData *indexInfo)
2031{
2032    GLenum err = mIndexDataManager->prepareIndexData(type, count, mState.elementArrayBuffer, indices, indexInfo);
2033
2034    if(err == GL_NO_ERROR)
2035    {
2036        device->setIndexBuffer(indexInfo->indexBuffer);
2037    }
2038
2039    return err;
2040}
2041
2042void Context::applyTextures()
2043{
2044	for(int unit = 0; unit < MAX_TEXTURE_UNITS; unit++)
2045    {
2046        Texture *texture = nullptr;
2047
2048		if(textureExternalEnabled[unit])
2049		{
2050			texture = getSamplerTexture(unit, TEXTURE_EXTERNAL);
2051		}
2052		else if(texture2Denabled[unit])
2053		{
2054			texture = getSamplerTexture(unit, TEXTURE_2D);
2055		}
2056
2057		if(texture && texture->isSamplerComplete())
2058        {
2059			texture->autoGenerateMipmaps();
2060
2061            GLenum wrapS = texture->getWrapS();
2062            GLenum wrapT = texture->getWrapT();
2063            GLenum minFilter = texture->getMinFilter();
2064            GLenum magFilter = texture->getMagFilter();
2065			GLfloat maxAnisotropy = texture->getMaxAnisotropy();
2066
2067			device->setAddressingModeU(sw::SAMPLER_PIXEL, unit, es2sw::ConvertTextureWrap(wrapS));
2068            device->setAddressingModeV(sw::SAMPLER_PIXEL, unit, es2sw::ConvertTextureWrap(wrapT));
2069
2070			device->setTextureFilter(sw::SAMPLER_PIXEL, unit, es2sw::ConvertTextureFilter(minFilter, magFilter, maxAnisotropy));
2071			device->setMipmapFilter(sw::SAMPLER_PIXEL, unit, es2sw::ConvertMipMapFilter(minFilter));
2072			device->setMaxAnisotropy(sw::SAMPLER_PIXEL, unit, maxAnisotropy);
2073
2074			applyTexture(unit, texture);
2075
2076			device->setConstantColor(unit, sw::Color<float>(mState.textureUnit[unit].color.red, mState.textureUnit[unit].color.green, mState.textureUnit[unit].color.blue, mState.textureUnit[unit].color.alpha));
2077
2078			if(mState.textureUnit[unit].environmentMode != GL_COMBINE)
2079			{
2080				device->setFirstArgument(unit, sw::TextureStage::SOURCE_TEXTURE);    // Cs
2081				device->setFirstModifier(unit, sw::TextureStage::MODIFIER_COLOR);
2082				device->setSecondArgument(unit, sw::TextureStage::SOURCE_CURRENT);   // Cp
2083				device->setSecondModifier(unit, sw::TextureStage::MODIFIER_COLOR);
2084				device->setThirdArgument(unit, sw::TextureStage::SOURCE_CONSTANT);   // Cc
2085				device->setThirdModifier(unit, sw::TextureStage::MODIFIER_COLOR);
2086
2087				device->setFirstArgumentAlpha(unit, sw::TextureStage::SOURCE_TEXTURE);    // As
2088				device->setFirstModifierAlpha(unit, sw::TextureStage::MODIFIER_ALPHA);
2089				device->setSecondArgumentAlpha(unit, sw::TextureStage::SOURCE_CURRENT);   // Ap
2090				device->setSecondModifierAlpha(unit, sw::TextureStage::MODIFIER_ALPHA);
2091				device->setThirdArgumentAlpha(unit, sw::TextureStage::SOURCE_CONSTANT);   // Ac
2092				device->setThirdModifierAlpha(unit, sw::TextureStage::MODIFIER_ALPHA);
2093
2094				GLenum texFormat = texture->getFormat(GL_TEXTURE_2D, 0);
2095
2096				switch(mState.textureUnit[unit].environmentMode)
2097				{
2098				case GL_REPLACE:
2099					if(IsAlpha(texFormat))   // GL_ALPHA
2100					{
2101						// Cv = Cp, Av = As
2102						device->setStageOperation(unit, sw::TextureStage::STAGE_SELECTARG2);
2103						device->setStageOperationAlpha(unit, sw::TextureStage::STAGE_SELECTARG1);
2104					}
2105					else if(IsRGB(texFormat))   // GL_LUMINANCE (or 1) / GL_RGB (or 3)
2106					{
2107						// Cv = Cs, Av = Ap
2108						device->setStageOperation(unit, sw::TextureStage::STAGE_SELECTARG1);
2109						device->setStageOperationAlpha(unit, sw::TextureStage::STAGE_SELECTARG2);
2110					}
2111					else if(IsRGBA(texFormat))   // GL_LUMINANCE_ALPHA (or 2) / GL_RGBA (or 4)
2112					{
2113						// Cv = Cs, Av = As
2114						device->setStageOperation(unit, sw::TextureStage::STAGE_SELECTARG1);
2115						device->setStageOperationAlpha(unit, sw::TextureStage::STAGE_SELECTARG1);
2116					}
2117					else UNREACHABLE(texFormat);
2118					break;
2119				case GL_MODULATE:
2120					if(IsAlpha(texFormat))   // GL_ALPHA
2121					{
2122						// Cv = Cp, Av = ApAs
2123						device->setStageOperation(unit, sw::TextureStage::STAGE_SELECTARG2);
2124						device->setStageOperationAlpha(unit, sw::TextureStage::STAGE_MODULATE);
2125					}
2126					else if(IsRGB(texFormat))   // GL_LUMINANCE (or 1) / GL_RGB (or 3)
2127					{
2128						// Cv = CpCs, Av = Ap
2129						device->setStageOperation(unit, sw::TextureStage::STAGE_MODULATE);
2130						device->setStageOperationAlpha(unit, sw::TextureStage::STAGE_SELECTARG2);
2131					}
2132					else if(IsRGBA(texFormat))   // GL_LUMINANCE_ALPHA (or 2) / GL_RGBA (or 4)
2133					{
2134						// Cv = CpCs, Av = ApAs
2135						device->setStageOperation(unit, sw::TextureStage::STAGE_MODULATE);
2136						device->setStageOperationAlpha(unit, sw::TextureStage::STAGE_MODULATE);
2137					}
2138					else UNREACHABLE(texFormat);
2139					break;
2140				case GL_DECAL:
2141					if(texFormat == GL_ALPHA ||
2142					   texFormat == GL_LUMINANCE ||
2143					   texFormat == GL_LUMINANCE_ALPHA)
2144					{
2145						// undefined   // FIXME: Log
2146						device->setStageOperation(unit, sw::TextureStage::STAGE_SELECTARG2);
2147						device->setStageOperationAlpha(unit, sw::TextureStage::STAGE_SELECTARG2);
2148					}
2149					else if(IsRGB(texFormat))   // GL_LUMINANCE (or 1) / GL_RGB (or 3)
2150					{
2151						// Cv = Cs, Av = Ap
2152						device->setStageOperation(unit, sw::TextureStage::STAGE_SELECTARG1);
2153						device->setStageOperationAlpha(unit, sw::TextureStage::STAGE_SELECTARG2);
2154					}
2155					else if(IsRGBA(texFormat))   // GL_LUMINANCE_ALPHA (or 2) / GL_RGBA (or 4)
2156					{
2157						// Cv = Cp(1 - As) + CsAs, Av = Ap
2158						device->setStageOperation(unit, sw::TextureStage::STAGE_BLENDTEXTUREALPHA);   // Alpha * (Arg1 - Arg2) + Arg2
2159						device->setStageOperationAlpha(unit, sw::TextureStage::STAGE_SELECTARG2);
2160					}
2161					else UNREACHABLE(texFormat);
2162					break;
2163				case GL_BLEND:
2164					if(IsAlpha(texFormat))   // GL_ALPHA
2165					{
2166						// Cv = Cp, Av = ApAs
2167						device->setStageOperation(unit, sw::TextureStage::STAGE_SELECTARG2);
2168						device->setStageOperationAlpha(unit, sw::TextureStage::STAGE_MODULATE);
2169					}
2170					else if(IsRGB(texFormat))   // GL_LUMINANCE (or 1) / GL_RGB (or 3)
2171					{
2172						// Cv = Cp(1 - Cs) + CcCs, Av = Ap
2173						device->setStageOperation(unit, sw::TextureStage::STAGE_LERP);   // Arg3 * (Arg1 - Arg2) + Arg2
2174						device->setStageOperationAlpha(unit, sw::TextureStage::STAGE_SELECTARG2);
2175					}
2176					else if(IsRGBA(texFormat))   // GL_LUMINANCE_ALPHA (or 2) / GL_RGBA (or 4)
2177					{
2178						// Cv = Cp(1 - Cs) + CcCs, Av = ApAs
2179						device->setStageOperation(unit, sw::TextureStage::STAGE_LERP);   // Arg3 * (Arg1 - Arg2) + Arg2
2180						device->setStageOperationAlpha(unit, sw::TextureStage::STAGE_MODULATE);
2181					}
2182					else UNREACHABLE(texFormat);
2183					break;
2184				case GL_ADD:
2185					if(IsAlpha(texFormat))   // GL_ALPHA
2186					{
2187						// Cv = Cp, Av = ApAs
2188						device->setStageOperation(unit, sw::TextureStage::STAGE_SELECTARG2);
2189						device->setStageOperationAlpha(unit, sw::TextureStage::STAGE_MODULATE);
2190					}
2191					else if(IsRGB(texFormat))   // GL_LUMINANCE (or 1) / GL_RGB (or 3)
2192					{
2193						// Cv = Cp + Cs, Av = Ap
2194						device->setStageOperation(unit, sw::TextureStage::STAGE_ADD);
2195						device->setStageOperationAlpha(unit, sw::TextureStage::STAGE_SELECTARG2);
2196					}
2197					else if(IsRGBA(texFormat))   // GL_LUMINANCE_ALPHA (or 2) / GL_RGBA (or 4)
2198					{
2199						// Cv = Cp + Cs, Av = ApAs
2200						device->setStageOperation(unit, sw::TextureStage::STAGE_ADD);
2201						device->setStageOperationAlpha(unit, sw::TextureStage::STAGE_MODULATE);
2202					}
2203					else UNREACHABLE(texFormat);
2204					break;
2205				default:
2206					UNREACHABLE(mState.textureUnit[unit].environmentMode);
2207				}
2208			}
2209			else   // GL_COMBINE
2210			{
2211				device->setFirstArgument(unit, es2sw::ConvertSourceArgument(mState.textureUnit[unit].src0RGB));
2212				device->setFirstModifier(unit, es2sw::ConvertSourceOperand(mState.textureUnit[unit].operand0RGB));
2213				device->setSecondArgument(unit, es2sw::ConvertSourceArgument(mState.textureUnit[unit].src1RGB));
2214				device->setSecondModifier(unit, es2sw::ConvertSourceOperand(mState.textureUnit[unit].operand1RGB));
2215				device->setThirdArgument(unit, es2sw::ConvertSourceArgument(mState.textureUnit[unit].src2RGB));
2216				device->setThirdModifier(unit, es2sw::ConvertSourceOperand(mState.textureUnit[unit].operand2RGB));
2217
2218				device->setStageOperation(unit, es2sw::ConvertCombineOperation(mState.textureUnit[unit].combineRGB));
2219
2220				device->setFirstArgumentAlpha(unit, es2sw::ConvertSourceArgument(mState.textureUnit[unit].src0Alpha));
2221				device->setFirstModifierAlpha(unit, es2sw::ConvertSourceOperand(mState.textureUnit[unit].operand0Alpha));
2222				device->setSecondArgumentAlpha(unit, es2sw::ConvertSourceArgument(mState.textureUnit[unit].src1Alpha));
2223				device->setSecondModifierAlpha(unit, es2sw::ConvertSourceOperand(mState.textureUnit[unit].operand1Alpha));
2224				device->setThirdArgumentAlpha(unit, es2sw::ConvertSourceArgument(mState.textureUnit[unit].src2Alpha));
2225				device->setThirdModifierAlpha(unit, es2sw::ConvertSourceOperand(mState.textureUnit[unit].operand2Alpha));
2226
2227				device->setStageOperationAlpha(unit, es2sw::ConvertCombineOperation(mState.textureUnit[unit].combineAlpha));
2228			}
2229        }
2230        else
2231        {
2232            applyTexture(unit, nullptr);
2233
2234			device->setFirstArgument(unit, sw::TextureStage::SOURCE_CURRENT);
2235			device->setFirstModifier(unit, sw::TextureStage::MODIFIER_COLOR);
2236			device->setStageOperation(unit, sw::TextureStage::STAGE_SELECTARG1);
2237
2238			device->setFirstArgumentAlpha(unit, sw::TextureStage::SOURCE_CURRENT);
2239			device->setFirstModifierAlpha(unit, sw::TextureStage::MODIFIER_ALPHA);
2240			device->setStageOperationAlpha(unit, sw::TextureStage::STAGE_SELECTARG1);
2241        }
2242    }
2243}
2244
2245void Context::setTextureEnvMode(GLenum texEnvMode)
2246{
2247	mState.textureUnit[mState.activeSampler].environmentMode = texEnvMode;
2248}
2249
2250void Context::setTextureEnvColor(GLclampf red, GLclampf green, GLclampf blue, GLclampf alpha)
2251{
2252	mState.textureUnit[mState.activeSampler].color = {red, green, blue, alpha};
2253}
2254
2255void Context::setCombineRGB(GLenum combineRGB)
2256{
2257	mState.textureUnit[mState.activeSampler].combineRGB = combineRGB;
2258}
2259
2260void Context::setCombineAlpha(GLenum combineAlpha)
2261{
2262	mState.textureUnit[mState.activeSampler].combineAlpha = combineAlpha;
2263}
2264
2265void Context::setOperand0RGB(GLenum operand)
2266{
2267	mState.textureUnit[mState.activeSampler].operand0RGB = operand;
2268}
2269
2270void Context::setOperand1RGB(GLenum operand)
2271{
2272	mState.textureUnit[mState.activeSampler].operand1RGB = operand;
2273}
2274
2275void Context::setOperand2RGB(GLenum operand)
2276{
2277	mState.textureUnit[mState.activeSampler].operand2RGB = operand;
2278}
2279
2280void Context::setOperand0Alpha(GLenum operand)
2281{
2282	mState.textureUnit[mState.activeSampler].operand0Alpha = operand;
2283}
2284
2285void Context::setOperand1Alpha(GLenum operand)
2286{
2287	mState.textureUnit[mState.activeSampler].operand1Alpha = operand;
2288}
2289
2290void Context::setOperand2Alpha(GLenum operand)
2291{
2292	mState.textureUnit[mState.activeSampler].operand2Alpha = operand;
2293}
2294
2295void Context::setSrc0RGB(GLenum src)
2296{
2297	mState.textureUnit[mState.activeSampler].src0RGB = src;
2298}
2299
2300void Context::setSrc1RGB(GLenum src)
2301{
2302	mState.textureUnit[mState.activeSampler].src1RGB = src;
2303}
2304
2305void Context::setSrc2RGB(GLenum src)
2306{
2307	mState.textureUnit[mState.activeSampler].src2RGB = src;
2308}
2309
2310void Context::setSrc0Alpha(GLenum src)
2311{
2312	mState.textureUnit[mState.activeSampler].src0Alpha = src;
2313}
2314
2315void Context::setSrc1Alpha(GLenum src)
2316{
2317	mState.textureUnit[mState.activeSampler].src1Alpha = src;
2318}
2319
2320void Context::setSrc2Alpha(GLenum src)
2321{
2322	mState.textureUnit[mState.activeSampler].src2Alpha = src;
2323}
2324
2325void Context::applyTexture(int index, Texture *baseTexture)
2326{
2327	sw::Resource *resource = 0;
2328
2329	if(baseTexture)
2330	{
2331		resource = baseTexture->getResource();
2332	}
2333
2334	device->setTextureResource(index, resource);
2335
2336	if(baseTexture)
2337	{
2338		int levelCount = baseTexture->getLevelCount();
2339
2340		if(baseTexture->getTarget() == GL_TEXTURE_2D || baseTexture->getTarget() == GL_TEXTURE_EXTERNAL_OES)
2341		{
2342			Texture2D *texture = static_cast<Texture2D*>(baseTexture);
2343
2344			for(int mipmapLevel = 0; mipmapLevel < MIPMAP_LEVELS; mipmapLevel++)
2345			{
2346				int surfaceLevel = mipmapLevel;
2347
2348				if(surfaceLevel < 0)
2349				{
2350					surfaceLevel = 0;
2351				}
2352				else if(surfaceLevel >= levelCount)
2353				{
2354					surfaceLevel = levelCount - 1;
2355				}
2356
2357				egl::Image *surface = texture->getImage(surfaceLevel);
2358				device->setTextureLevel(index, 0, mipmapLevel, surface, sw::TEXTURE_2D);
2359			}
2360		}
2361		else UNIMPLEMENTED();
2362	}
2363	else
2364	{
2365		device->setTextureLevel(index, 0, 0, 0, sw::TEXTURE_NULL);
2366	}
2367}
2368
2369void Context::readPixels(GLint x, GLint y, GLsizei width, GLsizei height,
2370                         GLenum format, GLenum type, GLsizei *bufSize, void* pixels)
2371{
2372    Framebuffer *framebuffer = getFramebuffer();
2373	int framebufferWidth, framebufferHeight, framebufferSamples;
2374
2375    if(framebuffer->completeness(framebufferWidth, framebufferHeight, framebufferSamples) != GL_FRAMEBUFFER_COMPLETE_OES)
2376    {
2377        return error(GL_INVALID_FRAMEBUFFER_OPERATION_OES);
2378    }
2379
2380    if(getFramebufferName() != 0 && framebufferSamples != 0)
2381    {
2382        return error(GL_INVALID_OPERATION);
2383    }
2384
2385	if(format != GL_RGBA || type != GL_UNSIGNED_BYTE)
2386	{
2387		if(format != framebuffer->getImplementationColorReadFormat() || type != framebuffer->getImplementationColorReadType())
2388		{
2389			return error(GL_INVALID_OPERATION);
2390		}
2391	}
2392
2393	GLsizei outputPitch = egl::ComputePitch(width, format, type, mState.packAlignment);
2394
2395	// Sized query sanity check
2396    if(bufSize)
2397    {
2398        int requiredSize = outputPitch * height;
2399        if(requiredSize > *bufSize)
2400        {
2401            return error(GL_INVALID_OPERATION);
2402        }
2403    }
2404
2405    egl::Image *renderTarget = framebuffer->getRenderTarget();
2406
2407    if(!renderTarget)
2408    {
2409        return error(GL_OUT_OF_MEMORY);
2410    }
2411
2412	sw::Rect rect = {x, y, x + width, y + height};
2413	rect.clip(0, 0, renderTarget->getWidth(), renderTarget->getHeight());
2414
2415    unsigned char *source = (unsigned char*)renderTarget->lock(rect.x0, rect.y0, sw::LOCK_READONLY);
2416    unsigned char *dest = (unsigned char*)pixels;
2417    int inputPitch = (int)renderTarget->getPitch();
2418
2419    for(int j = 0; j < rect.y1 - rect.y0; j++)
2420    {
2421		unsigned short *dest16 = (unsigned short*)dest;
2422		unsigned int *dest32 = (unsigned int*)dest;
2423
2424		if(renderTarget->getInternalFormat() == sw::FORMAT_A8B8G8R8 &&
2425           format == GL_RGBA && type == GL_UNSIGNED_BYTE)
2426        {
2427            memcpy(dest, source, (rect.x1 - rect.x0) * 4);
2428        }
2429		else if(renderTarget->getInternalFormat() == sw::FORMAT_A8R8G8B8 &&
2430                format == GL_RGBA && type == GL_UNSIGNED_BYTE)
2431        {
2432            for(int i = 0; i < rect.x1 - rect.x0; i++)
2433			{
2434				unsigned int argb = *(unsigned int*)(source + 4 * i);
2435
2436				dest32[i] = (argb & 0xFF00FF00) | ((argb & 0x000000FF) << 16) | ((argb & 0x00FF0000) >> 16);
2437			}
2438        }
2439		else if(renderTarget->getInternalFormat() == sw::FORMAT_X8R8G8B8 &&
2440                format == GL_RGBA && type == GL_UNSIGNED_BYTE)
2441        {
2442            for(int i = 0; i < rect.x1 - rect.x0; i++)
2443			{
2444				unsigned int xrgb = *(unsigned int*)(source + 4 * i);
2445
2446				dest32[i] = (xrgb & 0xFF00FF00) | ((xrgb & 0x000000FF) << 16) | ((xrgb & 0x00FF0000) >> 16) | 0xFF000000;
2447			}
2448        }
2449		else if(renderTarget->getInternalFormat() == sw::FORMAT_X8R8G8B8 &&
2450                format == GL_BGRA_EXT && type == GL_UNSIGNED_BYTE)
2451        {
2452            for(int i = 0; i < rect.x1 - rect.x0; i++)
2453			{
2454				unsigned int xrgb = *(unsigned int*)(source + 4 * i);
2455
2456				dest32[i] = xrgb | 0xFF000000;
2457			}
2458        }
2459        else if(renderTarget->getInternalFormat() == sw::FORMAT_A8R8G8B8 &&
2460                format == GL_BGRA_EXT && type == GL_UNSIGNED_BYTE)
2461        {
2462            memcpy(dest, source, (rect.x1 - rect.x0) * 4);
2463        }
2464		else if(renderTarget->getInternalFormat() == sw::FORMAT_A1R5G5B5 &&
2465                format == GL_BGRA_EXT && type == GL_UNSIGNED_SHORT_1_5_5_5_REV_EXT)
2466        {
2467            memcpy(dest, source, (rect.x1 - rect.x0) * 2);
2468        }
2469		else if(renderTarget->getInternalFormat() == sw::FORMAT_R5G6B5 &&
2470                format == 0x80E0 && type == GL_UNSIGNED_SHORT_5_6_5)   // GL_BGR_EXT
2471        {
2472            memcpy(dest, source, (rect.x1 - rect.x0) * 2);
2473        }
2474		else
2475		{
2476			for(int i = 0; i < rect.x1 - rect.x0; i++)
2477			{
2478				float r;
2479				float g;
2480				float b;
2481				float a;
2482
2483				switch(renderTarget->getInternalFormat())
2484				{
2485				case sw::FORMAT_R5G6B5:
2486					{
2487						unsigned short rgb = *(unsigned short*)(source + 2 * i);
2488
2489						a = 1.0f;
2490						b = (rgb & 0x001F) * (1.0f / 0x001F);
2491						g = (rgb & 0x07E0) * (1.0f / 0x07E0);
2492						r = (rgb & 0xF800) * (1.0f / 0xF800);
2493					}
2494					break;
2495				case sw::FORMAT_A1R5G5B5:
2496					{
2497						unsigned short argb = *(unsigned short*)(source + 2 * i);
2498
2499						a = (argb & 0x8000) ? 1.0f : 0.0f;
2500						b = (argb & 0x001F) * (1.0f / 0x001F);
2501						g = (argb & 0x03E0) * (1.0f / 0x03E0);
2502						r = (argb & 0x7C00) * (1.0f / 0x7C00);
2503					}
2504					break;
2505				case sw::FORMAT_A8R8G8B8:
2506					{
2507						unsigned int argb = *(unsigned int*)(source + 4 * i);
2508
2509						a = (argb & 0xFF000000) * (1.0f / 0xFF000000);
2510						b = (argb & 0x000000FF) * (1.0f / 0x000000FF);
2511						g = (argb & 0x0000FF00) * (1.0f / 0x0000FF00);
2512						r = (argb & 0x00FF0000) * (1.0f / 0x00FF0000);
2513					}
2514					break;
2515				case sw::FORMAT_A8B8G8R8:
2516					{
2517						unsigned int abgr = *(unsigned int*)(source + 4 * i);
2518
2519						a = (abgr & 0xFF000000) * (1.0f / 0xFF000000);
2520						b = (abgr & 0x00FF0000) * (1.0f / 0x00FF0000);
2521						g = (abgr & 0x0000FF00) * (1.0f / 0x0000FF00);
2522						r = (abgr & 0x000000FF) * (1.0f / 0x000000FF);
2523					}
2524					break;
2525				case sw::FORMAT_X8R8G8B8:
2526					{
2527						unsigned int xrgb = *(unsigned int*)(source + 4 * i);
2528
2529						a = 1.0f;
2530						b = (xrgb & 0x000000FF) * (1.0f / 0x000000FF);
2531						g = (xrgb & 0x0000FF00) * (1.0f / 0x0000FF00);
2532						r = (xrgb & 0x00FF0000) * (1.0f / 0x00FF0000);
2533					}
2534					break;
2535				case sw::FORMAT_X8B8G8R8:
2536					{
2537						unsigned int xbgr = *(unsigned int*)(source + 4 * i);
2538
2539						a = 1.0f;
2540						b = (xbgr & 0x00FF0000) * (1.0f / 0x00FF0000);
2541						g = (xbgr & 0x0000FF00) * (1.0f / 0x0000FF00);
2542						r = (xbgr & 0x000000FF) * (1.0f / 0x000000FF);
2543					}
2544					break;
2545				case sw::FORMAT_A2R10G10B10:
2546					{
2547						unsigned int argb = *(unsigned int*)(source + 4 * i);
2548
2549						a = (argb & 0xC0000000) * (1.0f / 0xC0000000);
2550						b = (argb & 0x000003FF) * (1.0f / 0x000003FF);
2551						g = (argb & 0x000FFC00) * (1.0f / 0x000FFC00);
2552						r = (argb & 0x3FF00000) * (1.0f / 0x3FF00000);
2553					}
2554					break;
2555				default:
2556					UNIMPLEMENTED();   // FIXME
2557					UNREACHABLE(renderTarget->getInternalFormat());
2558				}
2559
2560				switch(format)
2561				{
2562				case GL_RGBA:
2563					switch(type)
2564					{
2565					case GL_UNSIGNED_BYTE:
2566						dest[4 * i + 0] = (unsigned char)(255 * r + 0.5f);
2567						dest[4 * i + 1] = (unsigned char)(255 * g + 0.5f);
2568						dest[4 * i + 2] = (unsigned char)(255 * b + 0.5f);
2569						dest[4 * i + 3] = (unsigned char)(255 * a + 0.5f);
2570						break;
2571					default: UNREACHABLE(type);
2572					}
2573					break;
2574				case GL_BGRA_EXT:
2575					switch(type)
2576					{
2577					case GL_UNSIGNED_BYTE:
2578						dest[4 * i + 0] = (unsigned char)(255 * b + 0.5f);
2579						dest[4 * i + 1] = (unsigned char)(255 * g + 0.5f);
2580						dest[4 * i + 2] = (unsigned char)(255 * r + 0.5f);
2581						dest[4 * i + 3] = (unsigned char)(255 * a + 0.5f);
2582						break;
2583					case GL_UNSIGNED_SHORT_4_4_4_4_REV_EXT:
2584						// According to the desktop GL spec in the "Transfer of Pixel Rectangles" section
2585						// this type is packed as follows:
2586						//   15   14   13   12   11   10    9    8    7    6    5    4    3    2    1    0
2587						//  --------------------------------------------------------------------------------
2588						// |       4th         |        3rd         |        2nd        |   1st component   |
2589						//  --------------------------------------------------------------------------------
2590						// in the case of BGRA_EXT, B is the first component, G the second, and so forth.
2591						dest16[i] =
2592							((unsigned short)(15 * a + 0.5f) << 12)|
2593							((unsigned short)(15 * r + 0.5f) << 8) |
2594							((unsigned short)(15 * g + 0.5f) << 4) |
2595							((unsigned short)(15 * b + 0.5f) << 0);
2596						break;
2597					case GL_UNSIGNED_SHORT_1_5_5_5_REV_EXT:
2598						// According to the desktop GL spec in the "Transfer of Pixel Rectangles" section
2599						// this type is packed as follows:
2600						//   15   14   13   12   11   10    9    8    7    6    5    4    3    2    1    0
2601						//  --------------------------------------------------------------------------------
2602						// | 4th |          3rd           |           2nd          |      1st component     |
2603						//  --------------------------------------------------------------------------------
2604						// in the case of BGRA_EXT, B is the first component, G the second, and so forth.
2605						dest16[i] =
2606							((unsigned short)(     a + 0.5f) << 15) |
2607							((unsigned short)(31 * r + 0.5f) << 10) |
2608							((unsigned short)(31 * g + 0.5f) << 5) |
2609							((unsigned short)(31 * b + 0.5f) << 0);
2610						break;
2611					default: UNREACHABLE(type);
2612					}
2613					break;
2614				case GL_RGB:
2615					switch(type)
2616					{
2617					case GL_UNSIGNED_SHORT_5_6_5:
2618						dest16[i] =
2619							((unsigned short)(31 * b + 0.5f) << 0) |
2620							((unsigned short)(63 * g + 0.5f) << 5) |
2621							((unsigned short)(31 * r + 0.5f) << 11);
2622						break;
2623					default: UNREACHABLE(type);
2624					}
2625					break;
2626				default: UNREACHABLE(format);
2627				}
2628			}
2629        }
2630
2631		source += inputPitch;
2632		dest += outputPitch;
2633    }
2634
2635	renderTarget->unlock();
2636	renderTarget->release();
2637}
2638
2639void Context::clear(GLbitfield mask)
2640{
2641    Framebuffer *framebuffer = getFramebuffer();
2642
2643    if(!framebuffer || framebuffer->completeness() != GL_FRAMEBUFFER_COMPLETE_OES)
2644    {
2645        return error(GL_INVALID_FRAMEBUFFER_OPERATION_OES);
2646    }
2647
2648    if(!applyRenderTarget())
2649    {
2650        return;
2651    }
2652
2653    float depth = clamp01(mState.depthClearValue);
2654    int stencil = mState.stencilClearValue & 0x000000FF;
2655
2656	if(mask & GL_COLOR_BUFFER_BIT)
2657	{
2658		unsigned int rgbaMask = (mState.colorMaskRed ? 0x1 : 0) |
2659		                        (mState.colorMaskGreen ? 0x2 : 0) |
2660		                        (mState.colorMaskBlue ? 0x4 : 0) |
2661		                        (mState.colorMaskAlpha ? 0x8 : 0);
2662
2663		if(rgbaMask != 0)
2664		{
2665			device->clearColor(mState.colorClearValue.red, mState.colorClearValue.green, mState.colorClearValue.blue, mState.colorClearValue.alpha, rgbaMask);
2666		}
2667	}
2668
2669	if(mask & GL_DEPTH_BUFFER_BIT)
2670	{
2671		if(mState.depthMask != 0)
2672		{
2673			device->clearDepth(depth);
2674		}
2675	}
2676
2677	if(mask & GL_STENCIL_BUFFER_BIT)
2678	{
2679		if(mState.stencilWritemask != 0)
2680		{
2681			device->clearStencil(stencil, mState.stencilWritemask);
2682		}
2683	}
2684}
2685
2686void Context::drawArrays(GLenum mode, GLint first, GLsizei count)
2687{
2688    PrimitiveType primitiveType;
2689    int primitiveCount;
2690
2691    if(!es2sw::ConvertPrimitiveType(mode, count, primitiveType, primitiveCount))
2692        return error(GL_INVALID_ENUM);
2693
2694    if(primitiveCount <= 0)
2695    {
2696        return;
2697    }
2698
2699    if(!applyRenderTarget())
2700    {
2701        return;
2702    }
2703
2704    applyState(mode);
2705
2706    GLenum err = applyVertexBuffer(0, first, count);
2707    if(err != GL_NO_ERROR)
2708    {
2709        return error(err);
2710    }
2711
2712    applyTextures();
2713
2714    if(!cullSkipsDraw(mode))
2715    {
2716        device->drawPrimitive(primitiveType, primitiveCount);
2717    }
2718}
2719
2720void Context::drawElements(GLenum mode, GLsizei count, GLenum type, const void *indices)
2721{
2722    if(!indices && !mState.elementArrayBuffer)
2723    {
2724        return error(GL_INVALID_OPERATION);
2725    }
2726
2727    PrimitiveType primitiveType;
2728    int primitiveCount;
2729
2730    if(!es2sw::ConvertPrimitiveType(mode, count, primitiveType, primitiveCount))
2731        return error(GL_INVALID_ENUM);
2732
2733    if(primitiveCount <= 0)
2734    {
2735        return;
2736    }
2737
2738    if(!applyRenderTarget())
2739    {
2740        return;
2741    }
2742
2743    applyState(mode);
2744
2745    TranslatedIndexData indexInfo;
2746    GLenum err = applyIndexBuffer(indices, count, mode, type, &indexInfo);
2747    if(err != GL_NO_ERROR)
2748    {
2749        return error(err);
2750    }
2751
2752    GLsizei vertexCount = indexInfo.maxIndex - indexInfo.minIndex + 1;
2753    err = applyVertexBuffer(-(int)indexInfo.minIndex, indexInfo.minIndex, vertexCount);
2754    if(err != GL_NO_ERROR)
2755    {
2756        return error(err);
2757    }
2758
2759    applyTextures();
2760
2761    if(!cullSkipsDraw(mode))
2762    {
2763		device->drawIndexedPrimitive(primitiveType, indexInfo.indexOffset, primitiveCount, IndexDataManager::typeSize(type));
2764    }
2765}
2766
2767void Context::drawTexture(GLfloat x, GLfloat y, GLfloat z, GLfloat width, GLfloat height)
2768{
2769	es1::Framebuffer *framebuffer = getFramebuffer();
2770	es1::Renderbuffer *renderbuffer = framebuffer->getColorbuffer();
2771	float targetWidth = (float)renderbuffer->getWidth();
2772	float targetHeight = (float)renderbuffer->getHeight();
2773	float x0 = 2.0f * x / targetWidth - 1.0f;
2774	float y0 = 2.0f * y / targetHeight - 1.0f;
2775	float x1 = 2.0f * (x + width) / targetWidth - 1.0f;
2776	float y1 = 2.0f * (y + height) / targetHeight - 1.0f;
2777	float Zw = sw::clamp(mState.zNear + z * (mState.zFar - mState.zNear), mState.zNear, mState.zFar);
2778
2779	float vertices[][3] = {{x0, y0, Zw},
2780						   {x0, y1, Zw},
2781						   {x1, y0, Zw},
2782						   {x1, y1, Zw}};
2783
2784	ASSERT(mState.samplerTexture[TEXTURE_2D][1].name() == 0);   // Multi-texturing unimplemented
2785	es1::Texture *texture = getSamplerTexture(0, TEXTURE_2D);
2786	float textureWidth = (float)texture->getWidth(GL_TEXTURE_2D, 0);
2787	float textureHeight = (float)texture->getHeight(GL_TEXTURE_2D, 0);
2788	int Ucr = texture->getCropRectU();
2789	int Vcr = texture->getCropRectV();
2790	int Wcr = texture->getCropRectW();
2791	int Hcr = texture->getCropRectH();
2792
2793	float texCoords[][2] = {{Ucr / textureWidth, Vcr / textureHeight},
2794							{Ucr / textureWidth, (Vcr + Hcr) / textureHeight},
2795							{(Ucr + Wcr) / textureWidth, Vcr / textureHeight},
2796							{(Ucr + Wcr) / textureWidth, (Vcr + Hcr) / textureHeight}};
2797
2798	VertexAttribute oldPositionAttribute = mState.vertexAttribute[sw::Position];
2799	VertexAttribute oldTexCoord0Attribute = mState.vertexAttribute[sw::TexCoord0];
2800	gl::BindingPointer<Buffer> oldArrayBuffer = mState.arrayBuffer;
2801	mState.arrayBuffer = nullptr;
2802
2803	glVertexPointer(3, GL_FLOAT, 3 * sizeof(float), vertices);
2804	glEnableClientState(GL_VERTEX_ARRAY);
2805	glTexCoordPointer(2, GL_FLOAT, 2 * sizeof(float), texCoords);
2806	glEnableClientState(GL_TEXTURE_COORD_ARRAY);
2807
2808	sw::Matrix P = projectionStack.current();
2809	sw::Matrix M = modelViewStack.current();
2810	sw::Matrix T = textureStack0.current();
2811
2812	projectionStack.identity();
2813	modelViewStack.identity();
2814	textureStack0.identity();
2815
2816	drawArrays(GL_TRIANGLE_STRIP, 0, 4);
2817
2818	// Restore state
2819	mState.vertexAttribute[sw::Position] = oldPositionAttribute;
2820	mState.vertexAttribute[sw::TexCoord0] = oldTexCoord0Attribute;
2821	mState.arrayBuffer = oldArrayBuffer;
2822	oldArrayBuffer = nullptr;
2823	oldPositionAttribute.mBoundBuffer = nullptr;
2824	oldTexCoord0Attribute.mBoundBuffer = nullptr;
2825	textureStack0.load(T);
2826	modelViewStack.load(M);
2827	projectionStack.load(P);
2828}
2829
2830void Context::finish()
2831{
2832	device->finish();
2833}
2834
2835void Context::flush()
2836{
2837    // We don't queue anything without processing it as fast as possible
2838}
2839
2840void Context::recordInvalidEnum()
2841{
2842    mInvalidEnum = true;
2843}
2844
2845void Context::recordInvalidValue()
2846{
2847    mInvalidValue = true;
2848}
2849
2850void Context::recordInvalidOperation()
2851{
2852    mInvalidOperation = true;
2853}
2854
2855void Context::recordOutOfMemory()
2856{
2857    mOutOfMemory = true;
2858}
2859
2860void Context::recordInvalidFramebufferOperation()
2861{
2862    mInvalidFramebufferOperation = true;
2863}
2864
2865void Context::recordMatrixStackOverflow()
2866{
2867    mMatrixStackOverflow = true;
2868}
2869
2870void Context::recordMatrixStackUnderflow()
2871{
2872    mMatrixStackUnderflow = true;
2873}
2874
2875// Get one of the recorded errors and clear its flag, if any.
2876// [OpenGL ES 2.0.24] section 2.5 page 13.
2877GLenum Context::getError()
2878{
2879    if(mInvalidEnum)
2880    {
2881        mInvalidEnum = false;
2882
2883        return GL_INVALID_ENUM;
2884    }
2885
2886    if(mInvalidValue)
2887    {
2888        mInvalidValue = false;
2889
2890        return GL_INVALID_VALUE;
2891    }
2892
2893    if(mInvalidOperation)
2894    {
2895        mInvalidOperation = false;
2896
2897        return GL_INVALID_OPERATION;
2898    }
2899
2900    if(mOutOfMemory)
2901    {
2902        mOutOfMemory = false;
2903
2904        return GL_OUT_OF_MEMORY;
2905    }
2906
2907    if(mInvalidFramebufferOperation)
2908    {
2909        mInvalidFramebufferOperation = false;
2910
2911        return GL_INVALID_FRAMEBUFFER_OPERATION_OES;
2912    }
2913
2914	if(mMatrixStackOverflow)
2915    {
2916        mMatrixStackOverflow = false;
2917
2918        return GL_INVALID_FRAMEBUFFER_OPERATION_OES;
2919    }
2920
2921	if(mMatrixStackUnderflow)
2922    {
2923        mMatrixStackUnderflow = false;
2924
2925        return GL_INVALID_FRAMEBUFFER_OPERATION_OES;
2926    }
2927
2928    return GL_NO_ERROR;
2929}
2930
2931int Context::getSupportedMultisampleCount(int requested)
2932{
2933	int supported = 0;
2934
2935	for(int i = NUM_MULTISAMPLE_COUNTS - 1; i >= 0; i--)
2936	{
2937		if(supported >= requested)
2938		{
2939			return supported;
2940		}
2941
2942		supported = multisampleCount[i];
2943	}
2944
2945	return supported;
2946}
2947
2948void Context::detachBuffer(GLuint buffer)
2949{
2950    // [OpenGL ES 2.0.24] section 2.9 page 22:
2951    // If a buffer object is deleted while it is bound, all bindings to that object in the current context
2952    // (i.e. in the thread that called Delete-Buffers) are reset to zero.
2953
2954    if(mState.arrayBuffer.name() == buffer)
2955    {
2956        mState.arrayBuffer = NULL;
2957    }
2958
2959    if(mState.elementArrayBuffer.name() == buffer)
2960    {
2961        mState.elementArrayBuffer = NULL;
2962    }
2963
2964    for(int attribute = 0; attribute < MAX_VERTEX_ATTRIBS; attribute++)
2965    {
2966        if(mState.vertexAttribute[attribute].mBoundBuffer.name() == buffer)
2967        {
2968            mState.vertexAttribute[attribute].mBoundBuffer = NULL;
2969        }
2970    }
2971}
2972
2973void Context::detachTexture(GLuint texture)
2974{
2975    // [OpenGL ES 2.0.24] section 3.8 page 84:
2976    // If a texture object is deleted, it is as if all texture units which are bound to that texture object are
2977    // rebound to texture object zero
2978
2979    for(int type = 0; type < TEXTURE_TYPE_COUNT; type++)
2980    {
2981        for(int sampler = 0; sampler < MAX_TEXTURE_UNITS; sampler++)
2982        {
2983            if(mState.samplerTexture[type][sampler].name() == texture)
2984            {
2985                mState.samplerTexture[type][sampler] = NULL;
2986            }
2987        }
2988    }
2989
2990    // [OpenGL ES 2.0.24] section 4.4 page 112:
2991    // If a texture object is deleted while its image is attached to the currently bound framebuffer, then it is
2992    // as if FramebufferTexture2D had been called, with a texture of 0, for each attachment point to which this
2993    // image was attached in the currently bound framebuffer.
2994
2995    Framebuffer *framebuffer = getFramebuffer();
2996
2997    if(framebuffer)
2998    {
2999        framebuffer->detachTexture(texture);
3000    }
3001}
3002
3003void Context::detachFramebuffer(GLuint framebuffer)
3004{
3005    // [OpenGL ES 2.0.24] section 4.4 page 107:
3006    // If a framebuffer that is currently bound to the target FRAMEBUFFER is deleted, it is as though
3007    // BindFramebuffer had been executed with the target of FRAMEBUFFER and framebuffer of zero.
3008
3009    if(mState.framebuffer == framebuffer)
3010    {
3011        bindFramebuffer(0);
3012    }
3013}
3014
3015void Context::detachRenderbuffer(GLuint renderbuffer)
3016{
3017    // [OpenGL ES 2.0.24] section 4.4 page 109:
3018    // If a renderbuffer that is currently bound to RENDERBUFFER is deleted, it is as though BindRenderbuffer
3019    // had been executed with the target RENDERBUFFER and name of zero.
3020
3021    if(mState.renderbuffer.name() == renderbuffer)
3022    {
3023        bindRenderbuffer(0);
3024    }
3025
3026    // [OpenGL ES 2.0.24] section 4.4 page 111:
3027    // If a renderbuffer object is deleted while its image is attached to the currently bound framebuffer,
3028    // then it is as if FramebufferRenderbuffer had been called, with a renderbuffer of 0, for each attachment
3029    // point to which this image was attached in the currently bound framebuffer.
3030
3031    Framebuffer *framebuffer = getFramebuffer();
3032
3033    if(framebuffer)
3034    {
3035        framebuffer->detachRenderbuffer(renderbuffer);
3036    }
3037}
3038
3039bool Context::cullSkipsDraw(GLenum drawMode)
3040{
3041    return mState.cullFaceEnabled && mState.cullMode == GL_FRONT_AND_BACK && isTriangleMode(drawMode);
3042}
3043
3044bool Context::isTriangleMode(GLenum drawMode)
3045{
3046    switch(drawMode)
3047    {
3048    case GL_TRIANGLES:
3049    case GL_TRIANGLE_FAN:
3050    case GL_TRIANGLE_STRIP:
3051        return true;
3052    case GL_POINTS:
3053    case GL_LINES:
3054    case GL_LINE_LOOP:
3055    case GL_LINE_STRIP:
3056        return false;
3057    default: UNREACHABLE(drawMode);
3058    }
3059
3060    return false;
3061}
3062
3063void Context::setVertexAttrib(GLuint index, GLfloat x, GLfloat y, GLfloat z, GLfloat w)
3064{
3065    ASSERT(index < MAX_VERTEX_ATTRIBS);
3066
3067    mState.vertexAttribute[index].mCurrentValue[0] = x;
3068    mState.vertexAttribute[index].mCurrentValue[1] = y;
3069    mState.vertexAttribute[index].mCurrentValue[2] = z;
3070    mState.vertexAttribute[index].mCurrentValue[3] = w;
3071
3072    mVertexDataManager->dirtyCurrentValue(index);
3073}
3074
3075void Context::bindTexImage(egl::Surface *surface)
3076{
3077	es1::Texture2D *textureObject = getTexture2D();
3078
3079    if(textureObject)
3080    {
3081		textureObject->bindTexImage(surface);
3082	}
3083}
3084
3085EGLenum Context::validateSharedImage(EGLenum target, GLuint name, GLuint textureLevel)
3086{
3087    switch(target)
3088    {
3089    case EGL_GL_TEXTURE_2D_KHR:
3090        break;
3091    case EGL_GL_RENDERBUFFER_KHR:
3092        break;
3093    default:
3094        return EGL_BAD_PARAMETER;
3095    }
3096
3097    if(textureLevel >= IMPLEMENTATION_MAX_TEXTURE_LEVELS)
3098    {
3099        return EGL_BAD_MATCH;
3100    }
3101
3102	if(target == EGL_GL_TEXTURE_2D_KHR)
3103    {
3104        Texture *texture = getTexture(name);
3105
3106        if(!texture || texture->getTarget() != GL_TEXTURE_2D)
3107        {
3108            return EGL_BAD_PARAMETER;
3109        }
3110
3111        if(texture->isShared(GL_TEXTURE_2D, textureLevel))   // Bound to an EGLSurface or already an EGLImage sibling
3112        {
3113            return EGL_BAD_ACCESS;
3114        }
3115
3116        if(textureLevel != 0 && !texture->isSamplerComplete())
3117        {
3118            return EGL_BAD_PARAMETER;
3119        }
3120
3121        if(textureLevel == 0 && !(texture->isSamplerComplete() && texture->getLevelCount() == 1))
3122        {
3123            return EGL_BAD_PARAMETER;
3124        }
3125    }
3126    else if(target == EGL_GL_RENDERBUFFER_KHR)
3127    {
3128        Renderbuffer *renderbuffer = getRenderbuffer(name);
3129
3130        if(!renderbuffer)
3131        {
3132            return EGL_BAD_PARAMETER;
3133        }
3134
3135        if(renderbuffer->isShared())   // Already an EGLImage sibling
3136        {
3137            return EGL_BAD_ACCESS;
3138        }
3139    }
3140    else UNREACHABLE(target);
3141
3142	return EGL_SUCCESS;
3143}
3144
3145egl::Image *Context::createSharedImage(EGLenum target, GLuint name, GLuint textureLevel)
3146{
3147    if(target == EGL_GL_TEXTURE_2D_KHR)
3148    {
3149        es1::Texture *texture = getTexture(name);
3150
3151        return texture->createSharedImage(GL_TEXTURE_2D, textureLevel);
3152    }
3153    else if(target == EGL_GL_RENDERBUFFER_KHR)
3154    {
3155        es1::Renderbuffer *renderbuffer = getRenderbuffer(name);
3156
3157        return renderbuffer->createSharedImage();
3158    }
3159    else UNREACHABLE(target);
3160
3161	return 0;
3162}
3163
3164Device *Context::getDevice()
3165{
3166	return device;
3167}
3168
3169void Context::setMatrixMode(GLenum mode)
3170{
3171    matrixMode = mode;
3172}
3173
3174sw::MatrixStack &Context::currentMatrixStack()
3175{
3176	switch(matrixMode)
3177	{
3178	case GL_MODELVIEW:
3179		return modelViewStack;
3180	case GL_PROJECTION:
3181		return projectionStack;
3182	case GL_TEXTURE:
3183		switch(mState.activeSampler)
3184		{
3185		case 0: return textureStack0;
3186		case 1: return textureStack1;
3187		}
3188		break;
3189	}
3190
3191	UNREACHABLE(matrixMode);
3192	return textureStack0;
3193}
3194
3195void Context::loadIdentity()
3196{
3197	currentMatrixStack().identity();
3198}
3199
3200void Context::load(const GLfloat *m)
3201{
3202    currentMatrixStack().load(m);
3203}
3204
3205void Context::pushMatrix()
3206{
3207	if(!currentMatrixStack().push())
3208	{
3209		return error(GL_STACK_OVERFLOW);
3210	}
3211}
3212
3213void Context::popMatrix()
3214{
3215    if(!currentMatrixStack().pop())
3216	{
3217		return error(GL_STACK_OVERFLOW);
3218	}
3219}
3220
3221void Context::rotate(GLfloat angle, GLfloat x, GLfloat y, GLfloat z)
3222{
3223    currentMatrixStack().rotate(angle, x, y, z);
3224}
3225
3226void Context::translate(GLfloat x, GLfloat y, GLfloat z)
3227{
3228    currentMatrixStack().translate(x, y, z);
3229}
3230
3231void Context::scale(GLfloat x, GLfloat y, GLfloat z)
3232{
3233    currentMatrixStack().scale(x, y, z);
3234}
3235
3236void Context::multiply(const GLfloat *m)
3237{
3238    currentMatrixStack().multiply(m);
3239}
3240
3241void Context::frustum(GLfloat left, GLfloat right, GLfloat bottom, GLfloat top, GLfloat zNear, GLfloat zFar)
3242{
3243	currentMatrixStack().frustum(left, right, bottom, top, zNear, zFar);
3244}
3245
3246void Context::ortho(GLfloat left, GLfloat right, GLfloat bottom, GLfloat top, GLfloat zNear, GLfloat zFar)
3247{
3248	currentMatrixStack().ortho(left, right, bottom, top, zNear, zFar);
3249}
3250
3251void Context::setClipPlane(int index, const float plane[4])
3252{
3253	sw::Plane clipPlane = modelViewStack.current() * sw::Plane(plane);
3254	device->setClipPlane(index, &clipPlane.A);
3255}
3256
3257void Context::setClipPlaneEnabled(int index, bool enable)
3258{
3259	clipFlags = (clipFlags & ~((int)!enable << index)) | ((int)enable << index);
3260	device->setClipFlags(clipFlags);
3261}
3262
3263bool Context::isClipPlaneEnabled(int index) const
3264{
3265	return (clipFlags & (1 << index)) != 0;
3266}
3267
3268void Context::setColorLogicOpEnabled(bool enable)
3269{
3270	colorLogicOpEnabled = enable;
3271}
3272
3273bool Context::isColorLogicOpEnabled() const
3274{
3275	return colorLogicOpEnabled;
3276}
3277
3278void Context::setLogicalOperation(GLenum logicOp)
3279{
3280	logicalOperation = logicOp;
3281}
3282
3283void Context::setLineSmoothEnabled(bool enable)
3284{
3285	lineSmoothEnabled = enable;
3286}
3287
3288bool Context::isLineSmoothEnabled() const
3289{
3290	return lineSmoothEnabled;
3291}
3292
3293void Context::setColorMaterialEnabled(bool enable)
3294{
3295	colorMaterialEnabled = enable;
3296}
3297
3298bool Context::isColorMaterialEnabled() const
3299{
3300	return colorMaterialEnabled;
3301}
3302
3303void Context::setNormalizeEnabled(bool enable)
3304{
3305	normalizeEnabled = enable;
3306}
3307
3308bool Context::isNormalizeEnabled() const
3309{
3310	return normalizeEnabled;
3311}
3312
3313void Context::setRescaleNormalEnabled(bool enable)
3314{
3315	rescaleNormalEnabled = enable;
3316}
3317
3318bool Context::isRescaleNormalEnabled() const
3319{
3320	return rescaleNormalEnabled;
3321}
3322
3323void Context::setVertexArrayEnabled(bool enable)
3324{
3325	mState.vertexAttribute[sw::Position].mArrayEnabled = enable;
3326}
3327
3328bool Context::isVertexArrayEnabled() const
3329{
3330	return mState.vertexAttribute[sw::Position].mArrayEnabled;
3331}
3332
3333void Context::setNormalArrayEnabled(bool enable)
3334{
3335	mState.vertexAttribute[sw::Normal].mArrayEnabled = enable;
3336}
3337
3338bool Context::isNormalArrayEnabled() const
3339{
3340	return mState.vertexAttribute[sw::Normal].mArrayEnabled;
3341}
3342
3343void Context::setColorArrayEnabled(bool enable)
3344{
3345	mState.vertexAttribute[sw::Color0].mArrayEnabled = enable;
3346}
3347
3348bool Context::isColorArrayEnabled() const
3349{
3350	return mState.vertexAttribute[sw::Color0].mArrayEnabled;
3351}
3352
3353void Context::setPointSizeArrayEnabled(bool enable)
3354{
3355	mState.vertexAttribute[sw::PointSize].mArrayEnabled = enable;
3356}
3357
3358bool Context::isPointSizeArrayEnabled() const
3359{
3360	return mState.vertexAttribute[sw::PointSize].mArrayEnabled;
3361}
3362
3363void Context::setTextureCoordArrayEnabled(bool enable)
3364{
3365	mState.vertexAttribute[sw::TexCoord0 + clientTexture].mArrayEnabled = enable;
3366}
3367
3368bool Context::isTextureCoordArrayEnabled() const
3369{
3370	return mState.vertexAttribute[sw::TexCoord0 + clientTexture].mArrayEnabled;
3371}
3372
3373void Context::setMultisampleEnabled(bool enable)
3374{
3375	multisampleEnabled = enable;
3376}
3377
3378bool Context::isMultisampleEnabled() const
3379{
3380	return multisampleEnabled;
3381}
3382
3383void Context::setSampleAlphaToOneEnabled(bool enable)
3384{
3385	sampleAlphaToOneEnabled = enable;
3386}
3387
3388bool Context::isSampleAlphaToOneEnabled() const
3389{
3390	return sampleAlphaToOneEnabled;
3391}
3392
3393void Context::setPointSpriteEnabled(bool enable)
3394{
3395	pointSpriteEnabled = enable;
3396}
3397
3398bool Context::isPointSpriteEnabled() const
3399{
3400	return pointSpriteEnabled;
3401}
3402
3403void Context::setPointSmoothEnabled(bool enable)
3404{
3405	pointSmoothEnabled = enable;
3406}
3407
3408bool Context::isPointSmoothEnabled() const
3409{
3410	return pointSmoothEnabled;
3411}
3412
3413
3414void Context::setPointSizeMin(float min)
3415{
3416	pointSizeMin = min;
3417}
3418
3419void Context::setPointSizeMax(float max)
3420{
3421	pointSizeMax = max;
3422}
3423
3424void Context::setPointDistanceAttenuation(float a, float b, float c)
3425{
3426	pointDistanceAttenuation = {a, b, c};
3427}
3428
3429void Context::setPointFadeThresholdSize(float threshold)
3430{
3431	pointFadeThresholdSize = threshold;
3432}
3433
3434void Context::clientActiveTexture(GLenum texture)
3435{
3436	clientTexture = texture;
3437}
3438
3439GLenum Context::getClientActiveTexture() const
3440{
3441	return clientTexture;
3442}
3443
3444unsigned int Context::getActiveTexture() const
3445{
3446	return mState.activeSampler;
3447}
3448
3449}
3450
3451egl::Context *es1CreateContext(const egl::Config *config, const egl::Context *shareContext)
3452{
3453	ASSERT(!shareContext || shareContext->getClientVersion() == 1);   // Should be checked by eglCreateContext
3454	return new es1::Context(config, static_cast<const es1::Context*>(shareContext));
3455}
3456