blob: bf780d8d8e4ea943e6a9bb58f3a1ad732cd4e001 [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.com621ce052012-10-31 17:52:29 +00002059 D3DADAPTER_IDENTIFIER9 *identifier = mRenderer->getAdapterIdentifier();
apatrick@chromium.org144f2802012-07-12 01:42:34 +00002060 bool zeroColorMaskAllowed = identifier->VendorId != 0x1002;
2061 // Apparently some ATI cards have a bug where a draw with a zero color
2062 // write mask can cause later draws to have incorrect results. Instead,
2063 // set a nonzero color write mask but modify the blend state so that no
2064 // drawing is done.
2065 // http://code.google.com/p/angleproject/issues/detail?id=169
2066
2067 if (mCullStateDirty || mFrontFaceDirty)
2068 {
2069 if (mState.cullFace)
2070 {
2071 mDevice->SetRenderState(D3DRS_CULLMODE, es2dx::ConvertCullMode(mState.cullMode, mState.frontFace));
2072 }
2073 else
2074 {
2075 mDevice->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE);
2076 }
2077
2078 mCullStateDirty = false;
2079 }
2080
2081 if (mDepthStateDirty)
2082 {
2083 if (mState.depthTest)
2084 {
2085 mDevice->SetRenderState(D3DRS_ZENABLE, D3DZB_TRUE);
2086 mDevice->SetRenderState(D3DRS_ZFUNC, es2dx::ConvertComparison(mState.depthFunc));
2087 }
2088 else
2089 {
2090 mDevice->SetRenderState(D3DRS_ZENABLE, D3DZB_FALSE);
2091 }
2092
2093 mDepthStateDirty = false;
2094 }
2095
2096 if (!zeroColorMaskAllowed && (mMaskStateDirty || mBlendStateDirty))
2097 {
2098 mBlendStateDirty = true;
2099 mMaskStateDirty = true;
2100 }
2101
2102 if (mBlendStateDirty)
2103 {
2104 if (mState.blend)
2105 {
2106 mDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, TRUE);
2107
2108 if (mState.sourceBlendRGB != GL_CONSTANT_ALPHA && mState.sourceBlendRGB != GL_ONE_MINUS_CONSTANT_ALPHA &&
2109 mState.destBlendRGB != GL_CONSTANT_ALPHA && mState.destBlendRGB != GL_ONE_MINUS_CONSTANT_ALPHA)
2110 {
2111 mDevice->SetRenderState(D3DRS_BLENDFACTOR, es2dx::ConvertColor(mState.blendColor));
2112 }
2113 else
2114 {
2115 mDevice->SetRenderState(D3DRS_BLENDFACTOR, D3DCOLOR_RGBA(unorm<8>(mState.blendColor.alpha),
2116 unorm<8>(mState.blendColor.alpha),
2117 unorm<8>(mState.blendColor.alpha),
2118 unorm<8>(mState.blendColor.alpha)));
2119 }
2120
2121 mDevice->SetRenderState(D3DRS_SRCBLEND, es2dx::ConvertBlendFunc(mState.sourceBlendRGB));
2122 mDevice->SetRenderState(D3DRS_DESTBLEND, es2dx::ConvertBlendFunc(mState.destBlendRGB));
2123 mDevice->SetRenderState(D3DRS_BLENDOP, es2dx::ConvertBlendOp(mState.blendEquationRGB));
2124
2125 if (mState.sourceBlendRGB != mState.sourceBlendAlpha ||
2126 mState.destBlendRGB != mState.destBlendAlpha ||
2127 mState.blendEquationRGB != mState.blendEquationAlpha)
2128 {
2129 mDevice->SetRenderState(D3DRS_SEPARATEALPHABLENDENABLE, TRUE);
2130
2131 mDevice->SetRenderState(D3DRS_SRCBLENDALPHA, es2dx::ConvertBlendFunc(mState.sourceBlendAlpha));
2132 mDevice->SetRenderState(D3DRS_DESTBLENDALPHA, es2dx::ConvertBlendFunc(mState.destBlendAlpha));
2133 mDevice->SetRenderState(D3DRS_BLENDOPALPHA, es2dx::ConvertBlendOp(mState.blendEquationAlpha));
2134 }
2135 else
2136 {
2137 mDevice->SetRenderState(D3DRS_SEPARATEALPHABLENDENABLE, FALSE);
2138 }
2139 }
2140 else
2141 {
2142 mDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, FALSE);
2143 }
2144
2145 mBlendStateDirty = false;
2146 }
2147
2148 if (mStencilStateDirty || mFrontFaceDirty)
2149 {
2150 if (mState.stencilTest && framebufferObject->hasStencil())
2151 {
2152 mDevice->SetRenderState(D3DRS_STENCILENABLE, TRUE);
2153 mDevice->SetRenderState(D3DRS_TWOSIDEDSTENCILMODE, TRUE);
2154
2155 // FIXME: Unsupported by D3D9
2156 const D3DRENDERSTATETYPE D3DRS_CCW_STENCILREF = D3DRS_STENCILREF;
2157 const D3DRENDERSTATETYPE D3DRS_CCW_STENCILMASK = D3DRS_STENCILMASK;
2158 const D3DRENDERSTATETYPE D3DRS_CCW_STENCILWRITEMASK = D3DRS_STENCILWRITEMASK;
2159 if (mState.stencilWritemask != mState.stencilBackWritemask ||
2160 mState.stencilRef != mState.stencilBackRef ||
2161 mState.stencilMask != mState.stencilBackMask)
2162 {
2163 ERR("Separate front/back stencil writemasks, reference values, or stencil mask values are invalid under WebGL.");
2164 return error(GL_INVALID_OPERATION);
2165 }
2166
2167 // get the maximum size of the stencil ref
2168 gl::Renderbuffer *stencilbuffer = framebufferObject->getStencilbuffer();
2169 GLuint maxStencil = (1 << stencilbuffer->getStencilSize()) - 1;
2170
2171 mDevice->SetRenderState(mState.frontFace == GL_CCW ? D3DRS_STENCILWRITEMASK : D3DRS_CCW_STENCILWRITEMASK, mState.stencilWritemask);
2172 mDevice->SetRenderState(mState.frontFace == GL_CCW ? D3DRS_STENCILFUNC : D3DRS_CCW_STENCILFUNC,
2173 es2dx::ConvertComparison(mState.stencilFunc));
2174
2175 mDevice->SetRenderState(mState.frontFace == GL_CCW ? D3DRS_STENCILREF : D3DRS_CCW_STENCILREF, (mState.stencilRef < (GLint)maxStencil) ? mState.stencilRef : maxStencil);
2176 mDevice->SetRenderState(mState.frontFace == GL_CCW ? D3DRS_STENCILMASK : D3DRS_CCW_STENCILMASK, mState.stencilMask);
2177
2178 mDevice->SetRenderState(mState.frontFace == GL_CCW ? D3DRS_STENCILFAIL : D3DRS_CCW_STENCILFAIL,
2179 es2dx::ConvertStencilOp(mState.stencilFail));
2180 mDevice->SetRenderState(mState.frontFace == GL_CCW ? D3DRS_STENCILZFAIL : D3DRS_CCW_STENCILZFAIL,
2181 es2dx::ConvertStencilOp(mState.stencilPassDepthFail));
2182 mDevice->SetRenderState(mState.frontFace == GL_CCW ? D3DRS_STENCILPASS : D3DRS_CCW_STENCILPASS,
2183 es2dx::ConvertStencilOp(mState.stencilPassDepthPass));
2184
2185 mDevice->SetRenderState(mState.frontFace == GL_CW ? D3DRS_STENCILWRITEMASK : D3DRS_CCW_STENCILWRITEMASK, mState.stencilBackWritemask);
2186 mDevice->SetRenderState(mState.frontFace == GL_CW ? D3DRS_STENCILFUNC : D3DRS_CCW_STENCILFUNC,
2187 es2dx::ConvertComparison(mState.stencilBackFunc));
2188
2189 mDevice->SetRenderState(mState.frontFace == GL_CW ? D3DRS_STENCILREF : D3DRS_CCW_STENCILREF, (mState.stencilBackRef < (GLint)maxStencil) ? mState.stencilBackRef : maxStencil);
2190 mDevice->SetRenderState(mState.frontFace == GL_CW ? D3DRS_STENCILMASK : D3DRS_CCW_STENCILMASK, mState.stencilBackMask);
2191
2192 mDevice->SetRenderState(mState.frontFace == GL_CW ? D3DRS_STENCILFAIL : D3DRS_CCW_STENCILFAIL,
2193 es2dx::ConvertStencilOp(mState.stencilBackFail));
2194 mDevice->SetRenderState(mState.frontFace == GL_CW ? D3DRS_STENCILZFAIL : D3DRS_CCW_STENCILZFAIL,
2195 es2dx::ConvertStencilOp(mState.stencilBackPassDepthFail));
2196 mDevice->SetRenderState(mState.frontFace == GL_CW ? D3DRS_STENCILPASS : D3DRS_CCW_STENCILPASS,
2197 es2dx::ConvertStencilOp(mState.stencilBackPassDepthPass));
2198 }
2199 else
2200 {
2201 mDevice->SetRenderState(D3DRS_STENCILENABLE, FALSE);
2202 }
2203
2204 mStencilStateDirty = false;
2205 mFrontFaceDirty = false;
2206 }
2207
2208 if (mMaskStateDirty)
2209 {
2210 int colorMask = es2dx::ConvertColorMask(mState.colorMaskRed, mState.colorMaskGreen,
2211 mState.colorMaskBlue, mState.colorMaskAlpha);
2212 if (colorMask == 0 && !zeroColorMaskAllowed)
2213 {
2214 // Enable green channel, but set blending so nothing will be drawn.
2215 mDevice->SetRenderState(D3DRS_COLORWRITEENABLE, D3DCOLORWRITEENABLE_GREEN);
2216 mDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, TRUE);
2217
2218 mDevice->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_ZERO);
2219 mDevice->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_ONE);
2220 mDevice->SetRenderState(D3DRS_BLENDOP, D3DBLENDOP_ADD);
2221 }
2222 else
2223 {
2224 mDevice->SetRenderState(D3DRS_COLORWRITEENABLE, colorMask);
2225 }
2226 mDevice->SetRenderState(D3DRS_ZWRITEENABLE, mState.depthMask ? TRUE : FALSE);
2227
2228 mMaskStateDirty = false;
2229 }
2230
2231 if (mPolygonOffsetStateDirty)
2232 {
2233 if (mState.polygonOffsetFill)
2234 {
2235 gl::Renderbuffer *depthbuffer = framebufferObject->getDepthbuffer();
2236 if (depthbuffer)
2237 {
2238 mDevice->SetRenderState(D3DRS_SLOPESCALEDEPTHBIAS, *((DWORD*)&mState.polygonOffsetFactor));
2239 float depthBias = ldexp(mState.polygonOffsetUnits, -(int)(depthbuffer->getDepthSize()));
2240 mDevice->SetRenderState(D3DRS_DEPTHBIAS, *((DWORD*)&depthBias));
2241 }
2242 }
2243 else
2244 {
2245 mDevice->SetRenderState(D3DRS_SLOPESCALEDEPTHBIAS, 0);
2246 mDevice->SetRenderState(D3DRS_DEPTHBIAS, 0);
2247 }
2248
2249 mPolygonOffsetStateDirty = false;
2250 }
2251
2252 if (mSampleStateDirty)
2253 {
2254 if (mState.sampleAlphaToCoverage)
2255 {
2256 FIXME("Sample alpha to coverage is unimplemented.");
2257 }
2258
2259 mDevice->SetRenderState(D3DRS_MULTISAMPLEANTIALIAS, TRUE);
2260 if (mState.sampleCoverage)
2261 {
2262 unsigned int mask = 0;
2263 if (mState.sampleCoverageValue != 0)
2264 {
2265 float threshold = 0.5f;
2266
2267 for (int i = 0; i < framebufferObject->getSamples(); ++i)
2268 {
2269 mask <<= 1;
2270
2271 if ((i + 1) * mState.sampleCoverageValue >= threshold)
2272 {
2273 threshold += 1.0f;
2274 mask |= 1;
2275 }
2276 }
2277 }
2278
2279 if (mState.sampleCoverageInvert)
2280 {
2281 mask = ~mask;
2282 }
2283
2284 mDevice->SetRenderState(D3DRS_MULTISAMPLEMASK, mask);
2285 }
2286 else
2287 {
2288 mDevice->SetRenderState(D3DRS_MULTISAMPLEMASK, 0xFFFFFFFF);
2289 }
2290
2291 mSampleStateDirty = false;
2292 }
2293
2294 if (mDitherStateDirty)
2295 {
2296 mDevice->SetRenderState(D3DRS_DITHERENABLE, mState.dither ? TRUE : FALSE);
2297
2298 mDitherStateDirty = false;
2299 }
2300}
2301
2302GLenum Context::applyVertexBuffer(GLint first, GLsizei count, GLsizei instances, GLsizei *repeatDraw)
2303{
2304 TranslatedAttribute attributes[MAX_VERTEX_ATTRIBS];
2305
2306 GLenum err = mVertexDataManager->prepareVertexData(first, count, attributes, instances);
2307 if (err != GL_NO_ERROR)
2308 {
2309 return err;
2310 }
2311
daniel@transgaming.com62a28462012-07-24 18:33:59 +00002312 ProgramBinary *programBinary = getCurrentProgramBinary();
daniel@transgaming.com5ae3ccc2012-07-24 18:29:38 +00002313 return mVertexDeclarationCache.applyDeclaration(mDevice, attributes, programBinary, instances, repeatDraw);
apatrick@chromium.org144f2802012-07-12 01:42:34 +00002314}
2315
2316// Applies the indices and element array bindings to the Direct3D 9 device
2317GLenum Context::applyIndexBuffer(const GLvoid *indices, GLsizei count, GLenum mode, GLenum type, TranslatedIndexData *indexInfo)
2318{
2319 GLenum err = mIndexDataManager->prepareIndexData(type, count, mState.elementArrayBuffer.get(), indices, indexInfo);
2320
2321 if (err == GL_NO_ERROR)
2322 {
2323 if (indexInfo->serial != mAppliedIBSerial)
2324 {
2325 mDevice->SetIndices(indexInfo->indexBuffer);
2326 mAppliedIBSerial = indexInfo->serial;
2327 }
2328 }
2329
2330 return err;
2331}
2332
2333// Applies the shaders and shader constants to the Direct3D 9 device
2334void Context::applyShaders()
2335{
daniel@transgaming.com62a28462012-07-24 18:33:59 +00002336 ProgramBinary *programBinary = getCurrentProgramBinary();
apatrick@chromium.org144f2802012-07-12 01:42:34 +00002337
daniel@transgaming.come6af4f92012-07-24 18:31:31 +00002338 if (programBinary->getSerial() != mAppliedProgramBinarySerial)
apatrick@chromium.org144f2802012-07-12 01:42:34 +00002339 {
2340 IDirect3DVertexShader9 *vertexShader = programBinary->getVertexShader();
2341 IDirect3DPixelShader9 *pixelShader = programBinary->getPixelShader();
2342
2343 mDevice->SetPixelShader(pixelShader);
2344 mDevice->SetVertexShader(vertexShader);
2345 programBinary->dirtyAllUniforms();
daniel@transgaming.come6af4f92012-07-24 18:31:31 +00002346 mAppliedProgramBinarySerial = programBinary->getSerial();
apatrick@chromium.org144f2802012-07-12 01:42:34 +00002347 }
2348
2349 programBinary->applyUniforms();
2350}
2351
2352// Applies the textures and sampler states to the Direct3D 9 device
2353void Context::applyTextures()
2354{
2355 applyTextures(SAMPLER_PIXEL);
2356
2357 if (mSupportsVertexTexture)
2358 {
2359 applyTextures(SAMPLER_VERTEX);
2360 }
2361}
2362
2363// For each Direct3D 9 sampler of either the pixel or vertex stage,
2364// looks up the corresponding OpenGL texture image unit and texture type,
2365// and sets the texture and its addressing/filtering state (or NULL when inactive).
2366void Context::applyTextures(SamplerType type)
2367{
daniel@transgaming.com62a28462012-07-24 18:33:59 +00002368 ProgramBinary *programBinary = getCurrentProgramBinary();
apatrick@chromium.org144f2802012-07-12 01:42:34 +00002369
2370 int samplerCount = (type == SAMPLER_PIXEL) ? MAX_TEXTURE_IMAGE_UNITS : MAX_VERTEX_TEXTURE_IMAGE_UNITS_VTF; // Range of Direct3D 9 samplers of given sampler type
2371 unsigned int *appliedTextureSerial = (type == SAMPLER_PIXEL) ? mAppliedTextureSerialPS : mAppliedTextureSerialVS;
apatrick@chromium.org144f2802012-07-12 01:42:34 +00002372 int samplerRange = programBinary->getUsedSamplerRange(type);
2373
2374 for (int samplerIndex = 0; samplerIndex < samplerRange; samplerIndex++)
2375 {
2376 int textureUnit = programBinary->getSamplerMapping(type, samplerIndex); // OpenGL texture image unit index
apatrick@chromium.org144f2802012-07-12 01:42:34 +00002377
2378 if (textureUnit != -1)
2379 {
2380 TextureType textureType = programBinary->getSamplerTextureType(type, samplerIndex);
2381
2382 Texture *texture = getSamplerTexture(textureUnit, textureType);
2383 unsigned int texSerial = texture->getTextureSerial();
2384
2385 if (appliedTextureSerial[samplerIndex] != texSerial || texture->hasDirtyParameters() || texture->hasDirtyImages())
2386 {
daniel@transgaming.coma734f272012-10-31 18:07:48 +00002387 if (texture->isSamplerComplete())
apatrick@chromium.org144f2802012-07-12 01:42:34 +00002388 {
2389 if (appliedTextureSerial[samplerIndex] != texSerial || texture->hasDirtyParameters())
2390 {
daniel@transgaming.comebf139f2012-10-31 18:07:32 +00002391 SamplerState samplerState;
2392 texture->getSamplerState(&samplerState);
apatrick@chromium.org144f2802012-07-12 01:42:34 +00002393
daniel@transgaming.comba0570e2012-10-31 18:07:39 +00002394 mRenderer->setSamplerState(type, samplerIndex, samplerState);
apatrick@chromium.org144f2802012-07-12 01:42:34 +00002395 }
2396
2397 if (appliedTextureSerial[samplerIndex] != texSerial || texture->hasDirtyImages())
2398 {
daniel@transgaming.coma734f272012-10-31 18:07:48 +00002399 mRenderer->setTexture(type, samplerIndex, texture);
apatrick@chromium.org144f2802012-07-12 01:42:34 +00002400 }
2401 }
2402 else
2403 {
daniel@transgaming.coma734f272012-10-31 18:07:48 +00002404 mRenderer->setTexture(type, samplerIndex, getIncompleteTexture(textureType));
apatrick@chromium.org144f2802012-07-12 01:42:34 +00002405 }
2406
2407 appliedTextureSerial[samplerIndex] = texSerial;
2408 texture->resetDirty();
2409 }
2410 }
2411 else
2412 {
2413 if (appliedTextureSerial[samplerIndex] != 0)
2414 {
daniel@transgaming.coma734f272012-10-31 18:07:48 +00002415 mRenderer->setTexture(type, samplerIndex, NULL);
apatrick@chromium.org144f2802012-07-12 01:42:34 +00002416 appliedTextureSerial[samplerIndex] = 0;
2417 }
2418 }
2419 }
2420
2421 for (int samplerIndex = samplerRange; samplerIndex < samplerCount; samplerIndex++)
2422 {
2423 if (appliedTextureSerial[samplerIndex] != 0)
2424 {
daniel@transgaming.coma734f272012-10-31 18:07:48 +00002425 mRenderer->setTexture(type, samplerIndex, NULL);
apatrick@chromium.org144f2802012-07-12 01:42:34 +00002426 appliedTextureSerial[samplerIndex] = 0;
2427 }
2428 }
2429}
2430
2431void Context::readPixels(GLint x, GLint y, GLsizei width, GLsizei height,
2432 GLenum format, GLenum type, GLsizei *bufSize, void* pixels)
2433{
2434 Framebuffer *framebuffer = getReadFramebuffer();
2435
2436 if (framebuffer->completeness() != GL_FRAMEBUFFER_COMPLETE)
2437 {
2438 return error(GL_INVALID_FRAMEBUFFER_OPERATION);
2439 }
2440
2441 if (getReadFramebufferHandle() != 0 && framebuffer->getSamples() != 0)
2442 {
2443 return error(GL_INVALID_OPERATION);
2444 }
2445
daniel@transgaming.com6452adf2012-10-17 18:22:35 +00002446 GLsizei outputPitch = ComputePitch(width, ConvertSizedInternalFormat(format, type), mState.packAlignment);
apatrick@chromium.org144f2802012-07-12 01:42:34 +00002447 // sized query sanity check
2448 if (bufSize)
2449 {
2450 int requiredSize = outputPitch * height;
2451 if (requiredSize > *bufSize)
2452 {
2453 return error(GL_INVALID_OPERATION);
2454 }
2455 }
2456
2457 IDirect3DSurface9 *renderTarget = framebuffer->getRenderTarget();
2458 if (!renderTarget)
2459 {
2460 return; // Context must be lost, return silently
2461 }
2462
2463 D3DSURFACE_DESC desc;
2464 renderTarget->GetDesc(&desc);
2465
2466 if (desc.MultiSampleType != D3DMULTISAMPLE_NONE)
2467 {
2468 UNIMPLEMENTED(); // FIXME: Requires resolve using StretchRect into non-multisampled render target
2469 renderTarget->Release();
2470 return error(GL_OUT_OF_MEMORY);
2471 }
2472
2473 HRESULT result;
2474 IDirect3DSurface9 *systemSurface = NULL;
daniel@transgaming.com621ce052012-10-31 17:52:29 +00002475 bool directToPixels = !getPackReverseRowOrder() && getPackAlignment() <= 4 && mRenderer->isD3d9ExDevice() &&
apatrick@chromium.org144f2802012-07-12 01:42:34 +00002476 x == 0 && y == 0 && UINT(width) == desc.Width && UINT(height) == desc.Height &&
2477 desc.Format == D3DFMT_A8R8G8B8 && format == GL_BGRA_EXT && type == GL_UNSIGNED_BYTE;
2478 if (directToPixels)
2479 {
2480 // Use the pixels ptr as a shared handle to write directly into client's memory
2481 result = mDevice->CreateOffscreenPlainSurface(desc.Width, desc.Height, desc.Format,
2482 D3DPOOL_SYSTEMMEM, &systemSurface, &pixels);
2483 if (FAILED(result))
2484 {
2485 // Try again without the shared handle
2486 directToPixels = false;
2487 }
2488 }
2489
2490 if (!directToPixels)
2491 {
2492 result = mDevice->CreateOffscreenPlainSurface(desc.Width, desc.Height, desc.Format,
2493 D3DPOOL_SYSTEMMEM, &systemSurface, NULL);
2494 if (FAILED(result))
2495 {
2496 ASSERT(result == D3DERR_OUTOFVIDEOMEMORY || result == E_OUTOFMEMORY);
2497 renderTarget->Release();
2498 return error(GL_OUT_OF_MEMORY);
2499 }
2500 }
2501
2502 result = mDevice->GetRenderTargetData(renderTarget, systemSurface);
2503 renderTarget->Release();
2504 renderTarget = NULL;
2505
2506 if (FAILED(result))
2507 {
2508 systemSurface->Release();
2509
2510 // It turns out that D3D will sometimes produce more error
2511 // codes than those documented.
2512 if (checkDeviceLost(result))
2513 return error(GL_OUT_OF_MEMORY);
2514 else
2515 {
2516 UNREACHABLE();
2517 return;
2518 }
2519
2520 }
2521
2522 if (directToPixels)
2523 {
2524 systemSurface->Release();
2525 return;
2526 }
2527
2528 RECT rect;
2529 rect.left = clamp(x, 0L, static_cast<LONG>(desc.Width));
2530 rect.top = clamp(y, 0L, static_cast<LONG>(desc.Height));
2531 rect.right = clamp(x + width, 0L, static_cast<LONG>(desc.Width));
2532 rect.bottom = clamp(y + height, 0L, static_cast<LONG>(desc.Height));
2533
2534 D3DLOCKED_RECT lock;
2535 result = systemSurface->LockRect(&lock, &rect, D3DLOCK_READONLY);
2536
2537 if (FAILED(result))
2538 {
2539 UNREACHABLE();
2540 systemSurface->Release();
2541
2542 return; // No sensible error to generate
2543 }
2544
2545 unsigned char *dest = (unsigned char*)pixels;
2546 unsigned short *dest16 = (unsigned short*)pixels;
2547
2548 unsigned char *source;
2549 int inputPitch;
2550 if (getPackReverseRowOrder())
2551 {
2552 source = ((unsigned char*)lock.pBits) + lock.Pitch * (rect.bottom - rect.top - 1);
2553 inputPitch = -lock.Pitch;
2554 }
2555 else
2556 {
2557 source = (unsigned char*)lock.pBits;
2558 inputPitch = lock.Pitch;
2559 }
2560
daniel@transgaming.com42944b02012-09-27 17:45:57 +00002561 unsigned int fastPixelSize = 0;
2562
2563 if (desc.Format == D3DFMT_A8R8G8B8 &&
2564 format == GL_BGRA_EXT &&
2565 type == GL_UNSIGNED_BYTE)
2566 {
2567 fastPixelSize = 4;
2568 }
2569 else if ((desc.Format == D3DFMT_A4R4G4B4 &&
2570 format == GL_BGRA_EXT &&
2571 type == GL_UNSIGNED_SHORT_4_4_4_4_REV_EXT) ||
2572 (desc.Format == D3DFMT_A1R5G5B5 &&
2573 format == GL_BGRA_EXT &&
2574 type == GL_UNSIGNED_SHORT_1_5_5_5_REV_EXT))
2575 {
2576 fastPixelSize = 2;
2577 }
2578 else if (desc.Format == D3DFMT_A16B16G16R16F &&
2579 format == GL_RGBA &&
2580 type == GL_HALF_FLOAT_OES)
2581 {
2582 fastPixelSize = 8;
2583 }
2584 else if (desc.Format == D3DFMT_A32B32G32R32F &&
2585 format == GL_RGBA &&
2586 type == GL_FLOAT)
2587 {
2588 fastPixelSize = 16;
2589 }
2590
apatrick@chromium.org144f2802012-07-12 01:42:34 +00002591 for (int j = 0; j < rect.bottom - rect.top; j++)
2592 {
daniel@transgaming.com42944b02012-09-27 17:45:57 +00002593 if (fastPixelSize != 0)
apatrick@chromium.org144f2802012-07-12 01:42:34 +00002594 {
daniel@transgaming.com42944b02012-09-27 17:45:57 +00002595 // Fast path for formats which require no translation:
2596 // D3DFMT_A8R8G8B8 to BGRA/UNSIGNED_BYTE
2597 // D3DFMT_A4R4G4B4 to BGRA/UNSIGNED_SHORT_4_4_4_4_REV_EXT
2598 // D3DFMT_A1R5G5B5 to BGRA/UNSIGNED_SHORT_1_5_5_5_REV_EXT
2599 // D3DFMT_A16B16G16R16F to RGBA/HALF_FLOAT_OES
2600 // D3DFMT_A32B32G32R32F to RGBA/FLOAT
2601 //
2602 // Note that buffers with no alpha go through the slow path below.
apatrick@chromium.org144f2802012-07-12 01:42:34 +00002603 memcpy(dest + j * outputPitch,
2604 source + j * inputPitch,
daniel@transgaming.com42944b02012-09-27 17:45:57 +00002605 (rect.right - rect.left) * fastPixelSize);
apatrick@chromium.org144f2802012-07-12 01:42:34 +00002606 continue;
2607 }
2608
2609 for (int i = 0; i < rect.right - rect.left; i++)
2610 {
2611 float r;
2612 float g;
2613 float b;
2614 float a;
2615
2616 switch (desc.Format)
2617 {
2618 case D3DFMT_R5G6B5:
2619 {
2620 unsigned short rgb = *(unsigned short*)(source + 2 * i + j * inputPitch);
2621
2622 a = 1.0f;
2623 b = (rgb & 0x001F) * (1.0f / 0x001F);
2624 g = (rgb & 0x07E0) * (1.0f / 0x07E0);
2625 r = (rgb & 0xF800) * (1.0f / 0xF800);
2626 }
2627 break;
2628 case D3DFMT_A1R5G5B5:
2629 {
2630 unsigned short argb = *(unsigned short*)(source + 2 * i + j * inputPitch);
2631
2632 a = (argb & 0x8000) ? 1.0f : 0.0f;
2633 b = (argb & 0x001F) * (1.0f / 0x001F);
2634 g = (argb & 0x03E0) * (1.0f / 0x03E0);
2635 r = (argb & 0x7C00) * (1.0f / 0x7C00);
2636 }
2637 break;
2638 case D3DFMT_A8R8G8B8:
2639 {
2640 unsigned int argb = *(unsigned int*)(source + 4 * i + j * inputPitch);
2641
2642 a = (argb & 0xFF000000) * (1.0f / 0xFF000000);
2643 b = (argb & 0x000000FF) * (1.0f / 0x000000FF);
2644 g = (argb & 0x0000FF00) * (1.0f / 0x0000FF00);
2645 r = (argb & 0x00FF0000) * (1.0f / 0x00FF0000);
2646 }
2647 break;
2648 case D3DFMT_X8R8G8B8:
2649 {
2650 unsigned int xrgb = *(unsigned int*)(source + 4 * i + j * inputPitch);
2651
2652 a = 1.0f;
2653 b = (xrgb & 0x000000FF) * (1.0f / 0x000000FF);
2654 g = (xrgb & 0x0000FF00) * (1.0f / 0x0000FF00);
2655 r = (xrgb & 0x00FF0000) * (1.0f / 0x00FF0000);
2656 }
2657 break;
2658 case D3DFMT_A2R10G10B10:
2659 {
2660 unsigned int argb = *(unsigned int*)(source + 4 * i + j * inputPitch);
2661
2662 a = (argb & 0xC0000000) * (1.0f / 0xC0000000);
2663 b = (argb & 0x000003FF) * (1.0f / 0x000003FF);
2664 g = (argb & 0x000FFC00) * (1.0f / 0x000FFC00);
2665 r = (argb & 0x3FF00000) * (1.0f / 0x3FF00000);
2666 }
2667 break;
2668 case D3DFMT_A32B32G32R32F:
2669 {
2670 // float formats in D3D are stored rgba, rather than the other way round
2671 r = *((float*)(source + 16 * i + j * inputPitch) + 0);
2672 g = *((float*)(source + 16 * i + j * inputPitch) + 1);
2673 b = *((float*)(source + 16 * i + j * inputPitch) + 2);
2674 a = *((float*)(source + 16 * i + j * inputPitch) + 3);
2675 }
2676 break;
2677 case D3DFMT_A16B16G16R16F:
2678 {
2679 // float formats in D3D are stored rgba, rather than the other way round
apatrick@chromium.orgaa480672012-09-05 19:32:38 +00002680 r = float16ToFloat32(*((unsigned short*)(source + 8 * i + j * inputPitch) + 0));
2681 g = float16ToFloat32(*((unsigned short*)(source + 8 * i + j * inputPitch) + 1));
2682 b = float16ToFloat32(*((unsigned short*)(source + 8 * i + j * inputPitch) + 2));
2683 a = float16ToFloat32(*((unsigned short*)(source + 8 * i + j * inputPitch) + 3));
apatrick@chromium.org144f2802012-07-12 01:42:34 +00002684 }
2685 break;
2686 default:
2687 UNIMPLEMENTED(); // FIXME
2688 UNREACHABLE();
2689 return;
2690 }
2691
2692 switch (format)
2693 {
2694 case GL_RGBA:
2695 switch (type)
2696 {
2697 case GL_UNSIGNED_BYTE:
2698 dest[4 * i + j * outputPitch + 0] = (unsigned char)(255 * r + 0.5f);
2699 dest[4 * i + j * outputPitch + 1] = (unsigned char)(255 * g + 0.5f);
2700 dest[4 * i + j * outputPitch + 2] = (unsigned char)(255 * b + 0.5f);
2701 dest[4 * i + j * outputPitch + 3] = (unsigned char)(255 * a + 0.5f);
2702 break;
2703 default: UNREACHABLE();
2704 }
2705 break;
2706 case GL_BGRA_EXT:
2707 switch (type)
2708 {
2709 case GL_UNSIGNED_BYTE:
2710 dest[4 * i + j * outputPitch + 0] = (unsigned char)(255 * b + 0.5f);
2711 dest[4 * i + j * outputPitch + 1] = (unsigned char)(255 * g + 0.5f);
2712 dest[4 * i + j * outputPitch + 2] = (unsigned char)(255 * r + 0.5f);
2713 dest[4 * i + j * outputPitch + 3] = (unsigned char)(255 * a + 0.5f);
2714 break;
2715 case GL_UNSIGNED_SHORT_4_4_4_4_REV_EXT:
2716 // According to the desktop GL spec in the "Transfer of Pixel Rectangles" section
2717 // this type is packed as follows:
2718 // 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0
2719 // --------------------------------------------------------------------------------
2720 // | 4th | 3rd | 2nd | 1st component |
2721 // --------------------------------------------------------------------------------
2722 // in the case of BGRA_EXT, B is the first component, G the second, and so forth.
2723 dest16[i + j * outputPitch / sizeof(unsigned short)] =
2724 ((unsigned short)(15 * a + 0.5f) << 12)|
2725 ((unsigned short)(15 * r + 0.5f) << 8) |
2726 ((unsigned short)(15 * g + 0.5f) << 4) |
2727 ((unsigned short)(15 * b + 0.5f) << 0);
2728 break;
2729 case GL_UNSIGNED_SHORT_1_5_5_5_REV_EXT:
2730 // According to the desktop GL spec in the "Transfer of Pixel Rectangles" section
2731 // this type is packed as follows:
2732 // 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0
2733 // --------------------------------------------------------------------------------
2734 // | 4th | 3rd | 2nd | 1st component |
2735 // --------------------------------------------------------------------------------
2736 // in the case of BGRA_EXT, B is the first component, G the second, and so forth.
2737 dest16[i + j * outputPitch / sizeof(unsigned short)] =
2738 ((unsigned short)( a + 0.5f) << 15) |
2739 ((unsigned short)(31 * r + 0.5f) << 10) |
2740 ((unsigned short)(31 * g + 0.5f) << 5) |
2741 ((unsigned short)(31 * b + 0.5f) << 0);
2742 break;
2743 default: UNREACHABLE();
2744 }
2745 break;
daniel@transgaming.com42944b02012-09-27 17:45:57 +00002746 case GL_RGB:
apatrick@chromium.org144f2802012-07-12 01:42:34 +00002747 switch (type)
2748 {
daniel@transgaming.com42944b02012-09-27 17:45:57 +00002749 case GL_UNSIGNED_SHORT_5_6_5:
apatrick@chromium.org144f2802012-07-12 01:42:34 +00002750 dest16[i + j * outputPitch / sizeof(unsigned short)] =
2751 ((unsigned short)(31 * b + 0.5f) << 0) |
2752 ((unsigned short)(63 * g + 0.5f) << 5) |
2753 ((unsigned short)(31 * r + 0.5f) << 11);
2754 break;
daniel@transgaming.com42944b02012-09-27 17:45:57 +00002755 case GL_UNSIGNED_BYTE:
2756 dest[3 * i + j * outputPitch + 0] = (unsigned char)(255 * r + 0.5f);
2757 dest[3 * i + j * outputPitch + 1] = (unsigned char)(255 * g + 0.5f);
2758 dest[3 * i + j * outputPitch + 2] = (unsigned char)(255 * b + 0.5f);
2759 break;
apatrick@chromium.org144f2802012-07-12 01:42:34 +00002760 default: UNREACHABLE();
2761 }
2762 break;
2763 default: UNREACHABLE();
2764 }
2765 }
2766 }
2767
2768 systemSurface->UnlockRect();
2769
2770 systemSurface->Release();
2771}
2772
2773void Context::clear(GLbitfield mask)
2774{
2775 Framebuffer *framebufferObject = getDrawFramebuffer();
2776
2777 if (!framebufferObject || framebufferObject->completeness() != GL_FRAMEBUFFER_COMPLETE)
2778 {
2779 return error(GL_INVALID_FRAMEBUFFER_OPERATION);
2780 }
2781
2782 DWORD flags = 0;
2783
2784 if (mask & GL_COLOR_BUFFER_BIT)
2785 {
2786 mask &= ~GL_COLOR_BUFFER_BIT;
2787
2788 if (framebufferObject->getColorbufferType() != GL_NONE)
2789 {
2790 flags |= D3DCLEAR_TARGET;
2791 }
2792 }
2793
2794 if (mask & GL_DEPTH_BUFFER_BIT)
2795 {
2796 mask &= ~GL_DEPTH_BUFFER_BIT;
2797 if (mState.depthMask && framebufferObject->getDepthbufferType() != GL_NONE)
2798 {
2799 flags |= D3DCLEAR_ZBUFFER;
2800 }
2801 }
2802
2803 GLuint stencilUnmasked = 0x0;
2804
2805 if (mask & GL_STENCIL_BUFFER_BIT)
2806 {
2807 mask &= ~GL_STENCIL_BUFFER_BIT;
2808 if (framebufferObject->getStencilbufferType() != GL_NONE)
2809 {
2810 IDirect3DSurface9 *depthStencil = framebufferObject->getStencilbuffer()->getDepthStencil();
2811 if (!depthStencil)
2812 {
2813 ERR("Depth stencil pointer unexpectedly null.");
2814 return;
2815 }
2816
2817 D3DSURFACE_DESC desc;
2818 depthStencil->GetDesc(&desc);
2819 depthStencil->Release();
2820
2821 unsigned int stencilSize = dx2es::GetStencilSize(desc.Format);
2822 stencilUnmasked = (0x1 << stencilSize) - 1;
2823
2824 if (stencilUnmasked != 0x0)
2825 {
2826 flags |= D3DCLEAR_STENCIL;
2827 }
2828 }
2829 }
2830
2831 if (mask != 0)
2832 {
2833 return error(GL_INVALID_VALUE);
2834 }
2835
2836 if (!applyRenderTarget(true)) // Clips the clear to the scissor rectangle but not the viewport
2837 {
2838 return;
2839 }
2840
2841 D3DCOLOR color = D3DCOLOR_ARGB(unorm<8>(mState.colorClearValue.alpha),
2842 unorm<8>(mState.colorClearValue.red),
2843 unorm<8>(mState.colorClearValue.green),
2844 unorm<8>(mState.colorClearValue.blue));
2845 float depth = clamp01(mState.depthClearValue);
2846 int stencil = mState.stencilClearValue & 0x000000FF;
2847
2848 bool alphaUnmasked = (dx2es::GetAlphaSize(mRenderTargetDesc.Format) == 0) || mState.colorMaskAlpha;
2849
2850 const bool needMaskedStencilClear = (flags & D3DCLEAR_STENCIL) &&
2851 (mState.stencilWritemask & stencilUnmasked) != stencilUnmasked;
2852 const bool needMaskedColorClear = (flags & D3DCLEAR_TARGET) &&
2853 !(mState.colorMaskRed && mState.colorMaskGreen &&
2854 mState.colorMaskBlue && alphaUnmasked);
2855
2856 if (needMaskedColorClear || needMaskedStencilClear)
2857 {
2858 // State which is altered in all paths from this point to the clear call is saved.
2859 // State which is altered in only some paths will be flagged dirty in the case that
2860 // that path is taken.
2861 HRESULT hr;
2862 if (mMaskedClearSavedState == NULL)
2863 {
2864 hr = mDevice->BeginStateBlock();
2865 ASSERT(SUCCEEDED(hr) || hr == D3DERR_OUTOFVIDEOMEMORY || hr == E_OUTOFMEMORY);
2866
2867 mDevice->SetRenderState(D3DRS_ZWRITEENABLE, FALSE);
2868 mDevice->SetRenderState(D3DRS_ZFUNC, D3DCMP_ALWAYS);
2869 mDevice->SetRenderState(D3DRS_ZENABLE, FALSE);
2870 mDevice->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE);
2871 mDevice->SetRenderState(D3DRS_FILLMODE, D3DFILL_SOLID);
2872 mDevice->SetRenderState(D3DRS_ALPHATESTENABLE, FALSE);
2873 mDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, FALSE);
2874 mDevice->SetRenderState(D3DRS_CLIPPLANEENABLE, 0);
2875 mDevice->SetRenderState(D3DRS_COLORWRITEENABLE, 0);
2876 mDevice->SetRenderState(D3DRS_STENCILENABLE, FALSE);
2877 mDevice->SetPixelShader(NULL);
2878 mDevice->SetVertexShader(NULL);
2879 mDevice->SetFVF(D3DFVF_XYZRHW | D3DFVF_DIFFUSE);
2880 mDevice->SetStreamSource(0, NULL, 0, 0);
2881 mDevice->SetRenderState(D3DRS_SEPARATEALPHABLENDENABLE, TRUE);
2882 mDevice->SetTextureStageState(0, D3DTSS_COLOROP, D3DTOP_SELECTARG1);
2883 mDevice->SetTextureStageState(0, D3DTSS_COLORARG1, D3DTA_TFACTOR);
2884 mDevice->SetTextureStageState(0, D3DTSS_ALPHAOP, D3DTOP_SELECTARG1);
2885 mDevice->SetTextureStageState(0, D3DTSS_ALPHAARG1, D3DTA_TFACTOR);
2886 mDevice->SetRenderState(D3DRS_TEXTUREFACTOR, color);
2887 mDevice->SetRenderState(D3DRS_MULTISAMPLEMASK, 0xFFFFFFFF);
2888
2889 for(int i = 0; i < MAX_VERTEX_ATTRIBS; i++)
2890 {
2891 mDevice->SetStreamSourceFreq(i, 1);
2892 }
2893
2894 hr = mDevice->EndStateBlock(&mMaskedClearSavedState);
2895 ASSERT(SUCCEEDED(hr) || hr == D3DERR_OUTOFVIDEOMEMORY || hr == E_OUTOFMEMORY);
2896 }
2897
2898 ASSERT(mMaskedClearSavedState != NULL);
2899
2900 if (mMaskedClearSavedState != NULL)
2901 {
2902 hr = mMaskedClearSavedState->Capture();
2903 ASSERT(SUCCEEDED(hr));
2904 }
2905
2906 mDevice->SetRenderState(D3DRS_ZWRITEENABLE, FALSE);
2907 mDevice->SetRenderState(D3DRS_ZFUNC, D3DCMP_ALWAYS);
2908 mDevice->SetRenderState(D3DRS_ZENABLE, FALSE);
2909 mDevice->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE);
2910 mDevice->SetRenderState(D3DRS_FILLMODE, D3DFILL_SOLID);
2911 mDevice->SetRenderState(D3DRS_ALPHATESTENABLE, FALSE);
2912 mDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, FALSE);
2913 mDevice->SetRenderState(D3DRS_CLIPPLANEENABLE, 0);
2914
2915 if (flags & D3DCLEAR_TARGET)
2916 {
2917 mDevice->SetRenderState(D3DRS_COLORWRITEENABLE, es2dx::ConvertColorMask(mState.colorMaskRed, mState.colorMaskGreen, mState.colorMaskBlue, mState.colorMaskAlpha));
2918 }
2919 else
2920 {
2921 mDevice->SetRenderState(D3DRS_COLORWRITEENABLE, 0);
2922 }
2923
2924 if (stencilUnmasked != 0x0 && (flags & D3DCLEAR_STENCIL))
2925 {
2926 mDevice->SetRenderState(D3DRS_STENCILENABLE, TRUE);
2927 mDevice->SetRenderState(D3DRS_TWOSIDEDSTENCILMODE, FALSE);
2928 mDevice->SetRenderState(D3DRS_STENCILFUNC, D3DCMP_ALWAYS);
2929 mDevice->SetRenderState(D3DRS_STENCILREF, stencil);
2930 mDevice->SetRenderState(D3DRS_STENCILWRITEMASK, mState.stencilWritemask);
2931 mDevice->SetRenderState(D3DRS_STENCILFAIL, D3DSTENCILOP_REPLACE);
2932 mDevice->SetRenderState(D3DRS_STENCILZFAIL, D3DSTENCILOP_REPLACE);
2933 mDevice->SetRenderState(D3DRS_STENCILPASS, D3DSTENCILOP_REPLACE);
2934 mStencilStateDirty = true;
2935 }
2936 else
2937 {
2938 mDevice->SetRenderState(D3DRS_STENCILENABLE, FALSE);
2939 }
2940
2941 mDevice->SetPixelShader(NULL);
2942 mDevice->SetVertexShader(NULL);
2943 mDevice->SetFVF(D3DFVF_XYZRHW);
2944 mDevice->SetRenderState(D3DRS_SEPARATEALPHABLENDENABLE, TRUE);
2945 mDevice->SetTextureStageState(0, D3DTSS_COLOROP, D3DTOP_SELECTARG1);
2946 mDevice->SetTextureStageState(0, D3DTSS_COLORARG1, D3DTA_TFACTOR);
2947 mDevice->SetTextureStageState(0, D3DTSS_ALPHAOP, D3DTOP_SELECTARG1);
2948 mDevice->SetTextureStageState(0, D3DTSS_ALPHAARG1, D3DTA_TFACTOR);
2949 mDevice->SetRenderState(D3DRS_TEXTUREFACTOR, color);
2950 mDevice->SetRenderState(D3DRS_MULTISAMPLEMASK, 0xFFFFFFFF);
2951
2952 for(int i = 0; i < MAX_VERTEX_ATTRIBS; i++)
2953 {
2954 mDevice->SetStreamSourceFreq(i, 1);
2955 }
2956
2957 float quad[4][4]; // A quadrilateral covering the target, aligned to match the edges
2958 quad[0][0] = -0.5f;
2959 quad[0][1] = mRenderTargetDesc.Height - 0.5f;
2960 quad[0][2] = 0.0f;
2961 quad[0][3] = 1.0f;
2962
2963 quad[1][0] = mRenderTargetDesc.Width - 0.5f;
2964 quad[1][1] = mRenderTargetDesc.Height - 0.5f;
2965 quad[1][2] = 0.0f;
2966 quad[1][3] = 1.0f;
2967
2968 quad[2][0] = -0.5f;
2969 quad[2][1] = -0.5f;
2970 quad[2][2] = 0.0f;
2971 quad[2][3] = 1.0f;
2972
2973 quad[3][0] = mRenderTargetDesc.Width - 0.5f;
2974 quad[3][1] = -0.5f;
2975 quad[3][2] = 0.0f;
2976 quad[3][3] = 1.0f;
2977
daniel@transgaming.com621ce052012-10-31 17:52:29 +00002978 mRenderer->startScene();
apatrick@chromium.org144f2802012-07-12 01:42:34 +00002979 mDevice->DrawPrimitiveUP(D3DPT_TRIANGLESTRIP, 2, quad, sizeof(float[4]));
2980
2981 if (flags & D3DCLEAR_ZBUFFER)
2982 {
2983 mDevice->SetRenderState(D3DRS_ZENABLE, TRUE);
2984 mDevice->SetRenderState(D3DRS_ZWRITEENABLE, TRUE);
2985 mDevice->Clear(0, NULL, D3DCLEAR_ZBUFFER, color, depth, stencil);
2986 }
2987
2988 if (mMaskedClearSavedState != NULL)
2989 {
2990 mMaskedClearSavedState->Apply();
2991 }
2992 }
2993 else if (flags)
2994 {
2995 mDevice->Clear(0, NULL, flags, color, depth, stencil);
2996 }
2997}
2998
2999void Context::drawArrays(GLenum mode, GLint first, GLsizei count, GLsizei instances)
3000{
3001 if (!mState.currentProgram)
3002 {
3003 return error(GL_INVALID_OPERATION);
3004 }
3005
3006 D3DPRIMITIVETYPE primitiveType;
3007 int primitiveCount;
3008
3009 if(!es2dx::ConvertPrimitiveType(mode, count, &primitiveType, &primitiveCount))
3010 return error(GL_INVALID_ENUM);
3011
3012 if (primitiveCount <= 0)
3013 {
3014 return;
3015 }
3016
3017 if (!applyRenderTarget(false))
3018 {
3019 return;
3020 }
3021
3022 applyState(mode);
3023
3024 GLsizei repeatDraw = 1;
3025 GLenum err = applyVertexBuffer(first, count, instances, &repeatDraw);
3026 if (err != GL_NO_ERROR)
3027 {
3028 return error(err);
3029 }
3030
3031 applyShaders();
3032 applyTextures();
3033
daniel@transgaming.com62a28462012-07-24 18:33:59 +00003034 if (!getCurrentProgramBinary()->validateSamplers(NULL))
apatrick@chromium.org144f2802012-07-12 01:42:34 +00003035 {
3036 return error(GL_INVALID_OPERATION);
3037 }
3038
daniel@transgaming.com087e5782012-09-17 21:28:47 +00003039 if (!skipDraw(mode))
apatrick@chromium.org144f2802012-07-12 01:42:34 +00003040 {
daniel@transgaming.com621ce052012-10-31 17:52:29 +00003041 mRenderer->startScene();
apatrick@chromium.org144f2802012-07-12 01:42:34 +00003042
3043 if (mode == GL_LINE_LOOP)
3044 {
3045 drawLineLoop(count, GL_NONE, NULL, 0);
3046 }
3047 else if (instances > 0)
3048 {
3049 StaticIndexBuffer *countingIB = mIndexDataManager->getCountingIndices(count);
3050 if (countingIB)
3051 {
3052 if (mAppliedIBSerial != countingIB->getSerial())
3053 {
3054 mDevice->SetIndices(countingIB->getBuffer());
3055 mAppliedIBSerial = countingIB->getSerial();
3056 }
3057
3058 for (int i = 0; i < repeatDraw; i++)
3059 {
3060 mDevice->DrawIndexedPrimitive(primitiveType, 0, 0, count, 0, primitiveCount);
3061 }
3062 }
3063 else
3064 {
3065 ERR("Could not create a counting index buffer for glDrawArraysInstanced.");
3066 return error(GL_OUT_OF_MEMORY);
3067 }
3068 }
3069 else // Regular case
3070 {
3071 mDevice->DrawPrimitive(primitiveType, 0, primitiveCount);
3072 }
3073 }
3074}
3075
3076void Context::drawElements(GLenum mode, GLsizei count, GLenum type, const GLvoid *indices, GLsizei instances)
3077{
3078 if (!mState.currentProgram)
3079 {
3080 return error(GL_INVALID_OPERATION);
3081 }
3082
3083 if (!indices && !mState.elementArrayBuffer)
3084 {
3085 return error(GL_INVALID_OPERATION);
3086 }
3087
3088 D3DPRIMITIVETYPE primitiveType;
3089 int primitiveCount;
3090
3091 if(!es2dx::ConvertPrimitiveType(mode, count, &primitiveType, &primitiveCount))
3092 return error(GL_INVALID_ENUM);
3093
3094 if (primitiveCount <= 0)
3095 {
3096 return;
3097 }
3098
3099 if (!applyRenderTarget(false))
3100 {
3101 return;
3102 }
3103
3104 applyState(mode);
3105
3106 TranslatedIndexData indexInfo;
3107 GLenum err = applyIndexBuffer(indices, count, mode, type, &indexInfo);
3108 if (err != GL_NO_ERROR)
3109 {
3110 return error(err);
3111 }
3112
3113 GLsizei vertexCount = indexInfo.maxIndex - indexInfo.minIndex + 1;
3114 GLsizei repeatDraw = 1;
3115 err = applyVertexBuffer(indexInfo.minIndex, vertexCount, instances, &repeatDraw);
3116 if (err != GL_NO_ERROR)
3117 {
3118 return error(err);
3119 }
3120
3121 applyShaders();
3122 applyTextures();
3123
daniel@transgaming.com62a28462012-07-24 18:33:59 +00003124 if (!getCurrentProgramBinary()->validateSamplers(false))
apatrick@chromium.org144f2802012-07-12 01:42:34 +00003125 {
3126 return error(GL_INVALID_OPERATION);
3127 }
3128
daniel@transgaming.com087e5782012-09-17 21:28:47 +00003129 if (!skipDraw(mode))
apatrick@chromium.org144f2802012-07-12 01:42:34 +00003130 {
daniel@transgaming.com621ce052012-10-31 17:52:29 +00003131 mRenderer->startScene();
apatrick@chromium.org144f2802012-07-12 01:42:34 +00003132
3133 if (mode == GL_LINE_LOOP)
3134 {
3135 drawLineLoop(count, type, indices, indexInfo.minIndex);
3136 }
3137 else
3138 {
3139 for (int i = 0; i < repeatDraw; i++)
3140 {
3141 mDevice->DrawIndexedPrimitive(primitiveType, -(INT)indexInfo.minIndex, indexInfo.minIndex, vertexCount, indexInfo.startIndex, primitiveCount);
3142 }
3143 }
3144 }
3145}
3146
3147// Implements glFlush when block is false, glFinish when block is true
3148void Context::sync(bool block)
3149{
daniel@transgaming.comef21ab22012-10-31 17:52:47 +00003150 mRenderer->sync(block);
apatrick@chromium.org144f2802012-07-12 01:42:34 +00003151}
3152
3153void Context::drawLineLoop(GLsizei count, GLenum type, const GLvoid *indices, int minIndex)
3154{
3155 // Get the raw indices for an indexed draw
3156 if (type != GL_NONE && mState.elementArrayBuffer.get())
3157 {
3158 Buffer *indexBuffer = mState.elementArrayBuffer.get();
3159 intptr_t offset = reinterpret_cast<intptr_t>(indices);
3160 indices = static_cast<const GLubyte*>(indexBuffer->data()) + offset;
3161 }
3162
3163 UINT startIndex = 0;
3164 bool succeeded = false;
3165
3166 if (supports32bitIndices())
3167 {
3168 const int spaceNeeded = (count + 1) * sizeof(unsigned int);
3169
3170 if (!mLineLoopIB)
3171 {
daniel@transgaming.com6716a272012-10-31 18:31:39 +00003172 mLineLoopIB = new StreamingIndexBuffer(mRenderer, INITIAL_INDEX_BUFFER_SIZE, D3DFMT_INDEX32);
apatrick@chromium.org144f2802012-07-12 01:42:34 +00003173 }
3174
3175 if (mLineLoopIB)
3176 {
3177 mLineLoopIB->reserveSpace(spaceNeeded, GL_UNSIGNED_INT);
3178
3179 UINT offset = 0;
3180 unsigned int *data = static_cast<unsigned int*>(mLineLoopIB->map(spaceNeeded, &offset));
3181 startIndex = offset / 4;
3182
3183 if (data)
3184 {
3185 switch (type)
3186 {
3187 case GL_NONE: // Non-indexed draw
3188 for (int i = 0; i < count; i++)
3189 {
3190 data[i] = i;
3191 }
3192 data[count] = 0;
3193 break;
3194 case GL_UNSIGNED_BYTE:
3195 for (int i = 0; i < count; i++)
3196 {
3197 data[i] = static_cast<const GLubyte*>(indices)[i];
3198 }
3199 data[count] = static_cast<const GLubyte*>(indices)[0];
3200 break;
3201 case GL_UNSIGNED_SHORT:
3202 for (int i = 0; i < count; i++)
3203 {
3204 data[i] = static_cast<const GLushort*>(indices)[i];
3205 }
3206 data[count] = static_cast<const GLushort*>(indices)[0];
3207 break;
3208 case GL_UNSIGNED_INT:
3209 for (int i = 0; i < count; i++)
3210 {
3211 data[i] = static_cast<const GLuint*>(indices)[i];
3212 }
3213 data[count] = static_cast<const GLuint*>(indices)[0];
3214 break;
3215 default: UNREACHABLE();
3216 }
3217
3218 mLineLoopIB->unmap();
3219 succeeded = true;
3220 }
3221 }
3222 }
3223 else
3224 {
3225 const int spaceNeeded = (count + 1) * sizeof(unsigned short);
3226
3227 if (!mLineLoopIB)
3228 {
daniel@transgaming.com6716a272012-10-31 18:31:39 +00003229 mLineLoopIB = new StreamingIndexBuffer(mRenderer, INITIAL_INDEX_BUFFER_SIZE, D3DFMT_INDEX16);
apatrick@chromium.org144f2802012-07-12 01:42:34 +00003230 }
3231
3232 if (mLineLoopIB)
3233 {
3234 mLineLoopIB->reserveSpace(spaceNeeded, GL_UNSIGNED_SHORT);
3235
3236 UINT offset = 0;
3237 unsigned short *data = static_cast<unsigned short*>(mLineLoopIB->map(spaceNeeded, &offset));
3238 startIndex = offset / 2;
3239
3240 if (data)
3241 {
3242 switch (type)
3243 {
3244 case GL_NONE: // Non-indexed draw
3245 for (int i = 0; i < count; i++)
3246 {
3247 data[i] = i;
3248 }
3249 data[count] = 0;
3250 break;
3251 case GL_UNSIGNED_BYTE:
3252 for (int i = 0; i < count; i++)
3253 {
3254 data[i] = static_cast<const GLubyte*>(indices)[i];
3255 }
3256 data[count] = static_cast<const GLubyte*>(indices)[0];
3257 break;
3258 case GL_UNSIGNED_SHORT:
3259 for (int i = 0; i < count; i++)
3260 {
3261 data[i] = static_cast<const GLushort*>(indices)[i];
3262 }
3263 data[count] = static_cast<const GLushort*>(indices)[0];
3264 break;
3265 case GL_UNSIGNED_INT:
3266 for (int i = 0; i < count; i++)
3267 {
3268 data[i] = static_cast<const GLuint*>(indices)[i];
3269 }
3270 data[count] = static_cast<const GLuint*>(indices)[0];
3271 break;
3272 default: UNREACHABLE();
3273 }
3274
3275 mLineLoopIB->unmap();
3276 succeeded = true;
3277 }
3278 }
3279 }
3280
3281 if (succeeded)
3282 {
3283 if (mAppliedIBSerial != mLineLoopIB->getSerial())
3284 {
3285 mDevice->SetIndices(mLineLoopIB->getBuffer());
3286 mAppliedIBSerial = mLineLoopIB->getSerial();
3287 }
3288
3289 mDevice->DrawIndexedPrimitive(D3DPT_LINESTRIP, -minIndex, minIndex, count, startIndex, count);
3290 }
3291 else
3292 {
3293 ERR("Could not create a looping index buffer for GL_LINE_LOOP.");
3294 return error(GL_OUT_OF_MEMORY);
3295 }
3296}
3297
3298void Context::recordInvalidEnum()
3299{
3300 mInvalidEnum = true;
3301}
3302
3303void Context::recordInvalidValue()
3304{
3305 mInvalidValue = true;
3306}
3307
3308void Context::recordInvalidOperation()
3309{
3310 mInvalidOperation = true;
3311}
3312
3313void Context::recordOutOfMemory()
3314{
3315 mOutOfMemory = true;
3316}
3317
3318void Context::recordInvalidFramebufferOperation()
3319{
3320 mInvalidFramebufferOperation = true;
3321}
3322
3323// Get one of the recorded errors and clear its flag, if any.
3324// [OpenGL ES 2.0.24] section 2.5 page 13.
3325GLenum Context::getError()
3326{
3327 if (mInvalidEnum)
3328 {
3329 mInvalidEnum = false;
3330
3331 return GL_INVALID_ENUM;
3332 }
3333
3334 if (mInvalidValue)
3335 {
3336 mInvalidValue = false;
3337
3338 return GL_INVALID_VALUE;
3339 }
3340
3341 if (mInvalidOperation)
3342 {
3343 mInvalidOperation = false;
3344
3345 return GL_INVALID_OPERATION;
3346 }
3347
3348 if (mOutOfMemory)
3349 {
3350 mOutOfMemory = false;
3351
3352 return GL_OUT_OF_MEMORY;
3353 }
3354
3355 if (mInvalidFramebufferOperation)
3356 {
3357 mInvalidFramebufferOperation = false;
3358
3359 return GL_INVALID_FRAMEBUFFER_OPERATION;
3360 }
3361
3362 return GL_NO_ERROR;
3363}
3364
3365GLenum Context::getResetStatus()
3366{
3367 if (mResetStatus == GL_NO_ERROR)
3368 {
daniel@transgaming.comf688c0d2012-10-31 17:52:57 +00003369 // mResetStatus will be set by the markContextLost callback
3370 // in the case a notification is sent
3371 mRenderer->testDeviceLost(true);
apatrick@chromium.org144f2802012-07-12 01:42:34 +00003372 }
3373
3374 GLenum status = mResetStatus;
3375
3376 if (mResetStatus != GL_NO_ERROR)
3377 {
daniel@transgaming.com621ce052012-10-31 17:52:29 +00003378 if (mRenderer->testDeviceResettable())
apatrick@chromium.org144f2802012-07-12 01:42:34 +00003379 {
3380 mResetStatus = GL_NO_ERROR;
3381 }
3382 }
3383
3384 return status;
3385}
3386
3387bool Context::isResetNotificationEnabled()
3388{
3389 return (mResetStrategy == GL_LOSE_CONTEXT_ON_RESET_EXT);
3390}
3391
3392bool Context::supportsShaderModel3() const
3393{
3394 return mSupportsShaderModel3;
3395}
3396
3397float Context::getMaximumPointSize() const
3398{
3399 return mSupportsShaderModel3 ? mMaximumPointSize : ALIASED_POINT_SIZE_RANGE_MAX_SM2;
3400}
3401
3402int Context::getMaximumVaryingVectors() const
3403{
3404 return mSupportsShaderModel3 ? MAX_VARYING_VECTORS_SM3 : MAX_VARYING_VECTORS_SM2;
3405}
3406
3407unsigned int Context::getMaximumVertexTextureImageUnits() const
3408{
3409 return mSupportsVertexTexture ? MAX_VERTEX_TEXTURE_IMAGE_UNITS_VTF : 0;
3410}
3411
3412unsigned int Context::getMaximumCombinedTextureImageUnits() const
3413{
3414 return MAX_TEXTURE_IMAGE_UNITS + getMaximumVertexTextureImageUnits();
3415}
3416
3417int Context::getMaximumFragmentUniformVectors() const
3418{
3419 return mSupportsShaderModel3 ? MAX_FRAGMENT_UNIFORM_VECTORS_SM3 : MAX_FRAGMENT_UNIFORM_VECTORS_SM2;
3420}
3421
3422int Context::getMaxSupportedSamples() const
3423{
daniel@transgaming.comb7833982012-10-31 18:31:46 +00003424 return mRenderer->getMaxSupportedSamples();
apatrick@chromium.org144f2802012-07-12 01:42:34 +00003425}
3426
apatrick@chromium.org144f2802012-07-12 01:42:34 +00003427bool Context::supportsEventQueries() const
3428{
3429 return mSupportsEventQueries;
3430}
3431
3432bool Context::supportsOcclusionQueries() const
3433{
3434 return mSupportsOcclusionQueries;
3435}
3436
3437bool Context::supportsDXT1Textures() const
3438{
3439 return mSupportsDXT1Textures;
3440}
3441
3442bool Context::supportsDXT3Textures() const
3443{
3444 return mSupportsDXT3Textures;
3445}
3446
3447bool Context::supportsDXT5Textures() const
3448{
3449 return mSupportsDXT5Textures;
3450}
3451
3452bool Context::supportsFloat32Textures() const
3453{
3454 return mSupportsFloat32Textures;
3455}
3456
3457bool Context::supportsFloat32LinearFilter() const
3458{
3459 return mSupportsFloat32LinearFilter;
3460}
3461
3462bool Context::supportsFloat32RenderableTextures() const
3463{
3464 return mSupportsFloat32RenderableTextures;
3465}
3466
3467bool Context::supportsFloat16Textures() const
3468{
3469 return mSupportsFloat16Textures;
3470}
3471
3472bool Context::supportsFloat16LinearFilter() const
3473{
3474 return mSupportsFloat16LinearFilter;
3475}
3476
3477bool Context::supportsFloat16RenderableTextures() const
3478{
3479 return mSupportsFloat16RenderableTextures;
3480}
3481
3482int Context::getMaximumRenderbufferDimension() const
3483{
3484 return mMaxRenderbufferDimension;
3485}
3486
3487int Context::getMaximumTextureDimension() const
3488{
3489 return mMaxTextureDimension;
3490}
3491
3492int Context::getMaximumCubeTextureDimension() const
3493{
3494 return mMaxCubeTextureDimension;
3495}
3496
3497int Context::getMaximumTextureLevel() const
3498{
3499 return mMaxTextureLevel;
3500}
3501
3502bool Context::supportsLuminanceTextures() const
3503{
3504 return mSupportsLuminanceTextures;
3505}
3506
3507bool Context::supportsLuminanceAlphaTextures() const
3508{
3509 return mSupportsLuminanceAlphaTextures;
3510}
3511
3512bool Context::supportsDepthTextures() const
3513{
3514 return mSupportsDepthTextures;
3515}
3516
3517bool Context::supports32bitIndices() const
3518{
3519 return mSupports32bitIndices;
3520}
3521
3522bool Context::supportsNonPower2Texture() const
3523{
3524 return mSupportsNonPower2Texture;
3525}
3526
3527bool Context::supportsInstancing() const
3528{
3529 return mSupportsInstancing;
3530}
3531
daniel@transgaming.com07ab8412012-07-12 15:17:09 +00003532bool Context::supportsTextureFilterAnisotropy() const
3533{
3534 return mSupportsTextureFilterAnisotropy;
3535}
3536
3537float Context::getTextureMaxAnisotropy() const
3538{
3539 return mMaxTextureAnisotropy;
3540}
3541
daniel@transgaming.com42944b02012-09-27 17:45:57 +00003542bool Context::getCurrentReadFormatType(GLenum *format, GLenum *type)
3543{
3544 Framebuffer *framebuffer = getReadFramebuffer();
3545 if (!framebuffer || framebuffer->completeness() != GL_FRAMEBUFFER_COMPLETE)
3546 {
3547 return error(GL_INVALID_OPERATION, false);
3548 }
3549
3550 Renderbuffer *renderbuffer = framebuffer->getColorbuffer();
3551 if (!renderbuffer)
3552 {
3553 return error(GL_INVALID_OPERATION, false);
3554 }
3555
3556 if(!dx2es::ConvertReadBufferFormat(renderbuffer->getD3DFormat(), format, type))
3557 {
3558 ASSERT(false);
3559 return false;
3560 }
3561
3562 return true;
3563}
3564
apatrick@chromium.org144f2802012-07-12 01:42:34 +00003565void Context::detachBuffer(GLuint buffer)
3566{
3567 // [OpenGL ES 2.0.24] section 2.9 page 22:
3568 // If a buffer object is deleted while it is bound, all bindings to that object in the current context
3569 // (i.e. in the thread that called Delete-Buffers) are reset to zero.
3570
3571 if (mState.arrayBuffer.id() == buffer)
3572 {
3573 mState.arrayBuffer.set(NULL);
3574 }
3575
3576 if (mState.elementArrayBuffer.id() == buffer)
3577 {
3578 mState.elementArrayBuffer.set(NULL);
3579 }
3580
3581 for (int attribute = 0; attribute < MAX_VERTEX_ATTRIBS; attribute++)
3582 {
3583 if (mState.vertexAttribute[attribute].mBoundBuffer.id() == buffer)
3584 {
3585 mState.vertexAttribute[attribute].mBoundBuffer.set(NULL);
3586 }
3587 }
3588}
3589
3590void Context::detachTexture(GLuint texture)
3591{
3592 // [OpenGL ES 2.0.24] section 3.8 page 84:
3593 // If a texture object is deleted, it is as if all texture units which are bound to that texture object are
3594 // rebound to texture object zero
3595
3596 for (int type = 0; type < TEXTURE_TYPE_COUNT; type++)
3597 {
3598 for (int sampler = 0; sampler < MAX_COMBINED_TEXTURE_IMAGE_UNITS_VTF; sampler++)
3599 {
3600 if (mState.samplerTexture[type][sampler].id() == texture)
3601 {
3602 mState.samplerTexture[type][sampler].set(NULL);
3603 }
3604 }
3605 }
3606
3607 // [OpenGL ES 2.0.24] section 4.4 page 112:
3608 // If a texture object is deleted while its image is attached to the currently bound framebuffer, then it is
3609 // as if FramebufferTexture2D had been called, with a texture of 0, for each attachment point to which this
3610 // image was attached in the currently bound framebuffer.
3611
3612 Framebuffer *readFramebuffer = getReadFramebuffer();
3613 Framebuffer *drawFramebuffer = getDrawFramebuffer();
3614
3615 if (readFramebuffer)
3616 {
3617 readFramebuffer->detachTexture(texture);
3618 }
3619
3620 if (drawFramebuffer && drawFramebuffer != readFramebuffer)
3621 {
3622 drawFramebuffer->detachTexture(texture);
3623 }
3624}
3625
3626void Context::detachFramebuffer(GLuint framebuffer)
3627{
3628 // [OpenGL ES 2.0.24] section 4.4 page 107:
3629 // If a framebuffer that is currently bound to the target FRAMEBUFFER is deleted, it is as though
3630 // BindFramebuffer had been executed with the target of FRAMEBUFFER and framebuffer of zero.
3631
3632 if (mState.readFramebuffer == framebuffer)
3633 {
3634 bindReadFramebuffer(0);
3635 }
3636
3637 if (mState.drawFramebuffer == framebuffer)
3638 {
3639 bindDrawFramebuffer(0);
3640 }
3641}
3642
3643void Context::detachRenderbuffer(GLuint renderbuffer)
3644{
3645 // [OpenGL ES 2.0.24] section 4.4 page 109:
3646 // If a renderbuffer that is currently bound to RENDERBUFFER is deleted, it is as though BindRenderbuffer
3647 // had been executed with the target RENDERBUFFER and name of zero.
3648
3649 if (mState.renderbuffer.id() == renderbuffer)
3650 {
3651 bindRenderbuffer(0);
3652 }
3653
3654 // [OpenGL ES 2.0.24] section 4.4 page 111:
3655 // If a renderbuffer object is deleted while its image is attached to the currently bound framebuffer,
3656 // then it is as if FramebufferRenderbuffer had been called, with a renderbuffer of 0, for each attachment
3657 // point to which this image was attached in the currently bound framebuffer.
3658
3659 Framebuffer *readFramebuffer = getReadFramebuffer();
3660 Framebuffer *drawFramebuffer = getDrawFramebuffer();
3661
3662 if (readFramebuffer)
3663 {
3664 readFramebuffer->detachRenderbuffer(renderbuffer);
3665 }
3666
3667 if (drawFramebuffer && drawFramebuffer != readFramebuffer)
3668 {
3669 drawFramebuffer->detachRenderbuffer(renderbuffer);
3670 }
3671}
3672
3673Texture *Context::getIncompleteTexture(TextureType type)
3674{
3675 Texture *t = mIncompleteTextures[type].get();
3676
3677 if (t == NULL)
3678 {
3679 static const GLubyte color[] = { 0, 0, 0, 255 };
3680
3681 switch (type)
3682 {
3683 default:
3684 UNREACHABLE();
3685 // default falls through to TEXTURE_2D
3686
3687 case TEXTURE_2D:
3688 {
3689 Texture2D *incomplete2d = new Texture2D(Texture::INCOMPLETE_TEXTURE_ID);
3690 incomplete2d->setImage(0, 1, 1, GL_RGBA, GL_UNSIGNED_BYTE, 1, color);
3691 t = incomplete2d;
3692 }
3693 break;
3694
3695 case TEXTURE_CUBE:
3696 {
3697 TextureCubeMap *incompleteCube = new TextureCubeMap(Texture::INCOMPLETE_TEXTURE_ID);
3698
3699 incompleteCube->setImagePosX(0, 1, 1, GL_RGBA, GL_UNSIGNED_BYTE, 1, color);
3700 incompleteCube->setImageNegX(0, 1, 1, GL_RGBA, GL_UNSIGNED_BYTE, 1, color);
3701 incompleteCube->setImagePosY(0, 1, 1, GL_RGBA, GL_UNSIGNED_BYTE, 1, color);
3702 incompleteCube->setImageNegY(0, 1, 1, GL_RGBA, GL_UNSIGNED_BYTE, 1, color);
3703 incompleteCube->setImagePosZ(0, 1, 1, GL_RGBA, GL_UNSIGNED_BYTE, 1, color);
3704 incompleteCube->setImageNegZ(0, 1, 1, GL_RGBA, GL_UNSIGNED_BYTE, 1, color);
3705
3706 t = incompleteCube;
3707 }
3708 break;
3709 }
3710
3711 mIncompleteTextures[type].set(t);
3712 }
3713
3714 return t;
3715}
3716
daniel@transgaming.com087e5782012-09-17 21:28:47 +00003717bool Context::skipDraw(GLenum drawMode)
apatrick@chromium.org144f2802012-07-12 01:42:34 +00003718{
daniel@transgaming.com087e5782012-09-17 21:28:47 +00003719 if (drawMode == GL_POINTS)
3720 {
3721 // ProgramBinary assumes non-point rendering if gl_PointSize isn't written,
3722 // which affects varying interpolation. Since the value of gl_PointSize is
3723 // undefined when not written, just skip drawing to avoid unexpected results.
3724 if (!getCurrentProgramBinary()->usesPointSize())
3725 {
3726 // This is stictly speaking not an error, but developers should be
3727 // notified of risking undefined behavior.
3728 ERR("Point rendering without writing to gl_PointSize.");
3729
3730 return true;
3731 }
3732 }
3733 else if (isTriangleMode(drawMode))
3734 {
3735 if (mState.cullFace && mState.cullMode == GL_FRONT_AND_BACK)
3736 {
3737 return true;
3738 }
3739 }
3740
3741 return false;
apatrick@chromium.org144f2802012-07-12 01:42:34 +00003742}
3743
3744bool Context::isTriangleMode(GLenum drawMode)
3745{
3746 switch (drawMode)
3747 {
3748 case GL_TRIANGLES:
3749 case GL_TRIANGLE_FAN:
3750 case GL_TRIANGLE_STRIP:
3751 return true;
3752 case GL_POINTS:
3753 case GL_LINES:
3754 case GL_LINE_LOOP:
3755 case GL_LINE_STRIP:
3756 return false;
3757 default: UNREACHABLE();
3758 }
3759
3760 return false;
3761}
3762
3763void Context::setVertexAttrib(GLuint index, const GLfloat *values)
3764{
3765 ASSERT(index < gl::MAX_VERTEX_ATTRIBS);
3766
3767 mState.vertexAttribute[index].mCurrentValue[0] = values[0];
3768 mState.vertexAttribute[index].mCurrentValue[1] = values[1];
3769 mState.vertexAttribute[index].mCurrentValue[2] = values[2];
3770 mState.vertexAttribute[index].mCurrentValue[3] = values[3];
3771
3772 mVertexDataManager->dirtyCurrentValue(index);
3773}
3774
3775void Context::setVertexAttribDivisor(GLuint index, GLuint divisor)
3776{
3777 ASSERT(index < gl::MAX_VERTEX_ATTRIBS);
3778
3779 mState.vertexAttribute[index].mDivisor = divisor;
3780}
3781
3782// keep list sorted in following order
3783// OES extensions
3784// EXT extensions
3785// Vendor extensions
3786void Context::initExtensionString()
3787{
3788 mExtensionString = "";
3789
3790 // OES extensions
3791 if (supports32bitIndices())
3792 {
3793 mExtensionString += "GL_OES_element_index_uint ";
3794 }
3795
3796 mExtensionString += "GL_OES_packed_depth_stencil ";
3797 mExtensionString += "GL_OES_get_program_binary ";
3798 mExtensionString += "GL_OES_rgb8_rgba8 ";
3799 mExtensionString += "GL_OES_standard_derivatives ";
3800
3801 if (supportsFloat16Textures())
3802 {
3803 mExtensionString += "GL_OES_texture_half_float ";
3804 }
3805 if (supportsFloat16LinearFilter())
3806 {
3807 mExtensionString += "GL_OES_texture_half_float_linear ";
3808 }
3809 if (supportsFloat32Textures())
3810 {
3811 mExtensionString += "GL_OES_texture_float ";
3812 }
3813 if (supportsFloat32LinearFilter())
3814 {
3815 mExtensionString += "GL_OES_texture_float_linear ";
3816 }
3817
3818 if (supportsNonPower2Texture())
3819 {
3820 mExtensionString += "GL_OES_texture_npot ";
3821 }
3822
3823 // Multi-vendor (EXT) extensions
3824 if (supportsOcclusionQueries())
3825 {
3826 mExtensionString += "GL_EXT_occlusion_query_boolean ";
3827 }
3828
3829 mExtensionString += "GL_EXT_read_format_bgra ";
3830 mExtensionString += "GL_EXT_robustness ";
3831
3832 if (supportsDXT1Textures())
3833 {
3834 mExtensionString += "GL_EXT_texture_compression_dxt1 ";
3835 }
3836
daniel@transgaming.com07ab8412012-07-12 15:17:09 +00003837 if (supportsTextureFilterAnisotropy())
3838 {
3839 mExtensionString += "GL_EXT_texture_filter_anisotropic ";
3840 }
3841
apatrick@chromium.org144f2802012-07-12 01:42:34 +00003842 mExtensionString += "GL_EXT_texture_format_BGRA8888 ";
3843 mExtensionString += "GL_EXT_texture_storage ";
3844
3845 // ANGLE-specific extensions
3846 if (supportsDepthTextures())
3847 {
3848 mExtensionString += "GL_ANGLE_depth_texture ";
3849 }
3850
3851 mExtensionString += "GL_ANGLE_framebuffer_blit ";
3852 if (getMaxSupportedSamples() != 0)
3853 {
3854 mExtensionString += "GL_ANGLE_framebuffer_multisample ";
3855 }
3856
3857 if (supportsInstancing())
3858 {
3859 mExtensionString += "GL_ANGLE_instanced_arrays ";
3860 }
3861
3862 mExtensionString += "GL_ANGLE_pack_reverse_row_order ";
3863
3864 if (supportsDXT3Textures())
3865 {
3866 mExtensionString += "GL_ANGLE_texture_compression_dxt3 ";
3867 }
3868 if (supportsDXT5Textures())
3869 {
3870 mExtensionString += "GL_ANGLE_texture_compression_dxt5 ";
3871 }
3872
3873 mExtensionString += "GL_ANGLE_texture_usage ";
3874 mExtensionString += "GL_ANGLE_translated_shader_source ";
3875
3876 // Other vendor-specific extensions
3877 if (supportsEventQueries())
3878 {
3879 mExtensionString += "GL_NV_fence ";
3880 }
3881
3882 std::string::size_type end = mExtensionString.find_last_not_of(' ');
3883 if (end != std::string::npos)
3884 {
3885 mExtensionString.resize(end+1);
3886 }
3887}
3888
3889const char *Context::getExtensionString() const
3890{
3891 return mExtensionString.c_str();
3892}
3893
3894void Context::initRendererString()
3895{
daniel@transgaming.com621ce052012-10-31 17:52:29 +00003896 D3DADAPTER_IDENTIFIER9 *identifier = mRenderer->getAdapterIdentifier();
apatrick@chromium.org144f2802012-07-12 01:42:34 +00003897
3898 mRendererString = "ANGLE (";
3899 mRendererString += identifier->Description;
3900 mRendererString += ")";
3901}
3902
3903const char *Context::getRendererString() const
3904{
3905 return mRendererString.c_str();
3906}
3907
3908void Context::blitFramebuffer(GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1,
3909 GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1,
3910 GLbitfield mask)
3911{
3912 Framebuffer *readFramebuffer = getReadFramebuffer();
3913 Framebuffer *drawFramebuffer = getDrawFramebuffer();
3914
3915 if (!readFramebuffer || readFramebuffer->completeness() != GL_FRAMEBUFFER_COMPLETE ||
3916 !drawFramebuffer || drawFramebuffer->completeness() != GL_FRAMEBUFFER_COMPLETE)
3917 {
3918 return error(GL_INVALID_FRAMEBUFFER_OPERATION);
3919 }
3920
3921 if (drawFramebuffer->getSamples() != 0)
3922 {
3923 return error(GL_INVALID_OPERATION);
3924 }
3925
3926 int readBufferWidth = readFramebuffer->getColorbuffer()->getWidth();
3927 int readBufferHeight = readFramebuffer->getColorbuffer()->getHeight();
3928 int drawBufferWidth = drawFramebuffer->getColorbuffer()->getWidth();
3929 int drawBufferHeight = drawFramebuffer->getColorbuffer()->getHeight();
3930
3931 RECT sourceRect;
3932 RECT destRect;
3933
3934 if (srcX0 < srcX1)
3935 {
3936 sourceRect.left = srcX0;
3937 sourceRect.right = srcX1;
3938 destRect.left = dstX0;
3939 destRect.right = dstX1;
3940 }
3941 else
3942 {
3943 sourceRect.left = srcX1;
3944 destRect.left = dstX1;
3945 sourceRect.right = srcX0;
3946 destRect.right = dstX0;
3947 }
3948
3949 if (srcY0 < srcY1)
3950 {
3951 sourceRect.bottom = srcY1;
3952 destRect.bottom = dstY1;
3953 sourceRect.top = srcY0;
3954 destRect.top = dstY0;
3955 }
3956 else
3957 {
3958 sourceRect.bottom = srcY0;
3959 destRect.bottom = dstY0;
3960 sourceRect.top = srcY1;
3961 destRect.top = dstY1;
3962 }
3963
3964 RECT sourceScissoredRect = sourceRect;
3965 RECT destScissoredRect = destRect;
3966
3967 if (mState.scissorTest)
3968 {
3969 // Only write to parts of the destination framebuffer which pass the scissor test
3970 // Please note: the destRect is now in D3D-style coordinates, so the *top* of the
3971 // rect will be checked against scissorY, rather than the bottom.
3972 if (destRect.left < mState.scissorX)
3973 {
3974 int xDiff = mState.scissorX - destRect.left;
3975 destScissoredRect.left = mState.scissorX;
3976 sourceScissoredRect.left += xDiff;
3977 }
3978
3979 if (destRect.right > mState.scissorX + mState.scissorWidth)
3980 {
3981 int xDiff = destRect.right - (mState.scissorX + mState.scissorWidth);
3982 destScissoredRect.right = mState.scissorX + mState.scissorWidth;
3983 sourceScissoredRect.right -= xDiff;
3984 }
3985
3986 if (destRect.top < mState.scissorY)
3987 {
3988 int yDiff = mState.scissorY - destRect.top;
3989 destScissoredRect.top = mState.scissorY;
3990 sourceScissoredRect.top += yDiff;
3991 }
3992
3993 if (destRect.bottom > mState.scissorY + mState.scissorHeight)
3994 {
3995 int yDiff = destRect.bottom - (mState.scissorY + mState.scissorHeight);
3996 destScissoredRect.bottom = mState.scissorY + mState.scissorHeight;
3997 sourceScissoredRect.bottom -= yDiff;
3998 }
3999 }
4000
4001 bool blitRenderTarget = false;
4002 bool blitDepthStencil = false;
4003
4004 RECT sourceTrimmedRect = sourceScissoredRect;
4005 RECT destTrimmedRect = destScissoredRect;
4006
4007 // The source & destination rectangles also may need to be trimmed if they fall out of the bounds of
4008 // the actual draw and read surfaces.
4009 if (sourceTrimmedRect.left < 0)
4010 {
4011 int xDiff = 0 - sourceTrimmedRect.left;
4012 sourceTrimmedRect.left = 0;
4013 destTrimmedRect.left += xDiff;
4014 }
4015
4016 if (sourceTrimmedRect.right > readBufferWidth)
4017 {
4018 int xDiff = sourceTrimmedRect.right - readBufferWidth;
4019 sourceTrimmedRect.right = readBufferWidth;
4020 destTrimmedRect.right -= xDiff;
4021 }
4022
4023 if (sourceTrimmedRect.top < 0)
4024 {
4025 int yDiff = 0 - sourceTrimmedRect.top;
4026 sourceTrimmedRect.top = 0;
4027 destTrimmedRect.top += yDiff;
4028 }
4029
4030 if (sourceTrimmedRect.bottom > readBufferHeight)
4031 {
4032 int yDiff = sourceTrimmedRect.bottom - readBufferHeight;
4033 sourceTrimmedRect.bottom = readBufferHeight;
4034 destTrimmedRect.bottom -= yDiff;
4035 }
4036
4037 if (destTrimmedRect.left < 0)
4038 {
4039 int xDiff = 0 - destTrimmedRect.left;
4040 destTrimmedRect.left = 0;
4041 sourceTrimmedRect.left += xDiff;
4042 }
4043
4044 if (destTrimmedRect.right > drawBufferWidth)
4045 {
4046 int xDiff = destTrimmedRect.right - drawBufferWidth;
4047 destTrimmedRect.right = drawBufferWidth;
4048 sourceTrimmedRect.right -= xDiff;
4049 }
4050
4051 if (destTrimmedRect.top < 0)
4052 {
4053 int yDiff = 0 - destTrimmedRect.top;
4054 destTrimmedRect.top = 0;
4055 sourceTrimmedRect.top += yDiff;
4056 }
4057
4058 if (destTrimmedRect.bottom > drawBufferHeight)
4059 {
4060 int yDiff = destTrimmedRect.bottom - drawBufferHeight;
4061 destTrimmedRect.bottom = drawBufferHeight;
4062 sourceTrimmedRect.bottom -= yDiff;
4063 }
4064
4065 bool partialBufferCopy = false;
4066 if (sourceTrimmedRect.bottom - sourceTrimmedRect.top < readBufferHeight ||
4067 sourceTrimmedRect.right - sourceTrimmedRect.left < readBufferWidth ||
4068 destTrimmedRect.bottom - destTrimmedRect.top < drawBufferHeight ||
4069 destTrimmedRect.right - destTrimmedRect.left < drawBufferWidth ||
4070 sourceTrimmedRect.top != 0 || destTrimmedRect.top != 0 || sourceTrimmedRect.left != 0 || destTrimmedRect.left != 0)
4071 {
4072 partialBufferCopy = true;
4073 }
4074
4075 if (mask & GL_COLOR_BUFFER_BIT)
4076 {
4077 const bool validReadType = readFramebuffer->getColorbufferType() == GL_TEXTURE_2D ||
4078 readFramebuffer->getColorbufferType() == GL_RENDERBUFFER;
4079 const bool validDrawType = drawFramebuffer->getColorbufferType() == GL_TEXTURE_2D ||
4080 drawFramebuffer->getColorbufferType() == GL_RENDERBUFFER;
4081 if (!validReadType || !validDrawType ||
4082 readFramebuffer->getColorbuffer()->getD3DFormat() != drawFramebuffer->getColorbuffer()->getD3DFormat())
4083 {
4084 ERR("Color buffer format conversion in BlitFramebufferANGLE not supported by this implementation");
4085 return error(GL_INVALID_OPERATION);
4086 }
4087
4088 if (partialBufferCopy && readFramebuffer->getSamples() != 0)
4089 {
4090 return error(GL_INVALID_OPERATION);
4091 }
4092
4093 blitRenderTarget = true;
4094
4095 }
4096
4097 if (mask & (GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT))
4098 {
4099 Renderbuffer *readDSBuffer = NULL;
4100 Renderbuffer *drawDSBuffer = NULL;
4101
4102 // We support OES_packed_depth_stencil, and do not support a separately attached depth and stencil buffer, so if we have
4103 // both a depth and stencil buffer, it will be the same buffer.
4104
4105 if (mask & GL_DEPTH_BUFFER_BIT)
4106 {
4107 if (readFramebuffer->getDepthbuffer() && drawFramebuffer->getDepthbuffer())
4108 {
4109 if (readFramebuffer->getDepthbufferType() != drawFramebuffer->getDepthbufferType() ||
4110 readFramebuffer->getDepthbuffer()->getD3DFormat() != drawFramebuffer->getDepthbuffer()->getD3DFormat())
4111 {
4112 return error(GL_INVALID_OPERATION);
4113 }
4114
4115 blitDepthStencil = true;
4116 readDSBuffer = readFramebuffer->getDepthbuffer();
4117 drawDSBuffer = drawFramebuffer->getDepthbuffer();
4118 }
4119 }
4120
4121 if (mask & GL_STENCIL_BUFFER_BIT)
4122 {
4123 if (readFramebuffer->getStencilbuffer() && drawFramebuffer->getStencilbuffer())
4124 {
4125 if (readFramebuffer->getStencilbufferType() != drawFramebuffer->getStencilbufferType() ||
4126 readFramebuffer->getStencilbuffer()->getD3DFormat() != drawFramebuffer->getStencilbuffer()->getD3DFormat())
4127 {
4128 return error(GL_INVALID_OPERATION);
4129 }
4130
4131 blitDepthStencil = true;
4132 readDSBuffer = readFramebuffer->getStencilbuffer();
4133 drawDSBuffer = drawFramebuffer->getStencilbuffer();
4134 }
4135 }
4136
4137 if (partialBufferCopy)
4138 {
4139 ERR("Only whole-buffer depth and stencil blits are supported by this implementation.");
4140 return error(GL_INVALID_OPERATION); // only whole-buffer copies are permitted
4141 }
4142
4143 if ((drawDSBuffer && drawDSBuffer->getSamples() != 0) ||
4144 (readDSBuffer && readDSBuffer->getSamples() != 0))
4145 {
4146 return error(GL_INVALID_OPERATION);
4147 }
4148 }
4149
4150 if (blitRenderTarget || blitDepthStencil)
4151 {
daniel@transgaming.com621ce052012-10-31 17:52:29 +00004152 mRenderer->endScene();
apatrick@chromium.org144f2802012-07-12 01:42:34 +00004153
4154 if (blitRenderTarget)
4155 {
4156 IDirect3DSurface9* readRenderTarget = readFramebuffer->getRenderTarget();
4157 IDirect3DSurface9* drawRenderTarget = drawFramebuffer->getRenderTarget();
4158
4159 HRESULT result = mDevice->StretchRect(readRenderTarget, &sourceTrimmedRect,
4160 drawRenderTarget, &destTrimmedRect, D3DTEXF_NONE);
4161
4162 readRenderTarget->Release();
4163 drawRenderTarget->Release();
4164
4165 if (FAILED(result))
4166 {
4167 ERR("BlitFramebufferANGLE failed: StretchRect returned %x.", result);
4168 return;
4169 }
4170 }
4171
4172 if (blitDepthStencil)
4173 {
4174 IDirect3DSurface9* readDepthStencil = readFramebuffer->getDepthStencil();
4175 IDirect3DSurface9* drawDepthStencil = drawFramebuffer->getDepthStencil();
4176
4177 HRESULT result = mDevice->StretchRect(readDepthStencil, NULL, drawDepthStencil, NULL, D3DTEXF_NONE);
4178
4179 readDepthStencil->Release();
4180 drawDepthStencil->Release();
4181
4182 if (FAILED(result))
4183 {
4184 ERR("BlitFramebufferANGLE failed: StretchRect returned %x.", result);
4185 return;
4186 }
4187 }
4188 }
4189}
4190
4191VertexDeclarationCache::VertexDeclarationCache() : mMaxLru(0)
4192{
4193 for (int i = 0; i < NUM_VERTEX_DECL_CACHE_ENTRIES; i++)
4194 {
4195 mVertexDeclCache[i].vertexDeclaration = NULL;
4196 mVertexDeclCache[i].lruCount = 0;
4197 }
4198}
4199
4200VertexDeclarationCache::~VertexDeclarationCache()
4201{
4202 for (int i = 0; i < NUM_VERTEX_DECL_CACHE_ENTRIES; i++)
4203 {
4204 if (mVertexDeclCache[i].vertexDeclaration)
4205 {
4206 mVertexDeclCache[i].vertexDeclaration->Release();
4207 }
4208 }
4209}
4210
daniel@transgaming.com5ae3ccc2012-07-24 18:29:38 +00004211GLenum VertexDeclarationCache::applyDeclaration(IDirect3DDevice9 *device, TranslatedAttribute attributes[], ProgramBinary *programBinary, GLsizei instances, GLsizei *repeatDraw)
apatrick@chromium.org144f2802012-07-12 01:42:34 +00004212{
4213 *repeatDraw = 1;
4214
4215 int indexedAttribute = MAX_VERTEX_ATTRIBS;
4216 int instancedAttribute = MAX_VERTEX_ATTRIBS;
4217
4218 if (instances > 0)
4219 {
4220 // Find an indexed attribute to be mapped to D3D stream 0
4221 for (int i = 0; i < MAX_VERTEX_ATTRIBS; i++)
4222 {
4223 if (attributes[i].active)
4224 {
4225 if (indexedAttribute == MAX_VERTEX_ATTRIBS)
4226 {
4227 if (attributes[i].divisor == 0)
4228 {
4229 indexedAttribute = i;
4230 }
4231 }
4232 else if (instancedAttribute == MAX_VERTEX_ATTRIBS)
4233 {
4234 if (attributes[i].divisor != 0)
4235 {
4236 instancedAttribute = i;
4237 }
4238 }
4239 else break; // Found both an indexed and instanced attribute
4240 }
4241 }
4242
4243 if (indexedAttribute == MAX_VERTEX_ATTRIBS)
4244 {
4245 return GL_INVALID_OPERATION;
4246 }
4247 }
4248
4249 D3DVERTEXELEMENT9 elements[MAX_VERTEX_ATTRIBS + 1];
4250 D3DVERTEXELEMENT9 *element = &elements[0];
4251
apatrick@chromium.org144f2802012-07-12 01:42:34 +00004252 for (int i = 0; i < MAX_VERTEX_ATTRIBS; i++)
4253 {
4254 if (attributes[i].active)
4255 {
4256 int stream = i;
4257
4258 if (instances > 0)
4259 {
4260 // Due to a bug on ATI cards we can't enable instancing when none of the attributes are instanced.
4261 if (instancedAttribute == MAX_VERTEX_ATTRIBS)
4262 {
4263 *repeatDraw = instances;
4264 }
4265 else
4266 {
4267 if (i == indexedAttribute)
4268 {
4269 stream = 0;
4270 }
4271 else if (i == 0)
4272 {
4273 stream = indexedAttribute;
4274 }
4275
4276 UINT frequency = 1;
4277
4278 if (attributes[i].divisor == 0)
4279 {
4280 frequency = D3DSTREAMSOURCE_INDEXEDDATA | instances;
4281 }
4282 else
4283 {
4284 frequency = D3DSTREAMSOURCE_INSTANCEDATA | attributes[i].divisor;
4285 }
4286
4287 device->SetStreamSourceFreq(stream, frequency);
4288 mInstancingEnabled = true;
4289 }
4290 }
4291
4292 if (mAppliedVBs[stream].serial != attributes[i].serial ||
4293 mAppliedVBs[stream].stride != attributes[i].stride ||
4294 mAppliedVBs[stream].offset != attributes[i].offset)
4295 {
4296 device->SetStreamSource(stream, attributes[i].vertexBuffer, attributes[i].offset, attributes[i].stride);
4297 mAppliedVBs[stream].serial = attributes[i].serial;
4298 mAppliedVBs[stream].stride = attributes[i].stride;
4299 mAppliedVBs[stream].offset = attributes[i].offset;
4300 }
4301
4302 element->Stream = stream;
4303 element->Offset = 0;
4304 element->Type = attributes[i].type;
4305 element->Method = D3DDECLMETHOD_DEFAULT;
4306 element->Usage = D3DDECLUSAGE_TEXCOORD;
4307 element->UsageIndex = programBinary->getSemanticIndex(i);
4308 element++;
4309 }
4310 }
4311
4312 if (instances == 0 || instancedAttribute == MAX_VERTEX_ATTRIBS)
4313 {
4314 if (mInstancingEnabled)
4315 {
4316 for (int i = 0; i < MAX_VERTEX_ATTRIBS; i++)
4317 {
4318 device->SetStreamSourceFreq(i, 1);
4319 }
4320
4321 mInstancingEnabled = false;
4322 }
4323 }
4324
4325 static const D3DVERTEXELEMENT9 end = D3DDECL_END();
4326 *(element++) = end;
4327
4328 for (int i = 0; i < NUM_VERTEX_DECL_CACHE_ENTRIES; i++)
4329 {
4330 VertexDeclCacheEntry *entry = &mVertexDeclCache[i];
4331 if (memcmp(entry->cachedElements, elements, (element - elements) * sizeof(D3DVERTEXELEMENT9)) == 0 && entry->vertexDeclaration)
4332 {
4333 entry->lruCount = ++mMaxLru;
4334 if(entry->vertexDeclaration != mLastSetVDecl)
4335 {
4336 device->SetVertexDeclaration(entry->vertexDeclaration);
4337 mLastSetVDecl = entry->vertexDeclaration;
4338 }
4339
4340 return GL_NO_ERROR;
4341 }
4342 }
4343
4344 VertexDeclCacheEntry *lastCache = mVertexDeclCache;
4345
4346 for (int i = 0; i < NUM_VERTEX_DECL_CACHE_ENTRIES; i++)
4347 {
4348 if (mVertexDeclCache[i].lruCount < lastCache->lruCount)
4349 {
4350 lastCache = &mVertexDeclCache[i];
4351 }
4352 }
4353
4354 if (lastCache->vertexDeclaration != NULL)
4355 {
4356 lastCache->vertexDeclaration->Release();
4357 lastCache->vertexDeclaration = NULL;
4358 // mLastSetVDecl is set to the replacement, so we don't have to worry
4359 // about it.
4360 }
4361
4362 memcpy(lastCache->cachedElements, elements, (element - elements) * sizeof(D3DVERTEXELEMENT9));
4363 device->CreateVertexDeclaration(elements, &lastCache->vertexDeclaration);
4364 device->SetVertexDeclaration(lastCache->vertexDeclaration);
4365 mLastSetVDecl = lastCache->vertexDeclaration;
4366 lastCache->lruCount = ++mMaxLru;
4367
4368 return GL_NO_ERROR;
4369}
4370
4371void VertexDeclarationCache::markStateDirty()
4372{
4373 for (int i = 0; i < MAX_VERTEX_ATTRIBS; i++)
4374 {
4375 mAppliedVBs[i].serial = 0;
4376 }
4377
4378 mLastSetVDecl = NULL;
4379 mInstancingEnabled = true; // Forces it to be disabled when not used
4380}
4381
4382}
4383
4384extern "C"
4385{
daniel@transgaming.com21290e62012-10-31 18:38:28 +00004386gl::Context *glCreateContext(const gl::Context *shareContext, bool notifyResets, bool robustAccess)
apatrick@chromium.org144f2802012-07-12 01:42:34 +00004387{
daniel@transgaming.com21290e62012-10-31 18:38:28 +00004388 return new gl::Context(shareContext, notifyResets, robustAccess);
apatrick@chromium.org144f2802012-07-12 01:42:34 +00004389}
4390
4391void glDestroyContext(gl::Context *context)
4392{
4393 delete context;
4394
4395 if (context == gl::getContext())
4396 {
4397 gl::makeCurrent(NULL, NULL, NULL);
4398 }
4399}
4400
4401void glMakeCurrent(gl::Context *context, egl::Display *display, egl::Surface *surface)
4402{
4403 gl::makeCurrent(context, display, surface);
4404}
4405
4406gl::Context *glGetCurrentContext()
4407{
4408 return gl::getContext();
4409}
daniel@transgaming.com621ce052012-10-31 17:52:29 +00004410
daniel@transgaming.comef21ab22012-10-31 17:52:47 +00004411renderer::Renderer *glCreateRenderer(egl::Display *display, HMODULE hModule, HDC hDc)
daniel@transgaming.com621ce052012-10-31 17:52:29 +00004412{
daniel@transgaming.comef21ab22012-10-31 17:52:47 +00004413 return new renderer::Renderer(display, hModule, hDc);
daniel@transgaming.com621ce052012-10-31 17:52:29 +00004414}
4415
4416void glDestroyRenderer(renderer::Renderer *renderer)
4417{
4418 delete renderer;
4419}
4420
daniel@transgaming.com3c720782012-10-31 18:42:34 +00004421renderer::SwapChain *glCreateSwapChain(renderer::Renderer *renderer, HWND window, HANDLE shareHandle,
4422 GLenum backBufferFormat, GLenum depthBufferFormat)
4423{
4424 return new renderer::SwapChain(renderer, window, shareHandle, backBufferFormat, depthBufferFormat);
4425}
4426
4427void glDestroySwapChain(renderer::SwapChain *swapChain)
4428{
4429 delete swapChain;
4430}
4431
4432
apatrick@chromium.org144f2802012-07-12 01:42:34 +00004433}