BsD3D11RenderWindow.cpp 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879
  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. D3D11TextureView* d3d11TextureView = static_cast<D3D11TextureView*>(mDepthStencilView.get());
  452. *static_cast<ID3D11DepthStencilView**>(pData) = d3d11TextureView->getDSV();
  453. return;
  454. }
  455. RenderWindowCore::getCustomAttribute(name, pData);
  456. }
  457. void D3D11RenderWindowCore::copyToMemory(PixelData &dst, FrameBuffer buffer)
  458. {
  459. THROW_IF_NOT_CORE_THREAD;
  460. if(mBackBuffer == nullptr)
  461. return;
  462. // Get the backbuffer desc
  463. D3D11_TEXTURE2D_DESC BBDesc;
  464. mBackBuffer->GetDesc(&BBDesc);
  465. ID3D11Texture2D* backbuffer = nullptr;
  466. if(BBDesc.SampleDesc.Quality > 0)
  467. {
  468. D3D11_TEXTURE2D_DESC desc = BBDesc;
  469. desc.Usage = D3D11_USAGE_DEFAULT;
  470. desc.CPUAccessFlags = 0;
  471. desc.BindFlags = 0;
  472. desc.SampleDesc.Quality = 0;
  473. desc.SampleDesc.Count = 1;
  474. HRESULT hr = mDevice.getD3D11Device()->CreateTexture2D(&desc, nullptr, &backbuffer);
  475. if (FAILED(hr) || mDevice.hasError())
  476. {
  477. String errorDescription = mDevice.getErrorDescription();
  478. BS_EXCEPT(RenderingAPIException, "Error creating texture\nError Description:" + errorDescription);
  479. }
  480. mDevice.getImmediateContext()->ResolveSubresource(backbuffer, D3D11CalcSubresource(0, 0, 1), mBackBuffer, D3D11CalcSubresource(0, 0, 1), desc.Format);
  481. }
  482. // Change the parameters of the texture so we can read it
  483. BBDesc.Usage = D3D11_USAGE_STAGING;
  484. BBDesc.CPUAccessFlags = D3D11_CPU_ACCESS_READ;
  485. BBDesc.BindFlags = 0;
  486. BBDesc.SampleDesc.Quality = 0;
  487. BBDesc.SampleDesc.Count = 1;
  488. // Create a temp buffer to copy to
  489. ID3D11Texture2D* tempTexture;
  490. HRESULT hr = mDevice.getD3D11Device()->CreateTexture2D(&BBDesc, nullptr, &tempTexture);
  491. if (FAILED(hr) || mDevice.hasError())
  492. {
  493. String errorDescription = mDevice.getErrorDescription();
  494. BS_EXCEPT(RenderingAPIException, "Error creating texture\nError Description:" + errorDescription);
  495. }
  496. // Copy the back buffer
  497. mDevice.getImmediateContext()->CopyResource(tempTexture, backbuffer != NULL ? backbuffer : mBackBuffer);
  498. // Map the copied texture
  499. D3D11_MAPPED_SUBRESOURCE mappedTex2D;
  500. mDevice.getImmediateContext()->Map(tempTexture, 0,D3D11_MAP_READ, 0, &mappedTex2D);
  501. // Copy the the texture to the dest
  502. PixelData src(getProperties().getWidth(), getProperties().getHeight(), 1, PF_A8B8G8R8);
  503. src.setExternalBuffer((UINT8*)mappedTex2D.pData);
  504. PixelUtil::bulkPixelConversion(src, dst);
  505. // Unmap the temp buffer
  506. mDevice.getImmediateContext()->Unmap(tempTexture, 0);
  507. // Release the temp buffer
  508. SAFE_RELEASE(tempTexture);
  509. SAFE_RELEASE(backbuffer);
  510. }
  511. void D3D11RenderWindowCore::_windowMovedOrResized()
  512. {
  513. THROW_IF_NOT_CORE_THREAD;
  514. D3D11RenderWindowProperties& props = mProperties;
  515. if (!mHWnd || IsIconic(mHWnd))
  516. return;
  517. RECT rc;
  518. GetWindowRect(mHWnd, &rc);
  519. mProperties.mTop = rc.top;
  520. mProperties.mLeft = rc.left;
  521. GetClientRect(mHWnd, &rc);
  522. unsigned int width = rc.right - rc.left;
  523. unsigned int height = rc.bottom - rc.top;
  524. if (width == 0)
  525. width = 1;
  526. if (height == 0)
  527. height = 1;
  528. resizeSwapChainBuffers(width, height);
  529. RenderWindowCore::_windowMovedOrResized();
  530. }
  531. void D3D11RenderWindowCore::createSwapChain()
  532. {
  533. ZeroMemory(&mSwapChainDesc, sizeof(DXGI_SWAP_CHAIN_DESC));
  534. D3D11RenderWindowProperties& props = mProperties;
  535. IDXGIDevice* pDXGIDevice = queryDxgiDevice();
  536. ZeroMemory(&mSwapChainDesc, sizeof(DXGI_SWAP_CHAIN_DESC));
  537. DXGI_FORMAT format = DXGI_FORMAT_R8G8B8A8_UNORM;
  538. mSwapChainDesc.OutputWindow = mHWnd;
  539. mSwapChainDesc.BufferDesc.Width = props.mWidth;
  540. mSwapChainDesc.BufferDesc.Height = props.mHeight;
  541. mSwapChainDesc.BufferDesc.Format = format;
  542. if (props.mIsFullScreen)
  543. {
  544. mSwapChainDesc.BufferDesc.RefreshRate.Numerator = mRefreshRateNumerator;
  545. mSwapChainDesc.BufferDesc.RefreshRate.Denominator = mRefreshRateDenominator;
  546. }
  547. else
  548. {
  549. mSwapChainDesc.BufferDesc.RefreshRate.Numerator = 0;
  550. mSwapChainDesc.BufferDesc.RefreshRate.Denominator = 0;
  551. }
  552. mSwapChainDesc.BufferDesc.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED;
  553. mSwapChainDesc.BufferDesc.Scaling = DXGI_MODE_SCALING_UNSPECIFIED;
  554. mSwapChainDesc.Flags = DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH ;
  555. mSwapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
  556. mSwapChainDesc.BufferCount = 1;
  557. mSwapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_DISCARD ;
  558. mSwapChainDesc.Windowed = true;
  559. D3D11RenderAPI* rs = static_cast<D3D11RenderAPI*>(RenderAPICore::instancePtr());
  560. rs->determineMultisampleSettings(props.mMultisampleCount, format, &mMultisampleType);
  561. mSwapChainDesc.SampleDesc.Count = mMultisampleType.Count;
  562. mSwapChainDesc.SampleDesc.Quality = mMultisampleType.Quality;
  563. HRESULT hr;
  564. // Create swap chain
  565. hr = mDXGIFactory->CreateSwapChain(pDXGIDevice, &mSwapChainDesc, &mSwapChain);
  566. if (FAILED(hr))
  567. {
  568. // Try a second time, may fail the first time due to back buffer count,
  569. // which will be corrected by the runtime
  570. hr = mDXGIFactory->CreateSwapChain(pDXGIDevice, &mSwapChainDesc, &mSwapChain);
  571. }
  572. SAFE_RELEASE(pDXGIDevice);
  573. if (FAILED(hr))
  574. BS_EXCEPT(RenderingAPIException, "Unable to create swap chain");
  575. BS_INC_RENDER_STAT_CAT(ResCreated, RenderStatObject_SwapChain);
  576. }
  577. void D3D11RenderWindowCore::createSizeDependedD3DResources()
  578. {
  579. SAFE_RELEASE(mBackBuffer);
  580. HRESULT hr = mSwapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), (LPVOID*)&mBackBuffer);
  581. if(FAILED(hr))
  582. BS_EXCEPT(RenderingAPIException, "Unable to Get Back Buffer for swap chain");
  583. assert(mBackBuffer && !mRenderTargetView);
  584. D3D11_TEXTURE2D_DESC BBDesc;
  585. mBackBuffer->GetDesc(&BBDesc);
  586. D3D11_RENDER_TARGET_VIEW_DESC RTVDesc;
  587. ZeroMemory( &RTVDesc, sizeof(RTVDesc) );
  588. RTVDesc.Format = BBDesc.Format;
  589. RTVDesc.ViewDimension = getProperties().getMultisampleCount() ? D3D11_RTV_DIMENSION_TEXTURE2DMS : D3D11_RTV_DIMENSION_TEXTURE2D;
  590. RTVDesc.Texture2D.MipSlice = 0;
  591. hr = mDevice.getD3D11Device()->CreateRenderTargetView(mBackBuffer, &RTVDesc, &mRenderTargetView);
  592. if(FAILED(hr))
  593. {
  594. String errorDescription = mDevice.getErrorDescription();
  595. BS_EXCEPT(RenderingAPIException, "Unable to create rendertagert view\nError Description:" + errorDescription);
  596. }
  597. mDepthStencilBuffer = TextureCoreManager::instance().createTexture(TEX_TYPE_2D,
  598. BBDesc.Width, BBDesc.Height, 0, 0, PF_D24S8, TU_DEPTHSTENCIL, false,
  599. getProperties().getMultisampleCount());
  600. if(mDepthStencilView != nullptr)
  601. {
  602. TextureCore::releaseView(mDepthStencilView);
  603. mDepthStencilView = nullptr;
  604. }
  605. mDepthStencilView = TextureCore::requestView(mDepthStencilBuffer, 0, 1, 0, 1, GVU_DEPTHSTENCIL);
  606. }
  607. void D3D11RenderWindowCore::destroySizeDependedD3DResources()
  608. {
  609. SAFE_RELEASE(mBackBuffer);
  610. SAFE_RELEASE(mRenderTargetView);
  611. mDepthStencilBuffer = nullptr;
  612. }
  613. void D3D11RenderWindowCore::resizeSwapChainBuffers(UINT32 width, UINT32 height)
  614. {
  615. destroySizeDependedD3DResources();
  616. UINT Flags = mProperties.isFullScreen() ? DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH : 0;
  617. HRESULT hr = mSwapChain->ResizeBuffers(mSwapChainDesc.BufferCount, width, height, mSwapChainDesc.BufferDesc.Format, Flags);
  618. if(hr != S_OK)
  619. BS_EXCEPT(InternalErrorException, "Call to ResizeBuffers failed.");
  620. mSwapChain->GetDesc(&mSwapChainDesc);
  621. mProperties.mWidth = mSwapChainDesc.BufferDesc.Width;
  622. mProperties.mHeight = mSwapChainDesc.BufferDesc.Height;
  623. mProperties.mIsFullScreen = (0 == mSwapChainDesc.Windowed); // Alt-Enter together with SetWindowAssociation() can change this state
  624. createSizeDependedD3DResources();
  625. mDevice.getImmediateContext()->OMSetRenderTargets(0, 0, 0);
  626. }
  627. IDXGIDevice* D3D11RenderWindowCore::queryDxgiDevice()
  628. {
  629. if (mDevice.getD3D11Device() == nullptr)
  630. {
  631. BS_EXCEPT(RenderingAPIException, "D3D11Device is null.");
  632. }
  633. IDXGIDevice* pDXGIDevice = nullptr;
  634. HRESULT hr = mDevice.getD3D11Device()->QueryInterface(__uuidof(IDXGIDevice), (void**)&pDXGIDevice);
  635. if(FAILED(hr))
  636. BS_EXCEPT(RenderingAPIException, "Unable to query a DXGIDevice.");
  637. return pDXGIDevice;
  638. }
  639. void D3D11RenderWindowCore::syncProperties()
  640. {
  641. ScopedSpinLock lock(mLock);
  642. mProperties = mSyncedProperties;
  643. }
  644. D3D11RenderWindow::D3D11RenderWindow(const RENDER_WINDOW_DESC& desc, UINT32 windowId, D3D11Device& device, IDXGIFactory* DXGIFactory)
  645. :RenderWindow(desc, windowId), mProperties(desc), mDevice(device), mDXGIFactory(DXGIFactory)
  646. {
  647. }
  648. void D3D11RenderWindow::getCustomAttribute(const String& name, void* pData) const
  649. {
  650. if (name == "WINDOW")
  651. {
  652. UINT64 *pHwnd = (UINT64*)pData;
  653. *pHwnd = (UINT64)getHWnd();
  654. return;
  655. }
  656. }
  657. Vector2I D3D11RenderWindow::screenToWindowPos(const Vector2I& screenPos) const
  658. {
  659. POINT pos;
  660. pos.x = screenPos.x;
  661. pos.y = screenPos.y;
  662. ScreenToClient(getHWnd(), &pos);
  663. return Vector2I(pos.x, pos.y);
  664. }
  665. Vector2I D3D11RenderWindow::windowToScreenPos(const Vector2I& windowPos) const
  666. {
  667. POINT pos;
  668. pos.x = windowPos.x;
  669. pos.y = windowPos.y;
  670. ClientToScreen(getHWnd(), &pos);
  671. return Vector2I(pos.x, pos.y);
  672. }
  673. SPtr<D3D11RenderWindowCore> D3D11RenderWindow::getCore() const
  674. {
  675. return std::static_pointer_cast<D3D11RenderWindowCore>(mCoreSpecific);
  676. }
  677. HWND D3D11RenderWindow::getHWnd() const
  678. {
  679. // HACK: I'm accessing core method from sim thread, which means an invalid handle
  680. // could be returned here if requested too soon after initialization.
  681. return getCore()->_getWindowHandle();
  682. }
  683. void D3D11RenderWindow::syncProperties()
  684. {
  685. ScopedSpinLock lock(getCore()->mLock);
  686. mProperties = getCore()->mSyncedProperties;
  687. }
  688. }