CmD3D9RenderSystem.cpp 94 KB

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