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