blob: a09c36543fa078afa3c86ece4d6c1253210c8005 [file] [log] [blame]
apatrick@chromium.org144f2802012-07-12 01:42:34 +00001//
2// Copyright (c) 2002-2012 The ANGLE Project Authors. All rights reserved.
3// Use of this source code is governed by a BSD-style license that can be
4// found in the LICENSE file.
5//
6
7// Context.cpp: Implements the gl::Context class, managing all GL state and performing
8// rendering operations. It is the GLES2 specific implementation of EGLContext.
9
10#include "libGLESv2/Context.h"
11
12#include <algorithm>
13
14#include "libEGL/Display.h"
15
16#include "libGLESv2/main.h"
17#include "libGLESv2/mathutil.h"
18#include "libGLESv2/utilities.h"
daniel@transgaming.comd8e36562012-10-31 19:52:19 +000019#include "libGLESv2/renderer/renderer9_utils.h" // D3D9_REPLACE
apatrick@chromium.org144f2802012-07-12 01:42:34 +000020#include "libGLESv2/ResourceManager.h"
21#include "libGLESv2/Buffer.h"
22#include "libGLESv2/Fence.h"
daniel@transgaming.com29ab9522012-08-27 16:25:37 +000023#include "libGLESv2/Framebuffer.h"
apatrick@chromium.org144f2802012-07-12 01:42:34 +000024#include "libGLESv2/Program.h"
25#include "libGLESv2/ProgramBinary.h"
26#include "libGLESv2/Query.h"
daniel@transgaming.com29ab9522012-08-27 16:25:37 +000027#include "libGLESv2/Renderbuffer.h"
apatrick@chromium.org144f2802012-07-12 01:42:34 +000028#include "libGLESv2/Shader.h"
29#include "libGLESv2/Texture.h"
30#include "libGLESv2/VertexDataManager.h"
31#include "libGLESv2/IndexDataManager.h"
32
33#undef near
34#undef far
35
36namespace gl
37{
daniel@transgaming.com03d39092012-11-28 19:31:59 +000038Context::Context(const gl::Context *shareContext, rx::Renderer *renderer, bool notifyResets, bool robustAccess)
apatrick@chromium.org144f2802012-07-12 01:42:34 +000039{
40 ASSERT(robustAccess == false); // Unimplemented
41
daniel@transgaming.com03d39092012-11-28 19:31:59 +000042 ASSERT(dynamic_cast<rx::Renderer9*>(renderer) != NULL); // D3D9_REPLACE
43 mRenderer = static_cast<rx::Renderer9*>(renderer);
44
apatrick@chromium.org144f2802012-07-12 01:42:34 +000045 mDisplay = NULL;
46 mDevice = NULL;
47
48 mFenceHandleAllocator.setBaseHandle(0);
49
50 setClearColor(0.0f, 0.0f, 0.0f, 0.0f);
51
52 mState.depthClearValue = 1.0f;
53 mState.stencilClearValue = 0;
54
55 mState.cullFace = false;
56 mState.cullMode = GL_BACK;
57 mState.frontFace = GL_CCW;
58 mState.depthTest = false;
59 mState.depthFunc = GL_LESS;
60 mState.blend = false;
61 mState.sourceBlendRGB = GL_ONE;
62 mState.sourceBlendAlpha = GL_ONE;
63 mState.destBlendRGB = GL_ZERO;
64 mState.destBlendAlpha = GL_ZERO;
65 mState.blendEquationRGB = GL_FUNC_ADD;
66 mState.blendEquationAlpha = GL_FUNC_ADD;
67 mState.blendColor.red = 0;
68 mState.blendColor.green = 0;
69 mState.blendColor.blue = 0;
70 mState.blendColor.alpha = 0;
71 mState.stencilTest = false;
72 mState.stencilFunc = GL_ALWAYS;
73 mState.stencilRef = 0;
74 mState.stencilMask = -1;
75 mState.stencilWritemask = -1;
76 mState.stencilBackFunc = GL_ALWAYS;
77 mState.stencilBackRef = 0;
78 mState.stencilBackMask = - 1;
79 mState.stencilBackWritemask = -1;
80 mState.stencilFail = GL_KEEP;
81 mState.stencilPassDepthFail = GL_KEEP;
82 mState.stencilPassDepthPass = GL_KEEP;
83 mState.stencilBackFail = GL_KEEP;
84 mState.stencilBackPassDepthFail = GL_KEEP;
85 mState.stencilBackPassDepthPass = GL_KEEP;
86 mState.polygonOffsetFill = false;
87 mState.polygonOffsetFactor = 0.0f;
88 mState.polygonOffsetUnits = 0.0f;
89 mState.sampleAlphaToCoverage = false;
90 mState.sampleCoverage = false;
91 mState.sampleCoverageValue = 1.0f;
92 mState.sampleCoverageInvert = false;
93 mState.scissorTest = false;
94 mState.dither = true;
95 mState.generateMipmapHint = GL_DONT_CARE;
96 mState.fragmentShaderDerivativeHint = GL_DONT_CARE;
97
98 mState.lineWidth = 1.0f;
99
100 mState.viewportX = 0;
101 mState.viewportY = 0;
daniel@transgaming.com21290e62012-10-31 18:38:28 +0000102 mState.viewportWidth = 0;
103 mState.viewportHeight = 0;
apatrick@chromium.org144f2802012-07-12 01:42:34 +0000104 mState.zNear = 0.0f;
105 mState.zFar = 1.0f;
106
107 mState.scissorX = 0;
108 mState.scissorY = 0;
daniel@transgaming.com21290e62012-10-31 18:38:28 +0000109 mState.scissorWidth = 0;
110 mState.scissorHeight = 0;
apatrick@chromium.org144f2802012-07-12 01:42:34 +0000111
112 mState.colorMaskRed = true;
113 mState.colorMaskGreen = true;
114 mState.colorMaskBlue = true;
115 mState.colorMaskAlpha = true;
116 mState.depthMask = true;
117
118 if (shareContext != NULL)
119 {
120 mResourceManager = shareContext->mResourceManager;
121 mResourceManager->addRef();
122 }
123 else
124 {
daniel@transgaming.com370482e2012-11-28 19:32:13 +0000125 mResourceManager = new ResourceManager(mRenderer);
apatrick@chromium.org144f2802012-07-12 01:42:34 +0000126 }
127
128 // [OpenGL ES 2.0.24] section 3.7 page 83:
129 // In the initial state, TEXTURE_2D and TEXTURE_CUBE_MAP have twodimensional
130 // and cube map texture state vectors respectively associated with them.
131 // In order that access to these initial textures not be lost, they are treated as texture
132 // objects all of whose names are 0.
133
daniel@transgaming.com370482e2012-11-28 19:32:13 +0000134 mTexture2DZero.set(new Texture2D(mRenderer, 0));
135 mTextureCubeMapZero.set(new TextureCubeMap(mRenderer, 0));
apatrick@chromium.org144f2802012-07-12 01:42:34 +0000136
137 mState.activeSampler = 0;
138 bindArrayBuffer(0);
139 bindElementArrayBuffer(0);
140 bindTextureCubeMap(0);
141 bindTexture2D(0);
142 bindReadFramebuffer(0);
143 bindDrawFramebuffer(0);
144 bindRenderbuffer(0);
145
146 mState.currentProgram = 0;
daniel@transgaming.com989c1c82012-07-24 18:40:38 +0000147 mCurrentProgramBinary.set(NULL);
apatrick@chromium.org144f2802012-07-12 01:42:34 +0000148
149 mState.packAlignment = 4;
150 mState.unpackAlignment = 4;
151 mState.packReverseRowOrder = false;
152
153 mVertexDataManager = NULL;
154 mIndexDataManager = NULL;
apatrick@chromium.org144f2802012-07-12 01:42:34 +0000155 mLineLoopIB = NULL;
156
157 mInvalidEnum = false;
158 mInvalidValue = false;
159 mInvalidOperation = false;
160 mOutOfMemory = false;
161 mInvalidFramebufferOperation = false;
162
163 mHasBeenCurrent = false;
164 mContextLost = false;
165 mResetStatus = GL_NO_ERROR;
166 mResetStrategy = (notifyResets ? GL_LOSE_CONTEXT_ON_RESET_EXT : GL_NO_RESET_NOTIFICATION_EXT);
167 mRobustAccess = robustAccess;
168
169 mSupportsDXT1Textures = false;
170 mSupportsDXT3Textures = false;
171 mSupportsDXT5Textures = false;
172 mSupportsEventQueries = false;
173 mSupportsOcclusionQueries = false;
174 mNumCompressedTextureFormats = 0;
apatrick@chromium.org144f2802012-07-12 01:42:34 +0000175 mMaskedClearSavedState = NULL;
176 markAllStateDirty();
177}
178
179Context::~Context()
180{
181 if (mState.currentProgram != 0)
182 {
183 Program *programObject = mResourceManager->getProgram(mState.currentProgram);
184 if (programObject)
185 {
186 programObject->release();
187 }
188 mState.currentProgram = 0;
189 }
daniel@transgaming.com989c1c82012-07-24 18:40:38 +0000190 mCurrentProgramBinary.set(NULL);
apatrick@chromium.org144f2802012-07-12 01:42:34 +0000191
192 while (!mFramebufferMap.empty())
193 {
194 deleteFramebuffer(mFramebufferMap.begin()->first);
195 }
196
197 while (!mFenceMap.empty())
198 {
199 deleteFence(mFenceMap.begin()->first);
200 }
201
202 while (!mQueryMap.empty())
203 {
204 deleteQuery(mQueryMap.begin()->first);
205 }
206
apatrick@chromium.org144f2802012-07-12 01:42:34 +0000207 for (int type = 0; type < TEXTURE_TYPE_COUNT; type++)
208 {
209 for (int sampler = 0; sampler < MAX_COMBINED_TEXTURE_IMAGE_UNITS_VTF; sampler++)
210 {
211 mState.samplerTexture[type][sampler].set(NULL);
212 }
213 }
214
215 for (int type = 0; type < TEXTURE_TYPE_COUNT; type++)
216 {
217 mIncompleteTextures[type].set(NULL);
218 }
219
220 for (int i = 0; i < MAX_VERTEX_ATTRIBS; i++)
221 {
222 mState.vertexAttribute[i].mBoundBuffer.set(NULL);
223 }
224
225 for (int i = 0; i < QUERY_TYPE_COUNT; i++)
226 {
227 mState.activeQuery[i].set(NULL);
228 }
229
230 mState.arrayBuffer.set(NULL);
231 mState.elementArrayBuffer.set(NULL);
232 mState.renderbuffer.set(NULL);
233
234 mTexture2DZero.set(NULL);
235 mTextureCubeMapZero.set(NULL);
236
237 delete mVertexDataManager;
238 delete mIndexDataManager;
apatrick@chromium.org144f2802012-07-12 01:42:34 +0000239 delete mLineLoopIB;
240
241 if (mMaskedClearSavedState)
242 {
243 mMaskedClearSavedState->Release();
244 }
245
246 mResourceManager->release();
247}
248
daniel@transgaming.comad629872012-11-28 19:32:06 +0000249void Context::makeCurrent(egl::Surface *surface)
apatrick@chromium.org144f2802012-07-12 01:42:34 +0000250{
daniel@transgaming.com621ce052012-10-31 17:52:29 +0000251 mDevice = mRenderer->getDevice(); // D3D9_REMOVE
apatrick@chromium.org144f2802012-07-12 01:42:34 +0000252
253 if (!mHasBeenCurrent)
254 {
daniel@transgaming.com408caa52012-10-31 18:47:01 +0000255 mVertexDataManager = new VertexDataManager(mRenderer);
256 mIndexDataManager = new IndexDataManager(mRenderer);
apatrick@chromium.org144f2802012-07-12 01:42:34 +0000257
daniel@transgaming.com5f4c1362012-10-31 18:29:00 +0000258 mSupportsShaderModel3 = mRenderer->getShaderModel3Support();
259 mMaximumPointSize = mRenderer->getMaxPointSize();
daniel@transgaming.com621ce052012-10-31 17:52:29 +0000260 mSupportsVertexTexture = mRenderer->getVertexTextureSupport();
261 mSupportsNonPower2Texture = mRenderer->getNonPower2TextureSupport();
262 mSupportsInstancing = mRenderer->getInstancingSupport();
apatrick@chromium.org144f2802012-07-12 01:42:34 +0000263
daniel@transgaming.com5f4c1362012-10-31 18:29:00 +0000264 mMaxTextureDimension = std::min(std::min(mRenderer->getMaxTextureWidth(), mRenderer->getMaxTextureHeight()),
apatrick@chromium.org144f2802012-07-12 01:42:34 +0000265 (int)gl::IMPLEMENTATION_MAX_TEXTURE_SIZE);
266 mMaxCubeTextureDimension = std::min(mMaxTextureDimension, (int)gl::IMPLEMENTATION_MAX_CUBE_MAP_TEXTURE_SIZE);
267 mMaxRenderbufferDimension = mMaxTextureDimension;
268 mMaxTextureLevel = log2(mMaxTextureDimension) + 1;
daniel@transgaming.comba0570e2012-10-31 18:07:39 +0000269 mMaxTextureAnisotropy = mRenderer->getTextureMaxAnisotropy();
daniel@transgaming.com07ab8412012-07-12 15:17:09 +0000270 TRACE("MaxTextureDimension=%d, MaxCubeTextureDimension=%d, MaxRenderbufferDimension=%d, MaxTextureLevel=%d, MaxTextureAnisotropy=%f",
271 mMaxTextureDimension, mMaxCubeTextureDimension, mMaxRenderbufferDimension, mMaxTextureLevel, mMaxTextureAnisotropy);
apatrick@chromium.org144f2802012-07-12 01:42:34 +0000272
daniel@transgaming.com621ce052012-10-31 17:52:29 +0000273 mSupportsEventQueries = mRenderer->getEventQuerySupport();
274 mSupportsOcclusionQueries = mRenderer->getOcclusionQuerySupport();
275 mSupportsDXT1Textures = mRenderer->getDXT1TextureSupport();
276 mSupportsDXT3Textures = mRenderer->getDXT3TextureSupport();
277 mSupportsDXT5Textures = mRenderer->getDXT5TextureSupport();
278 mSupportsFloat32Textures = mRenderer->getFloat32TextureSupport(&mSupportsFloat32LinearFilter, &mSupportsFloat32RenderableTextures);
279 mSupportsFloat16Textures = mRenderer->getFloat16TextureSupport(&mSupportsFloat16LinearFilter, &mSupportsFloat16RenderableTextures);
280 mSupportsLuminanceTextures = mRenderer->getLuminanceTextureSupport();
281 mSupportsLuminanceAlphaTextures = mRenderer->getLuminanceAlphaTextureSupport();
282 mSupportsDepthTextures = mRenderer->getDepthTextureSupport();
daniel@transgaming.comba0570e2012-10-31 18:07:39 +0000283 mSupportsTextureFilterAnisotropy = mRenderer->getTextureFilterAnisotropySupport();
apatrick@chromium.org144f2802012-07-12 01:42:34 +0000284
daniel@transgaming.com5f4c1362012-10-31 18:29:00 +0000285 mSupports32bitIndices = mRenderer->get32BitIndexSupport();
apatrick@chromium.org144f2802012-07-12 01:42:34 +0000286
287 mNumCompressedTextureFormats = 0;
288 if (supportsDXT1Textures())
289 {
290 mNumCompressedTextureFormats += 2;
291 }
292 if (supportsDXT3Textures())
293 {
294 mNumCompressedTextureFormats += 1;
295 }
296 if (supportsDXT5Textures())
297 {
298 mNumCompressedTextureFormats += 1;
299 }
300
301 initExtensionString();
302 initRendererString();
303
304 mState.viewportX = 0;
305 mState.viewportY = 0;
306 mState.viewportWidth = surface->getWidth();
307 mState.viewportHeight = surface->getHeight();
308
309 mState.scissorX = 0;
310 mState.scissorY = 0;
311 mState.scissorWidth = surface->getWidth();
312 mState.scissorHeight = surface->getHeight();
313
314 mHasBeenCurrent = true;
315 }
316
daniel@transgaming.com024786d2012-10-31 18:42:55 +0000317 // Wrap the existing swapchain resources into GL objects and assign them to the '0' names
daniel@transgaming.com76d3e6e2012-10-31 19:55:33 +0000318 rx::SwapChain *swapchain = surface->getSwapChain();
apatrick@chromium.org144f2802012-07-12 01:42:34 +0000319
daniel@transgaming.com70062c92012-11-28 19:32:30 +0000320 Colorbuffer *colorbufferZero = new Colorbuffer(mRenderer, swapchain);
321 DepthStencilbuffer *depthStencilbufferZero = new DepthStencilbuffer(mRenderer, swapchain);
daniel@transgaming.com16418b12012-11-28 19:32:22 +0000322 Framebuffer *framebufferZero = new DefaultFramebuffer(mRenderer, colorbufferZero, depthStencilbufferZero);
apatrick@chromium.org144f2802012-07-12 01:42:34 +0000323
324 setFramebufferZero(framebufferZero);
325
apatrick@chromium.org909f21c2012-08-17 20:06:02 +0000326 // Reset pixel shader to null to work around a bug that only happens with Intel GPUs.
327 // http://crbug.com/110343
328 mDevice->SetPixelShader(NULL);
apatrick@chromium.org144f2802012-07-12 01:42:34 +0000329
330 markAllStateDirty();
331}
332
333// This function will set all of the state-related dirty flags, so that all state is set during next pre-draw.
334void Context::markAllStateDirty()
335{
336 for (int t = 0; t < MAX_TEXTURE_IMAGE_UNITS; t++)
337 {
338 mAppliedTextureSerialPS[t] = 0;
339 }
340
341 for (int t = 0; t < MAX_VERTEX_TEXTURE_IMAGE_UNITS_VTF; t++)
342 {
343 mAppliedTextureSerialVS[t] = 0;
344 }
345
daniel@transgaming.come6af4f92012-07-24 18:31:31 +0000346 mAppliedProgramBinarySerial = 0;
apatrick@chromium.org144f2802012-07-12 01:42:34 +0000347 mAppliedRenderTargetSerial = 0;
348 mAppliedDepthbufferSerial = 0;
349 mAppliedStencilbufferSerial = 0;
350 mAppliedIBSerial = 0;
351 mDepthStencilInitialized = false;
352 mViewportInitialized = false;
353 mRenderTargetDescInitialized = false;
354
355 mVertexDeclarationCache.markStateDirty();
356
357 mClearStateDirty = true;
358 mCullStateDirty = true;
359 mDepthStateDirty = true;
360 mMaskStateDirty = true;
361 mBlendStateDirty = true;
362 mStencilStateDirty = true;
363 mPolygonOffsetStateDirty = true;
364 mScissorStateDirty = true;
365 mSampleStateDirty = true;
366 mDitherStateDirty = true;
367 mFrontFaceDirty = true;
368 mDxUniformsDirty = true;
apatrick@chromium.org144f2802012-07-12 01:42:34 +0000369}
370
371void Context::markDxUniformsDirty()
372{
373 mDxUniformsDirty = true;
374}
375
daniel@transgaming.comf688c0d2012-10-31 17:52:57 +0000376// NOTE: this function should not assume that this context is current!
apatrick@chromium.org144f2802012-07-12 01:42:34 +0000377void Context::markContextLost()
378{
379 if (mResetStrategy == GL_LOSE_CONTEXT_ON_RESET_EXT)
380 mResetStatus = GL_UNKNOWN_CONTEXT_RESET_EXT;
381 mContextLost = true;
382}
383
384bool Context::isContextLost()
385{
386 return mContextLost;
387}
388
389void Context::setClearColor(float red, float green, float blue, float alpha)
390{
391 mState.colorClearValue.red = red;
392 mState.colorClearValue.green = green;
393 mState.colorClearValue.blue = blue;
394 mState.colorClearValue.alpha = alpha;
395}
396
397void Context::setClearDepth(float depth)
398{
399 mState.depthClearValue = depth;
400}
401
402void Context::setClearStencil(int stencil)
403{
404 mState.stencilClearValue = stencil;
405}
406
407void Context::setCullFace(bool enabled)
408{
409 if (mState.cullFace != enabled)
410 {
411 mState.cullFace = enabled;
412 mCullStateDirty = true;
413 }
414}
415
416bool Context::isCullFaceEnabled() const
417{
418 return mState.cullFace;
419}
420
421void Context::setCullMode(GLenum mode)
422{
423 if (mState.cullMode != mode)
424 {
425 mState.cullMode = mode;
426 mCullStateDirty = true;
427 }
428}
429
430void Context::setFrontFace(GLenum front)
431{
432 if (mState.frontFace != front)
433 {
434 mState.frontFace = front;
435 mFrontFaceDirty = true;
436 }
437}
438
439void Context::setDepthTest(bool enabled)
440{
441 if (mState.depthTest != enabled)
442 {
443 mState.depthTest = enabled;
444 mDepthStateDirty = true;
445 }
446}
447
448bool Context::isDepthTestEnabled() const
449{
450 return mState.depthTest;
451}
452
453void Context::setDepthFunc(GLenum depthFunc)
454{
455 if (mState.depthFunc != depthFunc)
456 {
457 mState.depthFunc = depthFunc;
458 mDepthStateDirty = true;
459 }
460}
461
462void Context::setDepthRange(float zNear, float zFar)
463{
464 mState.zNear = zNear;
465 mState.zFar = zFar;
466}
467
468void Context::setBlend(bool enabled)
469{
470 if (mState.blend != enabled)
471 {
472 mState.blend = enabled;
473 mBlendStateDirty = true;
474 }
475}
476
477bool Context::isBlendEnabled() const
478{
479 return mState.blend;
480}
481
482void Context::setBlendFactors(GLenum sourceRGB, GLenum destRGB, GLenum sourceAlpha, GLenum destAlpha)
483{
484 if (mState.sourceBlendRGB != sourceRGB ||
485 mState.sourceBlendAlpha != sourceAlpha ||
486 mState.destBlendRGB != destRGB ||
487 mState.destBlendAlpha != destAlpha)
488 {
489 mState.sourceBlendRGB = sourceRGB;
490 mState.destBlendRGB = destRGB;
491 mState.sourceBlendAlpha = sourceAlpha;
492 mState.destBlendAlpha = destAlpha;
493 mBlendStateDirty = true;
494 }
495}
496
497void Context::setBlendColor(float red, float green, float blue, float alpha)
498{
499 if (mState.blendColor.red != red ||
500 mState.blendColor.green != green ||
501 mState.blendColor.blue != blue ||
502 mState.blendColor.alpha != alpha)
503 {
504 mState.blendColor.red = red;
505 mState.blendColor.green = green;
506 mState.blendColor.blue = blue;
507 mState.blendColor.alpha = alpha;
508 mBlendStateDirty = true;
509 }
510}
511
512void Context::setBlendEquation(GLenum rgbEquation, GLenum alphaEquation)
513{
514 if (mState.blendEquationRGB != rgbEquation ||
515 mState.blendEquationAlpha != alphaEquation)
516 {
517 mState.blendEquationRGB = rgbEquation;
518 mState.blendEquationAlpha = alphaEquation;
519 mBlendStateDirty = true;
520 }
521}
522
523void Context::setStencilTest(bool enabled)
524{
525 if (mState.stencilTest != enabled)
526 {
527 mState.stencilTest = enabled;
528 mStencilStateDirty = true;
529 }
530}
531
532bool Context::isStencilTestEnabled() const
533{
534 return mState.stencilTest;
535}
536
537void Context::setStencilParams(GLenum stencilFunc, GLint stencilRef, GLuint stencilMask)
538{
539 if (mState.stencilFunc != stencilFunc ||
540 mState.stencilRef != stencilRef ||
541 mState.stencilMask != stencilMask)
542 {
543 mState.stencilFunc = stencilFunc;
544 mState.stencilRef = (stencilRef > 0) ? stencilRef : 0;
545 mState.stencilMask = stencilMask;
546 mStencilStateDirty = true;
547 }
548}
549
550void Context::setStencilBackParams(GLenum stencilBackFunc, GLint stencilBackRef, GLuint stencilBackMask)
551{
552 if (mState.stencilBackFunc != stencilBackFunc ||
553 mState.stencilBackRef != stencilBackRef ||
554 mState.stencilBackMask != stencilBackMask)
555 {
556 mState.stencilBackFunc = stencilBackFunc;
557 mState.stencilBackRef = (stencilBackRef > 0) ? stencilBackRef : 0;
558 mState.stencilBackMask = stencilBackMask;
559 mStencilStateDirty = true;
560 }
561}
562
563void Context::setStencilWritemask(GLuint stencilWritemask)
564{
565 if (mState.stencilWritemask != stencilWritemask)
566 {
567 mState.stencilWritemask = stencilWritemask;
568 mStencilStateDirty = true;
569 }
570}
571
572void Context::setStencilBackWritemask(GLuint stencilBackWritemask)
573{
574 if (mState.stencilBackWritemask != stencilBackWritemask)
575 {
576 mState.stencilBackWritemask = stencilBackWritemask;
577 mStencilStateDirty = true;
578 }
579}
580
581void Context::setStencilOperations(GLenum stencilFail, GLenum stencilPassDepthFail, GLenum stencilPassDepthPass)
582{
583 if (mState.stencilFail != stencilFail ||
584 mState.stencilPassDepthFail != stencilPassDepthFail ||
585 mState.stencilPassDepthPass != stencilPassDepthPass)
586 {
587 mState.stencilFail = stencilFail;
588 mState.stencilPassDepthFail = stencilPassDepthFail;
589 mState.stencilPassDepthPass = stencilPassDepthPass;
590 mStencilStateDirty = true;
591 }
592}
593
594void Context::setStencilBackOperations(GLenum stencilBackFail, GLenum stencilBackPassDepthFail, GLenum stencilBackPassDepthPass)
595{
596 if (mState.stencilBackFail != stencilBackFail ||
597 mState.stencilBackPassDepthFail != stencilBackPassDepthFail ||
598 mState.stencilBackPassDepthPass != stencilBackPassDepthPass)
599 {
600 mState.stencilBackFail = stencilBackFail;
601 mState.stencilBackPassDepthFail = stencilBackPassDepthFail;
602 mState.stencilBackPassDepthPass = stencilBackPassDepthPass;
603 mStencilStateDirty = true;
604 }
605}
606
607void Context::setPolygonOffsetFill(bool enabled)
608{
609 if (mState.polygonOffsetFill != enabled)
610 {
611 mState.polygonOffsetFill = enabled;
612 mPolygonOffsetStateDirty = true;
613 }
614}
615
616bool Context::isPolygonOffsetFillEnabled() const
617{
618 return mState.polygonOffsetFill;
619
620}
621
622void Context::setPolygonOffsetParams(GLfloat factor, GLfloat units)
623{
624 if (mState.polygonOffsetFactor != factor ||
625 mState.polygonOffsetUnits != units)
626 {
627 mState.polygonOffsetFactor = factor;
628 mState.polygonOffsetUnits = units;
629 mPolygonOffsetStateDirty = true;
630 }
631}
632
633void Context::setSampleAlphaToCoverage(bool enabled)
634{
635 if (mState.sampleAlphaToCoverage != enabled)
636 {
637 mState.sampleAlphaToCoverage = enabled;
638 mSampleStateDirty = true;
639 }
640}
641
642bool Context::isSampleAlphaToCoverageEnabled() const
643{
644 return mState.sampleAlphaToCoverage;
645}
646
647void Context::setSampleCoverage(bool enabled)
648{
649 if (mState.sampleCoverage != enabled)
650 {
651 mState.sampleCoverage = enabled;
652 mSampleStateDirty = true;
653 }
654}
655
656bool Context::isSampleCoverageEnabled() const
657{
658 return mState.sampleCoverage;
659}
660
661void Context::setSampleCoverageParams(GLclampf value, bool invert)
662{
663 if (mState.sampleCoverageValue != value ||
664 mState.sampleCoverageInvert != invert)
665 {
666 mState.sampleCoverageValue = value;
667 mState.sampleCoverageInvert = invert;
668 mSampleStateDirty = true;
669 }
670}
671
672void Context::setScissorTest(bool enabled)
673{
674 if (mState.scissorTest != enabled)
675 {
676 mState.scissorTest = enabled;
677 mScissorStateDirty = true;
678 }
679}
680
681bool Context::isScissorTestEnabled() const
682{
683 return mState.scissorTest;
684}
685
686void Context::setDither(bool enabled)
687{
688 if (mState.dither != enabled)
689 {
690 mState.dither = enabled;
691 mDitherStateDirty = true;
692 }
693}
694
695bool Context::isDitherEnabled() const
696{
697 return mState.dither;
698}
699
700void Context::setLineWidth(GLfloat width)
701{
702 mState.lineWidth = width;
703}
704
705void Context::setGenerateMipmapHint(GLenum hint)
706{
707 mState.generateMipmapHint = hint;
708}
709
710void Context::setFragmentShaderDerivativeHint(GLenum hint)
711{
712 mState.fragmentShaderDerivativeHint = hint;
713 // TODO: Propagate the hint to shader translator so we can write
714 // ddx, ddx_coarse, or ddx_fine depending on the hint.
715 // Ignore for now. It is valid for implementations to ignore hint.
716}
717
718void Context::setViewportParams(GLint x, GLint y, GLsizei width, GLsizei height)
719{
720 mState.viewportX = x;
721 mState.viewportY = y;
722 mState.viewportWidth = width;
723 mState.viewportHeight = height;
724}
725
726void Context::setScissorParams(GLint x, GLint y, GLsizei width, GLsizei height)
727{
728 if (mState.scissorX != x || mState.scissorY != y ||
729 mState.scissorWidth != width || mState.scissorHeight != height)
730 {
731 mState.scissorX = x;
732 mState.scissorY = y;
733 mState.scissorWidth = width;
734 mState.scissorHeight = height;
735 mScissorStateDirty = true;
736 }
737}
738
739void Context::setColorMask(bool red, bool green, bool blue, bool alpha)
740{
741 if (mState.colorMaskRed != red || mState.colorMaskGreen != green ||
742 mState.colorMaskBlue != blue || mState.colorMaskAlpha != alpha)
743 {
744 mState.colorMaskRed = red;
745 mState.colorMaskGreen = green;
746 mState.colorMaskBlue = blue;
747 mState.colorMaskAlpha = alpha;
748 mMaskStateDirty = true;
749 }
750}
751
752void Context::setDepthMask(bool mask)
753{
754 if (mState.depthMask != mask)
755 {
756 mState.depthMask = mask;
757 mMaskStateDirty = true;
758 }
759}
760
761void Context::setActiveSampler(unsigned int active)
762{
763 mState.activeSampler = active;
764}
765
766GLuint Context::getReadFramebufferHandle() const
767{
768 return mState.readFramebuffer;
769}
770
771GLuint Context::getDrawFramebufferHandle() const
772{
773 return mState.drawFramebuffer;
774}
775
776GLuint Context::getRenderbufferHandle() const
777{
778 return mState.renderbuffer.id();
779}
780
781GLuint Context::getArrayBufferHandle() const
782{
783 return mState.arrayBuffer.id();
784}
785
786GLuint Context::getActiveQuery(GLenum target) const
787{
788 Query *queryObject = NULL;
789
790 switch (target)
791 {
792 case GL_ANY_SAMPLES_PASSED_EXT:
793 queryObject = mState.activeQuery[QUERY_ANY_SAMPLES_PASSED].get();
794 break;
795 case GL_ANY_SAMPLES_PASSED_CONSERVATIVE_EXT:
796 queryObject = mState.activeQuery[QUERY_ANY_SAMPLES_PASSED_CONSERVATIVE].get();
797 break;
798 default:
799 ASSERT(false);
800 }
801
802 if (queryObject)
803 {
804 return queryObject->id();
805 }
806 else
807 {
808 return 0;
809 }
810}
811
812void Context::setEnableVertexAttribArray(unsigned int attribNum, bool enabled)
813{
814 mState.vertexAttribute[attribNum].mArrayEnabled = enabled;
815}
816
817const VertexAttribute &Context::getVertexAttribState(unsigned int attribNum)
818{
819 return mState.vertexAttribute[attribNum];
820}
821
822void Context::setVertexAttribState(unsigned int attribNum, Buffer *boundBuffer, GLint size, GLenum type, bool normalized,
823 GLsizei stride, const void *pointer)
824{
825 mState.vertexAttribute[attribNum].mBoundBuffer.set(boundBuffer);
826 mState.vertexAttribute[attribNum].mSize = size;
827 mState.vertexAttribute[attribNum].mType = type;
828 mState.vertexAttribute[attribNum].mNormalized = normalized;
829 mState.vertexAttribute[attribNum].mStride = stride;
830 mState.vertexAttribute[attribNum].mPointer = pointer;
831}
832
833const void *Context::getVertexAttribPointer(unsigned int attribNum) const
834{
835 return mState.vertexAttribute[attribNum].mPointer;
836}
837
apatrick@chromium.org144f2802012-07-12 01:42:34 +0000838void Context::setPackAlignment(GLint alignment)
839{
840 mState.packAlignment = alignment;
841}
842
843GLint Context::getPackAlignment() const
844{
845 return mState.packAlignment;
846}
847
848void Context::setUnpackAlignment(GLint alignment)
849{
850 mState.unpackAlignment = alignment;
851}
852
853GLint Context::getUnpackAlignment() const
854{
855 return mState.unpackAlignment;
856}
857
858void Context::setPackReverseRowOrder(bool reverseRowOrder)
859{
860 mState.packReverseRowOrder = reverseRowOrder;
861}
862
863bool Context::getPackReverseRowOrder() const
864{
865 return mState.packReverseRowOrder;
866}
867
868GLuint Context::createBuffer()
869{
870 return mResourceManager->createBuffer();
871}
872
873GLuint Context::createProgram()
874{
875 return mResourceManager->createProgram();
876}
877
878GLuint Context::createShader(GLenum type)
879{
880 return mResourceManager->createShader(type);
881}
882
883GLuint Context::createTexture()
884{
885 return mResourceManager->createTexture();
886}
887
888GLuint Context::createRenderbuffer()
889{
890 return mResourceManager->createRenderbuffer();
891}
892
893// Returns an unused framebuffer name
894GLuint Context::createFramebuffer()
895{
896 GLuint handle = mFramebufferHandleAllocator.allocate();
897
898 mFramebufferMap[handle] = NULL;
899
900 return handle;
901}
902
903GLuint Context::createFence()
904{
905 GLuint handle = mFenceHandleAllocator.allocate();
906
daniel@transgaming.comef21ab22012-10-31 17:52:47 +0000907 mFenceMap[handle] = new Fence(mRenderer);
apatrick@chromium.org144f2802012-07-12 01:42:34 +0000908
909 return handle;
910}
911
912// Returns an unused query name
913GLuint Context::createQuery()
914{
915 GLuint handle = mQueryHandleAllocator.allocate();
916
917 mQueryMap[handle] = NULL;
918
919 return handle;
920}
921
922void Context::deleteBuffer(GLuint buffer)
923{
924 if (mResourceManager->getBuffer(buffer))
925 {
926 detachBuffer(buffer);
927 }
928
929 mResourceManager->deleteBuffer(buffer);
930}
931
932void Context::deleteShader(GLuint shader)
933{
934 mResourceManager->deleteShader(shader);
935}
936
937void Context::deleteProgram(GLuint program)
938{
939 mResourceManager->deleteProgram(program);
apatrick@chromium.org144f2802012-07-12 01:42:34 +0000940}
941
942void Context::deleteTexture(GLuint texture)
943{
944 if (mResourceManager->getTexture(texture))
945 {
946 detachTexture(texture);
947 }
948
949 mResourceManager->deleteTexture(texture);
950}
951
952void Context::deleteRenderbuffer(GLuint renderbuffer)
953{
954 if (mResourceManager->getRenderbuffer(renderbuffer))
955 {
956 detachRenderbuffer(renderbuffer);
957 }
958
959 mResourceManager->deleteRenderbuffer(renderbuffer);
960}
961
962void Context::deleteFramebuffer(GLuint framebuffer)
963{
964 FramebufferMap::iterator framebufferObject = mFramebufferMap.find(framebuffer);
965
966 if (framebufferObject != mFramebufferMap.end())
967 {
968 detachFramebuffer(framebuffer);
969
970 mFramebufferHandleAllocator.release(framebufferObject->first);
971 delete framebufferObject->second;
972 mFramebufferMap.erase(framebufferObject);
973 }
974}
975
976void Context::deleteFence(GLuint fence)
977{
978 FenceMap::iterator fenceObject = mFenceMap.find(fence);
979
980 if (fenceObject != mFenceMap.end())
981 {
982 mFenceHandleAllocator.release(fenceObject->first);
983 delete fenceObject->second;
984 mFenceMap.erase(fenceObject);
985 }
986}
987
988void Context::deleteQuery(GLuint query)
989{
990 QueryMap::iterator queryObject = mQueryMap.find(query);
991 if (queryObject != mQueryMap.end())
992 {
993 mQueryHandleAllocator.release(queryObject->first);
994 if (queryObject->second)
995 {
996 queryObject->second->release();
997 }
998 mQueryMap.erase(queryObject);
999 }
1000}
1001
1002Buffer *Context::getBuffer(GLuint handle)
1003{
1004 return mResourceManager->getBuffer(handle);
1005}
1006
1007Shader *Context::getShader(GLuint handle)
1008{
1009 return mResourceManager->getShader(handle);
1010}
1011
1012Program *Context::getProgram(GLuint handle)
1013{
1014 return mResourceManager->getProgram(handle);
1015}
1016
1017Texture *Context::getTexture(GLuint handle)
1018{
1019 return mResourceManager->getTexture(handle);
1020}
1021
1022Renderbuffer *Context::getRenderbuffer(GLuint handle)
1023{
1024 return mResourceManager->getRenderbuffer(handle);
1025}
1026
1027Framebuffer *Context::getReadFramebuffer()
1028{
1029 return getFramebuffer(mState.readFramebuffer);
1030}
1031
1032Framebuffer *Context::getDrawFramebuffer()
1033{
1034 return mBoundDrawFramebuffer;
1035}
1036
1037void Context::bindArrayBuffer(unsigned int buffer)
1038{
1039 mResourceManager->checkBufferAllocation(buffer);
1040
1041 mState.arrayBuffer.set(getBuffer(buffer));
1042}
1043
1044void Context::bindElementArrayBuffer(unsigned int buffer)
1045{
1046 mResourceManager->checkBufferAllocation(buffer);
1047
1048 mState.elementArrayBuffer.set(getBuffer(buffer));
1049}
1050
1051void Context::bindTexture2D(GLuint texture)
1052{
1053 mResourceManager->checkTextureAllocation(texture, TEXTURE_2D);
1054
1055 mState.samplerTexture[TEXTURE_2D][mState.activeSampler].set(getTexture(texture));
1056}
1057
1058void Context::bindTextureCubeMap(GLuint texture)
1059{
1060 mResourceManager->checkTextureAllocation(texture, TEXTURE_CUBE);
1061
1062 mState.samplerTexture[TEXTURE_CUBE][mState.activeSampler].set(getTexture(texture));
1063}
1064
1065void Context::bindReadFramebuffer(GLuint framebuffer)
1066{
1067 if (!getFramebuffer(framebuffer))
1068 {
daniel@transgaming.com16418b12012-11-28 19:32:22 +00001069 mFramebufferMap[framebuffer] = new Framebuffer(mRenderer);
apatrick@chromium.org144f2802012-07-12 01:42:34 +00001070 }
1071
1072 mState.readFramebuffer = framebuffer;
1073}
1074
1075void Context::bindDrawFramebuffer(GLuint framebuffer)
1076{
1077 if (!getFramebuffer(framebuffer))
1078 {
daniel@transgaming.com16418b12012-11-28 19:32:22 +00001079 mFramebufferMap[framebuffer] = new Framebuffer(mRenderer);
apatrick@chromium.org144f2802012-07-12 01:42:34 +00001080 }
1081
1082 mState.drawFramebuffer = framebuffer;
1083
1084 mBoundDrawFramebuffer = getFramebuffer(framebuffer);
1085}
1086
1087void Context::bindRenderbuffer(GLuint renderbuffer)
1088{
1089 mResourceManager->checkRenderbufferAllocation(renderbuffer);
1090
1091 mState.renderbuffer.set(getRenderbuffer(renderbuffer));
1092}
1093
1094void Context::useProgram(GLuint program)
1095{
1096 GLuint priorProgram = mState.currentProgram;
1097 mState.currentProgram = program; // Must switch before trying to delete, otherwise it only gets flagged.
1098
1099 if (priorProgram != program)
1100 {
1101 Program *newProgram = mResourceManager->getProgram(program);
1102 Program *oldProgram = mResourceManager->getProgram(priorProgram);
daniel@transgaming.com989c1c82012-07-24 18:40:38 +00001103 mCurrentProgramBinary.set(NULL);
apatrick@chromium.org144f2802012-07-12 01:42:34 +00001104 mDxUniformsDirty = true;
1105
1106 if (newProgram)
1107 {
1108 newProgram->addRef();
daniel@transgaming.com989c1c82012-07-24 18:40:38 +00001109 mCurrentProgramBinary.set(newProgram->getProgramBinary());
apatrick@chromium.org144f2802012-07-12 01:42:34 +00001110 }
1111
1112 if (oldProgram)
1113 {
1114 oldProgram->release();
1115 }
1116 }
1117}
1118
daniel@transgaming.com95d29422012-07-24 18:36:10 +00001119void Context::linkProgram(GLuint program)
1120{
1121 Program *programObject = mResourceManager->getProgram(program);
1122
daniel@transgaming.com12394cf2012-07-24 18:37:59 +00001123 bool linked = programObject->link();
1124
1125 // if the current program was relinked successfully we
1126 // need to install the new executables
1127 if (linked && program == mState.currentProgram)
1128 {
daniel@transgaming.com989c1c82012-07-24 18:40:38 +00001129 mCurrentProgramBinary.set(programObject->getProgramBinary());
daniel@transgaming.com12394cf2012-07-24 18:37:59 +00001130 mDxUniformsDirty = true;
1131 }
daniel@transgaming.com95d29422012-07-24 18:36:10 +00001132}
1133
1134void Context::setProgramBinary(GLuint program, const void *binary, GLint length)
1135{
1136 Program *programObject = mResourceManager->getProgram(program);
1137
daniel@transgaming.com12394cf2012-07-24 18:37:59 +00001138 bool loaded = programObject->setProgramBinary(binary, length);
1139
1140 // if the current program was reloaded successfully we
1141 // need to install the new executables
1142 if (loaded && program == mState.currentProgram)
1143 {
daniel@transgaming.com989c1c82012-07-24 18:40:38 +00001144 mCurrentProgramBinary.set(programObject->getProgramBinary());
daniel@transgaming.com12394cf2012-07-24 18:37:59 +00001145 mDxUniformsDirty = true;
1146 }
1147
daniel@transgaming.com95d29422012-07-24 18:36:10 +00001148}
1149
apatrick@chromium.org144f2802012-07-12 01:42:34 +00001150void Context::beginQuery(GLenum target, GLuint query)
1151{
1152 // From EXT_occlusion_query_boolean: If BeginQueryEXT is called with an <id>
1153 // of zero, if the active query object name for <target> is non-zero (for the
1154 // targets ANY_SAMPLES_PASSED_EXT and ANY_SAMPLES_PASSED_CONSERVATIVE_EXT, if
1155 // the active query for either target is non-zero), if <id> is the name of an
1156 // existing query object whose type does not match <target>, or if <id> is the
1157 // active query object name for any query type, the error INVALID_OPERATION is
1158 // generated.
1159
1160 // Ensure no other queries are active
1161 // NOTE: If other queries than occlusion are supported, we will need to check
1162 // separately that:
1163 // a) The query ID passed is not the current active query for any target/type
1164 // b) There are no active queries for the requested target (and in the case
1165 // of GL_ANY_SAMPLES_PASSED_EXT and GL_ANY_SAMPLES_PASSED_CONSERVATIVE_EXT,
1166 // no query may be active for either if glBeginQuery targets either.
1167 for (int i = 0; i < QUERY_TYPE_COUNT; i++)
1168 {
1169 if (mState.activeQuery[i].get() != NULL)
1170 {
1171 return error(GL_INVALID_OPERATION);
1172 }
1173 }
1174
1175 QueryType qType;
1176 switch (target)
1177 {
1178 case GL_ANY_SAMPLES_PASSED_EXT:
1179 qType = QUERY_ANY_SAMPLES_PASSED;
1180 break;
1181 case GL_ANY_SAMPLES_PASSED_CONSERVATIVE_EXT:
1182 qType = QUERY_ANY_SAMPLES_PASSED_CONSERVATIVE;
1183 break;
1184 default:
1185 ASSERT(false);
1186 return;
1187 }
1188
1189 Query *queryObject = getQuery(query, true, target);
1190
1191 // check that name was obtained with glGenQueries
1192 if (!queryObject)
1193 {
1194 return error(GL_INVALID_OPERATION);
1195 }
1196
1197 // check for type mismatch
1198 if (queryObject->getType() != target)
1199 {
1200 return error(GL_INVALID_OPERATION);
1201 }
1202
1203 // set query as active for specified target
1204 mState.activeQuery[qType].set(queryObject);
1205
1206 // begin query
1207 queryObject->begin();
1208}
1209
1210void Context::endQuery(GLenum target)
1211{
1212 QueryType qType;
1213
1214 switch (target)
1215 {
1216 case GL_ANY_SAMPLES_PASSED_EXT:
1217 qType = QUERY_ANY_SAMPLES_PASSED;
1218 break;
1219 case GL_ANY_SAMPLES_PASSED_CONSERVATIVE_EXT:
1220 qType = QUERY_ANY_SAMPLES_PASSED_CONSERVATIVE;
1221 break;
1222 default:
1223 ASSERT(false);
1224 return;
1225 }
1226
1227 Query *queryObject = mState.activeQuery[qType].get();
1228
1229 if (queryObject == NULL)
1230 {
1231 return error(GL_INVALID_OPERATION);
1232 }
1233
1234 queryObject->end();
1235
1236 mState.activeQuery[qType].set(NULL);
1237}
1238
1239void Context::setFramebufferZero(Framebuffer *buffer)
1240{
1241 delete mFramebufferMap[0];
1242 mFramebufferMap[0] = buffer;
1243 if (mState.drawFramebuffer == 0)
1244 {
1245 mBoundDrawFramebuffer = buffer;
1246 }
1247}
1248
daniel@transgaming.com70062c92012-11-28 19:32:30 +00001249void Context::setRenderbufferStorage(GLsizei width, GLsizei height, GLenum internalformat, GLsizei samples)
apatrick@chromium.org144f2802012-07-12 01:42:34 +00001250{
daniel@transgaming.com70062c92012-11-28 19:32:30 +00001251 RenderbufferStorage *renderbuffer = NULL;
1252 switch (internalformat)
1253 {
1254 case GL_DEPTH_COMPONENT16:
1255 renderbuffer = new gl::Depthbuffer(mRenderer, width, height, samples);
1256 break;
1257 case GL_RGBA4:
1258 case GL_RGB5_A1:
1259 case GL_RGB565:
1260 case GL_RGB8_OES:
1261 case GL_RGBA8_OES:
1262 renderbuffer = new gl::Colorbuffer(mRenderer,width, height, internalformat, samples);
1263 break;
1264 case GL_STENCIL_INDEX8:
1265 renderbuffer = new gl::Stencilbuffer(mRenderer, width, height, samples);
1266 break;
1267 case GL_DEPTH24_STENCIL8_OES:
1268 renderbuffer = new gl::DepthStencilbuffer(mRenderer, width, height, samples);
1269 break;
1270 default:
1271 UNREACHABLE(); return;
1272 }
1273
apatrick@chromium.org144f2802012-07-12 01:42:34 +00001274 Renderbuffer *renderbufferObject = mState.renderbuffer.get();
1275 renderbufferObject->setStorage(renderbuffer);
1276}
1277
1278Framebuffer *Context::getFramebuffer(unsigned int handle)
1279{
1280 FramebufferMap::iterator framebuffer = mFramebufferMap.find(handle);
1281
1282 if (framebuffer == mFramebufferMap.end())
1283 {
1284 return NULL;
1285 }
1286 else
1287 {
1288 return framebuffer->second;
1289 }
1290}
1291
1292Fence *Context::getFence(unsigned int handle)
1293{
1294 FenceMap::iterator fence = mFenceMap.find(handle);
1295
1296 if (fence == mFenceMap.end())
1297 {
1298 return NULL;
1299 }
1300 else
1301 {
1302 return fence->second;
1303 }
1304}
1305
1306Query *Context::getQuery(unsigned int handle, bool create, GLenum type)
1307{
1308 QueryMap::iterator query = mQueryMap.find(handle);
1309
1310 if (query == mQueryMap.end())
1311 {
1312 return NULL;
1313 }
1314 else
1315 {
1316 if (!query->second && create)
1317 {
daniel@transgaming.comef21ab22012-10-31 17:52:47 +00001318 query->second = new Query(mRenderer, handle, type);
apatrick@chromium.org144f2802012-07-12 01:42:34 +00001319 query->second->addRef();
1320 }
1321 return query->second;
1322 }
1323}
1324
1325Buffer *Context::getArrayBuffer()
1326{
1327 return mState.arrayBuffer.get();
1328}
1329
1330Buffer *Context::getElementArrayBuffer()
1331{
1332 return mState.elementArrayBuffer.get();
1333}
1334
daniel@transgaming.com62a28462012-07-24 18:33:59 +00001335ProgramBinary *Context::getCurrentProgramBinary()
apatrick@chromium.org144f2802012-07-12 01:42:34 +00001336{
daniel@transgaming.com989c1c82012-07-24 18:40:38 +00001337 return mCurrentProgramBinary.get();
apatrick@chromium.org144f2802012-07-12 01:42:34 +00001338}
1339
1340Texture2D *Context::getTexture2D()
1341{
1342 return static_cast<Texture2D*>(getSamplerTexture(mState.activeSampler, TEXTURE_2D));
1343}
1344
1345TextureCubeMap *Context::getTextureCubeMap()
1346{
1347 return static_cast<TextureCubeMap*>(getSamplerTexture(mState.activeSampler, TEXTURE_CUBE));
1348}
1349
1350Texture *Context::getSamplerTexture(unsigned int sampler, TextureType type)
1351{
1352 GLuint texid = mState.samplerTexture[type][sampler].id();
1353
1354 if (texid == 0) // Special case: 0 refers to different initial textures based on the target
1355 {
1356 switch (type)
1357 {
1358 default: UNREACHABLE();
1359 case TEXTURE_2D: return mTexture2DZero.get();
1360 case TEXTURE_CUBE: return mTextureCubeMapZero.get();
1361 }
1362 }
1363
1364 return mState.samplerTexture[type][sampler].get();
1365}
1366
1367bool Context::getBooleanv(GLenum pname, GLboolean *params)
1368{
1369 switch (pname)
1370 {
1371 case GL_SHADER_COMPILER: *params = GL_TRUE; break;
1372 case GL_SAMPLE_COVERAGE_INVERT: *params = mState.sampleCoverageInvert; break;
1373 case GL_DEPTH_WRITEMASK: *params = mState.depthMask; break;
1374 case GL_COLOR_WRITEMASK:
1375 params[0] = mState.colorMaskRed;
1376 params[1] = mState.colorMaskGreen;
1377 params[2] = mState.colorMaskBlue;
1378 params[3] = mState.colorMaskAlpha;
1379 break;
1380 case GL_CULL_FACE: *params = mState.cullFace; break;
1381 case GL_POLYGON_OFFSET_FILL: *params = mState.polygonOffsetFill; break;
1382 case GL_SAMPLE_ALPHA_TO_COVERAGE: *params = mState.sampleAlphaToCoverage; break;
1383 case GL_SAMPLE_COVERAGE: *params = mState.sampleCoverage; break;
1384 case GL_SCISSOR_TEST: *params = mState.scissorTest; break;
1385 case GL_STENCIL_TEST: *params = mState.stencilTest; break;
1386 case GL_DEPTH_TEST: *params = mState.depthTest; break;
1387 case GL_BLEND: *params = mState.blend; break;
1388 case GL_DITHER: *params = mState.dither; break;
1389 case GL_CONTEXT_ROBUST_ACCESS_EXT: *params = mRobustAccess ? GL_TRUE : GL_FALSE; break;
1390 default:
1391 return false;
1392 }
1393
1394 return true;
1395}
1396
1397bool Context::getFloatv(GLenum pname, GLfloat *params)
1398{
1399 // Please note: DEPTH_CLEAR_VALUE is included in our internal getFloatv implementation
1400 // because it is stored as a float, despite the fact that the GL ES 2.0 spec names
1401 // GetIntegerv as its native query function. As it would require conversion in any
1402 // case, this should make no difference to the calling application.
1403 switch (pname)
1404 {
1405 case GL_LINE_WIDTH: *params = mState.lineWidth; break;
1406 case GL_SAMPLE_COVERAGE_VALUE: *params = mState.sampleCoverageValue; break;
1407 case GL_DEPTH_CLEAR_VALUE: *params = mState.depthClearValue; break;
1408 case GL_POLYGON_OFFSET_FACTOR: *params = mState.polygonOffsetFactor; break;
1409 case GL_POLYGON_OFFSET_UNITS: *params = mState.polygonOffsetUnits; break;
1410 case GL_ALIASED_LINE_WIDTH_RANGE:
1411 params[0] = gl::ALIASED_LINE_WIDTH_RANGE_MIN;
1412 params[1] = gl::ALIASED_LINE_WIDTH_RANGE_MAX;
1413 break;
1414 case GL_ALIASED_POINT_SIZE_RANGE:
1415 params[0] = gl::ALIASED_POINT_SIZE_RANGE_MIN;
1416 params[1] = getMaximumPointSize();
1417 break;
1418 case GL_DEPTH_RANGE:
1419 params[0] = mState.zNear;
1420 params[1] = mState.zFar;
1421 break;
1422 case GL_COLOR_CLEAR_VALUE:
1423 params[0] = mState.colorClearValue.red;
1424 params[1] = mState.colorClearValue.green;
1425 params[2] = mState.colorClearValue.blue;
1426 params[3] = mState.colorClearValue.alpha;
1427 break;
1428 case GL_BLEND_COLOR:
1429 params[0] = mState.blendColor.red;
1430 params[1] = mState.blendColor.green;
1431 params[2] = mState.blendColor.blue;
1432 params[3] = mState.blendColor.alpha;
1433 break;
daniel@transgaming.com07ab8412012-07-12 15:17:09 +00001434 case GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT:
1435 if (!supportsTextureFilterAnisotropy())
1436 {
1437 return false;
1438 }
1439 *params = mMaxTextureAnisotropy;
1440 break;
apatrick@chromium.org144f2802012-07-12 01:42:34 +00001441 default:
1442 return false;
1443 }
1444
1445 return true;
1446}
1447
1448bool Context::getIntegerv(GLenum pname, GLint *params)
1449{
1450 // Please note: DEPTH_CLEAR_VALUE is not included in our internal getIntegerv implementation
1451 // because it is stored as a float, despite the fact that the GL ES 2.0 spec names
1452 // GetIntegerv as its native query function. As it would require conversion in any
1453 // case, this should make no difference to the calling application. You may find it in
1454 // Context::getFloatv.
1455 switch (pname)
1456 {
1457 case GL_MAX_VERTEX_ATTRIBS: *params = gl::MAX_VERTEX_ATTRIBS; break;
1458 case GL_MAX_VERTEX_UNIFORM_VECTORS: *params = gl::MAX_VERTEX_UNIFORM_VECTORS; break;
1459 case GL_MAX_VARYING_VECTORS: *params = getMaximumVaryingVectors(); break;
1460 case GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS: *params = getMaximumCombinedTextureImageUnits(); break;
1461 case GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS: *params = getMaximumVertexTextureImageUnits(); break;
1462 case GL_MAX_TEXTURE_IMAGE_UNITS: *params = gl::MAX_TEXTURE_IMAGE_UNITS; break;
1463 case GL_MAX_FRAGMENT_UNIFORM_VECTORS: *params = getMaximumFragmentUniformVectors(); break;
1464 case GL_MAX_RENDERBUFFER_SIZE: *params = getMaximumRenderbufferDimension(); break;
1465 case GL_NUM_SHADER_BINARY_FORMATS: *params = 0; break;
1466 case GL_SHADER_BINARY_FORMATS: /* no shader binary formats are supported */ break;
1467 case GL_ARRAY_BUFFER_BINDING: *params = mState.arrayBuffer.id(); break;
1468 case GL_ELEMENT_ARRAY_BUFFER_BINDING: *params = mState.elementArrayBuffer.id(); break;
1469 //case GL_FRAMEBUFFER_BINDING: // now equivalent to GL_DRAW_FRAMEBUFFER_BINDING_ANGLE
1470 case GL_DRAW_FRAMEBUFFER_BINDING_ANGLE: *params = mState.drawFramebuffer; break;
1471 case GL_READ_FRAMEBUFFER_BINDING_ANGLE: *params = mState.readFramebuffer; break;
1472 case GL_RENDERBUFFER_BINDING: *params = mState.renderbuffer.id(); break;
1473 case GL_CURRENT_PROGRAM: *params = mState.currentProgram; break;
1474 case GL_PACK_ALIGNMENT: *params = mState.packAlignment; break;
1475 case GL_PACK_REVERSE_ROW_ORDER_ANGLE: *params = mState.packReverseRowOrder; break;
1476 case GL_UNPACK_ALIGNMENT: *params = mState.unpackAlignment; break;
1477 case GL_GENERATE_MIPMAP_HINT: *params = mState.generateMipmapHint; break;
1478 case GL_FRAGMENT_SHADER_DERIVATIVE_HINT_OES: *params = mState.fragmentShaderDerivativeHint; break;
1479 case GL_ACTIVE_TEXTURE: *params = (mState.activeSampler + GL_TEXTURE0); break;
1480 case GL_STENCIL_FUNC: *params = mState.stencilFunc; break;
1481 case GL_STENCIL_REF: *params = mState.stencilRef; break;
1482 case GL_STENCIL_VALUE_MASK: *params = mState.stencilMask; break;
1483 case GL_STENCIL_BACK_FUNC: *params = mState.stencilBackFunc; break;
1484 case GL_STENCIL_BACK_REF: *params = mState.stencilBackRef; break;
1485 case GL_STENCIL_BACK_VALUE_MASK: *params = mState.stencilBackMask; break;
1486 case GL_STENCIL_FAIL: *params = mState.stencilFail; break;
1487 case GL_STENCIL_PASS_DEPTH_FAIL: *params = mState.stencilPassDepthFail; break;
1488 case GL_STENCIL_PASS_DEPTH_PASS: *params = mState.stencilPassDepthPass; break;
1489 case GL_STENCIL_BACK_FAIL: *params = mState.stencilBackFail; break;
1490 case GL_STENCIL_BACK_PASS_DEPTH_FAIL: *params = mState.stencilBackPassDepthFail; break;
1491 case GL_STENCIL_BACK_PASS_DEPTH_PASS: *params = mState.stencilBackPassDepthPass; break;
1492 case GL_DEPTH_FUNC: *params = mState.depthFunc; break;
1493 case GL_BLEND_SRC_RGB: *params = mState.sourceBlendRGB; break;
1494 case GL_BLEND_SRC_ALPHA: *params = mState.sourceBlendAlpha; break;
1495 case GL_BLEND_DST_RGB: *params = mState.destBlendRGB; break;
1496 case GL_BLEND_DST_ALPHA: *params = mState.destBlendAlpha; break;
1497 case GL_BLEND_EQUATION_RGB: *params = mState.blendEquationRGB; break;
1498 case GL_BLEND_EQUATION_ALPHA: *params = mState.blendEquationAlpha; break;
1499 case GL_STENCIL_WRITEMASK: *params = mState.stencilWritemask; break;
1500 case GL_STENCIL_BACK_WRITEMASK: *params = mState.stencilBackWritemask; break;
1501 case GL_STENCIL_CLEAR_VALUE: *params = mState.stencilClearValue; break;
1502 case GL_SUBPIXEL_BITS: *params = 4; break;
1503 case GL_MAX_TEXTURE_SIZE: *params = getMaximumTextureDimension(); break;
1504 case GL_MAX_CUBE_MAP_TEXTURE_SIZE: *params = getMaximumCubeTextureDimension(); break;
1505 case GL_NUM_COMPRESSED_TEXTURE_FORMATS:
1506 params[0] = mNumCompressedTextureFormats;
1507 break;
1508 case GL_MAX_SAMPLES_ANGLE:
1509 {
1510 GLsizei maxSamples = getMaxSupportedSamples();
1511 if (maxSamples != 0)
1512 {
1513 *params = maxSamples;
1514 }
1515 else
1516 {
1517 return false;
1518 }
1519
1520 break;
1521 }
1522 case GL_SAMPLE_BUFFERS:
1523 case GL_SAMPLES:
1524 {
1525 gl::Framebuffer *framebuffer = getDrawFramebuffer();
1526 if (framebuffer->completeness() == GL_FRAMEBUFFER_COMPLETE)
1527 {
1528 switch (pname)
1529 {
1530 case GL_SAMPLE_BUFFERS:
1531 if (framebuffer->getSamples() != 0)
1532 {
1533 *params = 1;
1534 }
1535 else
1536 {
1537 *params = 0;
1538 }
1539 break;
1540 case GL_SAMPLES:
1541 *params = framebuffer->getSamples();
1542 break;
1543 }
1544 }
1545 else
1546 {
1547 *params = 0;
1548 }
1549 }
1550 break;
daniel@transgaming.com42944b02012-09-27 17:45:57 +00001551 case GL_IMPLEMENTATION_COLOR_READ_TYPE:
1552 case GL_IMPLEMENTATION_COLOR_READ_FORMAT:
1553 {
1554 GLenum format, type;
1555 if (getCurrentReadFormatType(&format, &type))
1556 {
1557 if (pname == GL_IMPLEMENTATION_COLOR_READ_FORMAT)
1558 *params = format;
1559 else
1560 *params = type;
1561 }
1562 }
1563 break;
apatrick@chromium.org144f2802012-07-12 01:42:34 +00001564 case GL_MAX_VIEWPORT_DIMS:
1565 {
1566 int maxDimension = std::max(getMaximumRenderbufferDimension(), getMaximumTextureDimension());
1567 params[0] = maxDimension;
1568 params[1] = maxDimension;
1569 }
1570 break;
1571 case GL_COMPRESSED_TEXTURE_FORMATS:
1572 {
1573 if (supportsDXT1Textures())
1574 {
1575 *params++ = GL_COMPRESSED_RGB_S3TC_DXT1_EXT;
1576 *params++ = GL_COMPRESSED_RGBA_S3TC_DXT1_EXT;
1577 }
1578 if (supportsDXT3Textures())
1579 {
1580 *params++ = GL_COMPRESSED_RGBA_S3TC_DXT3_ANGLE;
1581 }
1582 if (supportsDXT5Textures())
1583 {
1584 *params++ = GL_COMPRESSED_RGBA_S3TC_DXT5_ANGLE;
1585 }
1586 }
1587 break;
1588 case GL_VIEWPORT:
1589 params[0] = mState.viewportX;
1590 params[1] = mState.viewportY;
1591 params[2] = mState.viewportWidth;
1592 params[3] = mState.viewportHeight;
1593 break;
1594 case GL_SCISSOR_BOX:
1595 params[0] = mState.scissorX;
1596 params[1] = mState.scissorY;
1597 params[2] = mState.scissorWidth;
1598 params[3] = mState.scissorHeight;
1599 break;
1600 case GL_CULL_FACE_MODE: *params = mState.cullMode; break;
1601 case GL_FRONT_FACE: *params = mState.frontFace; break;
1602 case GL_RED_BITS:
1603 case GL_GREEN_BITS:
1604 case GL_BLUE_BITS:
1605 case GL_ALPHA_BITS:
1606 {
1607 gl::Framebuffer *framebuffer = getDrawFramebuffer();
1608 gl::Renderbuffer *colorbuffer = framebuffer->getColorbuffer();
1609
1610 if (colorbuffer)
1611 {
1612 switch (pname)
1613 {
1614 case GL_RED_BITS: *params = colorbuffer->getRedSize(); break;
1615 case GL_GREEN_BITS: *params = colorbuffer->getGreenSize(); break;
1616 case GL_BLUE_BITS: *params = colorbuffer->getBlueSize(); break;
1617 case GL_ALPHA_BITS: *params = colorbuffer->getAlphaSize(); break;
1618 }
1619 }
1620 else
1621 {
1622 *params = 0;
1623 }
1624 }
1625 break;
1626 case GL_DEPTH_BITS:
1627 {
1628 gl::Framebuffer *framebuffer = getDrawFramebuffer();
1629 gl::Renderbuffer *depthbuffer = framebuffer->getDepthbuffer();
1630
1631 if (depthbuffer)
1632 {
1633 *params = depthbuffer->getDepthSize();
1634 }
1635 else
1636 {
1637 *params = 0;
1638 }
1639 }
1640 break;
1641 case GL_STENCIL_BITS:
1642 {
1643 gl::Framebuffer *framebuffer = getDrawFramebuffer();
1644 gl::Renderbuffer *stencilbuffer = framebuffer->getStencilbuffer();
1645
1646 if (stencilbuffer)
1647 {
1648 *params = stencilbuffer->getStencilSize();
1649 }
1650 else
1651 {
1652 *params = 0;
1653 }
1654 }
1655 break;
1656 case GL_TEXTURE_BINDING_2D:
1657 {
1658 if (mState.activeSampler < 0 || mState.activeSampler > getMaximumCombinedTextureImageUnits() - 1)
1659 {
1660 error(GL_INVALID_OPERATION);
1661 return false;
1662 }
1663
1664 *params = mState.samplerTexture[TEXTURE_2D][mState.activeSampler].id();
1665 }
1666 break;
1667 case GL_TEXTURE_BINDING_CUBE_MAP:
1668 {
1669 if (mState.activeSampler < 0 || mState.activeSampler > getMaximumCombinedTextureImageUnits() - 1)
1670 {
1671 error(GL_INVALID_OPERATION);
1672 return false;
1673 }
1674
1675 *params = mState.samplerTexture[TEXTURE_CUBE][mState.activeSampler].id();
1676 }
1677 break;
1678 case GL_RESET_NOTIFICATION_STRATEGY_EXT:
1679 *params = mResetStrategy;
1680 break;
1681 case GL_NUM_PROGRAM_BINARY_FORMATS_OES:
1682 *params = 1;
1683 break;
1684 case GL_PROGRAM_BINARY_FORMATS_OES:
1685 *params = GL_PROGRAM_BINARY_ANGLE;
1686 break;
1687 default:
1688 return false;
1689 }
1690
1691 return true;
1692}
1693
1694bool Context::getQueryParameterInfo(GLenum pname, GLenum *type, unsigned int *numParams)
1695{
1696 // Please note: the query type returned for DEPTH_CLEAR_VALUE in this implementation
1697 // is FLOAT rather than INT, as would be suggested by the GL ES 2.0 spec. This is due
1698 // to the fact that it is stored internally as a float, and so would require conversion
1699 // if returned from Context::getIntegerv. Since this conversion is already implemented
1700 // in the case that one calls glGetIntegerv to retrieve a float-typed state variable, we
1701 // place DEPTH_CLEAR_VALUE with the floats. This should make no difference to the calling
1702 // application.
1703 switch (pname)
1704 {
1705 case GL_COMPRESSED_TEXTURE_FORMATS:
1706 {
1707 *type = GL_INT;
1708 *numParams = mNumCompressedTextureFormats;
1709 }
1710 break;
1711 case GL_SHADER_BINARY_FORMATS:
1712 {
1713 *type = GL_INT;
1714 *numParams = 0;
1715 }
1716 break;
1717 case GL_MAX_VERTEX_ATTRIBS:
1718 case GL_MAX_VERTEX_UNIFORM_VECTORS:
1719 case GL_MAX_VARYING_VECTORS:
1720 case GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS:
1721 case GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS:
1722 case GL_MAX_TEXTURE_IMAGE_UNITS:
1723 case GL_MAX_FRAGMENT_UNIFORM_VECTORS:
1724 case GL_MAX_RENDERBUFFER_SIZE:
1725 case GL_NUM_SHADER_BINARY_FORMATS:
1726 case GL_NUM_COMPRESSED_TEXTURE_FORMATS:
1727 case GL_ARRAY_BUFFER_BINDING:
1728 case GL_FRAMEBUFFER_BINDING:
1729 case GL_RENDERBUFFER_BINDING:
1730 case GL_CURRENT_PROGRAM:
1731 case GL_PACK_ALIGNMENT:
1732 case GL_PACK_REVERSE_ROW_ORDER_ANGLE:
1733 case GL_UNPACK_ALIGNMENT:
1734 case GL_GENERATE_MIPMAP_HINT:
1735 case GL_FRAGMENT_SHADER_DERIVATIVE_HINT_OES:
1736 case GL_RED_BITS:
1737 case GL_GREEN_BITS:
1738 case GL_BLUE_BITS:
1739 case GL_ALPHA_BITS:
1740 case GL_DEPTH_BITS:
1741 case GL_STENCIL_BITS:
1742 case GL_ELEMENT_ARRAY_BUFFER_BINDING:
1743 case GL_CULL_FACE_MODE:
1744 case GL_FRONT_FACE:
1745 case GL_ACTIVE_TEXTURE:
1746 case GL_STENCIL_FUNC:
1747 case GL_STENCIL_VALUE_MASK:
1748 case GL_STENCIL_REF:
1749 case GL_STENCIL_FAIL:
1750 case GL_STENCIL_PASS_DEPTH_FAIL:
1751 case GL_STENCIL_PASS_DEPTH_PASS:
1752 case GL_STENCIL_BACK_FUNC:
1753 case GL_STENCIL_BACK_VALUE_MASK:
1754 case GL_STENCIL_BACK_REF:
1755 case GL_STENCIL_BACK_FAIL:
1756 case GL_STENCIL_BACK_PASS_DEPTH_FAIL:
1757 case GL_STENCIL_BACK_PASS_DEPTH_PASS:
1758 case GL_DEPTH_FUNC:
1759 case GL_BLEND_SRC_RGB:
1760 case GL_BLEND_SRC_ALPHA:
1761 case GL_BLEND_DST_RGB:
1762 case GL_BLEND_DST_ALPHA:
1763 case GL_BLEND_EQUATION_RGB:
1764 case GL_BLEND_EQUATION_ALPHA:
1765 case GL_STENCIL_WRITEMASK:
1766 case GL_STENCIL_BACK_WRITEMASK:
1767 case GL_STENCIL_CLEAR_VALUE:
1768 case GL_SUBPIXEL_BITS:
1769 case GL_MAX_TEXTURE_SIZE:
1770 case GL_MAX_CUBE_MAP_TEXTURE_SIZE:
1771 case GL_SAMPLE_BUFFERS:
1772 case GL_SAMPLES:
1773 case GL_IMPLEMENTATION_COLOR_READ_TYPE:
1774 case GL_IMPLEMENTATION_COLOR_READ_FORMAT:
1775 case GL_TEXTURE_BINDING_2D:
1776 case GL_TEXTURE_BINDING_CUBE_MAP:
1777 case GL_RESET_NOTIFICATION_STRATEGY_EXT:
1778 case GL_NUM_PROGRAM_BINARY_FORMATS_OES:
1779 case GL_PROGRAM_BINARY_FORMATS_OES:
1780 {
1781 *type = GL_INT;
1782 *numParams = 1;
1783 }
1784 break;
1785 case GL_MAX_SAMPLES_ANGLE:
1786 {
1787 if (getMaxSupportedSamples() != 0)
1788 {
1789 *type = GL_INT;
1790 *numParams = 1;
1791 }
1792 else
1793 {
1794 return false;
1795 }
1796 }
1797 break;
1798 case GL_MAX_VIEWPORT_DIMS:
1799 {
1800 *type = GL_INT;
1801 *numParams = 2;
1802 }
1803 break;
1804 case GL_VIEWPORT:
1805 case GL_SCISSOR_BOX:
1806 {
1807 *type = GL_INT;
1808 *numParams = 4;
1809 }
1810 break;
1811 case GL_SHADER_COMPILER:
1812 case GL_SAMPLE_COVERAGE_INVERT:
1813 case GL_DEPTH_WRITEMASK:
1814 case GL_CULL_FACE: // CULL_FACE through DITHER are natural to IsEnabled,
1815 case GL_POLYGON_OFFSET_FILL: // but can be retrieved through the Get{Type}v queries.
1816 case GL_SAMPLE_ALPHA_TO_COVERAGE: // For this purpose, they are treated here as bool-natural
1817 case GL_SAMPLE_COVERAGE:
1818 case GL_SCISSOR_TEST:
1819 case GL_STENCIL_TEST:
1820 case GL_DEPTH_TEST:
1821 case GL_BLEND:
1822 case GL_DITHER:
1823 case GL_CONTEXT_ROBUST_ACCESS_EXT:
1824 {
1825 *type = GL_BOOL;
1826 *numParams = 1;
1827 }
1828 break;
1829 case GL_COLOR_WRITEMASK:
1830 {
1831 *type = GL_BOOL;
1832 *numParams = 4;
1833 }
1834 break;
1835 case GL_POLYGON_OFFSET_FACTOR:
1836 case GL_POLYGON_OFFSET_UNITS:
1837 case GL_SAMPLE_COVERAGE_VALUE:
1838 case GL_DEPTH_CLEAR_VALUE:
1839 case GL_LINE_WIDTH:
1840 {
1841 *type = GL_FLOAT;
1842 *numParams = 1;
1843 }
1844 break;
1845 case GL_ALIASED_LINE_WIDTH_RANGE:
1846 case GL_ALIASED_POINT_SIZE_RANGE:
1847 case GL_DEPTH_RANGE:
1848 {
1849 *type = GL_FLOAT;
1850 *numParams = 2;
1851 }
1852 break;
1853 case GL_COLOR_CLEAR_VALUE:
1854 case GL_BLEND_COLOR:
1855 {
1856 *type = GL_FLOAT;
1857 *numParams = 4;
1858 }
1859 break;
daniel@transgaming.com07ab8412012-07-12 15:17:09 +00001860 case GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT:
1861 if (!supportsTextureFilterAnisotropy())
1862 {
1863 return false;
1864 }
1865 *type = GL_FLOAT;
1866 *numParams = 1;
1867 break;
apatrick@chromium.org144f2802012-07-12 01:42:34 +00001868 default:
1869 return false;
1870 }
1871
1872 return true;
1873}
1874
1875// Applies the render target surface, depth stencil surface, viewport rectangle and
1876// scissor rectangle to the Direct3D 9 device
1877bool Context::applyRenderTarget(bool ignoreViewport)
1878{
1879 Framebuffer *framebufferObject = getDrawFramebuffer();
1880
1881 if (!framebufferObject || framebufferObject->completeness() != GL_FRAMEBUFFER_COMPLETE)
1882 {
1883 return error(GL_INVALID_FRAMEBUFFER_OPERATION, false);
1884 }
1885
1886 // if there is no color attachment we must synthesize a NULL colorattachment
1887 // to keep the D3D runtime happy. This should only be possible if depth texturing.
1888 Renderbuffer *renderbufferObject = NULL;
1889 if (framebufferObject->getColorbufferType() != GL_NONE)
1890 {
1891 renderbufferObject = framebufferObject->getColorbuffer();
1892 }
1893 else
1894 {
1895 renderbufferObject = framebufferObject->getNullColorbuffer();
1896 }
1897 if (!renderbufferObject)
1898 {
1899 ERR("unable to locate renderbuffer for FBO.");
1900 return false;
1901 }
1902
1903 bool renderTargetChanged = false;
1904 unsigned int renderTargetSerial = renderbufferObject->getSerial();
1905 if (renderTargetSerial != mAppliedRenderTargetSerial)
1906 {
1907 IDirect3DSurface9 *renderTarget = renderbufferObject->getRenderTarget();
1908 if (!renderTarget)
1909 {
1910 ERR("render target pointer unexpectedly null.");
1911 return false; // Context must be lost
1912 }
1913 mDevice->SetRenderTarget(0, renderTarget);
1914 mAppliedRenderTargetSerial = renderTargetSerial;
1915 mScissorStateDirty = true; // Scissor area must be clamped to render target's size-- this is different for different render targets.
1916 renderTargetChanged = true;
1917 renderTarget->Release();
1918 }
1919
1920 IDirect3DSurface9 *depthStencil = NULL;
1921 unsigned int depthbufferSerial = 0;
1922 unsigned int stencilbufferSerial = 0;
1923 if (framebufferObject->getDepthbufferType() != GL_NONE)
1924 {
1925 Renderbuffer *depthbuffer = framebufferObject->getDepthbuffer();
1926 depthStencil = depthbuffer->getDepthStencil();
1927 if (!depthStencil)
1928 {
1929 ERR("Depth stencil pointer unexpectedly null.");
1930 return false;
1931 }
1932
1933 depthbufferSerial = depthbuffer->getSerial();
1934 }
1935 else if (framebufferObject->getStencilbufferType() != GL_NONE)
1936 {
1937 Renderbuffer *stencilbuffer = framebufferObject->getStencilbuffer();
1938 depthStencil = stencilbuffer->getDepthStencil();
1939 if (!depthStencil)
1940 {
1941 ERR("Depth stencil pointer unexpectedly null.");
1942 return false;
1943 }
1944
1945 stencilbufferSerial = stencilbuffer->getSerial();
1946 }
1947
1948 if (depthbufferSerial != mAppliedDepthbufferSerial ||
1949 stencilbufferSerial != mAppliedStencilbufferSerial ||
1950 !mDepthStencilInitialized)
1951 {
1952 mDevice->SetDepthStencilSurface(depthStencil);
1953 mAppliedDepthbufferSerial = depthbufferSerial;
1954 mAppliedStencilbufferSerial = stencilbufferSerial;
1955 mDepthStencilInitialized = true;
1956 }
1957
1958 if (depthStencil)
1959 {
1960 depthStencil->Release();
1961 }
1962
1963 if (!mRenderTargetDescInitialized || renderTargetChanged)
1964 {
1965 IDirect3DSurface9 *renderTarget = renderbufferObject->getRenderTarget();
1966 if (!renderTarget)
1967 {
1968 return false; // Context must be lost
1969 }
1970 renderTarget->GetDesc(&mRenderTargetDesc);
1971 mRenderTargetDescInitialized = true;
1972 renderTarget->Release();
1973 }
1974
1975 D3DVIEWPORT9 viewport;
1976
1977 float zNear = clamp01(mState.zNear);
1978 float zFar = clamp01(mState.zFar);
1979
1980 if (ignoreViewport)
1981 {
1982 viewport.X = 0;
1983 viewport.Y = 0;
1984 viewport.Width = mRenderTargetDesc.Width;
1985 viewport.Height = mRenderTargetDesc.Height;
1986 viewport.MinZ = 0.0f;
1987 viewport.MaxZ = 1.0f;
1988 }
1989 else
1990 {
1991 viewport.X = clamp(mState.viewportX, 0L, static_cast<LONG>(mRenderTargetDesc.Width));
1992 viewport.Y = clamp(mState.viewportY, 0L, static_cast<LONG>(mRenderTargetDesc.Height));
1993 viewport.Width = clamp(mState.viewportWidth, 0L, static_cast<LONG>(mRenderTargetDesc.Width) - static_cast<LONG>(viewport.X));
1994 viewport.Height = clamp(mState.viewportHeight, 0L, static_cast<LONG>(mRenderTargetDesc.Height) - static_cast<LONG>(viewport.Y));
1995 viewport.MinZ = zNear;
1996 viewport.MaxZ = zFar;
1997 }
1998
1999 if (viewport.Width <= 0 || viewport.Height <= 0)
2000 {
2001 return false; // Nothing to render
2002 }
2003
2004 if (renderTargetChanged || !mViewportInitialized || memcmp(&viewport, &mSetViewport, sizeof mSetViewport) != 0)
2005 {
2006 mDevice->SetViewport(&viewport);
2007 mSetViewport = viewport;
2008 mViewportInitialized = true;
2009 mDxUniformsDirty = true;
2010 }
2011
2012 if (mScissorStateDirty)
2013 {
2014 if (mState.scissorTest)
2015 {
2016 RECT rect;
2017 rect.left = clamp(mState.scissorX, 0L, static_cast<LONG>(mRenderTargetDesc.Width));
2018 rect.top = clamp(mState.scissorY, 0L, static_cast<LONG>(mRenderTargetDesc.Height));
2019 rect.right = clamp(mState.scissorX + mState.scissorWidth, 0L, static_cast<LONG>(mRenderTargetDesc.Width));
2020 rect.bottom = clamp(mState.scissorY + mState.scissorHeight, 0L, static_cast<LONG>(mRenderTargetDesc.Height));
2021 mDevice->SetScissorRect(&rect);
2022 mDevice->SetRenderState(D3DRS_SCISSORTESTENABLE, TRUE);
2023 }
2024 else
2025 {
2026 mDevice->SetRenderState(D3DRS_SCISSORTESTENABLE, FALSE);
2027 }
2028
2029 mScissorStateDirty = false;
2030 }
2031
2032 if (mState.currentProgram && mDxUniformsDirty)
2033 {
daniel@transgaming.com62a28462012-07-24 18:33:59 +00002034 ProgramBinary *programBinary = getCurrentProgramBinary();
apatrick@chromium.org144f2802012-07-12 01:42:34 +00002035
2036 GLint halfPixelSize = programBinary->getDxHalfPixelSizeLocation();
2037 GLfloat xy[2] = {1.0f / viewport.Width, -1.0f / viewport.Height};
2038 programBinary->setUniform2fv(halfPixelSize, 1, xy);
2039
2040 // These values are used for computing gl_FragCoord in Program::linkVaryings().
2041 GLint coord = programBinary->getDxCoordLocation();
2042 GLfloat whxy[4] = {mState.viewportWidth / 2.0f, mState.viewportHeight / 2.0f,
2043 (float)mState.viewportX + mState.viewportWidth / 2.0f,
2044 (float)mState.viewportY + mState.viewportHeight / 2.0f};
2045 programBinary->setUniform4fv(coord, 1, whxy);
2046
2047 GLint depth = programBinary->getDxDepthLocation();
2048 GLfloat dz[2] = {(zFar - zNear) / 2.0f, (zNear + zFar) / 2.0f};
2049 programBinary->setUniform2fv(depth, 1, dz);
2050
2051 GLint depthRange = programBinary->getDxDepthRangeLocation();
2052 GLfloat nearFarDiff[3] = {zNear, zFar, zFar - zNear};
2053 programBinary->setUniform3fv(depthRange, 1, nearFarDiff);
2054 mDxUniformsDirty = false;
2055 }
2056
2057 return true;
2058}
2059
2060// Applies the fixed-function state (culling, depth test, alpha blending, stenciling, etc) to the Direct3D 9 device
2061void Context::applyState(GLenum drawMode)
2062{
daniel@transgaming.com62a28462012-07-24 18:33:59 +00002063 ProgramBinary *programBinary = getCurrentProgramBinary();
apatrick@chromium.org144f2802012-07-12 01:42:34 +00002064
2065 Framebuffer *framebufferObject = getDrawFramebuffer();
2066
2067 GLint frontCCW = programBinary->getDxFrontCCWLocation();
2068 GLint ccw = (mState.frontFace == GL_CCW);
2069 programBinary->setUniform1iv(frontCCW, 1, &ccw);
2070
2071 GLint pointsOrLines = programBinary->getDxPointsOrLinesLocation();
2072 GLint alwaysFront = !isTriangleMode(drawMode);
2073 programBinary->setUniform1iv(pointsOrLines, 1, &alwaysFront);
2074
daniel@transgaming.com4ca789e2012-10-31 18:46:40 +00002075 bool zeroColorMaskAllowed = mRenderer->getAdapterVendor() != VENDOR_ID_AMD;
apatrick@chromium.org144f2802012-07-12 01:42:34 +00002076 // Apparently some ATI cards have a bug where a draw with a zero color
2077 // write mask can cause later draws to have incorrect results. Instead,
2078 // set a nonzero color write mask but modify the blend state so that no
2079 // drawing is done.
2080 // http://code.google.com/p/angleproject/issues/detail?id=169
2081
2082 if (mCullStateDirty || mFrontFaceDirty)
2083 {
2084 if (mState.cullFace)
2085 {
2086 mDevice->SetRenderState(D3DRS_CULLMODE, es2dx::ConvertCullMode(mState.cullMode, mState.frontFace));
2087 }
2088 else
2089 {
2090 mDevice->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE);
2091 }
2092
2093 mCullStateDirty = false;
2094 }
2095
2096 if (mDepthStateDirty)
2097 {
2098 if (mState.depthTest)
2099 {
2100 mDevice->SetRenderState(D3DRS_ZENABLE, D3DZB_TRUE);
2101 mDevice->SetRenderState(D3DRS_ZFUNC, es2dx::ConvertComparison(mState.depthFunc));
2102 }
2103 else
2104 {
2105 mDevice->SetRenderState(D3DRS_ZENABLE, D3DZB_FALSE);
2106 }
2107
2108 mDepthStateDirty = false;
2109 }
2110
2111 if (!zeroColorMaskAllowed && (mMaskStateDirty || mBlendStateDirty))
2112 {
2113 mBlendStateDirty = true;
2114 mMaskStateDirty = true;
2115 }
2116
2117 if (mBlendStateDirty)
2118 {
2119 if (mState.blend)
2120 {
2121 mDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, TRUE);
2122
2123 if (mState.sourceBlendRGB != GL_CONSTANT_ALPHA && mState.sourceBlendRGB != GL_ONE_MINUS_CONSTANT_ALPHA &&
2124 mState.destBlendRGB != GL_CONSTANT_ALPHA && mState.destBlendRGB != GL_ONE_MINUS_CONSTANT_ALPHA)
2125 {
2126 mDevice->SetRenderState(D3DRS_BLENDFACTOR, es2dx::ConvertColor(mState.blendColor));
2127 }
2128 else
2129 {
2130 mDevice->SetRenderState(D3DRS_BLENDFACTOR, D3DCOLOR_RGBA(unorm<8>(mState.blendColor.alpha),
2131 unorm<8>(mState.blendColor.alpha),
2132 unorm<8>(mState.blendColor.alpha),
2133 unorm<8>(mState.blendColor.alpha)));
2134 }
2135
2136 mDevice->SetRenderState(D3DRS_SRCBLEND, es2dx::ConvertBlendFunc(mState.sourceBlendRGB));
2137 mDevice->SetRenderState(D3DRS_DESTBLEND, es2dx::ConvertBlendFunc(mState.destBlendRGB));
2138 mDevice->SetRenderState(D3DRS_BLENDOP, es2dx::ConvertBlendOp(mState.blendEquationRGB));
2139
2140 if (mState.sourceBlendRGB != mState.sourceBlendAlpha ||
2141 mState.destBlendRGB != mState.destBlendAlpha ||
2142 mState.blendEquationRGB != mState.blendEquationAlpha)
2143 {
2144 mDevice->SetRenderState(D3DRS_SEPARATEALPHABLENDENABLE, TRUE);
2145
2146 mDevice->SetRenderState(D3DRS_SRCBLENDALPHA, es2dx::ConvertBlendFunc(mState.sourceBlendAlpha));
2147 mDevice->SetRenderState(D3DRS_DESTBLENDALPHA, es2dx::ConvertBlendFunc(mState.destBlendAlpha));
2148 mDevice->SetRenderState(D3DRS_BLENDOPALPHA, es2dx::ConvertBlendOp(mState.blendEquationAlpha));
2149 }
2150 else
2151 {
2152 mDevice->SetRenderState(D3DRS_SEPARATEALPHABLENDENABLE, FALSE);
2153 }
2154 }
2155 else
2156 {
2157 mDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, FALSE);
2158 }
2159
2160 mBlendStateDirty = false;
2161 }
2162
2163 if (mStencilStateDirty || mFrontFaceDirty)
2164 {
2165 if (mState.stencilTest && framebufferObject->hasStencil())
2166 {
2167 mDevice->SetRenderState(D3DRS_STENCILENABLE, TRUE);
2168 mDevice->SetRenderState(D3DRS_TWOSIDEDSTENCILMODE, TRUE);
2169
2170 // FIXME: Unsupported by D3D9
2171 const D3DRENDERSTATETYPE D3DRS_CCW_STENCILREF = D3DRS_STENCILREF;
2172 const D3DRENDERSTATETYPE D3DRS_CCW_STENCILMASK = D3DRS_STENCILMASK;
2173 const D3DRENDERSTATETYPE D3DRS_CCW_STENCILWRITEMASK = D3DRS_STENCILWRITEMASK;
2174 if (mState.stencilWritemask != mState.stencilBackWritemask ||
2175 mState.stencilRef != mState.stencilBackRef ||
2176 mState.stencilMask != mState.stencilBackMask)
2177 {
2178 ERR("Separate front/back stencil writemasks, reference values, or stencil mask values are invalid under WebGL.");
2179 return error(GL_INVALID_OPERATION);
2180 }
2181
2182 // get the maximum size of the stencil ref
2183 gl::Renderbuffer *stencilbuffer = framebufferObject->getStencilbuffer();
2184 GLuint maxStencil = (1 << stencilbuffer->getStencilSize()) - 1;
2185
2186 mDevice->SetRenderState(mState.frontFace == GL_CCW ? D3DRS_STENCILWRITEMASK : D3DRS_CCW_STENCILWRITEMASK, mState.stencilWritemask);
2187 mDevice->SetRenderState(mState.frontFace == GL_CCW ? D3DRS_STENCILFUNC : D3DRS_CCW_STENCILFUNC,
2188 es2dx::ConvertComparison(mState.stencilFunc));
2189
2190 mDevice->SetRenderState(mState.frontFace == GL_CCW ? D3DRS_STENCILREF : D3DRS_CCW_STENCILREF, (mState.stencilRef < (GLint)maxStencil) ? mState.stencilRef : maxStencil);
2191 mDevice->SetRenderState(mState.frontFace == GL_CCW ? D3DRS_STENCILMASK : D3DRS_CCW_STENCILMASK, mState.stencilMask);
2192
2193 mDevice->SetRenderState(mState.frontFace == GL_CCW ? D3DRS_STENCILFAIL : D3DRS_CCW_STENCILFAIL,
2194 es2dx::ConvertStencilOp(mState.stencilFail));
2195 mDevice->SetRenderState(mState.frontFace == GL_CCW ? D3DRS_STENCILZFAIL : D3DRS_CCW_STENCILZFAIL,
2196 es2dx::ConvertStencilOp(mState.stencilPassDepthFail));
2197 mDevice->SetRenderState(mState.frontFace == GL_CCW ? D3DRS_STENCILPASS : D3DRS_CCW_STENCILPASS,
2198 es2dx::ConvertStencilOp(mState.stencilPassDepthPass));
2199
2200 mDevice->SetRenderState(mState.frontFace == GL_CW ? D3DRS_STENCILWRITEMASK : D3DRS_CCW_STENCILWRITEMASK, mState.stencilBackWritemask);
2201 mDevice->SetRenderState(mState.frontFace == GL_CW ? D3DRS_STENCILFUNC : D3DRS_CCW_STENCILFUNC,
2202 es2dx::ConvertComparison(mState.stencilBackFunc));
2203
2204 mDevice->SetRenderState(mState.frontFace == GL_CW ? D3DRS_STENCILREF : D3DRS_CCW_STENCILREF, (mState.stencilBackRef < (GLint)maxStencil) ? mState.stencilBackRef : maxStencil);
2205 mDevice->SetRenderState(mState.frontFace == GL_CW ? D3DRS_STENCILMASK : D3DRS_CCW_STENCILMASK, mState.stencilBackMask);
2206
2207 mDevice->SetRenderState(mState.frontFace == GL_CW ? D3DRS_STENCILFAIL : D3DRS_CCW_STENCILFAIL,
2208 es2dx::ConvertStencilOp(mState.stencilBackFail));
2209 mDevice->SetRenderState(mState.frontFace == GL_CW ? D3DRS_STENCILZFAIL : D3DRS_CCW_STENCILZFAIL,
2210 es2dx::ConvertStencilOp(mState.stencilBackPassDepthFail));
2211 mDevice->SetRenderState(mState.frontFace == GL_CW ? D3DRS_STENCILPASS : D3DRS_CCW_STENCILPASS,
2212 es2dx::ConvertStencilOp(mState.stencilBackPassDepthPass));
2213 }
2214 else
2215 {
2216 mDevice->SetRenderState(D3DRS_STENCILENABLE, FALSE);
2217 }
2218
2219 mStencilStateDirty = false;
2220 mFrontFaceDirty = false;
2221 }
2222
2223 if (mMaskStateDirty)
2224 {
2225 int colorMask = es2dx::ConvertColorMask(mState.colorMaskRed, mState.colorMaskGreen,
2226 mState.colorMaskBlue, mState.colorMaskAlpha);
2227 if (colorMask == 0 && !zeroColorMaskAllowed)
2228 {
2229 // Enable green channel, but set blending so nothing will be drawn.
2230 mDevice->SetRenderState(D3DRS_COLORWRITEENABLE, D3DCOLORWRITEENABLE_GREEN);
2231 mDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, TRUE);
2232
2233 mDevice->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_ZERO);
2234 mDevice->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_ONE);
2235 mDevice->SetRenderState(D3DRS_BLENDOP, D3DBLENDOP_ADD);
2236 }
2237 else
2238 {
2239 mDevice->SetRenderState(D3DRS_COLORWRITEENABLE, colorMask);
2240 }
2241 mDevice->SetRenderState(D3DRS_ZWRITEENABLE, mState.depthMask ? TRUE : FALSE);
2242
2243 mMaskStateDirty = false;
2244 }
2245
2246 if (mPolygonOffsetStateDirty)
2247 {
2248 if (mState.polygonOffsetFill)
2249 {
2250 gl::Renderbuffer *depthbuffer = framebufferObject->getDepthbuffer();
2251 if (depthbuffer)
2252 {
2253 mDevice->SetRenderState(D3DRS_SLOPESCALEDEPTHBIAS, *((DWORD*)&mState.polygonOffsetFactor));
2254 float depthBias = ldexp(mState.polygonOffsetUnits, -(int)(depthbuffer->getDepthSize()));
2255 mDevice->SetRenderState(D3DRS_DEPTHBIAS, *((DWORD*)&depthBias));
2256 }
2257 }
2258 else
2259 {
2260 mDevice->SetRenderState(D3DRS_SLOPESCALEDEPTHBIAS, 0);
2261 mDevice->SetRenderState(D3DRS_DEPTHBIAS, 0);
2262 }
2263
2264 mPolygonOffsetStateDirty = false;
2265 }
2266
2267 if (mSampleStateDirty)
2268 {
2269 if (mState.sampleAlphaToCoverage)
2270 {
2271 FIXME("Sample alpha to coverage is unimplemented.");
2272 }
2273
2274 mDevice->SetRenderState(D3DRS_MULTISAMPLEANTIALIAS, TRUE);
2275 if (mState.sampleCoverage)
2276 {
2277 unsigned int mask = 0;
2278 if (mState.sampleCoverageValue != 0)
2279 {
2280 float threshold = 0.5f;
2281
2282 for (int i = 0; i < framebufferObject->getSamples(); ++i)
2283 {
2284 mask <<= 1;
2285
2286 if ((i + 1) * mState.sampleCoverageValue >= threshold)
2287 {
2288 threshold += 1.0f;
2289 mask |= 1;
2290 }
2291 }
2292 }
2293
2294 if (mState.sampleCoverageInvert)
2295 {
2296 mask = ~mask;
2297 }
2298
2299 mDevice->SetRenderState(D3DRS_MULTISAMPLEMASK, mask);
2300 }
2301 else
2302 {
2303 mDevice->SetRenderState(D3DRS_MULTISAMPLEMASK, 0xFFFFFFFF);
2304 }
2305
2306 mSampleStateDirty = false;
2307 }
2308
2309 if (mDitherStateDirty)
2310 {
2311 mDevice->SetRenderState(D3DRS_DITHERENABLE, mState.dither ? TRUE : FALSE);
2312
2313 mDitherStateDirty = false;
2314 }
2315}
2316
2317GLenum Context::applyVertexBuffer(GLint first, GLsizei count, GLsizei instances, GLsizei *repeatDraw)
2318{
2319 TranslatedAttribute attributes[MAX_VERTEX_ATTRIBS];
2320
daniel@transgaming.com408caa52012-10-31 18:47:01 +00002321 ProgramBinary *programBinary = getCurrentProgramBinary();
2322 GLenum err = mVertexDataManager->prepareVertexData(mState.vertexAttribute, programBinary, first, count, attributes, instances);
apatrick@chromium.org144f2802012-07-12 01:42:34 +00002323 if (err != GL_NO_ERROR)
2324 {
2325 return err;
2326 }
daniel@transgaming.com408caa52012-10-31 18:47:01 +00002327
daniel@transgaming.com5ae3ccc2012-07-24 18:29:38 +00002328 return mVertexDeclarationCache.applyDeclaration(mDevice, attributes, programBinary, instances, repeatDraw);
apatrick@chromium.org144f2802012-07-12 01:42:34 +00002329}
2330
2331// Applies the indices and element array bindings to the Direct3D 9 device
2332GLenum Context::applyIndexBuffer(const GLvoid *indices, GLsizei count, GLenum mode, GLenum type, TranslatedIndexData *indexInfo)
2333{
2334 GLenum err = mIndexDataManager->prepareIndexData(type, count, mState.elementArrayBuffer.get(), indices, indexInfo);
2335
2336 if (err == GL_NO_ERROR)
2337 {
2338 if (indexInfo->serial != mAppliedIBSerial)
2339 {
2340 mDevice->SetIndices(indexInfo->indexBuffer);
2341 mAppliedIBSerial = indexInfo->serial;
2342 }
2343 }
2344
2345 return err;
2346}
2347
2348// Applies the shaders and shader constants to the Direct3D 9 device
2349void Context::applyShaders()
2350{
daniel@transgaming.com62a28462012-07-24 18:33:59 +00002351 ProgramBinary *programBinary = getCurrentProgramBinary();
apatrick@chromium.org144f2802012-07-12 01:42:34 +00002352
daniel@transgaming.come6af4f92012-07-24 18:31:31 +00002353 if (programBinary->getSerial() != mAppliedProgramBinarySerial)
apatrick@chromium.org144f2802012-07-12 01:42:34 +00002354 {
2355 IDirect3DVertexShader9 *vertexShader = programBinary->getVertexShader();
2356 IDirect3DPixelShader9 *pixelShader = programBinary->getPixelShader();
2357
2358 mDevice->SetPixelShader(pixelShader);
2359 mDevice->SetVertexShader(vertexShader);
2360 programBinary->dirtyAllUniforms();
daniel@transgaming.come6af4f92012-07-24 18:31:31 +00002361 mAppliedProgramBinarySerial = programBinary->getSerial();
apatrick@chromium.org144f2802012-07-12 01:42:34 +00002362 }
2363
2364 programBinary->applyUniforms();
2365}
2366
2367// Applies the textures and sampler states to the Direct3D 9 device
2368void Context::applyTextures()
2369{
2370 applyTextures(SAMPLER_PIXEL);
2371
2372 if (mSupportsVertexTexture)
2373 {
2374 applyTextures(SAMPLER_VERTEX);
2375 }
2376}
2377
2378// For each Direct3D 9 sampler of either the pixel or vertex stage,
2379// looks up the corresponding OpenGL texture image unit and texture type,
2380// and sets the texture and its addressing/filtering state (or NULL when inactive).
2381void Context::applyTextures(SamplerType type)
2382{
daniel@transgaming.com62a28462012-07-24 18:33:59 +00002383 ProgramBinary *programBinary = getCurrentProgramBinary();
apatrick@chromium.org144f2802012-07-12 01:42:34 +00002384
2385 int samplerCount = (type == SAMPLER_PIXEL) ? MAX_TEXTURE_IMAGE_UNITS : MAX_VERTEX_TEXTURE_IMAGE_UNITS_VTF; // Range of Direct3D 9 samplers of given sampler type
2386 unsigned int *appliedTextureSerial = (type == SAMPLER_PIXEL) ? mAppliedTextureSerialPS : mAppliedTextureSerialVS;
apatrick@chromium.org144f2802012-07-12 01:42:34 +00002387 int samplerRange = programBinary->getUsedSamplerRange(type);
2388
2389 for (int samplerIndex = 0; samplerIndex < samplerRange; samplerIndex++)
2390 {
2391 int textureUnit = programBinary->getSamplerMapping(type, samplerIndex); // OpenGL texture image unit index
apatrick@chromium.org144f2802012-07-12 01:42:34 +00002392
2393 if (textureUnit != -1)
2394 {
2395 TextureType textureType = programBinary->getSamplerTextureType(type, samplerIndex);
2396
2397 Texture *texture = getSamplerTexture(textureUnit, textureType);
2398 unsigned int texSerial = texture->getTextureSerial();
2399
2400 if (appliedTextureSerial[samplerIndex] != texSerial || texture->hasDirtyParameters() || texture->hasDirtyImages())
2401 {
daniel@transgaming.coma734f272012-10-31 18:07:48 +00002402 if (texture->isSamplerComplete())
apatrick@chromium.org144f2802012-07-12 01:42:34 +00002403 {
2404 if (appliedTextureSerial[samplerIndex] != texSerial || texture->hasDirtyParameters())
2405 {
daniel@transgaming.comebf139f2012-10-31 18:07:32 +00002406 SamplerState samplerState;
2407 texture->getSamplerState(&samplerState);
apatrick@chromium.org144f2802012-07-12 01:42:34 +00002408
daniel@transgaming.comba0570e2012-10-31 18:07:39 +00002409 mRenderer->setSamplerState(type, samplerIndex, samplerState);
apatrick@chromium.org144f2802012-07-12 01:42:34 +00002410 }
2411
2412 if (appliedTextureSerial[samplerIndex] != texSerial || texture->hasDirtyImages())
2413 {
daniel@transgaming.coma734f272012-10-31 18:07:48 +00002414 mRenderer->setTexture(type, samplerIndex, texture);
apatrick@chromium.org144f2802012-07-12 01:42:34 +00002415 }
2416 }
2417 else
2418 {
daniel@transgaming.coma734f272012-10-31 18:07:48 +00002419 mRenderer->setTexture(type, samplerIndex, getIncompleteTexture(textureType));
apatrick@chromium.org144f2802012-07-12 01:42:34 +00002420 }
2421
2422 appliedTextureSerial[samplerIndex] = texSerial;
2423 texture->resetDirty();
2424 }
2425 }
2426 else
2427 {
2428 if (appliedTextureSerial[samplerIndex] != 0)
2429 {
daniel@transgaming.coma734f272012-10-31 18:07:48 +00002430 mRenderer->setTexture(type, samplerIndex, NULL);
apatrick@chromium.org144f2802012-07-12 01:42:34 +00002431 appliedTextureSerial[samplerIndex] = 0;
2432 }
2433 }
2434 }
2435
2436 for (int samplerIndex = samplerRange; samplerIndex < samplerCount; samplerIndex++)
2437 {
2438 if (appliedTextureSerial[samplerIndex] != 0)
2439 {
daniel@transgaming.coma734f272012-10-31 18:07:48 +00002440 mRenderer->setTexture(type, samplerIndex, NULL);
apatrick@chromium.org144f2802012-07-12 01:42:34 +00002441 appliedTextureSerial[samplerIndex] = 0;
2442 }
2443 }
2444}
2445
2446void Context::readPixels(GLint x, GLint y, GLsizei width, GLsizei height,
2447 GLenum format, GLenum type, GLsizei *bufSize, void* pixels)
2448{
2449 Framebuffer *framebuffer = getReadFramebuffer();
2450
2451 if (framebuffer->completeness() != GL_FRAMEBUFFER_COMPLETE)
2452 {
2453 return error(GL_INVALID_FRAMEBUFFER_OPERATION);
2454 }
2455
2456 if (getReadFramebufferHandle() != 0 && framebuffer->getSamples() != 0)
2457 {
2458 return error(GL_INVALID_OPERATION);
2459 }
2460
daniel@transgaming.com6452adf2012-10-17 18:22:35 +00002461 GLsizei outputPitch = ComputePitch(width, ConvertSizedInternalFormat(format, type), mState.packAlignment);
apatrick@chromium.org144f2802012-07-12 01:42:34 +00002462 // sized query sanity check
2463 if (bufSize)
2464 {
2465 int requiredSize = outputPitch * height;
2466 if (requiredSize > *bufSize)
2467 {
2468 return error(GL_INVALID_OPERATION);
2469 }
2470 }
2471
2472 IDirect3DSurface9 *renderTarget = framebuffer->getRenderTarget();
2473 if (!renderTarget)
2474 {
2475 return; // Context must be lost, return silently
2476 }
2477
2478 D3DSURFACE_DESC desc;
2479 renderTarget->GetDesc(&desc);
2480
2481 if (desc.MultiSampleType != D3DMULTISAMPLE_NONE)
2482 {
2483 UNIMPLEMENTED(); // FIXME: Requires resolve using StretchRect into non-multisampled render target
2484 renderTarget->Release();
2485 return error(GL_OUT_OF_MEMORY);
2486 }
2487
2488 HRESULT result;
2489 IDirect3DSurface9 *systemSurface = NULL;
daniel@transgaming.com7cb796e2012-10-31 18:46:44 +00002490 bool directToPixels = !getPackReverseRowOrder() && getPackAlignment() <= 4 && mRenderer->getShareHandleSupport() &&
apatrick@chromium.org144f2802012-07-12 01:42:34 +00002491 x == 0 && y == 0 && UINT(width) == desc.Width && UINT(height) == desc.Height &&
2492 desc.Format == D3DFMT_A8R8G8B8 && format == GL_BGRA_EXT && type == GL_UNSIGNED_BYTE;
2493 if (directToPixels)
2494 {
2495 // Use the pixels ptr as a shared handle to write directly into client's memory
2496 result = mDevice->CreateOffscreenPlainSurface(desc.Width, desc.Height, desc.Format,
2497 D3DPOOL_SYSTEMMEM, &systemSurface, &pixels);
2498 if (FAILED(result))
2499 {
2500 // Try again without the shared handle
2501 directToPixels = false;
2502 }
2503 }
2504
2505 if (!directToPixels)
2506 {
2507 result = mDevice->CreateOffscreenPlainSurface(desc.Width, desc.Height, desc.Format,
2508 D3DPOOL_SYSTEMMEM, &systemSurface, NULL);
2509 if (FAILED(result))
2510 {
2511 ASSERT(result == D3DERR_OUTOFVIDEOMEMORY || result == E_OUTOFMEMORY);
2512 renderTarget->Release();
2513 return error(GL_OUT_OF_MEMORY);
2514 }
2515 }
2516
2517 result = mDevice->GetRenderTargetData(renderTarget, systemSurface);
2518 renderTarget->Release();
2519 renderTarget = NULL;
2520
2521 if (FAILED(result))
2522 {
2523 systemSurface->Release();
2524
2525 // It turns out that D3D will sometimes produce more error
2526 // codes than those documented.
2527 if (checkDeviceLost(result))
2528 return error(GL_OUT_OF_MEMORY);
2529 else
2530 {
2531 UNREACHABLE();
2532 return;
2533 }
2534
2535 }
2536
2537 if (directToPixels)
2538 {
2539 systemSurface->Release();
2540 return;
2541 }
2542
2543 RECT rect;
2544 rect.left = clamp(x, 0L, static_cast<LONG>(desc.Width));
2545 rect.top = clamp(y, 0L, static_cast<LONG>(desc.Height));
2546 rect.right = clamp(x + width, 0L, static_cast<LONG>(desc.Width));
2547 rect.bottom = clamp(y + height, 0L, static_cast<LONG>(desc.Height));
2548
2549 D3DLOCKED_RECT lock;
2550 result = systemSurface->LockRect(&lock, &rect, D3DLOCK_READONLY);
2551
2552 if (FAILED(result))
2553 {
2554 UNREACHABLE();
2555 systemSurface->Release();
2556
2557 return; // No sensible error to generate
2558 }
2559
2560 unsigned char *dest = (unsigned char*)pixels;
2561 unsigned short *dest16 = (unsigned short*)pixels;
2562
2563 unsigned char *source;
2564 int inputPitch;
2565 if (getPackReverseRowOrder())
2566 {
2567 source = ((unsigned char*)lock.pBits) + lock.Pitch * (rect.bottom - rect.top - 1);
2568 inputPitch = -lock.Pitch;
2569 }
2570 else
2571 {
2572 source = (unsigned char*)lock.pBits;
2573 inputPitch = lock.Pitch;
2574 }
2575
daniel@transgaming.com42944b02012-09-27 17:45:57 +00002576 unsigned int fastPixelSize = 0;
2577
2578 if (desc.Format == D3DFMT_A8R8G8B8 &&
2579 format == GL_BGRA_EXT &&
2580 type == GL_UNSIGNED_BYTE)
2581 {
2582 fastPixelSize = 4;
2583 }
2584 else if ((desc.Format == D3DFMT_A4R4G4B4 &&
2585 format == GL_BGRA_EXT &&
2586 type == GL_UNSIGNED_SHORT_4_4_4_4_REV_EXT) ||
2587 (desc.Format == D3DFMT_A1R5G5B5 &&
2588 format == GL_BGRA_EXT &&
2589 type == GL_UNSIGNED_SHORT_1_5_5_5_REV_EXT))
2590 {
2591 fastPixelSize = 2;
2592 }
2593 else if (desc.Format == D3DFMT_A16B16G16R16F &&
2594 format == GL_RGBA &&
2595 type == GL_HALF_FLOAT_OES)
2596 {
2597 fastPixelSize = 8;
2598 }
2599 else if (desc.Format == D3DFMT_A32B32G32R32F &&
2600 format == GL_RGBA &&
2601 type == GL_FLOAT)
2602 {
2603 fastPixelSize = 16;
2604 }
2605
apatrick@chromium.org144f2802012-07-12 01:42:34 +00002606 for (int j = 0; j < rect.bottom - rect.top; j++)
2607 {
daniel@transgaming.com42944b02012-09-27 17:45:57 +00002608 if (fastPixelSize != 0)
apatrick@chromium.org144f2802012-07-12 01:42:34 +00002609 {
daniel@transgaming.com42944b02012-09-27 17:45:57 +00002610 // Fast path for formats which require no translation:
2611 // D3DFMT_A8R8G8B8 to BGRA/UNSIGNED_BYTE
2612 // D3DFMT_A4R4G4B4 to BGRA/UNSIGNED_SHORT_4_4_4_4_REV_EXT
2613 // D3DFMT_A1R5G5B5 to BGRA/UNSIGNED_SHORT_1_5_5_5_REV_EXT
2614 // D3DFMT_A16B16G16R16F to RGBA/HALF_FLOAT_OES
2615 // D3DFMT_A32B32G32R32F to RGBA/FLOAT
2616 //
2617 // Note that buffers with no alpha go through the slow path below.
apatrick@chromium.org144f2802012-07-12 01:42:34 +00002618 memcpy(dest + j * outputPitch,
2619 source + j * inputPitch,
daniel@transgaming.com42944b02012-09-27 17:45:57 +00002620 (rect.right - rect.left) * fastPixelSize);
apatrick@chromium.org144f2802012-07-12 01:42:34 +00002621 continue;
2622 }
2623
2624 for (int i = 0; i < rect.right - rect.left; i++)
2625 {
2626 float r;
2627 float g;
2628 float b;
2629 float a;
2630
2631 switch (desc.Format)
2632 {
2633 case D3DFMT_R5G6B5:
2634 {
2635 unsigned short rgb = *(unsigned short*)(source + 2 * i + j * inputPitch);
2636
2637 a = 1.0f;
2638 b = (rgb & 0x001F) * (1.0f / 0x001F);
2639 g = (rgb & 0x07E0) * (1.0f / 0x07E0);
2640 r = (rgb & 0xF800) * (1.0f / 0xF800);
2641 }
2642 break;
2643 case D3DFMT_A1R5G5B5:
2644 {
2645 unsigned short argb = *(unsigned short*)(source + 2 * i + j * inputPitch);
2646
2647 a = (argb & 0x8000) ? 1.0f : 0.0f;
2648 b = (argb & 0x001F) * (1.0f / 0x001F);
2649 g = (argb & 0x03E0) * (1.0f / 0x03E0);
2650 r = (argb & 0x7C00) * (1.0f / 0x7C00);
2651 }
2652 break;
2653 case D3DFMT_A8R8G8B8:
2654 {
2655 unsigned int argb = *(unsigned int*)(source + 4 * i + j * inputPitch);
2656
2657 a = (argb & 0xFF000000) * (1.0f / 0xFF000000);
2658 b = (argb & 0x000000FF) * (1.0f / 0x000000FF);
2659 g = (argb & 0x0000FF00) * (1.0f / 0x0000FF00);
2660 r = (argb & 0x00FF0000) * (1.0f / 0x00FF0000);
2661 }
2662 break;
2663 case D3DFMT_X8R8G8B8:
2664 {
2665 unsigned int xrgb = *(unsigned int*)(source + 4 * i + j * inputPitch);
2666
2667 a = 1.0f;
2668 b = (xrgb & 0x000000FF) * (1.0f / 0x000000FF);
2669 g = (xrgb & 0x0000FF00) * (1.0f / 0x0000FF00);
2670 r = (xrgb & 0x00FF0000) * (1.0f / 0x00FF0000);
2671 }
2672 break;
2673 case D3DFMT_A2R10G10B10:
2674 {
2675 unsigned int argb = *(unsigned int*)(source + 4 * i + j * inputPitch);
2676
2677 a = (argb & 0xC0000000) * (1.0f / 0xC0000000);
2678 b = (argb & 0x000003FF) * (1.0f / 0x000003FF);
2679 g = (argb & 0x000FFC00) * (1.0f / 0x000FFC00);
2680 r = (argb & 0x3FF00000) * (1.0f / 0x3FF00000);
2681 }
2682 break;
2683 case D3DFMT_A32B32G32R32F:
2684 {
2685 // float formats in D3D are stored rgba, rather than the other way round
2686 r = *((float*)(source + 16 * i + j * inputPitch) + 0);
2687 g = *((float*)(source + 16 * i + j * inputPitch) + 1);
2688 b = *((float*)(source + 16 * i + j * inputPitch) + 2);
2689 a = *((float*)(source + 16 * i + j * inputPitch) + 3);
2690 }
2691 break;
2692 case D3DFMT_A16B16G16R16F:
2693 {
2694 // float formats in D3D are stored rgba, rather than the other way round
apatrick@chromium.orgaa480672012-09-05 19:32:38 +00002695 r = float16ToFloat32(*((unsigned short*)(source + 8 * i + j * inputPitch) + 0));
2696 g = float16ToFloat32(*((unsigned short*)(source + 8 * i + j * inputPitch) + 1));
2697 b = float16ToFloat32(*((unsigned short*)(source + 8 * i + j * inputPitch) + 2));
2698 a = float16ToFloat32(*((unsigned short*)(source + 8 * i + j * inputPitch) + 3));
apatrick@chromium.org144f2802012-07-12 01:42:34 +00002699 }
2700 break;
2701 default:
2702 UNIMPLEMENTED(); // FIXME
2703 UNREACHABLE();
2704 return;
2705 }
2706
2707 switch (format)
2708 {
2709 case GL_RGBA:
2710 switch (type)
2711 {
2712 case GL_UNSIGNED_BYTE:
2713 dest[4 * i + j * outputPitch + 0] = (unsigned char)(255 * r + 0.5f);
2714 dest[4 * i + j * outputPitch + 1] = (unsigned char)(255 * g + 0.5f);
2715 dest[4 * i + j * outputPitch + 2] = (unsigned char)(255 * b + 0.5f);
2716 dest[4 * i + j * outputPitch + 3] = (unsigned char)(255 * a + 0.5f);
2717 break;
2718 default: UNREACHABLE();
2719 }
2720 break;
2721 case GL_BGRA_EXT:
2722 switch (type)
2723 {
2724 case GL_UNSIGNED_BYTE:
2725 dest[4 * i + j * outputPitch + 0] = (unsigned char)(255 * b + 0.5f);
2726 dest[4 * i + j * outputPitch + 1] = (unsigned char)(255 * g + 0.5f);
2727 dest[4 * i + j * outputPitch + 2] = (unsigned char)(255 * r + 0.5f);
2728 dest[4 * i + j * outputPitch + 3] = (unsigned char)(255 * a + 0.5f);
2729 break;
2730 case GL_UNSIGNED_SHORT_4_4_4_4_REV_EXT:
2731 // According to the desktop GL spec in the "Transfer of Pixel Rectangles" section
2732 // this type is packed as follows:
2733 // 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0
2734 // --------------------------------------------------------------------------------
2735 // | 4th | 3rd | 2nd | 1st component |
2736 // --------------------------------------------------------------------------------
2737 // in the case of BGRA_EXT, B is the first component, G the second, and so forth.
2738 dest16[i + j * outputPitch / sizeof(unsigned short)] =
2739 ((unsigned short)(15 * a + 0.5f) << 12)|
2740 ((unsigned short)(15 * r + 0.5f) << 8) |
2741 ((unsigned short)(15 * g + 0.5f) << 4) |
2742 ((unsigned short)(15 * b + 0.5f) << 0);
2743 break;
2744 case GL_UNSIGNED_SHORT_1_5_5_5_REV_EXT:
2745 // According to the desktop GL spec in the "Transfer of Pixel Rectangles" section
2746 // this type is packed as follows:
2747 // 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0
2748 // --------------------------------------------------------------------------------
2749 // | 4th | 3rd | 2nd | 1st component |
2750 // --------------------------------------------------------------------------------
2751 // in the case of BGRA_EXT, B is the first component, G the second, and so forth.
2752 dest16[i + j * outputPitch / sizeof(unsigned short)] =
2753 ((unsigned short)( a + 0.5f) << 15) |
2754 ((unsigned short)(31 * r + 0.5f) << 10) |
2755 ((unsigned short)(31 * g + 0.5f) << 5) |
2756 ((unsigned short)(31 * b + 0.5f) << 0);
2757 break;
2758 default: UNREACHABLE();
2759 }
2760 break;
daniel@transgaming.com42944b02012-09-27 17:45:57 +00002761 case GL_RGB:
apatrick@chromium.org144f2802012-07-12 01:42:34 +00002762 switch (type)
2763 {
daniel@transgaming.com42944b02012-09-27 17:45:57 +00002764 case GL_UNSIGNED_SHORT_5_6_5:
apatrick@chromium.org144f2802012-07-12 01:42:34 +00002765 dest16[i + j * outputPitch / sizeof(unsigned short)] =
2766 ((unsigned short)(31 * b + 0.5f) << 0) |
2767 ((unsigned short)(63 * g + 0.5f) << 5) |
2768 ((unsigned short)(31 * r + 0.5f) << 11);
2769 break;
daniel@transgaming.com42944b02012-09-27 17:45:57 +00002770 case GL_UNSIGNED_BYTE:
2771 dest[3 * i + j * outputPitch + 0] = (unsigned char)(255 * r + 0.5f);
2772 dest[3 * i + j * outputPitch + 1] = (unsigned char)(255 * g + 0.5f);
2773 dest[3 * i + j * outputPitch + 2] = (unsigned char)(255 * b + 0.5f);
2774 break;
apatrick@chromium.org144f2802012-07-12 01:42:34 +00002775 default: UNREACHABLE();
2776 }
2777 break;
2778 default: UNREACHABLE();
2779 }
2780 }
2781 }
2782
2783 systemSurface->UnlockRect();
2784
2785 systemSurface->Release();
2786}
2787
2788void Context::clear(GLbitfield mask)
2789{
2790 Framebuffer *framebufferObject = getDrawFramebuffer();
2791
2792 if (!framebufferObject || framebufferObject->completeness() != GL_FRAMEBUFFER_COMPLETE)
2793 {
2794 return error(GL_INVALID_FRAMEBUFFER_OPERATION);
2795 }
2796
2797 DWORD flags = 0;
2798
2799 if (mask & GL_COLOR_BUFFER_BIT)
2800 {
2801 mask &= ~GL_COLOR_BUFFER_BIT;
2802
2803 if (framebufferObject->getColorbufferType() != GL_NONE)
2804 {
2805 flags |= D3DCLEAR_TARGET;
2806 }
2807 }
2808
2809 if (mask & GL_DEPTH_BUFFER_BIT)
2810 {
2811 mask &= ~GL_DEPTH_BUFFER_BIT;
2812 if (mState.depthMask && framebufferObject->getDepthbufferType() != GL_NONE)
2813 {
2814 flags |= D3DCLEAR_ZBUFFER;
2815 }
2816 }
2817
2818 GLuint stencilUnmasked = 0x0;
2819
2820 if (mask & GL_STENCIL_BUFFER_BIT)
2821 {
2822 mask &= ~GL_STENCIL_BUFFER_BIT;
2823 if (framebufferObject->getStencilbufferType() != GL_NONE)
2824 {
2825 IDirect3DSurface9 *depthStencil = framebufferObject->getStencilbuffer()->getDepthStencil();
2826 if (!depthStencil)
2827 {
2828 ERR("Depth stencil pointer unexpectedly null.");
2829 return;
2830 }
2831
2832 D3DSURFACE_DESC desc;
2833 depthStencil->GetDesc(&desc);
2834 depthStencil->Release();
2835
2836 unsigned int stencilSize = dx2es::GetStencilSize(desc.Format);
2837 stencilUnmasked = (0x1 << stencilSize) - 1;
2838
2839 if (stencilUnmasked != 0x0)
2840 {
2841 flags |= D3DCLEAR_STENCIL;
2842 }
2843 }
2844 }
2845
2846 if (mask != 0)
2847 {
2848 return error(GL_INVALID_VALUE);
2849 }
2850
2851 if (!applyRenderTarget(true)) // Clips the clear to the scissor rectangle but not the viewport
2852 {
2853 return;
2854 }
2855
2856 D3DCOLOR color = D3DCOLOR_ARGB(unorm<8>(mState.colorClearValue.alpha),
2857 unorm<8>(mState.colorClearValue.red),
2858 unorm<8>(mState.colorClearValue.green),
2859 unorm<8>(mState.colorClearValue.blue));
2860 float depth = clamp01(mState.depthClearValue);
2861 int stencil = mState.stencilClearValue & 0x000000FF;
2862
2863 bool alphaUnmasked = (dx2es::GetAlphaSize(mRenderTargetDesc.Format) == 0) || mState.colorMaskAlpha;
2864
2865 const bool needMaskedStencilClear = (flags & D3DCLEAR_STENCIL) &&
2866 (mState.stencilWritemask & stencilUnmasked) != stencilUnmasked;
2867 const bool needMaskedColorClear = (flags & D3DCLEAR_TARGET) &&
2868 !(mState.colorMaskRed && mState.colorMaskGreen &&
2869 mState.colorMaskBlue && alphaUnmasked);
2870
2871 if (needMaskedColorClear || needMaskedStencilClear)
2872 {
2873 // State which is altered in all paths from this point to the clear call is saved.
2874 // State which is altered in only some paths will be flagged dirty in the case that
2875 // that path is taken.
2876 HRESULT hr;
2877 if (mMaskedClearSavedState == NULL)
2878 {
2879 hr = mDevice->BeginStateBlock();
2880 ASSERT(SUCCEEDED(hr) || hr == D3DERR_OUTOFVIDEOMEMORY || hr == E_OUTOFMEMORY);
2881
2882 mDevice->SetRenderState(D3DRS_ZWRITEENABLE, FALSE);
2883 mDevice->SetRenderState(D3DRS_ZFUNC, D3DCMP_ALWAYS);
2884 mDevice->SetRenderState(D3DRS_ZENABLE, FALSE);
2885 mDevice->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE);
2886 mDevice->SetRenderState(D3DRS_FILLMODE, D3DFILL_SOLID);
2887 mDevice->SetRenderState(D3DRS_ALPHATESTENABLE, FALSE);
2888 mDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, FALSE);
2889 mDevice->SetRenderState(D3DRS_CLIPPLANEENABLE, 0);
2890 mDevice->SetRenderState(D3DRS_COLORWRITEENABLE, 0);
2891 mDevice->SetRenderState(D3DRS_STENCILENABLE, FALSE);
2892 mDevice->SetPixelShader(NULL);
2893 mDevice->SetVertexShader(NULL);
2894 mDevice->SetFVF(D3DFVF_XYZRHW | D3DFVF_DIFFUSE);
2895 mDevice->SetStreamSource(0, NULL, 0, 0);
2896 mDevice->SetRenderState(D3DRS_SEPARATEALPHABLENDENABLE, TRUE);
2897 mDevice->SetTextureStageState(0, D3DTSS_COLOROP, D3DTOP_SELECTARG1);
2898 mDevice->SetTextureStageState(0, D3DTSS_COLORARG1, D3DTA_TFACTOR);
2899 mDevice->SetTextureStageState(0, D3DTSS_ALPHAOP, D3DTOP_SELECTARG1);
2900 mDevice->SetTextureStageState(0, D3DTSS_ALPHAARG1, D3DTA_TFACTOR);
2901 mDevice->SetRenderState(D3DRS_TEXTUREFACTOR, color);
2902 mDevice->SetRenderState(D3DRS_MULTISAMPLEMASK, 0xFFFFFFFF);
2903
2904 for(int i = 0; i < MAX_VERTEX_ATTRIBS; i++)
2905 {
2906 mDevice->SetStreamSourceFreq(i, 1);
2907 }
2908
2909 hr = mDevice->EndStateBlock(&mMaskedClearSavedState);
2910 ASSERT(SUCCEEDED(hr) || hr == D3DERR_OUTOFVIDEOMEMORY || hr == E_OUTOFMEMORY);
2911 }
2912
2913 ASSERT(mMaskedClearSavedState != NULL);
2914
2915 if (mMaskedClearSavedState != NULL)
2916 {
2917 hr = mMaskedClearSavedState->Capture();
2918 ASSERT(SUCCEEDED(hr));
2919 }
2920
2921 mDevice->SetRenderState(D3DRS_ZWRITEENABLE, FALSE);
2922 mDevice->SetRenderState(D3DRS_ZFUNC, D3DCMP_ALWAYS);
2923 mDevice->SetRenderState(D3DRS_ZENABLE, FALSE);
2924 mDevice->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE);
2925 mDevice->SetRenderState(D3DRS_FILLMODE, D3DFILL_SOLID);
2926 mDevice->SetRenderState(D3DRS_ALPHATESTENABLE, FALSE);
2927 mDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, FALSE);
2928 mDevice->SetRenderState(D3DRS_CLIPPLANEENABLE, 0);
2929
2930 if (flags & D3DCLEAR_TARGET)
2931 {
2932 mDevice->SetRenderState(D3DRS_COLORWRITEENABLE, es2dx::ConvertColorMask(mState.colorMaskRed, mState.colorMaskGreen, mState.colorMaskBlue, mState.colorMaskAlpha));
2933 }
2934 else
2935 {
2936 mDevice->SetRenderState(D3DRS_COLORWRITEENABLE, 0);
2937 }
2938
2939 if (stencilUnmasked != 0x0 && (flags & D3DCLEAR_STENCIL))
2940 {
2941 mDevice->SetRenderState(D3DRS_STENCILENABLE, TRUE);
2942 mDevice->SetRenderState(D3DRS_TWOSIDEDSTENCILMODE, FALSE);
2943 mDevice->SetRenderState(D3DRS_STENCILFUNC, D3DCMP_ALWAYS);
2944 mDevice->SetRenderState(D3DRS_STENCILREF, stencil);
2945 mDevice->SetRenderState(D3DRS_STENCILWRITEMASK, mState.stencilWritemask);
2946 mDevice->SetRenderState(D3DRS_STENCILFAIL, D3DSTENCILOP_REPLACE);
2947 mDevice->SetRenderState(D3DRS_STENCILZFAIL, D3DSTENCILOP_REPLACE);
2948 mDevice->SetRenderState(D3DRS_STENCILPASS, D3DSTENCILOP_REPLACE);
2949 mStencilStateDirty = true;
2950 }
2951 else
2952 {
2953 mDevice->SetRenderState(D3DRS_STENCILENABLE, FALSE);
2954 }
2955
2956 mDevice->SetPixelShader(NULL);
2957 mDevice->SetVertexShader(NULL);
2958 mDevice->SetFVF(D3DFVF_XYZRHW);
2959 mDevice->SetRenderState(D3DRS_SEPARATEALPHABLENDENABLE, TRUE);
2960 mDevice->SetTextureStageState(0, D3DTSS_COLOROP, D3DTOP_SELECTARG1);
2961 mDevice->SetTextureStageState(0, D3DTSS_COLORARG1, D3DTA_TFACTOR);
2962 mDevice->SetTextureStageState(0, D3DTSS_ALPHAOP, D3DTOP_SELECTARG1);
2963 mDevice->SetTextureStageState(0, D3DTSS_ALPHAARG1, D3DTA_TFACTOR);
2964 mDevice->SetRenderState(D3DRS_TEXTUREFACTOR, color);
2965 mDevice->SetRenderState(D3DRS_MULTISAMPLEMASK, 0xFFFFFFFF);
2966
2967 for(int i = 0; i < MAX_VERTEX_ATTRIBS; i++)
2968 {
2969 mDevice->SetStreamSourceFreq(i, 1);
2970 }
2971
2972 float quad[4][4]; // A quadrilateral covering the target, aligned to match the edges
2973 quad[0][0] = -0.5f;
2974 quad[0][1] = mRenderTargetDesc.Height - 0.5f;
2975 quad[0][2] = 0.0f;
2976 quad[0][3] = 1.0f;
2977
2978 quad[1][0] = mRenderTargetDesc.Width - 0.5f;
2979 quad[1][1] = mRenderTargetDesc.Height - 0.5f;
2980 quad[1][2] = 0.0f;
2981 quad[1][3] = 1.0f;
2982
2983 quad[2][0] = -0.5f;
2984 quad[2][1] = -0.5f;
2985 quad[2][2] = 0.0f;
2986 quad[2][3] = 1.0f;
2987
2988 quad[3][0] = mRenderTargetDesc.Width - 0.5f;
2989 quad[3][1] = -0.5f;
2990 quad[3][2] = 0.0f;
2991 quad[3][3] = 1.0f;
2992
daniel@transgaming.com621ce052012-10-31 17:52:29 +00002993 mRenderer->startScene();
apatrick@chromium.org144f2802012-07-12 01:42:34 +00002994 mDevice->DrawPrimitiveUP(D3DPT_TRIANGLESTRIP, 2, quad, sizeof(float[4]));
2995
2996 if (flags & D3DCLEAR_ZBUFFER)
2997 {
2998 mDevice->SetRenderState(D3DRS_ZENABLE, TRUE);
2999 mDevice->SetRenderState(D3DRS_ZWRITEENABLE, TRUE);
3000 mDevice->Clear(0, NULL, D3DCLEAR_ZBUFFER, color, depth, stencil);
3001 }
3002
3003 if (mMaskedClearSavedState != NULL)
3004 {
3005 mMaskedClearSavedState->Apply();
3006 }
3007 }
3008 else if (flags)
3009 {
3010 mDevice->Clear(0, NULL, flags, color, depth, stencil);
3011 }
3012}
3013
3014void Context::drawArrays(GLenum mode, GLint first, GLsizei count, GLsizei instances)
3015{
3016 if (!mState.currentProgram)
3017 {
3018 return error(GL_INVALID_OPERATION);
3019 }
3020
3021 D3DPRIMITIVETYPE primitiveType;
3022 int primitiveCount;
3023
3024 if(!es2dx::ConvertPrimitiveType(mode, count, &primitiveType, &primitiveCount))
3025 return error(GL_INVALID_ENUM);
3026
3027 if (primitiveCount <= 0)
3028 {
3029 return;
3030 }
3031
3032 if (!applyRenderTarget(false))
3033 {
3034 return;
3035 }
3036
3037 applyState(mode);
3038
3039 GLsizei repeatDraw = 1;
3040 GLenum err = applyVertexBuffer(first, count, instances, &repeatDraw);
3041 if (err != GL_NO_ERROR)
3042 {
3043 return error(err);
3044 }
3045
3046 applyShaders();
3047 applyTextures();
3048
daniel@transgaming.com62a28462012-07-24 18:33:59 +00003049 if (!getCurrentProgramBinary()->validateSamplers(NULL))
apatrick@chromium.org144f2802012-07-12 01:42:34 +00003050 {
3051 return error(GL_INVALID_OPERATION);
3052 }
3053
daniel@transgaming.com087e5782012-09-17 21:28:47 +00003054 if (!skipDraw(mode))
apatrick@chromium.org144f2802012-07-12 01:42:34 +00003055 {
daniel@transgaming.com621ce052012-10-31 17:52:29 +00003056 mRenderer->startScene();
apatrick@chromium.org144f2802012-07-12 01:42:34 +00003057
3058 if (mode == GL_LINE_LOOP)
3059 {
3060 drawLineLoop(count, GL_NONE, NULL, 0);
3061 }
3062 else if (instances > 0)
3063 {
3064 StaticIndexBuffer *countingIB = mIndexDataManager->getCountingIndices(count);
3065 if (countingIB)
3066 {
3067 if (mAppliedIBSerial != countingIB->getSerial())
3068 {
3069 mDevice->SetIndices(countingIB->getBuffer());
3070 mAppliedIBSerial = countingIB->getSerial();
3071 }
3072
3073 for (int i = 0; i < repeatDraw; i++)
3074 {
3075 mDevice->DrawIndexedPrimitive(primitiveType, 0, 0, count, 0, primitiveCount);
3076 }
3077 }
3078 else
3079 {
3080 ERR("Could not create a counting index buffer for glDrawArraysInstanced.");
3081 return error(GL_OUT_OF_MEMORY);
3082 }
3083 }
3084 else // Regular case
3085 {
3086 mDevice->DrawPrimitive(primitiveType, 0, primitiveCount);
3087 }
3088 }
3089}
3090
3091void Context::drawElements(GLenum mode, GLsizei count, GLenum type, const GLvoid *indices, GLsizei instances)
3092{
3093 if (!mState.currentProgram)
3094 {
3095 return error(GL_INVALID_OPERATION);
3096 }
3097
3098 if (!indices && !mState.elementArrayBuffer)
3099 {
3100 return error(GL_INVALID_OPERATION);
3101 }
3102
3103 D3DPRIMITIVETYPE primitiveType;
3104 int primitiveCount;
3105
3106 if(!es2dx::ConvertPrimitiveType(mode, count, &primitiveType, &primitiveCount))
3107 return error(GL_INVALID_ENUM);
3108
3109 if (primitiveCount <= 0)
3110 {
3111 return;
3112 }
3113
3114 if (!applyRenderTarget(false))
3115 {
3116 return;
3117 }
3118
3119 applyState(mode);
3120
3121 TranslatedIndexData indexInfo;
3122 GLenum err = applyIndexBuffer(indices, count, mode, type, &indexInfo);
3123 if (err != GL_NO_ERROR)
3124 {
3125 return error(err);
3126 }
3127
3128 GLsizei vertexCount = indexInfo.maxIndex - indexInfo.minIndex + 1;
3129 GLsizei repeatDraw = 1;
3130 err = applyVertexBuffer(indexInfo.minIndex, vertexCount, instances, &repeatDraw);
3131 if (err != GL_NO_ERROR)
3132 {
3133 return error(err);
3134 }
3135
3136 applyShaders();
3137 applyTextures();
3138
daniel@transgaming.com62a28462012-07-24 18:33:59 +00003139 if (!getCurrentProgramBinary()->validateSamplers(false))
apatrick@chromium.org144f2802012-07-12 01:42:34 +00003140 {
3141 return error(GL_INVALID_OPERATION);
3142 }
3143
daniel@transgaming.com087e5782012-09-17 21:28:47 +00003144 if (!skipDraw(mode))
apatrick@chromium.org144f2802012-07-12 01:42:34 +00003145 {
daniel@transgaming.com621ce052012-10-31 17:52:29 +00003146 mRenderer->startScene();
apatrick@chromium.org144f2802012-07-12 01:42:34 +00003147
3148 if (mode == GL_LINE_LOOP)
3149 {
3150 drawLineLoop(count, type, indices, indexInfo.minIndex);
3151 }
3152 else
3153 {
3154 for (int i = 0; i < repeatDraw; i++)
3155 {
3156 mDevice->DrawIndexedPrimitive(primitiveType, -(INT)indexInfo.minIndex, indexInfo.minIndex, vertexCount, indexInfo.startIndex, primitiveCount);
3157 }
3158 }
3159 }
3160}
3161
3162// Implements glFlush when block is false, glFinish when block is true
3163void Context::sync(bool block)
3164{
daniel@transgaming.comef21ab22012-10-31 17:52:47 +00003165 mRenderer->sync(block);
apatrick@chromium.org144f2802012-07-12 01:42:34 +00003166}
3167
3168void Context::drawLineLoop(GLsizei count, GLenum type, const GLvoid *indices, int minIndex)
3169{
3170 // Get the raw indices for an indexed draw
3171 if (type != GL_NONE && mState.elementArrayBuffer.get())
3172 {
3173 Buffer *indexBuffer = mState.elementArrayBuffer.get();
3174 intptr_t offset = reinterpret_cast<intptr_t>(indices);
3175 indices = static_cast<const GLubyte*>(indexBuffer->data()) + offset;
3176 }
3177
3178 UINT startIndex = 0;
3179 bool succeeded = false;
3180
3181 if (supports32bitIndices())
3182 {
3183 const int spaceNeeded = (count + 1) * sizeof(unsigned int);
3184
3185 if (!mLineLoopIB)
3186 {
daniel@transgaming.com6716a272012-10-31 18:31:39 +00003187 mLineLoopIB = new StreamingIndexBuffer(mRenderer, INITIAL_INDEX_BUFFER_SIZE, D3DFMT_INDEX32);
apatrick@chromium.org144f2802012-07-12 01:42:34 +00003188 }
3189
3190 if (mLineLoopIB)
3191 {
3192 mLineLoopIB->reserveSpace(spaceNeeded, GL_UNSIGNED_INT);
3193
3194 UINT offset = 0;
3195 unsigned int *data = static_cast<unsigned int*>(mLineLoopIB->map(spaceNeeded, &offset));
3196 startIndex = offset / 4;
3197
3198 if (data)
3199 {
3200 switch (type)
3201 {
3202 case GL_NONE: // Non-indexed draw
3203 for (int i = 0; i < count; i++)
3204 {
3205 data[i] = i;
3206 }
3207 data[count] = 0;
3208 break;
3209 case GL_UNSIGNED_BYTE:
3210 for (int i = 0; i < count; i++)
3211 {
3212 data[i] = static_cast<const GLubyte*>(indices)[i];
3213 }
3214 data[count] = static_cast<const GLubyte*>(indices)[0];
3215 break;
3216 case GL_UNSIGNED_SHORT:
3217 for (int i = 0; i < count; i++)
3218 {
3219 data[i] = static_cast<const GLushort*>(indices)[i];
3220 }
3221 data[count] = static_cast<const GLushort*>(indices)[0];
3222 break;
3223 case GL_UNSIGNED_INT:
3224 for (int i = 0; i < count; i++)
3225 {
3226 data[i] = static_cast<const GLuint*>(indices)[i];
3227 }
3228 data[count] = static_cast<const GLuint*>(indices)[0];
3229 break;
3230 default: UNREACHABLE();
3231 }
3232
3233 mLineLoopIB->unmap();
3234 succeeded = true;
3235 }
3236 }
3237 }
3238 else
3239 {
3240 const int spaceNeeded = (count + 1) * sizeof(unsigned short);
3241
3242 if (!mLineLoopIB)
3243 {
daniel@transgaming.com6716a272012-10-31 18:31:39 +00003244 mLineLoopIB = new StreamingIndexBuffer(mRenderer, INITIAL_INDEX_BUFFER_SIZE, D3DFMT_INDEX16);
apatrick@chromium.org144f2802012-07-12 01:42:34 +00003245 }
3246
3247 if (mLineLoopIB)
3248 {
3249 mLineLoopIB->reserveSpace(spaceNeeded, GL_UNSIGNED_SHORT);
3250
3251 UINT offset = 0;
3252 unsigned short *data = static_cast<unsigned short*>(mLineLoopIB->map(spaceNeeded, &offset));
3253 startIndex = offset / 2;
3254
3255 if (data)
3256 {
3257 switch (type)
3258 {
3259 case GL_NONE: // Non-indexed draw
3260 for (int i = 0; i < count; i++)
3261 {
3262 data[i] = i;
3263 }
3264 data[count] = 0;
3265 break;
3266 case GL_UNSIGNED_BYTE:
3267 for (int i = 0; i < count; i++)
3268 {
3269 data[i] = static_cast<const GLubyte*>(indices)[i];
3270 }
3271 data[count] = static_cast<const GLubyte*>(indices)[0];
3272 break;
3273 case GL_UNSIGNED_SHORT:
3274 for (int i = 0; i < count; i++)
3275 {
3276 data[i] = static_cast<const GLushort*>(indices)[i];
3277 }
3278 data[count] = static_cast<const GLushort*>(indices)[0];
3279 break;
3280 case GL_UNSIGNED_INT:
3281 for (int i = 0; i < count; i++)
3282 {
3283 data[i] = static_cast<const GLuint*>(indices)[i];
3284 }
3285 data[count] = static_cast<const GLuint*>(indices)[0];
3286 break;
3287 default: UNREACHABLE();
3288 }
3289
3290 mLineLoopIB->unmap();
3291 succeeded = true;
3292 }
3293 }
3294 }
3295
3296 if (succeeded)
3297 {
3298 if (mAppliedIBSerial != mLineLoopIB->getSerial())
3299 {
3300 mDevice->SetIndices(mLineLoopIB->getBuffer());
3301 mAppliedIBSerial = mLineLoopIB->getSerial();
3302 }
3303
3304 mDevice->DrawIndexedPrimitive(D3DPT_LINESTRIP, -minIndex, minIndex, count, startIndex, count);
3305 }
3306 else
3307 {
3308 ERR("Could not create a looping index buffer for GL_LINE_LOOP.");
3309 return error(GL_OUT_OF_MEMORY);
3310 }
3311}
3312
3313void Context::recordInvalidEnum()
3314{
3315 mInvalidEnum = true;
3316}
3317
3318void Context::recordInvalidValue()
3319{
3320 mInvalidValue = true;
3321}
3322
3323void Context::recordInvalidOperation()
3324{
3325 mInvalidOperation = true;
3326}
3327
3328void Context::recordOutOfMemory()
3329{
3330 mOutOfMemory = true;
3331}
3332
3333void Context::recordInvalidFramebufferOperation()
3334{
3335 mInvalidFramebufferOperation = true;
3336}
3337
3338// Get one of the recorded errors and clear its flag, if any.
3339// [OpenGL ES 2.0.24] section 2.5 page 13.
3340GLenum Context::getError()
3341{
3342 if (mInvalidEnum)
3343 {
3344 mInvalidEnum = false;
3345
3346 return GL_INVALID_ENUM;
3347 }
3348
3349 if (mInvalidValue)
3350 {
3351 mInvalidValue = false;
3352
3353 return GL_INVALID_VALUE;
3354 }
3355
3356 if (mInvalidOperation)
3357 {
3358 mInvalidOperation = false;
3359
3360 return GL_INVALID_OPERATION;
3361 }
3362
3363 if (mOutOfMemory)
3364 {
3365 mOutOfMemory = false;
3366
3367 return GL_OUT_OF_MEMORY;
3368 }
3369
3370 if (mInvalidFramebufferOperation)
3371 {
3372 mInvalidFramebufferOperation = false;
3373
3374 return GL_INVALID_FRAMEBUFFER_OPERATION;
3375 }
3376
3377 return GL_NO_ERROR;
3378}
3379
3380GLenum Context::getResetStatus()
3381{
3382 if (mResetStatus == GL_NO_ERROR)
3383 {
daniel@transgaming.comf688c0d2012-10-31 17:52:57 +00003384 // mResetStatus will be set by the markContextLost callback
3385 // in the case a notification is sent
3386 mRenderer->testDeviceLost(true);
apatrick@chromium.org144f2802012-07-12 01:42:34 +00003387 }
3388
3389 GLenum status = mResetStatus;
3390
3391 if (mResetStatus != GL_NO_ERROR)
3392 {
daniel@transgaming.com621ce052012-10-31 17:52:29 +00003393 if (mRenderer->testDeviceResettable())
apatrick@chromium.org144f2802012-07-12 01:42:34 +00003394 {
3395 mResetStatus = GL_NO_ERROR;
3396 }
3397 }
3398
3399 return status;
3400}
3401
3402bool Context::isResetNotificationEnabled()
3403{
3404 return (mResetStrategy == GL_LOSE_CONTEXT_ON_RESET_EXT);
3405}
3406
3407bool Context::supportsShaderModel3() const
3408{
3409 return mSupportsShaderModel3;
3410}
3411
3412float Context::getMaximumPointSize() const
3413{
3414 return mSupportsShaderModel3 ? mMaximumPointSize : ALIASED_POINT_SIZE_RANGE_MAX_SM2;
3415}
3416
3417int Context::getMaximumVaryingVectors() const
3418{
3419 return mSupportsShaderModel3 ? MAX_VARYING_VECTORS_SM3 : MAX_VARYING_VECTORS_SM2;
3420}
3421
3422unsigned int Context::getMaximumVertexTextureImageUnits() const
3423{
3424 return mSupportsVertexTexture ? MAX_VERTEX_TEXTURE_IMAGE_UNITS_VTF : 0;
3425}
3426
3427unsigned int Context::getMaximumCombinedTextureImageUnits() const
3428{
3429 return MAX_TEXTURE_IMAGE_UNITS + getMaximumVertexTextureImageUnits();
3430}
3431
3432int Context::getMaximumFragmentUniformVectors() const
3433{
3434 return mSupportsShaderModel3 ? MAX_FRAGMENT_UNIFORM_VECTORS_SM3 : MAX_FRAGMENT_UNIFORM_VECTORS_SM2;
3435}
3436
3437int Context::getMaxSupportedSamples() const
3438{
daniel@transgaming.comb7833982012-10-31 18:31:46 +00003439 return mRenderer->getMaxSupportedSamples();
apatrick@chromium.org144f2802012-07-12 01:42:34 +00003440}
3441
apatrick@chromium.org144f2802012-07-12 01:42:34 +00003442bool Context::supportsEventQueries() const
3443{
3444 return mSupportsEventQueries;
3445}
3446
3447bool Context::supportsOcclusionQueries() const
3448{
3449 return mSupportsOcclusionQueries;
3450}
3451
3452bool Context::supportsDXT1Textures() const
3453{
3454 return mSupportsDXT1Textures;
3455}
3456
3457bool Context::supportsDXT3Textures() const
3458{
3459 return mSupportsDXT3Textures;
3460}
3461
3462bool Context::supportsDXT5Textures() const
3463{
3464 return mSupportsDXT5Textures;
3465}
3466
3467bool Context::supportsFloat32Textures() const
3468{
3469 return mSupportsFloat32Textures;
3470}
3471
3472bool Context::supportsFloat32LinearFilter() const
3473{
3474 return mSupportsFloat32LinearFilter;
3475}
3476
3477bool Context::supportsFloat32RenderableTextures() const
3478{
3479 return mSupportsFloat32RenderableTextures;
3480}
3481
3482bool Context::supportsFloat16Textures() const
3483{
3484 return mSupportsFloat16Textures;
3485}
3486
3487bool Context::supportsFloat16LinearFilter() const
3488{
3489 return mSupportsFloat16LinearFilter;
3490}
3491
3492bool Context::supportsFloat16RenderableTextures() const
3493{
3494 return mSupportsFloat16RenderableTextures;
3495}
3496
3497int Context::getMaximumRenderbufferDimension() const
3498{
3499 return mMaxRenderbufferDimension;
3500}
3501
3502int Context::getMaximumTextureDimension() const
3503{
3504 return mMaxTextureDimension;
3505}
3506
3507int Context::getMaximumCubeTextureDimension() const
3508{
3509 return mMaxCubeTextureDimension;
3510}
3511
3512int Context::getMaximumTextureLevel() const
3513{
3514 return mMaxTextureLevel;
3515}
3516
3517bool Context::supportsLuminanceTextures() const
3518{
3519 return mSupportsLuminanceTextures;
3520}
3521
3522bool Context::supportsLuminanceAlphaTextures() const
3523{
3524 return mSupportsLuminanceAlphaTextures;
3525}
3526
3527bool Context::supportsDepthTextures() const
3528{
3529 return mSupportsDepthTextures;
3530}
3531
3532bool Context::supports32bitIndices() const
3533{
3534 return mSupports32bitIndices;
3535}
3536
3537bool Context::supportsNonPower2Texture() const
3538{
3539 return mSupportsNonPower2Texture;
3540}
3541
3542bool Context::supportsInstancing() const
3543{
3544 return mSupportsInstancing;
3545}
3546
daniel@transgaming.com07ab8412012-07-12 15:17:09 +00003547bool Context::supportsTextureFilterAnisotropy() const
3548{
3549 return mSupportsTextureFilterAnisotropy;
3550}
3551
3552float Context::getTextureMaxAnisotropy() const
3553{
3554 return mMaxTextureAnisotropy;
3555}
3556
daniel@transgaming.com42944b02012-09-27 17:45:57 +00003557bool Context::getCurrentReadFormatType(GLenum *format, GLenum *type)
3558{
3559 Framebuffer *framebuffer = getReadFramebuffer();
3560 if (!framebuffer || framebuffer->completeness() != GL_FRAMEBUFFER_COMPLETE)
3561 {
3562 return error(GL_INVALID_OPERATION, false);
3563 }
3564
3565 Renderbuffer *renderbuffer = framebuffer->getColorbuffer();
3566 if (!renderbuffer)
3567 {
3568 return error(GL_INVALID_OPERATION, false);
3569 }
3570
daniel@transgaming.com20d36662012-10-31 19:51:43 +00003571 *format = gl::ExtractFormat(renderbuffer->getActualFormat());
3572 *type = gl::ExtractType(renderbuffer->getActualFormat());
daniel@transgaming.com42944b02012-09-27 17:45:57 +00003573
3574 return true;
3575}
3576
apatrick@chromium.org144f2802012-07-12 01:42:34 +00003577void Context::detachBuffer(GLuint buffer)
3578{
3579 // [OpenGL ES 2.0.24] section 2.9 page 22:
3580 // If a buffer object is deleted while it is bound, all bindings to that object in the current context
3581 // (i.e. in the thread that called Delete-Buffers) are reset to zero.
3582
3583 if (mState.arrayBuffer.id() == buffer)
3584 {
3585 mState.arrayBuffer.set(NULL);
3586 }
3587
3588 if (mState.elementArrayBuffer.id() == buffer)
3589 {
3590 mState.elementArrayBuffer.set(NULL);
3591 }
3592
3593 for (int attribute = 0; attribute < MAX_VERTEX_ATTRIBS; attribute++)
3594 {
3595 if (mState.vertexAttribute[attribute].mBoundBuffer.id() == buffer)
3596 {
3597 mState.vertexAttribute[attribute].mBoundBuffer.set(NULL);
3598 }
3599 }
3600}
3601
3602void Context::detachTexture(GLuint texture)
3603{
3604 // [OpenGL ES 2.0.24] section 3.8 page 84:
3605 // If a texture object is deleted, it is as if all texture units which are bound to that texture object are
3606 // rebound to texture object zero
3607
3608 for (int type = 0; type < TEXTURE_TYPE_COUNT; type++)
3609 {
3610 for (int sampler = 0; sampler < MAX_COMBINED_TEXTURE_IMAGE_UNITS_VTF; sampler++)
3611 {
3612 if (mState.samplerTexture[type][sampler].id() == texture)
3613 {
3614 mState.samplerTexture[type][sampler].set(NULL);
3615 }
3616 }
3617 }
3618
3619 // [OpenGL ES 2.0.24] section 4.4 page 112:
3620 // If a texture object is deleted while its image is attached to the currently bound framebuffer, then it is
3621 // as if FramebufferTexture2D had been called, with a texture of 0, for each attachment point to which this
3622 // image was attached in the currently bound framebuffer.
3623
3624 Framebuffer *readFramebuffer = getReadFramebuffer();
3625 Framebuffer *drawFramebuffer = getDrawFramebuffer();
3626
3627 if (readFramebuffer)
3628 {
3629 readFramebuffer->detachTexture(texture);
3630 }
3631
3632 if (drawFramebuffer && drawFramebuffer != readFramebuffer)
3633 {
3634 drawFramebuffer->detachTexture(texture);
3635 }
3636}
3637
3638void Context::detachFramebuffer(GLuint framebuffer)
3639{
3640 // [OpenGL ES 2.0.24] section 4.4 page 107:
3641 // If a framebuffer that is currently bound to the target FRAMEBUFFER is deleted, it is as though
3642 // BindFramebuffer had been executed with the target of FRAMEBUFFER and framebuffer of zero.
3643
3644 if (mState.readFramebuffer == framebuffer)
3645 {
3646 bindReadFramebuffer(0);
3647 }
3648
3649 if (mState.drawFramebuffer == framebuffer)
3650 {
3651 bindDrawFramebuffer(0);
3652 }
3653}
3654
3655void Context::detachRenderbuffer(GLuint renderbuffer)
3656{
3657 // [OpenGL ES 2.0.24] section 4.4 page 109:
3658 // If a renderbuffer that is currently bound to RENDERBUFFER is deleted, it is as though BindRenderbuffer
3659 // had been executed with the target RENDERBUFFER and name of zero.
3660
3661 if (mState.renderbuffer.id() == renderbuffer)
3662 {
3663 bindRenderbuffer(0);
3664 }
3665
3666 // [OpenGL ES 2.0.24] section 4.4 page 111:
3667 // If a renderbuffer object is deleted while its image is attached to the currently bound framebuffer,
3668 // then it is as if FramebufferRenderbuffer had been called, with a renderbuffer of 0, for each attachment
3669 // point to which this image was attached in the currently bound framebuffer.
3670
3671 Framebuffer *readFramebuffer = getReadFramebuffer();
3672 Framebuffer *drawFramebuffer = getDrawFramebuffer();
3673
3674 if (readFramebuffer)
3675 {
3676 readFramebuffer->detachRenderbuffer(renderbuffer);
3677 }
3678
3679 if (drawFramebuffer && drawFramebuffer != readFramebuffer)
3680 {
3681 drawFramebuffer->detachRenderbuffer(renderbuffer);
3682 }
3683}
3684
3685Texture *Context::getIncompleteTexture(TextureType type)
3686{
3687 Texture *t = mIncompleteTextures[type].get();
3688
3689 if (t == NULL)
3690 {
3691 static const GLubyte color[] = { 0, 0, 0, 255 };
3692
3693 switch (type)
3694 {
3695 default:
3696 UNREACHABLE();
3697 // default falls through to TEXTURE_2D
3698
3699 case TEXTURE_2D:
3700 {
daniel@transgaming.com370482e2012-11-28 19:32:13 +00003701 Texture2D *incomplete2d = new Texture2D(mRenderer, Texture::INCOMPLETE_TEXTURE_ID);
apatrick@chromium.org144f2802012-07-12 01:42:34 +00003702 incomplete2d->setImage(0, 1, 1, GL_RGBA, GL_UNSIGNED_BYTE, 1, color);
3703 t = incomplete2d;
3704 }
3705 break;
3706
3707 case TEXTURE_CUBE:
3708 {
daniel@transgaming.com370482e2012-11-28 19:32:13 +00003709 TextureCubeMap *incompleteCube = new TextureCubeMap(mRenderer, Texture::INCOMPLETE_TEXTURE_ID);
apatrick@chromium.org144f2802012-07-12 01:42:34 +00003710
3711 incompleteCube->setImagePosX(0, 1, 1, GL_RGBA, GL_UNSIGNED_BYTE, 1, color);
3712 incompleteCube->setImageNegX(0, 1, 1, GL_RGBA, GL_UNSIGNED_BYTE, 1, color);
3713 incompleteCube->setImagePosY(0, 1, 1, GL_RGBA, GL_UNSIGNED_BYTE, 1, color);
3714 incompleteCube->setImageNegY(0, 1, 1, GL_RGBA, GL_UNSIGNED_BYTE, 1, color);
3715 incompleteCube->setImagePosZ(0, 1, 1, GL_RGBA, GL_UNSIGNED_BYTE, 1, color);
3716 incompleteCube->setImageNegZ(0, 1, 1, GL_RGBA, GL_UNSIGNED_BYTE, 1, color);
3717
3718 t = incompleteCube;
3719 }
3720 break;
3721 }
3722
3723 mIncompleteTextures[type].set(t);
3724 }
3725
3726 return t;
3727}
3728
daniel@transgaming.com087e5782012-09-17 21:28:47 +00003729bool Context::skipDraw(GLenum drawMode)
apatrick@chromium.org144f2802012-07-12 01:42:34 +00003730{
daniel@transgaming.com087e5782012-09-17 21:28:47 +00003731 if (drawMode == GL_POINTS)
3732 {
3733 // ProgramBinary assumes non-point rendering if gl_PointSize isn't written,
3734 // which affects varying interpolation. Since the value of gl_PointSize is
3735 // undefined when not written, just skip drawing to avoid unexpected results.
3736 if (!getCurrentProgramBinary()->usesPointSize())
3737 {
3738 // This is stictly speaking not an error, but developers should be
3739 // notified of risking undefined behavior.
3740 ERR("Point rendering without writing to gl_PointSize.");
3741
3742 return true;
3743 }
3744 }
3745 else if (isTriangleMode(drawMode))
3746 {
3747 if (mState.cullFace && mState.cullMode == GL_FRONT_AND_BACK)
3748 {
3749 return true;
3750 }
3751 }
3752
3753 return false;
apatrick@chromium.org144f2802012-07-12 01:42:34 +00003754}
3755
3756bool Context::isTriangleMode(GLenum drawMode)
3757{
3758 switch (drawMode)
3759 {
3760 case GL_TRIANGLES:
3761 case GL_TRIANGLE_FAN:
3762 case GL_TRIANGLE_STRIP:
3763 return true;
3764 case GL_POINTS:
3765 case GL_LINES:
3766 case GL_LINE_LOOP:
3767 case GL_LINE_STRIP:
3768 return false;
3769 default: UNREACHABLE();
3770 }
3771
3772 return false;
3773}
3774
3775void Context::setVertexAttrib(GLuint index, const GLfloat *values)
3776{
3777 ASSERT(index < gl::MAX_VERTEX_ATTRIBS);
3778
3779 mState.vertexAttribute[index].mCurrentValue[0] = values[0];
3780 mState.vertexAttribute[index].mCurrentValue[1] = values[1];
3781 mState.vertexAttribute[index].mCurrentValue[2] = values[2];
3782 mState.vertexAttribute[index].mCurrentValue[3] = values[3];
3783
3784 mVertexDataManager->dirtyCurrentValue(index);
3785}
3786
3787void Context::setVertexAttribDivisor(GLuint index, GLuint divisor)
3788{
3789 ASSERT(index < gl::MAX_VERTEX_ATTRIBS);
3790
3791 mState.vertexAttribute[index].mDivisor = divisor;
3792}
3793
3794// keep list sorted in following order
3795// OES extensions
3796// EXT extensions
3797// Vendor extensions
3798void Context::initExtensionString()
3799{
3800 mExtensionString = "";
3801
3802 // OES extensions
3803 if (supports32bitIndices())
3804 {
3805 mExtensionString += "GL_OES_element_index_uint ";
3806 }
3807
3808 mExtensionString += "GL_OES_packed_depth_stencil ";
3809 mExtensionString += "GL_OES_get_program_binary ";
3810 mExtensionString += "GL_OES_rgb8_rgba8 ";
3811 mExtensionString += "GL_OES_standard_derivatives ";
3812
3813 if (supportsFloat16Textures())
3814 {
3815 mExtensionString += "GL_OES_texture_half_float ";
3816 }
3817 if (supportsFloat16LinearFilter())
3818 {
3819 mExtensionString += "GL_OES_texture_half_float_linear ";
3820 }
3821 if (supportsFloat32Textures())
3822 {
3823 mExtensionString += "GL_OES_texture_float ";
3824 }
3825 if (supportsFloat32LinearFilter())
3826 {
3827 mExtensionString += "GL_OES_texture_float_linear ";
3828 }
3829
3830 if (supportsNonPower2Texture())
3831 {
3832 mExtensionString += "GL_OES_texture_npot ";
3833 }
3834
3835 // Multi-vendor (EXT) extensions
3836 if (supportsOcclusionQueries())
3837 {
3838 mExtensionString += "GL_EXT_occlusion_query_boolean ";
3839 }
3840
3841 mExtensionString += "GL_EXT_read_format_bgra ";
3842 mExtensionString += "GL_EXT_robustness ";
3843
3844 if (supportsDXT1Textures())
3845 {
3846 mExtensionString += "GL_EXT_texture_compression_dxt1 ";
3847 }
3848
daniel@transgaming.com07ab8412012-07-12 15:17:09 +00003849 if (supportsTextureFilterAnisotropy())
3850 {
3851 mExtensionString += "GL_EXT_texture_filter_anisotropic ";
3852 }
3853
apatrick@chromium.org144f2802012-07-12 01:42:34 +00003854 mExtensionString += "GL_EXT_texture_format_BGRA8888 ";
3855 mExtensionString += "GL_EXT_texture_storage ";
3856
3857 // ANGLE-specific extensions
3858 if (supportsDepthTextures())
3859 {
3860 mExtensionString += "GL_ANGLE_depth_texture ";
3861 }
3862
3863 mExtensionString += "GL_ANGLE_framebuffer_blit ";
3864 if (getMaxSupportedSamples() != 0)
3865 {
3866 mExtensionString += "GL_ANGLE_framebuffer_multisample ";
3867 }
3868
3869 if (supportsInstancing())
3870 {
3871 mExtensionString += "GL_ANGLE_instanced_arrays ";
3872 }
3873
3874 mExtensionString += "GL_ANGLE_pack_reverse_row_order ";
3875
3876 if (supportsDXT3Textures())
3877 {
3878 mExtensionString += "GL_ANGLE_texture_compression_dxt3 ";
3879 }
3880 if (supportsDXT5Textures())
3881 {
3882 mExtensionString += "GL_ANGLE_texture_compression_dxt5 ";
3883 }
3884
3885 mExtensionString += "GL_ANGLE_texture_usage ";
3886 mExtensionString += "GL_ANGLE_translated_shader_source ";
3887
3888 // Other vendor-specific extensions
3889 if (supportsEventQueries())
3890 {
3891 mExtensionString += "GL_NV_fence ";
3892 }
3893
3894 std::string::size_type end = mExtensionString.find_last_not_of(' ');
3895 if (end != std::string::npos)
3896 {
3897 mExtensionString.resize(end+1);
3898 }
3899}
3900
3901const char *Context::getExtensionString() const
3902{
3903 return mExtensionString.c_str();
3904}
3905
3906void Context::initRendererString()
3907{
apatrick@chromium.org144f2802012-07-12 01:42:34 +00003908 mRendererString = "ANGLE (";
daniel@transgaming.com4ca789e2012-10-31 18:46:40 +00003909 mRendererString += mRenderer->getAdapterDescription();
apatrick@chromium.org144f2802012-07-12 01:42:34 +00003910 mRendererString += ")";
3911}
3912
3913const char *Context::getRendererString() const
3914{
3915 return mRendererString.c_str();
3916}
3917
3918void Context::blitFramebuffer(GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1,
3919 GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1,
3920 GLbitfield mask)
3921{
3922 Framebuffer *readFramebuffer = getReadFramebuffer();
3923 Framebuffer *drawFramebuffer = getDrawFramebuffer();
3924
3925 if (!readFramebuffer || readFramebuffer->completeness() != GL_FRAMEBUFFER_COMPLETE ||
3926 !drawFramebuffer || drawFramebuffer->completeness() != GL_FRAMEBUFFER_COMPLETE)
3927 {
3928 return error(GL_INVALID_FRAMEBUFFER_OPERATION);
3929 }
3930
3931 if (drawFramebuffer->getSamples() != 0)
3932 {
3933 return error(GL_INVALID_OPERATION);
3934 }
3935
3936 int readBufferWidth = readFramebuffer->getColorbuffer()->getWidth();
3937 int readBufferHeight = readFramebuffer->getColorbuffer()->getHeight();
3938 int drawBufferWidth = drawFramebuffer->getColorbuffer()->getWidth();
3939 int drawBufferHeight = drawFramebuffer->getColorbuffer()->getHeight();
3940
3941 RECT sourceRect;
3942 RECT destRect;
3943
3944 if (srcX0 < srcX1)
3945 {
3946 sourceRect.left = srcX0;
3947 sourceRect.right = srcX1;
3948 destRect.left = dstX0;
3949 destRect.right = dstX1;
3950 }
3951 else
3952 {
3953 sourceRect.left = srcX1;
3954 destRect.left = dstX1;
3955 sourceRect.right = srcX0;
3956 destRect.right = dstX0;
3957 }
3958
3959 if (srcY0 < srcY1)
3960 {
3961 sourceRect.bottom = srcY1;
3962 destRect.bottom = dstY1;
3963 sourceRect.top = srcY0;
3964 destRect.top = dstY0;
3965 }
3966 else
3967 {
3968 sourceRect.bottom = srcY0;
3969 destRect.bottom = dstY0;
3970 sourceRect.top = srcY1;
3971 destRect.top = dstY1;
3972 }
3973
3974 RECT sourceScissoredRect = sourceRect;
3975 RECT destScissoredRect = destRect;
3976
3977 if (mState.scissorTest)
3978 {
3979 // Only write to parts of the destination framebuffer which pass the scissor test
3980 // Please note: the destRect is now in D3D-style coordinates, so the *top* of the
3981 // rect will be checked against scissorY, rather than the bottom.
3982 if (destRect.left < mState.scissorX)
3983 {
3984 int xDiff = mState.scissorX - destRect.left;
3985 destScissoredRect.left = mState.scissorX;
3986 sourceScissoredRect.left += xDiff;
3987 }
3988
3989 if (destRect.right > mState.scissorX + mState.scissorWidth)
3990 {
3991 int xDiff = destRect.right - (mState.scissorX + mState.scissorWidth);
3992 destScissoredRect.right = mState.scissorX + mState.scissorWidth;
3993 sourceScissoredRect.right -= xDiff;
3994 }
3995
3996 if (destRect.top < mState.scissorY)
3997 {
3998 int yDiff = mState.scissorY - destRect.top;
3999 destScissoredRect.top = mState.scissorY;
4000 sourceScissoredRect.top += yDiff;
4001 }
4002
4003 if (destRect.bottom > mState.scissorY + mState.scissorHeight)
4004 {
4005 int yDiff = destRect.bottom - (mState.scissorY + mState.scissorHeight);
4006 destScissoredRect.bottom = mState.scissorY + mState.scissorHeight;
4007 sourceScissoredRect.bottom -= yDiff;
4008 }
4009 }
4010
4011 bool blitRenderTarget = false;
4012 bool blitDepthStencil = false;
4013
4014 RECT sourceTrimmedRect = sourceScissoredRect;
4015 RECT destTrimmedRect = destScissoredRect;
4016
4017 // The source & destination rectangles also may need to be trimmed if they fall out of the bounds of
4018 // the actual draw and read surfaces.
4019 if (sourceTrimmedRect.left < 0)
4020 {
4021 int xDiff = 0 - sourceTrimmedRect.left;
4022 sourceTrimmedRect.left = 0;
4023 destTrimmedRect.left += xDiff;
4024 }
4025
4026 if (sourceTrimmedRect.right > readBufferWidth)
4027 {
4028 int xDiff = sourceTrimmedRect.right - readBufferWidth;
4029 sourceTrimmedRect.right = readBufferWidth;
4030 destTrimmedRect.right -= xDiff;
4031 }
4032
4033 if (sourceTrimmedRect.top < 0)
4034 {
4035 int yDiff = 0 - sourceTrimmedRect.top;
4036 sourceTrimmedRect.top = 0;
4037 destTrimmedRect.top += yDiff;
4038 }
4039
4040 if (sourceTrimmedRect.bottom > readBufferHeight)
4041 {
4042 int yDiff = sourceTrimmedRect.bottom - readBufferHeight;
4043 sourceTrimmedRect.bottom = readBufferHeight;
4044 destTrimmedRect.bottom -= yDiff;
4045 }
4046
4047 if (destTrimmedRect.left < 0)
4048 {
4049 int xDiff = 0 - destTrimmedRect.left;
4050 destTrimmedRect.left = 0;
4051 sourceTrimmedRect.left += xDiff;
4052 }
4053
4054 if (destTrimmedRect.right > drawBufferWidth)
4055 {
4056 int xDiff = destTrimmedRect.right - drawBufferWidth;
4057 destTrimmedRect.right = drawBufferWidth;
4058 sourceTrimmedRect.right -= xDiff;
4059 }
4060
4061 if (destTrimmedRect.top < 0)
4062 {
4063 int yDiff = 0 - destTrimmedRect.top;
4064 destTrimmedRect.top = 0;
4065 sourceTrimmedRect.top += yDiff;
4066 }
4067
4068 if (destTrimmedRect.bottom > drawBufferHeight)
4069 {
4070 int yDiff = destTrimmedRect.bottom - drawBufferHeight;
4071 destTrimmedRect.bottom = drawBufferHeight;
4072 sourceTrimmedRect.bottom -= yDiff;
4073 }
4074
4075 bool partialBufferCopy = false;
4076 if (sourceTrimmedRect.bottom - sourceTrimmedRect.top < readBufferHeight ||
4077 sourceTrimmedRect.right - sourceTrimmedRect.left < readBufferWidth ||
4078 destTrimmedRect.bottom - destTrimmedRect.top < drawBufferHeight ||
4079 destTrimmedRect.right - destTrimmedRect.left < drawBufferWidth ||
4080 sourceTrimmedRect.top != 0 || destTrimmedRect.top != 0 || sourceTrimmedRect.left != 0 || destTrimmedRect.left != 0)
4081 {
4082 partialBufferCopy = true;
4083 }
4084
4085 if (mask & GL_COLOR_BUFFER_BIT)
4086 {
4087 const bool validReadType = readFramebuffer->getColorbufferType() == GL_TEXTURE_2D ||
4088 readFramebuffer->getColorbufferType() == GL_RENDERBUFFER;
4089 const bool validDrawType = drawFramebuffer->getColorbufferType() == GL_TEXTURE_2D ||
4090 drawFramebuffer->getColorbufferType() == GL_RENDERBUFFER;
4091 if (!validReadType || !validDrawType ||
daniel@transgaming.com20d36662012-10-31 19:51:43 +00004092 readFramebuffer->getColorbuffer()->getActualFormat() != drawFramebuffer->getColorbuffer()->getActualFormat())
apatrick@chromium.org144f2802012-07-12 01:42:34 +00004093 {
4094 ERR("Color buffer format conversion in BlitFramebufferANGLE not supported by this implementation");
4095 return error(GL_INVALID_OPERATION);
4096 }
4097
4098 if (partialBufferCopy && readFramebuffer->getSamples() != 0)
4099 {
4100 return error(GL_INVALID_OPERATION);
4101 }
4102
4103 blitRenderTarget = true;
4104
4105 }
4106
4107 if (mask & (GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT))
4108 {
4109 Renderbuffer *readDSBuffer = NULL;
4110 Renderbuffer *drawDSBuffer = NULL;
4111
4112 // We support OES_packed_depth_stencil, and do not support a separately attached depth and stencil buffer, so if we have
4113 // both a depth and stencil buffer, it will be the same buffer.
4114
4115 if (mask & GL_DEPTH_BUFFER_BIT)
4116 {
4117 if (readFramebuffer->getDepthbuffer() && drawFramebuffer->getDepthbuffer())
4118 {
4119 if (readFramebuffer->getDepthbufferType() != drawFramebuffer->getDepthbufferType() ||
daniel@transgaming.com20d36662012-10-31 19:51:43 +00004120 readFramebuffer->getDepthbuffer()->getActualFormat() != drawFramebuffer->getDepthbuffer()->getActualFormat())
apatrick@chromium.org144f2802012-07-12 01:42:34 +00004121 {
4122 return error(GL_INVALID_OPERATION);
4123 }
4124
4125 blitDepthStencil = true;
4126 readDSBuffer = readFramebuffer->getDepthbuffer();
4127 drawDSBuffer = drawFramebuffer->getDepthbuffer();
4128 }
4129 }
4130
4131 if (mask & GL_STENCIL_BUFFER_BIT)
4132 {
4133 if (readFramebuffer->getStencilbuffer() && drawFramebuffer->getStencilbuffer())
4134 {
4135 if (readFramebuffer->getStencilbufferType() != drawFramebuffer->getStencilbufferType() ||
daniel@transgaming.com20d36662012-10-31 19:51:43 +00004136 readFramebuffer->getStencilbuffer()->getActualFormat() != drawFramebuffer->getStencilbuffer()->getActualFormat())
apatrick@chromium.org144f2802012-07-12 01:42:34 +00004137 {
4138 return error(GL_INVALID_OPERATION);
4139 }
4140
4141 blitDepthStencil = true;
4142 readDSBuffer = readFramebuffer->getStencilbuffer();
4143 drawDSBuffer = drawFramebuffer->getStencilbuffer();
4144 }
4145 }
4146
4147 if (partialBufferCopy)
4148 {
4149 ERR("Only whole-buffer depth and stencil blits are supported by this implementation.");
4150 return error(GL_INVALID_OPERATION); // only whole-buffer copies are permitted
4151 }
4152
4153 if ((drawDSBuffer && drawDSBuffer->getSamples() != 0) ||
4154 (readDSBuffer && readDSBuffer->getSamples() != 0))
4155 {
4156 return error(GL_INVALID_OPERATION);
4157 }
4158 }
4159
4160 if (blitRenderTarget || blitDepthStencil)
4161 {
daniel@transgaming.com621ce052012-10-31 17:52:29 +00004162 mRenderer->endScene();
apatrick@chromium.org144f2802012-07-12 01:42:34 +00004163
4164 if (blitRenderTarget)
4165 {
4166 IDirect3DSurface9* readRenderTarget = readFramebuffer->getRenderTarget();
4167 IDirect3DSurface9* drawRenderTarget = drawFramebuffer->getRenderTarget();
4168
4169 HRESULT result = mDevice->StretchRect(readRenderTarget, &sourceTrimmedRect,
4170 drawRenderTarget, &destTrimmedRect, D3DTEXF_NONE);
4171
4172 readRenderTarget->Release();
4173 drawRenderTarget->Release();
4174
4175 if (FAILED(result))
4176 {
4177 ERR("BlitFramebufferANGLE failed: StretchRect returned %x.", result);
4178 return;
4179 }
4180 }
4181
4182 if (blitDepthStencil)
4183 {
4184 IDirect3DSurface9* readDepthStencil = readFramebuffer->getDepthStencil();
4185 IDirect3DSurface9* drawDepthStencil = drawFramebuffer->getDepthStencil();
4186
4187 HRESULT result = mDevice->StretchRect(readDepthStencil, NULL, drawDepthStencil, NULL, D3DTEXF_NONE);
4188
4189 readDepthStencil->Release();
4190 drawDepthStencil->Release();
4191
4192 if (FAILED(result))
4193 {
4194 ERR("BlitFramebufferANGLE failed: StretchRect returned %x.", result);
4195 return;
4196 }
4197 }
4198 }
4199}
4200
4201VertexDeclarationCache::VertexDeclarationCache() : mMaxLru(0)
4202{
4203 for (int i = 0; i < NUM_VERTEX_DECL_CACHE_ENTRIES; i++)
4204 {
4205 mVertexDeclCache[i].vertexDeclaration = NULL;
4206 mVertexDeclCache[i].lruCount = 0;
4207 }
4208}
4209
4210VertexDeclarationCache::~VertexDeclarationCache()
4211{
4212 for (int i = 0; i < NUM_VERTEX_DECL_CACHE_ENTRIES; i++)
4213 {
4214 if (mVertexDeclCache[i].vertexDeclaration)
4215 {
4216 mVertexDeclCache[i].vertexDeclaration->Release();
4217 }
4218 }
4219}
4220
daniel@transgaming.com5ae3ccc2012-07-24 18:29:38 +00004221GLenum VertexDeclarationCache::applyDeclaration(IDirect3DDevice9 *device, TranslatedAttribute attributes[], ProgramBinary *programBinary, GLsizei instances, GLsizei *repeatDraw)
apatrick@chromium.org144f2802012-07-12 01:42:34 +00004222{
4223 *repeatDraw = 1;
4224
4225 int indexedAttribute = MAX_VERTEX_ATTRIBS;
4226 int instancedAttribute = MAX_VERTEX_ATTRIBS;
4227
4228 if (instances > 0)
4229 {
4230 // Find an indexed attribute to be mapped to D3D stream 0
4231 for (int i = 0; i < MAX_VERTEX_ATTRIBS; i++)
4232 {
4233 if (attributes[i].active)
4234 {
4235 if (indexedAttribute == MAX_VERTEX_ATTRIBS)
4236 {
4237 if (attributes[i].divisor == 0)
4238 {
4239 indexedAttribute = i;
4240 }
4241 }
4242 else if (instancedAttribute == MAX_VERTEX_ATTRIBS)
4243 {
4244 if (attributes[i].divisor != 0)
4245 {
4246 instancedAttribute = i;
4247 }
4248 }
4249 else break; // Found both an indexed and instanced attribute
4250 }
4251 }
4252
4253 if (indexedAttribute == MAX_VERTEX_ATTRIBS)
4254 {
4255 return GL_INVALID_OPERATION;
4256 }
4257 }
4258
4259 D3DVERTEXELEMENT9 elements[MAX_VERTEX_ATTRIBS + 1];
4260 D3DVERTEXELEMENT9 *element = &elements[0];
4261
apatrick@chromium.org144f2802012-07-12 01:42:34 +00004262 for (int i = 0; i < MAX_VERTEX_ATTRIBS; i++)
4263 {
4264 if (attributes[i].active)
4265 {
4266 int stream = i;
4267
4268 if (instances > 0)
4269 {
4270 // Due to a bug on ATI cards we can't enable instancing when none of the attributes are instanced.
4271 if (instancedAttribute == MAX_VERTEX_ATTRIBS)
4272 {
4273 *repeatDraw = instances;
4274 }
4275 else
4276 {
4277 if (i == indexedAttribute)
4278 {
4279 stream = 0;
4280 }
4281 else if (i == 0)
4282 {
4283 stream = indexedAttribute;
4284 }
4285
4286 UINT frequency = 1;
4287
4288 if (attributes[i].divisor == 0)
4289 {
4290 frequency = D3DSTREAMSOURCE_INDEXEDDATA | instances;
4291 }
4292 else
4293 {
4294 frequency = D3DSTREAMSOURCE_INSTANCEDATA | attributes[i].divisor;
4295 }
4296
4297 device->SetStreamSourceFreq(stream, frequency);
4298 mInstancingEnabled = true;
4299 }
4300 }
4301
4302 if (mAppliedVBs[stream].serial != attributes[i].serial ||
4303 mAppliedVBs[stream].stride != attributes[i].stride ||
4304 mAppliedVBs[stream].offset != attributes[i].offset)
4305 {
4306 device->SetStreamSource(stream, attributes[i].vertexBuffer, attributes[i].offset, attributes[i].stride);
4307 mAppliedVBs[stream].serial = attributes[i].serial;
4308 mAppliedVBs[stream].stride = attributes[i].stride;
4309 mAppliedVBs[stream].offset = attributes[i].offset;
4310 }
4311
4312 element->Stream = stream;
4313 element->Offset = 0;
4314 element->Type = attributes[i].type;
4315 element->Method = D3DDECLMETHOD_DEFAULT;
4316 element->Usage = D3DDECLUSAGE_TEXCOORD;
4317 element->UsageIndex = programBinary->getSemanticIndex(i);
4318 element++;
4319 }
4320 }
4321
4322 if (instances == 0 || instancedAttribute == MAX_VERTEX_ATTRIBS)
4323 {
4324 if (mInstancingEnabled)
4325 {
4326 for (int i = 0; i < MAX_VERTEX_ATTRIBS; i++)
4327 {
4328 device->SetStreamSourceFreq(i, 1);
4329 }
4330
4331 mInstancingEnabled = false;
4332 }
4333 }
4334
4335 static const D3DVERTEXELEMENT9 end = D3DDECL_END();
4336 *(element++) = end;
4337
4338 for (int i = 0; i < NUM_VERTEX_DECL_CACHE_ENTRIES; i++)
4339 {
4340 VertexDeclCacheEntry *entry = &mVertexDeclCache[i];
4341 if (memcmp(entry->cachedElements, elements, (element - elements) * sizeof(D3DVERTEXELEMENT9)) == 0 && entry->vertexDeclaration)
4342 {
4343 entry->lruCount = ++mMaxLru;
4344 if(entry->vertexDeclaration != mLastSetVDecl)
4345 {
4346 device->SetVertexDeclaration(entry->vertexDeclaration);
4347 mLastSetVDecl = entry->vertexDeclaration;
4348 }
4349
4350 return GL_NO_ERROR;
4351 }
4352 }
4353
4354 VertexDeclCacheEntry *lastCache = mVertexDeclCache;
4355
4356 for (int i = 0; i < NUM_VERTEX_DECL_CACHE_ENTRIES; i++)
4357 {
4358 if (mVertexDeclCache[i].lruCount < lastCache->lruCount)
4359 {
4360 lastCache = &mVertexDeclCache[i];
4361 }
4362 }
4363
4364 if (lastCache->vertexDeclaration != NULL)
4365 {
4366 lastCache->vertexDeclaration->Release();
4367 lastCache->vertexDeclaration = NULL;
4368 // mLastSetVDecl is set to the replacement, so we don't have to worry
4369 // about it.
4370 }
4371
4372 memcpy(lastCache->cachedElements, elements, (element - elements) * sizeof(D3DVERTEXELEMENT9));
4373 device->CreateVertexDeclaration(elements, &lastCache->vertexDeclaration);
4374 device->SetVertexDeclaration(lastCache->vertexDeclaration);
4375 mLastSetVDecl = lastCache->vertexDeclaration;
4376 lastCache->lruCount = ++mMaxLru;
4377
4378 return GL_NO_ERROR;
4379}
4380
4381void VertexDeclarationCache::markStateDirty()
4382{
4383 for (int i = 0; i < MAX_VERTEX_ATTRIBS; i++)
4384 {
4385 mAppliedVBs[i].serial = 0;
4386 }
4387
4388 mLastSetVDecl = NULL;
4389 mInstancingEnabled = true; // Forces it to be disabled when not used
4390}
4391
4392}
4393
4394extern "C"
4395{
daniel@transgaming.com03d39092012-11-28 19:31:59 +00004396gl::Context *glCreateContext(const gl::Context *shareContext, rx::Renderer *renderer, bool notifyResets, bool robustAccess)
apatrick@chromium.org144f2802012-07-12 01:42:34 +00004397{
daniel@transgaming.com03d39092012-11-28 19:31:59 +00004398 return new gl::Context(shareContext, renderer, notifyResets, robustAccess);
apatrick@chromium.org144f2802012-07-12 01:42:34 +00004399}
4400
4401void glDestroyContext(gl::Context *context)
4402{
4403 delete context;
4404
4405 if (context == gl::getContext())
4406 {
4407 gl::makeCurrent(NULL, NULL, NULL);
4408 }
4409}
4410
4411void glMakeCurrent(gl::Context *context, egl::Display *display, egl::Surface *surface)
4412{
4413 gl::makeCurrent(context, display, surface);
4414}
4415
4416gl::Context *glGetCurrentContext()
4417{
4418 return gl::getContext();
4419}
daniel@transgaming.com621ce052012-10-31 17:52:29 +00004420
daniel@transgaming.com76d3e6e2012-10-31 19:55:33 +00004421rx::SwapChain *glCreateSwapChain(rx::Renderer9 *renderer, HWND window, HANDLE shareHandle,
daniel@transgaming.com3c720782012-10-31 18:42:34 +00004422 GLenum backBufferFormat, GLenum depthBufferFormat)
4423{
daniel@transgaming.com76d3e6e2012-10-31 19:55:33 +00004424 return new rx::SwapChain(renderer, window, shareHandle, backBufferFormat, depthBufferFormat);
daniel@transgaming.com3c720782012-10-31 18:42:34 +00004425}
4426
daniel@transgaming.com76d3e6e2012-10-31 19:55:33 +00004427void glDestroySwapChain(rx::SwapChain *swapChain)
daniel@transgaming.com3c720782012-10-31 18:42:34 +00004428{
4429 delete swapChain;
4430}
4431
4432
apatrick@chromium.org144f2802012-07-12 01:42:34 +00004433}