BsD3D9RenderSystem.cpp 69 KB

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