CmD3D9RenderSystem.cpp 90 KB

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