CmD3D9Device.cpp 42 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381
  1. /*
  2. -----------------------------------------------------------------------------
  3. This source file is part of OGRE
  4. (Object-oriented Graphics Rendering Engine)
  5. For the latest info, see http://www.ogre3d.org/
  6. Copyright (c) 2000-2011 Torus Knot Software Ltd
  7. Permission is hereby granted, free of charge, to any person obtaining a copy
  8. of this software and associated documentation files (the "Software"), to deal
  9. in the Software without restriction, including without limitation the rights
  10. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  11. copies of the Software, and to permit persons to whom the Software is
  12. furnished to do so, subject to the following conditions:
  13. The above copyright notice and this permission notice shall be included in
  14. all copies or substantial portions of the Software.
  15. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  21. THE SOFTWARE.
  22. -----------------------------------------------------------------------------
  23. */
  24. #include "CmD3D9Device.h"
  25. #include "CmD3D9DeviceManager.h"
  26. #include "CmD3D9Driver.h"
  27. #include "CmD3D9RenderSystem.h"
  28. #include "CmD3D9ResourceManager.h"
  29. #include "CmD3D9RenderWindow.h"
  30. #include "CmHardwareBufferManager.h"
  31. #include "CmException.h"
  32. #include "CmRenderSystemManager.h"
  33. namespace CamelotEngine
  34. {
  35. HWND D3D9Device::msSharedFocusWindow = NULL;
  36. //---------------------------------------------------------------------
  37. D3D9Device::D3D9Device(D3D9DeviceManager* deviceManager,
  38. UINT adapterNumber,
  39. HMONITOR hMonitor,
  40. D3DDEVTYPE devType,
  41. DWORD behaviorFlags)
  42. {
  43. mpDeviceManager = deviceManager;
  44. mpDevice = NULL;
  45. mAdapterNumber = adapterNumber;
  46. mMonitor = hMonitor;
  47. mDeviceType = devType;
  48. mFocusWindow = NULL;
  49. mBehaviorFlags = behaviorFlags;
  50. mD3D9DeviceCapsValid = false;
  51. mDeviceLost = false;
  52. mPresentationParamsCount = 0;
  53. mPresentationParams = NULL;
  54. memset(&mD3D9DeviceCaps, 0, sizeof(mD3D9DeviceCaps));
  55. memset(&mCreationParams, 0, sizeof(mCreationParams));
  56. }
  57. //---------------------------------------------------------------------
  58. D3D9Device::~D3D9Device()
  59. {
  60. }
  61. //---------------------------------------------------------------------
  62. D3D9Device::RenderWindowToResorucesIterator D3D9Device::getRenderWindowIterator(D3D9RenderWindow* renderWindow)
  63. {
  64. RenderWindowToResorucesIterator it = mMapRenderWindowToResoruces.find(renderWindow);
  65. if (it == mMapRenderWindowToResoruces.end())
  66. {
  67. CM_EXCEPT(RenderingAPIException,
  68. "Render window was not attached to this device !!");
  69. }
  70. return it;
  71. }
  72. //---------------------------------------------------------------------
  73. void D3D9Device::attachRenderWindow(D3D9RenderWindow* renderWindow)
  74. {
  75. RenderWindowToResorucesIterator it = mMapRenderWindowToResoruces.find(renderWindow);
  76. if (it == mMapRenderWindowToResoruces.end())
  77. {
  78. RenderWindowResources* renderWindowResources = new RenderWindowResources;
  79. memset(renderWindowResources, 0, sizeof(RenderWindowResources));
  80. renderWindowResources->adapterOrdinalInGroupIndex = 0;
  81. renderWindowResources->acquired = false;
  82. mMapRenderWindowToResoruces[renderWindow] = renderWindowResources;
  83. }
  84. updateRenderWindowsIndices();
  85. }
  86. //---------------------------------------------------------------------
  87. void D3D9Device::detachRenderWindow(D3D9RenderWindow* renderWindow)
  88. {
  89. RenderWindowToResorucesIterator it = mMapRenderWindowToResoruces.find(renderWindow);
  90. if (it != mMapRenderWindowToResoruces.end())
  91. {
  92. // The focus window in which the d3d9 device created on is detached.
  93. // resources must be acquired again.
  94. if (mFocusWindow == renderWindow->getWindowHandle())
  95. {
  96. mFocusWindow = NULL;
  97. }
  98. // Case this is the shared focus window.
  99. if (renderWindow->getWindowHandle() == msSharedFocusWindow)
  100. setSharedWindowHandle(NULL);
  101. RenderWindowResources* renderWindowResources = it->second;
  102. releaseRenderWindowResources(renderWindowResources);
  103. SAFE_DELETE(renderWindowResources);
  104. mMapRenderWindowToResoruces.erase(it);
  105. }
  106. updateRenderWindowsIndices();
  107. }
  108. //---------------------------------------------------------------------
  109. bool D3D9Device::acquire()
  110. {
  111. updatePresentationParameters();
  112. bool resetDevice = false;
  113. // Create device if need to.
  114. if (mpDevice == NULL)
  115. {
  116. createD3D9Device();
  117. }
  118. // Case device already exists.
  119. else
  120. {
  121. RenderWindowToResorucesIterator itPrimary = getRenderWindowIterator(getPrimaryWindow());
  122. if (itPrimary->second->swapChain != NULL)
  123. {
  124. D3DPRESENT_PARAMETERS currentPresentParams;
  125. HRESULT hr;
  126. hr = itPrimary->second->swapChain->GetPresentParameters(&currentPresentParams);
  127. if (FAILED(hr))
  128. {
  129. CM_EXCEPT(RenderingAPIException, "GetPresentParameters failed");
  130. }
  131. // Desired parameters are different then current parameters.
  132. // Possible scenario is that primary window resized and in the mean while another
  133. // window attached to this device.
  134. if (memcmp(&currentPresentParams, &mPresentationParams[0], sizeof(D3DPRESENT_PARAMETERS)) != 0)
  135. {
  136. resetDevice = true;
  137. }
  138. }
  139. // Make sure depth stencil is set to valid surface. It is going to be
  140. // grabbed by the primary window using the GetDepthStencilSurface method.
  141. if (resetDevice == false)
  142. {
  143. mpDevice->SetDepthStencilSurface(itPrimary->second->depthBuffer);
  144. }
  145. }
  146. // Reset device will update all render window resources.
  147. if (resetDevice)
  148. {
  149. reset();
  150. }
  151. // No need to reset -> just acquire resources.
  152. else
  153. {
  154. // Update resources of each window.
  155. RenderWindowToResorucesIterator it = mMapRenderWindowToResoruces.begin();
  156. while (it != mMapRenderWindowToResoruces.end())
  157. {
  158. acquireRenderWindowResources(it);
  159. ++it;
  160. }
  161. }
  162. return true;
  163. }
  164. //---------------------------------------------------------------------
  165. void D3D9Device::release()
  166. {
  167. if (mpDevice != NULL)
  168. {
  169. D3D9RenderSystem* renderSystem = static_cast<D3D9RenderSystem*>(CamelotEngine::RenderSystemManager::getActive());
  170. //// Clean up depth stencil surfaces
  171. //renderSystem->_cleanupDepthStencils(mpDevice);
  172. RenderWindowToResorucesIterator it = mMapRenderWindowToResoruces.begin();
  173. while (it != mMapRenderWindowToResoruces.end())
  174. {
  175. RenderWindowResources* renderWindowResources = it->second;
  176. releaseRenderWindowResources(renderWindowResources);
  177. ++it;
  178. }
  179. releaseD3D9Device();
  180. }
  181. }
  182. //---------------------------------------------------------------------
  183. bool D3D9Device::acquire(D3D9RenderWindow* renderWindow)
  184. {
  185. RenderWindowToResorucesIterator it = getRenderWindowIterator(renderWindow);
  186. acquireRenderWindowResources(it);
  187. return true;
  188. }
  189. //---------------------------------------------------------------------
  190. void D3D9Device::notifyDeviceLost()
  191. {
  192. // Case this device is already in lost state.
  193. if (mDeviceLost)
  194. return;
  195. // Case we just moved from valid state to lost state.
  196. mDeviceLost = true;
  197. D3D9RenderSystem* renderSystem = static_cast<D3D9RenderSystem*>(CamelotEngine::RenderSystemManager::getActive());
  198. renderSystem->notifyOnDeviceLost(this);
  199. }
  200. //---------------------------------------------------------------------
  201. IDirect3DSurface9* D3D9Device::getDepthBuffer(D3D9RenderWindow* renderWindow)
  202. {
  203. RenderWindowToResorucesIterator it = getRenderWindowIterator(renderWindow);
  204. return it->second->depthBuffer;
  205. }
  206. //---------------------------------------------------------------------
  207. IDirect3DSurface9* D3D9Device::getBackBuffer(D3D9RenderWindow* renderWindow)
  208. {
  209. RenderWindowToResorucesIterator it = getRenderWindowIterator(renderWindow);
  210. return it->second->backBuffer;
  211. }
  212. //---------------------------------------------------------------------
  213. UINT32 D3D9Device::getRenderWindowCount() const
  214. {
  215. return static_cast<UINT32>(mMapRenderWindowToResoruces.size());
  216. }
  217. //---------------------------------------------------------------------
  218. D3D9RenderWindow* D3D9Device::getRenderWindow(UINT32 index)
  219. {
  220. if (index >= mMapRenderWindowToResoruces.size())
  221. {
  222. CM_EXCEPT(RenderingAPIException,
  223. "Index of render window is out of bounds!");
  224. }
  225. RenderWindowToResorucesIterator it = mMapRenderWindowToResoruces.begin();
  226. while (it != mMapRenderWindowToResoruces.end())
  227. {
  228. if (index == 0)
  229. break;
  230. --index;
  231. ++it;
  232. }
  233. return it->first;
  234. }
  235. //---------------------------------------------------------------------
  236. void D3D9Device::setAdapterOrdinalIndex(D3D9RenderWindow* renderWindow, UINT32 adapterOrdinalInGroupIndex)
  237. {
  238. RenderWindowToResorucesIterator it = getRenderWindowIterator(renderWindow);
  239. it->second->adapterOrdinalInGroupIndex = adapterOrdinalInGroupIndex;
  240. updateRenderWindowsIndices();
  241. }
  242. //---------------------------------------------------------------------
  243. void D3D9Device::destroy()
  244. {
  245. // Lock access to rendering device.
  246. D3D9RenderSystem::getResourceManager()->lockDeviceAccess();
  247. release();
  248. RenderWindowToResorucesIterator it = mMapRenderWindowToResoruces.begin();
  249. if (it != mMapRenderWindowToResoruces.end())
  250. {
  251. if (it->first->getWindowHandle() == msSharedFocusWindow)
  252. setSharedWindowHandle(NULL);
  253. SAFE_DELETE(it->second);
  254. ++it;
  255. }
  256. mMapRenderWindowToResoruces.clear();
  257. // Reset dynamic attributes.
  258. mFocusWindow = NULL;
  259. mD3D9DeviceCapsValid = false;
  260. SAFE_DELETE_ARRAY(mPresentationParams);
  261. mPresentationParamsCount = 0;
  262. // Notify the device manager on this instance destruction.
  263. mpDeviceManager->notifyOnDeviceDestroy(this);
  264. // UnLock access to rendering device.
  265. D3D9RenderSystem::getResourceManager()->unlockDeviceAccess();
  266. }
  267. //---------------------------------------------------------------------
  268. bool D3D9Device::isDeviceLost()
  269. {
  270. HRESULT hr;
  271. hr = mpDevice->TestCooperativeLevel();
  272. if (hr == D3DERR_DEVICELOST ||
  273. hr == D3DERR_DEVICENOTRESET)
  274. {
  275. return true;
  276. }
  277. return false;
  278. }
  279. //---------------------------------------------------------------------
  280. bool D3D9Device::reset()
  281. {
  282. HRESULT hr;
  283. // Check that device is in valid state for reset.
  284. hr = mpDevice->TestCooperativeLevel();
  285. if (hr == D3DERR_DEVICELOST ||
  286. hr == D3DERR_DRIVERINTERNALERROR)
  287. {
  288. return false;
  289. }
  290. // Lock access to rendering device.
  291. D3D9RenderSystem::getResourceManager()->lockDeviceAccess();
  292. D3D9RenderSystem* renderSystem = static_cast<D3D9RenderSystem*>(CamelotEngine::RenderSystemManager::getActive());
  293. // Inform all resources that device lost.
  294. D3D9RenderSystem::getResourceManager()->notifyOnDeviceLost(mpDevice);
  295. // Notify all listener before device is rested
  296. renderSystem->notifyOnDeviceLost(this);
  297. // Cleanup depth stencils surfaces.
  298. renderSystem->cleanupDepthStencils(mpDevice);
  299. updatePresentationParameters();
  300. RenderWindowToResorucesIterator it = mMapRenderWindowToResoruces.begin();
  301. while (it != mMapRenderWindowToResoruces.end())
  302. {
  303. RenderWindowResources* renderWindowResources = it->second;
  304. releaseRenderWindowResources(renderWindowResources);
  305. ++it;
  306. }
  307. clearDeviceStreams();
  308. // Reset the device using the presentation parameters.
  309. hr = mpDevice->Reset(mPresentationParams);
  310. if (hr == D3DERR_DEVICELOST)
  311. {
  312. // UnLock access to rendering device.
  313. D3D9RenderSystem::getResourceManager()->unlockDeviceAccess();
  314. // Don't continue
  315. return false;
  316. }
  317. else if (FAILED(hr))
  318. {
  319. CM_EXCEPT(RenderingAPIException, "Cannot reset device!");
  320. }
  321. mDeviceLost = false;
  322. // Initialize device states.
  323. setupDeviceStates();
  324. // Update resources of each window.
  325. it = mMapRenderWindowToResoruces.begin();
  326. while (it != mMapRenderWindowToResoruces.end())
  327. {
  328. acquireRenderWindowResources(it);
  329. ++it;
  330. }
  331. D3D9Device* pCurActiveDevice = mpDeviceManager->getActiveDevice();
  332. mpDeviceManager->setActiveDevice(this);
  333. // Inform all resources that device has been reset.
  334. D3D9RenderSystem::getResourceManager()->notifyOnDeviceReset(mpDevice);
  335. mpDeviceManager->setActiveDevice(pCurActiveDevice);
  336. renderSystem->notifyOnDeviceReset(this);
  337. // UnLock access to rendering device.
  338. D3D9RenderSystem::getResourceManager()->unlockDeviceAccess();
  339. return true;
  340. }
  341. //---------------------------------------------------------------------
  342. bool D3D9Device::isAutoDepthStencil() const
  343. {
  344. const D3DPRESENT_PARAMETERS& primaryPresentationParams = mPresentationParams[0];
  345. // Check if auto depth stencil can be used.
  346. for (unsigned int i = 1; i < mPresentationParamsCount; i++)
  347. {
  348. // disable AutoDepthStencil if these parameters are not all the same.
  349. if(primaryPresentationParams.BackBufferHeight != mPresentationParams[i].BackBufferHeight ||
  350. primaryPresentationParams.BackBufferWidth != mPresentationParams[i].BackBufferWidth ||
  351. primaryPresentationParams.BackBufferFormat != mPresentationParams[i].BackBufferFormat ||
  352. primaryPresentationParams.AutoDepthStencilFormat != mPresentationParams[i].AutoDepthStencilFormat ||
  353. primaryPresentationParams.MultiSampleQuality != mPresentationParams[i].MultiSampleQuality ||
  354. primaryPresentationParams.MultiSampleType != mPresentationParams[i].MultiSampleType)
  355. {
  356. return false;
  357. }
  358. }
  359. return true;
  360. }
  361. //---------------------------------------------------------------------
  362. const D3DCAPS9& D3D9Device::getD3D9DeviceCaps() const
  363. {
  364. if (mD3D9DeviceCapsValid == false)
  365. {
  366. CM_EXCEPT(RenderingAPIException, "Device caps are invalid!");
  367. }
  368. return mD3D9DeviceCaps;
  369. }
  370. //---------------------------------------------------------------------
  371. D3DFORMAT D3D9Device::getBackBufferFormat() const
  372. {
  373. if (mPresentationParams == NULL || mPresentationParamsCount == 0)
  374. {
  375. CM_EXCEPT(RenderingAPIException, "Presentation parameters are invalid!");
  376. }
  377. return mPresentationParams[0].BackBufferFormat;
  378. }
  379. //---------------------------------------------------------------------
  380. IDirect3DDevice9* D3D9Device::getD3D9Device()
  381. {
  382. return mpDevice;
  383. }
  384. //---------------------------------------------------------------------
  385. void D3D9Device::updatePresentationParameters()
  386. {
  387. // Clear old presentation parameters.
  388. SAFE_DELETE_ARRAY(mPresentationParams);
  389. mPresentationParamsCount = 0;
  390. if (mMapRenderWindowToResoruces.size() > 0)
  391. {
  392. mPresentationParams = new D3DPRESENT_PARAMETERS[mMapRenderWindowToResoruces.size()];
  393. RenderWindowToResorucesIterator it = mMapRenderWindowToResoruces.begin();
  394. while (it != mMapRenderWindowToResoruces.end())
  395. {
  396. D3D9RenderWindow* renderWindow = it->first;
  397. RenderWindowResources* renderWindowResources = it->second;
  398. // Ask the render window to build it's own parameters.
  399. renderWindow->buildPresentParameters(&renderWindowResources->presentParameters);
  400. // Update shared focus window handle.
  401. if (renderWindow->isFullScreen() &&
  402. renderWindowResources->presentParametersIndex == 0 &&
  403. msSharedFocusWindow == NULL)
  404. setSharedWindowHandle(renderWindow->getWindowHandle());
  405. // This is the primary window or a full screen window that is part of multi head device.
  406. if (renderWindowResources->presentParametersIndex == 0 ||
  407. renderWindow->isFullScreen())
  408. {
  409. mPresentationParams[renderWindowResources->presentParametersIndex] = renderWindowResources->presentParameters;
  410. mPresentationParamsCount++;
  411. }
  412. ++it;
  413. }
  414. }
  415. // Case we have to cancel auto depth stencil.
  416. if (isMultihead() && isAutoDepthStencil() == false)
  417. {
  418. for(unsigned int i = 0; i < mPresentationParamsCount; i++)
  419. {
  420. mPresentationParams[i].EnableAutoDepthStencil = false;
  421. }
  422. }
  423. }
  424. //---------------------------------------------------------------------
  425. UINT D3D9Device::getAdapterNumber() const
  426. {
  427. return mAdapterNumber;
  428. }
  429. //---------------------------------------------------------------------
  430. D3DDEVTYPE D3D9Device::getDeviceType() const
  431. {
  432. return mDeviceType;
  433. }
  434. //---------------------------------------------------------------------
  435. bool D3D9Device::isMultihead() const
  436. {
  437. RenderWindowToResorucesMap::const_iterator it = mMapRenderWindowToResoruces.begin();
  438. while (it != mMapRenderWindowToResoruces.end())
  439. {
  440. RenderWindowResources* renderWindowResources = it->second;
  441. if (renderWindowResources->adapterOrdinalInGroupIndex > 0 &&
  442. it->first->isFullScreen())
  443. {
  444. return true;
  445. }
  446. ++it;
  447. }
  448. return false;
  449. }
  450. //---------------------------------------------------------------------
  451. void D3D9Device::clearDeviceStreams()
  452. {
  453. D3D9RenderSystem* renderSystem = static_cast<D3D9RenderSystem*>(CamelotEngine::RenderSystemManager::getActive());
  454. // Set all texture units to nothing to release texture surfaces
  455. for (DWORD stage = 0; stage < mD3D9DeviceCaps.MaxSimultaneousTextures; ++stage)
  456. {
  457. DWORD dwCurValue = D3DTOP_FORCE_DWORD;
  458. HRESULT hr;
  459. hr = mpDevice->SetTexture(stage, NULL);
  460. if( hr != S_OK )
  461. {
  462. String str = "Unable to disable texture '" + toString((unsigned int)stage) + "' in D3D9";
  463. CM_EXCEPT(RenderingAPIException, str);
  464. }
  465. mpDevice->GetTextureStageState(static_cast<DWORD>(stage), D3DTSS_COLOROP, &dwCurValue);
  466. if (dwCurValue != D3DTOP_DISABLE)
  467. {
  468. hr = mpDevice->SetTextureStageState(static_cast<DWORD>(stage), D3DTSS_COLOROP, D3DTOP_DISABLE);
  469. if( hr != S_OK )
  470. {
  471. String str = "Unable to disable texture '" + toString((unsigned)stage) + "' in D3D9";
  472. CM_EXCEPT(RenderingAPIException, str);
  473. }
  474. }
  475. // set stage desc. to defaults
  476. renderSystem->mTexStageDesc[stage].pTex = 0;
  477. renderSystem->mTexStageDesc[stage].coordIndex = 0;
  478. renderSystem->mTexStageDesc[stage].texType = D3D9Mappings::D3D_TEX_TYPE_NORMAL;
  479. }
  480. // Unbind any vertex streams to avoid memory leaks
  481. for (unsigned int i = 0; i < mD3D9DeviceCaps.MaxStreams; ++i)
  482. {
  483. mpDevice->SetStreamSource(i, NULL, 0, 0);
  484. }
  485. }
  486. //---------------------------------------------------------------------
  487. void D3D9Device::createD3D9Device()
  488. {
  489. // Update focus window.
  490. D3D9RenderWindow* primaryRenderWindow = getPrimaryWindow();
  491. // Case we have to share the same focus window.
  492. if (msSharedFocusWindow != NULL)
  493. mFocusWindow = msSharedFocusWindow;
  494. else
  495. mFocusWindow = primaryRenderWindow->getWindowHandle();
  496. IDirect3D9* pD3D9 = D3D9RenderSystem::getDirect3D9();
  497. HRESULT hr;
  498. if (isMultihead())
  499. {
  500. mBehaviorFlags |= D3DCREATE_ADAPTERGROUP_DEVICE;
  501. }
  502. else
  503. {
  504. mBehaviorFlags &= ~D3DCREATE_ADAPTERGROUP_DEVICE;
  505. }
  506. // Try to create the device with hardware vertex processing.
  507. mBehaviorFlags |= D3DCREATE_HARDWARE_VERTEXPROCESSING;
  508. hr = pD3D9->CreateDevice(mAdapterNumber, mDeviceType, mFocusWindow,
  509. mBehaviorFlags, mPresentationParams, &mpDevice);
  510. if (FAILED(hr))
  511. {
  512. // Try a second time, may fail the first time due to back buffer count,
  513. // which will be corrected down to 1 by the runtime
  514. hr = pD3D9->CreateDevice(mAdapterNumber, mDeviceType, mFocusWindow,
  515. mBehaviorFlags, mPresentationParams, &mpDevice);
  516. }
  517. // Case hardware vertex processing failed.
  518. if( FAILED( hr ) )
  519. {
  520. // Try to create the device with mixed vertex processing.
  521. mBehaviorFlags &= ~D3DCREATE_HARDWARE_VERTEXPROCESSING;
  522. mBehaviorFlags |= D3DCREATE_MIXED_VERTEXPROCESSING;
  523. hr = pD3D9->CreateDevice(mAdapterNumber, mDeviceType, mFocusWindow,
  524. mBehaviorFlags, mPresentationParams, &mpDevice);
  525. }
  526. if( FAILED( hr ) )
  527. {
  528. // try to create the device with software vertex processing.
  529. mBehaviorFlags &= ~D3DCREATE_MIXED_VERTEXPROCESSING;
  530. mBehaviorFlags |= D3DCREATE_SOFTWARE_VERTEXPROCESSING;
  531. hr = pD3D9->CreateDevice(mAdapterNumber, mDeviceType, mFocusWindow,
  532. mBehaviorFlags, mPresentationParams, &mpDevice);
  533. }
  534. if ( FAILED( hr ) )
  535. {
  536. // try reference device
  537. mDeviceType = D3DDEVTYPE_REF;
  538. hr = pD3D9->CreateDevice(mAdapterNumber, mDeviceType, mFocusWindow,
  539. mBehaviorFlags, mPresentationParams, &mpDevice);
  540. if ( FAILED( hr ) )
  541. {
  542. CM_EXCEPT(RenderingAPIException, "Cannot create device!");
  543. }
  544. }
  545. // Get current device caps.
  546. hr = mpDevice->GetDeviceCaps(&mD3D9DeviceCaps);
  547. if( FAILED( hr ) )
  548. {
  549. CM_EXCEPT(RenderingAPIException, "Cannot get device caps!");
  550. }
  551. // Get current creation parameters caps.
  552. hr = mpDevice->GetCreationParameters(&mCreationParams);
  553. if ( FAILED(hr) )
  554. {
  555. CM_EXCEPT(RenderingAPIException, "Error Get Creation Parameters");
  556. }
  557. mD3D9DeviceCapsValid = true;
  558. // Initialize device states.
  559. setupDeviceStates();
  560. // Lock access to rendering device.
  561. D3D9RenderSystem::getResourceManager()->lockDeviceAccess();
  562. D3D9Device* pCurActiveDevice = mpDeviceManager->getActiveDevice();
  563. mpDeviceManager->setActiveDevice(this);
  564. // Inform all resources that new device created.
  565. D3D9RenderSystem::getResourceManager()->notifyOnDeviceCreate(mpDevice);
  566. mpDeviceManager->setActiveDevice(pCurActiveDevice);
  567. // UnLock access to rendering device.
  568. D3D9RenderSystem::getResourceManager()->unlockDeviceAccess();
  569. }
  570. //---------------------------------------------------------------------
  571. void D3D9Device::releaseD3D9Device()
  572. {
  573. if (mpDevice != NULL)
  574. {
  575. // Lock access to rendering device.
  576. D3D9RenderSystem::getResourceManager()->lockDeviceAccess();
  577. D3D9Device* pCurActiveDevice = mpDeviceManager->getActiveDevice();
  578. mpDeviceManager->setActiveDevice(this);
  579. // Inform all resources that device is going to be destroyed.
  580. D3D9RenderSystem::getResourceManager()->notifyOnDeviceDestroy(mpDevice);
  581. mpDeviceManager->setActiveDevice(pCurActiveDevice);
  582. clearDeviceStreams();
  583. // Release device.
  584. SAFE_RELEASE(mpDevice);
  585. // UnLock access to rendering device.
  586. D3D9RenderSystem::getResourceManager()->unlockDeviceAccess();
  587. }
  588. }
  589. //---------------------------------------------------------------------
  590. void D3D9Device::releaseRenderWindowResources(RenderWindowResources* renderWindowResources)
  591. {
  592. SAFE_RELEASE(renderWindowResources->backBuffer);
  593. SAFE_RELEASE(renderWindowResources->depthBuffer);
  594. SAFE_RELEASE(renderWindowResources->swapChain);
  595. renderWindowResources->acquired = false;
  596. }
  597. //---------------------------------------------------------------------
  598. void D3D9Device::invalidate(D3D9RenderWindow* renderWindow)
  599. {
  600. RenderWindowToResorucesIterator it = getRenderWindowIterator(renderWindow);
  601. it->second->acquired = false;
  602. }
  603. //---------------------------------------------------------------------
  604. bool D3D9Device::validate(D3D9RenderWindow* renderWindow)
  605. {
  606. // Validate that the render window should run on this device.
  607. if (false == validateDisplayMonitor(renderWindow))
  608. return false;
  609. // Validate that this device created on the correct target focus window handle
  610. validateFocusWindow();
  611. // Validate that the render window dimensions matches to back buffer dimensions.
  612. validateBackBufferSize(renderWindow);
  613. // Validate that this device is in valid rendering state.
  614. if (false == validateDeviceState(renderWindow))
  615. return false;
  616. return true;
  617. }
  618. //---------------------------------------------------------------------
  619. void D3D9Device::validateFocusWindow()
  620. {
  621. // Focus window changed -> device should be re-acquired.
  622. if ((msSharedFocusWindow != NULL && mCreationParams.hFocusWindow != msSharedFocusWindow) ||
  623. (msSharedFocusWindow == NULL && mCreationParams.hFocusWindow != getPrimaryWindow()->getWindowHandle()))
  624. {
  625. // Lock access to rendering device.
  626. D3D9RenderSystem::getResourceManager()->lockDeviceAccess();
  627. release();
  628. acquire();
  629. // UnLock access to rendering device.
  630. D3D9RenderSystem::getResourceManager()->unlockDeviceAccess();
  631. }
  632. }
  633. //---------------------------------------------------------------------
  634. bool D3D9Device::validateDeviceState(D3D9RenderWindow* renderWindow)
  635. {
  636. RenderWindowToResorucesIterator it = getRenderWindowIterator(renderWindow);
  637. RenderWindowResources* renderWindowResources = it->second;
  638. HRESULT hr;
  639. hr = mpDevice->TestCooperativeLevel();
  640. // Case device is not valid for rendering.
  641. if (FAILED(hr))
  642. {
  643. // device lost, and we can't reset
  644. // can't do anything about it here, wait until we get
  645. // D3DERR_DEVICENOTRESET; rendering calls will silently fail until
  646. // then (except Present, but we ignore device lost there too)
  647. if (hr == D3DERR_DEVICELOST)
  648. {
  649. releaseRenderWindowResources(renderWindowResources);
  650. notifyDeviceLost();
  651. return false;
  652. }
  653. // device lost, and we can reset
  654. else if (hr == D3DERR_DEVICENOTRESET)
  655. {
  656. bool deviceRestored = reset();
  657. // Device was not restored yet.
  658. if (deviceRestored == false)
  659. {
  660. // Wait a while
  661. Sleep(50);
  662. return false;
  663. }
  664. }
  665. }
  666. // Render window resources explicitly invalidated. (Resize or window mode switch)
  667. if (renderWindowResources->acquired == false)
  668. {
  669. if (getPrimaryWindow() == renderWindow)
  670. {
  671. bool deviceRestored = reset();
  672. // Device was not restored yet.
  673. if (deviceRestored == false)
  674. {
  675. // Wait a while
  676. Sleep(50);
  677. return false;
  678. }
  679. }
  680. else
  681. {
  682. acquire(renderWindow);
  683. }
  684. }
  685. return true;
  686. }
  687. //---------------------------------------------------------------------
  688. void D3D9Device::validateBackBufferSize(D3D9RenderWindow* renderWindow)
  689. {
  690. RenderWindowToResorucesIterator it = getRenderWindowIterator(renderWindow);
  691. RenderWindowResources* renderWindowResources = it->second;
  692. // Case size has been changed.
  693. if (renderWindow->getWidth() != renderWindowResources->presentParameters.BackBufferWidth ||
  694. renderWindow->getHeight() != renderWindowResources->presentParameters.BackBufferHeight)
  695. {
  696. if (renderWindow->getWidth() > 0)
  697. renderWindowResources->presentParameters.BackBufferWidth = renderWindow->getWidth();
  698. if (renderWindow->getHeight() > 0)
  699. renderWindowResources->presentParameters.BackBufferHeight = renderWindow->getHeight();
  700. invalidate(renderWindow);
  701. }
  702. }
  703. //---------------------------------------------------------------------
  704. bool D3D9Device::validateDisplayMonitor(D3D9RenderWindow* renderWindow)
  705. {
  706. // Ignore full screen since it doesn't really move and it is possible
  707. // that it created using multi-head adapter so for a subordinate the
  708. // native monitor handle and this device handle will be different.
  709. if (renderWindow->isFullScreen())
  710. return true;
  711. RenderWindowToResorucesIterator it = getRenderWindowIterator(renderWindow);
  712. HMONITOR hRenderWindowMonitor = NULL;
  713. // Find the monitor this render window belongs to.
  714. hRenderWindowMonitor = MonitorFromWindow(renderWindow->getWindowHandle(), MONITOR_DEFAULTTONULL);
  715. // This window doesn't intersect with any of the display monitor
  716. if (hRenderWindowMonitor == NULL)
  717. return false;
  718. // Case this window changed monitor.
  719. if (hRenderWindowMonitor != mMonitor)
  720. {
  721. // Lock access to rendering device.
  722. D3D9RenderSystem::getResourceManager()->lockDeviceAccess();
  723. mpDeviceManager->linkRenderWindow(renderWindow);
  724. // UnLock access to rendering device.
  725. D3D9RenderSystem::getResourceManager()->unlockDeviceAccess();
  726. return false;
  727. }
  728. return true;
  729. }
  730. //---------------------------------------------------------------------
  731. void D3D9Device::present(D3D9RenderWindow* renderWindow)
  732. {
  733. RenderWindowToResorucesIterator it = getRenderWindowIterator(renderWindow);
  734. RenderWindowResources* renderWindowResources = it->second;
  735. // Skip present while current device state is invalid.
  736. if (mDeviceLost ||
  737. renderWindowResources->acquired == false ||
  738. isDeviceLost())
  739. return;
  740. HRESULT hr;
  741. if (isMultihead())
  742. {
  743. // Only the master will call present method results in synchronized
  744. // buffer swap for the rest of the implicit swap chain.
  745. if (getPrimaryWindow() == renderWindow)
  746. hr = mpDevice->Present( NULL, NULL, NULL, NULL );
  747. else
  748. hr = S_OK;
  749. }
  750. else
  751. {
  752. hr = renderWindowResources->swapChain->Present(NULL, NULL, NULL, NULL, 0);
  753. }
  754. if( D3DERR_DEVICELOST == hr)
  755. {
  756. releaseRenderWindowResources(renderWindowResources);
  757. notifyDeviceLost();
  758. }
  759. else if( FAILED(hr) )
  760. {
  761. CM_EXCEPT(RenderingAPIException, "Error Presenting surfaces");
  762. }
  763. else
  764. {
  765. // TODO PORT - What is this used for? In any case I don't have Root so just set it to 0
  766. //mLastPresentFrame = Root::getSingleton().getNextFrameNumber();
  767. mLastPresentFrame = 0;
  768. }
  769. }
  770. //---------------------------------------------------------------------
  771. void D3D9Device::acquireRenderWindowResources(RenderWindowToResorucesIterator it)
  772. {
  773. RenderWindowResources* renderWindowResources = it->second;
  774. D3D9RenderWindow* renderWindow = it->first;
  775. releaseRenderWindowResources(renderWindowResources);
  776. // Create additional swap chain
  777. if (isSwapChainWindow(renderWindow) && !isMultihead())
  778. {
  779. // Create swap chain
  780. HRESULT hr = mpDevice->CreateAdditionalSwapChain(&renderWindowResources->presentParameters,
  781. &renderWindowResources->swapChain);
  782. if (FAILED(hr))
  783. {
  784. // Try a second time, may fail the first time due to back buffer count,
  785. // which will be corrected by the runtime
  786. hr = mpDevice->CreateAdditionalSwapChain(&renderWindowResources->presentParameters,
  787. &renderWindowResources->swapChain);
  788. }
  789. if (FAILED(hr))
  790. {
  791. CM_EXCEPT(RenderingAPIException, "Unable to create an additional swap chain");
  792. }
  793. }
  794. else
  795. {
  796. // The swap chain is already created by the device
  797. HRESULT hr = mpDevice->GetSwapChain(renderWindowResources->presentParametersIndex,
  798. &renderWindowResources->swapChain);
  799. if (FAILED(hr))
  800. {
  801. CM_EXCEPT(RenderingAPIException, "Unable to get the swap chain");
  802. }
  803. }
  804. // Store references to buffers for convenience
  805. renderWindowResources->swapChain->GetBackBuffer(0, D3DBACKBUFFER_TYPE_MONO,
  806. &renderWindowResources->backBuffer);
  807. // Additional swap chains need their own depth buffer
  808. // to support resizing them
  809. if (renderWindow->isDepthBuffered())
  810. {
  811. // if multihead is enabled, depth buffer can be created automatically for
  812. // all the adapters. if multihead is not enabled, depth buffer is just
  813. // created for the main swap chain
  814. if (isMultihead() && isAutoDepthStencil() ||
  815. isMultihead() == false && isSwapChainWindow(renderWindow) == false)
  816. {
  817. mpDevice->GetDepthStencilSurface(&renderWindowResources->depthBuffer);
  818. }
  819. else
  820. {
  821. UINT32 targetWidth = renderWindow->getWidth();
  822. UINT32 targetHeight = renderWindow->getHeight();
  823. if (targetWidth == 0)
  824. targetWidth = 1;
  825. if (targetHeight == 0)
  826. targetHeight = 1;
  827. HRESULT hr = mpDevice->CreateDepthStencilSurface(
  828. targetWidth, targetHeight,
  829. renderWindowResources->presentParameters.AutoDepthStencilFormat,
  830. renderWindowResources->presentParameters.MultiSampleType,
  831. renderWindowResources->presentParameters.MultiSampleQuality,
  832. (renderWindowResources->presentParameters.Flags & D3DPRESENTFLAG_DISCARD_DEPTHSTENCIL),
  833. &renderWindowResources->depthBuffer, NULL
  834. );
  835. if (FAILED(hr))
  836. {
  837. CM_EXCEPT(RenderingAPIException, "Unable to create a depth buffer for the swap chain");
  838. }
  839. if (isSwapChainWindow(renderWindow) == false)
  840. {
  841. mpDevice->SetDepthStencilSurface(renderWindowResources->depthBuffer);
  842. }
  843. }
  844. }
  845. renderWindowResources->acquired = true;
  846. }
  847. //---------------------------------------------------------------------
  848. void D3D9Device::setupDeviceStates()
  849. {
  850. HRESULT hr = mpDevice->SetRenderState(D3DRS_SPECULARENABLE, TRUE);
  851. if (FAILED(hr))
  852. {
  853. CM_EXCEPT(RenderingAPIException, "Unable to apply render state: D3DRS_SPECULARENABLE <- TRUE");
  854. }
  855. }
  856. //---------------------------------------------------------------------
  857. bool D3D9Device::isSwapChainWindow(D3D9RenderWindow* renderWindow)
  858. {
  859. RenderWindowToResorucesIterator it = getRenderWindowIterator(renderWindow);
  860. if (it->second->presentParametersIndex == 0 || renderWindow->isFullScreen())
  861. return false;
  862. return true;
  863. }
  864. //---------------------------------------------------------------------
  865. D3D9RenderWindow* D3D9Device::getPrimaryWindow()
  866. {
  867. RenderWindowToResorucesIterator it = mMapRenderWindowToResoruces.begin();
  868. while (it != mMapRenderWindowToResoruces.end() && it->second->presentParametersIndex != 0)
  869. ++it;
  870. assert(it != mMapRenderWindowToResoruces.end());
  871. return it->first;
  872. }
  873. //---------------------------------------------------------------------
  874. void D3D9Device::setSharedWindowHandle(HWND hSharedHWND)
  875. {
  876. if (hSharedHWND != msSharedFocusWindow)
  877. msSharedFocusWindow = hSharedHWND;
  878. }
  879. //---------------------------------------------------------------------
  880. void D3D9Device::updateRenderWindowsIndices()
  881. {
  882. // Update present parameters index attribute per render window.
  883. if (isMultihead())
  884. {
  885. RenderWindowToResorucesIterator it = mMapRenderWindowToResoruces.begin();
  886. // Multi head device case -
  887. // Present parameter index is based on adapter ordinal in group index.
  888. while (it != mMapRenderWindowToResoruces.end())
  889. {
  890. it->second->presentParametersIndex = it->second->adapterOrdinalInGroupIndex;
  891. ++it;
  892. }
  893. }
  894. else
  895. {
  896. // Single head device case -
  897. // Just assign index in incremental order -
  898. // NOTE: It suppose to cover both cases that possible here:
  899. // 1. Single full screen window - only one allowed per device (this is not multi-head case).
  900. // 2. Multiple window mode windows.
  901. UINT32 nextPresParamIndex = 0;
  902. RenderWindowToResorucesIterator it;
  903. D3D9RenderWindow* deviceFocusWindow = NULL;
  904. // In case a d3d9 device exists - try to keep the present parameters order
  905. // so that the window that the device is focused on will stay the same and we
  906. // will avoid device re-creation.
  907. if (mpDevice != NULL)
  908. {
  909. it = mMapRenderWindowToResoruces.begin();
  910. while (it != mMapRenderWindowToResoruces.end())
  911. {
  912. if (it->first->getWindowHandle() == mCreationParams.hFocusWindow)
  913. {
  914. deviceFocusWindow = it->first;
  915. it->second->presentParametersIndex = nextPresParamIndex;
  916. ++nextPresParamIndex;
  917. break;
  918. }
  919. ++it;
  920. }
  921. }
  922. it = mMapRenderWindowToResoruces.begin();
  923. while (it != mMapRenderWindowToResoruces.end())
  924. {
  925. if (it->first != deviceFocusWindow)
  926. {
  927. it->second->presentParametersIndex = nextPresParamIndex;
  928. ++nextPresParamIndex;
  929. }
  930. ++it;
  931. }
  932. }
  933. }
  934. //---------------------------------------------------------------------
  935. void D3D9Device::copyContentsToMemory(D3D9RenderWindow* renderWindow,
  936. const PixelData &dst, RenderTarget::FrameBuffer buffer)
  937. {
  938. RenderWindowToResorucesIterator it = getRenderWindowIterator(renderWindow);
  939. RenderWindowResources* resources = it->second;
  940. bool swapChain = isSwapChainWindow(renderWindow);
  941. if ((dst.left < 0) || (dst.right > renderWindow->getWidth()) ||
  942. (dst.top < 0) || (dst.bottom > renderWindow->getHeight()) ||
  943. (dst.front != 0) || (dst.back != 1))
  944. {
  945. CM_EXCEPT(InvalidParametersException, "Invalid box.");
  946. }
  947. HRESULT hr;
  948. IDirect3DSurface9* pSurf = NULL;
  949. IDirect3DSurface9* pTempSurf = NULL;
  950. D3DSURFACE_DESC desc;
  951. D3DLOCKED_RECT lockedRect;
  952. if (buffer == RenderTarget::FB_AUTO)
  953. {
  954. //buffer = mIsFullScreen? FB_FRONT : FB_BACK;
  955. buffer = RenderTarget::FB_FRONT;
  956. }
  957. if (buffer == RenderTarget::FB_FRONT)
  958. {
  959. D3DDISPLAYMODE dm;
  960. if (FAILED(hr = mpDevice->GetDisplayMode(0, &dm)))
  961. {
  962. CM_EXCEPT(RenderingAPIException, "Can't get display mode: TODO PORT NO ERROR"); // TODO PORT - Translate HR to error
  963. }
  964. desc.Width = dm.Width;
  965. desc.Height = dm.Height;
  966. desc.Format = D3DFMT_A8R8G8B8;
  967. if (FAILED(hr = mpDevice->CreateOffscreenPlainSurface(desc.Width, desc.Height,
  968. desc.Format,
  969. D3DPOOL_SYSTEMMEM,
  970. &pTempSurf,
  971. 0)))
  972. {
  973. CM_EXCEPT(RenderingAPIException, "Can't create offscreen buffer: TODO PORT NO ERROR"); // TODO PORT - Translate HR to error
  974. }
  975. if (FAILED(hr = swapChain ? resources->swapChain->GetFrontBufferData(pTempSurf) :
  976. mpDevice->GetFrontBufferData(0, pTempSurf)))
  977. {
  978. SAFE_RELEASE(pTempSurf);
  979. CM_EXCEPT(RenderingAPIException, "Can't get front buffer: TODO PORT NO ERROR"); // TODO PORT - Translate HR to error
  980. }
  981. if(renderWindow->isFullScreen())
  982. {
  983. if ((dst.left == 0) && (dst.right == renderWindow->getWidth()) && (dst.top == 0) && (dst.bottom == renderWindow->getHeight()))
  984. {
  985. hr = pTempSurf->LockRect(&lockedRect, 0, D3DLOCK_READONLY | D3DLOCK_NOSYSLOCK);
  986. }
  987. else
  988. {
  989. RECT rect;
  990. rect.left = static_cast<LONG>(dst.left);
  991. rect.right = static_cast<LONG>(dst.right);
  992. rect.top = static_cast<LONG>(dst.top);
  993. rect.bottom = static_cast<LONG>(dst.bottom);
  994. hr = pTempSurf->LockRect(&lockedRect, &rect, D3DLOCK_READONLY | D3DLOCK_NOSYSLOCK);
  995. }
  996. if (FAILED(hr))
  997. {
  998. SAFE_RELEASE(pTempSurf);
  999. CM_EXCEPT(RenderingAPIException, "Can't lock rect: TODO PORT NO ERROR"); // TODO PORT - Translate HR to error
  1000. }
  1001. }
  1002. else
  1003. {
  1004. RECT srcRect;
  1005. //GetClientRect(mHWnd, &srcRect);
  1006. srcRect.left = static_cast<LONG>(dst.left);
  1007. srcRect.top = static_cast<LONG>(dst.top);
  1008. srcRect.right = static_cast<LONG>(dst.right);
  1009. srcRect.bottom = static_cast<LONG>(dst.bottom);
  1010. POINT point;
  1011. point.x = srcRect.left;
  1012. point.y = srcRect.top;
  1013. ClientToScreen(renderWindow->getWindowHandle(), &point);
  1014. srcRect.top = point.y;
  1015. srcRect.left = point.x;
  1016. srcRect.bottom += point.y;
  1017. srcRect.right += point.x;
  1018. desc.Width = srcRect.right - srcRect.left;
  1019. desc.Height = srcRect.bottom - srcRect.top;
  1020. if (FAILED(hr = pTempSurf->LockRect(&lockedRect, &srcRect, D3DLOCK_READONLY | D3DLOCK_NOSYSLOCK)))
  1021. {
  1022. SAFE_RELEASE(pTempSurf);
  1023. CM_EXCEPT(RenderingAPIException, "Can't lock rect: TODO PORT NO ERROR"); // TODO PORT - Translate HR to error
  1024. }
  1025. }
  1026. }
  1027. else
  1028. {
  1029. SAFE_RELEASE(pSurf);
  1030. if(FAILED(hr = swapChain? resources->swapChain->GetBackBuffer(0, D3DBACKBUFFER_TYPE_MONO, &pSurf) :
  1031. mpDevice->GetBackBuffer(0, 0, D3DBACKBUFFER_TYPE_MONO, &pSurf)))
  1032. {
  1033. CM_EXCEPT(RenderingAPIException, "Can't get back buffer: TODO PORT NO ERROR"); // TODO PORT - Translate HR to error
  1034. }
  1035. if(FAILED(hr = pSurf->GetDesc(&desc)))
  1036. {
  1037. CM_EXCEPT(RenderingAPIException, "Can't get description: TODO PORT NO ERROR"); // TODO PORT - Translate HR to error
  1038. }
  1039. if (FAILED(hr = mpDevice->CreateOffscreenPlainSurface(desc.Width, desc.Height,
  1040. desc.Format,
  1041. D3DPOOL_SYSTEMMEM,
  1042. &pTempSurf,
  1043. 0)))
  1044. {
  1045. CM_EXCEPT(RenderingAPIException, "Can't create offscreen surface: TODO PORT NO ERROR"); // TODO PORT - Translate HR to error
  1046. }
  1047. if (desc.MultiSampleType == D3DMULTISAMPLE_NONE)
  1048. {
  1049. if (FAILED(hr = mpDevice->GetRenderTargetData(pSurf, pTempSurf)))
  1050. {
  1051. SAFE_RELEASE(pTempSurf);
  1052. CM_EXCEPT(RenderingAPIException, "Can't get render target data: TODO PORT NO ERROR"); // TODO PORT - Translate HR to error
  1053. }
  1054. }
  1055. else
  1056. {
  1057. IDirect3DSurface9* pStretchSurf = 0;
  1058. if (FAILED(hr = mpDevice->CreateRenderTarget(desc.Width, desc.Height,
  1059. desc.Format,
  1060. D3DMULTISAMPLE_NONE,
  1061. 0,
  1062. false,
  1063. &pStretchSurf,
  1064. 0)))
  1065. {
  1066. SAFE_RELEASE(pTempSurf);
  1067. CM_EXCEPT(RenderingAPIException, "Can't create render target: TODO PORT NO ERROR"); // TODO PORT - Translate HR to error
  1068. }
  1069. if (FAILED(hr = mpDevice->StretchRect(pSurf, 0, pStretchSurf, 0, D3DTEXF_NONE)))
  1070. {
  1071. SAFE_RELEASE(pTempSurf);
  1072. SAFE_RELEASE(pStretchSurf);
  1073. CM_EXCEPT(RenderingAPIException, "Can't stretch rect: TODO PORT NO ERROR"); // TODO PORT - Translate HR to error
  1074. }
  1075. if (FAILED(hr = mpDevice->GetRenderTargetData(pStretchSurf, pTempSurf)))
  1076. {
  1077. SAFE_RELEASE(pTempSurf);
  1078. SAFE_RELEASE(pStretchSurf);
  1079. CM_EXCEPT(RenderingAPIException, "Can't get render target data: TODO PORT NO ERROR"); // TODO PORT - Translate HR to error
  1080. }
  1081. SAFE_RELEASE(pStretchSurf);
  1082. }
  1083. if ((dst.left == 0) && (dst.right == renderWindow->getWidth()) && (dst.top == 0) && (dst.bottom == renderWindow->getHeight()))
  1084. {
  1085. hr = pTempSurf->LockRect(&lockedRect, 0, D3DLOCK_READONLY | D3DLOCK_NOSYSLOCK);
  1086. }
  1087. else
  1088. {
  1089. RECT rect;
  1090. rect.left = static_cast<LONG>(dst.left);
  1091. rect.right = static_cast<LONG>(dst.right);
  1092. rect.top = static_cast<LONG>(dst.top);
  1093. rect.bottom = static_cast<LONG>(dst.bottom);
  1094. hr = pTempSurf->LockRect(&lockedRect, &rect, D3DLOCK_READONLY | D3DLOCK_NOSYSLOCK);
  1095. }
  1096. if (FAILED(hr))
  1097. {
  1098. SAFE_RELEASE(pTempSurf);
  1099. CM_EXCEPT(RenderingAPIException, "Can't lock rect: TODO PORT NO ERROR"); // TODO PORT - Translate HR to error
  1100. }
  1101. }
  1102. PixelFormat format = CamelotEngine::D3D9Mappings::_getPF(desc.Format);
  1103. if (format == PF_UNKNOWN)
  1104. {
  1105. SAFE_RELEASE(pTempSurf);
  1106. CM_EXCEPT(RenderingAPIException, "Unsupported format");
  1107. }
  1108. PixelData src(dst.getWidth(), dst.getHeight(), 1, format, lockedRect.pBits);
  1109. src.rowPitch = lockedRect.Pitch / PixelUtil::getNumElemBytes(format);
  1110. src.slicePitch = desc.Height * src.rowPitch;
  1111. PixelUtil::bulkPixelConversion(src, dst);
  1112. SAFE_RELEASE(pTempSurf);
  1113. SAFE_RELEASE(pSurf);
  1114. }
  1115. }