CmD3D9RenderSystem.cpp 83 KB

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