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