BsD3D9Texture.cpp 33 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067
  1. //__________________________ Banshee Project - A modern game development toolkit _________________________________//
  2. //_____________________________________ www.banshee-project.com __________________________________________________//
  3. //________________________ Copyright (c) 2014 Marko Pintera. All rights reserved. ________________________________//
  4. #include "BsCoreThread.h"
  5. #include "BsD3D9Texture.h"
  6. #include "BsD3D9PixelBuffer.h"
  7. #include "BsException.h"
  8. #include "BsBitwise.h"
  9. #include "BsD3D9Mappings.h"
  10. #include "BsD3D9RenderSystem.h"
  11. #include "BsD3D9TextureManager.h"
  12. #include "BsD3D9Device.h"
  13. #include "BsD3D9DeviceManager.h"
  14. #include "BsD3D9ResourceManager.h"
  15. #include "BsRenderStats.h"
  16. namespace BansheeEngine
  17. {
  18. D3D9Texture::D3D9Texture()
  19. :Texture(), mD3DPool(D3DPOOL_MANAGED), mDynamicTextures(false),
  20. mHwGammaReadSupported(false), mHwGammaWriteSupported(false), mMultisampleType(D3DMULTISAMPLE_NONE),
  21. mMultisampleQuality(0), mIsBindableAsShaderResource(true)
  22. { }
  23. D3D9Texture::~D3D9Texture()
  24. {
  25. }
  26. void D3D9Texture::initialize_internal()
  27. {
  28. THROW_IF_NOT_CORE_THREAD;
  29. for (UINT32 i = 0; i < D3D9RenderSystem::getResourceCreationDeviceCount(); ++i)
  30. {
  31. IDirect3DDevice9* d3d9Device = D3D9RenderSystem::getResourceCreationDevice(i);
  32. createInternalResources(d3d9Device);
  33. }
  34. BS_INC_RENDER_STAT_CAT(ResCreated, RenderStatObject_Texture);
  35. Texture::initialize_internal();
  36. }
  37. void D3D9Texture::destroy_internal()
  38. {
  39. THROW_IF_NOT_CORE_THREAD;
  40. for (auto& resPair : mMapDeviceToTextureResources)
  41. {
  42. TextureResources* textureResource = resPair.second;
  43. freeTextureResources(resPair.first, textureResource);
  44. }
  45. for (auto& resPair : mMapDeviceToTextureResources)
  46. {
  47. TextureResources* textureResource = resPair.second;
  48. if (textureResource != nullptr)
  49. bs_delete(textureResource);
  50. }
  51. mMapDeviceToTextureResources.clear();
  52. mSurfaceList.clear();
  53. clearBufferViews();
  54. BS_INC_RENDER_STAT_CAT(ResDestroyed, RenderStatObject_Texture);
  55. Texture::destroy_internal();
  56. }
  57. PixelData D3D9Texture::lockImpl(GpuLockOptions options, UINT32 mipLevel, UINT32 face)
  58. {
  59. if(mLockedBuffer != nullptr)
  60. BS_EXCEPT(InternalErrorException, "Trying to lock a buffer that's already locked.");
  61. if(getUsage() == TU_DEPTHSTENCIL)
  62. BS_EXCEPT(InternalErrorException, "Cannot lock a depth stencil texture.");
  63. UINT32 mipWidth = mWidth >> mipLevel;
  64. UINT32 mipHeight = mHeight >> mipLevel;
  65. UINT32 mipDepth = mDepth >> mipLevel;
  66. PixelData lockedArea(mipWidth, mipHeight, mipDepth, mFormat);
  67. mLockedBuffer = getBuffer(face, mipLevel);
  68. lockedArea.setExternalBuffer((UINT8*)mLockedBuffer->lock(options));
  69. return lockedArea;
  70. }
  71. void D3D9Texture::unlockImpl()
  72. {
  73. if(mLockedBuffer == nullptr)
  74. BS_EXCEPT(InternalErrorException, "Trying to unlock a buffer that's not locked.");
  75. mLockedBuffer->unlock();
  76. mLockedBuffer = nullptr;
  77. }
  78. void D3D9Texture::readData(PixelData& dest, UINT32 mipLevel, UINT32 face)
  79. {
  80. PixelData myData = lock(GBL_READ_ONLY, mipLevel, face);
  81. #if BS_DEBUG_MODE
  82. if(dest.getConsecutiveSize() != myData.getConsecutiveSize())
  83. {
  84. unlock();
  85. BS_EXCEPT(InternalErrorException, "Buffer sizes don't match.");
  86. }
  87. #endif
  88. PixelUtil::bulkPixelConversion(myData, dest);
  89. unlock();
  90. }
  91. void D3D9Texture::writeData(const PixelData& src, UINT32 mipLevel, UINT32 face, bool discardWholeBuffer)
  92. {
  93. if(mUsage == TU_DYNAMIC || mUsage == TU_STATIC)
  94. {
  95. PixelData myData = lock(discardWholeBuffer ? GBL_WRITE_ONLY_DISCARD : GBL_WRITE_ONLY, mipLevel, face);
  96. PixelUtil::bulkPixelConversion(src, myData);
  97. unlock();
  98. }
  99. else
  100. {
  101. BS_EXCEPT(RenderingAPIException, "Trying to write into a buffer with unsupported usage: " + toString(mUsage));
  102. }
  103. }
  104. void D3D9Texture::copyImpl(TexturePtr& target)
  105. {
  106. THROW_IF_NOT_CORE_THREAD;
  107. if (target->getUsage() != getUsage() || target->getTextureType() != getTextureType())
  108. {
  109. BS_EXCEPT(InvalidParametersException, "Src. and dest. textures must be of same type and must have the same usage.");
  110. }
  111. HRESULT hr;
  112. D3D9Texture *other = static_cast<D3D9Texture*>(target.get());
  113. RECT dstRC = { 0, 0, (LONG)(other->getWidth()), (LONG)(other->getHeight()) };
  114. for (auto& resPair : mMapDeviceToTextureResources)
  115. {
  116. TextureResources* srcTextureResource = resPair.second;
  117. TextureResources* dstTextureResource = other->getTextureResources(resPair.first);
  118. // Plain copy for normal textures
  119. if (getTextureType() == TEX_TYPE_2D && srcTextureResource->pNormTex != nullptr &&
  120. dstTextureResource->pNormTex != nullptr)
  121. {
  122. IDirect3DSurface9 *sourceSurface = 0;
  123. if(FAILED(hr = srcTextureResource->pNormTex->GetSurfaceLevel(0, &sourceSurface)))
  124. {
  125. String msg = DXGetErrorDescription(hr);
  126. BS_EXCEPT(RenderingAPIException, "Couldn't blit: " + msg);
  127. }
  128. IDirect3DSurface9 *destSurface = 0;
  129. if(FAILED(hr = dstTextureResource->pNormTex->GetSurfaceLevel(0, &destSurface)))
  130. {
  131. String msg = DXGetErrorDescription(hr);
  132. SAFE_RELEASE(sourceSurface);
  133. BS_EXCEPT(RenderingAPIException, "Couldn't blit: " + msg);
  134. }
  135. if (FAILED(hr = resPair.first->StretchRect(sourceSurface, NULL, destSurface, &dstRC, D3DTEXF_NONE)))
  136. {
  137. String msg = DXGetErrorDescription(hr);
  138. SAFE_RELEASE(sourceSurface);
  139. SAFE_RELEASE(destSurface);
  140. BS_EXCEPT(RenderingAPIException, "Couldn't blit: " + msg);
  141. }
  142. SAFE_RELEASE(sourceSurface);
  143. SAFE_RELEASE(destSurface);
  144. }
  145. else if (getTextureType() == TEX_TYPE_CUBE_MAP && srcTextureResource->pCubeTex != nullptr &&
  146. dstTextureResource->pCubeTex != nullptr)
  147. {
  148. for (UINT32 face = 0; face < 6; face++)
  149. {
  150. IDirect3DSurface9 *sourceSurface = 0;
  151. if( FAILED(hr = srcTextureResource->pCubeTex->GetCubeMapSurface((D3DCUBEMAP_FACES)face, 0, &sourceSurface)))
  152. {
  153. String msg = DXGetErrorDescription(hr);
  154. BS_EXCEPT(RenderingAPIException, "Couldn't blit: " + msg);
  155. }
  156. IDirect3DSurface9 *destSurface = 0;
  157. if( FAILED(hr = dstTextureResource->pCubeTex->GetCubeMapSurface((D3DCUBEMAP_FACES)face, 0, &destSurface)))
  158. {
  159. String msg = DXGetErrorDescription(hr);
  160. SAFE_RELEASE(sourceSurface);
  161. BS_EXCEPT(RenderingAPIException, "Couldn't blit: " + msg);
  162. }
  163. if (FAILED(hr = resPair.first->StretchRect(sourceSurface, NULL, destSurface, &dstRC, D3DTEXF_NONE)))
  164. {
  165. String msg = DXGetErrorDescription(hr);
  166. SAFE_RELEASE(sourceSurface);
  167. SAFE_RELEASE(destSurface);
  168. BS_EXCEPT(RenderingAPIException, "Couldn't blit: " + msg);
  169. }
  170. SAFE_RELEASE(sourceSurface);
  171. SAFE_RELEASE(destSurface);
  172. }
  173. }
  174. else
  175. {
  176. BS_EXCEPT(NotImplementedException, "Copy to texture is implemented only for 2D and cube textures.");
  177. }
  178. }
  179. }
  180. D3D9Texture::TextureResources* D3D9Texture::getTextureResources(IDirect3DDevice9* d3d9Device)
  181. {
  182. auto iterFind = mMapDeviceToTextureResources.find(d3d9Device);
  183. if (iterFind == mMapDeviceToTextureResources.end())
  184. return nullptr;
  185. return iterFind->second;
  186. }
  187. D3D9Texture::TextureResources* D3D9Texture::allocateTextureResources(IDirect3DDevice9* d3d9Device)
  188. {
  189. assert(mMapDeviceToTextureResources.find(d3d9Device) == mMapDeviceToTextureResources.end());
  190. TextureResources* textureResources = bs_new<TextureResources>();
  191. textureResources->pNormTex = nullptr;
  192. textureResources->pCubeTex = nullptr;
  193. textureResources->pVolumeTex = nullptr;
  194. textureResources->pBaseTex = nullptr;
  195. textureResources->pMultisampleSurface = nullptr;
  196. textureResources->pDepthStencilSurface = nullptr;
  197. mMapDeviceToTextureResources[d3d9Device] = textureResources;
  198. return textureResources;
  199. }
  200. void D3D9Texture::freeTextureResources(IDirect3DDevice9* d3d9Device, D3D9Texture::TextureResources* textureResources)
  201. {
  202. D3D9_DEVICE_ACCESS_CRITICAL_SECTION
  203. // Release surfaces from each mip level.
  204. for(unsigned int i = 0; i < mSurfaceList.size(); ++i)
  205. {
  206. D3D9PixelBuffer* pixelBuffer = static_cast<D3D9PixelBuffer*>(mSurfaceList[i].get());
  207. pixelBuffer->releaseSurfaces(d3d9Device);
  208. }
  209. // Release the rest of the resources.
  210. SAFE_RELEASE(textureResources->pBaseTex);
  211. SAFE_RELEASE(textureResources->pNormTex);
  212. SAFE_RELEASE(textureResources->pCubeTex);
  213. SAFE_RELEASE(textureResources->pVolumeTex);
  214. SAFE_RELEASE(textureResources->pMultisampleSurface);
  215. SAFE_RELEASE(textureResources->pDepthStencilSurface);
  216. }
  217. UINT32 D3D9Texture::calculateSize() const
  218. {
  219. UINT32 instanceSize = getNumFaces() * PixelUtil::getMemorySize(mWidth, mHeight, mDepth, mFormat);
  220. return instanceSize * (UINT32)mMapDeviceToTextureResources.size();
  221. }
  222. void D3D9Texture::determinePool()
  223. {
  224. if (useDefaultPool())
  225. mD3DPool = D3DPOOL_DEFAULT;
  226. else
  227. mD3DPool = D3DPOOL_MANAGED;
  228. }
  229. void D3D9Texture::createInternalResources(IDirect3DDevice9* d3d9Device)
  230. {
  231. switch (getTextureType())
  232. {
  233. case TEX_TYPE_1D:
  234. case TEX_TYPE_2D:
  235. createNormTex(d3d9Device);
  236. break;
  237. case TEX_TYPE_CUBE_MAP:
  238. createCubeTex(d3d9Device);
  239. break;
  240. case TEX_TYPE_3D:
  241. createVolumeTex(d3d9Device);
  242. break;
  243. default:
  244. destroy_internal();
  245. BS_EXCEPT(InternalErrorException, "Unknown texture type.");
  246. }
  247. }
  248. void D3D9Texture::createNormTex(IDirect3DDevice9* d3d9Device)
  249. {
  250. assert(mWidth > 0 || mHeight > 0);
  251. D3DFORMAT d3dPF = chooseD3DFormat(d3d9Device);
  252. if(mFormat != D3D9Mappings::_getPF(d3dPF))
  253. {
  254. BS_EXCEPT(RenderingAPIException, "Provided pixel format is not supported by the driver: " + toString(mFormat));
  255. }
  256. // Use D3DX to help us create the texture, this way it can adjust any relevant sizes
  257. UINT numMips = (mNumMipmaps == MIP_UNLIMITED) ? D3DX_DEFAULT : mNumMipmaps + 1;
  258. DWORD usage = 0;
  259. if((mUsage & TU_RENDERTARGET) != 0)
  260. usage = D3DUSAGE_RENDERTARGET;
  261. else if((mUsage & TU_DEPTHSTENCIL) != 0)
  262. usage = D3DUSAGE_DEPTHSTENCIL;
  263. // Check dynamic textures
  264. if (mUsage & TU_DYNAMIC)
  265. {
  266. if (canUseDynamicTextures(d3d9Device, usage, D3DRTYPE_TEXTURE, d3dPF))
  267. {
  268. usage |= D3DUSAGE_DYNAMIC;
  269. mDynamicTextures = true;
  270. }
  271. else
  272. {
  273. mDynamicTextures = false;
  274. }
  275. }
  276. // Check sRGB support
  277. if (mHwGamma)
  278. {
  279. mHwGammaReadSupported = canUseHardwareGammaCorrection(d3d9Device, usage, D3DRTYPE_TEXTURE, d3dPF, false);
  280. if (mUsage & TU_RENDERTARGET)
  281. mHwGammaWriteSupported = canUseHardwareGammaCorrection(d3d9Device, usage, D3DRTYPE_TEXTURE, d3dPF, true);
  282. }
  283. // Check multisample level
  284. if ((mUsage & TU_RENDERTARGET) != 0 || (mUsage & TU_DEPTHSTENCIL) != 0)
  285. {
  286. D3D9RenderSystem* rsys = static_cast<D3D9RenderSystem*>(BansheeEngine::RenderSystem::instancePtr());
  287. rsys->determineMultisampleSettings(d3d9Device, mMultisampleCount, mMultisampleHint, d3dPF, false, &mMultisampleType, &mMultisampleQuality);
  288. }
  289. else
  290. {
  291. mMultisampleType = D3DMULTISAMPLE_NONE;
  292. mMultisampleQuality = 0;
  293. }
  294. D3D9Device* device = D3D9RenderSystem::getDeviceManager()->getDeviceFromD3D9Device(d3d9Device);
  295. const D3DCAPS9& rkCurCaps = device->getD3D9DeviceCaps();
  296. // Check if mip maps are supported on hardware
  297. if (numMips > 1 && (!(rkCurCaps.TextureCaps & D3DPTEXTURECAPS_MIPMAP) || (mUsage & TU_RENDERTARGET) != 0 || (mUsage & TU_DEPTHSTENCIL) != 0))
  298. {
  299. BS_EXCEPT(InvalidParametersException, "Invalid number of mipmaps. Maximum allowed is: 0");
  300. }
  301. determinePool();
  302. TextureResources* textureResources;
  303. // Get or create new texture resources structure.
  304. textureResources = getTextureResources(d3d9Device);
  305. if (textureResources != NULL)
  306. freeTextureResources(d3d9Device, textureResources);
  307. else
  308. textureResources = allocateTextureResources(d3d9Device);
  309. if ((mUsage & TU_RENDERTARGET) != 0 && (mMultisampleType != D3DMULTISAMPLE_NONE))
  310. {
  311. // Create AA surface
  312. HRESULT hr = d3d9Device->CreateRenderTarget(mWidth, mHeight, d3dPF,
  313. mMultisampleType, mMultisampleQuality,
  314. TRUE, // TODO - Possible performance issues? Need to check
  315. &textureResources->pMultisampleSurface, NULL);
  316. if (FAILED(hr))
  317. BS_EXCEPT(RenderingAPIException, "Unable to create AA render target: " + String(DXGetErrorDescription(hr)));
  318. D3DSURFACE_DESC desc;
  319. hr = textureResources->pMultisampleSurface->GetDesc(&desc);
  320. if (FAILED(hr))
  321. {
  322. destroy_internal();
  323. BS_EXCEPT(RenderingAPIException, "Can't get texture description: " + String(DXGetErrorDescription(hr)));
  324. }
  325. setFinalAttributes(d3d9Device, textureResources, desc.Width, desc.Height, 1, D3D9Mappings::_getPF(desc.Format));
  326. mIsBindableAsShaderResource = true; // Cannot bind AA surfaces
  327. }
  328. else if ((mUsage & TU_DEPTHSTENCIL) != 0 && (mMultisampleType != D3DMULTISAMPLE_NONE))
  329. {
  330. // Create AA depth stencil surface
  331. HRESULT hr = d3d9Device->CreateDepthStencilSurface(mWidth, mHeight, d3dPF,
  332. mMultisampleType, mMultisampleQuality,
  333. TRUE, // TODO - Possible performance issues? Need to check
  334. &textureResources->pDepthStencilSurface, NULL);
  335. if (FAILED(hr))
  336. BS_EXCEPT(RenderingAPIException, "Unable to create AA depth stencil render target: " + String(DXGetErrorDescription(hr)));
  337. // Update final parameters as they may differ from requested ones
  338. D3DSURFACE_DESC desc;
  339. hr = textureResources->pDepthStencilSurface->GetDesc(&desc);
  340. if (FAILED(hr))
  341. {
  342. destroy_internal();
  343. BS_EXCEPT(RenderingAPIException, "Can't get texture description: " + String(DXGetErrorDescription(hr)));
  344. }
  345. setFinalAttributes(d3d9Device, textureResources, desc.Width, desc.Height, 1, D3D9Mappings::_getPF(desc.Format));
  346. mIsBindableAsShaderResource = true; // Cannot bind AA depth buffer
  347. }
  348. else
  349. {
  350. // Create normal texture
  351. HRESULT hr = D3DXCreateTexture(d3d9Device, (UINT)mWidth, (UINT)mHeight, numMips,
  352. usage, d3dPF, mD3DPool, &textureResources->pNormTex);
  353. if (FAILED(hr))
  354. {
  355. destroy_internal();
  356. BS_EXCEPT(RenderingAPIException, "Error creating texture: " + String(DXGetErrorDescription(hr)));
  357. }
  358. hr = textureResources->pNormTex->QueryInterface(IID_IDirect3DBaseTexture9, (void **)&textureResources->pBaseTex);
  359. if (FAILED(hr))
  360. {
  361. destroy_internal();
  362. BS_EXCEPT(RenderingAPIException, "Can't get base texture: " + String(DXGetErrorDescription(hr)));
  363. }
  364. // Update final parameters as they may differ from requested ones
  365. D3DSURFACE_DESC desc;
  366. hr = textureResources->pNormTex->GetLevelDesc(0, &desc);
  367. if (FAILED(hr))
  368. {
  369. destroy_internal();
  370. BS_EXCEPT(RenderingAPIException, "Can't get texture description: " + String(DXGetErrorDescription(hr)));
  371. }
  372. setFinalAttributes(d3d9Device, textureResources, desc.Width, desc.Height, 1, D3D9Mappings::_getPF(desc.Format));
  373. }
  374. }
  375. void D3D9Texture::createCubeTex(IDirect3DDevice9* d3d9Device)
  376. {
  377. assert(mWidth > 0 || mHeight > 0);
  378. if (mUsage & TU_RENDERTARGET)
  379. BS_EXCEPT(RenderingAPIException, "D3D9 Cube texture can not be created as render target !!");
  380. if (mUsage & TU_DEPTHSTENCIL)
  381. BS_EXCEPT(RenderingAPIException, "D3D9 Cube texture can not be created as a depth stencil target !!");
  382. D3DFORMAT d3dPF = chooseD3DFormat(d3d9Device);
  383. if(mFormat != D3D9Mappings::_getPF(d3dPF))
  384. {
  385. BS_EXCEPT(RenderingAPIException, "Provided pixel format is not supported by the driver: " + toString(mFormat));
  386. }
  387. // Use D3DX to help us create the texture, this way it can adjust any relevant sizes
  388. DWORD usage = (mUsage & TU_RENDERTARGET) ? D3DUSAGE_RENDERTARGET : 0;
  389. UINT numMips = (mNumMipmaps == MIP_UNLIMITED) ? D3DX_DEFAULT : mNumMipmaps + 1;
  390. // Check dynamic textures
  391. if (mUsage & TU_DYNAMIC)
  392. {
  393. if (canUseDynamicTextures(d3d9Device, usage, D3DRTYPE_CUBETEXTURE, d3dPF))
  394. {
  395. usage |= D3DUSAGE_DYNAMIC;
  396. mDynamicTextures = true;
  397. }
  398. else
  399. {
  400. mDynamicTextures = false;
  401. }
  402. }
  403. // Check sRGB support
  404. if (mHwGamma)
  405. {
  406. mHwGammaReadSupported = canUseHardwareGammaCorrection(d3d9Device, usage, D3DRTYPE_CUBETEXTURE, d3dPF, false);
  407. if (mUsage & TU_RENDERTARGET)
  408. mHwGammaWriteSupported = canUseHardwareGammaCorrection(d3d9Device, usage, D3DRTYPE_CUBETEXTURE, d3dPF, true);
  409. }
  410. // No multisampling on cube textures
  411. mMultisampleType = D3DMULTISAMPLE_NONE;
  412. mMultisampleQuality = 0;
  413. D3D9Device* device = D3D9RenderSystem::getDeviceManager()->getDeviceFromD3D9Device(d3d9Device);
  414. const D3DCAPS9& deviceCaps = device->getD3D9DeviceCaps();
  415. // Check if mip map cube textures are supported
  416. if (numMips > 1 && !(deviceCaps.TextureCaps & D3DPTEXTURECAPS_MIPCUBEMAP))
  417. {
  418. BS_EXCEPT(InvalidParametersException, "Invalid number of mipmaps. Maximum allowed is: 0");
  419. }
  420. determinePool();
  421. TextureResources* textureResources;
  422. // Get or create new texture resources structure.
  423. textureResources = getTextureResources(d3d9Device);
  424. if (textureResources != NULL)
  425. freeTextureResources(d3d9Device, textureResources);
  426. else
  427. textureResources = allocateTextureResources(d3d9Device);
  428. // Create the texture
  429. HRESULT hr = D3DXCreateCubeTexture(d3d9Device, (UINT)mWidth, numMips,
  430. usage, d3dPF, mD3DPool, &textureResources->pCubeTex);
  431. if (FAILED(hr))
  432. {
  433. destroy_internal();
  434. BS_EXCEPT(RenderingAPIException, "Error creating texture: " + String(DXGetErrorDescription(hr)));
  435. }
  436. hr = textureResources->pCubeTex->QueryInterface(IID_IDirect3DBaseTexture9, (void **)&textureResources->pBaseTex);
  437. if (FAILED(hr))
  438. {
  439. destroy_internal();
  440. BS_EXCEPT(RenderingAPIException, "Can't get base texture: " + String(DXGetErrorDescription(hr)));
  441. }
  442. // Update final parameters as they may differ from requested ones
  443. D3DSURFACE_DESC desc;
  444. hr = textureResources->pCubeTex->GetLevelDesc(0, &desc);
  445. if (FAILED(hr))
  446. {
  447. destroy_internal();
  448. BS_EXCEPT(RenderingAPIException, "Can't get texture description: " + String(DXGetErrorDescription(hr)));
  449. }
  450. setFinalAttributes(d3d9Device, textureResources, desc.Width, desc.Height, 1, D3D9Mappings::_getPF(desc.Format));
  451. }
  452. void D3D9Texture::createVolumeTex(IDirect3DDevice9* d3d9Device)
  453. {
  454. assert(mWidth > 0 && mHeight > 0 && mDepth>0);
  455. if (mUsage & TU_RENDERTARGET)
  456. BS_EXCEPT(RenderingAPIException, "D3D9 Volume texture can not be created as render target !!");
  457. if (mUsage & TU_DEPTHSTENCIL)
  458. BS_EXCEPT(RenderingAPIException, "D3D9 Volume texture can not be created as a depth stencil target !!");
  459. D3DFORMAT d3dPF = chooseD3DFormat(d3d9Device);
  460. if(mFormat != D3D9Mappings::_getPF(d3dPF))
  461. {
  462. BS_EXCEPT(RenderingAPIException, "Provided pixel format is not supported by the driver: " + toString(mFormat));
  463. }
  464. // Use D3DX to help us create the texture, this way it can adjust any relevant sizes
  465. DWORD usage = (mUsage & TU_RENDERTARGET) ? D3DUSAGE_RENDERTARGET : 0;
  466. UINT numMips = (mNumMipmaps == MIP_UNLIMITED) ? D3DX_DEFAULT : mNumMipmaps + 1;
  467. // Check dynamic textures
  468. if (mUsage & TU_DYNAMIC)
  469. {
  470. if (canUseDynamicTextures(d3d9Device, usage, D3DRTYPE_VOLUMETEXTURE, d3dPF))
  471. {
  472. usage |= D3DUSAGE_DYNAMIC;
  473. mDynamicTextures = true;
  474. }
  475. else
  476. {
  477. mDynamicTextures = false;
  478. }
  479. }
  480. // Check sRGB support
  481. if (mHwGamma)
  482. {
  483. mHwGammaReadSupported = canUseHardwareGammaCorrection(d3d9Device, usage, D3DRTYPE_VOLUMETEXTURE, d3dPF, false);
  484. if (mUsage & TU_RENDERTARGET)
  485. mHwGammaWriteSupported = canUseHardwareGammaCorrection(d3d9Device, usage, D3DRTYPE_VOLUMETEXTURE, d3dPF, true);
  486. }
  487. D3D9Device* device = D3D9RenderSystem::getDeviceManager()->getDeviceFromD3D9Device(d3d9Device);
  488. const D3DCAPS9& rkCurCaps = device->getD3D9DeviceCaps();
  489. // Check if mip map volume textures are supported
  490. if (numMips > 1 && !(rkCurCaps.TextureCaps & D3DPTEXTURECAPS_MIPVOLUMEMAP))
  491. {
  492. BS_EXCEPT(InvalidParametersException, "Invalid number of mipmaps. Maximum allowed is: 0");
  493. }
  494. determinePool();
  495. TextureResources* textureResources;
  496. // Get or create new texture resources structure.
  497. textureResources = getTextureResources(d3d9Device);
  498. if (textureResources != NULL)
  499. freeTextureResources(d3d9Device, textureResources);
  500. else
  501. textureResources = allocateTextureResources(d3d9Device);
  502. // Create the texture
  503. HRESULT hr = D3DXCreateVolumeTexture(d3d9Device, (UINT)mWidth, (UINT)mHeight, (UINT)mDepth,
  504. numMips, usage, d3dPF, mD3DPool, &textureResources->pVolumeTex);
  505. if (FAILED(hr))
  506. {
  507. destroy_internal();
  508. BS_EXCEPT(RenderingAPIException, "Error creating texture: " + String(DXGetErrorDescription(hr)));
  509. }
  510. hr = textureResources->pVolumeTex->QueryInterface(IID_IDirect3DBaseTexture9, (void**)&textureResources->pBaseTex);
  511. if (FAILED(hr))
  512. {
  513. destroy_internal();
  514. BS_EXCEPT(RenderingAPIException, "Can't get base texture: " + String(DXGetErrorDescription(hr)));
  515. }
  516. // Update final parameters as they may differ from requested ones
  517. D3DVOLUME_DESC desc;
  518. hr = textureResources->pVolumeTex->GetLevelDesc(0, &desc);
  519. if (FAILED(hr))
  520. {
  521. destroy_internal();
  522. BS_EXCEPT(RenderingAPIException, "Can't get texture description: " + String(DXGetErrorDescription(hr)));
  523. }
  524. setFinalAttributes(d3d9Device, textureResources, desc.Width, desc.Height, desc.Depth, D3D9Mappings::_getPF(desc.Format));
  525. }
  526. void D3D9Texture::setFinalAttributes(IDirect3DDevice9* d3d9Device, TextureResources* textureResources,
  527. UINT32 width, UINT32 height, UINT32 depth, PixelFormat format)
  528. {
  529. if(width != mWidth || height != mHeight || depth != mDepth)
  530. {
  531. BS_EXCEPT(InternalErrorException, "Wanted and created textures sizes don't match!" \
  532. "Width: " + toString(width) + "/" + toString(mWidth) +
  533. "Height: " + toString(height) + "/" + toString(mHeight) +
  534. "Depth: " + toString(depth) + "/" + toString(mDepth));
  535. }
  536. if(format != mFormat)
  537. {
  538. BS_EXCEPT(InternalErrorException, "Wanted and created texture formats don't match! " + toString(format) + "/" + toString(mFormat));
  539. }
  540. createSurfaceList(d3d9Device, textureResources);
  541. }
  542. D3DTEXTUREFILTERTYPE D3D9Texture::getBestFilterMethod(IDirect3DDevice9* d3d9Device)
  543. {
  544. D3D9Device* device = D3D9RenderSystem::getDeviceManager()->getDeviceFromD3D9Device(d3d9Device);
  545. const D3DCAPS9& deviceCaps = device->getD3D9DeviceCaps();
  546. DWORD filterCaps = 0;
  547. switch (getTextureType())
  548. {
  549. case TEX_TYPE_1D:
  550. // Same as 2D
  551. case TEX_TYPE_2D:
  552. filterCaps = deviceCaps.TextureFilterCaps;
  553. break;
  554. case TEX_TYPE_3D:
  555. filterCaps = deviceCaps.VolumeTextureFilterCaps;
  556. break;
  557. case TEX_TYPE_CUBE_MAP:
  558. filterCaps = deviceCaps.CubeTextureFilterCaps;
  559. break;
  560. }
  561. if(filterCaps & D3DPTFILTERCAPS_MINFGAUSSIANQUAD)
  562. return D3DTEXF_GAUSSIANQUAD;
  563. if(filterCaps & D3DPTFILTERCAPS_MINFPYRAMIDALQUAD)
  564. return D3DTEXF_PYRAMIDALQUAD;
  565. if(filterCaps & D3DPTFILTERCAPS_MINFANISOTROPIC)
  566. return D3DTEXF_ANISOTROPIC;
  567. if(filterCaps & D3DPTFILTERCAPS_MINFLINEAR)
  568. return D3DTEXF_LINEAR;
  569. if(filterCaps & D3DPTFILTERCAPS_MINFPOINT)
  570. return D3DTEXF_POINT;
  571. return D3DTEXF_POINT;
  572. }
  573. bool D3D9Texture::canUseDynamicTextures(IDirect3DDevice9* d3d9Device, DWORD srcUsage, D3DRESOURCETYPE srcType,
  574. D3DFORMAT srcFormat)
  575. {
  576. IDirect3D9* pD3D = nullptr;
  577. HRESULT hr = d3d9Device->GetDirect3D(&pD3D);
  578. if (FAILED(hr))
  579. BS_EXCEPT(InvalidParametersException, "GetDirect3D failed !!!");
  580. if (pD3D != nullptr)
  581. pD3D->Release();
  582. D3D9Device* device = D3D9RenderSystem::getDeviceManager()->getDeviceFromD3D9Device(d3d9Device);
  583. const D3DCAPS9& deviceCaps = device->getD3D9DeviceCaps();
  584. D3DFORMAT backBufferFormat = device->getBackBufferFormat();
  585. hr = pD3D->CheckDeviceFormat(deviceCaps.AdapterOrdinal, deviceCaps.DeviceType,
  586. backBufferFormat, srcUsage | D3DUSAGE_DYNAMIC, srcType, srcFormat);
  587. return hr == D3D_OK;
  588. }
  589. bool D3D9Texture::canUseHardwareGammaCorrection(IDirect3DDevice9* d3d9Device, DWORD srcUsage,
  590. D3DRESOURCETYPE srcType, D3DFORMAT srcFormat, bool forwriting)
  591. {
  592. IDirect3D9* pD3D = nullptr;
  593. HRESULT hr = d3d9Device->GetDirect3D(&pD3D);
  594. if (FAILED(hr))
  595. {
  596. BS_EXCEPT(InvalidParametersException, "GetDirect3D failed !!!" );
  597. }
  598. if (pD3D != nullptr)
  599. pD3D->Release();
  600. D3D9Device* device = D3D9RenderSystem::getDeviceManager()->getDeviceFromD3D9Device(d3d9Device);
  601. const D3DCAPS9& deviceCaps = device->getD3D9DeviceCaps();
  602. D3DFORMAT backBufferFormat = device->getBackBufferFormat();
  603. if (forwriting)
  604. srcUsage |= D3DUSAGE_QUERY_SRGBWRITE;
  605. else
  606. srcUsage |= D3DUSAGE_QUERY_SRGBREAD;
  607. hr = pD3D->CheckDeviceFormat(deviceCaps.AdapterOrdinal, deviceCaps.DeviceType,
  608. backBufferFormat, srcUsage, srcType, srcFormat);
  609. return hr == D3D_OK;
  610. }
  611. bool D3D9Texture::canAutoGenMipmaps(IDirect3DDevice9* d3d9Device, DWORD srcUsage, D3DRESOURCETYPE srcType, D3DFORMAT srcFormat)
  612. {
  613. IDirect3D9* pD3D = nullptr;
  614. HRESULT hr = d3d9Device->GetDirect3D(&pD3D);
  615. if (FAILED(hr))
  616. {
  617. BS_EXCEPT(InvalidParametersException, "GetDirect3D failed.");
  618. }
  619. if (pD3D != nullptr)
  620. pD3D->Release();
  621. D3D9Device* device = D3D9RenderSystem::getDeviceManager()->getDeviceFromD3D9Device(d3d9Device);
  622. const D3DCAPS9& deviceCaps = device->getD3D9DeviceCaps();
  623. D3DFORMAT backBufferFormat = device->getBackBufferFormat();
  624. if (deviceCaps.Caps2 & D3DCAPS2_CANAUTOGENMIPMAP)
  625. {
  626. hr = pD3D->CheckDeviceFormat(deviceCaps.AdapterOrdinal, deviceCaps.DeviceType,
  627. backBufferFormat, srcUsage | D3DUSAGE_AUTOGENMIPMAP, srcType, srcFormat);
  628. return hr == D3D_OK;
  629. }
  630. else
  631. return false;
  632. }
  633. D3DFORMAT D3D9Texture::chooseD3DFormat(IDirect3DDevice9* d3d9Device)
  634. {
  635. // Choose frame buffer pixel format in case PF_UNKNOWN was requested
  636. if(mFormat == PF_UNKNOWN)
  637. {
  638. D3D9Device* device = D3D9RenderSystem::getDeviceManager()->getDeviceFromD3D9Device(d3d9Device);
  639. if((mUsage & TU_DEPTHSTENCIL) != 0)
  640. return device->getDepthStencilFormat();
  641. else
  642. return device->getBackBufferFormat();
  643. }
  644. // Choose closest supported D3D format as a D3D format
  645. return D3D9Mappings::_getPF(D3D9Mappings::_getClosestSupportedPF(mFormat));
  646. }
  647. void D3D9Texture::createSurfaceList(IDirect3DDevice9* d3d9Device, TextureResources* textureResources)
  648. {
  649. assert(textureResources != nullptr);
  650. // Need to know static / dynamic
  651. UINT32 usage;
  652. if ((mUsage & TU_DYNAMIC) && mDynamicTextures)
  653. {
  654. usage = GBU_DYNAMIC;
  655. }
  656. else
  657. {
  658. usage = GBU_STATIC;
  659. }
  660. if (mUsage & TU_RENDERTARGET)
  661. {
  662. usage |= TU_RENDERTARGET;
  663. }
  664. else if(mUsage & TU_DEPTHSTENCIL)
  665. {
  666. usage |= TU_RENDERTARGET;
  667. }
  668. UINT32 surfaceCount = static_cast<UINT32>((getNumFaces() * (mNumMipmaps + 1)));
  669. bool updateOldList = mSurfaceList.size() == surfaceCount;
  670. if(!updateOldList)
  671. {
  672. mSurfaceList.clear();
  673. for(UINT32 face = 0; face < getNumFaces(); face++)
  674. {
  675. for(UINT32 mip = 0; mip <= mNumMipmaps; mip++)
  676. {
  677. mSurfaceList.push_back(bs_shared_ptr<D3D9PixelBuffer>((GpuBufferUsage)usage, this));
  678. }
  679. }
  680. }
  681. IDirect3DSurface9* surface = nullptr;
  682. IDirect3DVolume9* volume = nullptr;
  683. if((mUsage & TU_RENDERTARGET) != 0 && (mMultisampleType != D3DMULTISAMPLE_NONE))
  684. {
  685. assert(textureResources->pMultisampleSurface);
  686. assert(getTextureType() == TEX_TYPE_2D);
  687. D3D9PixelBuffer* currPixelBuffer = static_cast<D3D9PixelBuffer*>(mSurfaceList[0].get());
  688. currPixelBuffer->bind(d3d9Device, textureResources->pMultisampleSurface, textureResources->pBaseTex);
  689. }
  690. else if((mUsage & TU_DEPTHSTENCIL) != 0 && (mMultisampleType != D3DMULTISAMPLE_NONE))
  691. {
  692. assert(textureResources->pDepthStencilSurface);
  693. assert(getTextureType() == TEX_TYPE_2D);
  694. D3D9PixelBuffer* currPixelBuffer = static_cast<D3D9PixelBuffer*>(mSurfaceList[0].get());
  695. currPixelBuffer->bind(d3d9Device, textureResources->pDepthStencilSurface, textureResources->pBaseTex);
  696. }
  697. else
  698. {
  699. assert(textureResources->pBaseTex);
  700. UINT32 numCreatedMips = textureResources->pBaseTex->GetLevelCount() - 1;
  701. if(numCreatedMips != mNumMipmaps)
  702. {
  703. BS_EXCEPT(InternalErrorException, "Number of created and wanted mip map levels doesn't match: " +
  704. toString(numCreatedMips) + "/" + toString(mNumMipmaps));
  705. }
  706. switch(getTextureType())
  707. {
  708. case TEX_TYPE_2D:
  709. case TEX_TYPE_1D:
  710. assert(textureResources->pNormTex);
  711. for(UINT32 mip = 0; mip <= mNumMipmaps; mip++)
  712. {
  713. if(textureResources->pNormTex->GetSurfaceLevel(static_cast<UINT>(mip), &surface) != D3D_OK)
  714. BS_EXCEPT(RenderingAPIException, "Get surface level failed");
  715. D3D9PixelBuffer* currPixelBuffer = static_cast<D3D9PixelBuffer*>(mSurfaceList[mip].get());
  716. currPixelBuffer->bind(d3d9Device, surface, textureResources->pBaseTex);
  717. surface->Release();
  718. }
  719. break;
  720. case TEX_TYPE_CUBE_MAP:
  721. assert(textureResources->pCubeTex);
  722. for(UINT32 face = 0; face < 6; face++)
  723. {
  724. for(UINT32 mip = 0; mip <= mNumMipmaps; mip++)
  725. {
  726. if(textureResources->pCubeTex->GetCubeMapSurface((D3DCUBEMAP_FACES)face, static_cast<UINT>(mip), &surface) != D3D_OK)
  727. BS_EXCEPT(RenderingAPIException, "Get cubemap surface failed");
  728. UINT32 idx = face*(mNumMipmaps + 1) + mip;
  729. D3D9PixelBuffer* currPixelBuffer = static_cast<D3D9PixelBuffer*>(mSurfaceList[idx].get());
  730. currPixelBuffer->bind(d3d9Device, surface, textureResources->pBaseTex);
  731. surface->Release();
  732. }
  733. }
  734. break;
  735. case TEX_TYPE_3D:
  736. assert(textureResources->pVolumeTex);
  737. for(UINT32 mip = 0; mip <= mNumMipmaps; mip++)
  738. {
  739. if(textureResources->pVolumeTex->GetVolumeLevel(static_cast<UINT>(mip), &volume) != D3D_OK)
  740. BS_EXCEPT(RenderingAPIException, "Get volume level failed");
  741. D3D9PixelBuffer* currPixelBuffer = static_cast<D3D9PixelBuffer*>(mSurfaceList[mip].get());
  742. currPixelBuffer->bind(d3d9Device, volume, textureResources->pBaseTex);
  743. volume->Release();
  744. }
  745. break;
  746. };
  747. }
  748. }
  749. PixelBufferPtr D3D9Texture::getBuffer(UINT32 face, UINT32 mipmap)
  750. {
  751. THROW_IF_NOT_CORE_THREAD;
  752. if(face >= getNumFaces())
  753. BS_EXCEPT(InvalidParametersException, "A three dimensional cube has six faces");
  754. if(mipmap > mNumMipmaps)
  755. BS_EXCEPT(InvalidParametersException, "Mipmap index out of range");
  756. UINT32 idx = face*(mNumMipmaps+1) + mipmap;
  757. IDirect3DDevice9* d3d9Device = D3D9RenderSystem::getActiveD3D9Device();
  758. TextureResources* textureResources = getTextureResources(d3d9Device);
  759. if (textureResources == nullptr || textureResources->pBaseTex == nullptr)
  760. {
  761. createInternalResources(d3d9Device);
  762. textureResources = getTextureResources(d3d9Device);
  763. }
  764. assert(textureResources != nullptr);
  765. assert(idx < mSurfaceList.size());
  766. return mSurfaceList[idx];
  767. }
  768. bool D3D9Texture::useDefaultPool()
  769. {
  770. return (mUsage & TU_RENDERTARGET) || (mUsage & TU_DEPTHSTENCIL) || ((mUsage & TU_DYNAMIC) && mDynamicTextures);
  771. }
  772. void D3D9Texture::notifyOnDeviceCreate(IDirect3DDevice9* d3d9Device)
  773. {
  774. D3D9_DEVICE_ACCESS_CRITICAL_SECTION
  775. if (D3D9RenderSystem::getResourceManager()->getCreationPolicy() == RCP_CREATE_ON_ALL_DEVICES)
  776. createInternalResources(d3d9Device);
  777. }
  778. void D3D9Texture::notifyOnDeviceDestroy(IDirect3DDevice9* d3d9Device)
  779. {
  780. D3D9_DEVICE_ACCESS_CRITICAL_SECTION
  781. auto iterFind = mMapDeviceToTextureResources.find(d3d9Device);
  782. if (iterFind != mMapDeviceToTextureResources.end())
  783. {
  784. TextureResources* textureResource = iterFind->second;
  785. for(unsigned int i = 0; i < mSurfaceList.size(); ++i)
  786. {
  787. D3D9PixelBuffer* pixelBuffer = static_cast<D3D9PixelBuffer*>(mSurfaceList[i].get());
  788. pixelBuffer->destroyBufferResources(d3d9Device);
  789. }
  790. freeTextureResources(d3d9Device, textureResource);
  791. if(textureResource != nullptr)
  792. bs_delete(textureResource);
  793. mMapDeviceToTextureResources.erase(iterFind);
  794. }
  795. }
  796. void D3D9Texture::notifyOnDeviceLost(IDirect3DDevice9* d3d9Device)
  797. {
  798. D3D9_DEVICE_ACCESS_CRITICAL_SECTION
  799. if(mD3DPool == D3DPOOL_DEFAULT)
  800. {
  801. auto iterFind = mMapDeviceToTextureResources.find(d3d9Device);
  802. if (iterFind != mMapDeviceToTextureResources.end())
  803. {
  804. TextureResources* textureResource = iterFind->second;
  805. freeTextureResources(d3d9Device, textureResource);
  806. }
  807. }
  808. }
  809. void D3D9Texture::notifyOnDeviceReset(IDirect3DDevice9* d3d9Device)
  810. {
  811. D3D9_DEVICE_ACCESS_CRITICAL_SECTION
  812. if(mD3DPool == D3DPOOL_DEFAULT)
  813. {
  814. createInternalResources(d3d9Device);
  815. }
  816. }
  817. IDirect3DBaseTexture9* D3D9Texture::getTexture_internal()
  818. {
  819. THROW_IF_NOT_CORE_THREAD;
  820. TextureResources* textureResources;
  821. IDirect3DDevice9* d3d9Device = D3D9RenderSystem::getActiveD3D9Device();
  822. textureResources = getTextureResources(d3d9Device);
  823. if (textureResources == nullptr || textureResources->pBaseTex == nullptr)
  824. {
  825. createInternalResources(d3d9Device);
  826. textureResources = getTextureResources(d3d9Device);
  827. }
  828. assert(textureResources);
  829. assert(textureResources->pBaseTex);
  830. return textureResources->pBaseTex;
  831. }
  832. IDirect3DTexture9* D3D9Texture::getNormTexture_internal()
  833. {
  834. THROW_IF_NOT_CORE_THREAD;
  835. TextureResources* textureResources;
  836. IDirect3DDevice9* d3d9Device = D3D9RenderSystem::getActiveD3D9Device();
  837. textureResources = getTextureResources(d3d9Device);
  838. if (textureResources == nullptr || textureResources->pNormTex == nullptr)
  839. {
  840. createInternalResources(d3d9Device);
  841. textureResources = getTextureResources(d3d9Device);
  842. }
  843. assert(textureResources);
  844. assert(textureResources->pNormTex);
  845. return textureResources->pNormTex;
  846. }
  847. IDirect3DCubeTexture9* D3D9Texture::getCubeTexture_internal()
  848. {
  849. THROW_IF_NOT_CORE_THREAD;
  850. TextureResources* textureResources;
  851. IDirect3DDevice9* d3d9Device = D3D9RenderSystem::getActiveD3D9Device();
  852. textureResources = getTextureResources(d3d9Device);
  853. if (textureResources == nullptr || textureResources->pCubeTex)
  854. {
  855. createInternalResources(d3d9Device);
  856. textureResources = getTextureResources(d3d9Device);
  857. }
  858. assert(textureResources);
  859. assert(textureResources->pCubeTex);
  860. return textureResources->pCubeTex;
  861. }
  862. }