blob: 830a0dd4dfca4d917c0c164306e02a879f047dc6 [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.comb7386992012-10-31 18:29:58 +0000256 mVertexDataManager = new VertexDataManager(this, mRenderer);
daniel@transgaming.com6716a272012-10-31 18:31:39 +0000257 mIndexDataManager = new IndexDataManager(this, 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
840const VertexAttributeArray &Context::getVertexAttributes()
841{
842 return mState.vertexAttribute;
843}
844
845void Context::setPackAlignment(GLint alignment)
846{
847 mState.packAlignment = alignment;
848}
849
850GLint Context::getPackAlignment() const
851{
852 return mState.packAlignment;
853}
854
855void Context::setUnpackAlignment(GLint alignment)
856{
857 mState.unpackAlignment = alignment;
858}
859
860GLint Context::getUnpackAlignment() const
861{
862 return mState.unpackAlignment;
863}
864
865void Context::setPackReverseRowOrder(bool reverseRowOrder)
866{
867 mState.packReverseRowOrder = reverseRowOrder;
868}
869
870bool Context::getPackReverseRowOrder() const
871{
872 return mState.packReverseRowOrder;
873}
874
875GLuint Context::createBuffer()
876{
877 return mResourceManager->createBuffer();
878}
879
880GLuint Context::createProgram()
881{
882 return mResourceManager->createProgram();
883}
884
885GLuint Context::createShader(GLenum type)
886{
887 return mResourceManager->createShader(type);
888}
889
890GLuint Context::createTexture()
891{
892 return mResourceManager->createTexture();
893}
894
895GLuint Context::createRenderbuffer()
896{
897 return mResourceManager->createRenderbuffer();
898}
899
900// Returns an unused framebuffer name
901GLuint Context::createFramebuffer()
902{
903 GLuint handle = mFramebufferHandleAllocator.allocate();
904
905 mFramebufferMap[handle] = NULL;
906
907 return handle;
908}
909
910GLuint Context::createFence()
911{
912 GLuint handle = mFenceHandleAllocator.allocate();
913
daniel@transgaming.comef21ab22012-10-31 17:52:47 +0000914 mFenceMap[handle] = new Fence(mRenderer);
apatrick@chromium.org144f2802012-07-12 01:42:34 +0000915
916 return handle;
917}
918
919// Returns an unused query name
920GLuint Context::createQuery()
921{
922 GLuint handle = mQueryHandleAllocator.allocate();
923
924 mQueryMap[handle] = NULL;
925
926 return handle;
927}
928
929void Context::deleteBuffer(GLuint buffer)
930{
931 if (mResourceManager->getBuffer(buffer))
932 {
933 detachBuffer(buffer);
934 }
935
936 mResourceManager->deleteBuffer(buffer);
937}
938
939void Context::deleteShader(GLuint shader)
940{
941 mResourceManager->deleteShader(shader);
942}
943
944void Context::deleteProgram(GLuint program)
945{
946 mResourceManager->deleteProgram(program);
apatrick@chromium.org144f2802012-07-12 01:42:34 +0000947}
948
949void Context::deleteTexture(GLuint texture)
950{
951 if (mResourceManager->getTexture(texture))
952 {
953 detachTexture(texture);
954 }
955
956 mResourceManager->deleteTexture(texture);
957}
958
959void Context::deleteRenderbuffer(GLuint renderbuffer)
960{
961 if (mResourceManager->getRenderbuffer(renderbuffer))
962 {
963 detachRenderbuffer(renderbuffer);
964 }
965
966 mResourceManager->deleteRenderbuffer(renderbuffer);
967}
968
969void Context::deleteFramebuffer(GLuint framebuffer)
970{
971 FramebufferMap::iterator framebufferObject = mFramebufferMap.find(framebuffer);
972
973 if (framebufferObject != mFramebufferMap.end())
974 {
975 detachFramebuffer(framebuffer);
976
977 mFramebufferHandleAllocator.release(framebufferObject->first);
978 delete framebufferObject->second;
979 mFramebufferMap.erase(framebufferObject);
980 }
981}
982
983void Context::deleteFence(GLuint fence)
984{
985 FenceMap::iterator fenceObject = mFenceMap.find(fence);
986
987 if (fenceObject != mFenceMap.end())
988 {
989 mFenceHandleAllocator.release(fenceObject->first);
990 delete fenceObject->second;
991 mFenceMap.erase(fenceObject);
992 }
993}
994
995void Context::deleteQuery(GLuint query)
996{
997 QueryMap::iterator queryObject = mQueryMap.find(query);
998 if (queryObject != mQueryMap.end())
999 {
1000 mQueryHandleAllocator.release(queryObject->first);
1001 if (queryObject->second)
1002 {
1003 queryObject->second->release();
1004 }
1005 mQueryMap.erase(queryObject);
1006 }
1007}
1008
1009Buffer *Context::getBuffer(GLuint handle)
1010{
1011 return mResourceManager->getBuffer(handle);
1012}
1013
1014Shader *Context::getShader(GLuint handle)
1015{
1016 return mResourceManager->getShader(handle);
1017}
1018
1019Program *Context::getProgram(GLuint handle)
1020{
1021 return mResourceManager->getProgram(handle);
1022}
1023
1024Texture *Context::getTexture(GLuint handle)
1025{
1026 return mResourceManager->getTexture(handle);
1027}
1028
1029Renderbuffer *Context::getRenderbuffer(GLuint handle)
1030{
1031 return mResourceManager->getRenderbuffer(handle);
1032}
1033
1034Framebuffer *Context::getReadFramebuffer()
1035{
1036 return getFramebuffer(mState.readFramebuffer);
1037}
1038
1039Framebuffer *Context::getDrawFramebuffer()
1040{
1041 return mBoundDrawFramebuffer;
1042}
1043
1044void Context::bindArrayBuffer(unsigned int buffer)
1045{
1046 mResourceManager->checkBufferAllocation(buffer);
1047
1048 mState.arrayBuffer.set(getBuffer(buffer));
1049}
1050
1051void Context::bindElementArrayBuffer(unsigned int buffer)
1052{
1053 mResourceManager->checkBufferAllocation(buffer);
1054
1055 mState.elementArrayBuffer.set(getBuffer(buffer));
1056}
1057
1058void Context::bindTexture2D(GLuint texture)
1059{
1060 mResourceManager->checkTextureAllocation(texture, TEXTURE_2D);
1061
1062 mState.samplerTexture[TEXTURE_2D][mState.activeSampler].set(getTexture(texture));
1063}
1064
1065void Context::bindTextureCubeMap(GLuint texture)
1066{
1067 mResourceManager->checkTextureAllocation(texture, TEXTURE_CUBE);
1068
1069 mState.samplerTexture[TEXTURE_CUBE][mState.activeSampler].set(getTexture(texture));
1070}
1071
1072void Context::bindReadFramebuffer(GLuint framebuffer)
1073{
1074 if (!getFramebuffer(framebuffer))
1075 {
1076 mFramebufferMap[framebuffer] = new Framebuffer();
1077 }
1078
1079 mState.readFramebuffer = framebuffer;
1080}
1081
1082void Context::bindDrawFramebuffer(GLuint framebuffer)
1083{
1084 if (!getFramebuffer(framebuffer))
1085 {
1086 mFramebufferMap[framebuffer] = new Framebuffer();
1087 }
1088
1089 mState.drawFramebuffer = framebuffer;
1090
1091 mBoundDrawFramebuffer = getFramebuffer(framebuffer);
1092}
1093
1094void Context::bindRenderbuffer(GLuint renderbuffer)
1095{
1096 mResourceManager->checkRenderbufferAllocation(renderbuffer);
1097
1098 mState.renderbuffer.set(getRenderbuffer(renderbuffer));
1099}
1100
1101void Context::useProgram(GLuint program)
1102{
1103 GLuint priorProgram = mState.currentProgram;
1104 mState.currentProgram = program; // Must switch before trying to delete, otherwise it only gets flagged.
1105
1106 if (priorProgram != program)
1107 {
1108 Program *newProgram = mResourceManager->getProgram(program);
1109 Program *oldProgram = mResourceManager->getProgram(priorProgram);
daniel@transgaming.com989c1c82012-07-24 18:40:38 +00001110 mCurrentProgramBinary.set(NULL);
apatrick@chromium.org144f2802012-07-12 01:42:34 +00001111 mDxUniformsDirty = true;
1112
1113 if (newProgram)
1114 {
1115 newProgram->addRef();
daniel@transgaming.com989c1c82012-07-24 18:40:38 +00001116 mCurrentProgramBinary.set(newProgram->getProgramBinary());
apatrick@chromium.org144f2802012-07-12 01:42:34 +00001117 }
1118
1119 if (oldProgram)
1120 {
1121 oldProgram->release();
1122 }
1123 }
1124}
1125
daniel@transgaming.com95d29422012-07-24 18:36:10 +00001126void Context::linkProgram(GLuint program)
1127{
1128 Program *programObject = mResourceManager->getProgram(program);
1129
daniel@transgaming.com12394cf2012-07-24 18:37:59 +00001130 bool linked = programObject->link();
1131
1132 // if the current program was relinked successfully we
1133 // need to install the new executables
1134 if (linked && program == mState.currentProgram)
1135 {
daniel@transgaming.com989c1c82012-07-24 18:40:38 +00001136 mCurrentProgramBinary.set(programObject->getProgramBinary());
daniel@transgaming.com12394cf2012-07-24 18:37:59 +00001137 mDxUniformsDirty = true;
1138 }
daniel@transgaming.com95d29422012-07-24 18:36:10 +00001139}
1140
1141void Context::setProgramBinary(GLuint program, const void *binary, GLint length)
1142{
1143 Program *programObject = mResourceManager->getProgram(program);
1144
daniel@transgaming.com12394cf2012-07-24 18:37:59 +00001145 bool loaded = programObject->setProgramBinary(binary, length);
1146
1147 // if the current program was reloaded successfully we
1148 // need to install the new executables
1149 if (loaded && program == mState.currentProgram)
1150 {
daniel@transgaming.com989c1c82012-07-24 18:40:38 +00001151 mCurrentProgramBinary.set(programObject->getProgramBinary());
daniel@transgaming.com12394cf2012-07-24 18:37:59 +00001152 mDxUniformsDirty = true;
1153 }
1154
daniel@transgaming.com95d29422012-07-24 18:36:10 +00001155}
1156
apatrick@chromium.org144f2802012-07-12 01:42:34 +00001157void Context::beginQuery(GLenum target, GLuint query)
1158{
1159 // From EXT_occlusion_query_boolean: If BeginQueryEXT is called with an <id>
1160 // of zero, if the active query object name for <target> is non-zero (for the
1161 // targets ANY_SAMPLES_PASSED_EXT and ANY_SAMPLES_PASSED_CONSERVATIVE_EXT, if
1162 // the active query for either target is non-zero), if <id> is the name of an
1163 // existing query object whose type does not match <target>, or if <id> is the
1164 // active query object name for any query type, the error INVALID_OPERATION is
1165 // generated.
1166
1167 // Ensure no other queries are active
1168 // NOTE: If other queries than occlusion are supported, we will need to check
1169 // separately that:
1170 // a) The query ID passed is not the current active query for any target/type
1171 // b) There are no active queries for the requested target (and in the case
1172 // of GL_ANY_SAMPLES_PASSED_EXT and GL_ANY_SAMPLES_PASSED_CONSERVATIVE_EXT,
1173 // no query may be active for either if glBeginQuery targets either.
1174 for (int i = 0; i < QUERY_TYPE_COUNT; i++)
1175 {
1176 if (mState.activeQuery[i].get() != NULL)
1177 {
1178 return error(GL_INVALID_OPERATION);
1179 }
1180 }
1181
1182 QueryType qType;
1183 switch (target)
1184 {
1185 case GL_ANY_SAMPLES_PASSED_EXT:
1186 qType = QUERY_ANY_SAMPLES_PASSED;
1187 break;
1188 case GL_ANY_SAMPLES_PASSED_CONSERVATIVE_EXT:
1189 qType = QUERY_ANY_SAMPLES_PASSED_CONSERVATIVE;
1190 break;
1191 default:
1192 ASSERT(false);
1193 return;
1194 }
1195
1196 Query *queryObject = getQuery(query, true, target);
1197
1198 // check that name was obtained with glGenQueries
1199 if (!queryObject)
1200 {
1201 return error(GL_INVALID_OPERATION);
1202 }
1203
1204 // check for type mismatch
1205 if (queryObject->getType() != target)
1206 {
1207 return error(GL_INVALID_OPERATION);
1208 }
1209
1210 // set query as active for specified target
1211 mState.activeQuery[qType].set(queryObject);
1212
1213 // begin query
1214 queryObject->begin();
1215}
1216
1217void Context::endQuery(GLenum target)
1218{
1219 QueryType qType;
1220
1221 switch (target)
1222 {
1223 case GL_ANY_SAMPLES_PASSED_EXT:
1224 qType = QUERY_ANY_SAMPLES_PASSED;
1225 break;
1226 case GL_ANY_SAMPLES_PASSED_CONSERVATIVE_EXT:
1227 qType = QUERY_ANY_SAMPLES_PASSED_CONSERVATIVE;
1228 break;
1229 default:
1230 ASSERT(false);
1231 return;
1232 }
1233
1234 Query *queryObject = mState.activeQuery[qType].get();
1235
1236 if (queryObject == NULL)
1237 {
1238 return error(GL_INVALID_OPERATION);
1239 }
1240
1241 queryObject->end();
1242
1243 mState.activeQuery[qType].set(NULL);
1244}
1245
1246void Context::setFramebufferZero(Framebuffer *buffer)
1247{
1248 delete mFramebufferMap[0];
1249 mFramebufferMap[0] = buffer;
1250 if (mState.drawFramebuffer == 0)
1251 {
1252 mBoundDrawFramebuffer = buffer;
1253 }
1254}
1255
1256void Context::setRenderbufferStorage(RenderbufferStorage *renderbuffer)
1257{
1258 Renderbuffer *renderbufferObject = mState.renderbuffer.get();
1259 renderbufferObject->setStorage(renderbuffer);
1260}
1261
1262Framebuffer *Context::getFramebuffer(unsigned int handle)
1263{
1264 FramebufferMap::iterator framebuffer = mFramebufferMap.find(handle);
1265
1266 if (framebuffer == mFramebufferMap.end())
1267 {
1268 return NULL;
1269 }
1270 else
1271 {
1272 return framebuffer->second;
1273 }
1274}
1275
1276Fence *Context::getFence(unsigned int handle)
1277{
1278 FenceMap::iterator fence = mFenceMap.find(handle);
1279
1280 if (fence == mFenceMap.end())
1281 {
1282 return NULL;
1283 }
1284 else
1285 {
1286 return fence->second;
1287 }
1288}
1289
1290Query *Context::getQuery(unsigned int handle, bool create, GLenum type)
1291{
1292 QueryMap::iterator query = mQueryMap.find(handle);
1293
1294 if (query == mQueryMap.end())
1295 {
1296 return NULL;
1297 }
1298 else
1299 {
1300 if (!query->second && create)
1301 {
daniel@transgaming.comef21ab22012-10-31 17:52:47 +00001302 query->second = new Query(mRenderer, handle, type);
apatrick@chromium.org144f2802012-07-12 01:42:34 +00001303 query->second->addRef();
1304 }
1305 return query->second;
1306 }
1307}
1308
1309Buffer *Context::getArrayBuffer()
1310{
1311 return mState.arrayBuffer.get();
1312}
1313
1314Buffer *Context::getElementArrayBuffer()
1315{
1316 return mState.elementArrayBuffer.get();
1317}
1318
daniel@transgaming.com62a28462012-07-24 18:33:59 +00001319ProgramBinary *Context::getCurrentProgramBinary()
apatrick@chromium.org144f2802012-07-12 01:42:34 +00001320{
daniel@transgaming.com989c1c82012-07-24 18:40:38 +00001321 return mCurrentProgramBinary.get();
apatrick@chromium.org144f2802012-07-12 01:42:34 +00001322}
1323
1324Texture2D *Context::getTexture2D()
1325{
1326 return static_cast<Texture2D*>(getSamplerTexture(mState.activeSampler, TEXTURE_2D));
1327}
1328
1329TextureCubeMap *Context::getTextureCubeMap()
1330{
1331 return static_cast<TextureCubeMap*>(getSamplerTexture(mState.activeSampler, TEXTURE_CUBE));
1332}
1333
1334Texture *Context::getSamplerTexture(unsigned int sampler, TextureType type)
1335{
1336 GLuint texid = mState.samplerTexture[type][sampler].id();
1337
1338 if (texid == 0) // Special case: 0 refers to different initial textures based on the target
1339 {
1340 switch (type)
1341 {
1342 default: UNREACHABLE();
1343 case TEXTURE_2D: return mTexture2DZero.get();
1344 case TEXTURE_CUBE: return mTextureCubeMapZero.get();
1345 }
1346 }
1347
1348 return mState.samplerTexture[type][sampler].get();
1349}
1350
1351bool Context::getBooleanv(GLenum pname, GLboolean *params)
1352{
1353 switch (pname)
1354 {
1355 case GL_SHADER_COMPILER: *params = GL_TRUE; break;
1356 case GL_SAMPLE_COVERAGE_INVERT: *params = mState.sampleCoverageInvert; break;
1357 case GL_DEPTH_WRITEMASK: *params = mState.depthMask; break;
1358 case GL_COLOR_WRITEMASK:
1359 params[0] = mState.colorMaskRed;
1360 params[1] = mState.colorMaskGreen;
1361 params[2] = mState.colorMaskBlue;
1362 params[3] = mState.colorMaskAlpha;
1363 break;
1364 case GL_CULL_FACE: *params = mState.cullFace; break;
1365 case GL_POLYGON_OFFSET_FILL: *params = mState.polygonOffsetFill; break;
1366 case GL_SAMPLE_ALPHA_TO_COVERAGE: *params = mState.sampleAlphaToCoverage; break;
1367 case GL_SAMPLE_COVERAGE: *params = mState.sampleCoverage; break;
1368 case GL_SCISSOR_TEST: *params = mState.scissorTest; break;
1369 case GL_STENCIL_TEST: *params = mState.stencilTest; break;
1370 case GL_DEPTH_TEST: *params = mState.depthTest; break;
1371 case GL_BLEND: *params = mState.blend; break;
1372 case GL_DITHER: *params = mState.dither; break;
1373 case GL_CONTEXT_ROBUST_ACCESS_EXT: *params = mRobustAccess ? GL_TRUE : GL_FALSE; break;
1374 default:
1375 return false;
1376 }
1377
1378 return true;
1379}
1380
1381bool Context::getFloatv(GLenum pname, GLfloat *params)
1382{
1383 // Please note: DEPTH_CLEAR_VALUE is included in our internal getFloatv implementation
1384 // because it is stored as a float, despite the fact that the GL ES 2.0 spec names
1385 // GetIntegerv as its native query function. As it would require conversion in any
1386 // case, this should make no difference to the calling application.
1387 switch (pname)
1388 {
1389 case GL_LINE_WIDTH: *params = mState.lineWidth; break;
1390 case GL_SAMPLE_COVERAGE_VALUE: *params = mState.sampleCoverageValue; break;
1391 case GL_DEPTH_CLEAR_VALUE: *params = mState.depthClearValue; break;
1392 case GL_POLYGON_OFFSET_FACTOR: *params = mState.polygonOffsetFactor; break;
1393 case GL_POLYGON_OFFSET_UNITS: *params = mState.polygonOffsetUnits; break;
1394 case GL_ALIASED_LINE_WIDTH_RANGE:
1395 params[0] = gl::ALIASED_LINE_WIDTH_RANGE_MIN;
1396 params[1] = gl::ALIASED_LINE_WIDTH_RANGE_MAX;
1397 break;
1398 case GL_ALIASED_POINT_SIZE_RANGE:
1399 params[0] = gl::ALIASED_POINT_SIZE_RANGE_MIN;
1400 params[1] = getMaximumPointSize();
1401 break;
1402 case GL_DEPTH_RANGE:
1403 params[0] = mState.zNear;
1404 params[1] = mState.zFar;
1405 break;
1406 case GL_COLOR_CLEAR_VALUE:
1407 params[0] = mState.colorClearValue.red;
1408 params[1] = mState.colorClearValue.green;
1409 params[2] = mState.colorClearValue.blue;
1410 params[3] = mState.colorClearValue.alpha;
1411 break;
1412 case GL_BLEND_COLOR:
1413 params[0] = mState.blendColor.red;
1414 params[1] = mState.blendColor.green;
1415 params[2] = mState.blendColor.blue;
1416 params[3] = mState.blendColor.alpha;
1417 break;
daniel@transgaming.com07ab8412012-07-12 15:17:09 +00001418 case GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT:
1419 if (!supportsTextureFilterAnisotropy())
1420 {
1421 return false;
1422 }
1423 *params = mMaxTextureAnisotropy;
1424 break;
apatrick@chromium.org144f2802012-07-12 01:42:34 +00001425 default:
1426 return false;
1427 }
1428
1429 return true;
1430}
1431
1432bool Context::getIntegerv(GLenum pname, GLint *params)
1433{
1434 // Please note: DEPTH_CLEAR_VALUE is not included in our internal getIntegerv implementation
1435 // because it is stored as a float, despite the fact that the GL ES 2.0 spec names
1436 // GetIntegerv as its native query function. As it would require conversion in any
1437 // case, this should make no difference to the calling application. You may find it in
1438 // Context::getFloatv.
1439 switch (pname)
1440 {
1441 case GL_MAX_VERTEX_ATTRIBS: *params = gl::MAX_VERTEX_ATTRIBS; break;
1442 case GL_MAX_VERTEX_UNIFORM_VECTORS: *params = gl::MAX_VERTEX_UNIFORM_VECTORS; break;
1443 case GL_MAX_VARYING_VECTORS: *params = getMaximumVaryingVectors(); break;
1444 case GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS: *params = getMaximumCombinedTextureImageUnits(); break;
1445 case GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS: *params = getMaximumVertexTextureImageUnits(); break;
1446 case GL_MAX_TEXTURE_IMAGE_UNITS: *params = gl::MAX_TEXTURE_IMAGE_UNITS; break;
1447 case GL_MAX_FRAGMENT_UNIFORM_VECTORS: *params = getMaximumFragmentUniformVectors(); break;
1448 case GL_MAX_RENDERBUFFER_SIZE: *params = getMaximumRenderbufferDimension(); break;
1449 case GL_NUM_SHADER_BINARY_FORMATS: *params = 0; break;
1450 case GL_SHADER_BINARY_FORMATS: /* no shader binary formats are supported */ break;
1451 case GL_ARRAY_BUFFER_BINDING: *params = mState.arrayBuffer.id(); break;
1452 case GL_ELEMENT_ARRAY_BUFFER_BINDING: *params = mState.elementArrayBuffer.id(); break;
1453 //case GL_FRAMEBUFFER_BINDING: // now equivalent to GL_DRAW_FRAMEBUFFER_BINDING_ANGLE
1454 case GL_DRAW_FRAMEBUFFER_BINDING_ANGLE: *params = mState.drawFramebuffer; break;
1455 case GL_READ_FRAMEBUFFER_BINDING_ANGLE: *params = mState.readFramebuffer; break;
1456 case GL_RENDERBUFFER_BINDING: *params = mState.renderbuffer.id(); break;
1457 case GL_CURRENT_PROGRAM: *params = mState.currentProgram; break;
1458 case GL_PACK_ALIGNMENT: *params = mState.packAlignment; break;
1459 case GL_PACK_REVERSE_ROW_ORDER_ANGLE: *params = mState.packReverseRowOrder; break;
1460 case GL_UNPACK_ALIGNMENT: *params = mState.unpackAlignment; break;
1461 case GL_GENERATE_MIPMAP_HINT: *params = mState.generateMipmapHint; break;
1462 case GL_FRAGMENT_SHADER_DERIVATIVE_HINT_OES: *params = mState.fragmentShaderDerivativeHint; break;
1463 case GL_ACTIVE_TEXTURE: *params = (mState.activeSampler + GL_TEXTURE0); break;
1464 case GL_STENCIL_FUNC: *params = mState.stencilFunc; break;
1465 case GL_STENCIL_REF: *params = mState.stencilRef; break;
1466 case GL_STENCIL_VALUE_MASK: *params = mState.stencilMask; break;
1467 case GL_STENCIL_BACK_FUNC: *params = mState.stencilBackFunc; break;
1468 case GL_STENCIL_BACK_REF: *params = mState.stencilBackRef; break;
1469 case GL_STENCIL_BACK_VALUE_MASK: *params = mState.stencilBackMask; break;
1470 case GL_STENCIL_FAIL: *params = mState.stencilFail; break;
1471 case GL_STENCIL_PASS_DEPTH_FAIL: *params = mState.stencilPassDepthFail; break;
1472 case GL_STENCIL_PASS_DEPTH_PASS: *params = mState.stencilPassDepthPass; break;
1473 case GL_STENCIL_BACK_FAIL: *params = mState.stencilBackFail; break;
1474 case GL_STENCIL_BACK_PASS_DEPTH_FAIL: *params = mState.stencilBackPassDepthFail; break;
1475 case GL_STENCIL_BACK_PASS_DEPTH_PASS: *params = mState.stencilBackPassDepthPass; break;
1476 case GL_DEPTH_FUNC: *params = mState.depthFunc; break;
1477 case GL_BLEND_SRC_RGB: *params = mState.sourceBlendRGB; break;
1478 case GL_BLEND_SRC_ALPHA: *params = mState.sourceBlendAlpha; break;
1479 case GL_BLEND_DST_RGB: *params = mState.destBlendRGB; break;
1480 case GL_BLEND_DST_ALPHA: *params = mState.destBlendAlpha; break;
1481 case GL_BLEND_EQUATION_RGB: *params = mState.blendEquationRGB; break;
1482 case GL_BLEND_EQUATION_ALPHA: *params = mState.blendEquationAlpha; break;
1483 case GL_STENCIL_WRITEMASK: *params = mState.stencilWritemask; break;
1484 case GL_STENCIL_BACK_WRITEMASK: *params = mState.stencilBackWritemask; break;
1485 case GL_STENCIL_CLEAR_VALUE: *params = mState.stencilClearValue; break;
1486 case GL_SUBPIXEL_BITS: *params = 4; break;
1487 case GL_MAX_TEXTURE_SIZE: *params = getMaximumTextureDimension(); break;
1488 case GL_MAX_CUBE_MAP_TEXTURE_SIZE: *params = getMaximumCubeTextureDimension(); break;
1489 case GL_NUM_COMPRESSED_TEXTURE_FORMATS:
1490 params[0] = mNumCompressedTextureFormats;
1491 break;
1492 case GL_MAX_SAMPLES_ANGLE:
1493 {
1494 GLsizei maxSamples = getMaxSupportedSamples();
1495 if (maxSamples != 0)
1496 {
1497 *params = maxSamples;
1498 }
1499 else
1500 {
1501 return false;
1502 }
1503
1504 break;
1505 }
1506 case GL_SAMPLE_BUFFERS:
1507 case GL_SAMPLES:
1508 {
1509 gl::Framebuffer *framebuffer = getDrawFramebuffer();
1510 if (framebuffer->completeness() == GL_FRAMEBUFFER_COMPLETE)
1511 {
1512 switch (pname)
1513 {
1514 case GL_SAMPLE_BUFFERS:
1515 if (framebuffer->getSamples() != 0)
1516 {
1517 *params = 1;
1518 }
1519 else
1520 {
1521 *params = 0;
1522 }
1523 break;
1524 case GL_SAMPLES:
1525 *params = framebuffer->getSamples();
1526 break;
1527 }
1528 }
1529 else
1530 {
1531 *params = 0;
1532 }
1533 }
1534 break;
daniel@transgaming.com42944b02012-09-27 17:45:57 +00001535 case GL_IMPLEMENTATION_COLOR_READ_TYPE:
1536 case GL_IMPLEMENTATION_COLOR_READ_FORMAT:
1537 {
1538 GLenum format, type;
1539 if (getCurrentReadFormatType(&format, &type))
1540 {
1541 if (pname == GL_IMPLEMENTATION_COLOR_READ_FORMAT)
1542 *params = format;
1543 else
1544 *params = type;
1545 }
1546 }
1547 break;
apatrick@chromium.org144f2802012-07-12 01:42:34 +00001548 case GL_MAX_VIEWPORT_DIMS:
1549 {
1550 int maxDimension = std::max(getMaximumRenderbufferDimension(), getMaximumTextureDimension());
1551 params[0] = maxDimension;
1552 params[1] = maxDimension;
1553 }
1554 break;
1555 case GL_COMPRESSED_TEXTURE_FORMATS:
1556 {
1557 if (supportsDXT1Textures())
1558 {
1559 *params++ = GL_COMPRESSED_RGB_S3TC_DXT1_EXT;
1560 *params++ = GL_COMPRESSED_RGBA_S3TC_DXT1_EXT;
1561 }
1562 if (supportsDXT3Textures())
1563 {
1564 *params++ = GL_COMPRESSED_RGBA_S3TC_DXT3_ANGLE;
1565 }
1566 if (supportsDXT5Textures())
1567 {
1568 *params++ = GL_COMPRESSED_RGBA_S3TC_DXT5_ANGLE;
1569 }
1570 }
1571 break;
1572 case GL_VIEWPORT:
1573 params[0] = mState.viewportX;
1574 params[1] = mState.viewportY;
1575 params[2] = mState.viewportWidth;
1576 params[3] = mState.viewportHeight;
1577 break;
1578 case GL_SCISSOR_BOX:
1579 params[0] = mState.scissorX;
1580 params[1] = mState.scissorY;
1581 params[2] = mState.scissorWidth;
1582 params[3] = mState.scissorHeight;
1583 break;
1584 case GL_CULL_FACE_MODE: *params = mState.cullMode; break;
1585 case GL_FRONT_FACE: *params = mState.frontFace; break;
1586 case GL_RED_BITS:
1587 case GL_GREEN_BITS:
1588 case GL_BLUE_BITS:
1589 case GL_ALPHA_BITS:
1590 {
1591 gl::Framebuffer *framebuffer = getDrawFramebuffer();
1592 gl::Renderbuffer *colorbuffer = framebuffer->getColorbuffer();
1593
1594 if (colorbuffer)
1595 {
1596 switch (pname)
1597 {
1598 case GL_RED_BITS: *params = colorbuffer->getRedSize(); break;
1599 case GL_GREEN_BITS: *params = colorbuffer->getGreenSize(); break;
1600 case GL_BLUE_BITS: *params = colorbuffer->getBlueSize(); break;
1601 case GL_ALPHA_BITS: *params = colorbuffer->getAlphaSize(); break;
1602 }
1603 }
1604 else
1605 {
1606 *params = 0;
1607 }
1608 }
1609 break;
1610 case GL_DEPTH_BITS:
1611 {
1612 gl::Framebuffer *framebuffer = getDrawFramebuffer();
1613 gl::Renderbuffer *depthbuffer = framebuffer->getDepthbuffer();
1614
1615 if (depthbuffer)
1616 {
1617 *params = depthbuffer->getDepthSize();
1618 }
1619 else
1620 {
1621 *params = 0;
1622 }
1623 }
1624 break;
1625 case GL_STENCIL_BITS:
1626 {
1627 gl::Framebuffer *framebuffer = getDrawFramebuffer();
1628 gl::Renderbuffer *stencilbuffer = framebuffer->getStencilbuffer();
1629
1630 if (stencilbuffer)
1631 {
1632 *params = stencilbuffer->getStencilSize();
1633 }
1634 else
1635 {
1636 *params = 0;
1637 }
1638 }
1639 break;
1640 case GL_TEXTURE_BINDING_2D:
1641 {
1642 if (mState.activeSampler < 0 || mState.activeSampler > getMaximumCombinedTextureImageUnits() - 1)
1643 {
1644 error(GL_INVALID_OPERATION);
1645 return false;
1646 }
1647
1648 *params = mState.samplerTexture[TEXTURE_2D][mState.activeSampler].id();
1649 }
1650 break;
1651 case GL_TEXTURE_BINDING_CUBE_MAP:
1652 {
1653 if (mState.activeSampler < 0 || mState.activeSampler > getMaximumCombinedTextureImageUnits() - 1)
1654 {
1655 error(GL_INVALID_OPERATION);
1656 return false;
1657 }
1658
1659 *params = mState.samplerTexture[TEXTURE_CUBE][mState.activeSampler].id();
1660 }
1661 break;
1662 case GL_RESET_NOTIFICATION_STRATEGY_EXT:
1663 *params = mResetStrategy;
1664 break;
1665 case GL_NUM_PROGRAM_BINARY_FORMATS_OES:
1666 *params = 1;
1667 break;
1668 case GL_PROGRAM_BINARY_FORMATS_OES:
1669 *params = GL_PROGRAM_BINARY_ANGLE;
1670 break;
1671 default:
1672 return false;
1673 }
1674
1675 return true;
1676}
1677
1678bool Context::getQueryParameterInfo(GLenum pname, GLenum *type, unsigned int *numParams)
1679{
1680 // Please note: the query type returned for DEPTH_CLEAR_VALUE in this implementation
1681 // is FLOAT rather than INT, as would be suggested by the GL ES 2.0 spec. This is due
1682 // to the fact that it is stored internally as a float, and so would require conversion
1683 // if returned from Context::getIntegerv. Since this conversion is already implemented
1684 // in the case that one calls glGetIntegerv to retrieve a float-typed state variable, we
1685 // place DEPTH_CLEAR_VALUE with the floats. This should make no difference to the calling
1686 // application.
1687 switch (pname)
1688 {
1689 case GL_COMPRESSED_TEXTURE_FORMATS:
1690 {
1691 *type = GL_INT;
1692 *numParams = mNumCompressedTextureFormats;
1693 }
1694 break;
1695 case GL_SHADER_BINARY_FORMATS:
1696 {
1697 *type = GL_INT;
1698 *numParams = 0;
1699 }
1700 break;
1701 case GL_MAX_VERTEX_ATTRIBS:
1702 case GL_MAX_VERTEX_UNIFORM_VECTORS:
1703 case GL_MAX_VARYING_VECTORS:
1704 case GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS:
1705 case GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS:
1706 case GL_MAX_TEXTURE_IMAGE_UNITS:
1707 case GL_MAX_FRAGMENT_UNIFORM_VECTORS:
1708 case GL_MAX_RENDERBUFFER_SIZE:
1709 case GL_NUM_SHADER_BINARY_FORMATS:
1710 case GL_NUM_COMPRESSED_TEXTURE_FORMATS:
1711 case GL_ARRAY_BUFFER_BINDING:
1712 case GL_FRAMEBUFFER_BINDING:
1713 case GL_RENDERBUFFER_BINDING:
1714 case GL_CURRENT_PROGRAM:
1715 case GL_PACK_ALIGNMENT:
1716 case GL_PACK_REVERSE_ROW_ORDER_ANGLE:
1717 case GL_UNPACK_ALIGNMENT:
1718 case GL_GENERATE_MIPMAP_HINT:
1719 case GL_FRAGMENT_SHADER_DERIVATIVE_HINT_OES:
1720 case GL_RED_BITS:
1721 case GL_GREEN_BITS:
1722 case GL_BLUE_BITS:
1723 case GL_ALPHA_BITS:
1724 case GL_DEPTH_BITS:
1725 case GL_STENCIL_BITS:
1726 case GL_ELEMENT_ARRAY_BUFFER_BINDING:
1727 case GL_CULL_FACE_MODE:
1728 case GL_FRONT_FACE:
1729 case GL_ACTIVE_TEXTURE:
1730 case GL_STENCIL_FUNC:
1731 case GL_STENCIL_VALUE_MASK:
1732 case GL_STENCIL_REF:
1733 case GL_STENCIL_FAIL:
1734 case GL_STENCIL_PASS_DEPTH_FAIL:
1735 case GL_STENCIL_PASS_DEPTH_PASS:
1736 case GL_STENCIL_BACK_FUNC:
1737 case GL_STENCIL_BACK_VALUE_MASK:
1738 case GL_STENCIL_BACK_REF:
1739 case GL_STENCIL_BACK_FAIL:
1740 case GL_STENCIL_BACK_PASS_DEPTH_FAIL:
1741 case GL_STENCIL_BACK_PASS_DEPTH_PASS:
1742 case GL_DEPTH_FUNC:
1743 case GL_BLEND_SRC_RGB:
1744 case GL_BLEND_SRC_ALPHA:
1745 case GL_BLEND_DST_RGB:
1746 case GL_BLEND_DST_ALPHA:
1747 case GL_BLEND_EQUATION_RGB:
1748 case GL_BLEND_EQUATION_ALPHA:
1749 case GL_STENCIL_WRITEMASK:
1750 case GL_STENCIL_BACK_WRITEMASK:
1751 case GL_STENCIL_CLEAR_VALUE:
1752 case GL_SUBPIXEL_BITS:
1753 case GL_MAX_TEXTURE_SIZE:
1754 case GL_MAX_CUBE_MAP_TEXTURE_SIZE:
1755 case GL_SAMPLE_BUFFERS:
1756 case GL_SAMPLES:
1757 case GL_IMPLEMENTATION_COLOR_READ_TYPE:
1758 case GL_IMPLEMENTATION_COLOR_READ_FORMAT:
1759 case GL_TEXTURE_BINDING_2D:
1760 case GL_TEXTURE_BINDING_CUBE_MAP:
1761 case GL_RESET_NOTIFICATION_STRATEGY_EXT:
1762 case GL_NUM_PROGRAM_BINARY_FORMATS_OES:
1763 case GL_PROGRAM_BINARY_FORMATS_OES:
1764 {
1765 *type = GL_INT;
1766 *numParams = 1;
1767 }
1768 break;
1769 case GL_MAX_SAMPLES_ANGLE:
1770 {
1771 if (getMaxSupportedSamples() != 0)
1772 {
1773 *type = GL_INT;
1774 *numParams = 1;
1775 }
1776 else
1777 {
1778 return false;
1779 }
1780 }
1781 break;
1782 case GL_MAX_VIEWPORT_DIMS:
1783 {
1784 *type = GL_INT;
1785 *numParams = 2;
1786 }
1787 break;
1788 case GL_VIEWPORT:
1789 case GL_SCISSOR_BOX:
1790 {
1791 *type = GL_INT;
1792 *numParams = 4;
1793 }
1794 break;
1795 case GL_SHADER_COMPILER:
1796 case GL_SAMPLE_COVERAGE_INVERT:
1797 case GL_DEPTH_WRITEMASK:
1798 case GL_CULL_FACE: // CULL_FACE through DITHER are natural to IsEnabled,
1799 case GL_POLYGON_OFFSET_FILL: // but can be retrieved through the Get{Type}v queries.
1800 case GL_SAMPLE_ALPHA_TO_COVERAGE: // For this purpose, they are treated here as bool-natural
1801 case GL_SAMPLE_COVERAGE:
1802 case GL_SCISSOR_TEST:
1803 case GL_STENCIL_TEST:
1804 case GL_DEPTH_TEST:
1805 case GL_BLEND:
1806 case GL_DITHER:
1807 case GL_CONTEXT_ROBUST_ACCESS_EXT:
1808 {
1809 *type = GL_BOOL;
1810 *numParams = 1;
1811 }
1812 break;
1813 case GL_COLOR_WRITEMASK:
1814 {
1815 *type = GL_BOOL;
1816 *numParams = 4;
1817 }
1818 break;
1819 case GL_POLYGON_OFFSET_FACTOR:
1820 case GL_POLYGON_OFFSET_UNITS:
1821 case GL_SAMPLE_COVERAGE_VALUE:
1822 case GL_DEPTH_CLEAR_VALUE:
1823 case GL_LINE_WIDTH:
1824 {
1825 *type = GL_FLOAT;
1826 *numParams = 1;
1827 }
1828 break;
1829 case GL_ALIASED_LINE_WIDTH_RANGE:
1830 case GL_ALIASED_POINT_SIZE_RANGE:
1831 case GL_DEPTH_RANGE:
1832 {
1833 *type = GL_FLOAT;
1834 *numParams = 2;
1835 }
1836 break;
1837 case GL_COLOR_CLEAR_VALUE:
1838 case GL_BLEND_COLOR:
1839 {
1840 *type = GL_FLOAT;
1841 *numParams = 4;
1842 }
1843 break;
daniel@transgaming.com07ab8412012-07-12 15:17:09 +00001844 case GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT:
1845 if (!supportsTextureFilterAnisotropy())
1846 {
1847 return false;
1848 }
1849 *type = GL_FLOAT;
1850 *numParams = 1;
1851 break;
apatrick@chromium.org144f2802012-07-12 01:42:34 +00001852 default:
1853 return false;
1854 }
1855
1856 return true;
1857}
1858
1859// Applies the render target surface, depth stencil surface, viewport rectangle and
1860// scissor rectangle to the Direct3D 9 device
1861bool Context::applyRenderTarget(bool ignoreViewport)
1862{
1863 Framebuffer *framebufferObject = getDrawFramebuffer();
1864
1865 if (!framebufferObject || framebufferObject->completeness() != GL_FRAMEBUFFER_COMPLETE)
1866 {
1867 return error(GL_INVALID_FRAMEBUFFER_OPERATION, false);
1868 }
1869
1870 // if there is no color attachment we must synthesize a NULL colorattachment
1871 // to keep the D3D runtime happy. This should only be possible if depth texturing.
1872 Renderbuffer *renderbufferObject = NULL;
1873 if (framebufferObject->getColorbufferType() != GL_NONE)
1874 {
1875 renderbufferObject = framebufferObject->getColorbuffer();
1876 }
1877 else
1878 {
1879 renderbufferObject = framebufferObject->getNullColorbuffer();
1880 }
1881 if (!renderbufferObject)
1882 {
1883 ERR("unable to locate renderbuffer for FBO.");
1884 return false;
1885 }
1886
1887 bool renderTargetChanged = false;
1888 unsigned int renderTargetSerial = renderbufferObject->getSerial();
1889 if (renderTargetSerial != mAppliedRenderTargetSerial)
1890 {
1891 IDirect3DSurface9 *renderTarget = renderbufferObject->getRenderTarget();
1892 if (!renderTarget)
1893 {
1894 ERR("render target pointer unexpectedly null.");
1895 return false; // Context must be lost
1896 }
1897 mDevice->SetRenderTarget(0, renderTarget);
1898 mAppliedRenderTargetSerial = renderTargetSerial;
1899 mScissorStateDirty = true; // Scissor area must be clamped to render target's size-- this is different for different render targets.
1900 renderTargetChanged = true;
1901 renderTarget->Release();
1902 }
1903
1904 IDirect3DSurface9 *depthStencil = NULL;
1905 unsigned int depthbufferSerial = 0;
1906 unsigned int stencilbufferSerial = 0;
1907 if (framebufferObject->getDepthbufferType() != GL_NONE)
1908 {
1909 Renderbuffer *depthbuffer = framebufferObject->getDepthbuffer();
1910 depthStencil = depthbuffer->getDepthStencil();
1911 if (!depthStencil)
1912 {
1913 ERR("Depth stencil pointer unexpectedly null.");
1914 return false;
1915 }
1916
1917 depthbufferSerial = depthbuffer->getSerial();
1918 }
1919 else if (framebufferObject->getStencilbufferType() != GL_NONE)
1920 {
1921 Renderbuffer *stencilbuffer = framebufferObject->getStencilbuffer();
1922 depthStencil = stencilbuffer->getDepthStencil();
1923 if (!depthStencil)
1924 {
1925 ERR("Depth stencil pointer unexpectedly null.");
1926 return false;
1927 }
1928
1929 stencilbufferSerial = stencilbuffer->getSerial();
1930 }
1931
1932 if (depthbufferSerial != mAppliedDepthbufferSerial ||
1933 stencilbufferSerial != mAppliedStencilbufferSerial ||
1934 !mDepthStencilInitialized)
1935 {
1936 mDevice->SetDepthStencilSurface(depthStencil);
1937 mAppliedDepthbufferSerial = depthbufferSerial;
1938 mAppliedStencilbufferSerial = stencilbufferSerial;
1939 mDepthStencilInitialized = true;
1940 }
1941
1942 if (depthStencil)
1943 {
1944 depthStencil->Release();
1945 }
1946
1947 if (!mRenderTargetDescInitialized || renderTargetChanged)
1948 {
1949 IDirect3DSurface9 *renderTarget = renderbufferObject->getRenderTarget();
1950 if (!renderTarget)
1951 {
1952 return false; // Context must be lost
1953 }
1954 renderTarget->GetDesc(&mRenderTargetDesc);
1955 mRenderTargetDescInitialized = true;
1956 renderTarget->Release();
1957 }
1958
1959 D3DVIEWPORT9 viewport;
1960
1961 float zNear = clamp01(mState.zNear);
1962 float zFar = clamp01(mState.zFar);
1963
1964 if (ignoreViewport)
1965 {
1966 viewport.X = 0;
1967 viewport.Y = 0;
1968 viewport.Width = mRenderTargetDesc.Width;
1969 viewport.Height = mRenderTargetDesc.Height;
1970 viewport.MinZ = 0.0f;
1971 viewport.MaxZ = 1.0f;
1972 }
1973 else
1974 {
1975 viewport.X = clamp(mState.viewportX, 0L, static_cast<LONG>(mRenderTargetDesc.Width));
1976 viewport.Y = clamp(mState.viewportY, 0L, static_cast<LONG>(mRenderTargetDesc.Height));
1977 viewport.Width = clamp(mState.viewportWidth, 0L, static_cast<LONG>(mRenderTargetDesc.Width) - static_cast<LONG>(viewport.X));
1978 viewport.Height = clamp(mState.viewportHeight, 0L, static_cast<LONG>(mRenderTargetDesc.Height) - static_cast<LONG>(viewport.Y));
1979 viewport.MinZ = zNear;
1980 viewport.MaxZ = zFar;
1981 }
1982
1983 if (viewport.Width <= 0 || viewport.Height <= 0)
1984 {
1985 return false; // Nothing to render
1986 }
1987
1988 if (renderTargetChanged || !mViewportInitialized || memcmp(&viewport, &mSetViewport, sizeof mSetViewport) != 0)
1989 {
1990 mDevice->SetViewport(&viewport);
1991 mSetViewport = viewport;
1992 mViewportInitialized = true;
1993 mDxUniformsDirty = true;
1994 }
1995
1996 if (mScissorStateDirty)
1997 {
1998 if (mState.scissorTest)
1999 {
2000 RECT rect;
2001 rect.left = clamp(mState.scissorX, 0L, static_cast<LONG>(mRenderTargetDesc.Width));
2002 rect.top = clamp(mState.scissorY, 0L, static_cast<LONG>(mRenderTargetDesc.Height));
2003 rect.right = clamp(mState.scissorX + mState.scissorWidth, 0L, static_cast<LONG>(mRenderTargetDesc.Width));
2004 rect.bottom = clamp(mState.scissorY + mState.scissorHeight, 0L, static_cast<LONG>(mRenderTargetDesc.Height));
2005 mDevice->SetScissorRect(&rect);
2006 mDevice->SetRenderState(D3DRS_SCISSORTESTENABLE, TRUE);
2007 }
2008 else
2009 {
2010 mDevice->SetRenderState(D3DRS_SCISSORTESTENABLE, FALSE);
2011 }
2012
2013 mScissorStateDirty = false;
2014 }
2015
2016 if (mState.currentProgram && mDxUniformsDirty)
2017 {
daniel@transgaming.com62a28462012-07-24 18:33:59 +00002018 ProgramBinary *programBinary = getCurrentProgramBinary();
apatrick@chromium.org144f2802012-07-12 01:42:34 +00002019
2020 GLint halfPixelSize = programBinary->getDxHalfPixelSizeLocation();
2021 GLfloat xy[2] = {1.0f / viewport.Width, -1.0f / viewport.Height};
2022 programBinary->setUniform2fv(halfPixelSize, 1, xy);
2023
2024 // These values are used for computing gl_FragCoord in Program::linkVaryings().
2025 GLint coord = programBinary->getDxCoordLocation();
2026 GLfloat whxy[4] = {mState.viewportWidth / 2.0f, mState.viewportHeight / 2.0f,
2027 (float)mState.viewportX + mState.viewportWidth / 2.0f,
2028 (float)mState.viewportY + mState.viewportHeight / 2.0f};
2029 programBinary->setUniform4fv(coord, 1, whxy);
2030
2031 GLint depth = programBinary->getDxDepthLocation();
2032 GLfloat dz[2] = {(zFar - zNear) / 2.0f, (zNear + zFar) / 2.0f};
2033 programBinary->setUniform2fv(depth, 1, dz);
2034
2035 GLint depthRange = programBinary->getDxDepthRangeLocation();
2036 GLfloat nearFarDiff[3] = {zNear, zFar, zFar - zNear};
2037 programBinary->setUniform3fv(depthRange, 1, nearFarDiff);
2038 mDxUniformsDirty = false;
2039 }
2040
2041 return true;
2042}
2043
2044// Applies the fixed-function state (culling, depth test, alpha blending, stenciling, etc) to the Direct3D 9 device
2045void Context::applyState(GLenum drawMode)
2046{
daniel@transgaming.com62a28462012-07-24 18:33:59 +00002047 ProgramBinary *programBinary = getCurrentProgramBinary();
apatrick@chromium.org144f2802012-07-12 01:42:34 +00002048
2049 Framebuffer *framebufferObject = getDrawFramebuffer();
2050
2051 GLint frontCCW = programBinary->getDxFrontCCWLocation();
2052 GLint ccw = (mState.frontFace == GL_CCW);
2053 programBinary->setUniform1iv(frontCCW, 1, &ccw);
2054
2055 GLint pointsOrLines = programBinary->getDxPointsOrLinesLocation();
2056 GLint alwaysFront = !isTriangleMode(drawMode);
2057 programBinary->setUniform1iv(pointsOrLines, 1, &alwaysFront);
2058
daniel@transgaming.com4ca789e2012-10-31 18:46:40 +00002059 bool zeroColorMaskAllowed = mRenderer->getAdapterVendor() != VENDOR_ID_AMD;
apatrick@chromium.org144f2802012-07-12 01:42:34 +00002060 // Apparently some ATI cards have a bug where a draw with a zero color
2061 // write mask can cause later draws to have incorrect results. Instead,
2062 // set a nonzero color write mask but modify the blend state so that no
2063 // drawing is done.
2064 // http://code.google.com/p/angleproject/issues/detail?id=169
2065
2066 if (mCullStateDirty || mFrontFaceDirty)
2067 {
2068 if (mState.cullFace)
2069 {
2070 mDevice->SetRenderState(D3DRS_CULLMODE, es2dx::ConvertCullMode(mState.cullMode, mState.frontFace));
2071 }
2072 else
2073 {
2074 mDevice->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE);
2075 }
2076
2077 mCullStateDirty = false;
2078 }
2079
2080 if (mDepthStateDirty)
2081 {
2082 if (mState.depthTest)
2083 {
2084 mDevice->SetRenderState(D3DRS_ZENABLE, D3DZB_TRUE);
2085 mDevice->SetRenderState(D3DRS_ZFUNC, es2dx::ConvertComparison(mState.depthFunc));
2086 }
2087 else
2088 {
2089 mDevice->SetRenderState(D3DRS_ZENABLE, D3DZB_FALSE);
2090 }
2091
2092 mDepthStateDirty = false;
2093 }
2094
2095 if (!zeroColorMaskAllowed && (mMaskStateDirty || mBlendStateDirty))
2096 {
2097 mBlendStateDirty = true;
2098 mMaskStateDirty = true;
2099 }
2100
2101 if (mBlendStateDirty)
2102 {
2103 if (mState.blend)
2104 {
2105 mDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, TRUE);
2106
2107 if (mState.sourceBlendRGB != GL_CONSTANT_ALPHA && mState.sourceBlendRGB != GL_ONE_MINUS_CONSTANT_ALPHA &&
2108 mState.destBlendRGB != GL_CONSTANT_ALPHA && mState.destBlendRGB != GL_ONE_MINUS_CONSTANT_ALPHA)
2109 {
2110 mDevice->SetRenderState(D3DRS_BLENDFACTOR, es2dx::ConvertColor(mState.blendColor));
2111 }
2112 else
2113 {
2114 mDevice->SetRenderState(D3DRS_BLENDFACTOR, D3DCOLOR_RGBA(unorm<8>(mState.blendColor.alpha),
2115 unorm<8>(mState.blendColor.alpha),
2116 unorm<8>(mState.blendColor.alpha),
2117 unorm<8>(mState.blendColor.alpha)));
2118 }
2119
2120 mDevice->SetRenderState(D3DRS_SRCBLEND, es2dx::ConvertBlendFunc(mState.sourceBlendRGB));
2121 mDevice->SetRenderState(D3DRS_DESTBLEND, es2dx::ConvertBlendFunc(mState.destBlendRGB));
2122 mDevice->SetRenderState(D3DRS_BLENDOP, es2dx::ConvertBlendOp(mState.blendEquationRGB));
2123
2124 if (mState.sourceBlendRGB != mState.sourceBlendAlpha ||
2125 mState.destBlendRGB != mState.destBlendAlpha ||
2126 mState.blendEquationRGB != mState.blendEquationAlpha)
2127 {
2128 mDevice->SetRenderState(D3DRS_SEPARATEALPHABLENDENABLE, TRUE);
2129
2130 mDevice->SetRenderState(D3DRS_SRCBLENDALPHA, es2dx::ConvertBlendFunc(mState.sourceBlendAlpha));
2131 mDevice->SetRenderState(D3DRS_DESTBLENDALPHA, es2dx::ConvertBlendFunc(mState.destBlendAlpha));
2132 mDevice->SetRenderState(D3DRS_BLENDOPALPHA, es2dx::ConvertBlendOp(mState.blendEquationAlpha));
2133 }
2134 else
2135 {
2136 mDevice->SetRenderState(D3DRS_SEPARATEALPHABLENDENABLE, FALSE);
2137 }
2138 }
2139 else
2140 {
2141 mDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, FALSE);
2142 }
2143
2144 mBlendStateDirty = false;
2145 }
2146
2147 if (mStencilStateDirty || mFrontFaceDirty)
2148 {
2149 if (mState.stencilTest && framebufferObject->hasStencil())
2150 {
2151 mDevice->SetRenderState(D3DRS_STENCILENABLE, TRUE);
2152 mDevice->SetRenderState(D3DRS_TWOSIDEDSTENCILMODE, TRUE);
2153
2154 // FIXME: Unsupported by D3D9
2155 const D3DRENDERSTATETYPE D3DRS_CCW_STENCILREF = D3DRS_STENCILREF;
2156 const D3DRENDERSTATETYPE D3DRS_CCW_STENCILMASK = D3DRS_STENCILMASK;
2157 const D3DRENDERSTATETYPE D3DRS_CCW_STENCILWRITEMASK = D3DRS_STENCILWRITEMASK;
2158 if (mState.stencilWritemask != mState.stencilBackWritemask ||
2159 mState.stencilRef != mState.stencilBackRef ||
2160 mState.stencilMask != mState.stencilBackMask)
2161 {
2162 ERR("Separate front/back stencil writemasks, reference values, or stencil mask values are invalid under WebGL.");
2163 return error(GL_INVALID_OPERATION);
2164 }
2165
2166 // get the maximum size of the stencil ref
2167 gl::Renderbuffer *stencilbuffer = framebufferObject->getStencilbuffer();
2168 GLuint maxStencil = (1 << stencilbuffer->getStencilSize()) - 1;
2169
2170 mDevice->SetRenderState(mState.frontFace == GL_CCW ? D3DRS_STENCILWRITEMASK : D3DRS_CCW_STENCILWRITEMASK, mState.stencilWritemask);
2171 mDevice->SetRenderState(mState.frontFace == GL_CCW ? D3DRS_STENCILFUNC : D3DRS_CCW_STENCILFUNC,
2172 es2dx::ConvertComparison(mState.stencilFunc));
2173
2174 mDevice->SetRenderState(mState.frontFace == GL_CCW ? D3DRS_STENCILREF : D3DRS_CCW_STENCILREF, (mState.stencilRef < (GLint)maxStencil) ? mState.stencilRef : maxStencil);
2175 mDevice->SetRenderState(mState.frontFace == GL_CCW ? D3DRS_STENCILMASK : D3DRS_CCW_STENCILMASK, mState.stencilMask);
2176
2177 mDevice->SetRenderState(mState.frontFace == GL_CCW ? D3DRS_STENCILFAIL : D3DRS_CCW_STENCILFAIL,
2178 es2dx::ConvertStencilOp(mState.stencilFail));
2179 mDevice->SetRenderState(mState.frontFace == GL_CCW ? D3DRS_STENCILZFAIL : D3DRS_CCW_STENCILZFAIL,
2180 es2dx::ConvertStencilOp(mState.stencilPassDepthFail));
2181 mDevice->SetRenderState(mState.frontFace == GL_CCW ? D3DRS_STENCILPASS : D3DRS_CCW_STENCILPASS,
2182 es2dx::ConvertStencilOp(mState.stencilPassDepthPass));
2183
2184 mDevice->SetRenderState(mState.frontFace == GL_CW ? D3DRS_STENCILWRITEMASK : D3DRS_CCW_STENCILWRITEMASK, mState.stencilBackWritemask);
2185 mDevice->SetRenderState(mState.frontFace == GL_CW ? D3DRS_STENCILFUNC : D3DRS_CCW_STENCILFUNC,
2186 es2dx::ConvertComparison(mState.stencilBackFunc));
2187
2188 mDevice->SetRenderState(mState.frontFace == GL_CW ? D3DRS_STENCILREF : D3DRS_CCW_STENCILREF, (mState.stencilBackRef < (GLint)maxStencil) ? mState.stencilBackRef : maxStencil);
2189 mDevice->SetRenderState(mState.frontFace == GL_CW ? D3DRS_STENCILMASK : D3DRS_CCW_STENCILMASK, mState.stencilBackMask);
2190
2191 mDevice->SetRenderState(mState.frontFace == GL_CW ? D3DRS_STENCILFAIL : D3DRS_CCW_STENCILFAIL,
2192 es2dx::ConvertStencilOp(mState.stencilBackFail));
2193 mDevice->SetRenderState(mState.frontFace == GL_CW ? D3DRS_STENCILZFAIL : D3DRS_CCW_STENCILZFAIL,
2194 es2dx::ConvertStencilOp(mState.stencilBackPassDepthFail));
2195 mDevice->SetRenderState(mState.frontFace == GL_CW ? D3DRS_STENCILPASS : D3DRS_CCW_STENCILPASS,
2196 es2dx::ConvertStencilOp(mState.stencilBackPassDepthPass));
2197 }
2198 else
2199 {
2200 mDevice->SetRenderState(D3DRS_STENCILENABLE, FALSE);
2201 }
2202
2203 mStencilStateDirty = false;
2204 mFrontFaceDirty = false;
2205 }
2206
2207 if (mMaskStateDirty)
2208 {
2209 int colorMask = es2dx::ConvertColorMask(mState.colorMaskRed, mState.colorMaskGreen,
2210 mState.colorMaskBlue, mState.colorMaskAlpha);
2211 if (colorMask == 0 && !zeroColorMaskAllowed)
2212 {
2213 // Enable green channel, but set blending so nothing will be drawn.
2214 mDevice->SetRenderState(D3DRS_COLORWRITEENABLE, D3DCOLORWRITEENABLE_GREEN);
2215 mDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, TRUE);
2216
2217 mDevice->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_ZERO);
2218 mDevice->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_ONE);
2219 mDevice->SetRenderState(D3DRS_BLENDOP, D3DBLENDOP_ADD);
2220 }
2221 else
2222 {
2223 mDevice->SetRenderState(D3DRS_COLORWRITEENABLE, colorMask);
2224 }
2225 mDevice->SetRenderState(D3DRS_ZWRITEENABLE, mState.depthMask ? TRUE : FALSE);
2226
2227 mMaskStateDirty = false;
2228 }
2229
2230 if (mPolygonOffsetStateDirty)
2231 {
2232 if (mState.polygonOffsetFill)
2233 {
2234 gl::Renderbuffer *depthbuffer = framebufferObject->getDepthbuffer();
2235 if (depthbuffer)
2236 {
2237 mDevice->SetRenderState(D3DRS_SLOPESCALEDEPTHBIAS, *((DWORD*)&mState.polygonOffsetFactor));
2238 float depthBias = ldexp(mState.polygonOffsetUnits, -(int)(depthbuffer->getDepthSize()));
2239 mDevice->SetRenderState(D3DRS_DEPTHBIAS, *((DWORD*)&depthBias));
2240 }
2241 }
2242 else
2243 {
2244 mDevice->SetRenderState(D3DRS_SLOPESCALEDEPTHBIAS, 0);
2245 mDevice->SetRenderState(D3DRS_DEPTHBIAS, 0);
2246 }
2247
2248 mPolygonOffsetStateDirty = false;
2249 }
2250
2251 if (mSampleStateDirty)
2252 {
2253 if (mState.sampleAlphaToCoverage)
2254 {
2255 FIXME("Sample alpha to coverage is unimplemented.");
2256 }
2257
2258 mDevice->SetRenderState(D3DRS_MULTISAMPLEANTIALIAS, TRUE);
2259 if (mState.sampleCoverage)
2260 {
2261 unsigned int mask = 0;
2262 if (mState.sampleCoverageValue != 0)
2263 {
2264 float threshold = 0.5f;
2265
2266 for (int i = 0; i < framebufferObject->getSamples(); ++i)
2267 {
2268 mask <<= 1;
2269
2270 if ((i + 1) * mState.sampleCoverageValue >= threshold)
2271 {
2272 threshold += 1.0f;
2273 mask |= 1;
2274 }
2275 }
2276 }
2277
2278 if (mState.sampleCoverageInvert)
2279 {
2280 mask = ~mask;
2281 }
2282
2283 mDevice->SetRenderState(D3DRS_MULTISAMPLEMASK, mask);
2284 }
2285 else
2286 {
2287 mDevice->SetRenderState(D3DRS_MULTISAMPLEMASK, 0xFFFFFFFF);
2288 }
2289
2290 mSampleStateDirty = false;
2291 }
2292
2293 if (mDitherStateDirty)
2294 {
2295 mDevice->SetRenderState(D3DRS_DITHERENABLE, mState.dither ? TRUE : FALSE);
2296
2297 mDitherStateDirty = false;
2298 }
2299}
2300
2301GLenum Context::applyVertexBuffer(GLint first, GLsizei count, GLsizei instances, GLsizei *repeatDraw)
2302{
2303 TranslatedAttribute attributes[MAX_VERTEX_ATTRIBS];
2304
2305 GLenum err = mVertexDataManager->prepareVertexData(first, count, attributes, instances);
2306 if (err != GL_NO_ERROR)
2307 {
2308 return err;
2309 }
2310
daniel@transgaming.com62a28462012-07-24 18:33:59 +00002311 ProgramBinary *programBinary = getCurrentProgramBinary();
daniel@transgaming.com5ae3ccc2012-07-24 18:29:38 +00002312 return mVertexDeclarationCache.applyDeclaration(mDevice, attributes, programBinary, instances, repeatDraw);
apatrick@chromium.org144f2802012-07-12 01:42:34 +00002313}
2314
2315// Applies the indices and element array bindings to the Direct3D 9 device
2316GLenum Context::applyIndexBuffer(const GLvoid *indices, GLsizei count, GLenum mode, GLenum type, TranslatedIndexData *indexInfo)
2317{
2318 GLenum err = mIndexDataManager->prepareIndexData(type, count, mState.elementArrayBuffer.get(), indices, indexInfo);
2319
2320 if (err == GL_NO_ERROR)
2321 {
2322 if (indexInfo->serial != mAppliedIBSerial)
2323 {
2324 mDevice->SetIndices(indexInfo->indexBuffer);
2325 mAppliedIBSerial = indexInfo->serial;
2326 }
2327 }
2328
2329 return err;
2330}
2331
2332// Applies the shaders and shader constants to the Direct3D 9 device
2333void Context::applyShaders()
2334{
daniel@transgaming.com62a28462012-07-24 18:33:59 +00002335 ProgramBinary *programBinary = getCurrentProgramBinary();
apatrick@chromium.org144f2802012-07-12 01:42:34 +00002336
daniel@transgaming.come6af4f92012-07-24 18:31:31 +00002337 if (programBinary->getSerial() != mAppliedProgramBinarySerial)
apatrick@chromium.org144f2802012-07-12 01:42:34 +00002338 {
2339 IDirect3DVertexShader9 *vertexShader = programBinary->getVertexShader();
2340 IDirect3DPixelShader9 *pixelShader = programBinary->getPixelShader();
2341
2342 mDevice->SetPixelShader(pixelShader);
2343 mDevice->SetVertexShader(vertexShader);
2344 programBinary->dirtyAllUniforms();
daniel@transgaming.come6af4f92012-07-24 18:31:31 +00002345 mAppliedProgramBinarySerial = programBinary->getSerial();
apatrick@chromium.org144f2802012-07-12 01:42:34 +00002346 }
2347
2348 programBinary->applyUniforms();
2349}
2350
2351// Applies the textures and sampler states to the Direct3D 9 device
2352void Context::applyTextures()
2353{
2354 applyTextures(SAMPLER_PIXEL);
2355
2356 if (mSupportsVertexTexture)
2357 {
2358 applyTextures(SAMPLER_VERTEX);
2359 }
2360}
2361
2362// For each Direct3D 9 sampler of either the pixel or vertex stage,
2363// looks up the corresponding OpenGL texture image unit and texture type,
2364// and sets the texture and its addressing/filtering state (or NULL when inactive).
2365void Context::applyTextures(SamplerType type)
2366{
daniel@transgaming.com62a28462012-07-24 18:33:59 +00002367 ProgramBinary *programBinary = getCurrentProgramBinary();
apatrick@chromium.org144f2802012-07-12 01:42:34 +00002368
2369 int samplerCount = (type == SAMPLER_PIXEL) ? MAX_TEXTURE_IMAGE_UNITS : MAX_VERTEX_TEXTURE_IMAGE_UNITS_VTF; // Range of Direct3D 9 samplers of given sampler type
2370 unsigned int *appliedTextureSerial = (type == SAMPLER_PIXEL) ? mAppliedTextureSerialPS : mAppliedTextureSerialVS;
apatrick@chromium.org144f2802012-07-12 01:42:34 +00002371 int samplerRange = programBinary->getUsedSamplerRange(type);
2372
2373 for (int samplerIndex = 0; samplerIndex < samplerRange; samplerIndex++)
2374 {
2375 int textureUnit = programBinary->getSamplerMapping(type, samplerIndex); // OpenGL texture image unit index
apatrick@chromium.org144f2802012-07-12 01:42:34 +00002376
2377 if (textureUnit != -1)
2378 {
2379 TextureType textureType = programBinary->getSamplerTextureType(type, samplerIndex);
2380
2381 Texture *texture = getSamplerTexture(textureUnit, textureType);
2382 unsigned int texSerial = texture->getTextureSerial();
2383
2384 if (appliedTextureSerial[samplerIndex] != texSerial || texture->hasDirtyParameters() || texture->hasDirtyImages())
2385 {
daniel@transgaming.coma734f272012-10-31 18:07:48 +00002386 if (texture->isSamplerComplete())
apatrick@chromium.org144f2802012-07-12 01:42:34 +00002387 {
2388 if (appliedTextureSerial[samplerIndex] != texSerial || texture->hasDirtyParameters())
2389 {
daniel@transgaming.comebf139f2012-10-31 18:07:32 +00002390 SamplerState samplerState;
2391 texture->getSamplerState(&samplerState);
apatrick@chromium.org144f2802012-07-12 01:42:34 +00002392
daniel@transgaming.comba0570e2012-10-31 18:07:39 +00002393 mRenderer->setSamplerState(type, samplerIndex, samplerState);
apatrick@chromium.org144f2802012-07-12 01:42:34 +00002394 }
2395
2396 if (appliedTextureSerial[samplerIndex] != texSerial || texture->hasDirtyImages())
2397 {
daniel@transgaming.coma734f272012-10-31 18:07:48 +00002398 mRenderer->setTexture(type, samplerIndex, texture);
apatrick@chromium.org144f2802012-07-12 01:42:34 +00002399 }
2400 }
2401 else
2402 {
daniel@transgaming.coma734f272012-10-31 18:07:48 +00002403 mRenderer->setTexture(type, samplerIndex, getIncompleteTexture(textureType));
apatrick@chromium.org144f2802012-07-12 01:42:34 +00002404 }
2405
2406 appliedTextureSerial[samplerIndex] = texSerial;
2407 texture->resetDirty();
2408 }
2409 }
2410 else
2411 {
2412 if (appliedTextureSerial[samplerIndex] != 0)
2413 {
daniel@transgaming.coma734f272012-10-31 18:07:48 +00002414 mRenderer->setTexture(type, samplerIndex, NULL);
apatrick@chromium.org144f2802012-07-12 01:42:34 +00002415 appliedTextureSerial[samplerIndex] = 0;
2416 }
2417 }
2418 }
2419
2420 for (int samplerIndex = samplerRange; samplerIndex < samplerCount; samplerIndex++)
2421 {
2422 if (appliedTextureSerial[samplerIndex] != 0)
2423 {
daniel@transgaming.coma734f272012-10-31 18:07:48 +00002424 mRenderer->setTexture(type, samplerIndex, NULL);
apatrick@chromium.org144f2802012-07-12 01:42:34 +00002425 appliedTextureSerial[samplerIndex] = 0;
2426 }
2427 }
2428}
2429
2430void Context::readPixels(GLint x, GLint y, GLsizei width, GLsizei height,
2431 GLenum format, GLenum type, GLsizei *bufSize, void* pixels)
2432{
2433 Framebuffer *framebuffer = getReadFramebuffer();
2434
2435 if (framebuffer->completeness() != GL_FRAMEBUFFER_COMPLETE)
2436 {
2437 return error(GL_INVALID_FRAMEBUFFER_OPERATION);
2438 }
2439
2440 if (getReadFramebufferHandle() != 0 && framebuffer->getSamples() != 0)
2441 {
2442 return error(GL_INVALID_OPERATION);
2443 }
2444
daniel@transgaming.com6452adf2012-10-17 18:22:35 +00002445 GLsizei outputPitch = ComputePitch(width, ConvertSizedInternalFormat(format, type), mState.packAlignment);
apatrick@chromium.org144f2802012-07-12 01:42:34 +00002446 // sized query sanity check
2447 if (bufSize)
2448 {
2449 int requiredSize = outputPitch * height;
2450 if (requiredSize > *bufSize)
2451 {
2452 return error(GL_INVALID_OPERATION);
2453 }
2454 }
2455
2456 IDirect3DSurface9 *renderTarget = framebuffer->getRenderTarget();
2457 if (!renderTarget)
2458 {
2459 return; // Context must be lost, return silently
2460 }
2461
2462 D3DSURFACE_DESC desc;
2463 renderTarget->GetDesc(&desc);
2464
2465 if (desc.MultiSampleType != D3DMULTISAMPLE_NONE)
2466 {
2467 UNIMPLEMENTED(); // FIXME: Requires resolve using StretchRect into non-multisampled render target
2468 renderTarget->Release();
2469 return error(GL_OUT_OF_MEMORY);
2470 }
2471
2472 HRESULT result;
2473 IDirect3DSurface9 *systemSurface = NULL;
daniel@transgaming.com7cb796e2012-10-31 18:46:44 +00002474 bool directToPixels = !getPackReverseRowOrder() && getPackAlignment() <= 4 && mRenderer->getShareHandleSupport() &&
apatrick@chromium.org144f2802012-07-12 01:42:34 +00002475 x == 0 && y == 0 && UINT(width) == desc.Width && UINT(height) == desc.Height &&
2476 desc.Format == D3DFMT_A8R8G8B8 && format == GL_BGRA_EXT && type == GL_UNSIGNED_BYTE;
2477 if (directToPixels)
2478 {
2479 // Use the pixels ptr as a shared handle to write directly into client's memory
2480 result = mDevice->CreateOffscreenPlainSurface(desc.Width, desc.Height, desc.Format,
2481 D3DPOOL_SYSTEMMEM, &systemSurface, &pixels);
2482 if (FAILED(result))
2483 {
2484 // Try again without the shared handle
2485 directToPixels = false;
2486 }
2487 }
2488
2489 if (!directToPixels)
2490 {
2491 result = mDevice->CreateOffscreenPlainSurface(desc.Width, desc.Height, desc.Format,
2492 D3DPOOL_SYSTEMMEM, &systemSurface, NULL);
2493 if (FAILED(result))
2494 {
2495 ASSERT(result == D3DERR_OUTOFVIDEOMEMORY || result == E_OUTOFMEMORY);
2496 renderTarget->Release();
2497 return error(GL_OUT_OF_MEMORY);
2498 }
2499 }
2500
2501 result = mDevice->GetRenderTargetData(renderTarget, systemSurface);
2502 renderTarget->Release();
2503 renderTarget = NULL;
2504
2505 if (FAILED(result))
2506 {
2507 systemSurface->Release();
2508
2509 // It turns out that D3D will sometimes produce more error
2510 // codes than those documented.
2511 if (checkDeviceLost(result))
2512 return error(GL_OUT_OF_MEMORY);
2513 else
2514 {
2515 UNREACHABLE();
2516 return;
2517 }
2518
2519 }
2520
2521 if (directToPixels)
2522 {
2523 systemSurface->Release();
2524 return;
2525 }
2526
2527 RECT rect;
2528 rect.left = clamp(x, 0L, static_cast<LONG>(desc.Width));
2529 rect.top = clamp(y, 0L, static_cast<LONG>(desc.Height));
2530 rect.right = clamp(x + width, 0L, static_cast<LONG>(desc.Width));
2531 rect.bottom = clamp(y + height, 0L, static_cast<LONG>(desc.Height));
2532
2533 D3DLOCKED_RECT lock;
2534 result = systemSurface->LockRect(&lock, &rect, D3DLOCK_READONLY);
2535
2536 if (FAILED(result))
2537 {
2538 UNREACHABLE();
2539 systemSurface->Release();
2540
2541 return; // No sensible error to generate
2542 }
2543
2544 unsigned char *dest = (unsigned char*)pixels;
2545 unsigned short *dest16 = (unsigned short*)pixels;
2546
2547 unsigned char *source;
2548 int inputPitch;
2549 if (getPackReverseRowOrder())
2550 {
2551 source = ((unsigned char*)lock.pBits) + lock.Pitch * (rect.bottom - rect.top - 1);
2552 inputPitch = -lock.Pitch;
2553 }
2554 else
2555 {
2556 source = (unsigned char*)lock.pBits;
2557 inputPitch = lock.Pitch;
2558 }
2559
daniel@transgaming.com42944b02012-09-27 17:45:57 +00002560 unsigned int fastPixelSize = 0;
2561
2562 if (desc.Format == D3DFMT_A8R8G8B8 &&
2563 format == GL_BGRA_EXT &&
2564 type == GL_UNSIGNED_BYTE)
2565 {
2566 fastPixelSize = 4;
2567 }
2568 else if ((desc.Format == D3DFMT_A4R4G4B4 &&
2569 format == GL_BGRA_EXT &&
2570 type == GL_UNSIGNED_SHORT_4_4_4_4_REV_EXT) ||
2571 (desc.Format == D3DFMT_A1R5G5B5 &&
2572 format == GL_BGRA_EXT &&
2573 type == GL_UNSIGNED_SHORT_1_5_5_5_REV_EXT))
2574 {
2575 fastPixelSize = 2;
2576 }
2577 else if (desc.Format == D3DFMT_A16B16G16R16F &&
2578 format == GL_RGBA &&
2579 type == GL_HALF_FLOAT_OES)
2580 {
2581 fastPixelSize = 8;
2582 }
2583 else if (desc.Format == D3DFMT_A32B32G32R32F &&
2584 format == GL_RGBA &&
2585 type == GL_FLOAT)
2586 {
2587 fastPixelSize = 16;
2588 }
2589
apatrick@chromium.org144f2802012-07-12 01:42:34 +00002590 for (int j = 0; j < rect.bottom - rect.top; j++)
2591 {
daniel@transgaming.com42944b02012-09-27 17:45:57 +00002592 if (fastPixelSize != 0)
apatrick@chromium.org144f2802012-07-12 01:42:34 +00002593 {
daniel@transgaming.com42944b02012-09-27 17:45:57 +00002594 // Fast path for formats which require no translation:
2595 // D3DFMT_A8R8G8B8 to BGRA/UNSIGNED_BYTE
2596 // D3DFMT_A4R4G4B4 to BGRA/UNSIGNED_SHORT_4_4_4_4_REV_EXT
2597 // D3DFMT_A1R5G5B5 to BGRA/UNSIGNED_SHORT_1_5_5_5_REV_EXT
2598 // D3DFMT_A16B16G16R16F to RGBA/HALF_FLOAT_OES
2599 // D3DFMT_A32B32G32R32F to RGBA/FLOAT
2600 //
2601 // Note that buffers with no alpha go through the slow path below.
apatrick@chromium.org144f2802012-07-12 01:42:34 +00002602 memcpy(dest + j * outputPitch,
2603 source + j * inputPitch,
daniel@transgaming.com42944b02012-09-27 17:45:57 +00002604 (rect.right - rect.left) * fastPixelSize);
apatrick@chromium.org144f2802012-07-12 01:42:34 +00002605 continue;
2606 }
2607
2608 for (int i = 0; i < rect.right - rect.left; i++)
2609 {
2610 float r;
2611 float g;
2612 float b;
2613 float a;
2614
2615 switch (desc.Format)
2616 {
2617 case D3DFMT_R5G6B5:
2618 {
2619 unsigned short rgb = *(unsigned short*)(source + 2 * i + j * inputPitch);
2620
2621 a = 1.0f;
2622 b = (rgb & 0x001F) * (1.0f / 0x001F);
2623 g = (rgb & 0x07E0) * (1.0f / 0x07E0);
2624 r = (rgb & 0xF800) * (1.0f / 0xF800);
2625 }
2626 break;
2627 case D3DFMT_A1R5G5B5:
2628 {
2629 unsigned short argb = *(unsigned short*)(source + 2 * i + j * inputPitch);
2630
2631 a = (argb & 0x8000) ? 1.0f : 0.0f;
2632 b = (argb & 0x001F) * (1.0f / 0x001F);
2633 g = (argb & 0x03E0) * (1.0f / 0x03E0);
2634 r = (argb & 0x7C00) * (1.0f / 0x7C00);
2635 }
2636 break;
2637 case D3DFMT_A8R8G8B8:
2638 {
2639 unsigned int argb = *(unsigned int*)(source + 4 * i + j * inputPitch);
2640
2641 a = (argb & 0xFF000000) * (1.0f / 0xFF000000);
2642 b = (argb & 0x000000FF) * (1.0f / 0x000000FF);
2643 g = (argb & 0x0000FF00) * (1.0f / 0x0000FF00);
2644 r = (argb & 0x00FF0000) * (1.0f / 0x00FF0000);
2645 }
2646 break;
2647 case D3DFMT_X8R8G8B8:
2648 {
2649 unsigned int xrgb = *(unsigned int*)(source + 4 * i + j * inputPitch);
2650
2651 a = 1.0f;
2652 b = (xrgb & 0x000000FF) * (1.0f / 0x000000FF);
2653 g = (xrgb & 0x0000FF00) * (1.0f / 0x0000FF00);
2654 r = (xrgb & 0x00FF0000) * (1.0f / 0x00FF0000);
2655 }
2656 break;
2657 case D3DFMT_A2R10G10B10:
2658 {
2659 unsigned int argb = *(unsigned int*)(source + 4 * i + j * inputPitch);
2660
2661 a = (argb & 0xC0000000) * (1.0f / 0xC0000000);
2662 b = (argb & 0x000003FF) * (1.0f / 0x000003FF);
2663 g = (argb & 0x000FFC00) * (1.0f / 0x000FFC00);
2664 r = (argb & 0x3FF00000) * (1.0f / 0x3FF00000);
2665 }
2666 break;
2667 case D3DFMT_A32B32G32R32F:
2668 {
2669 // float formats in D3D are stored rgba, rather than the other way round
2670 r = *((float*)(source + 16 * i + j * inputPitch) + 0);
2671 g = *((float*)(source + 16 * i + j * inputPitch) + 1);
2672 b = *((float*)(source + 16 * i + j * inputPitch) + 2);
2673 a = *((float*)(source + 16 * i + j * inputPitch) + 3);
2674 }
2675 break;
2676 case D3DFMT_A16B16G16R16F:
2677 {
2678 // float formats in D3D are stored rgba, rather than the other way round
apatrick@chromium.orgaa480672012-09-05 19:32:38 +00002679 r = float16ToFloat32(*((unsigned short*)(source + 8 * i + j * inputPitch) + 0));
2680 g = float16ToFloat32(*((unsigned short*)(source + 8 * i + j * inputPitch) + 1));
2681 b = float16ToFloat32(*((unsigned short*)(source + 8 * i + j * inputPitch) + 2));
2682 a = float16ToFloat32(*((unsigned short*)(source + 8 * i + j * inputPitch) + 3));
apatrick@chromium.org144f2802012-07-12 01:42:34 +00002683 }
2684 break;
2685 default:
2686 UNIMPLEMENTED(); // FIXME
2687 UNREACHABLE();
2688 return;
2689 }
2690
2691 switch (format)
2692 {
2693 case GL_RGBA:
2694 switch (type)
2695 {
2696 case GL_UNSIGNED_BYTE:
2697 dest[4 * i + j * outputPitch + 0] = (unsigned char)(255 * r + 0.5f);
2698 dest[4 * i + j * outputPitch + 1] = (unsigned char)(255 * g + 0.5f);
2699 dest[4 * i + j * outputPitch + 2] = (unsigned char)(255 * b + 0.5f);
2700 dest[4 * i + j * outputPitch + 3] = (unsigned char)(255 * a + 0.5f);
2701 break;
2702 default: UNREACHABLE();
2703 }
2704 break;
2705 case GL_BGRA_EXT:
2706 switch (type)
2707 {
2708 case GL_UNSIGNED_BYTE:
2709 dest[4 * i + j * outputPitch + 0] = (unsigned char)(255 * b + 0.5f);
2710 dest[4 * i + j * outputPitch + 1] = (unsigned char)(255 * g + 0.5f);
2711 dest[4 * i + j * outputPitch + 2] = (unsigned char)(255 * r + 0.5f);
2712 dest[4 * i + j * outputPitch + 3] = (unsigned char)(255 * a + 0.5f);
2713 break;
2714 case GL_UNSIGNED_SHORT_4_4_4_4_REV_EXT:
2715 // According to the desktop GL spec in the "Transfer of Pixel Rectangles" section
2716 // this type is packed as follows:
2717 // 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0
2718 // --------------------------------------------------------------------------------
2719 // | 4th | 3rd | 2nd | 1st component |
2720 // --------------------------------------------------------------------------------
2721 // in the case of BGRA_EXT, B is the first component, G the second, and so forth.
2722 dest16[i + j * outputPitch / sizeof(unsigned short)] =
2723 ((unsigned short)(15 * a + 0.5f) << 12)|
2724 ((unsigned short)(15 * r + 0.5f) << 8) |
2725 ((unsigned short)(15 * g + 0.5f) << 4) |
2726 ((unsigned short)(15 * b + 0.5f) << 0);
2727 break;
2728 case GL_UNSIGNED_SHORT_1_5_5_5_REV_EXT:
2729 // According to the desktop GL spec in the "Transfer of Pixel Rectangles" section
2730 // this type is packed as follows:
2731 // 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0
2732 // --------------------------------------------------------------------------------
2733 // | 4th | 3rd | 2nd | 1st component |
2734 // --------------------------------------------------------------------------------
2735 // in the case of BGRA_EXT, B is the first component, G the second, and so forth.
2736 dest16[i + j * outputPitch / sizeof(unsigned short)] =
2737 ((unsigned short)( a + 0.5f) << 15) |
2738 ((unsigned short)(31 * r + 0.5f) << 10) |
2739 ((unsigned short)(31 * g + 0.5f) << 5) |
2740 ((unsigned short)(31 * b + 0.5f) << 0);
2741 break;
2742 default: UNREACHABLE();
2743 }
2744 break;
daniel@transgaming.com42944b02012-09-27 17:45:57 +00002745 case GL_RGB:
apatrick@chromium.org144f2802012-07-12 01:42:34 +00002746 switch (type)
2747 {
daniel@transgaming.com42944b02012-09-27 17:45:57 +00002748 case GL_UNSIGNED_SHORT_5_6_5:
apatrick@chromium.org144f2802012-07-12 01:42:34 +00002749 dest16[i + j * outputPitch / sizeof(unsigned short)] =
2750 ((unsigned short)(31 * b + 0.5f) << 0) |
2751 ((unsigned short)(63 * g + 0.5f) << 5) |
2752 ((unsigned short)(31 * r + 0.5f) << 11);
2753 break;
daniel@transgaming.com42944b02012-09-27 17:45:57 +00002754 case GL_UNSIGNED_BYTE:
2755 dest[3 * i + j * outputPitch + 0] = (unsigned char)(255 * r + 0.5f);
2756 dest[3 * i + j * outputPitch + 1] = (unsigned char)(255 * g + 0.5f);
2757 dest[3 * i + j * outputPitch + 2] = (unsigned char)(255 * b + 0.5f);
2758 break;
apatrick@chromium.org144f2802012-07-12 01:42:34 +00002759 default: UNREACHABLE();
2760 }
2761 break;
2762 default: UNREACHABLE();
2763 }
2764 }
2765 }
2766
2767 systemSurface->UnlockRect();
2768
2769 systemSurface->Release();
2770}
2771
2772void Context::clear(GLbitfield mask)
2773{
2774 Framebuffer *framebufferObject = getDrawFramebuffer();
2775
2776 if (!framebufferObject || framebufferObject->completeness() != GL_FRAMEBUFFER_COMPLETE)
2777 {
2778 return error(GL_INVALID_FRAMEBUFFER_OPERATION);
2779 }
2780
2781 DWORD flags = 0;
2782
2783 if (mask & GL_COLOR_BUFFER_BIT)
2784 {
2785 mask &= ~GL_COLOR_BUFFER_BIT;
2786
2787 if (framebufferObject->getColorbufferType() != GL_NONE)
2788 {
2789 flags |= D3DCLEAR_TARGET;
2790 }
2791 }
2792
2793 if (mask & GL_DEPTH_BUFFER_BIT)
2794 {
2795 mask &= ~GL_DEPTH_BUFFER_BIT;
2796 if (mState.depthMask && framebufferObject->getDepthbufferType() != GL_NONE)
2797 {
2798 flags |= D3DCLEAR_ZBUFFER;
2799 }
2800 }
2801
2802 GLuint stencilUnmasked = 0x0;
2803
2804 if (mask & GL_STENCIL_BUFFER_BIT)
2805 {
2806 mask &= ~GL_STENCIL_BUFFER_BIT;
2807 if (framebufferObject->getStencilbufferType() != GL_NONE)
2808 {
2809 IDirect3DSurface9 *depthStencil = framebufferObject->getStencilbuffer()->getDepthStencil();
2810 if (!depthStencil)
2811 {
2812 ERR("Depth stencil pointer unexpectedly null.");
2813 return;
2814 }
2815
2816 D3DSURFACE_DESC desc;
2817 depthStencil->GetDesc(&desc);
2818 depthStencil->Release();
2819
2820 unsigned int stencilSize = dx2es::GetStencilSize(desc.Format);
2821 stencilUnmasked = (0x1 << stencilSize) - 1;
2822
2823 if (stencilUnmasked != 0x0)
2824 {
2825 flags |= D3DCLEAR_STENCIL;
2826 }
2827 }
2828 }
2829
2830 if (mask != 0)
2831 {
2832 return error(GL_INVALID_VALUE);
2833 }
2834
2835 if (!applyRenderTarget(true)) // Clips the clear to the scissor rectangle but not the viewport
2836 {
2837 return;
2838 }
2839
2840 D3DCOLOR color = D3DCOLOR_ARGB(unorm<8>(mState.colorClearValue.alpha),
2841 unorm<8>(mState.colorClearValue.red),
2842 unorm<8>(mState.colorClearValue.green),
2843 unorm<8>(mState.colorClearValue.blue));
2844 float depth = clamp01(mState.depthClearValue);
2845 int stencil = mState.stencilClearValue & 0x000000FF;
2846
2847 bool alphaUnmasked = (dx2es::GetAlphaSize(mRenderTargetDesc.Format) == 0) || mState.colorMaskAlpha;
2848
2849 const bool needMaskedStencilClear = (flags & D3DCLEAR_STENCIL) &&
2850 (mState.stencilWritemask & stencilUnmasked) != stencilUnmasked;
2851 const bool needMaskedColorClear = (flags & D3DCLEAR_TARGET) &&
2852 !(mState.colorMaskRed && mState.colorMaskGreen &&
2853 mState.colorMaskBlue && alphaUnmasked);
2854
2855 if (needMaskedColorClear || needMaskedStencilClear)
2856 {
2857 // State which is altered in all paths from this point to the clear call is saved.
2858 // State which is altered in only some paths will be flagged dirty in the case that
2859 // that path is taken.
2860 HRESULT hr;
2861 if (mMaskedClearSavedState == NULL)
2862 {
2863 hr = mDevice->BeginStateBlock();
2864 ASSERT(SUCCEEDED(hr) || hr == D3DERR_OUTOFVIDEOMEMORY || hr == E_OUTOFMEMORY);
2865
2866 mDevice->SetRenderState(D3DRS_ZWRITEENABLE, FALSE);
2867 mDevice->SetRenderState(D3DRS_ZFUNC, D3DCMP_ALWAYS);
2868 mDevice->SetRenderState(D3DRS_ZENABLE, FALSE);
2869 mDevice->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE);
2870 mDevice->SetRenderState(D3DRS_FILLMODE, D3DFILL_SOLID);
2871 mDevice->SetRenderState(D3DRS_ALPHATESTENABLE, FALSE);
2872 mDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, FALSE);
2873 mDevice->SetRenderState(D3DRS_CLIPPLANEENABLE, 0);
2874 mDevice->SetRenderState(D3DRS_COLORWRITEENABLE, 0);
2875 mDevice->SetRenderState(D3DRS_STENCILENABLE, FALSE);
2876 mDevice->SetPixelShader(NULL);
2877 mDevice->SetVertexShader(NULL);
2878 mDevice->SetFVF(D3DFVF_XYZRHW | D3DFVF_DIFFUSE);
2879 mDevice->SetStreamSource(0, NULL, 0, 0);
2880 mDevice->SetRenderState(D3DRS_SEPARATEALPHABLENDENABLE, TRUE);
2881 mDevice->SetTextureStageState(0, D3DTSS_COLOROP, D3DTOP_SELECTARG1);
2882 mDevice->SetTextureStageState(0, D3DTSS_COLORARG1, D3DTA_TFACTOR);
2883 mDevice->SetTextureStageState(0, D3DTSS_ALPHAOP, D3DTOP_SELECTARG1);
2884 mDevice->SetTextureStageState(0, D3DTSS_ALPHAARG1, D3DTA_TFACTOR);
2885 mDevice->SetRenderState(D3DRS_TEXTUREFACTOR, color);
2886 mDevice->SetRenderState(D3DRS_MULTISAMPLEMASK, 0xFFFFFFFF);
2887
2888 for(int i = 0; i < MAX_VERTEX_ATTRIBS; i++)
2889 {
2890 mDevice->SetStreamSourceFreq(i, 1);
2891 }
2892
2893 hr = mDevice->EndStateBlock(&mMaskedClearSavedState);
2894 ASSERT(SUCCEEDED(hr) || hr == D3DERR_OUTOFVIDEOMEMORY || hr == E_OUTOFMEMORY);
2895 }
2896
2897 ASSERT(mMaskedClearSavedState != NULL);
2898
2899 if (mMaskedClearSavedState != NULL)
2900 {
2901 hr = mMaskedClearSavedState->Capture();
2902 ASSERT(SUCCEEDED(hr));
2903 }
2904
2905 mDevice->SetRenderState(D3DRS_ZWRITEENABLE, FALSE);
2906 mDevice->SetRenderState(D3DRS_ZFUNC, D3DCMP_ALWAYS);
2907 mDevice->SetRenderState(D3DRS_ZENABLE, FALSE);
2908 mDevice->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE);
2909 mDevice->SetRenderState(D3DRS_FILLMODE, D3DFILL_SOLID);
2910 mDevice->SetRenderState(D3DRS_ALPHATESTENABLE, FALSE);
2911 mDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, FALSE);
2912 mDevice->SetRenderState(D3DRS_CLIPPLANEENABLE, 0);
2913
2914 if (flags & D3DCLEAR_TARGET)
2915 {
2916 mDevice->SetRenderState(D3DRS_COLORWRITEENABLE, es2dx::ConvertColorMask(mState.colorMaskRed, mState.colorMaskGreen, mState.colorMaskBlue, mState.colorMaskAlpha));
2917 }
2918 else
2919 {
2920 mDevice->SetRenderState(D3DRS_COLORWRITEENABLE, 0);
2921 }
2922
2923 if (stencilUnmasked != 0x0 && (flags & D3DCLEAR_STENCIL))
2924 {
2925 mDevice->SetRenderState(D3DRS_STENCILENABLE, TRUE);
2926 mDevice->SetRenderState(D3DRS_TWOSIDEDSTENCILMODE, FALSE);
2927 mDevice->SetRenderState(D3DRS_STENCILFUNC, D3DCMP_ALWAYS);
2928 mDevice->SetRenderState(D3DRS_STENCILREF, stencil);
2929 mDevice->SetRenderState(D3DRS_STENCILWRITEMASK, mState.stencilWritemask);
2930 mDevice->SetRenderState(D3DRS_STENCILFAIL, D3DSTENCILOP_REPLACE);
2931 mDevice->SetRenderState(D3DRS_STENCILZFAIL, D3DSTENCILOP_REPLACE);
2932 mDevice->SetRenderState(D3DRS_STENCILPASS, D3DSTENCILOP_REPLACE);
2933 mStencilStateDirty = true;
2934 }
2935 else
2936 {
2937 mDevice->SetRenderState(D3DRS_STENCILENABLE, FALSE);
2938 }
2939
2940 mDevice->SetPixelShader(NULL);
2941 mDevice->SetVertexShader(NULL);
2942 mDevice->SetFVF(D3DFVF_XYZRHW);
2943 mDevice->SetRenderState(D3DRS_SEPARATEALPHABLENDENABLE, TRUE);
2944 mDevice->SetTextureStageState(0, D3DTSS_COLOROP, D3DTOP_SELECTARG1);
2945 mDevice->SetTextureStageState(0, D3DTSS_COLORARG1, D3DTA_TFACTOR);
2946 mDevice->SetTextureStageState(0, D3DTSS_ALPHAOP, D3DTOP_SELECTARG1);
2947 mDevice->SetTextureStageState(0, D3DTSS_ALPHAARG1, D3DTA_TFACTOR);
2948 mDevice->SetRenderState(D3DRS_TEXTUREFACTOR, color);
2949 mDevice->SetRenderState(D3DRS_MULTISAMPLEMASK, 0xFFFFFFFF);
2950
2951 for(int i = 0; i < MAX_VERTEX_ATTRIBS; i++)
2952 {
2953 mDevice->SetStreamSourceFreq(i, 1);
2954 }
2955
2956 float quad[4][4]; // A quadrilateral covering the target, aligned to match the edges
2957 quad[0][0] = -0.5f;
2958 quad[0][1] = mRenderTargetDesc.Height - 0.5f;
2959 quad[0][2] = 0.0f;
2960 quad[0][3] = 1.0f;
2961
2962 quad[1][0] = mRenderTargetDesc.Width - 0.5f;
2963 quad[1][1] = mRenderTargetDesc.Height - 0.5f;
2964 quad[1][2] = 0.0f;
2965 quad[1][3] = 1.0f;
2966
2967 quad[2][0] = -0.5f;
2968 quad[2][1] = -0.5f;
2969 quad[2][2] = 0.0f;
2970 quad[2][3] = 1.0f;
2971
2972 quad[3][0] = mRenderTargetDesc.Width - 0.5f;
2973 quad[3][1] = -0.5f;
2974 quad[3][2] = 0.0f;
2975 quad[3][3] = 1.0f;
2976
daniel@transgaming.com621ce052012-10-31 17:52:29 +00002977 mRenderer->startScene();
apatrick@chromium.org144f2802012-07-12 01:42:34 +00002978 mDevice->DrawPrimitiveUP(D3DPT_TRIANGLESTRIP, 2, quad, sizeof(float[4]));
2979
2980 if (flags & D3DCLEAR_ZBUFFER)
2981 {
2982 mDevice->SetRenderState(D3DRS_ZENABLE, TRUE);
2983 mDevice->SetRenderState(D3DRS_ZWRITEENABLE, TRUE);
2984 mDevice->Clear(0, NULL, D3DCLEAR_ZBUFFER, color, depth, stencil);
2985 }
2986
2987 if (mMaskedClearSavedState != NULL)
2988 {
2989 mMaskedClearSavedState->Apply();
2990 }
2991 }
2992 else if (flags)
2993 {
2994 mDevice->Clear(0, NULL, flags, color, depth, stencil);
2995 }
2996}
2997
2998void Context::drawArrays(GLenum mode, GLint first, GLsizei count, GLsizei instances)
2999{
3000 if (!mState.currentProgram)
3001 {
3002 return error(GL_INVALID_OPERATION);
3003 }
3004
3005 D3DPRIMITIVETYPE primitiveType;
3006 int primitiveCount;
3007
3008 if(!es2dx::ConvertPrimitiveType(mode, count, &primitiveType, &primitiveCount))
3009 return error(GL_INVALID_ENUM);
3010
3011 if (primitiveCount <= 0)
3012 {
3013 return;
3014 }
3015
3016 if (!applyRenderTarget(false))
3017 {
3018 return;
3019 }
3020
3021 applyState(mode);
3022
3023 GLsizei repeatDraw = 1;
3024 GLenum err = applyVertexBuffer(first, count, instances, &repeatDraw);
3025 if (err != GL_NO_ERROR)
3026 {
3027 return error(err);
3028 }
3029
3030 applyShaders();
3031 applyTextures();
3032
daniel@transgaming.com62a28462012-07-24 18:33:59 +00003033 if (!getCurrentProgramBinary()->validateSamplers(NULL))
apatrick@chromium.org144f2802012-07-12 01:42:34 +00003034 {
3035 return error(GL_INVALID_OPERATION);
3036 }
3037
daniel@transgaming.com087e5782012-09-17 21:28:47 +00003038 if (!skipDraw(mode))
apatrick@chromium.org144f2802012-07-12 01:42:34 +00003039 {
daniel@transgaming.com621ce052012-10-31 17:52:29 +00003040 mRenderer->startScene();
apatrick@chromium.org144f2802012-07-12 01:42:34 +00003041
3042 if (mode == GL_LINE_LOOP)
3043 {
3044 drawLineLoop(count, GL_NONE, NULL, 0);
3045 }
3046 else if (instances > 0)
3047 {
3048 StaticIndexBuffer *countingIB = mIndexDataManager->getCountingIndices(count);
3049 if (countingIB)
3050 {
3051 if (mAppliedIBSerial != countingIB->getSerial())
3052 {
3053 mDevice->SetIndices(countingIB->getBuffer());
3054 mAppliedIBSerial = countingIB->getSerial();
3055 }
3056
3057 for (int i = 0; i < repeatDraw; i++)
3058 {
3059 mDevice->DrawIndexedPrimitive(primitiveType, 0, 0, count, 0, primitiveCount);
3060 }
3061 }
3062 else
3063 {
3064 ERR("Could not create a counting index buffer for glDrawArraysInstanced.");
3065 return error(GL_OUT_OF_MEMORY);
3066 }
3067 }
3068 else // Regular case
3069 {
3070 mDevice->DrawPrimitive(primitiveType, 0, primitiveCount);
3071 }
3072 }
3073}
3074
3075void Context::drawElements(GLenum mode, GLsizei count, GLenum type, const GLvoid *indices, GLsizei instances)
3076{
3077 if (!mState.currentProgram)
3078 {
3079 return error(GL_INVALID_OPERATION);
3080 }
3081
3082 if (!indices && !mState.elementArrayBuffer)
3083 {
3084 return error(GL_INVALID_OPERATION);
3085 }
3086
3087 D3DPRIMITIVETYPE primitiveType;
3088 int primitiveCount;
3089
3090 if(!es2dx::ConvertPrimitiveType(mode, count, &primitiveType, &primitiveCount))
3091 return error(GL_INVALID_ENUM);
3092
3093 if (primitiveCount <= 0)
3094 {
3095 return;
3096 }
3097
3098 if (!applyRenderTarget(false))
3099 {
3100 return;
3101 }
3102
3103 applyState(mode);
3104
3105 TranslatedIndexData indexInfo;
3106 GLenum err = applyIndexBuffer(indices, count, mode, type, &indexInfo);
3107 if (err != GL_NO_ERROR)
3108 {
3109 return error(err);
3110 }
3111
3112 GLsizei vertexCount = indexInfo.maxIndex - indexInfo.minIndex + 1;
3113 GLsizei repeatDraw = 1;
3114 err = applyVertexBuffer(indexInfo.minIndex, vertexCount, instances, &repeatDraw);
3115 if (err != GL_NO_ERROR)
3116 {
3117 return error(err);
3118 }
3119
3120 applyShaders();
3121 applyTextures();
3122
daniel@transgaming.com62a28462012-07-24 18:33:59 +00003123 if (!getCurrentProgramBinary()->validateSamplers(false))
apatrick@chromium.org144f2802012-07-12 01:42:34 +00003124 {
3125 return error(GL_INVALID_OPERATION);
3126 }
3127
daniel@transgaming.com087e5782012-09-17 21:28:47 +00003128 if (!skipDraw(mode))
apatrick@chromium.org144f2802012-07-12 01:42:34 +00003129 {
daniel@transgaming.com621ce052012-10-31 17:52:29 +00003130 mRenderer->startScene();
apatrick@chromium.org144f2802012-07-12 01:42:34 +00003131
3132 if (mode == GL_LINE_LOOP)
3133 {
3134 drawLineLoop(count, type, indices, indexInfo.minIndex);
3135 }
3136 else
3137 {
3138 for (int i = 0; i < repeatDraw; i++)
3139 {
3140 mDevice->DrawIndexedPrimitive(primitiveType, -(INT)indexInfo.minIndex, indexInfo.minIndex, vertexCount, indexInfo.startIndex, primitiveCount);
3141 }
3142 }
3143 }
3144}
3145
3146// Implements glFlush when block is false, glFinish when block is true
3147void Context::sync(bool block)
3148{
daniel@transgaming.comef21ab22012-10-31 17:52:47 +00003149 mRenderer->sync(block);
apatrick@chromium.org144f2802012-07-12 01:42:34 +00003150}
3151
3152void Context::drawLineLoop(GLsizei count, GLenum type, const GLvoid *indices, int minIndex)
3153{
3154 // Get the raw indices for an indexed draw
3155 if (type != GL_NONE && mState.elementArrayBuffer.get())
3156 {
3157 Buffer *indexBuffer = mState.elementArrayBuffer.get();
3158 intptr_t offset = reinterpret_cast<intptr_t>(indices);
3159 indices = static_cast<const GLubyte*>(indexBuffer->data()) + offset;
3160 }
3161
3162 UINT startIndex = 0;
3163 bool succeeded = false;
3164
3165 if (supports32bitIndices())
3166 {
3167 const int spaceNeeded = (count + 1) * sizeof(unsigned int);
3168
3169 if (!mLineLoopIB)
3170 {
daniel@transgaming.com6716a272012-10-31 18:31:39 +00003171 mLineLoopIB = new StreamingIndexBuffer(mRenderer, INITIAL_INDEX_BUFFER_SIZE, D3DFMT_INDEX32);
apatrick@chromium.org144f2802012-07-12 01:42:34 +00003172 }
3173
3174 if (mLineLoopIB)
3175 {
3176 mLineLoopIB->reserveSpace(spaceNeeded, GL_UNSIGNED_INT);
3177
3178 UINT offset = 0;
3179 unsigned int *data = static_cast<unsigned int*>(mLineLoopIB->map(spaceNeeded, &offset));
3180 startIndex = offset / 4;
3181
3182 if (data)
3183 {
3184 switch (type)
3185 {
3186 case GL_NONE: // Non-indexed draw
3187 for (int i = 0; i < count; i++)
3188 {
3189 data[i] = i;
3190 }
3191 data[count] = 0;
3192 break;
3193 case GL_UNSIGNED_BYTE:
3194 for (int i = 0; i < count; i++)
3195 {
3196 data[i] = static_cast<const GLubyte*>(indices)[i];
3197 }
3198 data[count] = static_cast<const GLubyte*>(indices)[0];
3199 break;
3200 case GL_UNSIGNED_SHORT:
3201 for (int i = 0; i < count; i++)
3202 {
3203 data[i] = static_cast<const GLushort*>(indices)[i];
3204 }
3205 data[count] = static_cast<const GLushort*>(indices)[0];
3206 break;
3207 case GL_UNSIGNED_INT:
3208 for (int i = 0; i < count; i++)
3209 {
3210 data[i] = static_cast<const GLuint*>(indices)[i];
3211 }
3212 data[count] = static_cast<const GLuint*>(indices)[0];
3213 break;
3214 default: UNREACHABLE();
3215 }
3216
3217 mLineLoopIB->unmap();
3218 succeeded = true;
3219 }
3220 }
3221 }
3222 else
3223 {
3224 const int spaceNeeded = (count + 1) * sizeof(unsigned short);
3225
3226 if (!mLineLoopIB)
3227 {
daniel@transgaming.com6716a272012-10-31 18:31:39 +00003228 mLineLoopIB = new StreamingIndexBuffer(mRenderer, INITIAL_INDEX_BUFFER_SIZE, D3DFMT_INDEX16);
apatrick@chromium.org144f2802012-07-12 01:42:34 +00003229 }
3230
3231 if (mLineLoopIB)
3232 {
3233 mLineLoopIB->reserveSpace(spaceNeeded, GL_UNSIGNED_SHORT);
3234
3235 UINT offset = 0;
3236 unsigned short *data = static_cast<unsigned short*>(mLineLoopIB->map(spaceNeeded, &offset));
3237 startIndex = offset / 2;
3238
3239 if (data)
3240 {
3241 switch (type)
3242 {
3243 case GL_NONE: // Non-indexed draw
3244 for (int i = 0; i < count; i++)
3245 {
3246 data[i] = i;
3247 }
3248 data[count] = 0;
3249 break;
3250 case GL_UNSIGNED_BYTE:
3251 for (int i = 0; i < count; i++)
3252 {
3253 data[i] = static_cast<const GLubyte*>(indices)[i];
3254 }
3255 data[count] = static_cast<const GLubyte*>(indices)[0];
3256 break;
3257 case GL_UNSIGNED_SHORT:
3258 for (int i = 0; i < count; i++)
3259 {
3260 data[i] = static_cast<const GLushort*>(indices)[i];
3261 }
3262 data[count] = static_cast<const GLushort*>(indices)[0];
3263 break;
3264 case GL_UNSIGNED_INT:
3265 for (int i = 0; i < count; i++)
3266 {
3267 data[i] = static_cast<const GLuint*>(indices)[i];
3268 }
3269 data[count] = static_cast<const GLuint*>(indices)[0];
3270 break;
3271 default: UNREACHABLE();
3272 }
3273
3274 mLineLoopIB->unmap();
3275 succeeded = true;
3276 }
3277 }
3278 }
3279
3280 if (succeeded)
3281 {
3282 if (mAppliedIBSerial != mLineLoopIB->getSerial())
3283 {
3284 mDevice->SetIndices(mLineLoopIB->getBuffer());
3285 mAppliedIBSerial = mLineLoopIB->getSerial();
3286 }
3287
3288 mDevice->DrawIndexedPrimitive(D3DPT_LINESTRIP, -minIndex, minIndex, count, startIndex, count);
3289 }
3290 else
3291 {
3292 ERR("Could not create a looping index buffer for GL_LINE_LOOP.");
3293 return error(GL_OUT_OF_MEMORY);
3294 }
3295}
3296
3297void Context::recordInvalidEnum()
3298{
3299 mInvalidEnum = true;
3300}
3301
3302void Context::recordInvalidValue()
3303{
3304 mInvalidValue = true;
3305}
3306
3307void Context::recordInvalidOperation()
3308{
3309 mInvalidOperation = true;
3310}
3311
3312void Context::recordOutOfMemory()
3313{
3314 mOutOfMemory = true;
3315}
3316
3317void Context::recordInvalidFramebufferOperation()
3318{
3319 mInvalidFramebufferOperation = true;
3320}
3321
3322// Get one of the recorded errors and clear its flag, if any.
3323// [OpenGL ES 2.0.24] section 2.5 page 13.
3324GLenum Context::getError()
3325{
3326 if (mInvalidEnum)
3327 {
3328 mInvalidEnum = false;
3329
3330 return GL_INVALID_ENUM;
3331 }
3332
3333 if (mInvalidValue)
3334 {
3335 mInvalidValue = false;
3336
3337 return GL_INVALID_VALUE;
3338 }
3339
3340 if (mInvalidOperation)
3341 {
3342 mInvalidOperation = false;
3343
3344 return GL_INVALID_OPERATION;
3345 }
3346
3347 if (mOutOfMemory)
3348 {
3349 mOutOfMemory = false;
3350
3351 return GL_OUT_OF_MEMORY;
3352 }
3353
3354 if (mInvalidFramebufferOperation)
3355 {
3356 mInvalidFramebufferOperation = false;
3357
3358 return GL_INVALID_FRAMEBUFFER_OPERATION;
3359 }
3360
3361 return GL_NO_ERROR;
3362}
3363
3364GLenum Context::getResetStatus()
3365{
3366 if (mResetStatus == GL_NO_ERROR)
3367 {
daniel@transgaming.comf688c0d2012-10-31 17:52:57 +00003368 // mResetStatus will be set by the markContextLost callback
3369 // in the case a notification is sent
3370 mRenderer->testDeviceLost(true);
apatrick@chromium.org144f2802012-07-12 01:42:34 +00003371 }
3372
3373 GLenum status = mResetStatus;
3374
3375 if (mResetStatus != GL_NO_ERROR)
3376 {
daniel@transgaming.com621ce052012-10-31 17:52:29 +00003377 if (mRenderer->testDeviceResettable())
apatrick@chromium.org144f2802012-07-12 01:42:34 +00003378 {
3379 mResetStatus = GL_NO_ERROR;
3380 }
3381 }
3382
3383 return status;
3384}
3385
3386bool Context::isResetNotificationEnabled()
3387{
3388 return (mResetStrategy == GL_LOSE_CONTEXT_ON_RESET_EXT);
3389}
3390
3391bool Context::supportsShaderModel3() const
3392{
3393 return mSupportsShaderModel3;
3394}
3395
3396float Context::getMaximumPointSize() const
3397{
3398 return mSupportsShaderModel3 ? mMaximumPointSize : ALIASED_POINT_SIZE_RANGE_MAX_SM2;
3399}
3400
3401int Context::getMaximumVaryingVectors() const
3402{
3403 return mSupportsShaderModel3 ? MAX_VARYING_VECTORS_SM3 : MAX_VARYING_VECTORS_SM2;
3404}
3405
3406unsigned int Context::getMaximumVertexTextureImageUnits() const
3407{
3408 return mSupportsVertexTexture ? MAX_VERTEX_TEXTURE_IMAGE_UNITS_VTF : 0;
3409}
3410
3411unsigned int Context::getMaximumCombinedTextureImageUnits() const
3412{
3413 return MAX_TEXTURE_IMAGE_UNITS + getMaximumVertexTextureImageUnits();
3414}
3415
3416int Context::getMaximumFragmentUniformVectors() const
3417{
3418 return mSupportsShaderModel3 ? MAX_FRAGMENT_UNIFORM_VECTORS_SM3 : MAX_FRAGMENT_UNIFORM_VECTORS_SM2;
3419}
3420
3421int Context::getMaxSupportedSamples() const
3422{
daniel@transgaming.comb7833982012-10-31 18:31:46 +00003423 return mRenderer->getMaxSupportedSamples();
apatrick@chromium.org144f2802012-07-12 01:42:34 +00003424}
3425
apatrick@chromium.org144f2802012-07-12 01:42:34 +00003426bool Context::supportsEventQueries() const
3427{
3428 return mSupportsEventQueries;
3429}
3430
3431bool Context::supportsOcclusionQueries() const
3432{
3433 return mSupportsOcclusionQueries;
3434}
3435
3436bool Context::supportsDXT1Textures() const
3437{
3438 return mSupportsDXT1Textures;
3439}
3440
3441bool Context::supportsDXT3Textures() const
3442{
3443 return mSupportsDXT3Textures;
3444}
3445
3446bool Context::supportsDXT5Textures() const
3447{
3448 return mSupportsDXT5Textures;
3449}
3450
3451bool Context::supportsFloat32Textures() const
3452{
3453 return mSupportsFloat32Textures;
3454}
3455
3456bool Context::supportsFloat32LinearFilter() const
3457{
3458 return mSupportsFloat32LinearFilter;
3459}
3460
3461bool Context::supportsFloat32RenderableTextures() const
3462{
3463 return mSupportsFloat32RenderableTextures;
3464}
3465
3466bool Context::supportsFloat16Textures() const
3467{
3468 return mSupportsFloat16Textures;
3469}
3470
3471bool Context::supportsFloat16LinearFilter() const
3472{
3473 return mSupportsFloat16LinearFilter;
3474}
3475
3476bool Context::supportsFloat16RenderableTextures() const
3477{
3478 return mSupportsFloat16RenderableTextures;
3479}
3480
3481int Context::getMaximumRenderbufferDimension() const
3482{
3483 return mMaxRenderbufferDimension;
3484}
3485
3486int Context::getMaximumTextureDimension() const
3487{
3488 return mMaxTextureDimension;
3489}
3490
3491int Context::getMaximumCubeTextureDimension() const
3492{
3493 return mMaxCubeTextureDimension;
3494}
3495
3496int Context::getMaximumTextureLevel() const
3497{
3498 return mMaxTextureLevel;
3499}
3500
3501bool Context::supportsLuminanceTextures() const
3502{
3503 return mSupportsLuminanceTextures;
3504}
3505
3506bool Context::supportsLuminanceAlphaTextures() const
3507{
3508 return mSupportsLuminanceAlphaTextures;
3509}
3510
3511bool Context::supportsDepthTextures() const
3512{
3513 return mSupportsDepthTextures;
3514}
3515
3516bool Context::supports32bitIndices() const
3517{
3518 return mSupports32bitIndices;
3519}
3520
3521bool Context::supportsNonPower2Texture() const
3522{
3523 return mSupportsNonPower2Texture;
3524}
3525
3526bool Context::supportsInstancing() const
3527{
3528 return mSupportsInstancing;
3529}
3530
daniel@transgaming.com07ab8412012-07-12 15:17:09 +00003531bool Context::supportsTextureFilterAnisotropy() const
3532{
3533 return mSupportsTextureFilterAnisotropy;
3534}
3535
3536float Context::getTextureMaxAnisotropy() const
3537{
3538 return mMaxTextureAnisotropy;
3539}
3540
daniel@transgaming.com42944b02012-09-27 17:45:57 +00003541bool Context::getCurrentReadFormatType(GLenum *format, GLenum *type)
3542{
3543 Framebuffer *framebuffer = getReadFramebuffer();
3544 if (!framebuffer || framebuffer->completeness() != GL_FRAMEBUFFER_COMPLETE)
3545 {
3546 return error(GL_INVALID_OPERATION, false);
3547 }
3548
3549 Renderbuffer *renderbuffer = framebuffer->getColorbuffer();
3550 if (!renderbuffer)
3551 {
3552 return error(GL_INVALID_OPERATION, false);
3553 }
3554
3555 if(!dx2es::ConvertReadBufferFormat(renderbuffer->getD3DFormat(), format, type))
3556 {
3557 ASSERT(false);
3558 return false;
3559 }
3560
3561 return true;
3562}
3563
apatrick@chromium.org144f2802012-07-12 01:42:34 +00003564void Context::detachBuffer(GLuint buffer)
3565{
3566 // [OpenGL ES 2.0.24] section 2.9 page 22:
3567 // If a buffer object is deleted while it is bound, all bindings to that object in the current context
3568 // (i.e. in the thread that called Delete-Buffers) are reset to zero.
3569
3570 if (mState.arrayBuffer.id() == buffer)
3571 {
3572 mState.arrayBuffer.set(NULL);
3573 }
3574
3575 if (mState.elementArrayBuffer.id() == buffer)
3576 {
3577 mState.elementArrayBuffer.set(NULL);
3578 }
3579
3580 for (int attribute = 0; attribute < MAX_VERTEX_ATTRIBS; attribute++)
3581 {
3582 if (mState.vertexAttribute[attribute].mBoundBuffer.id() == buffer)
3583 {
3584 mState.vertexAttribute[attribute].mBoundBuffer.set(NULL);
3585 }
3586 }
3587}
3588
3589void Context::detachTexture(GLuint texture)
3590{
3591 // [OpenGL ES 2.0.24] section 3.8 page 84:
3592 // If a texture object is deleted, it is as if all texture units which are bound to that texture object are
3593 // rebound to texture object zero
3594
3595 for (int type = 0; type < TEXTURE_TYPE_COUNT; type++)
3596 {
3597 for (int sampler = 0; sampler < MAX_COMBINED_TEXTURE_IMAGE_UNITS_VTF; sampler++)
3598 {
3599 if (mState.samplerTexture[type][sampler].id() == texture)
3600 {
3601 mState.samplerTexture[type][sampler].set(NULL);
3602 }
3603 }
3604 }
3605
3606 // [OpenGL ES 2.0.24] section 4.4 page 112:
3607 // If a texture object is deleted while its image is attached to the currently bound framebuffer, then it is
3608 // as if FramebufferTexture2D had been called, with a texture of 0, for each attachment point to which this
3609 // image was attached in the currently bound framebuffer.
3610
3611 Framebuffer *readFramebuffer = getReadFramebuffer();
3612 Framebuffer *drawFramebuffer = getDrawFramebuffer();
3613
3614 if (readFramebuffer)
3615 {
3616 readFramebuffer->detachTexture(texture);
3617 }
3618
3619 if (drawFramebuffer && drawFramebuffer != readFramebuffer)
3620 {
3621 drawFramebuffer->detachTexture(texture);
3622 }
3623}
3624
3625void Context::detachFramebuffer(GLuint framebuffer)
3626{
3627 // [OpenGL ES 2.0.24] section 4.4 page 107:
3628 // If a framebuffer that is currently bound to the target FRAMEBUFFER is deleted, it is as though
3629 // BindFramebuffer had been executed with the target of FRAMEBUFFER and framebuffer of zero.
3630
3631 if (mState.readFramebuffer == framebuffer)
3632 {
3633 bindReadFramebuffer(0);
3634 }
3635
3636 if (mState.drawFramebuffer == framebuffer)
3637 {
3638 bindDrawFramebuffer(0);
3639 }
3640}
3641
3642void Context::detachRenderbuffer(GLuint renderbuffer)
3643{
3644 // [OpenGL ES 2.0.24] section 4.4 page 109:
3645 // If a renderbuffer that is currently bound to RENDERBUFFER is deleted, it is as though BindRenderbuffer
3646 // had been executed with the target RENDERBUFFER and name of zero.
3647
3648 if (mState.renderbuffer.id() == renderbuffer)
3649 {
3650 bindRenderbuffer(0);
3651 }
3652
3653 // [OpenGL ES 2.0.24] section 4.4 page 111:
3654 // If a renderbuffer object is deleted while its image is attached to the currently bound framebuffer,
3655 // then it is as if FramebufferRenderbuffer had been called, with a renderbuffer of 0, for each attachment
3656 // point to which this image was attached in the currently bound framebuffer.
3657
3658 Framebuffer *readFramebuffer = getReadFramebuffer();
3659 Framebuffer *drawFramebuffer = getDrawFramebuffer();
3660
3661 if (readFramebuffer)
3662 {
3663 readFramebuffer->detachRenderbuffer(renderbuffer);
3664 }
3665
3666 if (drawFramebuffer && drawFramebuffer != readFramebuffer)
3667 {
3668 drawFramebuffer->detachRenderbuffer(renderbuffer);
3669 }
3670}
3671
3672Texture *Context::getIncompleteTexture(TextureType type)
3673{
3674 Texture *t = mIncompleteTextures[type].get();
3675
3676 if (t == NULL)
3677 {
3678 static const GLubyte color[] = { 0, 0, 0, 255 };
3679
3680 switch (type)
3681 {
3682 default:
3683 UNREACHABLE();
3684 // default falls through to TEXTURE_2D
3685
3686 case TEXTURE_2D:
3687 {
3688 Texture2D *incomplete2d = new Texture2D(Texture::INCOMPLETE_TEXTURE_ID);
3689 incomplete2d->setImage(0, 1, 1, GL_RGBA, GL_UNSIGNED_BYTE, 1, color);
3690 t = incomplete2d;
3691 }
3692 break;
3693
3694 case TEXTURE_CUBE:
3695 {
3696 TextureCubeMap *incompleteCube = new TextureCubeMap(Texture::INCOMPLETE_TEXTURE_ID);
3697
3698 incompleteCube->setImagePosX(0, 1, 1, GL_RGBA, GL_UNSIGNED_BYTE, 1, color);
3699 incompleteCube->setImageNegX(0, 1, 1, GL_RGBA, GL_UNSIGNED_BYTE, 1, color);
3700 incompleteCube->setImagePosY(0, 1, 1, GL_RGBA, GL_UNSIGNED_BYTE, 1, color);
3701 incompleteCube->setImageNegY(0, 1, 1, GL_RGBA, GL_UNSIGNED_BYTE, 1, color);
3702 incompleteCube->setImagePosZ(0, 1, 1, GL_RGBA, GL_UNSIGNED_BYTE, 1, color);
3703 incompleteCube->setImageNegZ(0, 1, 1, GL_RGBA, GL_UNSIGNED_BYTE, 1, color);
3704
3705 t = incompleteCube;
3706 }
3707 break;
3708 }
3709
3710 mIncompleteTextures[type].set(t);
3711 }
3712
3713 return t;
3714}
3715
daniel@transgaming.com087e5782012-09-17 21:28:47 +00003716bool Context::skipDraw(GLenum drawMode)
apatrick@chromium.org144f2802012-07-12 01:42:34 +00003717{
daniel@transgaming.com087e5782012-09-17 21:28:47 +00003718 if (drawMode == GL_POINTS)
3719 {
3720 // ProgramBinary assumes non-point rendering if gl_PointSize isn't written,
3721 // which affects varying interpolation. Since the value of gl_PointSize is
3722 // undefined when not written, just skip drawing to avoid unexpected results.
3723 if (!getCurrentProgramBinary()->usesPointSize())
3724 {
3725 // This is stictly speaking not an error, but developers should be
3726 // notified of risking undefined behavior.
3727 ERR("Point rendering without writing to gl_PointSize.");
3728
3729 return true;
3730 }
3731 }
3732 else if (isTriangleMode(drawMode))
3733 {
3734 if (mState.cullFace && mState.cullMode == GL_FRONT_AND_BACK)
3735 {
3736 return true;
3737 }
3738 }
3739
3740 return false;
apatrick@chromium.org144f2802012-07-12 01:42:34 +00003741}
3742
3743bool Context::isTriangleMode(GLenum drawMode)
3744{
3745 switch (drawMode)
3746 {
3747 case GL_TRIANGLES:
3748 case GL_TRIANGLE_FAN:
3749 case GL_TRIANGLE_STRIP:
3750 return true;
3751 case GL_POINTS:
3752 case GL_LINES:
3753 case GL_LINE_LOOP:
3754 case GL_LINE_STRIP:
3755 return false;
3756 default: UNREACHABLE();
3757 }
3758
3759 return false;
3760}
3761
3762void Context::setVertexAttrib(GLuint index, const GLfloat *values)
3763{
3764 ASSERT(index < gl::MAX_VERTEX_ATTRIBS);
3765
3766 mState.vertexAttribute[index].mCurrentValue[0] = values[0];
3767 mState.vertexAttribute[index].mCurrentValue[1] = values[1];
3768 mState.vertexAttribute[index].mCurrentValue[2] = values[2];
3769 mState.vertexAttribute[index].mCurrentValue[3] = values[3];
3770
3771 mVertexDataManager->dirtyCurrentValue(index);
3772}
3773
3774void Context::setVertexAttribDivisor(GLuint index, GLuint divisor)
3775{
3776 ASSERT(index < gl::MAX_VERTEX_ATTRIBS);
3777
3778 mState.vertexAttribute[index].mDivisor = divisor;
3779}
3780
3781// keep list sorted in following order
3782// OES extensions
3783// EXT extensions
3784// Vendor extensions
3785void Context::initExtensionString()
3786{
3787 mExtensionString = "";
3788
3789 // OES extensions
3790 if (supports32bitIndices())
3791 {
3792 mExtensionString += "GL_OES_element_index_uint ";
3793 }
3794
3795 mExtensionString += "GL_OES_packed_depth_stencil ";
3796 mExtensionString += "GL_OES_get_program_binary ";
3797 mExtensionString += "GL_OES_rgb8_rgba8 ";
3798 mExtensionString += "GL_OES_standard_derivatives ";
3799
3800 if (supportsFloat16Textures())
3801 {
3802 mExtensionString += "GL_OES_texture_half_float ";
3803 }
3804 if (supportsFloat16LinearFilter())
3805 {
3806 mExtensionString += "GL_OES_texture_half_float_linear ";
3807 }
3808 if (supportsFloat32Textures())
3809 {
3810 mExtensionString += "GL_OES_texture_float ";
3811 }
3812 if (supportsFloat32LinearFilter())
3813 {
3814 mExtensionString += "GL_OES_texture_float_linear ";
3815 }
3816
3817 if (supportsNonPower2Texture())
3818 {
3819 mExtensionString += "GL_OES_texture_npot ";
3820 }
3821
3822 // Multi-vendor (EXT) extensions
3823 if (supportsOcclusionQueries())
3824 {
3825 mExtensionString += "GL_EXT_occlusion_query_boolean ";
3826 }
3827
3828 mExtensionString += "GL_EXT_read_format_bgra ";
3829 mExtensionString += "GL_EXT_robustness ";
3830
3831 if (supportsDXT1Textures())
3832 {
3833 mExtensionString += "GL_EXT_texture_compression_dxt1 ";
3834 }
3835
daniel@transgaming.com07ab8412012-07-12 15:17:09 +00003836 if (supportsTextureFilterAnisotropy())
3837 {
3838 mExtensionString += "GL_EXT_texture_filter_anisotropic ";
3839 }
3840
apatrick@chromium.org144f2802012-07-12 01:42:34 +00003841 mExtensionString += "GL_EXT_texture_format_BGRA8888 ";
3842 mExtensionString += "GL_EXT_texture_storage ";
3843
3844 // ANGLE-specific extensions
3845 if (supportsDepthTextures())
3846 {
3847 mExtensionString += "GL_ANGLE_depth_texture ";
3848 }
3849
3850 mExtensionString += "GL_ANGLE_framebuffer_blit ";
3851 if (getMaxSupportedSamples() != 0)
3852 {
3853 mExtensionString += "GL_ANGLE_framebuffer_multisample ";
3854 }
3855
3856 if (supportsInstancing())
3857 {
3858 mExtensionString += "GL_ANGLE_instanced_arrays ";
3859 }
3860
3861 mExtensionString += "GL_ANGLE_pack_reverse_row_order ";
3862
3863 if (supportsDXT3Textures())
3864 {
3865 mExtensionString += "GL_ANGLE_texture_compression_dxt3 ";
3866 }
3867 if (supportsDXT5Textures())
3868 {
3869 mExtensionString += "GL_ANGLE_texture_compression_dxt5 ";
3870 }
3871
3872 mExtensionString += "GL_ANGLE_texture_usage ";
3873 mExtensionString += "GL_ANGLE_translated_shader_source ";
3874
3875 // Other vendor-specific extensions
3876 if (supportsEventQueries())
3877 {
3878 mExtensionString += "GL_NV_fence ";
3879 }
3880
3881 std::string::size_type end = mExtensionString.find_last_not_of(' ');
3882 if (end != std::string::npos)
3883 {
3884 mExtensionString.resize(end+1);
3885 }
3886}
3887
3888const char *Context::getExtensionString() const
3889{
3890 return mExtensionString.c_str();
3891}
3892
3893void Context::initRendererString()
3894{
apatrick@chromium.org144f2802012-07-12 01:42:34 +00003895 mRendererString = "ANGLE (";
daniel@transgaming.com4ca789e2012-10-31 18:46:40 +00003896 mRendererString += mRenderer->getAdapterDescription();
apatrick@chromium.org144f2802012-07-12 01:42:34 +00003897 mRendererString += ")";
3898}
3899
3900const char *Context::getRendererString() const
3901{
3902 return mRendererString.c_str();
3903}
3904
3905void Context::blitFramebuffer(GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1,
3906 GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1,
3907 GLbitfield mask)
3908{
3909 Framebuffer *readFramebuffer = getReadFramebuffer();
3910 Framebuffer *drawFramebuffer = getDrawFramebuffer();
3911
3912 if (!readFramebuffer || readFramebuffer->completeness() != GL_FRAMEBUFFER_COMPLETE ||
3913 !drawFramebuffer || drawFramebuffer->completeness() != GL_FRAMEBUFFER_COMPLETE)
3914 {
3915 return error(GL_INVALID_FRAMEBUFFER_OPERATION);
3916 }
3917
3918 if (drawFramebuffer->getSamples() != 0)
3919 {
3920 return error(GL_INVALID_OPERATION);
3921 }
3922
3923 int readBufferWidth = readFramebuffer->getColorbuffer()->getWidth();
3924 int readBufferHeight = readFramebuffer->getColorbuffer()->getHeight();
3925 int drawBufferWidth = drawFramebuffer->getColorbuffer()->getWidth();
3926 int drawBufferHeight = drawFramebuffer->getColorbuffer()->getHeight();
3927
3928 RECT sourceRect;
3929 RECT destRect;
3930
3931 if (srcX0 < srcX1)
3932 {
3933 sourceRect.left = srcX0;
3934 sourceRect.right = srcX1;
3935 destRect.left = dstX0;
3936 destRect.right = dstX1;
3937 }
3938 else
3939 {
3940 sourceRect.left = srcX1;
3941 destRect.left = dstX1;
3942 sourceRect.right = srcX0;
3943 destRect.right = dstX0;
3944 }
3945
3946 if (srcY0 < srcY1)
3947 {
3948 sourceRect.bottom = srcY1;
3949 destRect.bottom = dstY1;
3950 sourceRect.top = srcY0;
3951 destRect.top = dstY0;
3952 }
3953 else
3954 {
3955 sourceRect.bottom = srcY0;
3956 destRect.bottom = dstY0;
3957 sourceRect.top = srcY1;
3958 destRect.top = dstY1;
3959 }
3960
3961 RECT sourceScissoredRect = sourceRect;
3962 RECT destScissoredRect = destRect;
3963
3964 if (mState.scissorTest)
3965 {
3966 // Only write to parts of the destination framebuffer which pass the scissor test
3967 // Please note: the destRect is now in D3D-style coordinates, so the *top* of the
3968 // rect will be checked against scissorY, rather than the bottom.
3969 if (destRect.left < mState.scissorX)
3970 {
3971 int xDiff = mState.scissorX - destRect.left;
3972 destScissoredRect.left = mState.scissorX;
3973 sourceScissoredRect.left += xDiff;
3974 }
3975
3976 if (destRect.right > mState.scissorX + mState.scissorWidth)
3977 {
3978 int xDiff = destRect.right - (mState.scissorX + mState.scissorWidth);
3979 destScissoredRect.right = mState.scissorX + mState.scissorWidth;
3980 sourceScissoredRect.right -= xDiff;
3981 }
3982
3983 if (destRect.top < mState.scissorY)
3984 {
3985 int yDiff = mState.scissorY - destRect.top;
3986 destScissoredRect.top = mState.scissorY;
3987 sourceScissoredRect.top += yDiff;
3988 }
3989
3990 if (destRect.bottom > mState.scissorY + mState.scissorHeight)
3991 {
3992 int yDiff = destRect.bottom - (mState.scissorY + mState.scissorHeight);
3993 destScissoredRect.bottom = mState.scissorY + mState.scissorHeight;
3994 sourceScissoredRect.bottom -= yDiff;
3995 }
3996 }
3997
3998 bool blitRenderTarget = false;
3999 bool blitDepthStencil = false;
4000
4001 RECT sourceTrimmedRect = sourceScissoredRect;
4002 RECT destTrimmedRect = destScissoredRect;
4003
4004 // The source & destination rectangles also may need to be trimmed if they fall out of the bounds of
4005 // the actual draw and read surfaces.
4006 if (sourceTrimmedRect.left < 0)
4007 {
4008 int xDiff = 0 - sourceTrimmedRect.left;
4009 sourceTrimmedRect.left = 0;
4010 destTrimmedRect.left += xDiff;
4011 }
4012
4013 if (sourceTrimmedRect.right > readBufferWidth)
4014 {
4015 int xDiff = sourceTrimmedRect.right - readBufferWidth;
4016 sourceTrimmedRect.right = readBufferWidth;
4017 destTrimmedRect.right -= xDiff;
4018 }
4019
4020 if (sourceTrimmedRect.top < 0)
4021 {
4022 int yDiff = 0 - sourceTrimmedRect.top;
4023 sourceTrimmedRect.top = 0;
4024 destTrimmedRect.top += yDiff;
4025 }
4026
4027 if (sourceTrimmedRect.bottom > readBufferHeight)
4028 {
4029 int yDiff = sourceTrimmedRect.bottom - readBufferHeight;
4030 sourceTrimmedRect.bottom = readBufferHeight;
4031 destTrimmedRect.bottom -= yDiff;
4032 }
4033
4034 if (destTrimmedRect.left < 0)
4035 {
4036 int xDiff = 0 - destTrimmedRect.left;
4037 destTrimmedRect.left = 0;
4038 sourceTrimmedRect.left += xDiff;
4039 }
4040
4041 if (destTrimmedRect.right > drawBufferWidth)
4042 {
4043 int xDiff = destTrimmedRect.right - drawBufferWidth;
4044 destTrimmedRect.right = drawBufferWidth;
4045 sourceTrimmedRect.right -= xDiff;
4046 }
4047
4048 if (destTrimmedRect.top < 0)
4049 {
4050 int yDiff = 0 - destTrimmedRect.top;
4051 destTrimmedRect.top = 0;
4052 sourceTrimmedRect.top += yDiff;
4053 }
4054
4055 if (destTrimmedRect.bottom > drawBufferHeight)
4056 {
4057 int yDiff = destTrimmedRect.bottom - drawBufferHeight;
4058 destTrimmedRect.bottom = drawBufferHeight;
4059 sourceTrimmedRect.bottom -= yDiff;
4060 }
4061
4062 bool partialBufferCopy = false;
4063 if (sourceTrimmedRect.bottom - sourceTrimmedRect.top < readBufferHeight ||
4064 sourceTrimmedRect.right - sourceTrimmedRect.left < readBufferWidth ||
4065 destTrimmedRect.bottom - destTrimmedRect.top < drawBufferHeight ||
4066 destTrimmedRect.right - destTrimmedRect.left < drawBufferWidth ||
4067 sourceTrimmedRect.top != 0 || destTrimmedRect.top != 0 || sourceTrimmedRect.left != 0 || destTrimmedRect.left != 0)
4068 {
4069 partialBufferCopy = true;
4070 }
4071
4072 if (mask & GL_COLOR_BUFFER_BIT)
4073 {
4074 const bool validReadType = readFramebuffer->getColorbufferType() == GL_TEXTURE_2D ||
4075 readFramebuffer->getColorbufferType() == GL_RENDERBUFFER;
4076 const bool validDrawType = drawFramebuffer->getColorbufferType() == GL_TEXTURE_2D ||
4077 drawFramebuffer->getColorbufferType() == GL_RENDERBUFFER;
4078 if (!validReadType || !validDrawType ||
4079 readFramebuffer->getColorbuffer()->getD3DFormat() != drawFramebuffer->getColorbuffer()->getD3DFormat())
4080 {
4081 ERR("Color buffer format conversion in BlitFramebufferANGLE not supported by this implementation");
4082 return error(GL_INVALID_OPERATION);
4083 }
4084
4085 if (partialBufferCopy && readFramebuffer->getSamples() != 0)
4086 {
4087 return error(GL_INVALID_OPERATION);
4088 }
4089
4090 blitRenderTarget = true;
4091
4092 }
4093
4094 if (mask & (GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT))
4095 {
4096 Renderbuffer *readDSBuffer = NULL;
4097 Renderbuffer *drawDSBuffer = NULL;
4098
4099 // We support OES_packed_depth_stencil, and do not support a separately attached depth and stencil buffer, so if we have
4100 // both a depth and stencil buffer, it will be the same buffer.
4101
4102 if (mask & GL_DEPTH_BUFFER_BIT)
4103 {
4104 if (readFramebuffer->getDepthbuffer() && drawFramebuffer->getDepthbuffer())
4105 {
4106 if (readFramebuffer->getDepthbufferType() != drawFramebuffer->getDepthbufferType() ||
4107 readFramebuffer->getDepthbuffer()->getD3DFormat() != drawFramebuffer->getDepthbuffer()->getD3DFormat())
4108 {
4109 return error(GL_INVALID_OPERATION);
4110 }
4111
4112 blitDepthStencil = true;
4113 readDSBuffer = readFramebuffer->getDepthbuffer();
4114 drawDSBuffer = drawFramebuffer->getDepthbuffer();
4115 }
4116 }
4117
4118 if (mask & GL_STENCIL_BUFFER_BIT)
4119 {
4120 if (readFramebuffer->getStencilbuffer() && drawFramebuffer->getStencilbuffer())
4121 {
4122 if (readFramebuffer->getStencilbufferType() != drawFramebuffer->getStencilbufferType() ||
4123 readFramebuffer->getStencilbuffer()->getD3DFormat() != drawFramebuffer->getStencilbuffer()->getD3DFormat())
4124 {
4125 return error(GL_INVALID_OPERATION);
4126 }
4127
4128 blitDepthStencil = true;
4129 readDSBuffer = readFramebuffer->getStencilbuffer();
4130 drawDSBuffer = drawFramebuffer->getStencilbuffer();
4131 }
4132 }
4133
4134 if (partialBufferCopy)
4135 {
4136 ERR("Only whole-buffer depth and stencil blits are supported by this implementation.");
4137 return error(GL_INVALID_OPERATION); // only whole-buffer copies are permitted
4138 }
4139
4140 if ((drawDSBuffer && drawDSBuffer->getSamples() != 0) ||
4141 (readDSBuffer && readDSBuffer->getSamples() != 0))
4142 {
4143 return error(GL_INVALID_OPERATION);
4144 }
4145 }
4146
4147 if (blitRenderTarget || blitDepthStencil)
4148 {
daniel@transgaming.com621ce052012-10-31 17:52:29 +00004149 mRenderer->endScene();
apatrick@chromium.org144f2802012-07-12 01:42:34 +00004150
4151 if (blitRenderTarget)
4152 {
4153 IDirect3DSurface9* readRenderTarget = readFramebuffer->getRenderTarget();
4154 IDirect3DSurface9* drawRenderTarget = drawFramebuffer->getRenderTarget();
4155
4156 HRESULT result = mDevice->StretchRect(readRenderTarget, &sourceTrimmedRect,
4157 drawRenderTarget, &destTrimmedRect, D3DTEXF_NONE);
4158
4159 readRenderTarget->Release();
4160 drawRenderTarget->Release();
4161
4162 if (FAILED(result))
4163 {
4164 ERR("BlitFramebufferANGLE failed: StretchRect returned %x.", result);
4165 return;
4166 }
4167 }
4168
4169 if (blitDepthStencil)
4170 {
4171 IDirect3DSurface9* readDepthStencil = readFramebuffer->getDepthStencil();
4172 IDirect3DSurface9* drawDepthStencil = drawFramebuffer->getDepthStencil();
4173
4174 HRESULT result = mDevice->StretchRect(readDepthStencil, NULL, drawDepthStencil, NULL, D3DTEXF_NONE);
4175
4176 readDepthStencil->Release();
4177 drawDepthStencil->Release();
4178
4179 if (FAILED(result))
4180 {
4181 ERR("BlitFramebufferANGLE failed: StretchRect returned %x.", result);
4182 return;
4183 }
4184 }
4185 }
4186}
4187
4188VertexDeclarationCache::VertexDeclarationCache() : mMaxLru(0)
4189{
4190 for (int i = 0; i < NUM_VERTEX_DECL_CACHE_ENTRIES; i++)
4191 {
4192 mVertexDeclCache[i].vertexDeclaration = NULL;
4193 mVertexDeclCache[i].lruCount = 0;
4194 }
4195}
4196
4197VertexDeclarationCache::~VertexDeclarationCache()
4198{
4199 for (int i = 0; i < NUM_VERTEX_DECL_CACHE_ENTRIES; i++)
4200 {
4201 if (mVertexDeclCache[i].vertexDeclaration)
4202 {
4203 mVertexDeclCache[i].vertexDeclaration->Release();
4204 }
4205 }
4206}
4207
daniel@transgaming.com5ae3ccc2012-07-24 18:29:38 +00004208GLenum VertexDeclarationCache::applyDeclaration(IDirect3DDevice9 *device, TranslatedAttribute attributes[], ProgramBinary *programBinary, GLsizei instances, GLsizei *repeatDraw)
apatrick@chromium.org144f2802012-07-12 01:42:34 +00004209{
4210 *repeatDraw = 1;
4211
4212 int indexedAttribute = MAX_VERTEX_ATTRIBS;
4213 int instancedAttribute = MAX_VERTEX_ATTRIBS;
4214
4215 if (instances > 0)
4216 {
4217 // Find an indexed attribute to be mapped to D3D stream 0
4218 for (int i = 0; i < MAX_VERTEX_ATTRIBS; i++)
4219 {
4220 if (attributes[i].active)
4221 {
4222 if (indexedAttribute == MAX_VERTEX_ATTRIBS)
4223 {
4224 if (attributes[i].divisor == 0)
4225 {
4226 indexedAttribute = i;
4227 }
4228 }
4229 else if (instancedAttribute == MAX_VERTEX_ATTRIBS)
4230 {
4231 if (attributes[i].divisor != 0)
4232 {
4233 instancedAttribute = i;
4234 }
4235 }
4236 else break; // Found both an indexed and instanced attribute
4237 }
4238 }
4239
4240 if (indexedAttribute == MAX_VERTEX_ATTRIBS)
4241 {
4242 return GL_INVALID_OPERATION;
4243 }
4244 }
4245
4246 D3DVERTEXELEMENT9 elements[MAX_VERTEX_ATTRIBS + 1];
4247 D3DVERTEXELEMENT9 *element = &elements[0];
4248
apatrick@chromium.org144f2802012-07-12 01:42:34 +00004249 for (int i = 0; i < MAX_VERTEX_ATTRIBS; i++)
4250 {
4251 if (attributes[i].active)
4252 {
4253 int stream = i;
4254
4255 if (instances > 0)
4256 {
4257 // Due to a bug on ATI cards we can't enable instancing when none of the attributes are instanced.
4258 if (instancedAttribute == MAX_VERTEX_ATTRIBS)
4259 {
4260 *repeatDraw = instances;
4261 }
4262 else
4263 {
4264 if (i == indexedAttribute)
4265 {
4266 stream = 0;
4267 }
4268 else if (i == 0)
4269 {
4270 stream = indexedAttribute;
4271 }
4272
4273 UINT frequency = 1;
4274
4275 if (attributes[i].divisor == 0)
4276 {
4277 frequency = D3DSTREAMSOURCE_INDEXEDDATA | instances;
4278 }
4279 else
4280 {
4281 frequency = D3DSTREAMSOURCE_INSTANCEDATA | attributes[i].divisor;
4282 }
4283
4284 device->SetStreamSourceFreq(stream, frequency);
4285 mInstancingEnabled = true;
4286 }
4287 }
4288
4289 if (mAppliedVBs[stream].serial != attributes[i].serial ||
4290 mAppliedVBs[stream].stride != attributes[i].stride ||
4291 mAppliedVBs[stream].offset != attributes[i].offset)
4292 {
4293 device->SetStreamSource(stream, attributes[i].vertexBuffer, attributes[i].offset, attributes[i].stride);
4294 mAppliedVBs[stream].serial = attributes[i].serial;
4295 mAppliedVBs[stream].stride = attributes[i].stride;
4296 mAppliedVBs[stream].offset = attributes[i].offset;
4297 }
4298
4299 element->Stream = stream;
4300 element->Offset = 0;
4301 element->Type = attributes[i].type;
4302 element->Method = D3DDECLMETHOD_DEFAULT;
4303 element->Usage = D3DDECLUSAGE_TEXCOORD;
4304 element->UsageIndex = programBinary->getSemanticIndex(i);
4305 element++;
4306 }
4307 }
4308
4309 if (instances == 0 || instancedAttribute == MAX_VERTEX_ATTRIBS)
4310 {
4311 if (mInstancingEnabled)
4312 {
4313 for (int i = 0; i < MAX_VERTEX_ATTRIBS; i++)
4314 {
4315 device->SetStreamSourceFreq(i, 1);
4316 }
4317
4318 mInstancingEnabled = false;
4319 }
4320 }
4321
4322 static const D3DVERTEXELEMENT9 end = D3DDECL_END();
4323 *(element++) = end;
4324
4325 for (int i = 0; i < NUM_VERTEX_DECL_CACHE_ENTRIES; i++)
4326 {
4327 VertexDeclCacheEntry *entry = &mVertexDeclCache[i];
4328 if (memcmp(entry->cachedElements, elements, (element - elements) * sizeof(D3DVERTEXELEMENT9)) == 0 && entry->vertexDeclaration)
4329 {
4330 entry->lruCount = ++mMaxLru;
4331 if(entry->vertexDeclaration != mLastSetVDecl)
4332 {
4333 device->SetVertexDeclaration(entry->vertexDeclaration);
4334 mLastSetVDecl = entry->vertexDeclaration;
4335 }
4336
4337 return GL_NO_ERROR;
4338 }
4339 }
4340
4341 VertexDeclCacheEntry *lastCache = mVertexDeclCache;
4342
4343 for (int i = 0; i < NUM_VERTEX_DECL_CACHE_ENTRIES; i++)
4344 {
4345 if (mVertexDeclCache[i].lruCount < lastCache->lruCount)
4346 {
4347 lastCache = &mVertexDeclCache[i];
4348 }
4349 }
4350
4351 if (lastCache->vertexDeclaration != NULL)
4352 {
4353 lastCache->vertexDeclaration->Release();
4354 lastCache->vertexDeclaration = NULL;
4355 // mLastSetVDecl is set to the replacement, so we don't have to worry
4356 // about it.
4357 }
4358
4359 memcpy(lastCache->cachedElements, elements, (element - elements) * sizeof(D3DVERTEXELEMENT9));
4360 device->CreateVertexDeclaration(elements, &lastCache->vertexDeclaration);
4361 device->SetVertexDeclaration(lastCache->vertexDeclaration);
4362 mLastSetVDecl = lastCache->vertexDeclaration;
4363 lastCache->lruCount = ++mMaxLru;
4364
4365 return GL_NO_ERROR;
4366}
4367
4368void VertexDeclarationCache::markStateDirty()
4369{
4370 for (int i = 0; i < MAX_VERTEX_ATTRIBS; i++)
4371 {
4372 mAppliedVBs[i].serial = 0;
4373 }
4374
4375 mLastSetVDecl = NULL;
4376 mInstancingEnabled = true; // Forces it to be disabled when not used
4377}
4378
4379}
4380
4381extern "C"
4382{
daniel@transgaming.com21290e62012-10-31 18:38:28 +00004383gl::Context *glCreateContext(const gl::Context *shareContext, bool notifyResets, bool robustAccess)
apatrick@chromium.org144f2802012-07-12 01:42:34 +00004384{
daniel@transgaming.com21290e62012-10-31 18:38:28 +00004385 return new gl::Context(shareContext, notifyResets, robustAccess);
apatrick@chromium.org144f2802012-07-12 01:42:34 +00004386}
4387
4388void glDestroyContext(gl::Context *context)
4389{
4390 delete context;
4391
4392 if (context == gl::getContext())
4393 {
4394 gl::makeCurrent(NULL, NULL, NULL);
4395 }
4396}
4397
4398void glMakeCurrent(gl::Context *context, egl::Display *display, egl::Surface *surface)
4399{
4400 gl::makeCurrent(context, display, surface);
4401}
4402
4403gl::Context *glGetCurrentContext()
4404{
4405 return gl::getContext();
4406}
daniel@transgaming.com621ce052012-10-31 17:52:29 +00004407
daniel@transgaming.com2507f412012-10-31 18:46:48 +00004408renderer::Renderer9 *glCreateRenderer(egl::Display *display, HMODULE hModule, HDC hDc)
daniel@transgaming.com621ce052012-10-31 17:52:29 +00004409{
daniel@transgaming.com2507f412012-10-31 18:46:48 +00004410 return new renderer::Renderer9(display, hModule, hDc); // D3D9_REPLACE
daniel@transgaming.com621ce052012-10-31 17:52:29 +00004411}
4412
4413void glDestroyRenderer(renderer::Renderer *renderer)
4414{
4415 delete renderer;
4416}
4417
daniel@transgaming.com2507f412012-10-31 18:46:48 +00004418renderer::SwapChain *glCreateSwapChain(renderer::Renderer9 *renderer, HWND window, HANDLE shareHandle,
daniel@transgaming.com3c720782012-10-31 18:42:34 +00004419 GLenum backBufferFormat, GLenum depthBufferFormat)
4420{
4421 return new renderer::SwapChain(renderer, window, shareHandle, backBufferFormat, depthBufferFormat);
4422}
4423
4424void glDestroySwapChain(renderer::SwapChain *swapChain)
4425{
4426 delete swapChain;
4427}
4428
4429
apatrick@chromium.org144f2802012-07-12 01:42:34 +00004430}