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