BsD3D11RenderWindow.cpp 24 KB

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