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