blob: f5423992885ac8f1e1a1447284261b368e69f109 [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
387 mAppliedProgramSerial = 0;
388 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
2315 return mVertexDeclarationCache.applyDeclaration(mDevice, attributes, getCurrentProgram(), instances, repeatDraw);
2316}
2317
2318// Applies the indices and element array bindings to the Direct3D 9 device
2319GLenum Context::applyIndexBuffer(const GLvoid *indices, GLsizei count, GLenum mode, GLenum type, TranslatedIndexData *indexInfo)
2320{
2321 GLenum err = mIndexDataManager->prepareIndexData(type, count, mState.elementArrayBuffer.get(), indices, indexInfo);
2322
2323 if (err == GL_NO_ERROR)
2324 {
2325 if (indexInfo->serial != mAppliedIBSerial)
2326 {
2327 mDevice->SetIndices(indexInfo->indexBuffer);
2328 mAppliedIBSerial = indexInfo->serial;
2329 }
2330 }
2331
2332 return err;
2333}
2334
2335// Applies the shaders and shader constants to the Direct3D 9 device
2336void Context::applyShaders()
2337{
2338 Program *programObject = getCurrentProgram();
2339 ProgramBinary *programBinary = programObject->getProgramBinary();
2340
2341 if (programObject->getSerial() != mAppliedProgramSerial)
2342 {
2343 IDirect3DVertexShader9 *vertexShader = programBinary->getVertexShader();
2344 IDirect3DPixelShader9 *pixelShader = programBinary->getPixelShader();
2345
2346 mDevice->SetPixelShader(pixelShader);
2347 mDevice->SetVertexShader(vertexShader);
2348 programBinary->dirtyAllUniforms();
2349 mAppliedProgramSerial = programObject->getSerial();
2350 }
2351
2352 programBinary->applyUniforms();
2353}
2354
2355// Applies the textures and sampler states to the Direct3D 9 device
2356void Context::applyTextures()
2357{
2358 applyTextures(SAMPLER_PIXEL);
2359
2360 if (mSupportsVertexTexture)
2361 {
2362 applyTextures(SAMPLER_VERTEX);
2363 }
2364}
2365
2366// For each Direct3D 9 sampler of either the pixel or vertex stage,
2367// looks up the corresponding OpenGL texture image unit and texture type,
2368// and sets the texture and its addressing/filtering state (or NULL when inactive).
2369void Context::applyTextures(SamplerType type)
2370{
2371 Program *programObject = getCurrentProgram();
2372 ProgramBinary *programBinary = programObject->getProgramBinary();
2373
2374 int samplerCount = (type == SAMPLER_PIXEL) ? MAX_TEXTURE_IMAGE_UNITS : MAX_VERTEX_TEXTURE_IMAGE_UNITS_VTF; // Range of Direct3D 9 samplers of given sampler type
2375 unsigned int *appliedTextureSerial = (type == SAMPLER_PIXEL) ? mAppliedTextureSerialPS : mAppliedTextureSerialVS;
2376 int d3dSamplerOffset = (type == SAMPLER_PIXEL) ? 0 : D3DVERTEXTEXTURESAMPLER0;
2377 int samplerRange = programBinary->getUsedSamplerRange(type);
2378
2379 for (int samplerIndex = 0; samplerIndex < samplerRange; samplerIndex++)
2380 {
2381 int textureUnit = programBinary->getSamplerMapping(type, samplerIndex); // OpenGL texture image unit index
2382 int d3dSampler = samplerIndex + d3dSamplerOffset;
2383
2384 if (textureUnit != -1)
2385 {
2386 TextureType textureType = programBinary->getSamplerTextureType(type, samplerIndex);
2387
2388 Texture *texture = getSamplerTexture(textureUnit, textureType);
2389 unsigned int texSerial = texture->getTextureSerial();
2390
2391 if (appliedTextureSerial[samplerIndex] != texSerial || texture->hasDirtyParameters() || texture->hasDirtyImages())
2392 {
2393 IDirect3DBaseTexture9 *d3dTexture = texture->getTexture();
2394
2395 if (d3dTexture)
2396 {
2397 if (appliedTextureSerial[samplerIndex] != texSerial || texture->hasDirtyParameters())
2398 {
2399 GLenum wrapS = texture->getWrapS();
2400 GLenum wrapT = texture->getWrapT();
2401 GLenum minFilter = texture->getMinFilter();
2402 GLenum magFilter = texture->getMagFilter();
daniel@transgaming.com07ab8412012-07-12 15:17:09 +00002403 float maxAnisotropy = texture->getMaxAnisotropy();
apatrick@chromium.org144f2802012-07-12 01:42:34 +00002404
2405 mDevice->SetSamplerState(d3dSampler, D3DSAMP_ADDRESSU, es2dx::ConvertTextureWrap(wrapS));
2406 mDevice->SetSamplerState(d3dSampler, D3DSAMP_ADDRESSV, es2dx::ConvertTextureWrap(wrapT));
2407
daniel@transgaming.com07ab8412012-07-12 15:17:09 +00002408 mDevice->SetSamplerState(d3dSampler, D3DSAMP_MAGFILTER, es2dx::ConvertMagFilter(magFilter, maxAnisotropy));
apatrick@chromium.org144f2802012-07-12 01:42:34 +00002409 D3DTEXTUREFILTERTYPE d3dMinFilter, d3dMipFilter;
daniel@transgaming.com07ab8412012-07-12 15:17:09 +00002410 es2dx::ConvertMinFilter(minFilter, &d3dMinFilter, &d3dMipFilter, maxAnisotropy);
apatrick@chromium.org144f2802012-07-12 01:42:34 +00002411 mDevice->SetSamplerState(d3dSampler, D3DSAMP_MINFILTER, d3dMinFilter);
2412 mDevice->SetSamplerState(d3dSampler, D3DSAMP_MIPFILTER, d3dMipFilter);
jbauman@chromium.org68715282012-07-12 23:28:41 +00002413 mDevice->SetSamplerState(d3dSampler, D3DSAMP_MAXMIPLEVEL, texture->getLodOffset());
daniel@transgaming.com07ab8412012-07-12 15:17:09 +00002414
2415 if (supportsTextureFilterAnisotropy())
2416 {
2417 mDevice->SetSamplerState(d3dSampler, D3DSAMP_MAXANISOTROPY, (DWORD)maxAnisotropy);
2418 }
apatrick@chromium.org144f2802012-07-12 01:42:34 +00002419 }
2420
2421 if (appliedTextureSerial[samplerIndex] != texSerial || texture->hasDirtyImages())
2422 {
2423 mDevice->SetTexture(d3dSampler, d3dTexture);
2424 }
2425 }
2426 else
2427 {
2428 mDevice->SetTexture(d3dSampler, getIncompleteTexture(textureType)->getTexture());
2429 }
2430
2431 appliedTextureSerial[samplerIndex] = texSerial;
2432 texture->resetDirty();
2433 }
2434 }
2435 else
2436 {
2437 if (appliedTextureSerial[samplerIndex] != 0)
2438 {
2439 mDevice->SetTexture(d3dSampler, NULL);
2440 appliedTextureSerial[samplerIndex] = 0;
2441 }
2442 }
2443 }
2444
2445 for (int samplerIndex = samplerRange; samplerIndex < samplerCount; samplerIndex++)
2446 {
2447 if (appliedTextureSerial[samplerIndex] != 0)
2448 {
2449 mDevice->SetTexture(samplerIndex + d3dSamplerOffset, NULL);
2450 appliedTextureSerial[samplerIndex] = 0;
2451 }
2452 }
2453}
2454
2455void Context::readPixels(GLint x, GLint y, GLsizei width, GLsizei height,
2456 GLenum format, GLenum type, GLsizei *bufSize, void* pixels)
2457{
2458 Framebuffer *framebuffer = getReadFramebuffer();
2459
2460 if (framebuffer->completeness() != GL_FRAMEBUFFER_COMPLETE)
2461 {
2462 return error(GL_INVALID_FRAMEBUFFER_OPERATION);
2463 }
2464
2465 if (getReadFramebufferHandle() != 0 && framebuffer->getSamples() != 0)
2466 {
2467 return error(GL_INVALID_OPERATION);
2468 }
2469
2470 GLsizei outputPitch = ComputePitch(width, format, type, mState.packAlignment);
2471 // sized query sanity check
2472 if (bufSize)
2473 {
2474 int requiredSize = outputPitch * height;
2475 if (requiredSize > *bufSize)
2476 {
2477 return error(GL_INVALID_OPERATION);
2478 }
2479 }
2480
2481 IDirect3DSurface9 *renderTarget = framebuffer->getRenderTarget();
2482 if (!renderTarget)
2483 {
2484 return; // Context must be lost, return silently
2485 }
2486
2487 D3DSURFACE_DESC desc;
2488 renderTarget->GetDesc(&desc);
2489
2490 if (desc.MultiSampleType != D3DMULTISAMPLE_NONE)
2491 {
2492 UNIMPLEMENTED(); // FIXME: Requires resolve using StretchRect into non-multisampled render target
2493 renderTarget->Release();
2494 return error(GL_OUT_OF_MEMORY);
2495 }
2496
2497 HRESULT result;
2498 IDirect3DSurface9 *systemSurface = NULL;
2499 bool directToPixels = !getPackReverseRowOrder() && getPackAlignment() <= 4 && mDisplay->isD3d9ExDevice() &&
2500 x == 0 && y == 0 && UINT(width) == desc.Width && UINT(height) == desc.Height &&
2501 desc.Format == D3DFMT_A8R8G8B8 && format == GL_BGRA_EXT && type == GL_UNSIGNED_BYTE;
2502 if (directToPixels)
2503 {
2504 // Use the pixels ptr as a shared handle to write directly into client's memory
2505 result = mDevice->CreateOffscreenPlainSurface(desc.Width, desc.Height, desc.Format,
2506 D3DPOOL_SYSTEMMEM, &systemSurface, &pixels);
2507 if (FAILED(result))
2508 {
2509 // Try again without the shared handle
2510 directToPixels = false;
2511 }
2512 }
2513
2514 if (!directToPixels)
2515 {
2516 result = mDevice->CreateOffscreenPlainSurface(desc.Width, desc.Height, desc.Format,
2517 D3DPOOL_SYSTEMMEM, &systemSurface, NULL);
2518 if (FAILED(result))
2519 {
2520 ASSERT(result == D3DERR_OUTOFVIDEOMEMORY || result == E_OUTOFMEMORY);
2521 renderTarget->Release();
2522 return error(GL_OUT_OF_MEMORY);
2523 }
2524 }
2525
2526 result = mDevice->GetRenderTargetData(renderTarget, systemSurface);
2527 renderTarget->Release();
2528 renderTarget = NULL;
2529
2530 if (FAILED(result))
2531 {
2532 systemSurface->Release();
2533
2534 // It turns out that D3D will sometimes produce more error
2535 // codes than those documented.
2536 if (checkDeviceLost(result))
2537 return error(GL_OUT_OF_MEMORY);
2538 else
2539 {
2540 UNREACHABLE();
2541 return;
2542 }
2543
2544 }
2545
2546 if (directToPixels)
2547 {
2548 systemSurface->Release();
2549 return;
2550 }
2551
2552 RECT rect;
2553 rect.left = clamp(x, 0L, static_cast<LONG>(desc.Width));
2554 rect.top = clamp(y, 0L, static_cast<LONG>(desc.Height));
2555 rect.right = clamp(x + width, 0L, static_cast<LONG>(desc.Width));
2556 rect.bottom = clamp(y + height, 0L, static_cast<LONG>(desc.Height));
2557
2558 D3DLOCKED_RECT lock;
2559 result = systemSurface->LockRect(&lock, &rect, D3DLOCK_READONLY);
2560
2561 if (FAILED(result))
2562 {
2563 UNREACHABLE();
2564 systemSurface->Release();
2565
2566 return; // No sensible error to generate
2567 }
2568
2569 unsigned char *dest = (unsigned char*)pixels;
2570 unsigned short *dest16 = (unsigned short*)pixels;
2571
2572 unsigned char *source;
2573 int inputPitch;
2574 if (getPackReverseRowOrder())
2575 {
2576 source = ((unsigned char*)lock.pBits) + lock.Pitch * (rect.bottom - rect.top - 1);
2577 inputPitch = -lock.Pitch;
2578 }
2579 else
2580 {
2581 source = (unsigned char*)lock.pBits;
2582 inputPitch = lock.Pitch;
2583 }
2584
2585 for (int j = 0; j < rect.bottom - rect.top; j++)
2586 {
2587 if (desc.Format == D3DFMT_A8R8G8B8 &&
2588 format == GL_BGRA_EXT &&
2589 type == GL_UNSIGNED_BYTE)
2590 {
2591 // Fast path for EXT_read_format_bgra, given
2592 // an RGBA source buffer. Note that buffers with no
2593 // alpha go through the slow path below.
2594 memcpy(dest + j * outputPitch,
2595 source + j * inputPitch,
2596 (rect.right - rect.left) * 4);
2597 continue;
2598 }
2599
2600 for (int i = 0; i < rect.right - rect.left; i++)
2601 {
2602 float r;
2603 float g;
2604 float b;
2605 float a;
2606
2607 switch (desc.Format)
2608 {
2609 case D3DFMT_R5G6B5:
2610 {
2611 unsigned short rgb = *(unsigned short*)(source + 2 * i + j * inputPitch);
2612
2613 a = 1.0f;
2614 b = (rgb & 0x001F) * (1.0f / 0x001F);
2615 g = (rgb & 0x07E0) * (1.0f / 0x07E0);
2616 r = (rgb & 0xF800) * (1.0f / 0xF800);
2617 }
2618 break;
2619 case D3DFMT_A1R5G5B5:
2620 {
2621 unsigned short argb = *(unsigned short*)(source + 2 * i + j * inputPitch);
2622
2623 a = (argb & 0x8000) ? 1.0f : 0.0f;
2624 b = (argb & 0x001F) * (1.0f / 0x001F);
2625 g = (argb & 0x03E0) * (1.0f / 0x03E0);
2626 r = (argb & 0x7C00) * (1.0f / 0x7C00);
2627 }
2628 break;
2629 case D3DFMT_A8R8G8B8:
2630 {
2631 unsigned int argb = *(unsigned int*)(source + 4 * i + j * inputPitch);
2632
2633 a = (argb & 0xFF000000) * (1.0f / 0xFF000000);
2634 b = (argb & 0x000000FF) * (1.0f / 0x000000FF);
2635 g = (argb & 0x0000FF00) * (1.0f / 0x0000FF00);
2636 r = (argb & 0x00FF0000) * (1.0f / 0x00FF0000);
2637 }
2638 break;
2639 case D3DFMT_X8R8G8B8:
2640 {
2641 unsigned int xrgb = *(unsigned int*)(source + 4 * i + j * inputPitch);
2642
2643 a = 1.0f;
2644 b = (xrgb & 0x000000FF) * (1.0f / 0x000000FF);
2645 g = (xrgb & 0x0000FF00) * (1.0f / 0x0000FF00);
2646 r = (xrgb & 0x00FF0000) * (1.0f / 0x00FF0000);
2647 }
2648 break;
2649 case D3DFMT_A2R10G10B10:
2650 {
2651 unsigned int argb = *(unsigned int*)(source + 4 * i + j * inputPitch);
2652
2653 a = (argb & 0xC0000000) * (1.0f / 0xC0000000);
2654 b = (argb & 0x000003FF) * (1.0f / 0x000003FF);
2655 g = (argb & 0x000FFC00) * (1.0f / 0x000FFC00);
2656 r = (argb & 0x3FF00000) * (1.0f / 0x3FF00000);
2657 }
2658 break;
2659 case D3DFMT_A32B32G32R32F:
2660 {
2661 // float formats in D3D are stored rgba, rather than the other way round
2662 r = *((float*)(source + 16 * i + j * inputPitch) + 0);
2663 g = *((float*)(source + 16 * i + j * inputPitch) + 1);
2664 b = *((float*)(source + 16 * i + j * inputPitch) + 2);
2665 a = *((float*)(source + 16 * i + j * inputPitch) + 3);
2666 }
2667 break;
2668 case D3DFMT_A16B16G16R16F:
2669 {
2670 // float formats in D3D are stored rgba, rather than the other way round
2671 float abgr[4];
2672
2673 D3DXFloat16To32Array(abgr, (D3DXFLOAT16*)(source + 8 * i + j * inputPitch), 4);
2674
2675 a = abgr[3];
2676 b = abgr[2];
2677 g = abgr[1];
2678 r = abgr[0];
2679 }
2680 break;
2681 default:
2682 UNIMPLEMENTED(); // FIXME
2683 UNREACHABLE();
2684 return;
2685 }
2686
2687 switch (format)
2688 {
2689 case GL_RGBA:
2690 switch (type)
2691 {
2692 case GL_UNSIGNED_BYTE:
2693 dest[4 * i + j * outputPitch + 0] = (unsigned char)(255 * r + 0.5f);
2694 dest[4 * i + j * outputPitch + 1] = (unsigned char)(255 * g + 0.5f);
2695 dest[4 * i + j * outputPitch + 2] = (unsigned char)(255 * b + 0.5f);
2696 dest[4 * i + j * outputPitch + 3] = (unsigned char)(255 * a + 0.5f);
2697 break;
2698 default: UNREACHABLE();
2699 }
2700 break;
2701 case GL_BGRA_EXT:
2702 switch (type)
2703 {
2704 case GL_UNSIGNED_BYTE:
2705 dest[4 * i + j * outputPitch + 0] = (unsigned char)(255 * b + 0.5f);
2706 dest[4 * i + j * outputPitch + 1] = (unsigned char)(255 * g + 0.5f);
2707 dest[4 * i + j * outputPitch + 2] = (unsigned char)(255 * r + 0.5f);
2708 dest[4 * i + j * outputPitch + 3] = (unsigned char)(255 * a + 0.5f);
2709 break;
2710 case GL_UNSIGNED_SHORT_4_4_4_4_REV_EXT:
2711 // According to the desktop GL spec in the "Transfer of Pixel Rectangles" section
2712 // this type is packed as follows:
2713 // 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0
2714 // --------------------------------------------------------------------------------
2715 // | 4th | 3rd | 2nd | 1st component |
2716 // --------------------------------------------------------------------------------
2717 // in the case of BGRA_EXT, B is the first component, G the second, and so forth.
2718 dest16[i + j * outputPitch / sizeof(unsigned short)] =
2719 ((unsigned short)(15 * a + 0.5f) << 12)|
2720 ((unsigned short)(15 * r + 0.5f) << 8) |
2721 ((unsigned short)(15 * g + 0.5f) << 4) |
2722 ((unsigned short)(15 * b + 0.5f) << 0);
2723 break;
2724 case GL_UNSIGNED_SHORT_1_5_5_5_REV_EXT:
2725 // According to the desktop GL spec in the "Transfer of Pixel Rectangles" section
2726 // this type is packed as follows:
2727 // 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0
2728 // --------------------------------------------------------------------------------
2729 // | 4th | 3rd | 2nd | 1st component |
2730 // --------------------------------------------------------------------------------
2731 // in the case of BGRA_EXT, B is the first component, G the second, and so forth.
2732 dest16[i + j * outputPitch / sizeof(unsigned short)] =
2733 ((unsigned short)( a + 0.5f) << 15) |
2734 ((unsigned short)(31 * r + 0.5f) << 10) |
2735 ((unsigned short)(31 * g + 0.5f) << 5) |
2736 ((unsigned short)(31 * b + 0.5f) << 0);
2737 break;
2738 default: UNREACHABLE();
2739 }
2740 break;
2741 case GL_RGB: // IMPLEMENTATION_COLOR_READ_FORMAT
2742 switch (type)
2743 {
2744 case GL_UNSIGNED_SHORT_5_6_5: // IMPLEMENTATION_COLOR_READ_TYPE
2745 dest16[i + j * outputPitch / sizeof(unsigned short)] =
2746 ((unsigned short)(31 * b + 0.5f) << 0) |
2747 ((unsigned short)(63 * g + 0.5f) << 5) |
2748 ((unsigned short)(31 * r + 0.5f) << 11);
2749 break;
2750 default: UNREACHABLE();
2751 }
2752 break;
2753 default: UNREACHABLE();
2754 }
2755 }
2756 }
2757
2758 systemSurface->UnlockRect();
2759
2760 systemSurface->Release();
2761}
2762
2763void Context::clear(GLbitfield mask)
2764{
2765 Framebuffer *framebufferObject = getDrawFramebuffer();
2766
2767 if (!framebufferObject || framebufferObject->completeness() != GL_FRAMEBUFFER_COMPLETE)
2768 {
2769 return error(GL_INVALID_FRAMEBUFFER_OPERATION);
2770 }
2771
2772 DWORD flags = 0;
2773
2774 if (mask & GL_COLOR_BUFFER_BIT)
2775 {
2776 mask &= ~GL_COLOR_BUFFER_BIT;
2777
2778 if (framebufferObject->getColorbufferType() != GL_NONE)
2779 {
2780 flags |= D3DCLEAR_TARGET;
2781 }
2782 }
2783
2784 if (mask & GL_DEPTH_BUFFER_BIT)
2785 {
2786 mask &= ~GL_DEPTH_BUFFER_BIT;
2787 if (mState.depthMask && framebufferObject->getDepthbufferType() != GL_NONE)
2788 {
2789 flags |= D3DCLEAR_ZBUFFER;
2790 }
2791 }
2792
2793 GLuint stencilUnmasked = 0x0;
2794
2795 if (mask & GL_STENCIL_BUFFER_BIT)
2796 {
2797 mask &= ~GL_STENCIL_BUFFER_BIT;
2798 if (framebufferObject->getStencilbufferType() != GL_NONE)
2799 {
2800 IDirect3DSurface9 *depthStencil = framebufferObject->getStencilbuffer()->getDepthStencil();
2801 if (!depthStencil)
2802 {
2803 ERR("Depth stencil pointer unexpectedly null.");
2804 return;
2805 }
2806
2807 D3DSURFACE_DESC desc;
2808 depthStencil->GetDesc(&desc);
2809 depthStencil->Release();
2810
2811 unsigned int stencilSize = dx2es::GetStencilSize(desc.Format);
2812 stencilUnmasked = (0x1 << stencilSize) - 1;
2813
2814 if (stencilUnmasked != 0x0)
2815 {
2816 flags |= D3DCLEAR_STENCIL;
2817 }
2818 }
2819 }
2820
2821 if (mask != 0)
2822 {
2823 return error(GL_INVALID_VALUE);
2824 }
2825
2826 if (!applyRenderTarget(true)) // Clips the clear to the scissor rectangle but not the viewport
2827 {
2828 return;
2829 }
2830
2831 D3DCOLOR color = D3DCOLOR_ARGB(unorm<8>(mState.colorClearValue.alpha),
2832 unorm<8>(mState.colorClearValue.red),
2833 unorm<8>(mState.colorClearValue.green),
2834 unorm<8>(mState.colorClearValue.blue));
2835 float depth = clamp01(mState.depthClearValue);
2836 int stencil = mState.stencilClearValue & 0x000000FF;
2837
2838 bool alphaUnmasked = (dx2es::GetAlphaSize(mRenderTargetDesc.Format) == 0) || mState.colorMaskAlpha;
2839
2840 const bool needMaskedStencilClear = (flags & D3DCLEAR_STENCIL) &&
2841 (mState.stencilWritemask & stencilUnmasked) != stencilUnmasked;
2842 const bool needMaskedColorClear = (flags & D3DCLEAR_TARGET) &&
2843 !(mState.colorMaskRed && mState.colorMaskGreen &&
2844 mState.colorMaskBlue && alphaUnmasked);
2845
2846 if (needMaskedColorClear || needMaskedStencilClear)
2847 {
2848 // State which is altered in all paths from this point to the clear call is saved.
2849 // State which is altered in only some paths will be flagged dirty in the case that
2850 // that path is taken.
2851 HRESULT hr;
2852 if (mMaskedClearSavedState == NULL)
2853 {
2854 hr = mDevice->BeginStateBlock();
2855 ASSERT(SUCCEEDED(hr) || hr == D3DERR_OUTOFVIDEOMEMORY || hr == E_OUTOFMEMORY);
2856
2857 mDevice->SetRenderState(D3DRS_ZWRITEENABLE, FALSE);
2858 mDevice->SetRenderState(D3DRS_ZFUNC, D3DCMP_ALWAYS);
2859 mDevice->SetRenderState(D3DRS_ZENABLE, FALSE);
2860 mDevice->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE);
2861 mDevice->SetRenderState(D3DRS_FILLMODE, D3DFILL_SOLID);
2862 mDevice->SetRenderState(D3DRS_ALPHATESTENABLE, FALSE);
2863 mDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, FALSE);
2864 mDevice->SetRenderState(D3DRS_CLIPPLANEENABLE, 0);
2865 mDevice->SetRenderState(D3DRS_COLORWRITEENABLE, 0);
2866 mDevice->SetRenderState(D3DRS_STENCILENABLE, FALSE);
2867 mDevice->SetPixelShader(NULL);
2868 mDevice->SetVertexShader(NULL);
2869 mDevice->SetFVF(D3DFVF_XYZRHW | D3DFVF_DIFFUSE);
2870 mDevice->SetStreamSource(0, NULL, 0, 0);
2871 mDevice->SetRenderState(D3DRS_SEPARATEALPHABLENDENABLE, TRUE);
2872 mDevice->SetTextureStageState(0, D3DTSS_COLOROP, D3DTOP_SELECTARG1);
2873 mDevice->SetTextureStageState(0, D3DTSS_COLORARG1, D3DTA_TFACTOR);
2874 mDevice->SetTextureStageState(0, D3DTSS_ALPHAOP, D3DTOP_SELECTARG1);
2875 mDevice->SetTextureStageState(0, D3DTSS_ALPHAARG1, D3DTA_TFACTOR);
2876 mDevice->SetRenderState(D3DRS_TEXTUREFACTOR, color);
2877 mDevice->SetRenderState(D3DRS_MULTISAMPLEMASK, 0xFFFFFFFF);
2878
2879 for(int i = 0; i < MAX_VERTEX_ATTRIBS; i++)
2880 {
2881 mDevice->SetStreamSourceFreq(i, 1);
2882 }
2883
2884 hr = mDevice->EndStateBlock(&mMaskedClearSavedState);
2885 ASSERT(SUCCEEDED(hr) || hr == D3DERR_OUTOFVIDEOMEMORY || hr == E_OUTOFMEMORY);
2886 }
2887
2888 ASSERT(mMaskedClearSavedState != NULL);
2889
2890 if (mMaskedClearSavedState != NULL)
2891 {
2892 hr = mMaskedClearSavedState->Capture();
2893 ASSERT(SUCCEEDED(hr));
2894 }
2895
2896 mDevice->SetRenderState(D3DRS_ZWRITEENABLE, FALSE);
2897 mDevice->SetRenderState(D3DRS_ZFUNC, D3DCMP_ALWAYS);
2898 mDevice->SetRenderState(D3DRS_ZENABLE, FALSE);
2899 mDevice->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE);
2900 mDevice->SetRenderState(D3DRS_FILLMODE, D3DFILL_SOLID);
2901 mDevice->SetRenderState(D3DRS_ALPHATESTENABLE, FALSE);
2902 mDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, FALSE);
2903 mDevice->SetRenderState(D3DRS_CLIPPLANEENABLE, 0);
2904
2905 if (flags & D3DCLEAR_TARGET)
2906 {
2907 mDevice->SetRenderState(D3DRS_COLORWRITEENABLE, es2dx::ConvertColorMask(mState.colorMaskRed, mState.colorMaskGreen, mState.colorMaskBlue, mState.colorMaskAlpha));
2908 }
2909 else
2910 {
2911 mDevice->SetRenderState(D3DRS_COLORWRITEENABLE, 0);
2912 }
2913
2914 if (stencilUnmasked != 0x0 && (flags & D3DCLEAR_STENCIL))
2915 {
2916 mDevice->SetRenderState(D3DRS_STENCILENABLE, TRUE);
2917 mDevice->SetRenderState(D3DRS_TWOSIDEDSTENCILMODE, FALSE);
2918 mDevice->SetRenderState(D3DRS_STENCILFUNC, D3DCMP_ALWAYS);
2919 mDevice->SetRenderState(D3DRS_STENCILREF, stencil);
2920 mDevice->SetRenderState(D3DRS_STENCILWRITEMASK, mState.stencilWritemask);
2921 mDevice->SetRenderState(D3DRS_STENCILFAIL, D3DSTENCILOP_REPLACE);
2922 mDevice->SetRenderState(D3DRS_STENCILZFAIL, D3DSTENCILOP_REPLACE);
2923 mDevice->SetRenderState(D3DRS_STENCILPASS, D3DSTENCILOP_REPLACE);
2924 mStencilStateDirty = true;
2925 }
2926 else
2927 {
2928 mDevice->SetRenderState(D3DRS_STENCILENABLE, FALSE);
2929 }
2930
2931 mDevice->SetPixelShader(NULL);
2932 mDevice->SetVertexShader(NULL);
2933 mDevice->SetFVF(D3DFVF_XYZRHW);
2934 mDevice->SetRenderState(D3DRS_SEPARATEALPHABLENDENABLE, TRUE);
2935 mDevice->SetTextureStageState(0, D3DTSS_COLOROP, D3DTOP_SELECTARG1);
2936 mDevice->SetTextureStageState(0, D3DTSS_COLORARG1, D3DTA_TFACTOR);
2937 mDevice->SetTextureStageState(0, D3DTSS_ALPHAOP, D3DTOP_SELECTARG1);
2938 mDevice->SetTextureStageState(0, D3DTSS_ALPHAARG1, D3DTA_TFACTOR);
2939 mDevice->SetRenderState(D3DRS_TEXTUREFACTOR, color);
2940 mDevice->SetRenderState(D3DRS_MULTISAMPLEMASK, 0xFFFFFFFF);
2941
2942 for(int i = 0; i < MAX_VERTEX_ATTRIBS; i++)
2943 {
2944 mDevice->SetStreamSourceFreq(i, 1);
2945 }
2946
2947 float quad[4][4]; // A quadrilateral covering the target, aligned to match the edges
2948 quad[0][0] = -0.5f;
2949 quad[0][1] = mRenderTargetDesc.Height - 0.5f;
2950 quad[0][2] = 0.0f;
2951 quad[0][3] = 1.0f;
2952
2953 quad[1][0] = mRenderTargetDesc.Width - 0.5f;
2954 quad[1][1] = mRenderTargetDesc.Height - 0.5f;
2955 quad[1][2] = 0.0f;
2956 quad[1][3] = 1.0f;
2957
2958 quad[2][0] = -0.5f;
2959 quad[2][1] = -0.5f;
2960 quad[2][2] = 0.0f;
2961 quad[2][3] = 1.0f;
2962
2963 quad[3][0] = mRenderTargetDesc.Width - 0.5f;
2964 quad[3][1] = -0.5f;
2965 quad[3][2] = 0.0f;
2966 quad[3][3] = 1.0f;
2967
2968 mDisplay->startScene();
2969 mDevice->DrawPrimitiveUP(D3DPT_TRIANGLESTRIP, 2, quad, sizeof(float[4]));
2970
2971 if (flags & D3DCLEAR_ZBUFFER)
2972 {
2973 mDevice->SetRenderState(D3DRS_ZENABLE, TRUE);
2974 mDevice->SetRenderState(D3DRS_ZWRITEENABLE, TRUE);
2975 mDevice->Clear(0, NULL, D3DCLEAR_ZBUFFER, color, depth, stencil);
2976 }
2977
2978 if (mMaskedClearSavedState != NULL)
2979 {
2980 mMaskedClearSavedState->Apply();
2981 }
2982 }
2983 else if (flags)
2984 {
2985 mDevice->Clear(0, NULL, flags, color, depth, stencil);
2986 }
2987}
2988
2989void Context::drawArrays(GLenum mode, GLint first, GLsizei count, GLsizei instances)
2990{
2991 if (!mState.currentProgram)
2992 {
2993 return error(GL_INVALID_OPERATION);
2994 }
2995
2996 D3DPRIMITIVETYPE primitiveType;
2997 int primitiveCount;
2998
2999 if(!es2dx::ConvertPrimitiveType(mode, count, &primitiveType, &primitiveCount))
3000 return error(GL_INVALID_ENUM);
3001
3002 if (primitiveCount <= 0)
3003 {
3004 return;
3005 }
3006
3007 if (!applyRenderTarget(false))
3008 {
3009 return;
3010 }
3011
3012 applyState(mode);
3013
3014 GLsizei repeatDraw = 1;
3015 GLenum err = applyVertexBuffer(first, count, instances, &repeatDraw);
3016 if (err != GL_NO_ERROR)
3017 {
3018 return error(err);
3019 }
3020
3021 applyShaders();
3022 applyTextures();
3023
3024 if (!getCurrentProgram()->getProgramBinary()->validateSamplers(NULL))
3025 {
3026 return error(GL_INVALID_OPERATION);
3027 }
3028
3029 if (!cullSkipsDraw(mode))
3030 {
3031 mDisplay->startScene();
3032
3033 if (mode == GL_LINE_LOOP)
3034 {
3035 drawLineLoop(count, GL_NONE, NULL, 0);
3036 }
3037 else if (instances > 0)
3038 {
3039 StaticIndexBuffer *countingIB = mIndexDataManager->getCountingIndices(count);
3040 if (countingIB)
3041 {
3042 if (mAppliedIBSerial != countingIB->getSerial())
3043 {
3044 mDevice->SetIndices(countingIB->getBuffer());
3045 mAppliedIBSerial = countingIB->getSerial();
3046 }
3047
3048 for (int i = 0; i < repeatDraw; i++)
3049 {
3050 mDevice->DrawIndexedPrimitive(primitiveType, 0, 0, count, 0, primitiveCount);
3051 }
3052 }
3053 else
3054 {
3055 ERR("Could not create a counting index buffer for glDrawArraysInstanced.");
3056 return error(GL_OUT_OF_MEMORY);
3057 }
3058 }
3059 else // Regular case
3060 {
3061 mDevice->DrawPrimitive(primitiveType, 0, primitiveCount);
3062 }
3063 }
3064}
3065
3066void Context::drawElements(GLenum mode, GLsizei count, GLenum type, const GLvoid *indices, GLsizei instances)
3067{
3068 if (!mState.currentProgram)
3069 {
3070 return error(GL_INVALID_OPERATION);
3071 }
3072
3073 if (!indices && !mState.elementArrayBuffer)
3074 {
3075 return error(GL_INVALID_OPERATION);
3076 }
3077
3078 D3DPRIMITIVETYPE primitiveType;
3079 int primitiveCount;
3080
3081 if(!es2dx::ConvertPrimitiveType(mode, count, &primitiveType, &primitiveCount))
3082 return error(GL_INVALID_ENUM);
3083
3084 if (primitiveCount <= 0)
3085 {
3086 return;
3087 }
3088
3089 if (!applyRenderTarget(false))
3090 {
3091 return;
3092 }
3093
3094 applyState(mode);
3095
3096 TranslatedIndexData indexInfo;
3097 GLenum err = applyIndexBuffer(indices, count, mode, type, &indexInfo);
3098 if (err != GL_NO_ERROR)
3099 {
3100 return error(err);
3101 }
3102
3103 GLsizei vertexCount = indexInfo.maxIndex - indexInfo.minIndex + 1;
3104 GLsizei repeatDraw = 1;
3105 err = applyVertexBuffer(indexInfo.minIndex, vertexCount, instances, &repeatDraw);
3106 if (err != GL_NO_ERROR)
3107 {
3108 return error(err);
3109 }
3110
3111 applyShaders();
3112 applyTextures();
3113
3114 if (!getCurrentProgram()->getProgramBinary()->validateSamplers(false))
3115 {
3116 return error(GL_INVALID_OPERATION);
3117 }
3118
3119 if (!cullSkipsDraw(mode))
3120 {
3121 mDisplay->startScene();
3122
3123 if (mode == GL_LINE_LOOP)
3124 {
3125 drawLineLoop(count, type, indices, indexInfo.minIndex);
3126 }
3127 else
3128 {
3129 for (int i = 0; i < repeatDraw; i++)
3130 {
3131 mDevice->DrawIndexedPrimitive(primitiveType, -(INT)indexInfo.minIndex, indexInfo.minIndex, vertexCount, indexInfo.startIndex, primitiveCount);
3132 }
3133 }
3134 }
3135}
3136
3137// Implements glFlush when block is false, glFinish when block is true
3138void Context::sync(bool block)
3139{
3140 mDisplay->sync(block);
3141}
3142
3143void Context::drawLineLoop(GLsizei count, GLenum type, const GLvoid *indices, int minIndex)
3144{
3145 // Get the raw indices for an indexed draw
3146 if (type != GL_NONE && mState.elementArrayBuffer.get())
3147 {
3148 Buffer *indexBuffer = mState.elementArrayBuffer.get();
3149 intptr_t offset = reinterpret_cast<intptr_t>(indices);
3150 indices = static_cast<const GLubyte*>(indexBuffer->data()) + offset;
3151 }
3152
3153 UINT startIndex = 0;
3154 bool succeeded = false;
3155
3156 if (supports32bitIndices())
3157 {
3158 const int spaceNeeded = (count + 1) * sizeof(unsigned int);
3159
3160 if (!mLineLoopIB)
3161 {
3162 mLineLoopIB = new StreamingIndexBuffer(mDevice, INITIAL_INDEX_BUFFER_SIZE, D3DFMT_INDEX32);
3163 }
3164
3165 if (mLineLoopIB)
3166 {
3167 mLineLoopIB->reserveSpace(spaceNeeded, GL_UNSIGNED_INT);
3168
3169 UINT offset = 0;
3170 unsigned int *data = static_cast<unsigned int*>(mLineLoopIB->map(spaceNeeded, &offset));
3171 startIndex = offset / 4;
3172
3173 if (data)
3174 {
3175 switch (type)
3176 {
3177 case GL_NONE: // Non-indexed draw
3178 for (int i = 0; i < count; i++)
3179 {
3180 data[i] = i;
3181 }
3182 data[count] = 0;
3183 break;
3184 case GL_UNSIGNED_BYTE:
3185 for (int i = 0; i < count; i++)
3186 {
3187 data[i] = static_cast<const GLubyte*>(indices)[i];
3188 }
3189 data[count] = static_cast<const GLubyte*>(indices)[0];
3190 break;
3191 case GL_UNSIGNED_SHORT:
3192 for (int i = 0; i < count; i++)
3193 {
3194 data[i] = static_cast<const GLushort*>(indices)[i];
3195 }
3196 data[count] = static_cast<const GLushort*>(indices)[0];
3197 break;
3198 case GL_UNSIGNED_INT:
3199 for (int i = 0; i < count; i++)
3200 {
3201 data[i] = static_cast<const GLuint*>(indices)[i];
3202 }
3203 data[count] = static_cast<const GLuint*>(indices)[0];
3204 break;
3205 default: UNREACHABLE();
3206 }
3207
3208 mLineLoopIB->unmap();
3209 succeeded = true;
3210 }
3211 }
3212 }
3213 else
3214 {
3215 const int spaceNeeded = (count + 1) * sizeof(unsigned short);
3216
3217 if (!mLineLoopIB)
3218 {
3219 mLineLoopIB = new StreamingIndexBuffer(mDevice, INITIAL_INDEX_BUFFER_SIZE, D3DFMT_INDEX16);
3220 }
3221
3222 if (mLineLoopIB)
3223 {
3224 mLineLoopIB->reserveSpace(spaceNeeded, GL_UNSIGNED_SHORT);
3225
3226 UINT offset = 0;
3227 unsigned short *data = static_cast<unsigned short*>(mLineLoopIB->map(spaceNeeded, &offset));
3228 startIndex = offset / 2;
3229
3230 if (data)
3231 {
3232 switch (type)
3233 {
3234 case GL_NONE: // Non-indexed draw
3235 for (int i = 0; i < count; i++)
3236 {
3237 data[i] = i;
3238 }
3239 data[count] = 0;
3240 break;
3241 case GL_UNSIGNED_BYTE:
3242 for (int i = 0; i < count; i++)
3243 {
3244 data[i] = static_cast<const GLubyte*>(indices)[i];
3245 }
3246 data[count] = static_cast<const GLubyte*>(indices)[0];
3247 break;
3248 case GL_UNSIGNED_SHORT:
3249 for (int i = 0; i < count; i++)
3250 {
3251 data[i] = static_cast<const GLushort*>(indices)[i];
3252 }
3253 data[count] = static_cast<const GLushort*>(indices)[0];
3254 break;
3255 case GL_UNSIGNED_INT:
3256 for (int i = 0; i < count; i++)
3257 {
3258 data[i] = static_cast<const GLuint*>(indices)[i];
3259 }
3260 data[count] = static_cast<const GLuint*>(indices)[0];
3261 break;
3262 default: UNREACHABLE();
3263 }
3264
3265 mLineLoopIB->unmap();
3266 succeeded = true;
3267 }
3268 }
3269 }
3270
3271 if (succeeded)
3272 {
3273 if (mAppliedIBSerial != mLineLoopIB->getSerial())
3274 {
3275 mDevice->SetIndices(mLineLoopIB->getBuffer());
3276 mAppliedIBSerial = mLineLoopIB->getSerial();
3277 }
3278
3279 mDevice->DrawIndexedPrimitive(D3DPT_LINESTRIP, -minIndex, minIndex, count, startIndex, count);
3280 }
3281 else
3282 {
3283 ERR("Could not create a looping index buffer for GL_LINE_LOOP.");
3284 return error(GL_OUT_OF_MEMORY);
3285 }
3286}
3287
3288void Context::recordInvalidEnum()
3289{
3290 mInvalidEnum = true;
3291}
3292
3293void Context::recordInvalidValue()
3294{
3295 mInvalidValue = true;
3296}
3297
3298void Context::recordInvalidOperation()
3299{
3300 mInvalidOperation = true;
3301}
3302
3303void Context::recordOutOfMemory()
3304{
3305 mOutOfMemory = true;
3306}
3307
3308void Context::recordInvalidFramebufferOperation()
3309{
3310 mInvalidFramebufferOperation = true;
3311}
3312
3313// Get one of the recorded errors and clear its flag, if any.
3314// [OpenGL ES 2.0.24] section 2.5 page 13.
3315GLenum Context::getError()
3316{
3317 if (mInvalidEnum)
3318 {
3319 mInvalidEnum = false;
3320
3321 return GL_INVALID_ENUM;
3322 }
3323
3324 if (mInvalidValue)
3325 {
3326 mInvalidValue = false;
3327
3328 return GL_INVALID_VALUE;
3329 }
3330
3331 if (mInvalidOperation)
3332 {
3333 mInvalidOperation = false;
3334
3335 return GL_INVALID_OPERATION;
3336 }
3337
3338 if (mOutOfMemory)
3339 {
3340 mOutOfMemory = false;
3341
3342 return GL_OUT_OF_MEMORY;
3343 }
3344
3345 if (mInvalidFramebufferOperation)
3346 {
3347 mInvalidFramebufferOperation = false;
3348
3349 return GL_INVALID_FRAMEBUFFER_OPERATION;
3350 }
3351
3352 return GL_NO_ERROR;
3353}
3354
3355GLenum Context::getResetStatus()
3356{
3357 if (mResetStatus == GL_NO_ERROR)
3358 {
3359 bool lost = mDisplay->testDeviceLost();
3360
3361 if (lost)
3362 {
3363 mDisplay->notifyDeviceLost(); // Sets mResetStatus
3364 }
3365 }
3366
3367 GLenum status = mResetStatus;
3368
3369 if (mResetStatus != GL_NO_ERROR)
3370 {
3371 if (mDisplay->testDeviceResettable())
3372 {
3373 mResetStatus = GL_NO_ERROR;
3374 }
3375 }
3376
3377 return status;
3378}
3379
3380bool Context::isResetNotificationEnabled()
3381{
3382 return (mResetStrategy == GL_LOSE_CONTEXT_ON_RESET_EXT);
3383}
3384
3385bool Context::supportsShaderModel3() const
3386{
3387 return mSupportsShaderModel3;
3388}
3389
3390float Context::getMaximumPointSize() const
3391{
3392 return mSupportsShaderModel3 ? mMaximumPointSize : ALIASED_POINT_SIZE_RANGE_MAX_SM2;
3393}
3394
3395int Context::getMaximumVaryingVectors() const
3396{
3397 return mSupportsShaderModel3 ? MAX_VARYING_VECTORS_SM3 : MAX_VARYING_VECTORS_SM2;
3398}
3399
3400unsigned int Context::getMaximumVertexTextureImageUnits() const
3401{
3402 return mSupportsVertexTexture ? MAX_VERTEX_TEXTURE_IMAGE_UNITS_VTF : 0;
3403}
3404
3405unsigned int Context::getMaximumCombinedTextureImageUnits() const
3406{
3407 return MAX_TEXTURE_IMAGE_UNITS + getMaximumVertexTextureImageUnits();
3408}
3409
3410int Context::getMaximumFragmentUniformVectors() const
3411{
3412 return mSupportsShaderModel3 ? MAX_FRAGMENT_UNIFORM_VECTORS_SM3 : MAX_FRAGMENT_UNIFORM_VECTORS_SM2;
3413}
3414
3415int Context::getMaxSupportedSamples() const
3416{
3417 return mMaxSupportedSamples;
3418}
3419
3420int Context::getNearestSupportedSamples(D3DFORMAT format, int requested) const
3421{
3422 if (requested == 0)
3423 {
3424 return requested;
3425 }
3426
3427 std::map<D3DFORMAT, bool *>::const_iterator itr = mMultiSampleSupport.find(format);
3428 if (itr == mMultiSampleSupport.end())
3429 {
3430 return -1;
3431 }
3432
3433 for (int i = requested; i <= D3DMULTISAMPLE_16_SAMPLES; ++i)
3434 {
3435 if (itr->second[i] && i != D3DMULTISAMPLE_NONMASKABLE)
3436 {
3437 return i;
3438 }
3439 }
3440
3441 return -1;
3442}
3443
3444bool Context::supportsEventQueries() const
3445{
3446 return mSupportsEventQueries;
3447}
3448
3449bool Context::supportsOcclusionQueries() const
3450{
3451 return mSupportsOcclusionQueries;
3452}
3453
3454bool Context::supportsDXT1Textures() const
3455{
3456 return mSupportsDXT1Textures;
3457}
3458
3459bool Context::supportsDXT3Textures() const
3460{
3461 return mSupportsDXT3Textures;
3462}
3463
3464bool Context::supportsDXT5Textures() const
3465{
3466 return mSupportsDXT5Textures;
3467}
3468
3469bool Context::supportsFloat32Textures() const
3470{
3471 return mSupportsFloat32Textures;
3472}
3473
3474bool Context::supportsFloat32LinearFilter() const
3475{
3476 return mSupportsFloat32LinearFilter;
3477}
3478
3479bool Context::supportsFloat32RenderableTextures() const
3480{
3481 return mSupportsFloat32RenderableTextures;
3482}
3483
3484bool Context::supportsFloat16Textures() const
3485{
3486 return mSupportsFloat16Textures;
3487}
3488
3489bool Context::supportsFloat16LinearFilter() const
3490{
3491 return mSupportsFloat16LinearFilter;
3492}
3493
3494bool Context::supportsFloat16RenderableTextures() const
3495{
3496 return mSupportsFloat16RenderableTextures;
3497}
3498
3499int Context::getMaximumRenderbufferDimension() const
3500{
3501 return mMaxRenderbufferDimension;
3502}
3503
3504int Context::getMaximumTextureDimension() const
3505{
3506 return mMaxTextureDimension;
3507}
3508
3509int Context::getMaximumCubeTextureDimension() const
3510{
3511 return mMaxCubeTextureDimension;
3512}
3513
3514int Context::getMaximumTextureLevel() const
3515{
3516 return mMaxTextureLevel;
3517}
3518
3519bool Context::supportsLuminanceTextures() const
3520{
3521 return mSupportsLuminanceTextures;
3522}
3523
3524bool Context::supportsLuminanceAlphaTextures() const
3525{
3526 return mSupportsLuminanceAlphaTextures;
3527}
3528
3529bool Context::supportsDepthTextures() const
3530{
3531 return mSupportsDepthTextures;
3532}
3533
3534bool Context::supports32bitIndices() const
3535{
3536 return mSupports32bitIndices;
3537}
3538
3539bool Context::supportsNonPower2Texture() const
3540{
3541 return mSupportsNonPower2Texture;
3542}
3543
3544bool Context::supportsInstancing() const
3545{
3546 return mSupportsInstancing;
3547}
3548
daniel@transgaming.com07ab8412012-07-12 15:17:09 +00003549bool Context::supportsTextureFilterAnisotropy() const
3550{
3551 return mSupportsTextureFilterAnisotropy;
3552}
3553
3554float Context::getTextureMaxAnisotropy() const
3555{
3556 return mMaxTextureAnisotropy;
3557}
3558
apatrick@chromium.org144f2802012-07-12 01:42:34 +00003559void Context::detachBuffer(GLuint buffer)
3560{
3561 // [OpenGL ES 2.0.24] section 2.9 page 22:
3562 // If a buffer object is deleted while it is bound, all bindings to that object in the current context
3563 // (i.e. in the thread that called Delete-Buffers) are reset to zero.
3564
3565 if (mState.arrayBuffer.id() == buffer)
3566 {
3567 mState.arrayBuffer.set(NULL);
3568 }
3569
3570 if (mState.elementArrayBuffer.id() == buffer)
3571 {
3572 mState.elementArrayBuffer.set(NULL);
3573 }
3574
3575 for (int attribute = 0; attribute < MAX_VERTEX_ATTRIBS; attribute++)
3576 {
3577 if (mState.vertexAttribute[attribute].mBoundBuffer.id() == buffer)
3578 {
3579 mState.vertexAttribute[attribute].mBoundBuffer.set(NULL);
3580 }
3581 }
3582}
3583
3584void Context::detachTexture(GLuint texture)
3585{
3586 // [OpenGL ES 2.0.24] section 3.8 page 84:
3587 // If a texture object is deleted, it is as if all texture units which are bound to that texture object are
3588 // rebound to texture object zero
3589
3590 for (int type = 0; type < TEXTURE_TYPE_COUNT; type++)
3591 {
3592 for (int sampler = 0; sampler < MAX_COMBINED_TEXTURE_IMAGE_UNITS_VTF; sampler++)
3593 {
3594 if (mState.samplerTexture[type][sampler].id() == texture)
3595 {
3596 mState.samplerTexture[type][sampler].set(NULL);
3597 }
3598 }
3599 }
3600
3601 // [OpenGL ES 2.0.24] section 4.4 page 112:
3602 // If a texture object is deleted while its image is attached to the currently bound framebuffer, then it is
3603 // as if FramebufferTexture2D had been called, with a texture of 0, for each attachment point to which this
3604 // image was attached in the currently bound framebuffer.
3605
3606 Framebuffer *readFramebuffer = getReadFramebuffer();
3607 Framebuffer *drawFramebuffer = getDrawFramebuffer();
3608
3609 if (readFramebuffer)
3610 {
3611 readFramebuffer->detachTexture(texture);
3612 }
3613
3614 if (drawFramebuffer && drawFramebuffer != readFramebuffer)
3615 {
3616 drawFramebuffer->detachTexture(texture);
3617 }
3618}
3619
3620void Context::detachFramebuffer(GLuint framebuffer)
3621{
3622 // [OpenGL ES 2.0.24] section 4.4 page 107:
3623 // If a framebuffer that is currently bound to the target FRAMEBUFFER is deleted, it is as though
3624 // BindFramebuffer had been executed with the target of FRAMEBUFFER and framebuffer of zero.
3625
3626 if (mState.readFramebuffer == framebuffer)
3627 {
3628 bindReadFramebuffer(0);
3629 }
3630
3631 if (mState.drawFramebuffer == framebuffer)
3632 {
3633 bindDrawFramebuffer(0);
3634 }
3635}
3636
3637void Context::detachRenderbuffer(GLuint renderbuffer)
3638{
3639 // [OpenGL ES 2.0.24] section 4.4 page 109:
3640 // If a renderbuffer that is currently bound to RENDERBUFFER is deleted, it is as though BindRenderbuffer
3641 // had been executed with the target RENDERBUFFER and name of zero.
3642
3643 if (mState.renderbuffer.id() == renderbuffer)
3644 {
3645 bindRenderbuffer(0);
3646 }
3647
3648 // [OpenGL ES 2.0.24] section 4.4 page 111:
3649 // If a renderbuffer object is deleted while its image is attached to the currently bound framebuffer,
3650 // then it is as if FramebufferRenderbuffer had been called, with a renderbuffer of 0, for each attachment
3651 // point to which this image was attached in the currently bound framebuffer.
3652
3653 Framebuffer *readFramebuffer = getReadFramebuffer();
3654 Framebuffer *drawFramebuffer = getDrawFramebuffer();
3655
3656 if (readFramebuffer)
3657 {
3658 readFramebuffer->detachRenderbuffer(renderbuffer);
3659 }
3660
3661 if (drawFramebuffer && drawFramebuffer != readFramebuffer)
3662 {
3663 drawFramebuffer->detachRenderbuffer(renderbuffer);
3664 }
3665}
3666
3667Texture *Context::getIncompleteTexture(TextureType type)
3668{
3669 Texture *t = mIncompleteTextures[type].get();
3670
3671 if (t == NULL)
3672 {
3673 static const GLubyte color[] = { 0, 0, 0, 255 };
3674
3675 switch (type)
3676 {
3677 default:
3678 UNREACHABLE();
3679 // default falls through to TEXTURE_2D
3680
3681 case TEXTURE_2D:
3682 {
3683 Texture2D *incomplete2d = new Texture2D(Texture::INCOMPLETE_TEXTURE_ID);
3684 incomplete2d->setImage(0, 1, 1, GL_RGBA, GL_UNSIGNED_BYTE, 1, color);
3685 t = incomplete2d;
3686 }
3687 break;
3688
3689 case TEXTURE_CUBE:
3690 {
3691 TextureCubeMap *incompleteCube = new TextureCubeMap(Texture::INCOMPLETE_TEXTURE_ID);
3692
3693 incompleteCube->setImagePosX(0, 1, 1, GL_RGBA, GL_UNSIGNED_BYTE, 1, color);
3694 incompleteCube->setImageNegX(0, 1, 1, GL_RGBA, GL_UNSIGNED_BYTE, 1, color);
3695 incompleteCube->setImagePosY(0, 1, 1, GL_RGBA, GL_UNSIGNED_BYTE, 1, color);
3696 incompleteCube->setImageNegY(0, 1, 1, GL_RGBA, GL_UNSIGNED_BYTE, 1, color);
3697 incompleteCube->setImagePosZ(0, 1, 1, GL_RGBA, GL_UNSIGNED_BYTE, 1, color);
3698 incompleteCube->setImageNegZ(0, 1, 1, GL_RGBA, GL_UNSIGNED_BYTE, 1, color);
3699
3700 t = incompleteCube;
3701 }
3702 break;
3703 }
3704
3705 mIncompleteTextures[type].set(t);
3706 }
3707
3708 return t;
3709}
3710
3711bool Context::cullSkipsDraw(GLenum drawMode)
3712{
3713 return mState.cullFace && mState.cullMode == GL_FRONT_AND_BACK && isTriangleMode(drawMode);
3714}
3715
3716bool Context::isTriangleMode(GLenum drawMode)
3717{
3718 switch (drawMode)
3719 {
3720 case GL_TRIANGLES:
3721 case GL_TRIANGLE_FAN:
3722 case GL_TRIANGLE_STRIP:
3723 return true;
3724 case GL_POINTS:
3725 case GL_LINES:
3726 case GL_LINE_LOOP:
3727 case GL_LINE_STRIP:
3728 return false;
3729 default: UNREACHABLE();
3730 }
3731
3732 return false;
3733}
3734
3735void Context::setVertexAttrib(GLuint index, const GLfloat *values)
3736{
3737 ASSERT(index < gl::MAX_VERTEX_ATTRIBS);
3738
3739 mState.vertexAttribute[index].mCurrentValue[0] = values[0];
3740 mState.vertexAttribute[index].mCurrentValue[1] = values[1];
3741 mState.vertexAttribute[index].mCurrentValue[2] = values[2];
3742 mState.vertexAttribute[index].mCurrentValue[3] = values[3];
3743
3744 mVertexDataManager->dirtyCurrentValue(index);
3745}
3746
3747void Context::setVertexAttribDivisor(GLuint index, GLuint divisor)
3748{
3749 ASSERT(index < gl::MAX_VERTEX_ATTRIBS);
3750
3751 mState.vertexAttribute[index].mDivisor = divisor;
3752}
3753
3754// keep list sorted in following order
3755// OES extensions
3756// EXT extensions
3757// Vendor extensions
3758void Context::initExtensionString()
3759{
3760 mExtensionString = "";
3761
3762 // OES extensions
3763 if (supports32bitIndices())
3764 {
3765 mExtensionString += "GL_OES_element_index_uint ";
3766 }
3767
3768 mExtensionString += "GL_OES_packed_depth_stencil ";
3769 mExtensionString += "GL_OES_get_program_binary ";
3770 mExtensionString += "GL_OES_rgb8_rgba8 ";
3771 mExtensionString += "GL_OES_standard_derivatives ";
3772
3773 if (supportsFloat16Textures())
3774 {
3775 mExtensionString += "GL_OES_texture_half_float ";
3776 }
3777 if (supportsFloat16LinearFilter())
3778 {
3779 mExtensionString += "GL_OES_texture_half_float_linear ";
3780 }
3781 if (supportsFloat32Textures())
3782 {
3783 mExtensionString += "GL_OES_texture_float ";
3784 }
3785 if (supportsFloat32LinearFilter())
3786 {
3787 mExtensionString += "GL_OES_texture_float_linear ";
3788 }
3789
3790 if (supportsNonPower2Texture())
3791 {
3792 mExtensionString += "GL_OES_texture_npot ";
3793 }
3794
3795 // Multi-vendor (EXT) extensions
3796 if (supportsOcclusionQueries())
3797 {
3798 mExtensionString += "GL_EXT_occlusion_query_boolean ";
3799 }
3800
3801 mExtensionString += "GL_EXT_read_format_bgra ";
3802 mExtensionString += "GL_EXT_robustness ";
3803
3804 if (supportsDXT1Textures())
3805 {
3806 mExtensionString += "GL_EXT_texture_compression_dxt1 ";
3807 }
3808
daniel@transgaming.com07ab8412012-07-12 15:17:09 +00003809 if (supportsTextureFilterAnisotropy())
3810 {
3811 mExtensionString += "GL_EXT_texture_filter_anisotropic ";
3812 }
3813
apatrick@chromium.org144f2802012-07-12 01:42:34 +00003814 mExtensionString += "GL_EXT_texture_format_BGRA8888 ";
3815 mExtensionString += "GL_EXT_texture_storage ";
3816
3817 // ANGLE-specific extensions
3818 if (supportsDepthTextures())
3819 {
3820 mExtensionString += "GL_ANGLE_depth_texture ";
3821 }
3822
3823 mExtensionString += "GL_ANGLE_framebuffer_blit ";
3824 if (getMaxSupportedSamples() != 0)
3825 {
3826 mExtensionString += "GL_ANGLE_framebuffer_multisample ";
3827 }
3828
3829 if (supportsInstancing())
3830 {
3831 mExtensionString += "GL_ANGLE_instanced_arrays ";
3832 }
3833
3834 mExtensionString += "GL_ANGLE_pack_reverse_row_order ";
3835
3836 if (supportsDXT3Textures())
3837 {
3838 mExtensionString += "GL_ANGLE_texture_compression_dxt3 ";
3839 }
3840 if (supportsDXT5Textures())
3841 {
3842 mExtensionString += "GL_ANGLE_texture_compression_dxt5 ";
3843 }
3844
3845 mExtensionString += "GL_ANGLE_texture_usage ";
3846 mExtensionString += "GL_ANGLE_translated_shader_source ";
3847
3848 // Other vendor-specific extensions
3849 if (supportsEventQueries())
3850 {
3851 mExtensionString += "GL_NV_fence ";
3852 }
3853
3854 std::string::size_type end = mExtensionString.find_last_not_of(' ');
3855 if (end != std::string::npos)
3856 {
3857 mExtensionString.resize(end+1);
3858 }
3859}
3860
3861const char *Context::getExtensionString() const
3862{
3863 return mExtensionString.c_str();
3864}
3865
3866void Context::initRendererString()
3867{
3868 D3DADAPTER_IDENTIFIER9 *identifier = mDisplay->getAdapterIdentifier();
3869
3870 mRendererString = "ANGLE (";
3871 mRendererString += identifier->Description;
3872 mRendererString += ")";
3873}
3874
3875const char *Context::getRendererString() const
3876{
3877 return mRendererString.c_str();
3878}
3879
3880void Context::blitFramebuffer(GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1,
3881 GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1,
3882 GLbitfield mask)
3883{
3884 Framebuffer *readFramebuffer = getReadFramebuffer();
3885 Framebuffer *drawFramebuffer = getDrawFramebuffer();
3886
3887 if (!readFramebuffer || readFramebuffer->completeness() != GL_FRAMEBUFFER_COMPLETE ||
3888 !drawFramebuffer || drawFramebuffer->completeness() != GL_FRAMEBUFFER_COMPLETE)
3889 {
3890 return error(GL_INVALID_FRAMEBUFFER_OPERATION);
3891 }
3892
3893 if (drawFramebuffer->getSamples() != 0)
3894 {
3895 return error(GL_INVALID_OPERATION);
3896 }
3897
3898 int readBufferWidth = readFramebuffer->getColorbuffer()->getWidth();
3899 int readBufferHeight = readFramebuffer->getColorbuffer()->getHeight();
3900 int drawBufferWidth = drawFramebuffer->getColorbuffer()->getWidth();
3901 int drawBufferHeight = drawFramebuffer->getColorbuffer()->getHeight();
3902
3903 RECT sourceRect;
3904 RECT destRect;
3905
3906 if (srcX0 < srcX1)
3907 {
3908 sourceRect.left = srcX0;
3909 sourceRect.right = srcX1;
3910 destRect.left = dstX0;
3911 destRect.right = dstX1;
3912 }
3913 else
3914 {
3915 sourceRect.left = srcX1;
3916 destRect.left = dstX1;
3917 sourceRect.right = srcX0;
3918 destRect.right = dstX0;
3919 }
3920
3921 if (srcY0 < srcY1)
3922 {
3923 sourceRect.bottom = srcY1;
3924 destRect.bottom = dstY1;
3925 sourceRect.top = srcY0;
3926 destRect.top = dstY0;
3927 }
3928 else
3929 {
3930 sourceRect.bottom = srcY0;
3931 destRect.bottom = dstY0;
3932 sourceRect.top = srcY1;
3933 destRect.top = dstY1;
3934 }
3935
3936 RECT sourceScissoredRect = sourceRect;
3937 RECT destScissoredRect = destRect;
3938
3939 if (mState.scissorTest)
3940 {
3941 // Only write to parts of the destination framebuffer which pass the scissor test
3942 // Please note: the destRect is now in D3D-style coordinates, so the *top* of the
3943 // rect will be checked against scissorY, rather than the bottom.
3944 if (destRect.left < mState.scissorX)
3945 {
3946 int xDiff = mState.scissorX - destRect.left;
3947 destScissoredRect.left = mState.scissorX;
3948 sourceScissoredRect.left += xDiff;
3949 }
3950
3951 if (destRect.right > mState.scissorX + mState.scissorWidth)
3952 {
3953 int xDiff = destRect.right - (mState.scissorX + mState.scissorWidth);
3954 destScissoredRect.right = mState.scissorX + mState.scissorWidth;
3955 sourceScissoredRect.right -= xDiff;
3956 }
3957
3958 if (destRect.top < mState.scissorY)
3959 {
3960 int yDiff = mState.scissorY - destRect.top;
3961 destScissoredRect.top = mState.scissorY;
3962 sourceScissoredRect.top += yDiff;
3963 }
3964
3965 if (destRect.bottom > mState.scissorY + mState.scissorHeight)
3966 {
3967 int yDiff = destRect.bottom - (mState.scissorY + mState.scissorHeight);
3968 destScissoredRect.bottom = mState.scissorY + mState.scissorHeight;
3969 sourceScissoredRect.bottom -= yDiff;
3970 }
3971 }
3972
3973 bool blitRenderTarget = false;
3974 bool blitDepthStencil = false;
3975
3976 RECT sourceTrimmedRect = sourceScissoredRect;
3977 RECT destTrimmedRect = destScissoredRect;
3978
3979 // The source & destination rectangles also may need to be trimmed if they fall out of the bounds of
3980 // the actual draw and read surfaces.
3981 if (sourceTrimmedRect.left < 0)
3982 {
3983 int xDiff = 0 - sourceTrimmedRect.left;
3984 sourceTrimmedRect.left = 0;
3985 destTrimmedRect.left += xDiff;
3986 }
3987
3988 if (sourceTrimmedRect.right > readBufferWidth)
3989 {
3990 int xDiff = sourceTrimmedRect.right - readBufferWidth;
3991 sourceTrimmedRect.right = readBufferWidth;
3992 destTrimmedRect.right -= xDiff;
3993 }
3994
3995 if (sourceTrimmedRect.top < 0)
3996 {
3997 int yDiff = 0 - sourceTrimmedRect.top;
3998 sourceTrimmedRect.top = 0;
3999 destTrimmedRect.top += yDiff;
4000 }
4001
4002 if (sourceTrimmedRect.bottom > readBufferHeight)
4003 {
4004 int yDiff = sourceTrimmedRect.bottom - readBufferHeight;
4005 sourceTrimmedRect.bottom = readBufferHeight;
4006 destTrimmedRect.bottom -= yDiff;
4007 }
4008
4009 if (destTrimmedRect.left < 0)
4010 {
4011 int xDiff = 0 - destTrimmedRect.left;
4012 destTrimmedRect.left = 0;
4013 sourceTrimmedRect.left += xDiff;
4014 }
4015
4016 if (destTrimmedRect.right > drawBufferWidth)
4017 {
4018 int xDiff = destTrimmedRect.right - drawBufferWidth;
4019 destTrimmedRect.right = drawBufferWidth;
4020 sourceTrimmedRect.right -= xDiff;
4021 }
4022
4023 if (destTrimmedRect.top < 0)
4024 {
4025 int yDiff = 0 - destTrimmedRect.top;
4026 destTrimmedRect.top = 0;
4027 sourceTrimmedRect.top += yDiff;
4028 }
4029
4030 if (destTrimmedRect.bottom > drawBufferHeight)
4031 {
4032 int yDiff = destTrimmedRect.bottom - drawBufferHeight;
4033 destTrimmedRect.bottom = drawBufferHeight;
4034 sourceTrimmedRect.bottom -= yDiff;
4035 }
4036
4037 bool partialBufferCopy = false;
4038 if (sourceTrimmedRect.bottom - sourceTrimmedRect.top < readBufferHeight ||
4039 sourceTrimmedRect.right - sourceTrimmedRect.left < readBufferWidth ||
4040 destTrimmedRect.bottom - destTrimmedRect.top < drawBufferHeight ||
4041 destTrimmedRect.right - destTrimmedRect.left < drawBufferWidth ||
4042 sourceTrimmedRect.top != 0 || destTrimmedRect.top != 0 || sourceTrimmedRect.left != 0 || destTrimmedRect.left != 0)
4043 {
4044 partialBufferCopy = true;
4045 }
4046
4047 if (mask & GL_COLOR_BUFFER_BIT)
4048 {
4049 const bool validReadType = readFramebuffer->getColorbufferType() == GL_TEXTURE_2D ||
4050 readFramebuffer->getColorbufferType() == GL_RENDERBUFFER;
4051 const bool validDrawType = drawFramebuffer->getColorbufferType() == GL_TEXTURE_2D ||
4052 drawFramebuffer->getColorbufferType() == GL_RENDERBUFFER;
4053 if (!validReadType || !validDrawType ||
4054 readFramebuffer->getColorbuffer()->getD3DFormat() != drawFramebuffer->getColorbuffer()->getD3DFormat())
4055 {
4056 ERR("Color buffer format conversion in BlitFramebufferANGLE not supported by this implementation");
4057 return error(GL_INVALID_OPERATION);
4058 }
4059
4060 if (partialBufferCopy && readFramebuffer->getSamples() != 0)
4061 {
4062 return error(GL_INVALID_OPERATION);
4063 }
4064
4065 blitRenderTarget = true;
4066
4067 }
4068
4069 if (mask & (GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT))
4070 {
4071 Renderbuffer *readDSBuffer = NULL;
4072 Renderbuffer *drawDSBuffer = NULL;
4073
4074 // We support OES_packed_depth_stencil, and do not support a separately attached depth and stencil buffer, so if we have
4075 // both a depth and stencil buffer, it will be the same buffer.
4076
4077 if (mask & GL_DEPTH_BUFFER_BIT)
4078 {
4079 if (readFramebuffer->getDepthbuffer() && drawFramebuffer->getDepthbuffer())
4080 {
4081 if (readFramebuffer->getDepthbufferType() != drawFramebuffer->getDepthbufferType() ||
4082 readFramebuffer->getDepthbuffer()->getD3DFormat() != drawFramebuffer->getDepthbuffer()->getD3DFormat())
4083 {
4084 return error(GL_INVALID_OPERATION);
4085 }
4086
4087 blitDepthStencil = true;
4088 readDSBuffer = readFramebuffer->getDepthbuffer();
4089 drawDSBuffer = drawFramebuffer->getDepthbuffer();
4090 }
4091 }
4092
4093 if (mask & GL_STENCIL_BUFFER_BIT)
4094 {
4095 if (readFramebuffer->getStencilbuffer() && drawFramebuffer->getStencilbuffer())
4096 {
4097 if (readFramebuffer->getStencilbufferType() != drawFramebuffer->getStencilbufferType() ||
4098 readFramebuffer->getStencilbuffer()->getD3DFormat() != drawFramebuffer->getStencilbuffer()->getD3DFormat())
4099 {
4100 return error(GL_INVALID_OPERATION);
4101 }
4102
4103 blitDepthStencil = true;
4104 readDSBuffer = readFramebuffer->getStencilbuffer();
4105 drawDSBuffer = drawFramebuffer->getStencilbuffer();
4106 }
4107 }
4108
4109 if (partialBufferCopy)
4110 {
4111 ERR("Only whole-buffer depth and stencil blits are supported by this implementation.");
4112 return error(GL_INVALID_OPERATION); // only whole-buffer copies are permitted
4113 }
4114
4115 if ((drawDSBuffer && drawDSBuffer->getSamples() != 0) ||
4116 (readDSBuffer && readDSBuffer->getSamples() != 0))
4117 {
4118 return error(GL_INVALID_OPERATION);
4119 }
4120 }
4121
4122 if (blitRenderTarget || blitDepthStencil)
4123 {
4124 mDisplay->endScene();
4125
4126 if (blitRenderTarget)
4127 {
4128 IDirect3DSurface9* readRenderTarget = readFramebuffer->getRenderTarget();
4129 IDirect3DSurface9* drawRenderTarget = drawFramebuffer->getRenderTarget();
4130
4131 HRESULT result = mDevice->StretchRect(readRenderTarget, &sourceTrimmedRect,
4132 drawRenderTarget, &destTrimmedRect, D3DTEXF_NONE);
4133
4134 readRenderTarget->Release();
4135 drawRenderTarget->Release();
4136
4137 if (FAILED(result))
4138 {
4139 ERR("BlitFramebufferANGLE failed: StretchRect returned %x.", result);
4140 return;
4141 }
4142 }
4143
4144 if (blitDepthStencil)
4145 {
4146 IDirect3DSurface9* readDepthStencil = readFramebuffer->getDepthStencil();
4147 IDirect3DSurface9* drawDepthStencil = drawFramebuffer->getDepthStencil();
4148
4149 HRESULT result = mDevice->StretchRect(readDepthStencil, NULL, drawDepthStencil, NULL, D3DTEXF_NONE);
4150
4151 readDepthStencil->Release();
4152 drawDepthStencil->Release();
4153
4154 if (FAILED(result))
4155 {
4156 ERR("BlitFramebufferANGLE failed: StretchRect returned %x.", result);
4157 return;
4158 }
4159 }
4160 }
4161}
4162
4163VertexDeclarationCache::VertexDeclarationCache() : mMaxLru(0)
4164{
4165 for (int i = 0; i < NUM_VERTEX_DECL_CACHE_ENTRIES; i++)
4166 {
4167 mVertexDeclCache[i].vertexDeclaration = NULL;
4168 mVertexDeclCache[i].lruCount = 0;
4169 }
4170}
4171
4172VertexDeclarationCache::~VertexDeclarationCache()
4173{
4174 for (int i = 0; i < NUM_VERTEX_DECL_CACHE_ENTRIES; i++)
4175 {
4176 if (mVertexDeclCache[i].vertexDeclaration)
4177 {
4178 mVertexDeclCache[i].vertexDeclaration->Release();
4179 }
4180 }
4181}
4182
4183GLenum VertexDeclarationCache::applyDeclaration(IDirect3DDevice9 *device, TranslatedAttribute attributes[], Program *program, GLsizei instances, GLsizei *repeatDraw)
4184{
4185 *repeatDraw = 1;
4186
4187 int indexedAttribute = MAX_VERTEX_ATTRIBS;
4188 int instancedAttribute = MAX_VERTEX_ATTRIBS;
4189
4190 if (instances > 0)
4191 {
4192 // Find an indexed attribute to be mapped to D3D stream 0
4193 for (int i = 0; i < MAX_VERTEX_ATTRIBS; i++)
4194 {
4195 if (attributes[i].active)
4196 {
4197 if (indexedAttribute == MAX_VERTEX_ATTRIBS)
4198 {
4199 if (attributes[i].divisor == 0)
4200 {
4201 indexedAttribute = i;
4202 }
4203 }
4204 else if (instancedAttribute == MAX_VERTEX_ATTRIBS)
4205 {
4206 if (attributes[i].divisor != 0)
4207 {
4208 instancedAttribute = i;
4209 }
4210 }
4211 else break; // Found both an indexed and instanced attribute
4212 }
4213 }
4214
4215 if (indexedAttribute == MAX_VERTEX_ATTRIBS)
4216 {
4217 return GL_INVALID_OPERATION;
4218 }
4219 }
4220
4221 D3DVERTEXELEMENT9 elements[MAX_VERTEX_ATTRIBS + 1];
4222 D3DVERTEXELEMENT9 *element = &elements[0];
4223
4224 ProgramBinary *programBinary = program->getProgramBinary();
4225
4226 for (int i = 0; i < MAX_VERTEX_ATTRIBS; i++)
4227 {
4228 if (attributes[i].active)
4229 {
4230 int stream = i;
4231
4232 if (instances > 0)
4233 {
4234 // Due to a bug on ATI cards we can't enable instancing when none of the attributes are instanced.
4235 if (instancedAttribute == MAX_VERTEX_ATTRIBS)
4236 {
4237 *repeatDraw = instances;
4238 }
4239 else
4240 {
4241 if (i == indexedAttribute)
4242 {
4243 stream = 0;
4244 }
4245 else if (i == 0)
4246 {
4247 stream = indexedAttribute;
4248 }
4249
4250 UINT frequency = 1;
4251
4252 if (attributes[i].divisor == 0)
4253 {
4254 frequency = D3DSTREAMSOURCE_INDEXEDDATA | instances;
4255 }
4256 else
4257 {
4258 frequency = D3DSTREAMSOURCE_INSTANCEDATA | attributes[i].divisor;
4259 }
4260
4261 device->SetStreamSourceFreq(stream, frequency);
4262 mInstancingEnabled = true;
4263 }
4264 }
4265
4266 if (mAppliedVBs[stream].serial != attributes[i].serial ||
4267 mAppliedVBs[stream].stride != attributes[i].stride ||
4268 mAppliedVBs[stream].offset != attributes[i].offset)
4269 {
4270 device->SetStreamSource(stream, attributes[i].vertexBuffer, attributes[i].offset, attributes[i].stride);
4271 mAppliedVBs[stream].serial = attributes[i].serial;
4272 mAppliedVBs[stream].stride = attributes[i].stride;
4273 mAppliedVBs[stream].offset = attributes[i].offset;
4274 }
4275
4276 element->Stream = stream;
4277 element->Offset = 0;
4278 element->Type = attributes[i].type;
4279 element->Method = D3DDECLMETHOD_DEFAULT;
4280 element->Usage = D3DDECLUSAGE_TEXCOORD;
4281 element->UsageIndex = programBinary->getSemanticIndex(i);
4282 element++;
4283 }
4284 }
4285
4286 if (instances == 0 || instancedAttribute == MAX_VERTEX_ATTRIBS)
4287 {
4288 if (mInstancingEnabled)
4289 {
4290 for (int i = 0; i < MAX_VERTEX_ATTRIBS; i++)
4291 {
4292 device->SetStreamSourceFreq(i, 1);
4293 }
4294
4295 mInstancingEnabled = false;
4296 }
4297 }
4298
4299 static const D3DVERTEXELEMENT9 end = D3DDECL_END();
4300 *(element++) = end;
4301
4302 for (int i = 0; i < NUM_VERTEX_DECL_CACHE_ENTRIES; i++)
4303 {
4304 VertexDeclCacheEntry *entry = &mVertexDeclCache[i];
4305 if (memcmp(entry->cachedElements, elements, (element - elements) * sizeof(D3DVERTEXELEMENT9)) == 0 && entry->vertexDeclaration)
4306 {
4307 entry->lruCount = ++mMaxLru;
4308 if(entry->vertexDeclaration != mLastSetVDecl)
4309 {
4310 device->SetVertexDeclaration(entry->vertexDeclaration);
4311 mLastSetVDecl = entry->vertexDeclaration;
4312 }
4313
4314 return GL_NO_ERROR;
4315 }
4316 }
4317
4318 VertexDeclCacheEntry *lastCache = mVertexDeclCache;
4319
4320 for (int i = 0; i < NUM_VERTEX_DECL_CACHE_ENTRIES; i++)
4321 {
4322 if (mVertexDeclCache[i].lruCount < lastCache->lruCount)
4323 {
4324 lastCache = &mVertexDeclCache[i];
4325 }
4326 }
4327
4328 if (lastCache->vertexDeclaration != NULL)
4329 {
4330 lastCache->vertexDeclaration->Release();
4331 lastCache->vertexDeclaration = NULL;
4332 // mLastSetVDecl is set to the replacement, so we don't have to worry
4333 // about it.
4334 }
4335
4336 memcpy(lastCache->cachedElements, elements, (element - elements) * sizeof(D3DVERTEXELEMENT9));
4337 device->CreateVertexDeclaration(elements, &lastCache->vertexDeclaration);
4338 device->SetVertexDeclaration(lastCache->vertexDeclaration);
4339 mLastSetVDecl = lastCache->vertexDeclaration;
4340 lastCache->lruCount = ++mMaxLru;
4341
4342 return GL_NO_ERROR;
4343}
4344
4345void VertexDeclarationCache::markStateDirty()
4346{
4347 for (int i = 0; i < MAX_VERTEX_ATTRIBS; i++)
4348 {
4349 mAppliedVBs[i].serial = 0;
4350 }
4351
4352 mLastSetVDecl = NULL;
4353 mInstancingEnabled = true; // Forces it to be disabled when not used
4354}
4355
4356}
4357
4358extern "C"
4359{
4360gl::Context *glCreateContext(const egl::Config *config, const gl::Context *shareContext, bool notifyResets, bool robustAccess)
4361{
4362 return new gl::Context(config, shareContext, notifyResets, robustAccess);
4363}
4364
4365void glDestroyContext(gl::Context *context)
4366{
4367 delete context;
4368
4369 if (context == gl::getContext())
4370 {
4371 gl::makeCurrent(NULL, NULL, NULL);
4372 }
4373}
4374
4375void glMakeCurrent(gl::Context *context, egl::Display *display, egl::Surface *surface)
4376{
4377 gl::makeCurrent(context, display, surface);
4378}
4379
4380gl::Context *glGetCurrentContext()
4381{
4382 return gl::getContext();
4383}
4384}