CmD3D9RenderSystem.cpp 84 KB

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