BsD3D9RenderSystem.cpp 69 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314
  1. #include "BsD3D9RenderSystem.h"
  2. #include "BsD3D9Prerequisites.h"
  3. #include "BsD3D9DriverList.h"
  4. #include "BsD3D9Driver.h"
  5. #include "BsD3D9RenderWindow.h"
  6. #include "BsD3D9TextureManager.h"
  7. #include "BsD3D9Texture.h"
  8. #include "BsMath.h"
  9. #include "BsD3D9HardwareBufferManager.h"
  10. #include "BsD3D9IndexBuffer.h"
  11. #include "BsD3D9VertexBuffer.h"
  12. #include "BsD3D9VertexDeclaration.h"
  13. #include "BsD3D9GpuProgram.h"
  14. #include "BsD3D9HLSLProgramFactory.h"
  15. #include "BsD3D9OcclusionQuery.h"
  16. #include "BsD3D9DeviceManager.h"
  17. #include "BsD3D9ResourceManager.h"
  18. #include "BsD3D9RenderWindowManager.h"
  19. #include "BsGpuProgramManager.h"
  20. #include "BsRenderStateManager.h"
  21. #include "BsAsyncOp.h"
  22. #include "BsBlendState.h"
  23. #include "BsRasterizerState.h"
  24. #include "BsDepthStencilState.h"
  25. #include "BsGpuParams.h"
  26. #include "BsGpuParamDesc.h"
  27. #include "BsGpuParamBlockBuffer.h"
  28. #include "BsCoreThread.h"
  29. #include "BsD3D9QueryManager.h"
  30. #include "BsDebug.h"
  31. #include "BsRenderStats.h"
  32. namespace BansheeEngine
  33. {
  34. D3D9RenderSystem* D3D9RenderSystem::msD3D9RenderSystem = nullptr;
  35. D3D9RenderSystem::D3D9RenderSystem(HINSTANCE hInstance)
  36. : mTexStageDesc(nullptr), mNumTexStages(0), mCurrentDrawOperation(DOT_TRIANGLE_LIST),
  37. mViewportLeft(0), mViewportTop(0), mViewportWidth(0), mViewportHeight(0),
  38. mIsFrameInProgress(false), mRestoreFrameOnReset(false), mhInstance(hInstance),
  39. mpD3D(nullptr), mDriverList(nullptr), mActiveD3DDriver(nullptr), mHLSLProgramFactory(nullptr),
  40. mDeviceManager(nullptr), mResourceManager(nullptr)
  41. {
  42. msD3D9RenderSystem = this;
  43. mScissorRect.left = 0;
  44. mScissorRect.right = 1280;
  45. mScissorRect.top = 0;
  46. mScissorRect.bottom = 720;
  47. }
  48. D3D9RenderSystem::~D3D9RenderSystem()
  49. {
  50. }
  51. const String& D3D9RenderSystem::getName() const
  52. {
  53. static String strName( "D3D9RenderSystem");
  54. return strName;
  55. }
  56. const String& D3D9RenderSystem::getShadingLanguageName() const
  57. {
  58. static String strName("hlsl");
  59. return strName;
  60. }
  61. void D3D9RenderSystem::initialize_internal(AsyncOp& asyncOp)
  62. {
  63. THROW_IF_NOT_CORE_THREAD;
  64. // Create the resource manager.
  65. mResourceManager = bs_new<D3D9ResourceManager>();
  66. // Create our Direct3D object
  67. if( NULL == (mpD3D = Direct3DCreate9(D3D_SDK_VERSION)) )
  68. BS_EXCEPT(InternalErrorException, "Failed to create Direct3D9 object");
  69. RenderWindow* autoWindow = NULL;
  70. // Init using current settings
  71. mActiveD3DDriver = getDirect3DDrivers()->item(0); // TODO - We always use the first driver
  72. if( !mActiveD3DDriver )
  73. BS_EXCEPT(InvalidParametersException, "Problems finding requested Direct3D driver!" );
  74. // get driver version
  75. mDriverVersion.major = HIWORD(mActiveD3DDriver->getAdapterIdentifier().DriverVersion.HighPart);
  76. mDriverVersion.minor = LOWORD(mActiveD3DDriver->getAdapterIdentifier().DriverVersion.HighPart);
  77. mDriverVersion.release = HIWORD(mActiveD3DDriver->getAdapterIdentifier().DriverVersion.LowPart);
  78. mDriverVersion.build = LOWORD(mActiveD3DDriver->getAdapterIdentifier().DriverVersion.LowPart);
  79. mVideoModeInfo = getDirect3DDrivers()->getVideoModeInfo();
  80. // Create the device manager.
  81. mDeviceManager = bs_new<D3D9DeviceManager>();
  82. // Also create hardware buffer manager
  83. HardwareBufferManager::startUp<D3D9HardwareBufferManager>();
  84. // Create & register HLSL factory
  85. mHLSLProgramFactory = bs_new<D3D9HLSLProgramFactory>();
  86. // Create render window manager
  87. RenderWindowManager::startUp<D3D9RenderWindowManager>(this);
  88. // Create render state manager
  89. RenderStateManager::startUp();
  90. // Create primary window and finalize initialization
  91. RenderWindowPtr primaryWindow = RenderWindow::create(mPrimaryWindowDesc);
  92. D3D9RenderWindow* d3d9renderWindow = static_cast<D3D9RenderWindow*>(primaryWindow.get());
  93. updateRenderSystemCapabilities(d3d9renderWindow);
  94. // Create the texture manager for use by others
  95. TextureManager::startUp<D3D9TextureManager>();
  96. QueryManager::startUp<D3D9QueryManager>();
  97. // call superclass method
  98. RenderSystem::initialize_internal(asyncOp);
  99. asyncOp._completeOperation(primaryWindow);
  100. }
  101. void D3D9RenderSystem::destroy_internal()
  102. {
  103. if(mTexStageDesc != nullptr)
  104. {
  105. bs_deleteN(mTexStageDesc, mNumTexStages);
  106. mTexStageDesc = nullptr;
  107. }
  108. RenderSystem::destroy_internal();
  109. if(mDeviceManager != nullptr)
  110. {
  111. bs_delete(mDeviceManager);
  112. mDeviceManager = nullptr;
  113. }
  114. if(mDriverList != nullptr)
  115. {
  116. bs_delete(mDriverList);
  117. mDriverList = nullptr;
  118. }
  119. mActiveD3DDriver = NULL;
  120. QueryManager::shutDown();
  121. TextureManager::shutDown();
  122. HardwareBufferManager::shutDown();
  123. RenderWindowManager::shutDown();
  124. RenderStateManager::shutDown();
  125. // Deleting the HLSL program factory
  126. if (mHLSLProgramFactory)
  127. {
  128. GpuProgramManager::instance().removeFactory(mHLSLProgramFactory);
  129. bs_delete(mHLSLProgramFactory);
  130. mHLSLProgramFactory = 0;
  131. }
  132. SAFE_RELEASE(mpD3D);
  133. if(mResourceManager != nullptr)
  134. {
  135. bs_delete(mResourceManager);
  136. mResourceManager = nullptr;
  137. }
  138. msD3D9RenderSystem = NULL;
  139. }
  140. void D3D9RenderSystem::registerWindow(RenderWindowCore& renderWindow)
  141. {
  142. THROW_IF_NOT_CORE_THREAD;
  143. D3D9RenderWindowCore* d3d9renderWindow = static_cast<D3D9RenderWindowCore*>(&renderWindow);
  144. String msg;
  145. mResourceManager->lockDeviceAccess();
  146. try
  147. {
  148. mDeviceManager->linkRenderWindow(d3d9renderWindow);
  149. }
  150. catch (const BansheeEngine::RenderingAPIException&)
  151. {
  152. // after catching the exception, clean up
  153. mResourceManager->unlockDeviceAccess();
  154. // re-throw
  155. throw;
  156. }
  157. mResourceManager->unlockDeviceAccess();
  158. }
  159. void D3D9RenderSystem::bindGpuProgram(HGpuProgram prg)
  160. {
  161. THROW_IF_NOT_CORE_THREAD;
  162. if(!prg.isLoaded())
  163. return;
  164. GpuProgramPtr bindingPrg = std::static_pointer_cast<GpuProgram>(prg->getThisPtr());
  165. HRESULT hr;
  166. switch (bindingPrg->getType())
  167. {
  168. case GPT_VERTEX_PROGRAM:
  169. hr = getActiveD3D9Device()->SetVertexShader(
  170. static_cast<D3D9GpuVertexProgram*>(bindingPrg.get())->getVertexShader());
  171. if (FAILED(hr))
  172. {
  173. BS_EXCEPT(RenderingAPIException, "Error calling SetVertexShader");
  174. }
  175. break;
  176. case GPT_FRAGMENT_PROGRAM:
  177. hr = getActiveD3D9Device()->SetPixelShader(
  178. static_cast<D3D9GpuFragmentProgram*>(bindingPrg.get())->getPixelShader());
  179. if (FAILED(hr))
  180. {
  181. BS_EXCEPT(RenderingAPIException, "Error calling SetPixelShader");
  182. }
  183. break;
  184. };
  185. // Make sure texcoord index is equal to stage value, As SDK Doc suggests:
  186. // "When rendering using vertex shaders, each stage's texture coordinate index must be set to its default value."
  187. // This solves such an errors when working with the Debug runtime -
  188. // "Direct3D9: (ERROR) :Stage 1 - Texture coordinate index in the stage must be equal to the stage index when programmable vertex pipeline is used".
  189. for (unsigned int nStage=0; nStage < 8; ++nStage)
  190. setTextureStageState(nStage, D3DTSS_TEXCOORDINDEX, nStage);
  191. BS_INC_RENDER_STAT(NumGpuProgramBinds);
  192. RenderSystem::bindGpuProgram(prg);
  193. }
  194. void D3D9RenderSystem::unbindGpuProgram(GpuProgramType gptype)
  195. {
  196. THROW_IF_NOT_CORE_THREAD;
  197. HRESULT hr;
  198. switch(gptype)
  199. {
  200. case GPT_VERTEX_PROGRAM:
  201. hr = getActiveD3D9Device()->SetVertexShader(NULL);
  202. if (FAILED(hr))
  203. {
  204. BS_EXCEPT(RenderingAPIException, "Error resetting SetVertexShader to NULL");
  205. }
  206. break;
  207. case GPT_FRAGMENT_PROGRAM:
  208. hr = getActiveD3D9Device()->SetPixelShader(NULL);
  209. if (FAILED(hr))
  210. {
  211. BS_EXCEPT(RenderingAPIException, "Error resetting SetPixelShader to NULL");
  212. }
  213. break;
  214. };
  215. BS_INC_RENDER_STAT(NumGpuProgramBinds);
  216. RenderSystem::unbindGpuProgram(gptype);
  217. }
  218. void D3D9RenderSystem::bindGpuParams(GpuProgramType gptype, GpuParamsPtr bindableParams)
  219. {
  220. THROW_IF_NOT_CORE_THREAD;
  221. bindableParams->updateHardwareBuffers();
  222. const GpuParamDesc& paramDesc = bindableParams->getParamDesc();
  223. for(auto iter = paramDesc.samplers.begin(); iter != paramDesc.samplers.end(); ++iter)
  224. {
  225. HSamplerState& samplerState = bindableParams->getSamplerState(iter->second.slot);
  226. if(samplerState == nullptr)
  227. setSamplerState(gptype, iter->second.slot, SamplerState::getDefault());
  228. else
  229. setSamplerState(gptype, iter->second.slot, samplerState.getInternalPtr());
  230. }
  231. for(auto iter = paramDesc.textures.begin(); iter != paramDesc.textures.end(); ++iter)
  232. {
  233. HTexture texture = bindableParams->getTexture(iter->second.slot);
  234. if(!texture.isLoaded())
  235. setTexture(gptype, iter->second.slot, false, nullptr);
  236. else
  237. setTexture(gptype, iter->second.slot, true, texture.getInternalPtr());
  238. }
  239. // Read all the buffer data so we can assign it. Not the most efficient way of accessing data
  240. // but it is required in order to have standardized buffer interface.
  241. UnorderedMap<UINT32, UINT8*> bufferData;
  242. for(auto& curParam : paramDesc.params)
  243. {
  244. UINT32 paramBlockSlot = curParam.second.paramBlockSlot;
  245. auto iterFind = bufferData.find(paramBlockSlot);
  246. if(iterFind == bufferData.end())
  247. {
  248. GpuParamBlockBufferPtr paramBlock = bindableParams->getParamBlockBuffer(paramBlockSlot);
  249. UINT8* data = (UINT8*)bs_alloc<ScratchAlloc>(paramBlock->getSize());
  250. paramBlock->readData(data);
  251. bufferData[paramBlockSlot] = data;
  252. }
  253. }
  254. HRESULT hr;
  255. switch(gptype)
  256. {
  257. case GPT_VERTEX_PROGRAM:
  258. {
  259. for(auto iter = paramDesc.params.begin(); iter != paramDesc.params.end(); ++iter)
  260. {
  261. const GpuParamDataDesc& paramDesc = iter->second;
  262. const UINT8* ptrData = bufferData[paramDesc.paramBlockSlot] + paramDesc.cpuMemOffset * sizeof(UINT32);
  263. switch(paramDesc.type)
  264. {
  265. case GPDT_FLOAT1:
  266. case GPDT_FLOAT2:
  267. case GPDT_FLOAT3:
  268. case GPDT_FLOAT4:
  269. case GPDT_MATRIX_2X2:
  270. case GPDT_MATRIX_2X3:
  271. case GPDT_MATRIX_2X4:
  272. case GPDT_MATRIX_3X2:
  273. case GPDT_MATRIX_3X3:
  274. case GPDT_MATRIX_3X4:
  275. case GPDT_MATRIX_4X2:
  276. case GPDT_MATRIX_4X3:
  277. case GPDT_MATRIX_4X4:
  278. {
  279. UINT32 slotCount = (paramDesc.elementSize / 4) * paramDesc.arraySize;
  280. assert (paramDesc.elementSize % 4 == 0 && "Should not have any elements less than 4 wide for D3D9");
  281. if (FAILED(hr = getActiveD3D9Device()->SetVertexShaderConstantF(paramDesc.gpuMemOffset, (const float*)ptrData, slotCount)))
  282. BS_EXCEPT(RenderingAPIException, "Unable to upload vertex shader float parameters.");
  283. break;
  284. }
  285. case GPDT_INT1:
  286. case GPDT_INT2:
  287. case GPDT_INT3:
  288. case GPDT_INT4:
  289. {
  290. UINT32 slotCount = (paramDesc.elementSize / 4) * paramDesc.arraySize;
  291. assert (paramDesc.elementSize % 4 == 0 && "Should not have any elements less than 4 wide for D3D9");
  292. if (FAILED(hr = getActiveD3D9Device()->SetVertexShaderConstantI(paramDesc.gpuMemOffset, (const INT32*)ptrData, slotCount)))
  293. BS_EXCEPT(RenderingAPIException, "Unable to upload vertex shader int parameters.");
  294. break;
  295. }
  296. case GPDT_BOOL:
  297. if (FAILED(hr = getActiveD3D9Device()->SetVertexShaderConstantB(paramDesc.gpuMemOffset, (const BOOL*)ptrData, paramDesc.arraySize)))
  298. BS_EXCEPT(RenderingAPIException, "Unable to upload vertex shader bool parameters.");
  299. break;
  300. }
  301. }
  302. }
  303. break;
  304. case GPT_FRAGMENT_PROGRAM:
  305. {
  306. for(auto iter = paramDesc.params.begin(); iter != paramDesc.params.end(); ++iter)
  307. {
  308. const GpuParamDataDesc& paramDesc = iter->second;
  309. const UINT8* ptrData = bufferData[paramDesc.paramBlockSlot] + paramDesc.cpuMemOffset * sizeof(UINT32);
  310. switch(paramDesc.type)
  311. {
  312. case GPDT_FLOAT1:
  313. case GPDT_FLOAT2:
  314. case GPDT_FLOAT3:
  315. case GPDT_FLOAT4:
  316. case GPDT_MATRIX_2X2:
  317. case GPDT_MATRIX_2X3:
  318. case GPDT_MATRIX_2X4:
  319. case GPDT_MATRIX_3X2:
  320. case GPDT_MATRIX_3X3:
  321. case GPDT_MATRIX_3X4:
  322. case GPDT_MATRIX_4X2:
  323. case GPDT_MATRIX_4X3:
  324. case GPDT_MATRIX_4X4:
  325. {
  326. UINT32 slotCount = (paramDesc.elementSize / 4) * paramDesc.arraySize;
  327. assert (paramDesc.elementSize % 4 == 0 && "Should not have any elements less than 4 wide for D3D9");
  328. if (FAILED(hr = getActiveD3D9Device()->SetPixelShaderConstantF(paramDesc.gpuMemOffset, (const float*)ptrData, slotCount)))
  329. BS_EXCEPT(RenderingAPIException, "Unable to upload pixel shader float parameters.");
  330. break;
  331. }
  332. case GPDT_INT1:
  333. case GPDT_INT2:
  334. case GPDT_INT3:
  335. case GPDT_INT4:
  336. {
  337. UINT32 slotCount = (paramDesc.elementSize / 4) * paramDesc.arraySize;
  338. assert (paramDesc.elementSize % 4 == 0 && "Should not have any elements less than 4 wide for D3D9");
  339. if (FAILED(hr = getActiveD3D9Device()->SetPixelShaderConstantI(paramDesc.gpuMemOffset, (const INT32*)ptrData, slotCount)))
  340. BS_EXCEPT(RenderingAPIException, "Unable to upload pixel shader int parameters.");
  341. break;
  342. }
  343. case GPDT_BOOL:
  344. if (FAILED(hr = getActiveD3D9Device()->SetPixelShaderConstantB(paramDesc.gpuMemOffset, (const BOOL*)ptrData, paramDesc.arraySize)))
  345. BS_EXCEPT(RenderingAPIException, "Unable to upload pixel shader bool parameters.");
  346. break;
  347. }
  348. }
  349. }
  350. break;
  351. };
  352. for(auto& curBufferData : bufferData)
  353. {
  354. bs_free<ScratchAlloc>(curBufferData.second);
  355. }
  356. BS_INC_RENDER_STAT(NumGpuParamBufferBinds);
  357. }
  358. void D3D9RenderSystem::setTexture(GpuProgramType gptype, UINT16 unit, bool enabled, const TexturePtr& tex)
  359. {
  360. THROW_IF_NOT_CORE_THREAD;
  361. if(!tex->isBindableAsShaderResource())
  362. BS_EXCEPT(InvalidParametersException, "Texture you have specified cannot be bound to a shader.");
  363. if(gptype != GPT_FRAGMENT_PROGRAM && gptype != GPT_VERTEX_PROGRAM)
  364. {
  365. LOGWRN("D3D9 cannot assign textures to this gpu program type: " + toString(gptype));
  366. return;
  367. }
  368. if(gptype == GPT_VERTEX_PROGRAM)
  369. {
  370. unit = D3DVERTEXTEXTURESAMPLER0 + unit; // Vertex stage uses special samplers
  371. }
  372. HRESULT hr;
  373. D3D9TexturePtr dt = std::static_pointer_cast<D3D9Texture>(tex);
  374. if (enabled && (dt != nullptr))
  375. {
  376. IDirect3DBaseTexture9 *pTex = dt->getTexture_internal();
  377. if (mTexStageDesc[unit].pTex != pTex)
  378. {
  379. hr = getActiveD3D9Device()->SetTexture(static_cast<DWORD>(unit), pTex);
  380. if( hr != S_OK )
  381. {
  382. String str = "Unable to set texture in D3D9";
  383. BS_EXCEPT(RenderingAPIException, str);
  384. }
  385. // set stage desc.
  386. mTexStageDesc[unit].pTex = pTex;
  387. mTexStageDesc[unit].texType = D3D9Mappings::get(dt->getTextureType());
  388. // Set gamma now too
  389. if (dt->isHardwareGammaReadToBeUsed())
  390. {
  391. setSamplerState(static_cast<DWORD>(unit), D3DSAMP_SRGBTEXTURE, TRUE);
  392. }
  393. else
  394. {
  395. setSamplerState(static_cast<DWORD>(unit), D3DSAMP_SRGBTEXTURE, FALSE);
  396. }
  397. BS_INC_RENDER_STAT(NumTextureBinds);
  398. BS_INC_RENDER_STAT(NumSamplerBinds);
  399. }
  400. }
  401. else
  402. {
  403. if (mTexStageDesc[unit].pTex != 0)
  404. {
  405. hr = getActiveD3D9Device()->SetTexture(static_cast<DWORD>(unit), 0);
  406. if( hr != S_OK )
  407. {
  408. String str = "Unable to disable texture '" + toString(unit) + "' in D3D9";
  409. BS_EXCEPT(RenderingAPIException, str);
  410. }
  411. BS_INC_RENDER_STAT(NumTextureBinds);
  412. }
  413. hr = setTextureStageState(static_cast<DWORD>(unit), D3DTSS_COLOROP, D3DTOP_DISABLE);
  414. if( hr != S_OK )
  415. {
  416. String str = "Unable to disable texture '" + toString(unit) + "' in D3D9";
  417. BS_EXCEPT(RenderingAPIException, str);
  418. }
  419. // set stage desc. to defaults
  420. mTexStageDesc[unit].pTex = 0;
  421. mTexStageDesc[unit].coordIndex = 0;
  422. mTexStageDesc[unit].texType = D3D9Mappings::D3D_TEX_TYPE_NORMAL;
  423. }
  424. }
  425. void D3D9RenderSystem::setSamplerState(GpuProgramType gptype, UINT16 unit, const SamplerStatePtr& state)
  426. {
  427. THROW_IF_NOT_CORE_THREAD;
  428. if(gptype != GPT_FRAGMENT_PROGRAM && gptype != GPT_VERTEX_PROGRAM)
  429. {
  430. LOGWRN("D3D9 doesn't support this gpu program type: " + toString(gptype));
  431. return;
  432. }
  433. if(gptype == GPT_VERTEX_PROGRAM)
  434. {
  435. unit = D3DVERTEXTEXTURESAMPLER0 + unit; // Vertex stage uses special samplers
  436. }
  437. // Set texture layer filtering
  438. setTextureFiltering(unit, FT_MIN, state->getTextureFiltering(FT_MIN));
  439. setTextureFiltering(unit, FT_MAG, state->getTextureFiltering(FT_MAG));
  440. setTextureFiltering(unit, FT_MIP, state->getTextureFiltering(FT_MIP));
  441. // Set texture layer filtering
  442. if (state->getTextureAnisotropy() > 0)
  443. setTextureAnisotropy(unit, state->getTextureAnisotropy());
  444. // Set mipmap biasing
  445. setTextureMipmapBias(unit, state->getTextureMipmapBias());
  446. // Texture addressing mode
  447. const UVWAddressingMode& uvw = state->getTextureAddressingMode();
  448. setTextureAddressingMode(unit, uvw);
  449. // Set border color
  450. setTextureBorderColor(unit, state->getBorderColor());
  451. BS_INC_RENDER_STAT(NumSamplerBinds);
  452. }
  453. void D3D9RenderSystem::setBlendState(const BlendStatePtr& blendState)
  454. {
  455. THROW_IF_NOT_CORE_THREAD;
  456. // Alpha to coverage
  457. setAlphaToCoverage(blendState->getAlphaToCoverageEnabled());
  458. // Blend states
  459. // DirectX 9 doesn't allow us to specify blend state per render target, so we just use the first one.
  460. if(blendState->getBlendEnabled(0))
  461. {
  462. setSceneBlending(blendState->getSrcBlend(0), blendState->getDstBlend(0), blendState->getAlphaSrcBlend(0), blendState->getAlphaDstBlend(0)
  463. , blendState->getBlendOperation(0), blendState->getAlphaBlendOperation(0));
  464. }
  465. else
  466. {
  467. setSceneBlending(BF_ONE, BF_ZERO, BO_ADD);
  468. }
  469. // Color write mask
  470. UINT8 writeMask = blendState->getRenderTargetWriteMask(0);
  471. setColorBufferWriteEnabled((writeMask & 0x1) != 0, (writeMask & 0x2) != 0, (writeMask & 0x4) != 0, (writeMask & 0x8) != 0);
  472. BS_INC_RENDER_STAT(NumBlendStateChanges);
  473. }
  474. void D3D9RenderSystem::setRasterizerState(const RasterizerStatePtr& rasterizerState)
  475. {
  476. THROW_IF_NOT_CORE_THREAD;
  477. setDepthBias((float)rasterizerState->getDepthBias(), rasterizerState->getSlopeScaledDepthBias());
  478. setCullingMode(rasterizerState->getCullMode());
  479. setPolygonMode(rasterizerState->getPolygonMode());
  480. setScissorTestEnable(rasterizerState->getScissorEnable());
  481. setMultisampleAntialiasEnable(rasterizerState->getMultisampleEnable());
  482. setAntialiasedLineEnable(rasterizerState->getAntialiasedLineEnable());
  483. BS_INC_RENDER_STAT(NumRasterizerStateChanges);
  484. }
  485. void D3D9RenderSystem::setDepthStencilState(const DepthStencilStatePtr& depthStencilState, UINT32 stencilRefValue)
  486. {
  487. THROW_IF_NOT_CORE_THREAD;
  488. // Set stencil buffer options
  489. setStencilCheckEnabled(depthStencilState->getStencilEnable());
  490. setStencilBufferOperations(depthStencilState->getStencilFrontFailOp(), depthStencilState->getStencilFrontZFailOp(), depthStencilState->getStencilFrontPassOp(), true);
  491. setStencilBufferFunc(depthStencilState->getStencilFrontCompFunc(), true);
  492. setStencilBufferOperations(depthStencilState->getStencilBackFailOp(), depthStencilState->getStencilBackZFailOp(), depthStencilState->getStencilBackPassOp(), false);
  493. setStencilBufferFunc(depthStencilState->getStencilBackCompFunc(), false);
  494. setStencilBufferReadMask(depthStencilState->getStencilReadMask());
  495. setStencilBufferWriteMask(depthStencilState->getStencilWriteMask());
  496. // Set depth buffer options
  497. setDepthBufferCheckEnabled(depthStencilState->getDepthReadEnable());
  498. setDepthBufferWriteEnabled(depthStencilState->getDepthWriteEnable());
  499. setDepthBufferFunction(depthStencilState->getDepthComparisonFunc());
  500. // Set stencil ref value
  501. setStencilRefValue(stencilRefValue);
  502. BS_INC_RENDER_STAT(NumDepthStencilStateChanges);
  503. }
  504. void D3D9RenderSystem::setTextureMipmapBias(UINT16 unit, float bias)
  505. {
  506. THROW_IF_NOT_CORE_THREAD;
  507. if (mCurrentCapabilities->hasCapability(RSC_MIPMAP_LOD_BIAS))
  508. {
  509. // ugh - have to pass float data through DWORD with no conversion
  510. HRESULT hr = setSamplerState(static_cast<DWORD>(unit), D3DSAMP_MIPMAPLODBIAS,
  511. *(DWORD*)&bias);
  512. if(FAILED(hr))
  513. BS_EXCEPT(RenderingAPIException, "Unable to set texture mipmap bias");
  514. }
  515. }
  516. void D3D9RenderSystem::setTextureAddressingMode( UINT16 stage,
  517. const UVWAddressingMode& uvw )
  518. {
  519. THROW_IF_NOT_CORE_THREAD;
  520. HRESULT hr;
  521. if( FAILED( hr = setSamplerState( static_cast<DWORD>(stage), D3DSAMP_ADDRESSU, D3D9Mappings::get(uvw.u, mDeviceManager->getActiveDevice()->getD3D9DeviceCaps()) ) ) )
  522. BS_EXCEPT(RenderingAPIException, "Failed to set texture addressing mode for U" );
  523. if( FAILED( hr = setSamplerState( static_cast<DWORD>(stage), D3DSAMP_ADDRESSV, D3D9Mappings::get(uvw.v, mDeviceManager->getActiveDevice()->getD3D9DeviceCaps()) ) ) )
  524. BS_EXCEPT(RenderingAPIException, "Failed to set texture addressing mode for V");
  525. if( FAILED( hr = setSamplerState( static_cast<DWORD>(stage), D3DSAMP_ADDRESSW, D3D9Mappings::get(uvw.w, mDeviceManager->getActiveDevice()->getD3D9DeviceCaps()) ) ) )
  526. BS_EXCEPT(RenderingAPIException, "Failed to set texture addressing mode for W");
  527. }
  528. void D3D9RenderSystem::setTextureBorderColor(UINT16 stage, const Color& colour)
  529. {
  530. THROW_IF_NOT_CORE_THREAD;
  531. HRESULT hr;
  532. if( FAILED( hr = setSamplerState( static_cast<DWORD>(stage), D3DSAMP_BORDERCOLOR, colour.getAsBGRA()) ) )
  533. BS_EXCEPT(RenderingAPIException, "Failed to set texture border colour");
  534. }
  535. void D3D9RenderSystem::setSceneBlending( BlendFactor sourceFactor, BlendFactor destFactor, BlendOperation op )
  536. {
  537. THROW_IF_NOT_CORE_THREAD;
  538. HRESULT hr;
  539. if( sourceFactor == BF_ONE && destFactor == BF_ZERO)
  540. {
  541. if (FAILED(hr = setRenderState(D3DRS_ALPHABLENDENABLE, FALSE)))
  542. BS_EXCEPT(RenderingAPIException, "Failed to set alpha blending option");
  543. }
  544. else
  545. {
  546. if (FAILED(hr = setRenderState(D3DRS_ALPHABLENDENABLE, TRUE)))
  547. BS_EXCEPT(RenderingAPIException, "Failed to set alpha blending option");
  548. if (FAILED(hr = setRenderState(D3DRS_SEPARATEALPHABLENDENABLE, FALSE)))
  549. BS_EXCEPT(RenderingAPIException, "Failed to set separate alpha blending option");
  550. if( FAILED( hr = setRenderState( D3DRS_SRCBLEND, D3D9Mappings::get(sourceFactor) ) ) )
  551. BS_EXCEPT(RenderingAPIException, "Failed to set source blend");
  552. if( FAILED( hr = setRenderState( D3DRS_DESTBLEND, D3D9Mappings::get(destFactor) ) ) )
  553. BS_EXCEPT(RenderingAPIException, "Failed to set destination blend");
  554. }
  555. if (FAILED(hr = setRenderState(D3DRS_BLENDOP, D3D9Mappings::get(op))))
  556. BS_EXCEPT(RenderingAPIException, "Failed to set scene blending operation option");
  557. if (FAILED(hr = setRenderState(D3DRS_BLENDOPALPHA, D3D9Mappings::get(op))))
  558. BS_EXCEPT(RenderingAPIException, "Failed to set scene blending operation option");
  559. }
  560. void D3D9RenderSystem::setSceneBlending( BlendFactor sourceFactor, BlendFactor destFactor, BlendFactor sourceFactorAlpha,
  561. BlendFactor destFactorAlpha, BlendOperation op, BlendOperation alphaOp )
  562. {
  563. THROW_IF_NOT_CORE_THREAD;
  564. HRESULT hr;
  565. if( sourceFactor == BF_ONE && destFactor == BF_ZERO &&
  566. sourceFactorAlpha == BF_ONE && destFactorAlpha == BF_ZERO)
  567. {
  568. if (FAILED(hr = setRenderState(D3DRS_ALPHABLENDENABLE, FALSE)))
  569. BS_EXCEPT(RenderingAPIException, "Failed to set alpha blending option");
  570. }
  571. else
  572. {
  573. if (FAILED(hr = setRenderState(D3DRS_ALPHABLENDENABLE, TRUE)))
  574. BS_EXCEPT(RenderingAPIException, "Failed to set alpha blending option");
  575. if (FAILED(hr = setRenderState(D3DRS_SEPARATEALPHABLENDENABLE, TRUE)))
  576. BS_EXCEPT(RenderingAPIException, "Failed to set separate alpha blending option");
  577. if( FAILED( hr = setRenderState( D3DRS_SRCBLEND, D3D9Mappings::get(sourceFactor) ) ) )
  578. BS_EXCEPT(RenderingAPIException, "Failed to set source blend");
  579. if( FAILED( hr = setRenderState( D3DRS_DESTBLEND, D3D9Mappings::get(destFactor) ) ) )
  580. BS_EXCEPT(RenderingAPIException, "Failed to set destination blend");
  581. if( FAILED( hr = setRenderState( D3DRS_SRCBLENDALPHA, D3D9Mappings::get(sourceFactorAlpha) ) ) )
  582. BS_EXCEPT(RenderingAPIException, "Failed to set alpha source blend");
  583. if( FAILED( hr = setRenderState( D3DRS_DESTBLENDALPHA, D3D9Mappings::get(destFactorAlpha) ) ) )
  584. BS_EXCEPT(RenderingAPIException, "Failed to set alpha destination blend");
  585. }
  586. if (FAILED(hr = setRenderState(D3DRS_BLENDOP, D3D9Mappings::get(op))))
  587. BS_EXCEPT(RenderingAPIException, "Failed to set scene blending operation option");
  588. if (FAILED(hr = setRenderState(D3DRS_BLENDOPALPHA, D3D9Mappings::get(alphaOp))))
  589. BS_EXCEPT(RenderingAPIException, "Failed to set alpha scene blending operation option");
  590. }
  591. void D3D9RenderSystem::setAlphaTest(CompareFunction func, unsigned char value)
  592. {
  593. THROW_IF_NOT_CORE_THREAD;
  594. HRESULT hr;
  595. if (func != CMPF_ALWAYS_PASS)
  596. {
  597. if( FAILED( hr = setRenderState( D3DRS_ALPHATESTENABLE, TRUE ) ) )
  598. BS_EXCEPT(RenderingAPIException, "Failed to enable alpha testing");
  599. }
  600. else
  601. {
  602. if( FAILED( hr = setRenderState( D3DRS_ALPHATESTENABLE, FALSE ) ) )
  603. BS_EXCEPT(RenderingAPIException, "Failed to disable alpha testing");
  604. }
  605. // Set always just be sure
  606. if( FAILED( hr = setRenderState( D3DRS_ALPHAFUNC, D3D9Mappings::get(func) ) ) )
  607. BS_EXCEPT(RenderingAPIException, "Failed to set alpha reject function");
  608. if( FAILED( hr = setRenderState( D3DRS_ALPHAREF, value ) ) )
  609. BS_EXCEPT(RenderingAPIException, "Failed to set render state D3DRS_ALPHAREF");
  610. }
  611. void D3D9RenderSystem::setAlphaToCoverage(bool enable)
  612. {
  613. THROW_IF_NOT_CORE_THREAD;
  614. HRESULT hr;
  615. static bool lasta2c = false;
  616. // Alpha to coverage
  617. if (getCapabilities()->hasCapability(RSC_ALPHA_TO_COVERAGE))
  618. {
  619. // Vendor-specific hacks on renderstate, gotta love 'em
  620. if (getCapabilities()->getVendor() == GPU_NVIDIA)
  621. {
  622. if (enable)
  623. {
  624. if( FAILED( hr = setRenderState( D3DRS_ADAPTIVETESS_Y, (D3DFORMAT)MAKEFOURCC('A', 'T', 'O', 'C') ) ) )
  625. BS_EXCEPT(RenderingAPIException, "Failed to set alpha to coverage option");
  626. }
  627. else
  628. {
  629. if( FAILED( hr = setRenderState( D3DRS_ADAPTIVETESS_Y, D3DFMT_UNKNOWN ) ) )
  630. BS_EXCEPT(RenderingAPIException, "Failed to set alpha to coverage option");
  631. }
  632. }
  633. else if ((getCapabilities()->getVendor() == GPU_AMD))
  634. {
  635. if (enable)
  636. {
  637. if( FAILED( hr = setRenderState( D3DRS_POINTSIZE, MAKEFOURCC('A','2','M','1') ) ) )
  638. BS_EXCEPT(RenderingAPIException, "Failed to set alpha to coverage option");
  639. }
  640. else
  641. {
  642. // discovered this through trial and error, seems to work
  643. if( FAILED( hr = setRenderState( D3DRS_POINTSIZE, MAKEFOURCC('A','2','M','0') ) ) )
  644. BS_EXCEPT(RenderingAPIException, "Failed to set alpha to coverage option");
  645. }
  646. }
  647. lasta2c = enable;
  648. }
  649. }
  650. void D3D9RenderSystem::setCullingMode(CullingMode mode)
  651. {
  652. THROW_IF_NOT_CORE_THREAD;
  653. mCullingMode = mode;
  654. HRESULT hr;
  655. if( FAILED (hr = setRenderState(D3DRS_CULLMODE,
  656. D3D9Mappings::get(mode, false))) )
  657. BS_EXCEPT(RenderingAPIException, "Failed to set culling mode");
  658. }
  659. void D3D9RenderSystem::setDepthBufferCheckEnabled(bool enabled)
  660. {
  661. THROW_IF_NOT_CORE_THREAD;
  662. HRESULT hr;
  663. if( enabled )
  664. hr = setRenderState(D3DRS_ZENABLE, D3DZB_TRUE);
  665. else
  666. hr = setRenderState(D3DRS_ZENABLE, D3DZB_FALSE);
  667. if(FAILED(hr))
  668. BS_EXCEPT(RenderingAPIException, "Error setting depth buffer test state");
  669. }
  670. void D3D9RenderSystem::setDepthBufferWriteEnabled(bool enabled)
  671. {
  672. THROW_IF_NOT_CORE_THREAD;
  673. HRESULT hr;
  674. if( FAILED( hr = setRenderState( D3DRS_ZWRITEENABLE, enabled ) ) )
  675. BS_EXCEPT(RenderingAPIException, "Error setting depth buffer write state");
  676. }
  677. void D3D9RenderSystem::setDepthBufferFunction(CompareFunction func)
  678. {
  679. THROW_IF_NOT_CORE_THREAD;
  680. HRESULT hr;
  681. if( FAILED( hr = setRenderState( D3DRS_ZFUNC, D3D9Mappings::get(func) ) ) )
  682. BS_EXCEPT(RenderingAPIException, "Error setting depth buffer test function");
  683. }
  684. void D3D9RenderSystem::setDepthBias(float constantBias, float slopeScaleBias)
  685. {
  686. THROW_IF_NOT_CORE_THREAD;
  687. if ((mDeviceManager->getActiveDevice()->getD3D9DeviceCaps().RasterCaps & D3DPRASTERCAPS_DEPTHBIAS) != 0)
  688. {
  689. // Negate bias since D3D is backward
  690. // D3D also expresses the constant bias as an absolute value, rather than
  691. // relative to minimum depth unit, so scale to fit
  692. constantBias = -constantBias / 250000.0f;
  693. HRESULT hr = setRenderState(D3DRS_DEPTHBIAS, *((DWORD*)&constantBias));
  694. if (FAILED(hr))
  695. BS_EXCEPT(RenderingAPIException, "Error setting constant depth bias");
  696. }
  697. if ((mDeviceManager->getActiveDevice()->getD3D9DeviceCaps().RasterCaps & D3DPRASTERCAPS_SLOPESCALEDEPTHBIAS) != 0)
  698. {
  699. // Negate bias since D3D is backward
  700. slopeScaleBias = -slopeScaleBias;
  701. HRESULT hr = setRenderState(D3DRS_SLOPESCALEDEPTHBIAS, *((DWORD*)&slopeScaleBias));
  702. if (FAILED(hr))
  703. BS_EXCEPT(RenderingAPIException, "Error setting slope scale depth bias");
  704. }
  705. }
  706. void D3D9RenderSystem::setColorBufferWriteEnabled(bool red, bool green, bool blue, bool alpha)
  707. {
  708. THROW_IF_NOT_CORE_THREAD;
  709. DWORD val = 0;
  710. if (red)
  711. val |= D3DCOLORWRITEENABLE_RED;
  712. if (green)
  713. val |= D3DCOLORWRITEENABLE_GREEN;
  714. if (blue)
  715. val |= D3DCOLORWRITEENABLE_BLUE;
  716. if (alpha)
  717. val |= D3DCOLORWRITEENABLE_ALPHA;
  718. HRESULT hr = setRenderState(D3DRS_COLORWRITEENABLE, val);
  719. if (FAILED(hr))
  720. BS_EXCEPT(RenderingAPIException, "Error setting colour write enable flags");
  721. }
  722. void D3D9RenderSystem::setPolygonMode(PolygonMode level)
  723. {
  724. THROW_IF_NOT_CORE_THREAD;
  725. HRESULT hr = setRenderState(D3DRS_FILLMODE, D3D9Mappings::get(level));
  726. if (FAILED(hr))
  727. BS_EXCEPT(RenderingAPIException, "Error setting polygon mode.");
  728. }
  729. void D3D9RenderSystem::setStencilCheckEnabled(bool enabled)
  730. {
  731. THROW_IF_NOT_CORE_THREAD;
  732. // Allow stencilling
  733. HRESULT hr = setRenderState(D3DRS_STENCILENABLE, enabled);
  734. if (FAILED(hr))
  735. BS_EXCEPT(RenderingAPIException, "Error enabling / disabling stencilling.");
  736. if (mCurrentCapabilities->hasCapability(RSC_TWO_SIDED_STENCIL))
  737. {
  738. hr = setRenderState(D3DRS_TWOSIDEDSTENCILMODE, TRUE);
  739. if (FAILED(hr))
  740. BS_EXCEPT(RenderingAPIException, "Error setting 2-sided stencil mode.");
  741. }
  742. else
  743. {
  744. hr = setRenderState(D3DRS_TWOSIDEDSTENCILMODE, FALSE);
  745. if (FAILED(hr))
  746. BS_EXCEPT(RenderingAPIException, "Error setting 1-sided stencil mode.");
  747. }
  748. }
  749. void D3D9RenderSystem::setStencilBufferOperations(StencilOperation stencilFailOp, StencilOperation depthFailOp, StencilOperation passOp, bool ccw)
  750. {
  751. THROW_IF_NOT_CORE_THREAD;
  752. HRESULT hr;
  753. // 2-sided operation
  754. if (ccw)
  755. {
  756. // fail op
  757. hr = setRenderState(D3DRS_CCW_STENCILFAIL, D3D9Mappings::get(stencilFailOp));
  758. if (FAILED(hr))
  759. BS_EXCEPT(RenderingAPIException, "Error setting stencil fail operation (ccw).");
  760. // depth fail op
  761. hr = setRenderState(D3DRS_CCW_STENCILZFAIL, D3D9Mappings::get(depthFailOp));
  762. if (FAILED(hr))
  763. BS_EXCEPT(RenderingAPIException, "Error setting stencil depth fail operation (ccw).");
  764. // pass op
  765. hr = setRenderState(D3DRS_CCW_STENCILPASS, D3D9Mappings::get(passOp));
  766. if (FAILED(hr))
  767. BS_EXCEPT(RenderingAPIException, "Error setting stencil pass operation (ccw).");
  768. }
  769. else
  770. {
  771. // fail op
  772. hr = setRenderState(D3DRS_STENCILFAIL, D3D9Mappings::get(stencilFailOp, true));
  773. if (FAILED(hr))
  774. BS_EXCEPT(RenderingAPIException, "Error setting stencil fail operation (cw).");
  775. // depth fail op
  776. hr = setRenderState(D3DRS_STENCILZFAIL, D3D9Mappings::get(depthFailOp, true));
  777. if (FAILED(hr))
  778. BS_EXCEPT(RenderingAPIException, "Error setting stencil depth fail operation (cw).");
  779. // pass op
  780. hr = setRenderState(D3DRS_STENCILPASS, D3D9Mappings::get(passOp, true));
  781. if (FAILED(hr))
  782. BS_EXCEPT(RenderingAPIException, "Error setting stencil pass operation (cw).");
  783. }
  784. }
  785. void D3D9RenderSystem::setStencilBufferFunc(CompareFunction func, bool ccw)
  786. {
  787. HRESULT hr;
  788. if(ccw)
  789. hr = setRenderState(D3DRS_CCW_STENCILFUNC, D3D9Mappings::get(func));
  790. else
  791. hr = setRenderState(D3DRS_STENCILFUNC, D3D9Mappings::get(func));
  792. if (FAILED(hr))
  793. BS_EXCEPT(RenderingAPIException, "Error setting stencil buffer test function.");
  794. }
  795. void D3D9RenderSystem::setStencilBufferReadMask(UINT32 mask)
  796. {
  797. HRESULT hr = setRenderState(D3DRS_STENCILMASK, mask);
  798. if (FAILED(hr))
  799. BS_EXCEPT(RenderingAPIException, "Error setting stencil buffer mask.");
  800. }
  801. void D3D9RenderSystem::setStencilBufferWriteMask(UINT32 mask)
  802. {
  803. HRESULT hr = setRenderState(D3DRS_STENCILWRITEMASK, mask);
  804. if (FAILED(hr))
  805. BS_EXCEPT(RenderingAPIException, "Error setting stencil buffer write mask.");
  806. }
  807. void D3D9RenderSystem::setStencilRefValue(UINT32 refValue)
  808. {
  809. THROW_IF_NOT_CORE_THREAD;
  810. HRESULT hr = setRenderState(D3DRS_STENCILREF, refValue);
  811. if (FAILED(hr))
  812. BS_EXCEPT(RenderingAPIException, "Error setting stencil buffer reference value.");
  813. }
  814. void D3D9RenderSystem::setTextureFiltering(UINT16 unit, FilterType ftype, FilterOptions filter)
  815. {
  816. THROW_IF_NOT_CORE_THREAD;
  817. HRESULT hr;
  818. D3D9Mappings::D3DTexType texType = mTexStageDesc[unit].texType;
  819. hr = setSamplerState( static_cast<DWORD>(unit), D3D9Mappings::get(ftype),
  820. D3D9Mappings::get(ftype, filter, mDeviceManager->getActiveDevice()->getD3D9DeviceCaps(), texType));
  821. if (FAILED(hr))
  822. BS_EXCEPT(RenderingAPIException, "Failed to set texture filter ");
  823. }
  824. void D3D9RenderSystem::setTextureAnisotropy(UINT16 unit, unsigned int maxAnisotropy)
  825. {
  826. THROW_IF_NOT_CORE_THREAD;
  827. if (static_cast<DWORD>(maxAnisotropy) > mDeviceManager->getActiveDevice()->getD3D9DeviceCaps().MaxAnisotropy)
  828. maxAnisotropy = mDeviceManager->getActiveDevice()->getD3D9DeviceCaps().MaxAnisotropy;
  829. if (getCurrentAnisotropy(unit) != maxAnisotropy)
  830. setSamplerState( static_cast<DWORD>(unit), D3DSAMP_MAXANISOTROPY, maxAnisotropy );
  831. }
  832. void D3D9RenderSystem::setRenderTarget(RenderTargetPtr target)
  833. {
  834. THROW_IF_NOT_CORE_THREAD;
  835. mActiveRenderTarget = target;
  836. HRESULT hr;
  837. // Possibly change device if the target is a window
  838. if (target->getCore()->getProperties().isWindow())
  839. {
  840. D3D9RenderWindow* window = static_cast<D3D9RenderWindow*>(target.get());
  841. mDeviceManager->setActiveRenderTargetDevice(window->getCore()->_getDevice());
  842. window->getCore()->_validateDevice();
  843. }
  844. // Retrieve render surfaces
  845. UINT32 maxRenderTargets = mCurrentCapabilities->getNumMultiRenderTargets();
  846. IDirect3DSurface9** pBack = bs_newN<IDirect3DSurface9*, ScratchAlloc>(maxRenderTargets);
  847. memset(pBack, 0, sizeof(IDirect3DSurface9*) * maxRenderTargets);
  848. target->getCore()->getCustomAttribute("DDBACKBUFFER", pBack);
  849. if (!pBack[0])
  850. {
  851. bs_deleteN<ScratchAlloc>(pBack, maxRenderTargets);
  852. return;
  853. }
  854. IDirect3DSurface9* pDepth = NULL;
  855. if (!pDepth)
  856. target->getCore()->getCustomAttribute("D3DZBUFFER", &pDepth);
  857. // Bind render targets
  858. for(UINT32 x = 0; x < maxRenderTargets; ++x)
  859. {
  860. hr = getActiveD3D9Device()->SetRenderTarget(x, pBack[x]);
  861. if (FAILED(hr))
  862. {
  863. String msg = DXGetErrorDescription(hr);
  864. BS_EXCEPT(RenderingAPIException, "Failed to setRenderTarget : " + msg);
  865. }
  866. }
  867. bs_deleteN<ScratchAlloc>(pBack, maxRenderTargets);
  868. hr = getActiveD3D9Device()->SetDepthStencilSurface(pDepth);
  869. if (FAILED(hr))
  870. {
  871. String msg = DXGetErrorDescription(hr);
  872. BS_EXCEPT(RenderingAPIException, "Failed to setDepthStencil : " + msg);
  873. }
  874. BS_INC_RENDER_STAT(NumRenderTargetChanges);
  875. }
  876. void D3D9RenderSystem::setViewport(Viewport vp)
  877. {
  878. THROW_IF_NOT_CORE_THREAD;
  879. // ok, it's different, time to set render target and viewport params
  880. D3DVIEWPORT9 d3dvp;
  881. HRESULT hr;
  882. // Set render target
  883. RenderTargetPtr target = vp.getTarget();
  884. setRenderTarget(target);
  885. const RenderTargetProperties& rtProps = target->getCore()->getProperties();
  886. setCullingMode( mCullingMode );
  887. // Set viewport dimensions
  888. mViewportLeft = (UINT32)(rtProps.getWidth() * vp.getNormalizedX());
  889. mViewportTop = (UINT32)(rtProps.getHeight() * vp.getNormalizedY());
  890. mViewportWidth = (UINT32)(rtProps.getWidth() * vp.getNormalizedWidth());
  891. mViewportHeight = (UINT32)(rtProps.getHeight() * vp.getNormalizedHeight());
  892. d3dvp.X = mViewportLeft;
  893. d3dvp.Y = mViewportTop;
  894. d3dvp.Width = mViewportWidth;
  895. d3dvp.Height = mViewportHeight;
  896. if (target->requiresTextureFlipping())
  897. {
  898. // Convert "top-left" to "bottom-left"
  899. d3dvp.Y = rtProps.getHeight() - d3dvp.Height - d3dvp.Y;
  900. }
  901. // Z-values from 0.0 to 1.0 (TODO: standardise with OpenGL)
  902. d3dvp.MinZ = 0.0f;
  903. d3dvp.MaxZ = 1.0f;
  904. if( FAILED( hr = getActiveD3D9Device()->SetViewport( &d3dvp ) ) )
  905. BS_EXCEPT(RenderingAPIException, "Failed to set viewport.");
  906. // Set sRGB write mode
  907. setRenderState(D3DRS_SRGBWRITEENABLE, rtProps.isHwGammaEnabled());
  908. }
  909. void D3D9RenderSystem::beginFrame()
  910. {
  911. THROW_IF_NOT_CORE_THREAD;
  912. HRESULT hr;
  913. if(FAILED(hr = getActiveD3D9Device()->BeginScene()))
  914. {
  915. String msg = DXGetErrorDescription(hr);
  916. BS_EXCEPT(RenderingAPIException, "Error beginning frame :" + msg);
  917. }
  918. mDeviceManager->getActiveDevice()->clearDeviceStreams();
  919. mIsFrameInProgress = true;
  920. }
  921. void D3D9RenderSystem::endFrame()
  922. {
  923. THROW_IF_NOT_CORE_THREAD;
  924. HRESULT hr;
  925. if(FAILED(hr = getActiveD3D9Device()->EndScene()))
  926. BS_EXCEPT(RenderingAPIException, "Error ending frame");
  927. mIsFrameInProgress = false;
  928. }
  929. void D3D9RenderSystem::setVertexDeclaration(VertexDeclarationPtr decl)
  930. {
  931. THROW_IF_NOT_CORE_THREAD;
  932. std::shared_ptr<D3D9VertexDeclaration> d3ddecl = std::static_pointer_cast<D3D9VertexDeclaration>(decl);
  933. HRESULT hr;
  934. if (FAILED(hr = getActiveD3D9Device()->SetVertexDeclaration(d3ddecl->getD3DVertexDeclaration())))
  935. {
  936. BS_EXCEPT(RenderingAPIException, "Unable to set D3D9 vertex declaration");
  937. }
  938. }
  939. void D3D9RenderSystem::setVertexBuffers(UINT32 index, VertexBufferPtr* buffers, UINT32 numBuffers)
  940. {
  941. THROW_IF_NOT_CORE_THREAD;
  942. UINT32 maxBoundVertexBuffers = mCurrentCapabilities->getMaxBoundVertexBuffers();
  943. if(index < 0 || (index + numBuffers) > maxBoundVertexBuffers)
  944. BS_EXCEPT(InvalidParametersException, "Invalid vertex index: " + toString(index) + ". Valid range is 0 .. " + toString(maxBoundVertexBuffers - 1));
  945. HRESULT hr;
  946. for(UINT32 i = 0; i < numBuffers; i++)
  947. {
  948. if(buffers[i] != nullptr)
  949. {
  950. D3D9VertexBuffer* d3d9buf = static_cast<D3D9VertexBuffer*>(buffers[i].get());
  951. hr = getActiveD3D9Device()->SetStreamSource(
  952. static_cast<UINT>(index + i),
  953. d3d9buf->getD3D9VertexBuffer(),
  954. 0,
  955. static_cast<UINT>(d3d9buf->getVertexSize()) // stride
  956. );
  957. }
  958. else
  959. {
  960. hr = getActiveD3D9Device()->SetStreamSource(static_cast<UINT>(index + i), nullptr, 0, 0);
  961. }
  962. if (FAILED(hr))
  963. BS_EXCEPT(RenderingAPIException, "Unable to set D3D9 stream source for buffer binding");
  964. BS_INC_RENDER_STAT(NumVertexBufferBinds);
  965. }
  966. }
  967. void D3D9RenderSystem::setIndexBuffer(const IndexBufferPtr& buffer)
  968. {
  969. THROW_IF_NOT_CORE_THREAD;
  970. D3D9IndexBuffer* d3dIdxBuf = static_cast<D3D9IndexBuffer*>(buffer.get());
  971. HRESULT hr = getActiveD3D9Device()->SetIndices( d3dIdxBuf->getD3DIndexBuffer() );
  972. if (FAILED(hr))
  973. BS_EXCEPT(RenderingAPIException, "Failed to set index buffer");
  974. BS_INC_RENDER_STAT(NumIndexBufferBinds);
  975. }
  976. void D3D9RenderSystem::setDrawOperation(DrawOperationType op)
  977. {
  978. THROW_IF_NOT_CORE_THREAD;
  979. mCurrentDrawOperation = op;
  980. }
  981. void D3D9RenderSystem::draw(UINT32 vertexOffset, UINT32 vertexCount)
  982. {
  983. UINT32 primCount = vertexCountToPrimCount(mCurrentDrawOperation, vertexCount);
  984. HRESULT hr = getActiveD3D9Device()->DrawPrimitive(getD3D9PrimitiveType(), static_cast<UINT>(vertexOffset), static_cast<UINT>(primCount));
  985. if(FAILED(hr))
  986. {
  987. String msg = DXGetErrorDescription(hr);
  988. BS_EXCEPT(RenderingAPIException, "Failed to DrawPrimitive : " + msg);
  989. }
  990. BS_INC_RENDER_STAT(NumDrawCalls);
  991. BS_ADD_RENDER_STAT(NumVertices, vertexCount);
  992. BS_ADD_RENDER_STAT(NumPrimitives, primCount);
  993. }
  994. void D3D9RenderSystem::drawIndexed(UINT32 startIndex, UINT32 indexCount, UINT32 vertexOffset, UINT32 vertexCount)
  995. {
  996. UINT32 primCount = vertexCountToPrimCount(mCurrentDrawOperation, indexCount);
  997. // do indexed draw operation
  998. HRESULT hr = getActiveD3D9Device()->DrawIndexedPrimitive(
  999. getD3D9PrimitiveType(),
  1000. static_cast<UINT>(vertexOffset),
  1001. 0,
  1002. static_cast<UINT>(vertexCount),
  1003. static_cast<UINT>(startIndex),
  1004. static_cast<UINT>(primCount)
  1005. );
  1006. if(FAILED(hr))
  1007. {
  1008. String msg = DXGetErrorDescription(hr);
  1009. BS_EXCEPT(RenderingAPIException, "Failed to DrawIndexedPrimitive : " + msg);
  1010. }
  1011. BS_INC_RENDER_STAT(NumDrawCalls);
  1012. BS_ADD_RENDER_STAT(NumVertices, vertexCount);
  1013. BS_ADD_RENDER_STAT(NumPrimitives, primCount);
  1014. }
  1015. void D3D9RenderSystem::setScissorRect(UINT32 left, UINT32 top, UINT32 right, UINT32 bottom)
  1016. {
  1017. THROW_IF_NOT_CORE_THREAD;
  1018. mScissorRect.left = static_cast<LONG>(left);
  1019. mScissorRect.top = static_cast<LONG>(top);
  1020. mScissorRect.bottom = static_cast<LONG>(bottom);
  1021. mScissorRect.right = static_cast<LONG>(right);
  1022. }
  1023. void D3D9RenderSystem::setScissorTestEnable(bool enable)
  1024. {
  1025. THROW_IF_NOT_CORE_THREAD;
  1026. HRESULT hr;
  1027. if (enable)
  1028. {
  1029. if (FAILED(hr = setRenderState(D3DRS_SCISSORTESTENABLE, TRUE)))
  1030. {
  1031. BS_EXCEPT(RenderingAPIException, "Unable to enable scissor rendering state; " + getErrorDescription(hr));
  1032. }
  1033. if (FAILED(hr = getActiveD3D9Device()->SetScissorRect(&mScissorRect)))
  1034. {
  1035. BS_EXCEPT(RenderingAPIException, "Unable to set scissor rectangle; " + getErrorDescription(hr));
  1036. }
  1037. }
  1038. else
  1039. {
  1040. if (FAILED(hr = setRenderState(D3DRS_SCISSORTESTENABLE, FALSE)))
  1041. {
  1042. BS_EXCEPT(RenderingAPIException, "Unable to disable scissor rendering state; " + getErrorDescription(hr));
  1043. }
  1044. }
  1045. }
  1046. void D3D9RenderSystem::setMultisampleAntialiasEnable(bool enable)
  1047. {
  1048. HRESULT hr;
  1049. if(enable)
  1050. {
  1051. if (FAILED(hr = setRenderState(D3DRS_MULTISAMPLEANTIALIAS, TRUE)))
  1052. {
  1053. BS_EXCEPT(RenderingAPIException, "Unable to enable multisample antialiasing. Error description: " + getErrorDescription(hr));
  1054. }
  1055. }
  1056. else
  1057. {
  1058. if (FAILED(hr = setRenderState(D3DRS_MULTISAMPLEANTIALIAS, FALSE)))
  1059. {
  1060. BS_EXCEPT(RenderingAPIException, "Unable to disable multisample antialiasing. Error description: " + getErrorDescription(hr));
  1061. }
  1062. }
  1063. }
  1064. void D3D9RenderSystem::setAntialiasedLineEnable(bool enable)
  1065. {
  1066. HRESULT hr;
  1067. if(enable)
  1068. {
  1069. if (FAILED(hr = setRenderState(D3DRS_ANTIALIASEDLINEENABLE, TRUE)))
  1070. {
  1071. BS_EXCEPT(RenderingAPIException, "Unable to enable line antialiasing. Error description: " + getErrorDescription(hr));
  1072. }
  1073. }
  1074. else
  1075. {
  1076. if (FAILED(hr = setRenderState(D3DRS_ANTIALIASEDLINEENABLE, FALSE)))
  1077. {
  1078. BS_EXCEPT(RenderingAPIException, "Unable to disable line antialiasing. Error description: " + getErrorDescription(hr));
  1079. }
  1080. }
  1081. }
  1082. void D3D9RenderSystem::clearRenderTarget(UINT32 buffers, const Color& color, float depth, UINT16 stencil)
  1083. {
  1084. if(mActiveRenderTarget == nullptr)
  1085. return;
  1086. const RenderTargetProperties& rtProps = mActiveRenderTarget->getCore()->getProperties();
  1087. Rect2I clearRect(0, 0, rtProps.getWidth(), rtProps.getHeight());
  1088. clearArea(buffers, color, depth, stencil, clearRect);
  1089. }
  1090. void D3D9RenderSystem::clearViewport(UINT32 buffers, const Color& color, float depth, UINT16 stencil)
  1091. {
  1092. Rect2I clearRect(mViewportLeft, mViewportTop, mViewportWidth, mViewportHeight);
  1093. clearArea(buffers, color, depth, stencil, clearRect);
  1094. }
  1095. void D3D9RenderSystem::clearArea(UINT32 buffers, const Color& color, float depth, UINT16 stencil, const Rect2I& clearRect)
  1096. {
  1097. THROW_IF_NOT_CORE_THREAD;
  1098. if(mActiveRenderTarget == nullptr)
  1099. return;
  1100. DWORD flags = 0;
  1101. if (buffers & FBT_COLOR)
  1102. {
  1103. flags |= D3DCLEAR_TARGET;
  1104. }
  1105. if (buffers & FBT_DEPTH)
  1106. {
  1107. flags |= D3DCLEAR_ZBUFFER;
  1108. }
  1109. // Only try to clear the stencil buffer if supported
  1110. if (buffers & FBT_STENCIL)
  1111. {
  1112. flags |= D3DCLEAR_STENCIL;
  1113. }
  1114. const RenderTargetProperties& rtProps = mActiveRenderTarget->getCore()->getProperties();
  1115. bool clearEntireTarget = clearRect.width == 0 || clearRect.height == 0;
  1116. clearEntireTarget |= (clearRect.x == 0 && clearRect.y == 0 && clearRect.width == rtProps.getWidth() && clearRect.height == rtProps.getHeight());
  1117. if(!clearEntireTarget)
  1118. {
  1119. D3DRECT clearD3DRect;
  1120. clearD3DRect.x1 = (LONG)Math::clamp(clearRect.x, 0, (INT32)rtProps.getWidth() - 1);
  1121. clearD3DRect.x2 = (LONG)Math::clamp((INT32)clearD3DRect.x1 + clearRect.width, 0, (INT32)rtProps.getWidth() - 1);
  1122. clearD3DRect.y1 = (LONG)Math::clamp(clearRect.y, 0, (INT32)rtProps.getHeight() - 1);
  1123. clearD3DRect.y2 = (LONG)Math::clamp((INT32)clearD3DRect.y1 + clearRect.height, 0, (INT32)rtProps.getHeight() - 1);
  1124. HRESULT hr;
  1125. if(FAILED(hr = getActiveD3D9Device()->Clear(1, &clearD3DRect, flags, color.getAsBGRA(), depth, stencil)))
  1126. {
  1127. String msg = DXGetErrorDescription(hr);
  1128. BS_EXCEPT(RenderingAPIException, "Error clearing frame buffer : " + msg);
  1129. }
  1130. }
  1131. else
  1132. {
  1133. HRESULT hr;
  1134. if(FAILED(hr = getActiveD3D9Device()->Clear(0, nullptr, flags, color.getAsBGRA(), depth, stencil)))
  1135. {
  1136. String msg = DXGetErrorDescription(hr);
  1137. BS_EXCEPT(RenderingAPIException, "Error clearing frame buffer : " + msg);
  1138. }
  1139. }
  1140. BS_INC_RENDER_STAT(NumClears);
  1141. }
  1142. IDirect3D9* D3D9RenderSystem::getDirect3D9()
  1143. {
  1144. THROW_IF_NOT_CORE_THREAD;
  1145. return msD3D9RenderSystem->mpD3D;
  1146. }
  1147. UINT D3D9RenderSystem::getResourceCreationDeviceCount()
  1148. {
  1149. THROW_IF_NOT_CORE_THREAD;
  1150. D3D9ResourceCreationPolicy creationPolicy = msD3D9RenderSystem->mResourceManager->getCreationPolicy();
  1151. if (creationPolicy == RCP_CREATE_ON_ACTIVE_DEVICE)
  1152. {
  1153. return 1;
  1154. }
  1155. else if (creationPolicy == RCP_CREATE_ON_ALL_DEVICES)
  1156. {
  1157. return msD3D9RenderSystem->mDeviceManager->getDeviceCount();
  1158. }
  1159. BS_EXCEPT(InvalidParametersException, "Invalid resource creation policy.");
  1160. return 0;
  1161. }
  1162. IDirect3DDevice9* D3D9RenderSystem::getResourceCreationDevice(UINT index)
  1163. {
  1164. THROW_IF_NOT_CORE_THREAD;
  1165. D3D9ResourceCreationPolicy creationPolicy = msD3D9RenderSystem->mResourceManager->getCreationPolicy();
  1166. IDirect3DDevice9* d3d9Device = NULL;
  1167. if (creationPolicy == RCP_CREATE_ON_ACTIVE_DEVICE)
  1168. {
  1169. d3d9Device = msD3D9RenderSystem->getActiveD3D9Device();
  1170. }
  1171. else if (creationPolicy == RCP_CREATE_ON_ALL_DEVICES)
  1172. {
  1173. d3d9Device = msD3D9RenderSystem->mDeviceManager->getDevice(index)->getD3D9Device();
  1174. }
  1175. else
  1176. {
  1177. BS_EXCEPT(InvalidParametersException, "Invalid resource creation policy.");
  1178. }
  1179. return d3d9Device;
  1180. }
  1181. IDirect3DDevice9* D3D9RenderSystem::getActiveD3D9Device()
  1182. {
  1183. THROW_IF_NOT_CORE_THREAD;
  1184. D3D9Device* activeDevice = msD3D9RenderSystem->mDeviceManager->getActiveDevice();
  1185. IDirect3DDevice9* d3d9Device;
  1186. d3d9Device = activeDevice->getD3D9Device();
  1187. if (d3d9Device == nullptr)
  1188. BS_EXCEPT(InvalidParametersException, "Current d3d9 device is null.");
  1189. return d3d9Device;
  1190. }
  1191. D3D9ResourceManager* D3D9RenderSystem::getResourceManager()
  1192. {
  1193. // No need to check if we're on core thread as this is synced up internally
  1194. return msD3D9RenderSystem->mResourceManager;
  1195. }
  1196. D3D9DeviceManager* D3D9RenderSystem::getDeviceManager()
  1197. {
  1198. THROW_IF_NOT_CORE_THREAD;
  1199. return msD3D9RenderSystem->mDeviceManager;
  1200. }
  1201. /************************************************************************/
  1202. /* UTILITY METHODS */
  1203. /************************************************************************/
  1204. float D3D9RenderSystem::getHorizontalTexelOffset()
  1205. {
  1206. // D3D considers the origin to be in the center of a pixel
  1207. return -0.5f;
  1208. }
  1209. float D3D9RenderSystem::getVerticalTexelOffset()
  1210. {
  1211. // D3D considers the origin to be in the center of a pixel
  1212. return -0.5f;
  1213. }
  1214. float D3D9RenderSystem::getMinimumDepthInputValue()
  1215. {
  1216. // Range [0.0f, 1.0f]
  1217. return 0.0f;
  1218. }
  1219. float D3D9RenderSystem::getMaximumDepthInputValue()
  1220. {
  1221. // Range [0.0f, 1.0f]
  1222. // D3D inverts even identity view matrices, so maximum INPUT is -1.0
  1223. return -1.0f;
  1224. }
  1225. VertexElementType D3D9RenderSystem::getColorVertexElementType() const
  1226. {
  1227. return VET_COLOR_ARGB;
  1228. }
  1229. void D3D9RenderSystem::convertProjectionMatrix(const Matrix4& matrix, Matrix4& dest, bool forGpuProgram)
  1230. {
  1231. dest = matrix;
  1232. // Convert depth range from [-1,+1] to [0,1]
  1233. dest[2][0] = (dest[2][0] + dest[3][0]) / 2;
  1234. dest[2][1] = (dest[2][1] + dest[3][1]) / 2;
  1235. dest[2][2] = (dest[2][2] + dest[3][2]) / 2;
  1236. dest[2][3] = (dest[2][3] + dest[3][3]) / 2;
  1237. if (!forGpuProgram)
  1238. {
  1239. // Convert right-handed to left-handed
  1240. dest[0][2] = -dest[0][2];
  1241. dest[1][2] = -dest[1][2];
  1242. dest[2][2] = -dest[2][2];
  1243. dest[3][2] = -dest[3][2];
  1244. }
  1245. }
  1246. /************************************************************************/
  1247. /* PRIVATE */
  1248. /************************************************************************/
  1249. D3D9DriverList* D3D9RenderSystem::getDirect3DDrivers() const
  1250. {
  1251. if( !mDriverList )
  1252. mDriverList = bs_new<D3D9DriverList>();
  1253. return mDriverList;
  1254. }
  1255. D3DPRIMITIVETYPE D3D9RenderSystem::getD3D9PrimitiveType() const
  1256. {
  1257. switch(mCurrentDrawOperation)
  1258. {
  1259. case DOT_POINT_LIST:
  1260. return D3DPT_POINTLIST;
  1261. case DOT_LINE_LIST:
  1262. return D3DPT_LINELIST;
  1263. case DOT_LINE_STRIP:
  1264. return D3DPT_LINESTRIP;
  1265. case DOT_TRIANGLE_LIST:
  1266. return D3DPT_TRIANGLELIST;
  1267. case DOT_TRIANGLE_STRIP:
  1268. return D3DPT_TRIANGLESTRIP;
  1269. case DOT_TRIANGLE_FAN:
  1270. return D3DPT_TRIANGLEFAN;
  1271. }
  1272. return D3DPT_TRIANGLELIST;
  1273. }
  1274. RenderSystemCapabilities* D3D9RenderSystem::updateRenderSystemCapabilities(D3D9RenderWindow* renderWindow)
  1275. {
  1276. RenderSystemCapabilities* rsc = mCurrentCapabilities;
  1277. if (rsc == nullptr)
  1278. rsc = bs_new<RenderSystemCapabilities>();
  1279. rsc->setDriverVersion(mDriverVersion);
  1280. rsc->setDeviceName(mActiveD3DDriver->getDriverDescription());
  1281. rsc->setRenderSystemName(getName());
  1282. // Init caps to maximum.
  1283. rsc->setCapability(RSC_ANISOTROPY);
  1284. rsc->setCapability(RSC_AUTOMIPMAP);
  1285. rsc->setCapability(RSC_CUBEMAPPING);
  1286. rsc->setCapability(RSC_TWO_SIDED_STENCIL);
  1287. rsc->setCapability(RSC_STENCIL_WRAP);
  1288. rsc->setCapability(RSC_HWOCCLUSION);
  1289. rsc->setCapability(RSC_USER_CLIP_PLANES);
  1290. rsc->setCapability(RSC_VERTEX_FORMAT_UBYTE4);
  1291. rsc->setCapability(RSC_TEXTURE_3D);
  1292. rsc->setCapability(RSC_NON_POWER_OF_2_TEXTURES);
  1293. rsc->setNumMultiRenderTargets(BS_MAX_MULTIPLE_RENDER_TARGETS);
  1294. rsc->setCapability(RSC_MRT_DIFFERENT_BIT_DEPTHS);
  1295. rsc->setCapability(RSC_POINT_SPRITES);
  1296. rsc->setCapability(RSC_POINT_EXTENDED_PARAMETERS);
  1297. rsc->setMaxPointSize(10.0);
  1298. rsc->setCapability(RSC_MIPMAP_LOD_BIAS);
  1299. rsc->setCapability(RSC_PERSTAGECONSTANT);
  1300. rsc->setStencilBufferBitDepth(8);
  1301. rsc->setCapability(RSC_ADVANCED_BLEND_OPERATIONS);
  1302. for (UINT32 i=0; i < mDeviceManager->getDeviceCount(); ++i)
  1303. {
  1304. D3D9Device* device = mDeviceManager->getDevice(i);
  1305. IDirect3DDevice9* d3d9Device = device->getD3D9Device();
  1306. IDirect3DSurface9* pSurf;
  1307. // Check for hardware stencil support
  1308. d3d9Device->GetDepthStencilSurface(&pSurf);
  1309. if (pSurf != nullptr)
  1310. {
  1311. D3DSURFACE_DESC surfDesc;
  1312. pSurf->GetDesc(&surfDesc);
  1313. pSurf->Release();
  1314. }
  1315. // Check for hardware occlusion support
  1316. HRESULT hr = d3d9Device->CreateQuery(D3DQUERYTYPE_OCCLUSION, NULL);
  1317. if (FAILED(hr))
  1318. rsc->unsetCapability(RSC_HWOCCLUSION);
  1319. }
  1320. // Update RS caps using the minimum value found in adapter list.
  1321. for (unsigned int i=0; i < mDriverList->count(); ++i)
  1322. {
  1323. D3D9Driver* pCurDriver = mDriverList->item(i);
  1324. const D3DCAPS9& rkCurCaps = pCurDriver->getD3D9DeviceCaps();
  1325. rsc->setNumTextureUnits(GPT_FRAGMENT_PROGRAM, 16); // We don't support anything lower than SM3, and 16 is the sampler count determined by the specification
  1326. rsc->setMaxBoundVertexBuffers(static_cast<UINT32>(rkCurCaps.MaxStreams));
  1327. // Check for Anisotropy.
  1328. if (rkCurCaps.MaxAnisotropy <= 1)
  1329. rsc->unsetCapability(RSC_ANISOTROPY);
  1330. // Check automatic mipmap generation.
  1331. if ((rkCurCaps.Caps2 & D3DCAPS2_CANAUTOGENMIPMAP) == 0)
  1332. rsc->unsetCapability(RSC_AUTOMIPMAP);
  1333. // Two-sided stencil
  1334. if ((rkCurCaps.StencilCaps & D3DSTENCILCAPS_TWOSIDED) == 0)
  1335. rsc->unsetCapability(RSC_TWO_SIDED_STENCIL);
  1336. // stencil wrap
  1337. if ((rkCurCaps.StencilCaps & D3DSTENCILCAPS_INCR) == 0 ||
  1338. (rkCurCaps.StencilCaps & D3DSTENCILCAPS_DECR) == 0)
  1339. rsc->unsetCapability(RSC_STENCIL_WRAP);
  1340. // User clip planes
  1341. if (rkCurCaps.MaxUserClipPlanes == 0)
  1342. rsc->unsetCapability(RSC_USER_CLIP_PLANES);
  1343. // UBYTE4 type?
  1344. if ((rkCurCaps.DeclTypes & D3DDTCAPS_UBYTE4) == 0)
  1345. rsc->unsetCapability(RSC_VERTEX_FORMAT_UBYTE4);
  1346. // Check cube map support.
  1347. if ((rkCurCaps.TextureCaps & D3DPTEXTURECAPS_CUBEMAP) == 0)
  1348. rsc->unsetCapability(RSC_CUBEMAPPING);
  1349. // 3D textures?
  1350. if ((rkCurCaps.TextureCaps & D3DPTEXTURECAPS_VOLUMEMAP) == 0)
  1351. rsc->unsetCapability(RSC_TEXTURE_3D);
  1352. if (rkCurCaps.TextureCaps & D3DPTEXTURECAPS_POW2)
  1353. {
  1354. // Conditional support for non POW2
  1355. if (!(rkCurCaps.TextureCaps & D3DPTEXTURECAPS_NONPOW2CONDITIONAL))
  1356. rsc->unsetCapability(RSC_NON_POWER_OF_2_TEXTURES);
  1357. }
  1358. // Number of render targets
  1359. if (rkCurCaps.NumSimultaneousRTs < rsc->getNumMultiRenderTargets())
  1360. {
  1361. rsc->setNumMultiRenderTargets(std::min((UINT16)rkCurCaps.NumSimultaneousRTs, (UINT16)BS_MAX_MULTIPLE_RENDER_TARGETS));
  1362. }
  1363. if((rkCurCaps.PrimitiveMiscCaps & D3DPMISCCAPS_MRTINDEPENDENTBITDEPTHS) == 0)
  1364. {
  1365. rsc->unsetCapability(RSC_MRT_DIFFERENT_BIT_DEPTHS);
  1366. }
  1367. // Point sprites
  1368. if (rkCurCaps.MaxPointSize <= 1.0f)
  1369. {
  1370. rsc->unsetCapability(RSC_POINT_SPRITES);
  1371. // sprites and extended parameters go together in D3D
  1372. rsc->unsetCapability(RSC_POINT_EXTENDED_PARAMETERS);
  1373. }
  1374. // Take the minimum point size.
  1375. if (rkCurCaps.MaxPointSize < rsc->getMaxPointSize())
  1376. rsc->setMaxPointSize(rkCurCaps.MaxPointSize);
  1377. // Mipmap LOD biasing?
  1378. if ((rkCurCaps.RasterCaps & D3DPRASTERCAPS_MIPMAPLODBIAS) == 0)
  1379. rsc->unsetCapability(RSC_MIPMAP_LOD_BIAS);
  1380. // Do we support per-stage src_manual constants?
  1381. // HACK - ATI drivers seem to be buggy and don't support per-stage constants properly?
  1382. // TODO: move this to RSC
  1383. if((rkCurCaps.PrimitiveMiscCaps & D3DPMISCCAPS_PERSTAGECONSTANT) == 0)
  1384. rsc->unsetCapability(RSC_PERSTAGECONSTANT);
  1385. // Advanced blend operations? min max subtract rev
  1386. if((rkCurCaps.PrimitiveMiscCaps & D3DPMISCCAPS_BLENDOP) == 0)
  1387. rsc->unsetCapability(RSC_ADVANCED_BLEND_OPERATIONS);
  1388. }
  1389. // We always support compression, D3DX will decompress if device does not support
  1390. rsc->setCapability(RSC_TEXTURE_COMPRESSION);
  1391. rsc->setCapability(RSC_TEXTURE_COMPRESSION_DXT);
  1392. updateVertexShaderCaps(rsc);
  1393. updatePixelShaderCaps(rsc);
  1394. // Adapter details
  1395. const D3DADAPTER_IDENTIFIER9& adapterID = mActiveD3DDriver->getAdapterIdentifier();
  1396. // determine vendor
  1397. // Full list of vendors here: http://www.pcidatabase.com/vendors.php?sort=id
  1398. switch(adapterID.VendorId)
  1399. {
  1400. case 0x10DE:
  1401. rsc->setVendor(GPU_NVIDIA);
  1402. break;
  1403. case 0x1002:
  1404. rsc->setVendor(GPU_AMD);
  1405. break;
  1406. case 0x163C:
  1407. case 0x8086:
  1408. rsc->setVendor(GPU_INTEL);
  1409. break;
  1410. default:
  1411. rsc->setVendor(GPU_UNKNOWN);
  1412. break;
  1413. };
  1414. rsc->setCapability(RSC_INFINITE_FAR_PLANE);
  1415. // We always support rendertextures bigger than the frame buffer
  1416. rsc->setCapability(RSC_HWRENDER_TO_TEXTURE);
  1417. // Determine if any floating point texture format is supported
  1418. D3DFORMAT floatFormats[6] = {D3DFMT_R16F, D3DFMT_G16R16F,
  1419. D3DFMT_A16B16G16R16F, D3DFMT_R32F, D3DFMT_G32R32F,
  1420. D3DFMT_A32B32G32R32F};
  1421. IDirect3DSurface9* bbSurf;
  1422. renderWindow->getCore()->getCustomAttribute("DDBACKBUFFER", &bbSurf);
  1423. D3DSURFACE_DESC bbSurfDesc;
  1424. bbSurf->GetDesc(&bbSurfDesc);
  1425. for (int i = 0; i < 6; ++i)
  1426. {
  1427. if (SUCCEEDED(mpD3D->CheckDeviceFormat(mActiveD3DDriver->getAdapterNumber(),
  1428. D3DDEVTYPE_HAL, bbSurfDesc.Format,
  1429. 0, D3DRTYPE_TEXTURE, floatFormats[i])))
  1430. {
  1431. rsc->setCapability(RSC_TEXTURE_FLOAT);
  1432. break;
  1433. }
  1434. }
  1435. // Vertex textures
  1436. if (rsc->isShaderProfileSupported("vs_3_0"))
  1437. {
  1438. rsc->setCapability(RSC_VERTEX_TEXTURE_FETCH);
  1439. rsc->setNumTextureUnits(GPT_VERTEX_PROGRAM, 4);
  1440. rsc->setNumCombinedTextureUnits(rsc->getNumTextureUnits(GPT_FRAGMENT_PROGRAM) +
  1441. rsc->getNumTextureUnits(GPT_VERTEX_PROGRAM));
  1442. }
  1443. else
  1444. {
  1445. rsc->setNumCombinedTextureUnits(rsc->getNumTextureUnits(GPT_FRAGMENT_PROGRAM));
  1446. }
  1447. // Check alpha to coverage support
  1448. // this varies per vendor! But at least SM3 is required
  1449. if (rsc->isShaderProfileSupported("ps_3_0"))
  1450. {
  1451. // NVIDIA needs a separate check
  1452. if (rsc->getVendor() == GPU_NVIDIA)
  1453. {
  1454. if (mpD3D->CheckDeviceFormat(
  1455. D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, D3DFMT_X8R8G8B8, 0,D3DRTYPE_SURFACE,
  1456. (D3DFORMAT)MAKEFOURCC('A', 'T', 'O', 'C')) == S_OK)
  1457. {
  1458. rsc->setCapability(RSC_ALPHA_TO_COVERAGE);
  1459. }
  1460. }
  1461. else if (rsc->getVendor() == GPU_AMD)
  1462. {
  1463. // There is no check on ATI, we have to assume SM3 == support
  1464. rsc->setCapability(RSC_ALPHA_TO_COVERAGE);
  1465. }
  1466. // no other cards have Dx9 hacks for alpha to coverage, as far as I know
  1467. }
  1468. if (mCurrentCapabilities == nullptr)
  1469. {
  1470. mCurrentCapabilities = rsc;
  1471. mCurrentCapabilities->addShaderProfile("hlsl");
  1472. mCurrentCapabilities->addShaderProfile("cg");
  1473. if (mCurrentCapabilities->isShaderProfileSupported("hlsl"))
  1474. GpuProgramManager::instance().addFactory(mHLSLProgramFactory);
  1475. mNumTexStages = mCurrentCapabilities->getNumCombinedTextureUnits();
  1476. mTexStageDesc = bs_newN<sD3DTextureStageDesc>(mNumTexStages);
  1477. // set stages desc. to defaults
  1478. for (UINT32 n = 0; n < mNumTexStages; n++)
  1479. {
  1480. mTexStageDesc[n].coordIndex = 0;
  1481. mTexStageDesc[n].texType = D3D9Mappings::D3D_TEX_TYPE_NORMAL;
  1482. mTexStageDesc[n].pTex = 0;
  1483. mTexStageDesc[n].pVertexTex = 0;
  1484. }
  1485. }
  1486. return rsc;
  1487. }
  1488. void D3D9RenderSystem::updateVertexShaderCaps(RenderSystemCapabilities* rsc) const
  1489. {
  1490. UINT16 major = 0xFF;
  1491. UINT16 minor = 0xFF;
  1492. D3DCAPS9 minVSCaps;
  1493. // Find the device with the lowest vertex shader caps.
  1494. for (unsigned int i=0; i < mDriverList->count(); ++i)
  1495. {
  1496. D3D9Driver* pCurDriver = mDriverList->item(i);
  1497. const D3DCAPS9& rkCurCaps = pCurDriver->getD3D9DeviceCaps();
  1498. UINT16 currMajor = static_cast<UINT16>((rkCurCaps.VertexShaderVersion & 0x0000FF00) >> 8);
  1499. UINT16 currMinor = static_cast<UINT16>(rkCurCaps.VertexShaderVersion & 0x000000FF);
  1500. if (currMajor < major)
  1501. {
  1502. major = currMajor;
  1503. minor = currMinor;
  1504. minVSCaps = rkCurCaps;
  1505. }
  1506. else if (currMajor == major && currMinor < minor)
  1507. {
  1508. minor = currMinor;
  1509. minVSCaps = rkCurCaps;
  1510. }
  1511. }
  1512. // In case we didn't found any vertex shader support
  1513. // try the IDirect3DDevice9 caps instead of the IDirect3D9
  1514. // software vertex processing is reported there
  1515. if (major == 0 && minor == 0)
  1516. {
  1517. IDirect3DDevice9* lpD3DDevice9 = getActiveD3D9Device();
  1518. D3DCAPS9 d3dDeviceCaps9;
  1519. lpD3DDevice9->GetDeviceCaps(&d3dDeviceCaps9);
  1520. major = static_cast<UINT16>((d3dDeviceCaps9.VertexShaderVersion & 0x0000FF00) >> 8);
  1521. minor = static_cast<UINT16>(d3dDeviceCaps9.VertexShaderVersion & 0x000000FF);
  1522. }
  1523. bool vs2x = false;
  1524. bool vs2a = false;
  1525. // Special case detection for vs_2_x/a support
  1526. if (major >= 2)
  1527. {
  1528. if ((minVSCaps.VS20Caps.Caps & D3DVS20CAPS_PREDICATION) &&
  1529. (minVSCaps.VS20Caps.DynamicFlowControlDepth > 0) &&
  1530. (minVSCaps.VS20Caps.NumTemps >= 12))
  1531. {
  1532. vs2x = true;
  1533. }
  1534. if ((minVSCaps.VS20Caps.Caps & D3DVS20CAPS_PREDICATION) &&
  1535. (minVSCaps.VS20Caps.DynamicFlowControlDepth > 0) &&
  1536. (minVSCaps.VS20Caps.NumTemps >= 13))
  1537. {
  1538. vs2a = true;
  1539. }
  1540. }
  1541. // Populate max param count
  1542. switch (major)
  1543. {
  1544. case 1:
  1545. // No boolean params allowed
  1546. rsc->setVertexProgramConstantBoolCount(0);
  1547. // No integer params allowed
  1548. rsc->setVertexProgramConstantIntCount(0);
  1549. // float params, always 4D
  1550. rsc->setVertexProgramConstantFloatCount(static_cast<UINT16>(minVSCaps.MaxVertexShaderConst));
  1551. break;
  1552. case 2:
  1553. // 16 boolean params allowed
  1554. rsc->setVertexProgramConstantBoolCount(16);
  1555. // 16 integer params allowed, 4D
  1556. rsc->setVertexProgramConstantIntCount(16);
  1557. // float params, always 4D
  1558. rsc->setVertexProgramConstantFloatCount(static_cast<UINT16>(minVSCaps.MaxVertexShaderConst));
  1559. break;
  1560. case 3:
  1561. // 16 boolean params allowed
  1562. rsc->setVertexProgramConstantBoolCount(16);
  1563. // 16 integer params allowed, 4D
  1564. rsc->setVertexProgramConstantIntCount(16);
  1565. // float params, always 4D
  1566. rsc->setVertexProgramConstantFloatCount(static_cast<UINT16>(minVSCaps.MaxVertexShaderConst));
  1567. break;
  1568. }
  1569. // populate syntax codes in program manager (no breaks in this one so it falls through)
  1570. switch(major)
  1571. {
  1572. case 3:
  1573. rsc->addShaderProfile("vs_3_0");
  1574. rsc->addGpuProgramProfile(GPP_VS_3_0, "vs_3_0");
  1575. case 2:
  1576. if (vs2x)
  1577. {
  1578. rsc->addShaderProfile("vs_2_x");
  1579. rsc->addGpuProgramProfile(GPP_VS_2_x, "vs_2_x");
  1580. }
  1581. if (vs2a)
  1582. {
  1583. rsc->addShaderProfile("vs_2_a");
  1584. rsc->addGpuProgramProfile(GPP_VS_2_a, "vs_2_a");
  1585. }
  1586. rsc->addShaderProfile("vs_2_0");
  1587. rsc->addGpuProgramProfile(GPP_VS_2_0, "vs_2_0");
  1588. case 1:
  1589. rsc->addShaderProfile("vs_1_1");
  1590. rsc->addGpuProgramProfile(GPP_VS_1_1, "vs_1_1");
  1591. }
  1592. }
  1593. void D3D9RenderSystem::updatePixelShaderCaps(RenderSystemCapabilities* rsc) const
  1594. {
  1595. UINT16 major = 0xFF;
  1596. UINT16 minor = 0xFF;
  1597. D3DCAPS9 minPSCaps;
  1598. // Find the device with the lowest pixel shader caps.
  1599. for (unsigned int i=0; i < mDriverList->count(); ++i)
  1600. {
  1601. D3D9Driver* pCurDriver = mDriverList->item(i);
  1602. const D3DCAPS9& currCaps = pCurDriver->getD3D9DeviceCaps();
  1603. UINT16 currMajor = static_cast<UINT16>((currCaps.PixelShaderVersion & 0x0000FF00) >> 8);
  1604. UINT16 currMinor = static_cast<UINT16>(currCaps.PixelShaderVersion & 0x000000FF);
  1605. if (currMajor < major)
  1606. {
  1607. major = currMajor;
  1608. minor = currMinor;
  1609. minPSCaps = currCaps;
  1610. }
  1611. else if (currMajor == major && currMinor < minor)
  1612. {
  1613. minor = currMinor;
  1614. minPSCaps = currCaps;
  1615. }
  1616. }
  1617. bool ps2a = false;
  1618. bool ps2b = false;
  1619. bool ps2x = false;
  1620. // Special case detection for ps_2_x/a/b support
  1621. if (major >= 2)
  1622. {
  1623. if ((minPSCaps.PS20Caps.Caps & D3DPS20CAPS_NOTEXINSTRUCTIONLIMIT) &&
  1624. (minPSCaps.PS20Caps.NumTemps >= 32))
  1625. {
  1626. ps2b = true;
  1627. }
  1628. if ((minPSCaps.PS20Caps.Caps & D3DPS20CAPS_NOTEXINSTRUCTIONLIMIT) &&
  1629. (minPSCaps.PS20Caps.Caps & D3DPS20CAPS_NODEPENDENTREADLIMIT) &&
  1630. (minPSCaps.PS20Caps.Caps & D3DPS20CAPS_ARBITRARYSWIZZLE) &&
  1631. (minPSCaps.PS20Caps.Caps & D3DPS20CAPS_GRADIENTINSTRUCTIONS) &&
  1632. (minPSCaps.PS20Caps.Caps & D3DPS20CAPS_PREDICATION) &&
  1633. (minPSCaps.PS20Caps.NumTemps >= 22))
  1634. {
  1635. ps2a = true;
  1636. }
  1637. // Does this enough?
  1638. if (ps2a || ps2b)
  1639. {
  1640. ps2x = true;
  1641. }
  1642. }
  1643. switch (major)
  1644. {
  1645. case 1:
  1646. // no boolean params allowed
  1647. rsc->setFragmentProgramConstantBoolCount(0);
  1648. // no integer params allowed
  1649. rsc->setFragmentProgramConstantIntCount(0);
  1650. // float params, always 4D
  1651. rsc->setFragmentProgramConstantFloatCount(8);
  1652. break;
  1653. case 2:
  1654. // 16 boolean params allowed
  1655. rsc->setFragmentProgramConstantBoolCount(16);
  1656. // 16 integer params allowed, 4D
  1657. rsc->setFragmentProgramConstantIntCount(16);
  1658. // float params, always 4D
  1659. rsc->setFragmentProgramConstantFloatCount(32);
  1660. break;
  1661. case 3:
  1662. // 16 boolean params allowed
  1663. rsc->setFragmentProgramConstantBoolCount(16);
  1664. // 16 integer params allowed, 4D
  1665. rsc->setFragmentProgramConstantIntCount(16);
  1666. // float params, always 4D
  1667. rsc->setFragmentProgramConstantFloatCount(224);
  1668. break;
  1669. }
  1670. // populate syntax codes in program manager (no breaks in this one so it falls through)
  1671. switch(major)
  1672. {
  1673. case 3:
  1674. if (minor > 0)
  1675. {
  1676. rsc->addShaderProfile("ps_3_x");
  1677. rsc->addGpuProgramProfile(GPP_PS_3_x, "ps_3_x");
  1678. }
  1679. rsc->addShaderProfile("ps_3_0");
  1680. rsc->addGpuProgramProfile(GPP_PS_3_0, "ps_3_0");
  1681. case 2:
  1682. if (ps2x)
  1683. {
  1684. rsc->addShaderProfile("ps_2_x");
  1685. rsc->addGpuProgramProfile(GPP_PS_2_x, "ps_2_x");
  1686. }
  1687. if (ps2a)
  1688. {
  1689. rsc->addShaderProfile("ps_2_a");
  1690. rsc->addGpuProgramProfile(GPP_PS_2_a, "ps_2_a");
  1691. }
  1692. if (ps2b)
  1693. {
  1694. rsc->addShaderProfile("ps_2_b");
  1695. rsc->addGpuProgramProfile(GPP_PS_2_b, "ps_2_b");
  1696. }
  1697. rsc->addShaderProfile("ps_2_0");
  1698. rsc->addGpuProgramProfile(GPP_PS_2_0, "ps_2_0");
  1699. case 1:
  1700. if (major > 1 || minor >= 4)
  1701. {
  1702. rsc->addShaderProfile("ps_1_4");
  1703. rsc->addGpuProgramProfile(GPP_PS_1_4, "ps_1_4");
  1704. }
  1705. if (major > 1 || minor >= 3)
  1706. {
  1707. rsc->addShaderProfile("ps_1_3");
  1708. rsc->addGpuProgramProfile(GPP_PS_1_3, "ps_1_3");
  1709. }
  1710. if (major > 1 || minor >= 2)
  1711. {
  1712. rsc->addShaderProfile("ps_1_2");
  1713. rsc->addGpuProgramProfile(GPP_PS_1_2, "ps_1_2");
  1714. }
  1715. rsc->addShaderProfile("ps_1_1");
  1716. rsc->addGpuProgramProfile(GPP_PS_1_1, "ps_1_1");
  1717. }
  1718. }
  1719. String D3D9RenderSystem::getErrorDescription(long errorNumber) const
  1720. {
  1721. const String errMsg = DXGetErrorDescription(errorNumber);
  1722. return errMsg;
  1723. }
  1724. void D3D9RenderSystem::setClipPlane (UINT16 index, float A, float B, float C, float D)
  1725. {
  1726. float plane[4] = { A, B, C, D };
  1727. getActiveD3D9Device()->SetClipPlane (index, plane);
  1728. }
  1729. void D3D9RenderSystem::enableClipPlane (UINT16 index, bool enable)
  1730. {
  1731. DWORD prev;
  1732. getActiveD3D9Device()->GetRenderState(D3DRS_CLIPPLANEENABLE, &prev);
  1733. setRenderState(D3DRS_CLIPPLANEENABLE, enable?
  1734. (prev | (1 << index)) : (prev & ~(1 << index)));
  1735. }
  1736. void D3D9RenderSystem::notifyOnDeviceLost(D3D9Device* device)
  1737. {
  1738. if (mIsFrameInProgress)
  1739. {
  1740. endFrame();
  1741. mRestoreFrameOnReset = true;
  1742. }
  1743. }
  1744. void D3D9RenderSystem::notifyOnDeviceReset(D3D9Device* device)
  1745. {
  1746. // Reset state attributes.
  1747. mVertexProgramBound = false;
  1748. mFragmentProgramBound = false;
  1749. if (mRestoreFrameOnReset)
  1750. {
  1751. beginFrame();
  1752. mRestoreFrameOnReset = false;
  1753. }
  1754. }
  1755. void D3D9RenderSystem::determineMultisampleSettings(IDirect3DDevice9* d3d9Device,
  1756. UINT32 multisampleCount, const String& multisampleHint, D3DFORMAT d3dPixelFormat,
  1757. bool fullScreen, D3DMULTISAMPLE_TYPE *outMultisampleType, DWORD *outMultisampleQuality) const
  1758. {
  1759. bool ok = false;
  1760. bool qualityHint = multisampleHint.find("Quality") != String::npos;
  1761. UINT32 origCount = multisampleCount;
  1762. D3D9DriverList* driverList = getDirect3DDrivers();
  1763. D3D9Driver* deviceDriver = mActiveD3DDriver;
  1764. D3D9Device* device = mDeviceManager->getDeviceFromD3D9Device(d3d9Device);
  1765. for (UINT32 i = 0; i < driverList->count(); ++i)
  1766. {
  1767. D3D9Driver* currDriver = driverList->item(i);
  1768. if (currDriver->getAdapterNumber() == device->getAdapterNumber())
  1769. {
  1770. deviceDriver = currDriver;
  1771. break;
  1772. }
  1773. }
  1774. bool tryCSAA = false;
  1775. // NVIDIA, prefer CSAA if available for 8+
  1776. // it would be tempting to use getCapabilities()->getVendor() == GPU_NVIDIA but
  1777. // if this is the first window, caps will not be initialised yet
  1778. if (deviceDriver->getAdapterIdentifier().VendorId == 0x10DE &&
  1779. multisampleCount >= 8)
  1780. {
  1781. tryCSAA = true;
  1782. }
  1783. while (!ok)
  1784. {
  1785. // Deal with special cases
  1786. if (tryCSAA)
  1787. {
  1788. // see http://developer.nvidia.com/object/coverage-sampled-aa.html
  1789. switch(multisampleCount)
  1790. {
  1791. case 8:
  1792. if (qualityHint)
  1793. {
  1794. *outMultisampleType = D3DMULTISAMPLE_8_SAMPLES;
  1795. *outMultisampleQuality = 0;
  1796. }
  1797. else
  1798. {
  1799. *outMultisampleType = D3DMULTISAMPLE_4_SAMPLES;
  1800. *outMultisampleQuality = 2;
  1801. }
  1802. break;
  1803. case 16:
  1804. if (qualityHint)
  1805. {
  1806. *outMultisampleType = D3DMULTISAMPLE_8_SAMPLES;
  1807. *outMultisampleQuality = 2;
  1808. }
  1809. else
  1810. {
  1811. *outMultisampleType = D3DMULTISAMPLE_4_SAMPLES;
  1812. *outMultisampleQuality = 4;
  1813. }
  1814. break;
  1815. }
  1816. }
  1817. else // !CSAA
  1818. {
  1819. *outMultisampleType = (D3DMULTISAMPLE_TYPE)multisampleCount;
  1820. *outMultisampleQuality = 0;
  1821. }
  1822. HRESULT hr;
  1823. DWORD outQuality;
  1824. hr = mpD3D->CheckDeviceMultiSampleType(
  1825. deviceDriver->getAdapterNumber(),
  1826. D3DDEVTYPE_HAL,
  1827. d3dPixelFormat,
  1828. !fullScreen,
  1829. *outMultisampleType,
  1830. &outQuality);
  1831. if (SUCCEEDED(hr) &&
  1832. (!tryCSAA || outQuality > *outMultisampleQuality))
  1833. {
  1834. ok = true;
  1835. }
  1836. else
  1837. {
  1838. // downgrade
  1839. if (tryCSAA && multisampleCount == 8)
  1840. {
  1841. // for CSAA, we'll try downgrading with quality mode at all samples.
  1842. // then try without quality, then drop CSAA
  1843. if (qualityHint)
  1844. {
  1845. // drop quality first
  1846. qualityHint = false;
  1847. }
  1848. else
  1849. {
  1850. // drop CSAA entirely
  1851. tryCSAA = false;
  1852. }
  1853. // return to original requested samples
  1854. multisampleCount = origCount;
  1855. }
  1856. else
  1857. {
  1858. // drop samples
  1859. --multisampleCount;
  1860. if (multisampleCount == 1)
  1861. {
  1862. // ran out of options, no multisampling
  1863. multisampleCount = 0;
  1864. ok = true;
  1865. }
  1866. }
  1867. }
  1868. } // while !ok
  1869. }
  1870. void D3D9RenderSystem::setClipPlanesImpl(const PlaneList& clipPlanes)
  1871. {
  1872. size_t i;
  1873. size_t numClipPlanes;
  1874. D3DXPLANE dx9ClipPlane;
  1875. DWORD mask = 0;
  1876. HRESULT hr;
  1877. numClipPlanes = clipPlanes.size();
  1878. for (i = 0; i < numClipPlanes; ++i)
  1879. {
  1880. const Plane& plane = clipPlanes[i];
  1881. dx9ClipPlane.a = plane.normal.x;
  1882. dx9ClipPlane.b = plane.normal.y;
  1883. dx9ClipPlane.c = plane.normal.z;
  1884. dx9ClipPlane.d = plane.d;
  1885. // TODO Low priority - Transform planes to clip space?
  1886. hr = getActiveD3D9Device()->SetClipPlane(static_cast<DWORD>(i), dx9ClipPlane);
  1887. if (FAILED(hr))
  1888. {
  1889. BS_EXCEPT(RenderingAPIException, "Unable to set clip plane");
  1890. }
  1891. mask |= (1 << i);
  1892. }
  1893. hr = setRenderState(D3DRS_CLIPPLANEENABLE, mask);
  1894. if (FAILED(hr))
  1895. {
  1896. BS_EXCEPT(RenderingAPIException, "Unable to set render state for clip planes");
  1897. }
  1898. }
  1899. HRESULT D3D9RenderSystem::setRenderState(D3DRENDERSTATETYPE state, DWORD value)
  1900. {
  1901. return getActiveD3D9Device()->SetRenderState(state, value);
  1902. }
  1903. HRESULT D3D9RenderSystem::setSamplerState(DWORD sampler, D3DSAMPLERSTATETYPE type, DWORD value)
  1904. {
  1905. return getActiveD3D9Device()->SetSamplerState(sampler, type, value);
  1906. }
  1907. HRESULT D3D9RenderSystem::setTextureStageState(DWORD stage, D3DTEXTURESTAGESTATETYPE type, DWORD value)
  1908. {
  1909. if (stage < 8)
  1910. return getActiveD3D9Device()->SetTextureStageState(stage, type, value);
  1911. else
  1912. return D3D_OK;
  1913. }
  1914. DWORD D3D9RenderSystem::getCurrentAnisotropy(UINT32 unit)
  1915. {
  1916. DWORD oldVal;
  1917. getActiveD3D9Device()->GetSamplerState(static_cast<DWORD>(unit), D3DSAMP_MAXANISOTROPY, &oldVal);
  1918. return oldVal;
  1919. }
  1920. }