CmD3D9RenderSystem.cpp 74 KB

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