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