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