BsD3D9Texture.cpp 33 KB

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