CmD3D11RenderWindow.cpp 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751
  1. #include "CmD3D11RenderWindow.h"
  2. #include "CmCoreThread.h"
  3. #include "CmPlatformWndProc.h"
  4. #include "CmD3D11RenderSystem.h"
  5. #include "CmD3D11Device.h"
  6. #include "CmD3D11RenderTexture.h"
  7. #include "CmD3D11TextureView.h"
  8. #include "CmTextureManager.h"
  9. #include "CmD3D11DriverList.h"
  10. #include "CmD3D11Driver.h"
  11. #include "CmInput.h"
  12. #include "CmException.h"
  13. namespace CamelotFramework
  14. {
  15. D3D11RenderWindow::D3D11RenderWindow(const RENDER_WINDOW_DESC& desc,D3D11Device& device, IDXGIFactory* DXGIFactory)
  16. : RenderWindow(desc)
  17. , mDevice(device)
  18. , mDXGIFactory(DXGIFactory)
  19. , mIsExternal(false)
  20. , mSizing(false)
  21. , mClosed(false)
  22. , mSwitchingFullscreen(false)
  23. , mDisplayFrequency(0)
  24. , mRenderTargetView(nullptr)
  25. , mBackBuffer(nullptr)
  26. , mSwapChain(nullptr)
  27. , mHWnd(0)
  28. , mDepthStencilView(nullptr)
  29. {
  30. ZeroMemory(&mSwapChainDesc, sizeof(DXGI_SWAP_CHAIN_DESC));
  31. }
  32. D3D11RenderWindow::~D3D11RenderWindow()
  33. {
  34. }
  35. void D3D11RenderWindow::initialize_internal()
  36. {
  37. mFSAAType.Count = 1;
  38. mFSAAType.Quality = 0;
  39. mFSAA = 0;
  40. mFSAAHint = "";
  41. mVSync = false;
  42. mVSyncInterval = 1;
  43. HWND parentHWnd = 0;
  44. HWND externalHandle = 0;
  45. HMONITOR hMonitor = NULL;
  46. // Get variable-length params
  47. NameValuePairList::const_iterator opt;
  48. // parentWindowHandle -> parentHWnd
  49. opt = mDesc.platformSpecific.find("parentWindowHandle");
  50. if(opt != mDesc.platformSpecific.end())
  51. parentHWnd = (HWND)parseUnsignedInt(opt->second);
  52. // externalWindowHandle -> externalHandle
  53. opt = mDesc.platformSpecific.find("externalWindowHandle");
  54. if(opt != mDesc.platformSpecific.end())
  55. externalHandle = (HWND)parseUnsignedInt(opt->second);
  56. // monitor handle
  57. opt = mDesc.platformSpecific.find("monitorHandle");
  58. if (opt != mDesc.platformSpecific.end())
  59. hMonitor = (HMONITOR)parseInt(opt->second);
  60. mName = mDesc.title;
  61. mIsFullScreen = mDesc.fullscreen;
  62. mColorDepth = mDesc.colorDepth;
  63. mWidth = mHeight = mLeft = mTop = 0;
  64. mActive = true;
  65. mClosed = false;
  66. if (!externalHandle)
  67. {
  68. DWORD dwStyle = (mHidden ? 0 : WS_VISIBLE) | WS_CLIPCHILDREN;
  69. DWORD dwStyleEx = 0;
  70. RECT rc;
  71. MONITORINFO monitorInfo;
  72. // If we specified which adapter we want to use - find it's monitor.
  73. if (mDesc.monitorIndex != -1)
  74. {
  75. RenderSystem* rs = RenderSystem::instancePtr();
  76. D3D11RenderSystem* d3d11rs = static_cast<D3D11RenderSystem*>(rs);
  77. D3D11DriverList* driverList = d3d11rs->getDriverList();
  78. UINT32 curOutput = 0;
  79. for(UINT32 i = 0; i < driverList->count(); i++)
  80. {
  81. D3D11Driver* driver = driverList->item(i);
  82. UINT32 numOutputs = driver->getNumAdapterOutputs();
  83. for(UINT32 j = 0; j < numOutputs; j++)
  84. {
  85. if(curOutput == mDesc.monitorIndex)
  86. {
  87. hMonitor = driver->getOutputDesc(j).Monitor;
  88. break;
  89. }
  90. curOutput++;
  91. }
  92. if(curOutput == mDesc.monitorIndex)
  93. break;
  94. }
  95. }
  96. // If we didn't specified the adapter index, or if it didn't find it
  97. if (hMonitor == NULL)
  98. {
  99. POINT windowAnchorPoint;
  100. // Fill in anchor point.
  101. windowAnchorPoint.x = mDesc.left;
  102. windowAnchorPoint.y = mDesc.top;
  103. // Get the nearest monitor to this window.
  104. hMonitor = MonitorFromPoint(windowAnchorPoint, MONITOR_DEFAULTTOPRIMARY);
  105. }
  106. // Get the target monitor info
  107. memset(&monitorInfo, 0, sizeof(MONITORINFO));
  108. monitorInfo.cbSize = sizeof(MONITORINFO);
  109. GetMonitorInfo(hMonitor, &monitorInfo);
  110. unsigned int winWidth, winHeight;
  111. winWidth = mDesc.width;
  112. winHeight = mDesc.height;
  113. UINT32 left = mDesc.left;
  114. UINT32 top = mDesc.top;
  115. // No specified top left -> Center the window in the middle of the monitor
  116. if (left == -1 || top == -1)
  117. {
  118. int screenw = monitorInfo.rcWork.right - monitorInfo.rcWork.left;
  119. int screenh = monitorInfo.rcWork.bottom - monitorInfo.rcWork.top;
  120. // clamp window dimensions to screen size
  121. int outerw = (int(winWidth) < screenw)? int(winWidth) : screenw;
  122. int outerh = (int(winHeight) < screenh)? int(winHeight) : screenh;
  123. if (left == -1)
  124. left = monitorInfo.rcWork.left + (screenw - outerw) / 2;
  125. else if (mDesc.monitorIndex != -1)
  126. left += monitorInfo.rcWork.left;
  127. if (top == -1)
  128. top = monitorInfo.rcWork.top + (screenh - outerh) / 2;
  129. else if (mDesc.monitorIndex != -1)
  130. top += monitorInfo.rcWork.top;
  131. }
  132. else if (mDesc.monitorIndex != -1)
  133. {
  134. left += monitorInfo.rcWork.left;
  135. top += monitorInfo.rcWork.top;
  136. }
  137. mWidth = mDesc.width;
  138. mHeight = mDesc.height;
  139. mTop = top;
  140. mLeft = left;
  141. if (!mDesc.fullscreen)
  142. {
  143. if (parentHWnd)
  144. {
  145. if(mDesc.toolWindow)
  146. dwStyleEx = WS_EX_TOOLWINDOW;
  147. else
  148. dwStyle |= WS_CHILD;
  149. }
  150. if (!parentHWnd || mDesc.toolWindow)
  151. {
  152. if (mDesc.border == WindowBorder::None)
  153. dwStyle |= WS_POPUP;
  154. else if (mDesc.border == WindowBorder::Fixed)
  155. dwStyle |= WS_OVERLAPPED | WS_BORDER | WS_CAPTION |
  156. WS_SYSMENU | WS_MINIMIZEBOX;
  157. else
  158. dwStyle |= WS_OVERLAPPEDWINDOW;
  159. }
  160. if (!mDesc.outerDimensions)
  161. {
  162. // Calculate window dimensions required
  163. // to get the requested client area
  164. SetRect(&rc, 0, 0, mWidth, mHeight);
  165. AdjustWindowRect(&rc, dwStyle, false);
  166. mWidth = rc.right - rc.left;
  167. mHeight = rc.bottom - rc.top;
  168. // Clamp width and height to the desktop dimensions
  169. int screenw = GetSystemMetrics(SM_CXSCREEN);
  170. int screenh = GetSystemMetrics(SM_CYSCREEN);
  171. if ((int)mWidth > screenw)
  172. mWidth = screenw;
  173. if ((int)mHeight > screenh)
  174. mHeight = screenh;
  175. if (mLeft < 0)
  176. mLeft = (screenw - mWidth) / 2;
  177. if (mTop < 0)
  178. mTop = (screenh - mHeight) / 2;
  179. }
  180. }
  181. else
  182. {
  183. dwStyle |= WS_POPUP;
  184. mTop = mLeft = 0;
  185. }
  186. UINT classStyle = 0;
  187. if (mDesc.enableDoubleClick)
  188. classStyle |= CS_DBLCLKS;
  189. HINSTANCE hInst = NULL;
  190. // Register the window class
  191. // Allow 4 bytes of window data for D3D11RenderWindow pointer
  192. WNDCLASS wc = { classStyle, PlatformWndProc::_win32WndProc, 0, 0, hInst,
  193. LoadIcon(0, IDI_APPLICATION), LoadCursor(NULL, IDC_ARROW),
  194. (HBRUSH)GetStockObject(BLACK_BRUSH), 0, "D3D11Wnd" };
  195. RegisterClass(&wc);
  196. // Create our main window
  197. // Pass pointer to self
  198. mIsExternal = false;
  199. mHWnd = CreateWindowEx(dwStyleEx, "D3D11Wnd", mDesc.title.c_str(), dwStyle,
  200. mLeft, mTop, mWidth, mHeight, parentHWnd, 0, hInst, this);
  201. }
  202. else
  203. {
  204. mHWnd = externalHandle;
  205. mIsExternal = true;
  206. }
  207. RECT rc;
  208. // top and left represent outer window coordinates
  209. GetWindowRect(mHWnd, &rc);
  210. mTop = rc.top;
  211. mLeft = rc.left;
  212. // width and height represent interior drawable area
  213. GetClientRect(mHWnd, &rc);
  214. mWidth = rc.right;
  215. mHeight = rc.bottom;
  216. createSwapChain();
  217. createSizeDependedD3DResources();
  218. mDXGIFactory->MakeWindowAssociation(mHWnd, NULL);
  219. setHidden(mHidden);
  220. RenderWindow::initialize_internal();
  221. }
  222. void D3D11RenderWindow::destroy_internal()
  223. {
  224. mActive = false;
  225. mClosed = true;
  226. SAFE_RELEASE(mSwapChain);
  227. if (mHWnd && !mIsExternal)
  228. {
  229. DestroyWindow(mHWnd);
  230. }
  231. if(mDepthStencilView != nullptr)
  232. {
  233. Texture::releaseView(mDepthStencilView);
  234. mDepthStencilView = nullptr;
  235. }
  236. mHWnd = nullptr;
  237. destroySizeDependedD3DResources();
  238. RenderWindow::destroy_internal();
  239. }
  240. void D3D11RenderWindow::swapBuffers()
  241. {
  242. THROW_IF_NOT_CORE_THREAD;
  243. if(mDevice.getD3D11Device() != nullptr)
  244. {
  245. HRESULT hr = mSwapChain->Present(mVSync ? mVSyncInterval : 0, 0);
  246. if( FAILED(hr) )
  247. CM_EXCEPT(RenderingAPIException, "Error Presenting surfaces");
  248. }
  249. }
  250. void D3D11RenderWindow::move(INT32 top, INT32 left)
  251. {
  252. THROW_IF_NOT_CORE_THREAD;
  253. if (mHWnd && !mIsFullScreen)
  254. {
  255. mTop = top;
  256. mLeft = left;
  257. SetWindowPos(mHWnd, 0, top, left, 0, 0,
  258. SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE);
  259. }
  260. }
  261. void D3D11RenderWindow::resize(UINT32 width, UINT32 height)
  262. {
  263. THROW_IF_NOT_CORE_THREAD;
  264. if (mHWnd && !mIsFullScreen)
  265. {
  266. mWidth = width;
  267. mHeight = height;
  268. RECT rc = { 0, 0, width, height };
  269. AdjustWindowRect(&rc, GetWindowLong(mHWnd, GWL_STYLE), false);
  270. width = rc.right - rc.left;
  271. height = rc.bottom - rc.top;
  272. SetWindowPos(mHWnd, 0, 0, 0, width, height,
  273. SWP_NOMOVE | SWP_NOZORDER | SWP_NOACTIVATE);
  274. }
  275. }
  276. void D3D11RenderWindow::setActive(bool state)
  277. {
  278. THROW_IF_NOT_CORE_THREAD;
  279. if (mHWnd && mSwapChain)
  280. {
  281. if (state)
  282. {
  283. ShowWindow(mHWnd, SW_RESTORE);
  284. mSwapChain->SetFullscreenState(mIsFullScreen, nullptr);
  285. }
  286. else
  287. {
  288. ShowWindow(mHWnd, SW_SHOWMINIMIZED);
  289. mSwapChain->SetFullscreenState(FALSE, nullptr);
  290. }
  291. }
  292. RenderWindow::setActive(state);
  293. }
  294. void D3D11RenderWindow::setHidden(bool hidden)
  295. {
  296. THROW_IF_NOT_CORE_THREAD;
  297. mHidden = hidden;
  298. if (!mIsExternal)
  299. {
  300. if (hidden)
  301. ShowWindow(mHWnd, SW_HIDE);
  302. else
  303. ShowWindow(mHWnd, SW_SHOWNORMAL);
  304. }
  305. }
  306. void D3D11RenderWindow::setFullscreen(bool fullScreen, unsigned int width, unsigned int height)
  307. {
  308. THROW_IF_NOT_CORE_THREAD;
  309. if (fullScreen != mIsFullScreen || width != mWidth || height != mHeight)
  310. {
  311. if (fullScreen != mIsFullScreen)
  312. mSwitchingFullscreen = true;
  313. DWORD dwStyle = WS_VISIBLE | WS_CLIPCHILDREN;
  314. bool oldFullscreen = mIsFullScreen;
  315. mIsFullScreen = fullScreen;
  316. if (fullScreen)
  317. {
  318. dwStyle |= WS_POPUP;
  319. mTop = mLeft = 0;
  320. mWidth = width;
  321. mHeight = height;
  322. // need different ordering here
  323. if (oldFullscreen)
  324. {
  325. // was previously fullscreen, just changing the resolution
  326. SetWindowPos(mHWnd, HWND_TOPMOST, 0, 0, width, height, SWP_NOACTIVATE);
  327. }
  328. else
  329. {
  330. SetWindowPos(mHWnd, HWND_TOPMOST, 0, 0, width, height, SWP_NOACTIVATE);
  331. //MoveWindow(mHWnd, mLeft, mTop, mWidth, mHeight, FALSE);
  332. SetWindowLong(mHWnd, GWL_STYLE, dwStyle);
  333. SetWindowPos(mHWnd, 0, 0,0, 0,0, SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER);
  334. }
  335. }
  336. else
  337. {
  338. dwStyle |= WS_OVERLAPPEDWINDOW;
  339. // Calculate window dimensions required
  340. // to get the requested client area
  341. RECT rc;
  342. SetRect(&rc, 0, 0, width, height);
  343. AdjustWindowRect(&rc, dwStyle, false);
  344. unsigned int winWidth = rc.right - rc.left;
  345. unsigned int winHeight = rc.bottom - rc.top;
  346. SetWindowLong(mHWnd, GWL_STYLE, dwStyle);
  347. SetWindowPos(mHWnd, HWND_NOTOPMOST, 0, 0, winWidth, winHeight,
  348. SWP_DRAWFRAME | SWP_FRAMECHANGED | SWP_NOMOVE | SWP_NOACTIVATE);
  349. // Note that we also set the position in the restoreLostDevice method
  350. // via _finishSwitchingFullScreen
  351. }
  352. mSwapChainDesc.Windowed = !fullScreen;
  353. mSwapChainDesc.BufferDesc.RefreshRate.Numerator = 0;
  354. mSwapChainDesc.BufferDesc.RefreshRate.Denominator=0;
  355. mSwapChainDesc.BufferDesc.Height = height;
  356. mSwapChainDesc.BufferDesc.Width = width;
  357. }
  358. }
  359. void D3D11RenderWindow::getCustomAttribute( const String& name, void* pData ) const
  360. {
  361. if(name == "WINDOW")
  362. {
  363. HWND *pWnd = (HWND*)pData;
  364. *pWnd = mHWnd;
  365. return;
  366. }
  367. if(name == "RTV")
  368. {
  369. *static_cast<ID3D11RenderTargetView**>(pData) = mRenderTargetView;
  370. return;
  371. }
  372. else if(name == "DSV")
  373. {
  374. D3D11TextureView* d3d11TextureView = static_cast<D3D11TextureView*>(mDepthStencilView.get());
  375. *static_cast<ID3D11DepthStencilView**>(pData) = d3d11TextureView->getDSV();
  376. return;
  377. }
  378. RenderWindow::getCustomAttribute(name, pData);
  379. }
  380. void D3D11RenderWindow::copyToMemory(const PixelData &dst, FrameBuffer buffer)
  381. {
  382. THROW_IF_NOT_CORE_THREAD;
  383. if(mBackBuffer == nullptr)
  384. return;
  385. // get the backbuffer desc
  386. D3D11_TEXTURE2D_DESC BBDesc;
  387. mBackBuffer->GetDesc(&BBDesc);
  388. ID3D11Texture2D *backbuffer = nullptr;
  389. if(BBDesc.SampleDesc.Quality > 0)
  390. {
  391. D3D11_TEXTURE2D_DESC desc = BBDesc;
  392. desc.Usage = D3D11_USAGE_DEFAULT;
  393. desc.CPUAccessFlags = 0;
  394. desc.BindFlags = 0;
  395. desc.SampleDesc.Quality = 0;
  396. desc.SampleDesc.Count = 1;
  397. HRESULT hr = mDevice.getD3D11Device()->CreateTexture2D(
  398. &desc,
  399. NULL,
  400. &backbuffer);
  401. if (FAILED(hr) || mDevice.hasError())
  402. {
  403. String errorDescription = mDevice.getErrorDescription();
  404. CM_EXCEPT(RenderingAPIException,
  405. "Error creating texture\nError Description:" + errorDescription);
  406. }
  407. mDevice.getImmediateContext()->ResolveSubresource(backbuffer, D3D11CalcSubresource(0, 0, 1), mBackBuffer, D3D11CalcSubresource(0, 0, 1), desc.Format);
  408. }
  409. // change the parameters of the texture so we can read it
  410. BBDesc.Usage = D3D11_USAGE_STAGING;
  411. BBDesc.CPUAccessFlags = D3D11_CPU_ACCESS_READ;
  412. BBDesc.BindFlags = 0;
  413. BBDesc.SampleDesc.Quality = 0;
  414. BBDesc.SampleDesc.Count = 1;
  415. // create a temp buffer to copy to
  416. ID3D11Texture2D * pTempTexture2D;
  417. HRESULT hr = mDevice.getD3D11Device()->CreateTexture2D(
  418. &BBDesc,
  419. NULL,
  420. &pTempTexture2D);
  421. if (FAILED(hr) || mDevice.hasError())
  422. {
  423. String errorDescription = mDevice.getErrorDescription();
  424. CM_EXCEPT(RenderingAPIException,
  425. "Error creating texture\nError Description:" + errorDescription);
  426. }
  427. // copy the back buffer
  428. mDevice.getImmediateContext()->CopyResource(pTempTexture2D, backbuffer != NULL ? backbuffer : mBackBuffer);
  429. // map the copied texture
  430. D3D11_MAPPED_SUBRESOURCE mappedTex2D;
  431. mDevice.getImmediateContext()->Map(pTempTexture2D, 0,D3D11_MAP_READ, 0, &mappedTex2D);
  432. // copy the the texture to the dest
  433. PixelData src(mWidth, mHeight, 1, PF_A8B8G8R8);
  434. src.setExternalBuffer((UINT8*)mappedTex2D.pData);
  435. PixelUtil::bulkPixelConversion(src, dst);
  436. // unmap the temp buffer
  437. mDevice.getImmediateContext()->Unmap(pTempTexture2D, 0);
  438. // Release the temp buffer
  439. SAFE_RELEASE(pTempTexture2D);
  440. SAFE_RELEASE(backbuffer);
  441. }
  442. Vector2I D3D11RenderWindow::screenToWindowPos(const Vector2I& screenPos) const
  443. {
  444. POINT pos;
  445. pos.x = screenPos.x;
  446. pos.y = screenPos.y;
  447. ScreenToClient(mHWnd, &pos);
  448. return Vector2I(pos.x, pos.y);
  449. }
  450. Vector2I D3D11RenderWindow::windowToScreenPos(const Vector2I& windowPos) const
  451. {
  452. POINT pos;
  453. pos.x = windowPos.x;
  454. pos.y = windowPos.y;
  455. ClientToScreen(mHWnd, &pos);
  456. return Vector2I(pos.x, pos.y);
  457. }
  458. void D3D11RenderWindow::_windowMovedOrResized()
  459. {
  460. THROW_IF_NOT_CORE_THREAD;
  461. if (!mHWnd || IsIconic(mHWnd))
  462. return;
  463. RECT rc;
  464. // top and left represent outer window position
  465. GetWindowRect(mHWnd, &rc);
  466. mTop = rc.top;
  467. mLeft = rc.left;
  468. // width and height represent drawable area only
  469. GetClientRect(mHWnd, &rc);
  470. unsigned int width = rc.right - rc.left;
  471. unsigned int height = rc.bottom - rc.top;
  472. if (width == 0)
  473. width = 1;
  474. if (height == 0)
  475. height = 1;
  476. resizeSwapChainBuffers(width, height);
  477. RenderWindow::_windowMovedOrResized();
  478. }
  479. void D3D11RenderWindow::createSwapChain()
  480. {
  481. ZeroMemory(&mSwapChainDesc, sizeof(DXGI_SWAP_CHAIN_DESC));
  482. // get the dxgi device
  483. IDXGIDevice* pDXGIDevice = queryDxgiDevice();
  484. ZeroMemory(&mSwapChainDesc, sizeof(DXGI_SWAP_CHAIN_DESC));
  485. DXGI_FORMAT format = DXGI_FORMAT_R8G8B8A8_UNORM;
  486. mSwapChainDesc.OutputWindow = mHWnd;
  487. mSwapChainDesc.BufferDesc.Width = mWidth;
  488. mSwapChainDesc.BufferDesc.Height = mHeight;
  489. mSwapChainDesc.BufferDesc.Format = format;
  490. mSwapChainDesc.BufferDesc.RefreshRate.Numerator=0;
  491. mSwapChainDesc.BufferDesc.RefreshRate.Denominator = 0;
  492. mSwapChainDesc.BufferDesc.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED;
  493. mSwapChainDesc.BufferDesc.Scaling = DXGI_MODE_SCALING_UNSPECIFIED;
  494. mSwapChainDesc.Flags = DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH ;
  495. // triple buffer if VSync is on
  496. mSwapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
  497. mSwapChainDesc.BufferCount = mVSync ? 2 : 1;
  498. mSwapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_DISCARD ;
  499. mSwapChainDesc.OutputWindow = mHWnd;
  500. mSwapChainDesc.Windowed = !mIsFullScreen;
  501. D3D11RenderSystem* rs = static_cast<D3D11RenderSystem*>(RenderSystem::instancePtr());
  502. rs->determineFSAASettings(mFSAA, mFSAAHint, format, &mFSAAType);
  503. mSwapChainDesc.SampleDesc.Count = mFSAAType.Count;
  504. mSwapChainDesc.SampleDesc.Quality = mFSAAType.Quality;
  505. HRESULT hr;
  506. // Create swap chain
  507. hr = mDXGIFactory->CreateSwapChain(pDXGIDevice, &mSwapChainDesc, &mSwapChain);
  508. if (FAILED(hr))
  509. {
  510. // Try a second time, may fail the first time due to back buffer count,
  511. // which will be corrected by the runtime
  512. hr = mDXGIFactory->CreateSwapChain(pDXGIDevice, &mSwapChainDesc, &mSwapChain);
  513. }
  514. SAFE_RELEASE(pDXGIDevice);
  515. if (FAILED(hr))
  516. CM_EXCEPT(RenderingAPIException, "Unable to create swap chain");
  517. }
  518. void D3D11RenderWindow::createSizeDependedD3DResources()
  519. {
  520. // obtain back buffer
  521. SAFE_RELEASE(mBackBuffer);
  522. HRESULT hr = mSwapChain->GetBuffer(0, __uuidof( ID3D11Texture2D ), (LPVOID*)&mBackBuffer);
  523. if( FAILED(hr) )
  524. CM_EXCEPT(RenderingAPIException, "Unable to Get Back Buffer for swap chain");
  525. // create all other size depended resources
  526. assert(mBackBuffer && !mRenderTargetView);
  527. // get the backbuffer desc
  528. D3D11_TEXTURE2D_DESC BBDesc;
  529. mBackBuffer->GetDesc(&BBDesc);
  530. // create the render target view
  531. D3D11_RENDER_TARGET_VIEW_DESC RTVDesc;
  532. ZeroMemory( &RTVDesc, sizeof(RTVDesc) );
  533. RTVDesc.Format = BBDesc.Format;
  534. RTVDesc.ViewDimension = mFSAA ? D3D11_RTV_DIMENSION_TEXTURE2DMS : D3D11_RTV_DIMENSION_TEXTURE2D;
  535. RTVDesc.Texture2D.MipSlice = 0;
  536. hr = mDevice.getD3D11Device()->CreateRenderTargetView(mBackBuffer, &RTVDesc, &mRenderTargetView);
  537. if( FAILED(hr) )
  538. {
  539. String errorDescription = mDevice.getErrorDescription();
  540. CM_EXCEPT(RenderingAPIException, "Unable to create rendertagert view\nError Description:" + errorDescription);
  541. }
  542. mDepthStencilBuffer = TextureManager::instance().createTexture(TEX_TYPE_2D,
  543. BBDesc.Width, BBDesc.Height, 0, PF_D24S8, TU_DEPTHSTENCIL, false, mFSAA, mFSAAHint);
  544. if(mDepthStencilView != nullptr)
  545. {
  546. Texture::releaseView(mDepthStencilView);
  547. mDepthStencilView = nullptr;
  548. }
  549. mDepthStencilView = Texture::requestView(mDepthStencilBuffer, 0, 1, 0, 1, GVU_DEPTHSTENCIL);
  550. }
  551. void D3D11RenderWindow::destroySizeDependedD3DResources()
  552. {
  553. SAFE_RELEASE(mBackBuffer);
  554. SAFE_RELEASE(mRenderTargetView);
  555. mDepthStencilBuffer = nullptr;
  556. }
  557. void D3D11RenderWindow::resizeSwapChainBuffers(unsigned width, unsigned height)
  558. {
  559. destroySizeDependedD3DResources();
  560. // width and height can be zero to autodetect size, therefore do not rely on them
  561. UINT Flags = mIsFullScreen ? DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH : 0;
  562. HRESULT hr = mSwapChain->ResizeBuffers(mSwapChainDesc.BufferCount, width, height, mSwapChainDesc.BufferDesc.Format, Flags);
  563. if(hr != S_OK)
  564. CM_EXCEPT(InternalErrorException, "Call to ResizeBuffers failed.");
  565. mSwapChain->GetDesc(&mSwapChainDesc);
  566. mWidth = mSwapChainDesc.BufferDesc.Width;
  567. mHeight = mSwapChainDesc.BufferDesc.Height;
  568. mIsFullScreen = (0 == mSwapChainDesc.Windowed); // Alt-Enter together with SetWindowAssociation() can change this state
  569. createSizeDependedD3DResources();
  570. mDevice.getImmediateContext()->OMSetRenderTargets(0, 0, 0);
  571. }
  572. IDXGIDevice* D3D11RenderWindow::queryDxgiDevice()
  573. {
  574. if (mDevice.getD3D11Device() == nullptr)
  575. {
  576. CM_EXCEPT(RenderingAPIException, "D3D11Device is NULL!");
  577. }
  578. IDXGIDevice* pDXGIDevice = nullptr;
  579. HRESULT hr = mDevice.getD3D11Device()->QueryInterface(__uuidof(IDXGIDevice), (void**)&pDXGIDevice);
  580. if(FAILED(hr))
  581. CM_EXCEPT(RenderingAPIException, "Unable to query a DXGIDevice");
  582. return pDXGIDevice;
  583. }
  584. void D3D11RenderWindow::finishSwitchingFullscreen()
  585. {
  586. if(mIsFullScreen)
  587. {
  588. // Need to reset the region on the window sometimes, when the
  589. // windowed mode was constrained by desktop
  590. HRGN hRgn = CreateRectRgn(0, 0, mSwapChainDesc.BufferDesc.Width, mSwapChainDesc.BufferDesc.Height);
  591. SetWindowRgn(mHWnd, hRgn, FALSE);
  592. }
  593. else
  594. {
  595. // When switching back to windowed mode, need to reset window size
  596. // after device has been restored
  597. RECT rc;
  598. SetRect(&rc, 0, 0, mSwapChainDesc.BufferDesc.Width, mSwapChainDesc.BufferDesc.Height);
  599. AdjustWindowRect(&rc, GetWindowLong(mHWnd, GWL_STYLE), false);
  600. unsigned int winWidth = rc.right - rc.left;
  601. unsigned int winHeight = rc.bottom - rc.top;
  602. int screenw = GetSystemMetrics(SM_CXSCREEN);
  603. int screenh = GetSystemMetrics(SM_CYSCREEN);
  604. int left = (screenw - winWidth) / 2;
  605. int top = (screenh - winHeight) / 2;
  606. SetWindowPos(mHWnd, HWND_NOTOPMOST, left, top, winWidth, winHeight,
  607. SWP_DRAWFRAME | SWP_FRAMECHANGED | SWP_NOACTIVATE);
  608. }
  609. mSwapChain->SetFullscreenState(mIsFullScreen, NULL);
  610. mSwitchingFullscreen = false;
  611. }
  612. bool D3D11RenderWindow::checkMultiSampleQuality(UINT32 SampleCount, UINT32 *outQuality, DXGI_FORMAT format)
  613. {
  614. if (SUCCEEDED(mDevice.getD3D11Device()->CheckMultisampleQualityLevels(format, SampleCount, outQuality)))
  615. return true;
  616. else
  617. return false;
  618. }
  619. }