CmD3D9RenderSystem.cpp 74 KB

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