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