BsD3D9Texture.cpp 33 KB

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