BsD3D9Texture.cpp 33 KB

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