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