2 // Copyright (c) 2002-2010 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.
7 // Surface.cpp: Implements the egl::Surface class, representing a drawing surface
8 // such as the client area of a window, including any back buffers.
9 // Implements EGLSurface and related functionality. [EGL 1.4] section 2.2 page 3.
13 #include "libEGL/Surface.h"
15 #include "common/debug.h"
16 #include "libGLESv2/Texture.h"
18 #include "libEGL/main.h"
19 #include "libEGL/Display.h"
26 Surface::Surface(Display *display, const Config *config, HWND window, EGLint postSubBufferSupported)
27 : mDisplay(display), mConfig(config), mWindow(window), mPostSubBufferSupported(postSubBufferSupported)
33 mOffscreenTexture = NULL;
36 mTextureFormat = EGL_NO_TEXTURE;
37 mTextureTarget = EGL_NO_TEXTURE;
39 mPixelAspectRatio = (EGLint)(1.0 * EGL_DISPLAY_SCALING); // FIXME: Determine actual pixel aspect ratio
40 mRenderBuffer = EGL_BACK_BUFFER;
41 mSwapBehavior = EGL_BUFFER_PRESERVED;
48 Surface::Surface(Display *display, const Config *config, HANDLE shareHandle, EGLint width, EGLint height, EGLenum textureFormat, EGLenum textureType)
49 : mDisplay(display), mWindow(NULL), mConfig(config), mShareHandle(shareHandle), mWidth(width), mHeight(height), mPostSubBufferSupported(EGL_FALSE)
55 mOffscreenTexture = NULL;
56 mWindowSubclassed = false;
58 mTextureFormat = textureFormat;
59 mTextureTarget = textureType;
61 mPixelAspectRatio = (EGLint)(1.0 * EGL_DISPLAY_SCALING); // FIXME: Determine actual pixel aspect ratio
62 mRenderBuffer = EGL_BACK_BUFFER;
63 mSwapBehavior = EGL_BUFFER_PRESERVED;
74 bool Surface::initialize()
76 ASSERT(!mSwapChain && !mOffscreenTexture && !mDepthStencil);
78 if (!resetSwapChain())
81 // Modify present parameters for this window, if we are composited,
82 // to minimize the amount of queuing done by DWM between our calls to
83 // present and the actual screen.
84 if (mWindow && (getComparableOSVersion() >= versionWindowsVista)) {
86 HRESULT result = DwmIsCompositionEnabled(&isComposited);
87 if (SUCCEEDED(result) && isComposited) {
88 DWM_PRESENT_PARAMETERS presentParams;
89 memset(&presentParams, 0, sizeof(presentParams));
90 presentParams.cbSize = sizeof(DWM_PRESENT_PARAMETERS);
91 presentParams.cBuffer = 2;
93 result = DwmSetPresentParameters(mWindow, &presentParams);
95 ERR("Unable to set present parameters: 0x%08X", result);
102 void Surface::release()
106 mSwapChain->Release();
112 mBackBuffer->Release();
118 mDepthStencil->Release();
119 mDepthStencil = NULL;
124 mRenderTarget->Release();
125 mRenderTarget = NULL;
128 if (mOffscreenTexture)
130 mOffscreenTexture->Release();
131 mOffscreenTexture = NULL;
136 mTexture->releaseTexImage();
143 bool Surface::resetSwapChain()
147 return resetSwapChain(mWidth, mHeight);
151 if (!GetClientRect(getWindowHandle(), &windowRect))
155 ERR("Could not retrieve the window dimensions");
159 return resetSwapChain(windowRect.right - windowRect.left, windowRect.bottom - windowRect.top);
162 bool Surface::resetSwapChain(int backbufferWidth, int backbufferHeight)
164 IDirect3DDevice9 *device = mDisplay->getDevice();
171 // Evict all non-render target textures to system memory and release all resources
172 // before reallocating them to free up as much video memory as possible.
173 device->EvictManagedResources();
177 // Release specific resources to free up memory for the new render target, while the
178 // old render target still exists for the purpose of preserving its contents.
181 mSwapChain->Release();
187 mBackBuffer->Release();
191 if (mOffscreenTexture)
193 mOffscreenTexture->Release();
194 mOffscreenTexture = NULL;
199 mDepthStencil->Release();
200 mDepthStencil = NULL;
204 HANDLE *pShareHandle = NULL;
205 if (!mWindow && mDisplay->shareHandleSupported())
207 pShareHandle = &mShareHandle;
210 result = device->CreateTexture(backbufferWidth, backbufferHeight, 1, D3DUSAGE_RENDERTARGET,
211 mConfig->mRenderTargetFormat, D3DPOOL_DEFAULT, &mOffscreenTexture, pShareHandle);
214 ERR("Could not create offscreen texture: %08lX", result);
217 if(isDeviceLostError(result))
219 mDisplay->notifyDeviceLost();
224 return error(EGL_BAD_ALLOC, false);
228 IDirect3DSurface9 *oldRenderTarget = mRenderTarget;
230 result = mOffscreenTexture->GetSurfaceLevel(0, &mRenderTarget);
231 ASSERT(SUCCEEDED(result));
241 if (rect.right > static_cast<LONG>(backbufferWidth))
243 rect.right = backbufferWidth;
246 if (rect.bottom > static_cast<LONG>(backbufferHeight))
248 rect.bottom = backbufferHeight;
251 mDisplay->endScene();
253 result = device->StretchRect(oldRenderTarget, &rect, mRenderTarget, &rect, D3DTEXF_NONE);
254 ASSERT(SUCCEEDED(result));
256 oldRenderTarget->Release();
261 D3DPRESENT_PARAMETERS presentParameters = {0};
262 presentParameters.AutoDepthStencilFormat = mConfig->mDepthStencilFormat;
263 presentParameters.BackBufferCount = 1;
264 presentParameters.BackBufferFormat = mConfig->mRenderTargetFormat;
265 presentParameters.EnableAutoDepthStencil = FALSE;
266 presentParameters.Flags = 0;
267 presentParameters.hDeviceWindow = getWindowHandle();
268 presentParameters.MultiSampleQuality = 0; // FIXME: Unimplemented
269 presentParameters.MultiSampleType = D3DMULTISAMPLE_NONE; // FIXME: Unimplemented
270 presentParameters.PresentationInterval = mPresentInterval;
271 presentParameters.SwapEffect = D3DSWAPEFFECT_DISCARD;
272 presentParameters.Windowed = TRUE;
273 presentParameters.BackBufferWidth = backbufferWidth;
274 presentParameters.BackBufferHeight = backbufferHeight;
276 // http://crbug.com/140239
277 // http://crbug.com/143434
279 // Some AMD/Intel switchable systems / drivers appear to round swap chain surfaces to a multiple of 64 pixels in width
280 // when using the integrated Intel. This rounds the width up rather than down.
282 // Some non-switchable AMD GPUs / drivers do not respect the source rectangle to Present. Therefore, when the vendor ID
283 // is not Intel, the back buffer width must be exactly the same width as the window or horizontal scaling will occur.
284 D3DADAPTER_IDENTIFIER9* adapterIdentifier = mDisplay->getAdapterIdentifier();
285 if (adapterIdentifier->VendorId == VENDOR_ID_INTEL)
287 presentParameters.BackBufferWidth = (presentParameters.BackBufferWidth + 63) / 64 * 64;
290 result = device->CreateAdditionalSwapChain(&presentParameters, &mSwapChain);
294 ASSERT(result == D3DERR_OUTOFVIDEOMEMORY || result == E_OUTOFMEMORY || result == D3DERR_INVALIDCALL || result == D3DERR_DEVICELOST);
296 ERR("Could not create additional swap chains or offscreen surfaces: %08lX", result);
299 if(isDeviceLostError(result))
301 mDisplay->notifyDeviceLost();
306 return error(EGL_BAD_ALLOC, false);
310 result = mSwapChain->GetBackBuffer(0, D3DBACKBUFFER_TYPE_MONO, &mBackBuffer);
311 ASSERT(SUCCEEDED(result));
314 if (mConfig->mDepthStencilFormat != D3DFMT_UNKNOWN)
316 result = device->CreateDepthStencilSurface(backbufferWidth, backbufferHeight, mConfig->mDepthStencilFormat, D3DMULTISAMPLE_NONE,
317 0, FALSE, &mDepthStencil, NULL);
321 ASSERT(result == D3DERR_OUTOFVIDEOMEMORY || result == E_OUTOFMEMORY || result == D3DERR_INVALIDCALL);
323 ERR("Could not create depthstencil surface for new swap chain: 0x%08X", result);
326 if(isDeviceLostError(result))
328 mDisplay->notifyDeviceLost();
333 return error(EGL_BAD_ALLOC, false);
338 mWidth = backbufferWidth;
339 mHeight = backbufferHeight;
341 mPresentIntervalDirty = false;
345 bool Surface::swapRect(EGLint x, EGLint y, EGLint width, EGLint height)
352 if (x + width > mWidth)
357 if (y + height > mHeight)
359 height = mHeight - y;
362 if (width == 0 || height == 0)
367 IDirect3DDevice9 *device = mDisplay->getDevice();
369 // Disable all pipeline operations
370 device->SetRenderState(D3DRS_ZENABLE, D3DZB_FALSE);
371 device->SetRenderState(D3DRS_FILLMODE, D3DFILL_SOLID);
372 device->SetRenderState(D3DRS_ALPHATESTENABLE, FALSE);
373 device->SetRenderState(D3DRS_ALPHABLENDENABLE, FALSE);
374 device->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE);
375 device->SetRenderState(D3DRS_STENCILENABLE, FALSE);
376 device->SetRenderState(D3DRS_CLIPPLANEENABLE, 0);
377 device->SetRenderState(D3DRS_COLORWRITEENABLE, D3DCOLORWRITEENABLE_ALPHA | D3DCOLORWRITEENABLE_BLUE | D3DCOLORWRITEENABLE_GREEN | D3DCOLORWRITEENABLE_RED);
378 device->SetRenderState(D3DRS_SRGBWRITEENABLE, FALSE);
379 device->SetRenderState(D3DRS_SCISSORTESTENABLE, FALSE);
380 device->SetPixelShader(NULL);
381 device->SetVertexShader(NULL);
383 device->SetRenderTarget(0, mBackBuffer);
384 device->SetDepthStencilSurface(NULL);
386 device->SetTexture(0, mOffscreenTexture);
387 device->SetTextureStageState(0, D3DTSS_COLOROP, D3DTOP_SELECTARG1);
388 device->SetTextureStageState(0, D3DTSS_COLORARG1, D3DTA_TEXTURE);
389 device->SetTextureStageState(1, D3DTSS_COLOROP, D3DTOP_DISABLE);
390 device->SetSamplerState(0, D3DSAMP_MAGFILTER, D3DTEXF_POINT);
391 device->SetSamplerState(0, D3DSAMP_MINFILTER, D3DTEXF_POINT);
392 device->SetSamplerState(0, D3DSAMP_ADDRESSU, D3DTADDRESS_CLAMP);
393 device->SetSamplerState(0, D3DSAMP_ADDRESSV, D3DTADDRESS_CLAMP);
394 device->SetFVF(D3DFVF_XYZRHW | D3DFVF_TEX1);
396 D3DVIEWPORT9 viewport = {0, 0, mWidth, mHeight, 0.0f, 1.0f};
397 device->SetViewport(&viewport);
400 float y1 = (mHeight - y - height) - 0.5f;
401 float x2 = (x + width) - 0.5f;
402 float y2 = (mHeight - y) - 0.5f;
404 float u1 = x / float(mWidth);
405 float v1 = y / float(mHeight);
406 float u2 = (x + width) / float(mWidth);
407 float v2 = (y + height) / float(mHeight);
409 float quad[4][6] = {{x1, y1, 0.0f, 1.0f, u1, v2},
410 {x2, y1, 0.0f, 1.0f, u2, v2},
411 {x2, y2, 0.0f, 1.0f, u2, v1},
412 {x1, y2, 0.0f, 1.0f, u1, v1}}; // x, y, z, rhw, u, v
414 mDisplay->startScene();
415 device->DrawPrimitiveUP(D3DPT_TRIANGLEFAN, 2, quad, 6 * sizeof(float));
416 mDisplay->endScene();
418 device->SetTexture(0, NULL);
422 x, mHeight - y - height,
423 x + width, mHeight - y
426 HRESULT result = mSwapChain->Present(&rect, &rect, NULL, NULL, 0);
428 gl::Context *context = static_cast<gl::Context*>(glGetCurrentContext());
431 context->markAllStateDirty();
434 if (isDeviceLostError(result))
436 mDisplay->notifyDeviceLost();
440 if (result == D3DERR_OUTOFVIDEOMEMORY || result == E_OUTOFMEMORY || result == D3DERR_DRIVERINTERNALERROR)
442 return error(EGL_BAD_ALLOC, false);
445 ASSERT(SUCCEEDED(result));
447 checkForOutOfDateSwapChain();
452 HWND Surface::getWindowHandle()
458 #define kSurfaceProperty _TEXT("Egl::SurfaceOwner")
459 #define kParentWndProc _TEXT("Egl::SurfaceParentWndProc")
461 static LRESULT CALLBACK SurfaceWindowProc(HWND hwnd, UINT message, WPARAM wparam, LPARAM lparam)
463 if (message == WM_SIZE)
465 Surface* surf = reinterpret_cast<Surface*>(GetProp(hwnd, kSurfaceProperty));
468 surf->checkForOutOfDateSwapChain();
471 WNDPROC prevWndFunc = reinterpret_cast<WNDPROC >(GetProp(hwnd, kParentWndProc));
472 return CallWindowProc(prevWndFunc, hwnd, message, wparam, lparam);
475 void Surface::subclassWindow()
483 DWORD threadId = GetWindowThreadProcessId(mWindow, &processId);
484 if (processId != GetCurrentProcessId() || threadId != GetCurrentThreadId())
490 LONG_PTR oldWndProc = SetWindowLongPtr(mWindow, GWLP_WNDPROC, reinterpret_cast<LONG_PTR>(SurfaceWindowProc));
491 if(oldWndProc == 0 && GetLastError() != ERROR_SUCCESS)
493 mWindowSubclassed = false;
497 SetProp(mWindow, kSurfaceProperty, reinterpret_cast<HANDLE>(this));
498 SetProp(mWindow, kParentWndProc, reinterpret_cast<HANDLE>(oldWndProc));
499 mWindowSubclassed = true;
502 void Surface::unsubclassWindow()
504 if(!mWindowSubclassed)
510 LONG_PTR parentWndFunc = reinterpret_cast<LONG_PTR>(GetProp(mWindow, kParentWndProc));
512 // Check the windowproc is still SurfaceWindowProc.
513 // If this assert fails, then it is likely the application has subclassed the
514 // hwnd as well and did not unsubclass before destroying its EGL context. The
515 // application should be modified to either subclass before initializing the
516 // EGL context, or to unsubclass before destroying the EGL context.
519 LONG_PTR prevWndFunc = SetWindowLongPtr(mWindow, GWLP_WNDPROC, parentWndFunc);
520 ASSERT(prevWndFunc == reinterpret_cast<LONG_PTR>(SurfaceWindowProc));
523 RemoveProp(mWindow, kSurfaceProperty);
524 RemoveProp(mWindow, kParentWndProc);
525 mWindowSubclassed = false;
528 bool Surface::checkForOutOfDateSwapChain()
531 if (!GetClientRect(getWindowHandle(), &client))
537 // Grow the buffer now, if the window has grown. We need to grow now to avoid losing information.
538 int clientWidth = client.right - client.left;
539 int clientHeight = client.bottom - client.top;
540 bool sizeDirty = clientWidth != getWidth() || clientHeight != getHeight();
542 if (sizeDirty || mPresentIntervalDirty)
544 resetSwapChain(clientWidth, clientHeight);
545 if (static_cast<egl::Surface*>(getCurrentDrawSurface()) == this)
547 glMakeCurrent(glGetCurrentContext(), static_cast<egl::Display*>(getCurrentDisplay()), this);
555 DWORD Surface::convertInterval(EGLint interval)
559 case 0: return D3DPRESENT_INTERVAL_IMMEDIATE;
560 case 1: return D3DPRESENT_INTERVAL_ONE;
561 case 2: return D3DPRESENT_INTERVAL_TWO;
562 case 3: return D3DPRESENT_INTERVAL_THREE;
563 case 4: return D3DPRESENT_INTERVAL_FOUR;
564 default: UNREACHABLE();
567 return D3DPRESENT_INTERVAL_DEFAULT;
572 return swapRect(0, 0, mWidth, mHeight);
575 bool Surface::postSubBuffer(EGLint x, EGLint y, EGLint width, EGLint height)
577 if (!mPostSubBufferSupported)
579 // Spec is not clear about how this should be handled.
583 return swapRect(x, y, width, height);
586 EGLint Surface::getWidth() const
591 EGLint Surface::getHeight() const
596 EGLint Surface::isPostSubBufferSupported() const
598 return mPostSubBufferSupported;
601 // Increments refcount on surface.
602 // caller must Release() the returned surface
603 IDirect3DSurface9 *Surface::getRenderTarget()
607 mRenderTarget->AddRef();
610 return mRenderTarget;
613 // Increments refcount on surface.
614 // caller must Release() the returned surface
615 IDirect3DSurface9 *Surface::getDepthStencil()
619 mDepthStencil->AddRef();
622 return mDepthStencil;
625 IDirect3DTexture9 *Surface::getOffscreenTexture()
627 if (mOffscreenTexture)
629 mOffscreenTexture->AddRef();
632 return mOffscreenTexture;
635 void Surface::setSwapInterval(EGLint interval)
637 if (mSwapInterval == interval)
642 mSwapInterval = interval;
643 mSwapInterval = std::max(mSwapInterval, mDisplay->getMinSwapInterval());
644 mSwapInterval = std::min(mSwapInterval, mDisplay->getMaxSwapInterval());
646 mPresentInterval = convertInterval(mSwapInterval);
647 mPresentIntervalDirty = true;
650 EGLenum Surface::getTextureFormat() const
652 return mTextureFormat;
655 EGLenum Surface::getTextureTarget() const
657 return mTextureTarget;
660 void Surface::setBoundTexture(gl::Texture2D *texture)
665 gl::Texture2D *Surface::getBoundTexture() const
670 D3DFORMAT Surface::getFormat() const
672 return mConfig->mRenderTargetFormat;