BsD3D11RenderWindow.cpp 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892
  1. #include "BsD3D11RenderWindow.h"
  2. #include "BsCoreThread.h"
  3. #include "Win32/BsWin32Platform.h"
  4. #include "BsD3D11RenderAPI.h"
  5. #include "BsD3D11Device.h"
  6. #include "BsD3D11RenderTexture.h"
  7. #include "BsD3D11TextureView.h"
  8. #include "BsTextureManager.h"
  9. #include "BsD3D11DriverList.h"
  10. #include "BsD3D11Driver.h"
  11. #include "BsD3D11VideoModeInfo.h"
  12. #include "BsRenderStats.h"
  13. #include "BsInput.h"
  14. #include "BsException.h"
  15. #include "BsRenderWindowManager.h"
  16. namespace BansheeEngine
  17. {
  18. D3D11RenderWindowProperties::D3D11RenderWindowProperties(const RENDER_WINDOW_DESC& desc)
  19. :RenderWindowProperties(desc)
  20. { }
  21. D3D11RenderWindowCore::D3D11RenderWindowCore(const RENDER_WINDOW_DESC& desc, UINT32 windowId, D3D11Device& device, IDXGIFactory* DXGIFactory)
  22. : RenderWindowCore(desc, windowId), mProperties(desc), mSyncedProperties(desc), mDevice(device), mDXGIFactory(DXGIFactory), mIsExternal(false),
  23. mSizing(false), mRenderTargetView(nullptr), mBackBuffer(nullptr), mSwapChain(nullptr), mDepthStencilView(nullptr), mIsChild(false),
  24. mRefreshRateNumerator(0), mRefreshRateDenominator(0), mHWnd(0), mShowOnSwap(false)
  25. { }
  26. D3D11RenderWindowCore::~D3D11RenderWindowCore()
  27. {
  28. D3D11RenderWindowProperties& props = mProperties;
  29. props.mActive = false;
  30. SAFE_RELEASE(mSwapChain);
  31. BS_INC_RENDER_STAT_CAT(ResDestroyed, RenderStatObject_SwapChain);
  32. if (mHWnd && !mIsExternal)
  33. {
  34. DestroyWindow(mHWnd);
  35. }
  36. if (mDepthStencilView != nullptr)
  37. {
  38. TextureCore::releaseView(mDepthStencilView);
  39. mDepthStencilView = nullptr;
  40. }
  41. mHWnd = 0;
  42. destroySizeDependedD3DResources();
  43. }
  44. void D3D11RenderWindowCore::initialize()
  45. {
  46. RenderWindowCore::initialize();
  47. ZeroMemory(&mSwapChainDesc, sizeof(DXGI_SWAP_CHAIN_DESC));
  48. D3D11RenderWindowProperties& props = mProperties;
  49. mMultisampleType.Count = 1;
  50. mMultisampleType.Quality = 0;
  51. HWND parentHWnd = 0;
  52. HWND externalHandle = 0;
  53. NameValuePairList::const_iterator opt;
  54. opt = mDesc.platformSpecific.find("parentWindowHandle");
  55. if (opt != mDesc.platformSpecific.end())
  56. parentHWnd = (HWND)parseUnsignedInt(opt->second);
  57. opt = mDesc.platformSpecific.find("externalWindowHandle");
  58. if (opt != mDesc.platformSpecific.end())
  59. externalHandle = (HWND)parseUnsignedInt(opt->second);
  60. mIsChild = parentHWnd != 0;
  61. props.mIsFullScreen = mDesc.fullscreen && !mIsChild;
  62. props.mColorDepth = 32;
  63. props.mActive = true;
  64. if (mDesc.videoMode.isCustom())
  65. {
  66. mRefreshRateNumerator = Math::roundToInt(mDesc.videoMode.getRefreshRate());
  67. mRefreshRateDenominator = 1;
  68. }
  69. else
  70. {
  71. const D3D11VideoMode& d3d11videoMode = static_cast<const D3D11VideoMode&>(mDesc.videoMode);
  72. mRefreshRateNumerator = d3d11videoMode.getRefreshRateNumerator();
  73. mRefreshRateDenominator = d3d11videoMode.getRefreshRateDenominator();
  74. }
  75. HMONITOR hMonitor = NULL;
  76. const D3D11VideoOutputInfo* outputInfo = nullptr;
  77. const D3D11VideoModeInfo& videoModeInfo = static_cast<const D3D11VideoModeInfo&>(RenderAPICore::instance().getVideoModeInfo());
  78. UINT32 numOutputs = videoModeInfo.getNumOutputs();
  79. if (numOutputs > 0)
  80. {
  81. UINT32 actualMonitorIdx = std::min(mDesc.videoMode.getOutputIdx(), numOutputs - 1);
  82. outputInfo = static_cast<const D3D11VideoOutputInfo*>(&videoModeInfo.getOutputInfo(actualMonitorIdx));
  83. DXGI_OUTPUT_DESC desc;
  84. outputInfo->getDXGIOutput()->GetDesc(&desc);
  85. hMonitor = desc.Monitor;
  86. }
  87. if (!externalHandle)
  88. {
  89. DWORD dwStyle = WS_CLIPCHILDREN;
  90. mShowOnSwap = mDesc.hideUntilSwap;
  91. props.mHidden = mDesc.hideUntilSwap;
  92. if (!mShowOnSwap)
  93. dwStyle |= WS_VISIBLE;
  94. DWORD dwStyleEx = 0;
  95. RECT rc;
  96. MONITORINFO monitorInfo;
  97. // If we didn't specified the adapter index, or if it didn't find it
  98. if (hMonitor == NULL)
  99. {
  100. POINT windowAnchorPoint;
  101. // Fill in anchor point.
  102. windowAnchorPoint.x = mDesc.left;
  103. windowAnchorPoint.y = mDesc.top;
  104. // Get the nearest monitor to this window.
  105. hMonitor = MonitorFromPoint(windowAnchorPoint, MONITOR_DEFAULTTOPRIMARY);
  106. }
  107. // Get the target monitor info
  108. memset(&monitorInfo, 0, sizeof(MONITORINFO));
  109. monitorInfo.cbSize = sizeof(MONITORINFO);
  110. GetMonitorInfo(hMonitor, &monitorInfo);
  111. unsigned int winWidth, winHeight;
  112. winWidth = mDesc.videoMode.getWidth();
  113. winHeight = mDesc.videoMode.getHeight();
  114. UINT32 left = mDesc.left;
  115. UINT32 top = mDesc.top;
  116. // No specified top left -> Center the window in the middle of the monitor
  117. if (left == -1 || top == -1)
  118. {
  119. int screenw = monitorInfo.rcWork.right - monitorInfo.rcWork.left;
  120. int screenh = monitorInfo.rcWork.bottom - monitorInfo.rcWork.top;
  121. // clamp window dimensions to screen size
  122. int outerw = (int(winWidth) < screenw) ? int(winWidth) : screenw;
  123. int outerh = (int(winHeight) < screenh) ? int(winHeight) : screenh;
  124. if (left == -1)
  125. left = monitorInfo.rcWork.left + (screenw - outerw) / 2;
  126. else if (hMonitor != NULL)
  127. left += monitorInfo.rcWork.left;
  128. if (top == -1)
  129. top = monitorInfo.rcWork.top + (screenh - outerh) / 2;
  130. else if (hMonitor != NULL)
  131. top += monitorInfo.rcWork.top;
  132. }
  133. else if (hMonitor != NULL)
  134. {
  135. left += monitorInfo.rcWork.left;
  136. top += monitorInfo.rcWork.top;
  137. }
  138. props.mWidth = mDesc.videoMode.getWidth();
  139. props.mHeight = mDesc.videoMode.getHeight();
  140. props.mTop = top;
  141. props.mLeft = left;
  142. if (!mDesc.fullscreen)
  143. {
  144. if (parentHWnd)
  145. {
  146. if (mDesc.toolWindow)
  147. dwStyleEx = WS_EX_TOOLWINDOW;
  148. else
  149. dwStyle |= WS_CHILD;
  150. }
  151. if (!parentHWnd || mDesc.toolWindow)
  152. {
  153. if (mDesc.border == WindowBorder::None)
  154. dwStyle |= WS_POPUP;
  155. else if (mDesc.border == WindowBorder::Fixed)
  156. dwStyle |= WS_OVERLAPPED | WS_BORDER | WS_CAPTION |
  157. WS_SYSMENU | WS_MINIMIZEBOX;
  158. else
  159. dwStyle |= WS_OVERLAPPEDWINDOW;
  160. }
  161. if (!mDesc.outerDimensions)
  162. {
  163. // Calculate window dimensions required
  164. // to get the requested client area
  165. SetRect(&rc, 0, 0, props.mWidth, props.mHeight);
  166. AdjustWindowRect(&rc, dwStyle, false);
  167. props.mWidth = rc.right - rc.left;
  168. props.mHeight = rc.bottom - rc.top;
  169. // Clamp width and height to the desktop dimensions
  170. int screenw = GetSystemMetrics(SM_CXSCREEN);
  171. int screenh = GetSystemMetrics(SM_CYSCREEN);
  172. if ((int)props.mWidth > screenw)
  173. props.mWidth = screenw;
  174. if ((int)props.mHeight > screenh)
  175. props.mHeight = screenh;
  176. if (props.mLeft < 0)
  177. props.mLeft = (screenw - props.mWidth) / 2;
  178. if (props.mTop < 0)
  179. props.mTop = (screenh - props.mHeight) / 2;
  180. }
  181. }
  182. else
  183. {
  184. dwStyle |= WS_POPUP;
  185. props.mTop = 0;
  186. props.mLeft = 0;
  187. }
  188. UINT classStyle = 0;
  189. if (mDesc.enableDoubleClick)
  190. classStyle |= CS_DBLCLKS;
  191. HINSTANCE hInst = NULL;
  192. // Register the window class
  193. // Allow 4 bytes of window data for D3D11RenderWindow pointer
  194. WNDCLASS wc = { classStyle, Win32Platform::_win32WndProc, 0, 0, hInst,
  195. LoadIcon(0, IDI_APPLICATION), LoadCursor(NULL, IDC_ARROW),
  196. (HBRUSH)GetStockObject(BLACK_BRUSH), 0, "D3D11Wnd" };
  197. RegisterClass(&wc);
  198. // Create our main window
  199. // Pass pointer to self
  200. mIsExternal = false;
  201. mHWnd = CreateWindowEx(dwStyleEx, "D3D11Wnd", mDesc.title.c_str(), dwStyle,
  202. props.mLeft, props.mTop, props.mWidth, props.mHeight, parentHWnd, 0, hInst, this);
  203. }
  204. else
  205. {
  206. mHWnd = externalHandle;
  207. mIsExternal = true;
  208. }
  209. RECT rc;
  210. GetWindowRect(mHWnd, &rc);
  211. props.mTop = rc.top;
  212. props.mLeft = rc.left;
  213. GetClientRect(mHWnd, &rc);
  214. props.mWidth = rc.right;
  215. props.mHeight = rc.bottom;
  216. createSwapChain();
  217. if (props.isFullScreen())
  218. {
  219. if (outputInfo != nullptr)
  220. mSwapChain->SetFullscreenState(true, outputInfo->getDXGIOutput());
  221. else
  222. mSwapChain->SetFullscreenState(true, nullptr);
  223. }
  224. createSizeDependedD3DResources();
  225. mDXGIFactory->MakeWindowAssociation(mHWnd, NULL);
  226. {
  227. ScopedSpinLock lock(mLock);
  228. mSyncedProperties = props;
  229. }
  230. RenderWindowManager::instance().notifySyncDataDirty(this);
  231. }
  232. void D3D11RenderWindowCore::swapBuffers()
  233. {
  234. THROW_IF_NOT_CORE_THREAD;
  235. if (mShowOnSwap)
  236. setHidden(false);
  237. if(mDevice.getD3D11Device() != nullptr)
  238. {
  239. HRESULT hr = mSwapChain->Present(getProperties().getVSync() ? getProperties().getVSyncInterval() : 0, 0);
  240. if( FAILED(hr) )
  241. BS_EXCEPT(RenderingAPIException, "Error Presenting surfaces");
  242. }
  243. }
  244. void D3D11RenderWindowCore::move(INT32 top, INT32 left)
  245. {
  246. THROW_IF_NOT_CORE_THREAD;
  247. D3D11RenderWindowProperties& props = mProperties;
  248. if (mHWnd && !props.mIsFullScreen)
  249. {
  250. props.mTop = top;
  251. props.mLeft = left;
  252. SetWindowPos(mHWnd, 0, top, left, 0, 0, SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE);
  253. {
  254. ScopedSpinLock lock(mLock);
  255. mSyncedProperties.mTop = props.mTop;
  256. mSyncedProperties.mLeft = props.mLeft;
  257. }
  258. RenderWindowManager::instance().notifySyncDataDirty(this);
  259. }
  260. }
  261. void D3D11RenderWindowCore::resize(UINT32 width, UINT32 height)
  262. {
  263. THROW_IF_NOT_CORE_THREAD;
  264. D3D11RenderWindowProperties& props = mProperties;
  265. if (mHWnd && !props.mIsFullScreen)
  266. {
  267. props.mWidth = width;
  268. props.mHeight = height;
  269. RECT rc = { 0, 0, width, height };
  270. AdjustWindowRect(&rc, GetWindowLong(mHWnd, GWL_STYLE), false);
  271. width = rc.right - rc.left;
  272. height = rc.bottom - rc.top;
  273. SetWindowPos(mHWnd, 0, 0, 0, width, height, SWP_NOMOVE | SWP_NOZORDER | SWP_NOACTIVATE);
  274. {
  275. ScopedSpinLock lock(mLock);
  276. mSyncedProperties.mWidth = props.mWidth;
  277. mSyncedProperties.mHeight = props.mHeight;
  278. }
  279. RenderWindowManager::instance().notifySyncDataDirty(this);
  280. }
  281. }
  282. void D3D11RenderWindowCore::setActive(bool state)
  283. {
  284. THROW_IF_NOT_CORE_THREAD;
  285. D3D11RenderWindowProperties& props = mProperties;
  286. if (mHWnd && mSwapChain)
  287. {
  288. if (state)
  289. {
  290. ShowWindow(mHWnd, SW_RESTORE);
  291. mSwapChain->SetFullscreenState(props.mIsFullScreen, nullptr);
  292. }
  293. else
  294. {
  295. ShowWindow(mHWnd, SW_SHOWMINNOACTIVE);
  296. mSwapChain->SetFullscreenState(FALSE, nullptr);
  297. }
  298. }
  299. RenderWindowCore::setActive(state);
  300. }
  301. void D3D11RenderWindowCore::setHidden(bool hidden)
  302. {
  303. THROW_IF_NOT_CORE_THREAD;
  304. mShowOnSwap = false;
  305. if (!mIsExternal)
  306. {
  307. if (hidden)
  308. ShowWindow(mHWnd, SW_HIDE);
  309. else
  310. ShowWindow(mHWnd, SW_SHOWNORMAL);
  311. }
  312. RenderWindowCore::setHidden(hidden);
  313. }
  314. void D3D11RenderWindowCore::minimize()
  315. {
  316. THROW_IF_NOT_CORE_THREAD;
  317. if (mHWnd)
  318. SendMessage(mHWnd, WM_SYSCOMMAND, SC_MINIMIZE, 0);
  319. }
  320. void D3D11RenderWindowCore::maximize()
  321. {
  322. THROW_IF_NOT_CORE_THREAD;
  323. if (mHWnd)
  324. SendMessage(mHWnd, WM_SYSCOMMAND, SC_MAXIMIZE, 0);
  325. }
  326. void D3D11RenderWindowCore::restore()
  327. {
  328. THROW_IF_NOT_CORE_THREAD;
  329. if (mHWnd)
  330. SendMessage(mHWnd, WM_SYSCOMMAND, SC_RESTORE, 0);
  331. }
  332. void D3D11RenderWindowCore::setFullscreen(UINT32 width, UINT32 height, float refreshRate, UINT32 monitorIdx)
  333. {
  334. THROW_IF_NOT_CORE_THREAD;
  335. if (mIsChild)
  336. return;
  337. const D3D11VideoModeInfo& videoModeInfo = static_cast<const D3D11VideoModeInfo&>(RenderAPICore::instance().getVideoModeInfo());
  338. UINT32 numOutputs = videoModeInfo.getNumOutputs();
  339. if (numOutputs == 0)
  340. return;
  341. UINT32 actualMonitorIdx = std::min(monitorIdx, numOutputs - 1);
  342. const D3D11VideoOutputInfo& outputInfo = static_cast<const D3D11VideoOutputInfo&>(videoModeInfo.getOutputInfo(actualMonitorIdx));
  343. DXGI_MODE_DESC modeDesc;
  344. ZeroMemory(&modeDesc, sizeof(modeDesc));
  345. modeDesc.Width = width;
  346. modeDesc.Height = height;
  347. modeDesc.RefreshRate.Numerator = Math::roundToInt(refreshRate);
  348. modeDesc.RefreshRate.Denominator = 1;
  349. modeDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
  350. modeDesc.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED;
  351. modeDesc.Scaling = DXGI_MODE_SCALING_UNSPECIFIED;
  352. DXGI_MODE_DESC nearestMode;
  353. ZeroMemory(&nearestMode, sizeof(nearestMode));
  354. outputInfo.getDXGIOutput()->FindClosestMatchingMode(&modeDesc, &nearestMode, nullptr);
  355. mProperties.mIsFullScreen = true;
  356. mProperties.mWidth = width;
  357. mProperties.mHeight = height;
  358. mSwapChain->ResizeTarget(&nearestMode);
  359. mSwapChain->SetFullscreenState(true, outputInfo.getDXGIOutput());
  360. {
  361. ScopedSpinLock lock(mLock);
  362. mSyncedProperties.mTop = mProperties.mTop;
  363. mSyncedProperties.mLeft = mProperties.mLeft;
  364. mSyncedProperties.mWidth = mProperties.mWidth;
  365. mSyncedProperties.mHeight = mProperties.mHeight;
  366. }
  367. RenderWindowManager::instance().notifySyncDataDirty(this);
  368. RenderWindowManager::instance().notifyMovedOrResized(this);
  369. }
  370. void D3D11RenderWindowCore::setFullscreen(const VideoMode& mode)
  371. {
  372. THROW_IF_NOT_CORE_THREAD;
  373. if (mIsChild)
  374. return;
  375. if (mode.isCustom())
  376. {
  377. setFullscreen(mode.getWidth(), mode.getHeight(), mode.getRefreshRate(), mode.getOutputIdx());
  378. return;
  379. }
  380. const D3D11VideoModeInfo& videoModeInfo = static_cast<const D3D11VideoModeInfo&>(RenderAPICore::instance().getVideoModeInfo());
  381. UINT32 numOutputs = videoModeInfo.getNumOutputs();
  382. if (numOutputs == 0)
  383. return;
  384. UINT32 actualMonitorIdx = std::min(mode.getOutputIdx(), numOutputs - 1);
  385. const D3D11VideoOutputInfo& outputInfo = static_cast<const D3D11VideoOutputInfo&>(videoModeInfo.getOutputInfo(actualMonitorIdx));
  386. const D3D11VideoMode& videoMode = static_cast<const D3D11VideoMode&>(mode);
  387. mProperties.mIsFullScreen = true;
  388. mProperties.mWidth = mode.getWidth();
  389. mProperties.mHeight = mode.getHeight();
  390. mSwapChain->ResizeTarget(&videoMode.getDXGIModeDesc());
  391. mSwapChain->SetFullscreenState(true, outputInfo.getDXGIOutput());
  392. {
  393. ScopedSpinLock lock(mLock);
  394. mSyncedProperties.mTop = mProperties.mTop;
  395. mSyncedProperties.mLeft = mProperties.mLeft;
  396. mSyncedProperties.mWidth = mProperties.mWidth;
  397. mSyncedProperties.mHeight = mProperties.mHeight;
  398. }
  399. RenderWindowManager::instance().notifySyncDataDirty(this);
  400. RenderWindowManager::instance().notifyMovedOrResized(this);
  401. }
  402. void D3D11RenderWindowCore::setWindowed(UINT32 width, UINT32 height)
  403. {
  404. THROW_IF_NOT_CORE_THREAD;
  405. mProperties.mWidth = width;
  406. mProperties.mHeight = height;
  407. mProperties.mIsFullScreen = false;
  408. mSwapChainDesc.Windowed = true;
  409. mSwapChainDesc.BufferDesc.RefreshRate.Numerator = 0;
  410. mSwapChainDesc.BufferDesc.RefreshRate.Denominator = 0;
  411. mSwapChainDesc.BufferDesc.Width = width;
  412. mSwapChainDesc.BufferDesc.Height = height;
  413. DXGI_MODE_DESC modeDesc;
  414. ZeroMemory(&modeDesc, sizeof(modeDesc));
  415. modeDesc.Width = width;
  416. modeDesc.Height = height;
  417. modeDesc.RefreshRate.Numerator = 0;
  418. modeDesc.RefreshRate.Denominator = 0;
  419. modeDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
  420. mSwapChain->SetFullscreenState(false, nullptr);
  421. mSwapChain->ResizeTarget(&modeDesc);
  422. {
  423. ScopedSpinLock lock(mLock);
  424. mSyncedProperties.mTop = mProperties.mTop;
  425. mSyncedProperties.mLeft = mProperties.mLeft;
  426. mSyncedProperties.mWidth = mProperties.mWidth;
  427. mSyncedProperties.mHeight = mProperties.mHeight;
  428. }
  429. RenderWindowManager::instance().notifySyncDataDirty(this);
  430. RenderWindowManager::instance().notifyMovedOrResized(this);
  431. }
  432. HWND D3D11RenderWindowCore::_getWindowHandle() const
  433. {
  434. return mHWnd;
  435. }
  436. void D3D11RenderWindowCore::getCustomAttribute(const String& name, void* pData) const
  437. {
  438. if(name == "WINDOW")
  439. {
  440. UINT64 *pWnd = (UINT64*)pData;
  441. *pWnd = (UINT64)mHWnd;
  442. return;
  443. }
  444. if(name == "RTV")
  445. {
  446. *static_cast<ID3D11RenderTargetView**>(pData) = mRenderTargetView;
  447. return;
  448. }
  449. else if(name == "DSV")
  450. {
  451. if (mDepthStencilView != nullptr)
  452. {
  453. D3D11TextureView* d3d11TextureView = static_cast<D3D11TextureView*>(mDepthStencilView.get());
  454. *static_cast<ID3D11DepthStencilView**>(pData) = d3d11TextureView->getDSV();
  455. }
  456. else
  457. {
  458. *static_cast<ID3D11DepthStencilView**>(pData) = nullptr;
  459. }
  460. return;
  461. }
  462. RenderWindowCore::getCustomAttribute(name, pData);
  463. }
  464. void D3D11RenderWindowCore::copyToMemory(PixelData &dst, FrameBuffer buffer)
  465. {
  466. THROW_IF_NOT_CORE_THREAD;
  467. if(mBackBuffer == nullptr)
  468. return;
  469. // Get the backbuffer desc
  470. D3D11_TEXTURE2D_DESC BBDesc;
  471. mBackBuffer->GetDesc(&BBDesc);
  472. ID3D11Texture2D* backbuffer = nullptr;
  473. if(BBDesc.SampleDesc.Quality > 0)
  474. {
  475. D3D11_TEXTURE2D_DESC desc = BBDesc;
  476. desc.Usage = D3D11_USAGE_DEFAULT;
  477. desc.CPUAccessFlags = 0;
  478. desc.BindFlags = 0;
  479. desc.SampleDesc.Quality = 0;
  480. desc.SampleDesc.Count = 1;
  481. HRESULT hr = mDevice.getD3D11Device()->CreateTexture2D(&desc, nullptr, &backbuffer);
  482. if (FAILED(hr) || mDevice.hasError())
  483. {
  484. String errorDescription = mDevice.getErrorDescription();
  485. BS_EXCEPT(RenderingAPIException, "Error creating texture\nError Description:" + errorDescription);
  486. }
  487. mDevice.getImmediateContext()->ResolveSubresource(backbuffer, D3D11CalcSubresource(0, 0, 1), mBackBuffer, D3D11CalcSubresource(0, 0, 1), desc.Format);
  488. }
  489. // Change the parameters of the texture so we can read it
  490. BBDesc.Usage = D3D11_USAGE_STAGING;
  491. BBDesc.CPUAccessFlags = D3D11_CPU_ACCESS_READ;
  492. BBDesc.BindFlags = 0;
  493. BBDesc.SampleDesc.Quality = 0;
  494. BBDesc.SampleDesc.Count = 1;
  495. // Create a temp buffer to copy to
  496. ID3D11Texture2D* tempTexture;
  497. HRESULT hr = mDevice.getD3D11Device()->CreateTexture2D(&BBDesc, nullptr, &tempTexture);
  498. if (FAILED(hr) || mDevice.hasError())
  499. {
  500. String errorDescription = mDevice.getErrorDescription();
  501. BS_EXCEPT(RenderingAPIException, "Error creating texture\nError Description:" + errorDescription);
  502. }
  503. // Copy the back buffer
  504. mDevice.getImmediateContext()->CopyResource(tempTexture, backbuffer != NULL ? backbuffer : mBackBuffer);
  505. // Map the copied texture
  506. D3D11_MAPPED_SUBRESOURCE mappedTex2D;
  507. mDevice.getImmediateContext()->Map(tempTexture, 0,D3D11_MAP_READ, 0, &mappedTex2D);
  508. // Copy the the texture to the dest
  509. PixelData src(getProperties().getWidth(), getProperties().getHeight(), 1, PF_A8B8G8R8);
  510. src.setExternalBuffer((UINT8*)mappedTex2D.pData);
  511. PixelUtil::bulkPixelConversion(src, dst);
  512. // Unmap the temp buffer
  513. mDevice.getImmediateContext()->Unmap(tempTexture, 0);
  514. // Release the temp buffer
  515. SAFE_RELEASE(tempTexture);
  516. SAFE_RELEASE(backbuffer);
  517. }
  518. void D3D11RenderWindowCore::_windowMovedOrResized()
  519. {
  520. THROW_IF_NOT_CORE_THREAD;
  521. D3D11RenderWindowProperties& props = mProperties;
  522. if (!mHWnd || IsIconic(mHWnd))
  523. return;
  524. RECT rc;
  525. GetWindowRect(mHWnd, &rc);
  526. mProperties.mTop = rc.top;
  527. mProperties.mLeft = rc.left;
  528. GetClientRect(mHWnd, &rc);
  529. unsigned int width = rc.right - rc.left;
  530. unsigned int height = rc.bottom - rc.top;
  531. if (width == 0)
  532. width = 1;
  533. if (height == 0)
  534. height = 1;
  535. resizeSwapChainBuffers(width, height);
  536. RenderWindowCore::_windowMovedOrResized();
  537. }
  538. void D3D11RenderWindowCore::createSwapChain()
  539. {
  540. ZeroMemory(&mSwapChainDesc, sizeof(DXGI_SWAP_CHAIN_DESC));
  541. D3D11RenderWindowProperties& props = mProperties;
  542. IDXGIDevice* pDXGIDevice = queryDxgiDevice();
  543. ZeroMemory(&mSwapChainDesc, sizeof(DXGI_SWAP_CHAIN_DESC));
  544. DXGI_FORMAT format = DXGI_FORMAT_R8G8B8A8_UNORM;
  545. mSwapChainDesc.OutputWindow = mHWnd;
  546. mSwapChainDesc.BufferDesc.Width = props.mWidth;
  547. mSwapChainDesc.BufferDesc.Height = props.mHeight;
  548. mSwapChainDesc.BufferDesc.Format = format;
  549. if (props.mIsFullScreen)
  550. {
  551. mSwapChainDesc.BufferDesc.RefreshRate.Numerator = mRefreshRateNumerator;
  552. mSwapChainDesc.BufferDesc.RefreshRate.Denominator = mRefreshRateDenominator;
  553. }
  554. else
  555. {
  556. mSwapChainDesc.BufferDesc.RefreshRate.Numerator = 0;
  557. mSwapChainDesc.BufferDesc.RefreshRate.Denominator = 0;
  558. }
  559. mSwapChainDesc.BufferDesc.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED;
  560. mSwapChainDesc.BufferDesc.Scaling = DXGI_MODE_SCALING_UNSPECIFIED;
  561. mSwapChainDesc.Flags = DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH ;
  562. mSwapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
  563. mSwapChainDesc.BufferCount = 1;
  564. mSwapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_DISCARD ;
  565. mSwapChainDesc.Windowed = true;
  566. D3D11RenderAPI* rs = static_cast<D3D11RenderAPI*>(RenderAPICore::instancePtr());
  567. rs->determineMultisampleSettings(props.mMultisampleCount, format, &mMultisampleType);
  568. mSwapChainDesc.SampleDesc.Count = mMultisampleType.Count;
  569. mSwapChainDesc.SampleDesc.Quality = mMultisampleType.Quality;
  570. HRESULT hr;
  571. // Create swap chain
  572. hr = mDXGIFactory->CreateSwapChain(pDXGIDevice, &mSwapChainDesc, &mSwapChain);
  573. if (FAILED(hr))
  574. {
  575. // Try a second time, may fail the first time due to back buffer count,
  576. // which will be corrected by the runtime
  577. hr = mDXGIFactory->CreateSwapChain(pDXGIDevice, &mSwapChainDesc, &mSwapChain);
  578. }
  579. SAFE_RELEASE(pDXGIDevice);
  580. if (FAILED(hr))
  581. BS_EXCEPT(RenderingAPIException, "Unable to create swap chain");
  582. BS_INC_RENDER_STAT_CAT(ResCreated, RenderStatObject_SwapChain);
  583. }
  584. void D3D11RenderWindowCore::createSizeDependedD3DResources()
  585. {
  586. SAFE_RELEASE(mBackBuffer);
  587. HRESULT hr = mSwapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), (LPVOID*)&mBackBuffer);
  588. if(FAILED(hr))
  589. BS_EXCEPT(RenderingAPIException, "Unable to Get Back Buffer for swap chain");
  590. assert(mBackBuffer && !mRenderTargetView);
  591. D3D11_TEXTURE2D_DESC BBDesc;
  592. mBackBuffer->GetDesc(&BBDesc);
  593. D3D11_RENDER_TARGET_VIEW_DESC RTVDesc;
  594. ZeroMemory( &RTVDesc, sizeof(RTVDesc) );
  595. RTVDesc.Format = BBDesc.Format;
  596. RTVDesc.ViewDimension = getProperties().getMultisampleCount() > 1 ? D3D11_RTV_DIMENSION_TEXTURE2DMS : D3D11_RTV_DIMENSION_TEXTURE2D;
  597. RTVDesc.Texture2D.MipSlice = 0;
  598. hr = mDevice.getD3D11Device()->CreateRenderTargetView(mBackBuffer, &RTVDesc, &mRenderTargetView);
  599. if(FAILED(hr))
  600. {
  601. String errorDescription = mDevice.getErrorDescription();
  602. BS_EXCEPT(RenderingAPIException, "Unable to create rendertagert view\nError Description:" + errorDescription);
  603. }
  604. if (mDepthStencilView != nullptr)
  605. {
  606. TextureCore::releaseView(mDepthStencilView);
  607. mDepthStencilView = nullptr;
  608. }
  609. if (mDesc.depthBuffer)
  610. {
  611. mDepthStencilBuffer = TextureCoreManager::instance().createTexture(TEX_TYPE_2D,
  612. BBDesc.Width, BBDesc.Height, 0, 0, PF_D24S8, TU_DEPTHSTENCIL, false,
  613. getProperties().getMultisampleCount());
  614. mDepthStencilView = TextureCore::requestView(mDepthStencilBuffer, 0, 1, 0, 1, GVU_DEPTHSTENCIL);
  615. }
  616. else
  617. mDepthStencilBuffer = nullptr;
  618. }
  619. void D3D11RenderWindowCore::destroySizeDependedD3DResources()
  620. {
  621. SAFE_RELEASE(mBackBuffer);
  622. SAFE_RELEASE(mRenderTargetView);
  623. mDepthStencilBuffer = nullptr;
  624. }
  625. void D3D11RenderWindowCore::resizeSwapChainBuffers(UINT32 width, UINT32 height)
  626. {
  627. destroySizeDependedD3DResources();
  628. UINT Flags = mProperties.isFullScreen() ? DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH : 0;
  629. HRESULT hr = mSwapChain->ResizeBuffers(mSwapChainDesc.BufferCount, width, height, mSwapChainDesc.BufferDesc.Format, Flags);
  630. if(hr != S_OK)
  631. BS_EXCEPT(InternalErrorException, "Call to ResizeBuffers failed.");
  632. mSwapChain->GetDesc(&mSwapChainDesc);
  633. mProperties.mWidth = mSwapChainDesc.BufferDesc.Width;
  634. mProperties.mHeight = mSwapChainDesc.BufferDesc.Height;
  635. mProperties.mIsFullScreen = (0 == mSwapChainDesc.Windowed); // Alt-Enter together with SetWindowAssociation() can change this state
  636. createSizeDependedD3DResources();
  637. mDevice.getImmediateContext()->OMSetRenderTargets(0, 0, 0);
  638. }
  639. IDXGIDevice* D3D11RenderWindowCore::queryDxgiDevice()
  640. {
  641. if (mDevice.getD3D11Device() == nullptr)
  642. {
  643. BS_EXCEPT(RenderingAPIException, "D3D11Device is null.");
  644. }
  645. IDXGIDevice* pDXGIDevice = nullptr;
  646. HRESULT hr = mDevice.getD3D11Device()->QueryInterface(__uuidof(IDXGIDevice), (void**)&pDXGIDevice);
  647. if(FAILED(hr))
  648. BS_EXCEPT(RenderingAPIException, "Unable to query a DXGIDevice.");
  649. return pDXGIDevice;
  650. }
  651. void D3D11RenderWindowCore::syncProperties()
  652. {
  653. ScopedSpinLock lock(mLock);
  654. mProperties = mSyncedProperties;
  655. }
  656. D3D11RenderWindow::D3D11RenderWindow(const RENDER_WINDOW_DESC& desc, UINT32 windowId, D3D11Device& device, IDXGIFactory* DXGIFactory)
  657. :RenderWindow(desc, windowId), mProperties(desc), mDevice(device), mDXGIFactory(DXGIFactory)
  658. {
  659. }
  660. void D3D11RenderWindow::getCustomAttribute(const String& name, void* pData) const
  661. {
  662. if (name == "WINDOW")
  663. {
  664. UINT64 *pHwnd = (UINT64*)pData;
  665. *pHwnd = (UINT64)getHWnd();
  666. return;
  667. }
  668. }
  669. Vector2I D3D11RenderWindow::screenToWindowPos(const Vector2I& screenPos) const
  670. {
  671. POINT pos;
  672. pos.x = screenPos.x;
  673. pos.y = screenPos.y;
  674. ScreenToClient(getHWnd(), &pos);
  675. return Vector2I(pos.x, pos.y);
  676. }
  677. Vector2I D3D11RenderWindow::windowToScreenPos(const Vector2I& windowPos) const
  678. {
  679. POINT pos;
  680. pos.x = windowPos.x;
  681. pos.y = windowPos.y;
  682. ClientToScreen(getHWnd(), &pos);
  683. return Vector2I(pos.x, pos.y);
  684. }
  685. SPtr<D3D11RenderWindowCore> D3D11RenderWindow::getCore() const
  686. {
  687. return std::static_pointer_cast<D3D11RenderWindowCore>(mCoreSpecific);
  688. }
  689. HWND D3D11RenderWindow::getHWnd() const
  690. {
  691. // HACK: I'm accessing core method from sim thread, which means an invalid handle
  692. // could be returned here if requested too soon after initialization.
  693. return getCore()->_getWindowHandle();
  694. }
  695. void D3D11RenderWindow::syncProperties()
  696. {
  697. ScopedSpinLock lock(getCore()->mLock);
  698. mProperties = getCore()->mSyncedProperties;
  699. }
  700. }