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