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