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