CmD3D9RenderSystem.cpp 116 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612
  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. #define FLOAT2DWORD(f) *((DWORD*)&f)
  48. namespace CamelotEngine
  49. {
  50. D3D9RenderSystem* D3D9RenderSystem::msD3D9RenderSystem = NULL;
  51. //---------------------------------------------------------------------
  52. D3D9RenderSystem::D3D9RenderSystem( HINSTANCE hInstance )
  53. {
  54. // update singleton access pointer.
  55. msD3D9RenderSystem = this;
  56. // set the instance being passed
  57. mhInstance = hInstance;
  58. // set pointers to NULL
  59. mpD3D = NULL;
  60. mDriverList = NULL;
  61. mActiveD3DDriver = NULL;
  62. mUseNVPerfHUD = false;
  63. mHLSLProgramFactory = NULL;
  64. mCgProgramFactory = NULL;
  65. mDeviceManager = NULL;
  66. // Create the resource manager.
  67. mResourceManager = new D3D9ResourceManager();
  68. // Create our Direct3D object
  69. if( NULL == (mpD3D = Direct3DCreate9(D3D_SDK_VERSION)) )
  70. CM_EXCEPT(InternalErrorException, "Failed to create Direct3D9 object");
  71. // set config options defaults
  72. initConfigOptions();
  73. // fsaa options
  74. mFSAAHint = "";
  75. mFSAASamples = 0;
  76. // set stages desc. to defaults
  77. for (size_t n = 0; n < CM_MAX_TEXTURE_LAYERS; n++)
  78. {
  79. mTexStageDesc[n].autoTexCoordType = TEXCALC_NONE;
  80. mTexStageDesc[n].coordIndex = 0;
  81. mTexStageDesc[n].texType = D3D9Mappings::D3D_TEX_TYPE_NORMAL;
  82. mTexStageDesc[n].pTex = 0;
  83. mTexStageDesc[n].pVertexTex = 0;
  84. }
  85. mLastVertexSourceCount = 0;
  86. mCurrentLights.clear();
  87. // Enumerate events
  88. mEventNames.push_back("DeviceLost");
  89. mEventNames.push_back("DeviceRestored");
  90. }
  91. //---------------------------------------------------------------------
  92. D3D9RenderSystem::~D3D9RenderSystem()
  93. {
  94. shutdown();
  95. // Deleting the HLSL program factory
  96. if (mHLSLProgramFactory)
  97. {
  98. HighLevelGpuProgramManager::instance().removeFactory(mHLSLProgramFactory);
  99. delete mHLSLProgramFactory;
  100. mHLSLProgramFactory = 0;
  101. }
  102. if(mCgProgramFactory)
  103. {
  104. HighLevelGpuProgramManager::instance().removeFactory(mCgProgramFactory);
  105. delete mCgProgramFactory;
  106. mCgProgramFactory = 0;
  107. }
  108. SAFE_RELEASE( mpD3D );
  109. SAFE_DELETE ( mResourceManager );
  110. msD3D9RenderSystem = NULL;
  111. }
  112. //---------------------------------------------------------------------
  113. const String& D3D9RenderSystem::getName() const
  114. {
  115. static String strName( "Direct3D9 Rendering Subsystem");
  116. return strName;
  117. }
  118. //---------------------------------------------------------------------
  119. D3D9DriverList* D3D9RenderSystem::getDirect3DDrivers()
  120. {
  121. if( !mDriverList )
  122. mDriverList = new D3D9DriverList();
  123. return mDriverList;
  124. }
  125. //---------------------------------------------------------------------
  126. bool D3D9RenderSystem::_checkMultiSampleQuality(D3DMULTISAMPLE_TYPE type, DWORD *outQuality, D3DFORMAT format, UINT adapterNum, D3DDEVTYPE deviceType, BOOL fullScreen)
  127. {
  128. HRESULT hr;
  129. hr = mpD3D->CheckDeviceMultiSampleType(
  130. adapterNum,
  131. deviceType,
  132. format,
  133. fullScreen,
  134. type,
  135. outQuality);
  136. if (SUCCEEDED(hr))
  137. return true;
  138. else
  139. return false;
  140. }
  141. //---------------------------------------------------------------------
  142. void D3D9RenderSystem::initConfigOptions()
  143. {
  144. D3D9DriverList* driverList;
  145. D3D9Driver* driver;
  146. ConfigOption optDevice;
  147. ConfigOption optVideoMode;
  148. ConfigOption optFullScreen;
  149. ConfigOption optVSync;
  150. ConfigOption optVSyncInterval;
  151. ConfigOption optAA;
  152. ConfigOption optFPUMode;
  153. ConfigOption optNVPerfHUD;
  154. ConfigOption optSRGB;
  155. ConfigOption optResourceCeationPolicy;
  156. driverList = this->getDirect3DDrivers();
  157. optDevice.name = "Rendering Device";
  158. optDevice.currentValue.clear();
  159. optDevice.possibleValues.clear();
  160. optDevice.immutable = false;
  161. optVideoMode.name = "Video Mode";
  162. optVideoMode.currentValue = "800 x 600 @ 32-bit colour";
  163. optVideoMode.immutable = false;
  164. optFullScreen.name = "Full Screen";
  165. optFullScreen.possibleValues.push_back( "Yes" );
  166. optFullScreen.possibleValues.push_back( "No" );
  167. optFullScreen.currentValue = "Yes";
  168. optFullScreen.immutable = false;
  169. optResourceCeationPolicy.name = "Resource Creation Policy";
  170. optResourceCeationPolicy.possibleValues.push_back( "Create on all devices" );
  171. optResourceCeationPolicy.possibleValues.push_back( "Create on active device" );
  172. if (mResourceManager->getCreationPolicy() == RCP_CREATE_ON_ACTIVE_DEVICE)
  173. optResourceCeationPolicy.currentValue = "Create on active device";
  174. else if (mResourceManager->getCreationPolicy() == RCP_CREATE_ON_ALL_DEVICES)
  175. optResourceCeationPolicy.currentValue = "Create on all devices";
  176. else
  177. optResourceCeationPolicy.currentValue = "N/A";
  178. optResourceCeationPolicy.immutable = false;
  179. for( unsigned j=0; j < driverList->count(); j++ )
  180. {
  181. driver = driverList->item(j);
  182. optDevice.possibleValues.push_back( driver->DriverDescription() );
  183. // Make first one default
  184. if( j==0 )
  185. optDevice.currentValue = driver->DriverDescription();
  186. }
  187. optVSync.name = "VSync";
  188. optVSync.immutable = false;
  189. optVSync.possibleValues.push_back( "Yes" );
  190. optVSync.possibleValues.push_back( "No" );
  191. optVSync.currentValue = "No";
  192. optVSyncInterval.name = "VSync Interval";
  193. optVSyncInterval.immutable = false;
  194. optVSyncInterval.possibleValues.push_back( "1" );
  195. optVSyncInterval.possibleValues.push_back( "2" );
  196. optVSyncInterval.possibleValues.push_back( "3" );
  197. optVSyncInterval.possibleValues.push_back( "4" );
  198. optVSyncInterval.currentValue = "1";
  199. optAA.name = "FSAA";
  200. optAA.immutable = false;
  201. optAA.possibleValues.push_back( "None" );
  202. optAA.currentValue = "None";
  203. optFPUMode.name = "Floating-point mode";
  204. #if OGRE_DOUBLE_PRECISION
  205. optFPUMode.currentValue = "Consistent";
  206. #else
  207. optFPUMode.currentValue = "Fastest";
  208. #endif
  209. optFPUMode.possibleValues.clear();
  210. optFPUMode.possibleValues.push_back("Fastest");
  211. optFPUMode.possibleValues.push_back("Consistent");
  212. optFPUMode.immutable = false;
  213. optNVPerfHUD.currentValue = "No";
  214. optNVPerfHUD.immutable = false;
  215. optNVPerfHUD.name = "Allow NVPerfHUD";
  216. optNVPerfHUD.possibleValues.push_back( "Yes" );
  217. optNVPerfHUD.possibleValues.push_back( "No" );
  218. // SRGB on auto window
  219. optSRGB.name = "sRGB Gamma Conversion";
  220. optSRGB.possibleValues.push_back("Yes");
  221. optSRGB.possibleValues.push_back("No");
  222. optSRGB.currentValue = "No";
  223. optSRGB.immutable = false;
  224. mOptions[optDevice.name] = optDevice;
  225. mOptions[optVideoMode.name] = optVideoMode;
  226. mOptions[optFullScreen.name] = optFullScreen;
  227. mOptions[optVSync.name] = optVSync;
  228. mOptions[optVSyncInterval.name] = optVSyncInterval;
  229. mOptions[optAA.name] = optAA;
  230. mOptions[optFPUMode.name] = optFPUMode;
  231. mOptions[optNVPerfHUD.name] = optNVPerfHUD;
  232. mOptions[optSRGB.name] = optSRGB;
  233. mOptions[optResourceCeationPolicy.name] = optResourceCeationPolicy;
  234. refreshD3DSettings();
  235. }
  236. //---------------------------------------------------------------------
  237. void D3D9RenderSystem::refreshD3DSettings()
  238. {
  239. ConfigOption* optVideoMode;
  240. D3D9Driver* driver = 0;
  241. D3D9VideoMode* videoMode;
  242. ConfigOptionMap::iterator opt = mOptions.find( "Rendering Device" );
  243. if( opt != mOptions.end() )
  244. {
  245. for( unsigned j=0; j < getDirect3DDrivers()->count(); j++ )
  246. {
  247. D3D9Driver* curDriver = getDirect3DDrivers()->item(j);
  248. if( curDriver->DriverDescription() == opt->second.currentValue )
  249. {
  250. driver = curDriver;
  251. break;
  252. }
  253. }
  254. if (driver)
  255. {
  256. opt = mOptions.find( "Video Mode" );
  257. optVideoMode = &opt->second;
  258. optVideoMode->possibleValues.clear();
  259. // get vide modes for this device
  260. for( unsigned k=0; k < driver->getVideoModeList()->count(); k++ )
  261. {
  262. videoMode = driver->getVideoModeList()->item( k );
  263. optVideoMode->possibleValues.push_back( videoMode->getDescription() );
  264. }
  265. // Reset video mode to default if previous doesn't avail in new possible values
  266. std::vector<CamelotEngine::String>::const_iterator itValue =
  267. std::find(optVideoMode->possibleValues.begin(),
  268. optVideoMode->possibleValues.end(),
  269. optVideoMode->currentValue);
  270. if (itValue == optVideoMode->possibleValues.end())
  271. {
  272. optVideoMode->currentValue = "800 x 600 @ 32-bit colour";
  273. }
  274. // Also refresh FSAA options
  275. refreshFSAAOptions();
  276. }
  277. }
  278. }
  279. //---------------------------------------------------------------------
  280. void D3D9RenderSystem::setConfigOption( const String &name, const String &value )
  281. {
  282. bool viewModeChanged = false;
  283. // Find option
  284. ConfigOptionMap::iterator it = mOptions.find( name );
  285. // Update
  286. if( it != mOptions.end() )
  287. it->second.currentValue = value;
  288. else
  289. {
  290. StringUtil::StrStreamType str;
  291. str << "Option named '" << name << "' does not exist.";
  292. CM_EXCEPT(InvalidParametersException, str.str() );
  293. }
  294. // Refresh other options if D3DDriver changed
  295. if( name == "Rendering Device" )
  296. refreshD3DSettings();
  297. if( name == "Full Screen" )
  298. {
  299. // Video mode is applicable
  300. it = mOptions.find( "Video Mode" );
  301. if (it->second.currentValue.empty())
  302. {
  303. it->second.currentValue = "800 x 600 @ 32-bit colour";
  304. viewModeChanged = true;
  305. }
  306. }
  307. if( name == "FSAA" )
  308. {
  309. std::vector<CamelotEngine::String> values = StringUtil::split(value, " ", 1);
  310. mFSAASamples = parseUnsignedInt(values[0]);
  311. if (values.size() > 1)
  312. mFSAAHint = values[1];
  313. }
  314. if( name == "VSync" )
  315. {
  316. if (value == "Yes")
  317. mVSync = true;
  318. else
  319. mVSync = false;
  320. }
  321. if( name == "VSync Interval" )
  322. {
  323. mVSyncInterval = parseUnsignedInt(value);
  324. }
  325. if( name == "Allow NVPerfHUD" )
  326. {
  327. if (value == "Yes")
  328. mUseNVPerfHUD = true;
  329. else
  330. mUseNVPerfHUD = false;
  331. }
  332. if (viewModeChanged || name == "Video Mode")
  333. {
  334. refreshFSAAOptions();
  335. }
  336. if (name == "Resource Creation Policy")
  337. {
  338. if (value == "Create on active device")
  339. mResourceManager->setCreationPolicy(RCP_CREATE_ON_ACTIVE_DEVICE);
  340. else if (value == "Create on all devices")
  341. mResourceManager->setCreationPolicy(RCP_CREATE_ON_ALL_DEVICES);
  342. }
  343. }
  344. //---------------------------------------------------------------------
  345. void D3D9RenderSystem::refreshFSAAOptions()
  346. {
  347. ConfigOptionMap::iterator it = mOptions.find( "FSAA" );
  348. ConfigOption* optFSAA = &it->second;
  349. optFSAA->possibleValues.clear();
  350. optFSAA->possibleValues.push_back("0");
  351. it = mOptions.find("Rendering Device");
  352. D3D9Driver *driver = getDirect3DDrivers()->item(it->second.currentValue);
  353. if (driver)
  354. {
  355. it = mOptions.find("Video Mode");
  356. D3D9VideoMode *videoMode = driver->getVideoModeList()->item(it->second.currentValue);
  357. if (videoMode)
  358. {
  359. DWORD numLevels = 0;
  360. bool bOK;
  361. for (unsigned int n = 2; n < 25; n++)
  362. {
  363. bOK = this->_checkMultiSampleQuality(
  364. (D3DMULTISAMPLE_TYPE)n,
  365. &numLevels,
  366. videoMode->getFormat(),
  367. driver->getAdapterNumber(),
  368. D3DDEVTYPE_HAL,
  369. TRUE);
  370. if (bOK)
  371. {
  372. optFSAA->possibleValues.push_back(toString(n));
  373. if (n >= 8)
  374. optFSAA->possibleValues.push_back(toString(n) + " [Quality]");
  375. }
  376. }
  377. }
  378. }
  379. // Reset FSAA to none if previous doesn't avail in new possible values
  380. std::vector<CamelotEngine::String>::const_iterator itValue =
  381. std::find(optFSAA->possibleValues.begin(),
  382. optFSAA->possibleValues.end(),
  383. optFSAA->currentValue);
  384. if (itValue == optFSAA->possibleValues.end())
  385. {
  386. optFSAA->currentValue = "0";
  387. }
  388. }
  389. //---------------------------------------------------------------------
  390. String D3D9RenderSystem::validateConfigOptions()
  391. {
  392. ConfigOptionMap::iterator it;
  393. // check if video mode is selected
  394. it = mOptions.find( "Video Mode" );
  395. if (it->second.currentValue.empty())
  396. return "A video mode must be selected.";
  397. it = mOptions.find( "Rendering Device" );
  398. bool foundDriver = false;
  399. D3D9DriverList* driverList = getDirect3DDrivers();
  400. for( UINT16 j=0; j < driverList->count(); j++ )
  401. {
  402. if( driverList->item(j)->DriverDescription() == it->second.currentValue )
  403. {
  404. foundDriver = true;
  405. break;
  406. }
  407. }
  408. if (!foundDriver)
  409. {
  410. // Just pick the first driver
  411. setConfigOption("Rendering Device", driverList->item(0)->DriverDescription());
  412. return "Your DirectX driver name has changed since the last time you ran OGRE; "
  413. "the 'Rendering Device' has been changed.";
  414. }
  415. it = mOptions.find( "VSync" );
  416. if( it->second.currentValue == "Yes" )
  417. mVSync = true;
  418. else
  419. mVSync = false;
  420. return StringUtil::BLANK;
  421. }
  422. //---------------------------------------------------------------------
  423. RenderWindow* D3D9RenderSystem::_initialise( bool autoCreateWindow, const String& windowTitle )
  424. {
  425. RenderWindow* autoWindow = NULL;
  426. // Init using current settings
  427. mActiveD3DDriver = NULL;
  428. ConfigOptionMap::iterator opt = mOptions.find( "Rendering Device" );
  429. for( UINT32 j=0; j < getDirect3DDrivers()->count(); j++ )
  430. {
  431. if( getDirect3DDrivers()->item(j)->DriverDescription() == opt->second.currentValue )
  432. {
  433. mActiveD3DDriver = getDirect3DDrivers()->item(j);
  434. break;
  435. }
  436. }
  437. if( !mActiveD3DDriver )
  438. CM_EXCEPT(InvalidParametersException, "Problems finding requested Direct3D driver!" );
  439. // get driver version
  440. mDriverVersion.major = HIWORD(mActiveD3DDriver->getAdapterIdentifier().DriverVersion.HighPart);
  441. mDriverVersion.minor = LOWORD(mActiveD3DDriver->getAdapterIdentifier().DriverVersion.HighPart);
  442. mDriverVersion.release = HIWORD(mActiveD3DDriver->getAdapterIdentifier().DriverVersion.LowPart);
  443. mDriverVersion.build = LOWORD(mActiveD3DDriver->getAdapterIdentifier().DriverVersion.LowPart);
  444. // Create the device manager.
  445. mDeviceManager = new D3D9DeviceManager();
  446. // Create the texture manager for use by others
  447. TextureManager::startUp(new D3D9TextureManager());
  448. // Also create hardware buffer manager
  449. HardwareBufferManager::startUp(new D3D9HardwareBufferManager());
  450. // Create the GPU program manager
  451. GpuProgramManager::startUp(new D3D9GpuProgramManager());
  452. // Create & register HLSL factory
  453. mHLSLProgramFactory = new D3D9HLSLProgramFactory();
  454. // Create & register Cg factory
  455. mCgProgramFactory = new CgProgramFactory();
  456. if( autoCreateWindow )
  457. {
  458. bool fullScreen;
  459. opt = mOptions.find( "Full Screen" );
  460. if( opt == mOptions.end() )
  461. CM_EXCEPT(InternalErrorException, "Can't find full screen option!");
  462. fullScreen = opt->second.currentValue == "Yes";
  463. D3D9VideoMode* videoMode = NULL;
  464. unsigned int width, height;
  465. String temp;
  466. opt = mOptions.find( "Video Mode" );
  467. if( opt == mOptions.end() )
  468. CM_EXCEPT(InternalErrorException, "Can't find Video Mode option!");
  469. // The string we are manipulating looks like this :width x height @ colourDepth
  470. // Pull out the colour depth by getting what comes after the @ and a space
  471. String colourDepth = opt->second.currentValue.substr(opt->second.currentValue.rfind('@')+1);
  472. // Now we know that the width starts a 0, so if we can find the end we can parse that out
  473. String::size_type widthEnd = opt->second.currentValue.find(' ');
  474. // we know that the height starts 3 characters after the width and goes until the next space
  475. String::size_type heightEnd = opt->second.currentValue.find(' ', widthEnd+3);
  476. // Now we can parse out the values
  477. width = parseInt(opt->second.currentValue.substr(0, widthEnd));
  478. height = parseInt(opt->second.currentValue.substr(widthEnd+3, heightEnd));
  479. for( unsigned j=0; j < mActiveD3DDriver->getVideoModeList()->count(); j++ )
  480. {
  481. temp = mActiveD3DDriver->getVideoModeList()->item(j)->getDescription();
  482. // In full screen we only want to allow supported resolutions, so temp and opt->second.currentValue need to
  483. // match exactly, but in windowed mode we can allow for arbitrary window sized, so we only need
  484. // to match the colour values
  485. if(fullScreen && (temp == opt->second.currentValue) ||
  486. !fullScreen && (temp.substr(temp.rfind('@')+1) == colourDepth))
  487. {
  488. videoMode = mActiveD3DDriver->getVideoModeList()->item(j);
  489. break;
  490. }
  491. }
  492. if( !videoMode )
  493. CM_EXCEPT(InternalErrorException, "Can't find requested video mode.");
  494. // sRGB window option
  495. bool hwGamma = false;
  496. opt = mOptions.find( "sRGB Gamma Conversion" );
  497. if( opt == mOptions.end() )
  498. CM_EXCEPT(InternalErrorException, "Can't find sRGB option!");
  499. hwGamma = opt->second.currentValue == "Yes";
  500. NameValuePairList miscParams;
  501. miscParams["colourDepth"] = toString(videoMode->getColourDepth());
  502. miscParams["FSAA"] = toString(mFSAASamples);
  503. miscParams["FSAAHint"] = mFSAAHint;
  504. miscParams["vsync"] = toString(mVSync);
  505. miscParams["vsyncInterval"] = toString(mVSyncInterval);
  506. miscParams["useNVPerfHUD"] = toString(mUseNVPerfHUD);
  507. miscParams["gamma"] = toString(hwGamma);
  508. miscParams["monitorIndex"] = toString(static_cast<int>(mActiveD3DDriver->getAdapterNumber()));
  509. autoWindow = _createRenderWindow( windowTitle, width, height,
  510. fullScreen, &miscParams );
  511. // If we have 16bit depth buffer enable w-buffering.
  512. assert( autoWindow );
  513. if ( autoWindow->getColourDepth() == 16 )
  514. {
  515. mWBuffer = true;
  516. }
  517. else
  518. {
  519. mWBuffer = false;
  520. }
  521. }
  522. // call superclass method
  523. RenderSystem::_initialise( autoCreateWindow );
  524. return autoWindow;
  525. }
  526. //---------------------------------------------------------------------
  527. void D3D9RenderSystem::reinitialise()
  528. {
  529. this->shutdown();
  530. this->_initialise( true );
  531. }
  532. //---------------------------------------------------------------------
  533. void D3D9RenderSystem::shutdown()
  534. {
  535. RenderSystem::shutdown();
  536. SAFE_DELETE( mDeviceManager );
  537. SAFE_DELETE( mDriverList );
  538. mActiveD3DDriver = NULL;
  539. TextureManager::shutDown();
  540. HardwareBufferManager::shutDown();
  541. GpuProgramManager::shutDown();
  542. }
  543. //---------------------------------------------------------------------
  544. RenderWindow* D3D9RenderSystem::_createRenderWindow(const String &name,
  545. unsigned int width, unsigned int height, bool fullScreen,
  546. const NameValuePairList *miscParams)
  547. {
  548. // Log a message
  549. StringStream ss;
  550. ss << "D3D9RenderSystem::_createRenderWindow \"" << name << "\", " <<
  551. width << "x" << height << " ";
  552. if(fullScreen)
  553. ss << "fullscreen ";
  554. else
  555. ss << "windowed ";
  556. if(miscParams)
  557. {
  558. ss << " miscParams: ";
  559. NameValuePairList::const_iterator it;
  560. for(it=miscParams->begin(); it!=miscParams->end(); ++it)
  561. {
  562. ss << it->first << "=" << it->second << " ";
  563. }
  564. }
  565. String msg;
  566. // Make sure we don't already have a render target of the
  567. // same name as the one supplied
  568. if( mRenderTargets.find( name ) != mRenderTargets.end() )
  569. {
  570. msg = "A render target of the same name '" + name + "' already "
  571. "exists. You cannot create a new window with this name.";
  572. CM_EXCEPT(InternalErrorException, msg);
  573. }
  574. D3D9RenderWindow* renderWindow = new D3D9RenderWindow(mhInstance);
  575. renderWindow->create(name, width, height, fullScreen, miscParams);
  576. mResourceManager->lockDeviceAccess();
  577. try
  578. {
  579. mDeviceManager->linkRenderWindow(renderWindow);
  580. }
  581. catch (const CamelotEngine::RenderingAPIException&)
  582. {
  583. // after catching the exception, clean up
  584. mResourceManager->unlockDeviceAccess();
  585. renderWindow->destroy();
  586. // re-throw
  587. throw;
  588. }
  589. mResourceManager->unlockDeviceAccess();
  590. mRenderWindows.push_back(renderWindow);
  591. updateRenderSystemCapabilities(renderWindow);
  592. attachRenderTarget( *renderWindow );
  593. return renderWindow;
  594. }
  595. //---------------------------------------------------------------------
  596. bool D3D9RenderSystem::_createRenderWindows(const RenderWindowDescriptionList& renderWindowDescriptions,
  597. RenderWindowList& createdWindows)
  598. {
  599. // Call base render system method.
  600. if (false == RenderSystem::_createRenderWindows(renderWindowDescriptions, createdWindows))
  601. return false;
  602. // Simply call _createRenderWindow in a loop.
  603. for (size_t i = 0; i < renderWindowDescriptions.size(); ++i)
  604. {
  605. const RenderWindowDescription& curRenderWindowDescription = renderWindowDescriptions[i];
  606. RenderWindow* curWindow = NULL;
  607. curWindow = _createRenderWindow(curRenderWindowDescription.name,
  608. curRenderWindowDescription.width,
  609. curRenderWindowDescription.height,
  610. curRenderWindowDescription.useFullScreen,
  611. &curRenderWindowDescription.miscParams);
  612. createdWindows.push_back(curWindow);
  613. }
  614. return true;
  615. }
  616. //---------------------------------------------------------------------
  617. RenderSystemCapabilities* D3D9RenderSystem::updateRenderSystemCapabilities(D3D9RenderWindow* renderWindow)
  618. {
  619. RenderSystemCapabilities* rsc = mRealCapabilities;
  620. if (rsc == NULL)
  621. rsc = new RenderSystemCapabilities();
  622. rsc->setCategoryRelevant(CAPS_CATEGORY_D3D9, true);
  623. rsc->setDriverVersion(mDriverVersion);
  624. rsc->setDeviceName(mActiveD3DDriver->DriverDescription());
  625. rsc->setRenderSystemName(getName());
  626. // Supports fixed-function
  627. rsc->setCapability(RSC_FIXED_FUNCTION);
  628. // Init caps to maximum.
  629. rsc->setNumTextureUnits(1024);
  630. rsc->setCapability(RSC_ANISOTROPY);
  631. rsc->setCapability(RSC_AUTOMIPMAP);
  632. rsc->setCapability(RSC_DOT3);
  633. rsc->setCapability(RSC_CUBEMAPPING);
  634. rsc->setCapability(RSC_SCISSOR_TEST);
  635. rsc->setCapability(RSC_TWO_SIDED_STENCIL);
  636. rsc->setCapability(RSC_STENCIL_WRAP);
  637. rsc->setCapability(RSC_HWOCCLUSION);
  638. rsc->setCapability(RSC_USER_CLIP_PLANES);
  639. rsc->setCapability(RSC_VERTEX_FORMAT_UBYTE4);
  640. rsc->setCapability(RSC_TEXTURE_3D);
  641. rsc->setCapability(RSC_NON_POWER_OF_2_TEXTURES);
  642. rsc->setNonPOW2TexturesLimited(false);
  643. rsc->setNumMultiRenderTargets(CM_MAX_MULTIPLE_RENDER_TARGETS);
  644. rsc->setCapability(RSC_MRT_DIFFERENT_BIT_DEPTHS);
  645. rsc->setCapability(RSC_POINT_SPRITES);
  646. rsc->setCapability(RSC_POINT_EXTENDED_PARAMETERS);
  647. rsc->setMaxPointSize(10.0);
  648. rsc->setCapability(RSC_MIPMAP_LOD_BIAS);
  649. rsc->setCapability(RSC_PERSTAGECONSTANT);
  650. rsc->setCapability(RSC_HWSTENCIL);
  651. rsc->setStencilBufferBitDepth(8);
  652. rsc->setCapability(RSC_ADVANCED_BLEND_OPERATIONS);
  653. for (UINT32 i=0; i < mDeviceManager->getDeviceCount(); ++i)
  654. {
  655. D3D9Device* device = mDeviceManager->getDevice(i);
  656. IDirect3DDevice9* d3d9Device = device->getD3D9Device();
  657. IDirect3DSurface9* pSurf;
  658. // Check for hardware stencil support
  659. d3d9Device->GetDepthStencilSurface(&pSurf);
  660. if (pSurf != NULL)
  661. {
  662. D3DSURFACE_DESC surfDesc;
  663. pSurf->GetDesc(&surfDesc);
  664. pSurf->Release();
  665. if (surfDesc.Format != D3DFMT_D15S1 &&
  666. surfDesc.Format != D3DFMT_D24S8 &&
  667. surfDesc.Format != D3DFMT_D24X4S4 &&
  668. surfDesc.Format != D3DFMT_D24FS8)
  669. rsc->unsetCapability(RSC_HWSTENCIL);
  670. }
  671. // Check for hardware occlusion support
  672. HRESULT hr = d3d9Device->CreateQuery(D3DQUERYTYPE_OCCLUSION, NULL);
  673. if (FAILED(hr))
  674. rsc->unsetCapability(RSC_HWOCCLUSION);
  675. }
  676. // Update RS caps using the minimum value found in adapter list.
  677. for (unsigned int i=0; i < mDriverList->count(); ++i)
  678. {
  679. D3D9Driver* pCurDriver = mDriverList->item(i);
  680. const D3DCAPS9& rkCurCaps = pCurDriver->getD3D9DeviceCaps();
  681. if (rkCurCaps.MaxSimultaneousTextures < rsc->getNumTextureUnits())
  682. {
  683. rsc->setNumTextureUnits(static_cast<UINT16>(rkCurCaps.MaxSimultaneousTextures));
  684. }
  685. // Check for Anisotropy.
  686. if (rkCurCaps.MaxAnisotropy <= 1)
  687. rsc->unsetCapability(RSC_ANISOTROPY);
  688. // Check automatic mipmap generation.
  689. if ((rkCurCaps.Caps2 & D3DCAPS2_CANAUTOGENMIPMAP) == 0)
  690. rsc->unsetCapability(RSC_AUTOMIPMAP);
  691. // Check Dot product 3.
  692. if ((rkCurCaps.TextureOpCaps & D3DTEXOPCAPS_DOTPRODUCT3) == 0)
  693. rsc->unsetCapability(RSC_DOT3);
  694. // Scissor test
  695. if ((rkCurCaps.RasterCaps & D3DPRASTERCAPS_SCISSORTEST) == 0)
  696. rsc->unsetCapability(RSC_SCISSOR_TEST);
  697. // Two-sided stencil
  698. if ((rkCurCaps.StencilCaps & D3DSTENCILCAPS_TWOSIDED) == 0)
  699. rsc->unsetCapability(RSC_TWO_SIDED_STENCIL);
  700. // stencil wrap
  701. if ((rkCurCaps.StencilCaps & D3DSTENCILCAPS_INCR) == 0 ||
  702. (rkCurCaps.StencilCaps & D3DSTENCILCAPS_DECR) == 0)
  703. rsc->unsetCapability(RSC_STENCIL_WRAP);
  704. // User clip planes
  705. if (rkCurCaps.MaxUserClipPlanes == 0)
  706. rsc->unsetCapability(RSC_USER_CLIP_PLANES);
  707. // UBYTE4 type?
  708. if ((rkCurCaps.DeclTypes & D3DDTCAPS_UBYTE4) == 0)
  709. rsc->unsetCapability(RSC_VERTEX_FORMAT_UBYTE4);
  710. // Check cube map support.
  711. if ((rkCurCaps.TextureCaps & D3DPTEXTURECAPS_CUBEMAP) == 0)
  712. rsc->unsetCapability(RSC_CUBEMAPPING);
  713. // 3D textures?
  714. if ((rkCurCaps.TextureCaps & D3DPTEXTURECAPS_VOLUMEMAP) == 0)
  715. rsc->unsetCapability(RSC_TEXTURE_3D);
  716. if (rkCurCaps.TextureCaps & D3DPTEXTURECAPS_POW2)
  717. {
  718. // Conditional support for non POW2
  719. if (rkCurCaps.TextureCaps & D3DPTEXTURECAPS_NONPOW2CONDITIONAL)
  720. rsc->setNonPOW2TexturesLimited(true);
  721. // Only power of 2 supported.
  722. else
  723. rsc->unsetCapability(RSC_NON_POWER_OF_2_TEXTURES);
  724. }
  725. // Number of render targets
  726. if (rkCurCaps.NumSimultaneousRTs < rsc->getNumMultiRenderTargets())
  727. {
  728. rsc->setNumMultiRenderTargets(std::min((UINT16)rkCurCaps.NumSimultaneousRTs, (UINT16)CM_MAX_MULTIPLE_RENDER_TARGETS));
  729. }
  730. if((rkCurCaps.PrimitiveMiscCaps & D3DPMISCCAPS_MRTINDEPENDENTBITDEPTHS) == 0)
  731. {
  732. rsc->unsetCapability(RSC_MRT_DIFFERENT_BIT_DEPTHS);
  733. }
  734. // Point sprites
  735. if (rkCurCaps.MaxPointSize <= 1.0f)
  736. {
  737. rsc->unsetCapability(RSC_POINT_SPRITES);
  738. // sprites and extended parameters go together in D3D
  739. rsc->unsetCapability(RSC_POINT_EXTENDED_PARAMETERS);
  740. }
  741. // Take the minimum point size.
  742. if (rkCurCaps.MaxPointSize < rsc->getMaxPointSize())
  743. rsc->setMaxPointSize(rkCurCaps.MaxPointSize);
  744. // Mipmap LOD biasing?
  745. if ((rkCurCaps.RasterCaps & D3DPRASTERCAPS_MIPMAPLODBIAS) == 0)
  746. rsc->unsetCapability(RSC_MIPMAP_LOD_BIAS);
  747. // Do we support per-stage src_manual constants?
  748. // HACK - ATI drivers seem to be buggy and don't support per-stage constants properly?
  749. // TODO: move this to RSC
  750. if((rkCurCaps.PrimitiveMiscCaps & D3DPMISCCAPS_PERSTAGECONSTANT) == 0)
  751. rsc->unsetCapability(RSC_PERSTAGECONSTANT);
  752. // Advanced blend operations? min max subtract rev
  753. if((rkCurCaps.PrimitiveMiscCaps & D3DPMISCCAPS_BLENDOP) == 0)
  754. rsc->unsetCapability(RSC_ADVANCED_BLEND_OPERATIONS);
  755. }
  756. // Blending between stages supported
  757. rsc->setCapability(RSC_BLENDING);
  758. // We always support compression, D3DX will decompress if device does not support
  759. rsc->setCapability(RSC_TEXTURE_COMPRESSION);
  760. rsc->setCapability(RSC_TEXTURE_COMPRESSION_DXT);
  761. // We always support VBOs
  762. rsc->setCapability(RSC_VBO);
  763. convertVertexShaderCaps(rsc);
  764. convertPixelShaderCaps(rsc);
  765. // Adapter details
  766. const D3DADAPTER_IDENTIFIER9& adapterID = mActiveD3DDriver->getAdapterIdentifier();
  767. // determine vendor
  768. // Full list of vendors here: http://www.pcidatabase.com/vendors.php?sort=id
  769. switch(adapterID.VendorId)
  770. {
  771. case 0x10DE:
  772. rsc->setVendor(GPU_NVIDIA);
  773. break;
  774. case 0x1002:
  775. rsc->setVendor(GPU_ATI);
  776. break;
  777. case 0x163C:
  778. case 0x8086:
  779. rsc->setVendor(GPU_INTEL);
  780. break;
  781. case 0x5333:
  782. rsc->setVendor(GPU_S3);
  783. break;
  784. case 0x3D3D:
  785. rsc->setVendor(GPU_3DLABS);
  786. break;
  787. case 0x102B:
  788. rsc->setVendor(GPU_MATROX);
  789. break;
  790. case 0x1039:
  791. rsc->setVendor(GPU_SIS);
  792. break;
  793. default:
  794. rsc->setVendor(GPU_UNKNOWN);
  795. break;
  796. };
  797. // Infinite projection?
  798. // We have no capability for this, so we have to base this on our
  799. // experience and reports from users
  800. // Non-vertex program capable hardware does not appear to support it
  801. if (rsc->hasCapability(RSC_VERTEX_PROGRAM))
  802. {
  803. // GeForce4 Ti (and presumably GeForce3) does not
  804. // render infinite projection properly, even though it does in GL
  805. // So exclude all cards prior to the FX range from doing infinite
  806. if (rsc->getVendor() != GPU_NVIDIA || // not nVidia
  807. !((adapterID.DeviceId >= 0x200 && adapterID.DeviceId <= 0x20F) || //gf3
  808. (adapterID.DeviceId >= 0x250 && adapterID.DeviceId <= 0x25F) || //gf4ti
  809. (adapterID.DeviceId >= 0x280 && adapterID.DeviceId <= 0x28F) || //gf4ti
  810. (adapterID.DeviceId >= 0x170 && adapterID.DeviceId <= 0x18F) || //gf4 go
  811. (adapterID.DeviceId >= 0x280 && adapterID.DeviceId <= 0x28F))) //gf4ti go
  812. {
  813. rsc->setCapability(RSC_INFINITE_FAR_PLANE);
  814. }
  815. }
  816. // We always support rendertextures bigger than the frame buffer
  817. rsc->setCapability(RSC_HWRENDER_TO_TEXTURE);
  818. // Determine if any floating point texture format is supported
  819. D3DFORMAT floatFormats[6] = {D3DFMT_R16F, D3DFMT_G16R16F,
  820. D3DFMT_A16B16G16R16F, D3DFMT_R32F, D3DFMT_G32R32F,
  821. D3DFMT_A32B32G32R32F};
  822. IDirect3DSurface9* bbSurf;
  823. renderWindow->getCustomAttribute("DDBACKBUFFER", &bbSurf);
  824. D3DSURFACE_DESC bbSurfDesc;
  825. bbSurf->GetDesc(&bbSurfDesc);
  826. for (int i = 0; i < 6; ++i)
  827. {
  828. if (SUCCEEDED(mpD3D->CheckDeviceFormat(mActiveD3DDriver->getAdapterNumber(),
  829. D3DDEVTYPE_HAL, bbSurfDesc.Format,
  830. 0, D3DRTYPE_TEXTURE, floatFormats[i])))
  831. {
  832. rsc->setCapability(RSC_TEXTURE_FLOAT);
  833. break;
  834. }
  835. }
  836. // TODO: make convertVertex/Fragment fill in rsc
  837. // TODO: update the below line to use rsc
  838. // Vertex textures
  839. if (rsc->isShaderProfileSupported("vs_3_0"))
  840. {
  841. // Run through all the texture formats looking for any which support
  842. // vertex texture fetching. Must have at least one!
  843. // All ATI Radeon up to X1n00 say they support vs_3_0,
  844. // but they support no texture formats for vertex texture fetch (cheaters!)
  845. if (checkVertexTextureFormats(renderWindow))
  846. {
  847. rsc->setCapability(RSC_VERTEX_TEXTURE_FETCH);
  848. // always 4 vertex texture units in vs_3_0, and never shared
  849. rsc->setNumVertexTextureUnits(4);
  850. rsc->setVertexTextureUnitsShared(false);
  851. }
  852. }
  853. // Check alpha to coverage support
  854. // this varies per vendor! But at least SM3 is required
  855. if (rsc->isShaderProfileSupported("ps_3_0"))
  856. {
  857. // NVIDIA needs a separate check
  858. if (rsc->getVendor() == GPU_NVIDIA)
  859. {
  860. if (mpD3D->CheckDeviceFormat(
  861. D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, D3DFMT_X8R8G8B8, 0,D3DRTYPE_SURFACE,
  862. (D3DFORMAT)MAKEFOURCC('A', 'T', 'O', 'C')) == S_OK)
  863. {
  864. rsc->setCapability(RSC_ALPHA_TO_COVERAGE);
  865. }
  866. }
  867. else if (rsc->getVendor() == GPU_ATI)
  868. {
  869. // There is no check on ATI, we have to assume SM3 == support
  870. rsc->setCapability(RSC_ALPHA_TO_COVERAGE);
  871. }
  872. // no other cards have Dx9 hacks for alpha to coverage, as far as I know
  873. }
  874. if (mRealCapabilities == NULL)
  875. {
  876. mRealCapabilities = rsc;
  877. mRealCapabilities->addShaderProfile("hlsl");
  878. mRealCapabilities->addShaderProfile("cg");
  879. // if we are using custom capabilities, then
  880. // mCurrentCapabilities has already been loaded
  881. if(!mUseCustomCapabilities)
  882. mCurrentCapabilities = mRealCapabilities;
  883. initialiseFromRenderSystemCapabilities(mCurrentCapabilities, renderWindow);
  884. }
  885. return rsc;
  886. }
  887. //---------------------------------------------------------------------
  888. void D3D9RenderSystem::convertVertexShaderCaps(RenderSystemCapabilities* rsc) const
  889. {
  890. UINT16 major = 0xFF;
  891. UINT16 minor = 0xFF;
  892. D3DCAPS9 minVSCaps;
  893. // Find the device with the lowest vertex shader caps.
  894. for (unsigned int i=0; i < mDriverList->count(); ++i)
  895. {
  896. D3D9Driver* pCurDriver = mDriverList->item(i);
  897. const D3DCAPS9& rkCurCaps = pCurDriver->getD3D9DeviceCaps();
  898. UINT16 currMajor = static_cast<UINT16>((rkCurCaps.VertexShaderVersion & 0x0000FF00) >> 8);
  899. UINT16 currMinor = static_cast<UINT16>(rkCurCaps.VertexShaderVersion & 0x000000FF);
  900. if (currMajor < major)
  901. {
  902. major = currMajor;
  903. minor = currMinor;
  904. minVSCaps = rkCurCaps;
  905. }
  906. else if (currMajor == major && currMinor < minor)
  907. {
  908. minor = currMinor;
  909. minVSCaps = rkCurCaps;
  910. }
  911. }
  912. // In case we didn't found any vertex shader support
  913. // try the IDirect3DDevice9 caps instead of the IDirect3D9
  914. // software vertex processing is reported there
  915. if (major == 0 && minor == 0)
  916. {
  917. IDirect3DDevice9* lpD3DDevice9 = getActiveD3D9Device();
  918. D3DCAPS9 d3dDeviceCaps9;
  919. lpD3DDevice9->GetDeviceCaps(&d3dDeviceCaps9);
  920. major = static_cast<UINT16>((d3dDeviceCaps9.VertexShaderVersion & 0x0000FF00) >> 8);
  921. minor = static_cast<UINT16>(d3dDeviceCaps9.VertexShaderVersion & 0x000000FF);
  922. }
  923. bool vs2x = false;
  924. bool vs2a = false;
  925. // Special case detection for vs_2_x/a support
  926. if (major >= 2)
  927. {
  928. if ((minVSCaps.VS20Caps.Caps & D3DVS20CAPS_PREDICATION) &&
  929. (minVSCaps.VS20Caps.DynamicFlowControlDepth > 0) &&
  930. (minVSCaps.VS20Caps.NumTemps >= 12))
  931. {
  932. vs2x = true;
  933. }
  934. if ((minVSCaps.VS20Caps.Caps & D3DVS20CAPS_PREDICATION) &&
  935. (minVSCaps.VS20Caps.DynamicFlowControlDepth > 0) &&
  936. (minVSCaps.VS20Caps.NumTemps >= 13))
  937. {
  938. vs2a = true;
  939. }
  940. }
  941. // Populate max param count
  942. switch (major)
  943. {
  944. case 1:
  945. // No boolean params allowed
  946. rsc->setVertexProgramConstantBoolCount(0);
  947. // No integer params allowed
  948. rsc->setVertexProgramConstantIntCount(0);
  949. // float params, always 4D
  950. rsc->setVertexProgramConstantFloatCount(static_cast<UINT16>(minVSCaps.MaxVertexShaderConst));
  951. break;
  952. case 2:
  953. // 16 boolean params allowed
  954. rsc->setVertexProgramConstantBoolCount(16);
  955. // 16 integer params allowed, 4D
  956. rsc->setVertexProgramConstantIntCount(16);
  957. // float params, always 4D
  958. rsc->setVertexProgramConstantFloatCount(static_cast<UINT16>(minVSCaps.MaxVertexShaderConst));
  959. break;
  960. case 3:
  961. // 16 boolean params allowed
  962. rsc->setVertexProgramConstantBoolCount(16);
  963. // 16 integer params allowed, 4D
  964. rsc->setVertexProgramConstantIntCount(16);
  965. // float params, always 4D
  966. rsc->setVertexProgramConstantFloatCount(static_cast<UINT16>(minVSCaps.MaxVertexShaderConst));
  967. break;
  968. }
  969. // populate syntax codes in program manager (no breaks in this one so it falls through)
  970. switch(major)
  971. {
  972. case 3:
  973. rsc->addShaderProfile("vs_3_0");
  974. rsc->addGpuProgramProfile(GPP_VS_3_0, "vs_3_0");
  975. case 2:
  976. if (vs2x)
  977. {
  978. rsc->addShaderProfile("vs_2_x");
  979. rsc->addGpuProgramProfile(GPP_VS_2_x, "vs_2_x");
  980. }
  981. if (vs2a)
  982. {
  983. rsc->addShaderProfile("vs_2_a");
  984. rsc->addGpuProgramProfile(GPP_VS_2_a, "vs_2_a");
  985. }
  986. rsc->addShaderProfile("vs_2_0");
  987. rsc->addGpuProgramProfile(GPP_VS_2_0, "vs_2_0");
  988. case 1:
  989. rsc->addShaderProfile("vs_1_1");
  990. rsc->addGpuProgramProfile(GPP_VS_1_1, "vs_1_1");
  991. rsc->setCapability(RSC_VERTEX_PROGRAM);
  992. }
  993. }
  994. //---------------------------------------------------------------------
  995. void D3D9RenderSystem::convertPixelShaderCaps(RenderSystemCapabilities* rsc) const
  996. {
  997. UINT16 major = 0xFF;
  998. UINT16 minor = 0xFF;
  999. D3DCAPS9 minPSCaps;
  1000. // Find the device with the lowest pixel shader caps.
  1001. for (unsigned int i=0; i < mDriverList->count(); ++i)
  1002. {
  1003. D3D9Driver* pCurDriver = mDriverList->item(i);
  1004. const D3DCAPS9& currCaps = pCurDriver->getD3D9DeviceCaps();
  1005. UINT16 currMajor = static_cast<UINT16>((currCaps.PixelShaderVersion & 0x0000FF00) >> 8);
  1006. UINT16 currMinor = static_cast<UINT16>(currCaps.PixelShaderVersion & 0x000000FF);
  1007. if (currMajor < major)
  1008. {
  1009. major = currMajor;
  1010. minor = currMinor;
  1011. minPSCaps = currCaps;
  1012. }
  1013. else if (currMajor == major && currMinor < minor)
  1014. {
  1015. minor = currMinor;
  1016. minPSCaps = currCaps;
  1017. }
  1018. }
  1019. bool ps2a = false;
  1020. bool ps2b = false;
  1021. bool ps2x = false;
  1022. // Special case detection for ps_2_x/a/b support
  1023. if (major >= 2)
  1024. {
  1025. if ((minPSCaps.PS20Caps.Caps & D3DPS20CAPS_NOTEXINSTRUCTIONLIMIT) &&
  1026. (minPSCaps.PS20Caps.NumTemps >= 32))
  1027. {
  1028. ps2b = true;
  1029. }
  1030. if ((minPSCaps.PS20Caps.Caps & D3DPS20CAPS_NOTEXINSTRUCTIONLIMIT) &&
  1031. (minPSCaps.PS20Caps.Caps & D3DPS20CAPS_NODEPENDENTREADLIMIT) &&
  1032. (minPSCaps.PS20Caps.Caps & D3DPS20CAPS_ARBITRARYSWIZZLE) &&
  1033. (minPSCaps.PS20Caps.Caps & D3DPS20CAPS_GRADIENTINSTRUCTIONS) &&
  1034. (minPSCaps.PS20Caps.Caps & D3DPS20CAPS_PREDICATION) &&
  1035. (minPSCaps.PS20Caps.NumTemps >= 22))
  1036. {
  1037. ps2a = true;
  1038. }
  1039. // Does this enough?
  1040. if (ps2a || ps2b)
  1041. {
  1042. ps2x = true;
  1043. }
  1044. }
  1045. switch (major)
  1046. {
  1047. case 1:
  1048. // no boolean params allowed
  1049. rsc->setFragmentProgramConstantBoolCount(0);
  1050. // no integer params allowed
  1051. rsc->setFragmentProgramConstantIntCount(0);
  1052. // float params, always 4D
  1053. // NB in ps_1_x these are actually stored as fixed point values,
  1054. // but they are entered as floats
  1055. rsc->setFragmentProgramConstantFloatCount(8);
  1056. break;
  1057. case 2:
  1058. // 16 boolean params allowed
  1059. rsc->setFragmentProgramConstantBoolCount(16);
  1060. // 16 integer params allowed, 4D
  1061. rsc->setFragmentProgramConstantIntCount(16);
  1062. // float params, always 4D
  1063. rsc->setFragmentProgramConstantFloatCount(32);
  1064. break;
  1065. case 3:
  1066. // 16 boolean params allowed
  1067. rsc->setFragmentProgramConstantBoolCount(16);
  1068. // 16 integer params allowed, 4D
  1069. rsc->setFragmentProgramConstantIntCount(16);
  1070. // float params, always 4D
  1071. rsc->setFragmentProgramConstantFloatCount(224);
  1072. break;
  1073. }
  1074. // populate syntax codes in program manager (no breaks in this one so it falls through)
  1075. switch(major)
  1076. {
  1077. case 3:
  1078. if (minor > 0)
  1079. {
  1080. rsc->addShaderProfile("ps_3_x");
  1081. rsc->addGpuProgramProfile(GPP_PS_3_x, "ps_3_x");
  1082. }
  1083. rsc->addShaderProfile("ps_3_0");
  1084. rsc->addGpuProgramProfile(GPP_PS_3_0, "ps_3_0");
  1085. case 2:
  1086. if (ps2x)
  1087. {
  1088. rsc->addShaderProfile("ps_2_x");
  1089. rsc->addGpuProgramProfile(GPP_PS_2_x, "ps_2_x");
  1090. }
  1091. if (ps2a)
  1092. {
  1093. rsc->addShaderProfile("ps_2_a");
  1094. rsc->addGpuProgramProfile(GPP_PS_2_a, "ps_2_a");
  1095. }
  1096. if (ps2b)
  1097. {
  1098. rsc->addShaderProfile("ps_2_b");
  1099. rsc->addGpuProgramProfile(GPP_PS_2_b, "ps_2_b");
  1100. }
  1101. rsc->addShaderProfile("ps_2_0");
  1102. rsc->addGpuProgramProfile(GPP_PS_2_0, "ps_2_0");
  1103. case 1:
  1104. if (major > 1 || minor >= 4)
  1105. {
  1106. rsc->addShaderProfile("ps_1_4");
  1107. rsc->addGpuProgramProfile(GPP_PS_1_4, "ps_1_4");
  1108. }
  1109. if (major > 1 || minor >= 3)
  1110. {
  1111. rsc->addShaderProfile("ps_1_3");
  1112. rsc->addGpuProgramProfile(GPP_PS_1_3, "ps_1_3");
  1113. }
  1114. if (major > 1 || minor >= 2)
  1115. {
  1116. rsc->addShaderProfile("ps_1_2");
  1117. rsc->addGpuProgramProfile(GPP_PS_1_2, "ps_1_2");
  1118. }
  1119. rsc->addShaderProfile("ps_1_1");
  1120. rsc->addGpuProgramProfile(GPP_PS_1_1, "ps_1_1");
  1121. rsc->setCapability(RSC_FRAGMENT_PROGRAM);
  1122. }
  1123. }
  1124. //-----------------------------------------------------------------------
  1125. bool D3D9RenderSystem::checkVertexTextureFormats(D3D9RenderWindow* renderWindow) const
  1126. {
  1127. bool anySupported = false;
  1128. IDirect3DSurface9* bbSurf;
  1129. renderWindow->getCustomAttribute("DDBACKBUFFER", &bbSurf);
  1130. D3DSURFACE_DESC bbSurfDesc;
  1131. bbSurf->GetDesc(&bbSurfDesc);
  1132. for (UINT32 ipf = static_cast<UINT32>(PF_L8); ipf < static_cast<UINT32>(PF_COUNT); ++ipf)
  1133. {
  1134. PixelFormat pf = (PixelFormat)ipf;
  1135. D3DFORMAT fmt =
  1136. D3D9Mappings::_getPF(D3D9Mappings::_getClosestSupportedPF(pf));
  1137. if (SUCCEEDED(mpD3D->CheckDeviceFormat(
  1138. mActiveD3DDriver->getAdapterNumber(), D3DDEVTYPE_HAL, bbSurfDesc.Format,
  1139. D3DUSAGE_QUERY_VERTEXTEXTURE, D3DRTYPE_TEXTURE, fmt)))
  1140. {
  1141. // cool, at least one supported
  1142. anySupported = true;
  1143. }
  1144. }
  1145. return anySupported;
  1146. }
  1147. //-----------------------------------------------------------------------
  1148. void D3D9RenderSystem::initialiseFromRenderSystemCapabilities(RenderSystemCapabilities* caps, RenderTarget* primary)
  1149. {
  1150. if (caps->getRenderSystemName() != getName())
  1151. {
  1152. CM_EXCEPT(InvalidParametersException,
  1153. "Trying to initialize D3D9RenderSystem from RenderSystemCapabilities that do not support Direct3D9");
  1154. }
  1155. if (caps->isShaderProfileSupported("hlsl"))
  1156. HighLevelGpuProgramManager::instance().addFactory(mHLSLProgramFactory);
  1157. if (caps->isShaderProfileSupported("cg"))
  1158. HighLevelGpuProgramManager::instance().addFactory(mCgProgramFactory);
  1159. }
  1160. //-----------------------------------------------------------------------
  1161. bool D3D9RenderSystem::_checkTextureFilteringSupported(TextureType ttype, PixelFormat format, int usage)
  1162. {
  1163. // Gets D3D format
  1164. D3DFORMAT d3dPF = D3D9Mappings::_getPF(format);
  1165. if (d3dPF == D3DFMT_UNKNOWN)
  1166. return false;
  1167. for (UINT32 i = 0; i < mDeviceManager->getDeviceCount(); ++i)
  1168. {
  1169. D3D9Device* currDevice = mDeviceManager->getDevice(i);
  1170. D3D9RenderWindow* currDevicePrimaryWindow = currDevice->getPrimaryWindow();
  1171. IDirect3DSurface9* pSurface = currDevicePrimaryWindow->getRenderSurface();
  1172. D3DSURFACE_DESC srfDesc;
  1173. // Get surface desc
  1174. if (FAILED(pSurface->GetDesc(&srfDesc)))
  1175. return false;
  1176. // Calculate usage
  1177. DWORD d3dusage = D3DUSAGE_QUERY_FILTER;
  1178. if (usage & TU_RENDERTARGET)
  1179. d3dusage |= D3DUSAGE_RENDERTARGET;
  1180. if (usage & TU_DYNAMIC)
  1181. d3dusage |= D3DUSAGE_DYNAMIC;
  1182. // Detect resource type
  1183. D3DRESOURCETYPE rtype;
  1184. switch(ttype)
  1185. {
  1186. case TEX_TYPE_1D:
  1187. case TEX_TYPE_2D:
  1188. rtype = D3DRTYPE_TEXTURE;
  1189. break;
  1190. case TEX_TYPE_3D:
  1191. rtype = D3DRTYPE_VOLUMETEXTURE;
  1192. break;
  1193. case TEX_TYPE_CUBE_MAP:
  1194. rtype = D3DRTYPE_CUBETEXTURE;
  1195. break;
  1196. default:
  1197. return false;
  1198. }
  1199. HRESULT hr = mpD3D->CheckDeviceFormat(
  1200. currDevice->getAdapterNumber(),
  1201. currDevice->getDeviceType(),
  1202. srfDesc.Format,
  1203. d3dusage,
  1204. rtype,
  1205. d3dPF);
  1206. if (FAILED(hr))
  1207. return false;
  1208. }
  1209. return true;
  1210. }
  1211. //-----------------------------------------------------------------------
  1212. MultiRenderTarget * D3D9RenderSystem::createMultiRenderTarget(const String & name)
  1213. {
  1214. MultiRenderTarget *retval;
  1215. retval = new D3D9MultiRenderTarget(name);
  1216. attachRenderTarget(*retval);
  1217. return retval;
  1218. }
  1219. //---------------------------------------------------------------------
  1220. void D3D9RenderSystem::destroyRenderTarget(const String& name)
  1221. {
  1222. D3D9RenderWindow* renderWindow = NULL;
  1223. // Check render windows
  1224. D3D9RenderWindowList::iterator sw;
  1225. for (sw = mRenderWindows.begin(); sw != mRenderWindows.end(); ++sw)
  1226. {
  1227. if ((*sw)->getName() == name)
  1228. {
  1229. renderWindow = (*sw);
  1230. mRenderWindows.erase(sw);
  1231. break;
  1232. }
  1233. }
  1234. // Do the real removal
  1235. RenderSystem::destroyRenderTarget(name);
  1236. }
  1237. //---------------------------------------------------------------------
  1238. String D3D9RenderSystem::getErrorDescription( long errorNumber ) const
  1239. {
  1240. const String errMsg = DXGetErrorDescription( errorNumber );
  1241. return errMsg;
  1242. }
  1243. //---------------------------------------------------------------------
  1244. VertexElementType D3D9RenderSystem::getColourVertexElementType() const
  1245. {
  1246. return VET_COLOUR_ARGB;
  1247. }
  1248. //---------------------------------------------------------------------
  1249. void D3D9RenderSystem::_convertProjectionMatrix(const Matrix4& matrix,
  1250. Matrix4& dest, bool forGpuProgram)
  1251. {
  1252. dest = matrix;
  1253. // Convert depth range from [-1,+1] to [0,1]
  1254. dest[2][0] = (dest[2][0] + dest[3][0]) / 2;
  1255. dest[2][1] = (dest[2][1] + dest[3][1]) / 2;
  1256. dest[2][2] = (dest[2][2] + dest[3][2]) / 2;
  1257. dest[2][3] = (dest[2][3] + dest[3][3]) / 2;
  1258. if (!forGpuProgram)
  1259. {
  1260. // Convert right-handed to left-handed
  1261. dest[0][2] = -dest[0][2];
  1262. dest[1][2] = -dest[1][2];
  1263. dest[2][2] = -dest[2][2];
  1264. dest[3][2] = -dest[3][2];
  1265. }
  1266. }
  1267. //---------------------------------------------------------------------
  1268. void D3D9RenderSystem::_makeProjectionMatrix(const Radian& fovy, float aspect, float nearPlane,
  1269. float farPlane, Matrix4& dest, bool forGpuProgram)
  1270. {
  1271. Radian theta ( fovy * 0.5 );
  1272. float h = 1 / Math::Tan(theta);
  1273. float w = h / aspect;
  1274. float q, qn;
  1275. if (farPlane == 0)
  1276. {
  1277. q = 1 - Camera::INFINITE_FAR_PLANE_ADJUST;
  1278. qn = nearPlane * (Camera::INFINITE_FAR_PLANE_ADJUST - 1);
  1279. }
  1280. else
  1281. {
  1282. q = farPlane / ( farPlane - nearPlane );
  1283. qn = -q * nearPlane;
  1284. }
  1285. dest = Matrix4::ZERO;
  1286. dest[0][0] = w;
  1287. dest[1][1] = h;
  1288. if (forGpuProgram)
  1289. {
  1290. dest[2][2] = -q;
  1291. dest[3][2] = -1.0f;
  1292. }
  1293. else
  1294. {
  1295. dest[2][2] = q;
  1296. dest[3][2] = 1.0f;
  1297. }
  1298. dest[2][3] = qn;
  1299. }
  1300. //---------------------------------------------------------------------
  1301. void D3D9RenderSystem::_makeOrthoMatrix(const Radian& fovy, float aspect, float nearPlane, float farPlane,
  1302. Matrix4& dest, bool forGpuProgram )
  1303. {
  1304. Radian thetaY (fovy / 2.0f);
  1305. float tanThetaY = Math::Tan(thetaY);
  1306. //float thetaX = thetaY * aspect;
  1307. float tanThetaX = tanThetaY * aspect; //Math::Tan(thetaX);
  1308. float half_w = tanThetaX * nearPlane;
  1309. float half_h = tanThetaY * nearPlane;
  1310. float iw = static_cast<float>(1.0 / half_w);
  1311. float ih = static_cast<float>(1.0 / half_h);
  1312. float q;
  1313. if (farPlane == 0)
  1314. {
  1315. q = 0;
  1316. }
  1317. else
  1318. {
  1319. q = static_cast<float>(1.0 / (farPlane - nearPlane));
  1320. }
  1321. dest = Matrix4::ZERO;
  1322. dest[0][0] = iw;
  1323. dest[1][1] = ih;
  1324. dest[2][2] = q;
  1325. dest[2][3] = -nearPlane / (farPlane - nearPlane);
  1326. dest[3][3] = 1;
  1327. if (forGpuProgram)
  1328. {
  1329. dest[2][2] = -dest[2][2];
  1330. }
  1331. }
  1332. //---------------------------------------------------------------------
  1333. void D3D9RenderSystem::setAmbientLight( float r, float g, float b )
  1334. {
  1335. HRESULT hr = __SetRenderState( D3DRS_AMBIENT, D3DCOLOR_COLORVALUE( r, g, b, 1.0f ) );
  1336. if( FAILED( hr ) )
  1337. CM_EXCEPT(RenderingAPIException, "Failed to set render stat D3DRS_AMBIENT");
  1338. }
  1339. //---------------------------------------------------------------------
  1340. void D3D9RenderSystem::setShadingType( ShadeOptions so )
  1341. {
  1342. HRESULT hr = __SetRenderState( D3DRS_SHADEMODE, D3D9Mappings::get(so) );
  1343. if( FAILED( hr ) )
  1344. CM_EXCEPT(RenderingAPIException, "Failed to set render stat D3DRS_SHADEMODE");
  1345. }
  1346. //---------------------------------------------------------------------
  1347. void D3D9RenderSystem::setLightingEnabled( bool enabled )
  1348. {
  1349. HRESULT hr;
  1350. if( FAILED( hr = __SetRenderState( D3DRS_LIGHTING, enabled ) ) )
  1351. CM_EXCEPT(RenderingAPIException, "Failed to set render state D3DRS_LIGHTING");
  1352. }
  1353. //---------------------------------------------------------------------
  1354. void D3D9RenderSystem::_setViewMatrix( const Matrix4 &m )
  1355. {
  1356. // save latest view matrix
  1357. mViewMatrix = m;
  1358. mViewMatrix[2][0] = -mViewMatrix[2][0];
  1359. mViewMatrix[2][1] = -mViewMatrix[2][1];
  1360. mViewMatrix[2][2] = -mViewMatrix[2][2];
  1361. mViewMatrix[2][3] = -mViewMatrix[2][3];
  1362. mDxViewMat = D3D9Mappings::makeD3DXMatrix( mViewMatrix );
  1363. HRESULT hr;
  1364. if( FAILED( hr = getActiveD3D9Device()->SetTransform( D3DTS_VIEW, &mDxViewMat ) ) )
  1365. CM_EXCEPT(RenderingAPIException, "Cannot set D3D9 view matrix");
  1366. // also mark clip planes dirty
  1367. if (!mClipPlanes.empty())
  1368. mClipPlanesDirty = true;
  1369. }
  1370. //---------------------------------------------------------------------
  1371. void D3D9RenderSystem::_setProjectionMatrix( const Matrix4 &m )
  1372. {
  1373. // save latest matrix
  1374. mDxProjMat = D3D9Mappings::makeD3DXMatrix( m );
  1375. if( mActiveRenderTarget->requiresTextureFlipping() )
  1376. {
  1377. // Invert transformed y
  1378. mDxProjMat._12 = - mDxProjMat._12;
  1379. mDxProjMat._22 = - mDxProjMat._22;
  1380. mDxProjMat._32 = - mDxProjMat._32;
  1381. mDxProjMat._42 = - mDxProjMat._42;
  1382. }
  1383. HRESULT hr;
  1384. if( FAILED( hr = getActiveD3D9Device()->SetTransform( D3DTS_PROJECTION, &mDxProjMat ) ) )
  1385. CM_EXCEPT(RenderingAPIException, "Cannot set D3D9 projection matrix");
  1386. // also mark clip planes dirty
  1387. if (!mClipPlanes.empty())
  1388. mClipPlanesDirty = true;
  1389. }
  1390. //---------------------------------------------------------------------
  1391. void D3D9RenderSystem::_setWorldMatrix( const Matrix4 &m )
  1392. {
  1393. // save latest matrix
  1394. mDxWorldMat = D3D9Mappings::makeD3DXMatrix( m );
  1395. HRESULT hr;
  1396. if( FAILED( hr = getActiveD3D9Device()->SetTransform( D3DTS_WORLD, &mDxWorldMat ) ) )
  1397. CM_EXCEPT(RenderingAPIException, "Cannot set D3D9 world matrix");
  1398. }
  1399. //---------------------------------------------------------------------
  1400. void D3D9RenderSystem::_setSurfaceParams( const Color &ambient, const Color &diffuse,
  1401. const Color &specular, const Color &emissive, float shininess,
  1402. TrackVertexColourType tracking )
  1403. {
  1404. D3DMATERIAL9 material;
  1405. material.Diffuse = D3DXCOLOR( diffuse.r, diffuse.g, diffuse.b, diffuse.a );
  1406. material.Ambient = D3DXCOLOR( ambient.r, ambient.g, ambient.b, ambient.a );
  1407. material.Specular = D3DXCOLOR( specular.r, specular.g, specular.b, specular.a );
  1408. material.Emissive = D3DXCOLOR( emissive.r, emissive.g, emissive.b, emissive.a );
  1409. material.Power = shininess;
  1410. HRESULT hr = getActiveD3D9Device()->SetMaterial( &material );
  1411. if( FAILED( hr ) )
  1412. CM_EXCEPT(RenderingAPIException, "Error setting D3D material");
  1413. if(tracking != TVC_NONE)
  1414. {
  1415. __SetRenderState(D3DRS_COLORVERTEX, TRUE);
  1416. __SetRenderState(D3DRS_AMBIENTMATERIALSOURCE, (tracking&TVC_AMBIENT)?D3DMCS_COLOR1:D3DMCS_MATERIAL);
  1417. __SetRenderState(D3DRS_DIFFUSEMATERIALSOURCE, (tracking&TVC_DIFFUSE)?D3DMCS_COLOR1:D3DMCS_MATERIAL);
  1418. __SetRenderState(D3DRS_SPECULARMATERIALSOURCE, (tracking&TVC_SPECULAR)?D3DMCS_COLOR1:D3DMCS_MATERIAL);
  1419. __SetRenderState(D3DRS_EMISSIVEMATERIALSOURCE, (tracking&TVC_EMISSIVE)?D3DMCS_COLOR1:D3DMCS_MATERIAL);
  1420. }
  1421. else
  1422. {
  1423. __SetRenderState(D3DRS_COLORVERTEX, FALSE);
  1424. }
  1425. }
  1426. //---------------------------------------------------------------------
  1427. void D3D9RenderSystem::_setPointParameters(float size,
  1428. bool attenuationEnabled, float constant, float linear, float quadratic,
  1429. float minSize, float maxSize)
  1430. {
  1431. if(attenuationEnabled)
  1432. {
  1433. // scaling required
  1434. __SetRenderState(D3DRS_POINTSCALEENABLE, TRUE);
  1435. __SetFloatRenderState(D3DRS_POINTSCALE_A, constant);
  1436. __SetFloatRenderState(D3DRS_POINTSCALE_B, linear);
  1437. __SetFloatRenderState(D3DRS_POINTSCALE_C, quadratic);
  1438. }
  1439. else
  1440. {
  1441. // no scaling required
  1442. __SetRenderState(D3DRS_POINTSCALEENABLE, FALSE);
  1443. }
  1444. __SetFloatRenderState(D3DRS_POINTSIZE, size);
  1445. __SetFloatRenderState(D3DRS_POINTSIZE_MIN, minSize);
  1446. if (maxSize == 0.0f)
  1447. maxSize = mCurrentCapabilities->getMaxPointSize();
  1448. __SetFloatRenderState(D3DRS_POINTSIZE_MAX, maxSize);
  1449. }
  1450. //---------------------------------------------------------------------
  1451. void D3D9RenderSystem::_setPointSpritesEnabled(bool enabled)
  1452. {
  1453. if (enabled)
  1454. {
  1455. __SetRenderState(D3DRS_POINTSPRITEENABLE, TRUE);
  1456. }
  1457. else
  1458. {
  1459. __SetRenderState(D3DRS_POINTSPRITEENABLE, FALSE);
  1460. }
  1461. }
  1462. //---------------------------------------------------------------------
  1463. void D3D9RenderSystem::_setTexture( size_t stage, bool enabled, const TexturePtr& tex )
  1464. {
  1465. HRESULT hr;
  1466. D3D9TexturePtr dt = std::static_pointer_cast<D3D9Texture>(tex);
  1467. if (enabled && (dt != nullptr))
  1468. {
  1469. IDirect3DBaseTexture9 *pTex = dt->getTexture();
  1470. if (mTexStageDesc[stage].pTex != pTex)
  1471. {
  1472. hr = getActiveD3D9Device()->SetTexture(static_cast<DWORD>(stage), pTex);
  1473. if( hr != S_OK )
  1474. {
  1475. String str = "Unable to set texture in D3D9";
  1476. CM_EXCEPT(RenderingAPIException, str);
  1477. }
  1478. // set stage desc.
  1479. mTexStageDesc[stage].pTex = pTex;
  1480. mTexStageDesc[stage].texType = D3D9Mappings::get(dt->getTextureType());
  1481. // Set gamma now too
  1482. if (dt->isHardwareGammaReadToBeUsed())
  1483. {
  1484. __SetSamplerState(static_cast<DWORD>(stage), D3DSAMP_SRGBTEXTURE, TRUE);
  1485. }
  1486. else
  1487. {
  1488. __SetSamplerState(static_cast<DWORD>(stage), D3DSAMP_SRGBTEXTURE, FALSE);
  1489. }
  1490. }
  1491. }
  1492. else
  1493. {
  1494. if (mTexStageDesc[stage].pTex != 0)
  1495. {
  1496. hr = getActiveD3D9Device()->SetTexture(static_cast<DWORD>(stage), 0);
  1497. if( hr != S_OK )
  1498. {
  1499. String str = "Unable to disable texture '" + toString(stage) + "' in D3D9";
  1500. CM_EXCEPT(RenderingAPIException, str);
  1501. }
  1502. }
  1503. hr = __SetTextureStageState(static_cast<DWORD>(stage), D3DTSS_COLOROP, D3DTOP_DISABLE);
  1504. if( hr != S_OK )
  1505. {
  1506. String str = "Unable to disable texture '" + toString(stage) + "' in D3D9";
  1507. CM_EXCEPT(RenderingAPIException, str);
  1508. }
  1509. // set stage desc. to defaults
  1510. mTexStageDesc[stage].pTex = 0;
  1511. mTexStageDesc[stage].autoTexCoordType = TEXCALC_NONE;
  1512. mTexStageDesc[stage].coordIndex = 0;
  1513. mTexStageDesc[stage].texType = D3D9Mappings::D3D_TEX_TYPE_NORMAL;
  1514. }
  1515. }
  1516. //---------------------------------------------------------------------
  1517. void D3D9RenderSystem::_setVertexTexture(size_t stage, const TexturePtr& tex)
  1518. {
  1519. if (tex == nullptr)
  1520. {
  1521. if (mTexStageDesc[stage].pVertexTex != 0)
  1522. {
  1523. HRESULT hr = getActiveD3D9Device()->SetTexture(D3DVERTEXTEXTURESAMPLER0 + static_cast<DWORD>(stage), 0);
  1524. if( hr != S_OK )
  1525. {
  1526. String str = "Unable to disable vertex texture '"
  1527. + toString(stage) + "' in D3D9";
  1528. CM_EXCEPT(RenderingAPIException, str);
  1529. }
  1530. }
  1531. // set stage desc. to defaults
  1532. mTexStageDesc[stage].pVertexTex = 0;
  1533. }
  1534. else
  1535. {
  1536. D3D9TexturePtr dt = std::static_pointer_cast<D3D9Texture>(tex);
  1537. IDirect3DBaseTexture9 *pTex = dt->getTexture();
  1538. if (mTexStageDesc[stage].pVertexTex != pTex)
  1539. {
  1540. HRESULT hr = getActiveD3D9Device()->SetTexture(D3DVERTEXTEXTURESAMPLER0 + static_cast<DWORD>(stage), pTex);
  1541. if( hr != S_OK )
  1542. {
  1543. String str = "Unable to set vertex texture in D3D9";
  1544. CM_EXCEPT(RenderingAPIException, str);
  1545. }
  1546. // set stage desc.
  1547. mTexStageDesc[stage].pVertexTex = pTex;
  1548. }
  1549. }
  1550. }
  1551. //---------------------------------------------------------------------
  1552. void D3D9RenderSystem::_disableTextureUnit(size_t texUnit)
  1553. {
  1554. RenderSystem::_disableTextureUnit(texUnit);
  1555. // also disable vertex texture unit
  1556. static TexturePtr nullPtr;
  1557. _setVertexTexture(texUnit, nullPtr);
  1558. }
  1559. //---------------------------------------------------------------------
  1560. void D3D9RenderSystem::_setTextureCoordSet( size_t stage, size_t index )
  1561. {
  1562. // if vertex shader is being used, stage and index must match
  1563. if (mVertexProgramBound)
  1564. index = stage;
  1565. HRESULT hr;
  1566. // Record settings
  1567. mTexStageDesc[stage].coordIndex = index;
  1568. hr = __SetTextureStageState( static_cast<DWORD>(stage), D3DTSS_TEXCOORDINDEX, D3D9Mappings::get(mTexStageDesc[stage].autoTexCoordType, mDeviceManager->getActiveDevice()->getD3D9DeviceCaps()) | index );
  1569. if( FAILED( hr ) )
  1570. CM_EXCEPT(RenderingAPIException, "Unable to set texture coord. set index");
  1571. }
  1572. //---------------------------------------------------------------------
  1573. void D3D9RenderSystem::_setTextureMipmapBias(size_t unit, float bias)
  1574. {
  1575. if (mCurrentCapabilities->hasCapability(RSC_MIPMAP_LOD_BIAS))
  1576. {
  1577. // ugh - have to pass float data through DWORD with no conversion
  1578. HRESULT hr = __SetSamplerState(static_cast<DWORD>(unit), D3DSAMP_MIPMAPLODBIAS,
  1579. *(DWORD*)&bias);
  1580. if(FAILED(hr))
  1581. CM_EXCEPT(RenderingAPIException, "Unable to set texture mipmap bias");
  1582. }
  1583. }
  1584. //---------------------------------------------------------------------
  1585. void D3D9RenderSystem::_setTextureAddressingMode( size_t stage,
  1586. const TextureState::UVWAddressingMode& uvw )
  1587. {
  1588. HRESULT hr;
  1589. if( FAILED( hr = __SetSamplerState( static_cast<DWORD>(stage), D3DSAMP_ADDRESSU, D3D9Mappings::get(uvw.u, mDeviceManager->getActiveDevice()->getD3D9DeviceCaps()) ) ) )
  1590. CM_EXCEPT(RenderingAPIException, "Failed to set texture addressing mode for U" );
  1591. if( FAILED( hr = __SetSamplerState( static_cast<DWORD>(stage), D3DSAMP_ADDRESSV, D3D9Mappings::get(uvw.v, mDeviceManager->getActiveDevice()->getD3D9DeviceCaps()) ) ) )
  1592. CM_EXCEPT(RenderingAPIException, "Failed to set texture addressing mode for V");
  1593. if( FAILED( hr = __SetSamplerState( static_cast<DWORD>(stage), D3DSAMP_ADDRESSW, D3D9Mappings::get(uvw.w, mDeviceManager->getActiveDevice()->getD3D9DeviceCaps()) ) ) )
  1594. CM_EXCEPT(RenderingAPIException, "Failed to set texture addressing mode for W");
  1595. }
  1596. //-----------------------------------------------------------------------------
  1597. void D3D9RenderSystem::_setTextureBorderColour(size_t stage,
  1598. const Color& colour)
  1599. {
  1600. HRESULT hr;
  1601. if( FAILED( hr = __SetSamplerState( static_cast<DWORD>(stage), D3DSAMP_BORDERCOLOR, colour.getAsARGB()) ) )
  1602. CM_EXCEPT(RenderingAPIException, "Failed to set texture border colour");
  1603. }
  1604. //---------------------------------------------------------------------
  1605. void D3D9RenderSystem::_setSceneBlending( SceneBlendFactor sourceFactor, SceneBlendFactor destFactor, SceneBlendOperation op )
  1606. {
  1607. HRESULT hr;
  1608. if( sourceFactor == SBF_ONE && destFactor == SBF_ZERO)
  1609. {
  1610. if (FAILED(hr = __SetRenderState(D3DRS_ALPHABLENDENABLE, FALSE)))
  1611. CM_EXCEPT(RenderingAPIException, "Failed to set alpha blending option");
  1612. }
  1613. else
  1614. {
  1615. if (FAILED(hr = __SetRenderState(D3DRS_ALPHABLENDENABLE, TRUE)))
  1616. CM_EXCEPT(RenderingAPIException, "Failed to set alpha blending option");
  1617. if (FAILED(hr = __SetRenderState(D3DRS_SEPARATEALPHABLENDENABLE, FALSE)))
  1618. CM_EXCEPT(RenderingAPIException, "Failed to set separate alpha blending option");
  1619. if( FAILED( hr = __SetRenderState( D3DRS_SRCBLEND, D3D9Mappings::get(sourceFactor) ) ) )
  1620. CM_EXCEPT(RenderingAPIException, "Failed to set source blend");
  1621. if( FAILED( hr = __SetRenderState( D3DRS_DESTBLEND, D3D9Mappings::get(destFactor) ) ) )
  1622. CM_EXCEPT(RenderingAPIException, "Failed to set destination blend");
  1623. }
  1624. if (FAILED(hr = __SetRenderState(D3DRS_BLENDOP, D3D9Mappings::get(op))))
  1625. CM_EXCEPT(RenderingAPIException, "Failed to set scene blending operation option");
  1626. if (FAILED(hr = __SetRenderState(D3DRS_BLENDOPALPHA, D3D9Mappings::get(op))))
  1627. CM_EXCEPT(RenderingAPIException, "Failed to set scene blending operation option");
  1628. }
  1629. //---------------------------------------------------------------------
  1630. void D3D9RenderSystem::_setSeparateSceneBlending( SceneBlendFactor sourceFactor, SceneBlendFactor destFactor, SceneBlendFactor sourceFactorAlpha,
  1631. SceneBlendFactor destFactorAlpha, SceneBlendOperation op, SceneBlendOperation alphaOp )
  1632. {
  1633. HRESULT hr;
  1634. if( sourceFactor == SBF_ONE && destFactor == SBF_ZERO &&
  1635. sourceFactorAlpha == SBF_ONE && destFactorAlpha == SBF_ZERO)
  1636. {
  1637. if (FAILED(hr = __SetRenderState(D3DRS_ALPHABLENDENABLE, FALSE)))
  1638. CM_EXCEPT(RenderingAPIException, "Failed to set alpha blending option");
  1639. }
  1640. else
  1641. {
  1642. if (FAILED(hr = __SetRenderState(D3DRS_ALPHABLENDENABLE, TRUE)))
  1643. CM_EXCEPT(RenderingAPIException, "Failed to set alpha blending option");
  1644. if (FAILED(hr = __SetRenderState(D3DRS_SEPARATEALPHABLENDENABLE, TRUE)))
  1645. CM_EXCEPT(RenderingAPIException, "Failed to set separate alpha blending option");
  1646. if( FAILED( hr = __SetRenderState( D3DRS_SRCBLEND, D3D9Mappings::get(sourceFactor) ) ) )
  1647. CM_EXCEPT(RenderingAPIException, "Failed to set source blend");
  1648. if( FAILED( hr = __SetRenderState( D3DRS_DESTBLEND, D3D9Mappings::get(destFactor) ) ) )
  1649. CM_EXCEPT(RenderingAPIException, "Failed to set destination blend");
  1650. if( FAILED( hr = __SetRenderState( D3DRS_SRCBLENDALPHA, D3D9Mappings::get(sourceFactorAlpha) ) ) )
  1651. CM_EXCEPT(RenderingAPIException, "Failed to set alpha source blend");
  1652. if( FAILED( hr = __SetRenderState( D3DRS_DESTBLENDALPHA, D3D9Mappings::get(destFactorAlpha) ) ) )
  1653. CM_EXCEPT(RenderingAPIException, "Failed to set alpha destination blend");
  1654. }
  1655. if (FAILED(hr = __SetRenderState(D3DRS_BLENDOP, D3D9Mappings::get(op))))
  1656. CM_EXCEPT(RenderingAPIException, "Failed to set scene blending operation option");
  1657. if (FAILED(hr = __SetRenderState(D3DRS_BLENDOPALPHA, D3D9Mappings::get(alphaOp))))
  1658. CM_EXCEPT(RenderingAPIException, "Failed to set alpha scene blending operation option");
  1659. }
  1660. //---------------------------------------------------------------------
  1661. void D3D9RenderSystem::_setAlphaRejectSettings( CompareFunction func, unsigned char value, bool alphaToCoverage )
  1662. {
  1663. HRESULT hr;
  1664. bool a2c = false;
  1665. static bool lasta2c = false;
  1666. if (func != CMPF_ALWAYS_PASS)
  1667. {
  1668. if( FAILED( hr = __SetRenderState( D3DRS_ALPHATESTENABLE, TRUE ) ) )
  1669. CM_EXCEPT(RenderingAPIException, "Failed to enable alpha testing");
  1670. a2c = alphaToCoverage;
  1671. }
  1672. else
  1673. {
  1674. if( FAILED( hr = __SetRenderState( D3DRS_ALPHATESTENABLE, FALSE ) ) )
  1675. CM_EXCEPT(RenderingAPIException, "Failed to disable alpha testing");
  1676. }
  1677. // Set always just be sure
  1678. if( FAILED( hr = __SetRenderState( D3DRS_ALPHAFUNC, D3D9Mappings::get(func) ) ) )
  1679. CM_EXCEPT(RenderingAPIException, "Failed to set alpha reject function");
  1680. if( FAILED( hr = __SetRenderState( D3DRS_ALPHAREF, value ) ) )
  1681. CM_EXCEPT(RenderingAPIException, "Failed to set render state D3DRS_ALPHAREF");
  1682. // Alpha to coverage
  1683. if (getCapabilities()->hasCapability(RSC_ALPHA_TO_COVERAGE))
  1684. {
  1685. // Vendor-specific hacks on renderstate, gotta love 'em
  1686. if (getCapabilities()->getVendor() == GPU_NVIDIA)
  1687. {
  1688. if (a2c)
  1689. {
  1690. if( FAILED( hr = __SetRenderState( D3DRS_ADAPTIVETESS_Y, (D3DFORMAT)MAKEFOURCC('A', 'T', 'O', 'C') ) ) )
  1691. CM_EXCEPT(RenderingAPIException, "Failed to set alpha to coverage option");
  1692. }
  1693. else
  1694. {
  1695. if( FAILED( hr = __SetRenderState( D3DRS_ADAPTIVETESS_Y, D3DFMT_UNKNOWN ) ) )
  1696. CM_EXCEPT(RenderingAPIException, "Failed to set alpha to coverage option");
  1697. }
  1698. }
  1699. else if ((getCapabilities()->getVendor() == GPU_ATI))
  1700. {
  1701. if (a2c)
  1702. {
  1703. if( FAILED( hr = __SetRenderState( D3DRS_POINTSIZE, MAKEFOURCC('A','2','M','1') ) ) )
  1704. CM_EXCEPT(RenderingAPIException, "Failed to set alpha to coverage option");
  1705. }
  1706. else
  1707. {
  1708. // discovered this through trial and error, seems to work
  1709. if( FAILED( hr = __SetRenderState( D3DRS_POINTSIZE, MAKEFOURCC('A','2','M','0') ) ) )
  1710. CM_EXCEPT(RenderingAPIException, "Failed to set alpha to coverage option");
  1711. }
  1712. }
  1713. // no hacks available for any other vendors?
  1714. lasta2c = a2c;
  1715. }
  1716. }
  1717. //---------------------------------------------------------------------
  1718. void D3D9RenderSystem::_setCullingMode( CullingMode mode )
  1719. {
  1720. mCullingMode = mode;
  1721. HRESULT hr;
  1722. bool flip = ((mActiveRenderTarget->requiresTextureFlipping() && !mInvertVertexWinding) ||
  1723. (!mActiveRenderTarget->requiresTextureFlipping() && mInvertVertexWinding));
  1724. if( FAILED (hr = __SetRenderState(D3DRS_CULLMODE,
  1725. D3D9Mappings::get(mode, flip))) )
  1726. CM_EXCEPT(RenderingAPIException, "Failed to set culling mode");
  1727. }
  1728. //---------------------------------------------------------------------
  1729. void D3D9RenderSystem::_setDepthBufferParams( bool depthTest, bool depthWrite, CompareFunction depthFunction )
  1730. {
  1731. _setDepthBufferCheckEnabled( depthTest );
  1732. _setDepthBufferWriteEnabled( depthWrite );
  1733. _setDepthBufferFunction( depthFunction );
  1734. }
  1735. //---------------------------------------------------------------------
  1736. void D3D9RenderSystem::_setDepthBufferCheckEnabled( bool enabled )
  1737. {
  1738. HRESULT hr;
  1739. if( enabled )
  1740. {
  1741. // Use w-buffer if available and enabled
  1742. if( mWBuffer && mDeviceManager->getActiveDevice()->getD3D9DeviceCaps().RasterCaps & D3DPRASTERCAPS_WBUFFER )
  1743. hr = __SetRenderState( D3DRS_ZENABLE, D3DZB_USEW );
  1744. else
  1745. hr = __SetRenderState( D3DRS_ZENABLE, D3DZB_TRUE );
  1746. }
  1747. else
  1748. hr = __SetRenderState( D3DRS_ZENABLE, D3DZB_FALSE );
  1749. if( FAILED( hr ) )
  1750. CM_EXCEPT(RenderingAPIException, "Error setting depth buffer test state");
  1751. }
  1752. //---------------------------------------------------------------------
  1753. void D3D9RenderSystem::_setDepthBufferWriteEnabled( bool enabled )
  1754. {
  1755. HRESULT hr;
  1756. if( FAILED( hr = __SetRenderState( D3DRS_ZWRITEENABLE, enabled ) ) )
  1757. CM_EXCEPT(RenderingAPIException, "Error setting depth buffer write state");
  1758. }
  1759. //---------------------------------------------------------------------
  1760. void D3D9RenderSystem::_setDepthBufferFunction( CompareFunction func )
  1761. {
  1762. HRESULT hr;
  1763. if( FAILED( hr = __SetRenderState( D3DRS_ZFUNC, D3D9Mappings::get(func) ) ) )
  1764. CM_EXCEPT(RenderingAPIException, "Error setting depth buffer test function");
  1765. }
  1766. //---------------------------------------------------------------------
  1767. void D3D9RenderSystem::_setDepthBias(float constantBias, float slopeScaleBias)
  1768. {
  1769. if ((mDeviceManager->getActiveDevice()->getD3D9DeviceCaps().RasterCaps & D3DPRASTERCAPS_DEPTHBIAS) != 0)
  1770. {
  1771. // Negate bias since D3D is backward
  1772. // D3D also expresses the constant bias as an absolute value, rather than
  1773. // relative to minimum depth unit, so scale to fit
  1774. constantBias = -constantBias / 250000.0f;
  1775. HRESULT hr = __SetRenderState(D3DRS_DEPTHBIAS, FLOAT2DWORD(constantBias));
  1776. if (FAILED(hr))
  1777. CM_EXCEPT(RenderingAPIException, "Error setting constant depth bias");
  1778. }
  1779. if ((mDeviceManager->getActiveDevice()->getD3D9DeviceCaps().RasterCaps & D3DPRASTERCAPS_SLOPESCALEDEPTHBIAS) != 0)
  1780. {
  1781. // Negate bias since D3D is backward
  1782. slopeScaleBias = -slopeScaleBias;
  1783. HRESULT hr = __SetRenderState(D3DRS_SLOPESCALEDEPTHBIAS, FLOAT2DWORD(slopeScaleBias));
  1784. if (FAILED(hr))
  1785. CM_EXCEPT(RenderingAPIException, "Error setting slope scale depth bias");
  1786. }
  1787. }
  1788. //---------------------------------------------------------------------
  1789. void D3D9RenderSystem::_setColourBufferWriteEnabled(bool red, bool green,
  1790. bool blue, bool alpha)
  1791. {
  1792. DWORD val = 0;
  1793. if (red)
  1794. val |= D3DCOLORWRITEENABLE_RED;
  1795. if (green)
  1796. val |= D3DCOLORWRITEENABLE_GREEN;
  1797. if (blue)
  1798. val |= D3DCOLORWRITEENABLE_BLUE;
  1799. if (alpha)
  1800. val |= D3DCOLORWRITEENABLE_ALPHA;
  1801. HRESULT hr = __SetRenderState(D3DRS_COLORWRITEENABLE, val);
  1802. if (FAILED(hr))
  1803. CM_EXCEPT(RenderingAPIException, "Error setting colour write enable flags");
  1804. }
  1805. //---------------------------------------------------------------------
  1806. void D3D9RenderSystem::_setFog( FogMode mode, const Color& colour, float densitiy, float start, float end )
  1807. {
  1808. HRESULT hr;
  1809. D3DRENDERSTATETYPE fogType, fogTypeNot;
  1810. if (mDeviceManager->getActiveDevice()->getD3D9DeviceCaps().RasterCaps & D3DPRASTERCAPS_FOGTABLE)
  1811. {
  1812. fogType = D3DRS_FOGTABLEMODE;
  1813. fogTypeNot = D3DRS_FOGVERTEXMODE;
  1814. }
  1815. else
  1816. {
  1817. fogType = D3DRS_FOGVERTEXMODE;
  1818. fogTypeNot = D3DRS_FOGTABLEMODE;
  1819. }
  1820. if( mode == FOG_NONE)
  1821. {
  1822. // just disable
  1823. hr = __SetRenderState(fogType, D3DFOG_NONE );
  1824. hr = __SetRenderState(D3DRS_FOGENABLE, FALSE);
  1825. }
  1826. else
  1827. {
  1828. // Allow fog
  1829. hr = __SetRenderState( D3DRS_FOGENABLE, TRUE );
  1830. hr = __SetRenderState( fogTypeNot, D3DFOG_NONE );
  1831. hr = __SetRenderState( fogType, D3D9Mappings::get(mode) );
  1832. hr = __SetRenderState( D3DRS_FOGCOLOR, colour.getAsARGB() );
  1833. hr = __SetFloatRenderState( D3DRS_FOGSTART, start );
  1834. hr = __SetFloatRenderState( D3DRS_FOGEND, end );
  1835. hr = __SetFloatRenderState( D3DRS_FOGDENSITY, densitiy );
  1836. }
  1837. if( FAILED( hr ) )
  1838. CM_EXCEPT(RenderingAPIException, "Error setting render state");
  1839. }
  1840. //---------------------------------------------------------------------
  1841. void D3D9RenderSystem::_setPolygonMode(PolygonMode level)
  1842. {
  1843. HRESULT hr = __SetRenderState(D3DRS_FILLMODE, D3D9Mappings::get(level));
  1844. if (FAILED(hr))
  1845. CM_EXCEPT(RenderingAPIException, "Error setting polygon mode.");
  1846. }
  1847. //---------------------------------------------------------------------
  1848. void D3D9RenderSystem::setStencilCheckEnabled(bool enabled)
  1849. {
  1850. // Allow stencilling
  1851. HRESULT hr = __SetRenderState(D3DRS_STENCILENABLE, enabled);
  1852. if (FAILED(hr))
  1853. CM_EXCEPT(RenderingAPIException, "Error enabling / disabling stencilling.");
  1854. }
  1855. //---------------------------------------------------------------------
  1856. void D3D9RenderSystem::setStencilBufferParams(CompareFunction func,
  1857. UINT32 refValue, UINT32 mask, StencilOperation stencilFailOp,
  1858. StencilOperation depthFailOp, StencilOperation passOp,
  1859. bool twoSidedOperation)
  1860. {
  1861. HRESULT hr;
  1862. bool flip;
  1863. // 2-sided operation
  1864. if (twoSidedOperation)
  1865. {
  1866. if (!mCurrentCapabilities->hasCapability(RSC_TWO_SIDED_STENCIL))
  1867. CM_EXCEPT(InvalidParametersException, "2-sided stencils are not supported");
  1868. hr = __SetRenderState(D3DRS_TWOSIDEDSTENCILMODE, TRUE);
  1869. if (FAILED(hr))
  1870. CM_EXCEPT(RenderingAPIException, "Error setting 2-sided stencil mode.");
  1871. // NB: We should always treat CCW as front face for consistent with default
  1872. // culling mode. Therefore, we must take care with two-sided stencil settings.
  1873. flip = (mInvertVertexWinding && mActiveRenderTarget->requiresTextureFlipping()) ||
  1874. (!mInvertVertexWinding && !mActiveRenderTarget->requiresTextureFlipping());
  1875. // Set alternative versions of ops
  1876. // fail op
  1877. hr = __SetRenderState(D3DRS_CCW_STENCILFAIL, D3D9Mappings::get(stencilFailOp, !flip));
  1878. if (FAILED(hr))
  1879. CM_EXCEPT(RenderingAPIException, "Error setting stencil fail operation (2-sided).");
  1880. // depth fail op
  1881. hr = __SetRenderState(D3DRS_CCW_STENCILZFAIL, D3D9Mappings::get(depthFailOp, !flip));
  1882. if (FAILED(hr))
  1883. CM_EXCEPT(RenderingAPIException, "Error setting stencil depth fail operation (2-sided).");
  1884. // pass op
  1885. hr = __SetRenderState(D3DRS_CCW_STENCILPASS, D3D9Mappings::get(passOp, !flip));
  1886. if (FAILED(hr))
  1887. CM_EXCEPT(RenderingAPIException, "Error setting stencil pass operation (2-sided).");
  1888. }
  1889. else
  1890. {
  1891. hr = __SetRenderState(D3DRS_TWOSIDEDSTENCILMODE, FALSE);
  1892. if (FAILED(hr))
  1893. CM_EXCEPT(RenderingAPIException, "Error setting 1-sided stencil mode.");
  1894. flip = false;
  1895. }
  1896. // func
  1897. hr = __SetRenderState(D3DRS_STENCILFUNC, D3D9Mappings::get(func));
  1898. if (FAILED(hr))
  1899. CM_EXCEPT(RenderingAPIException, "Error setting stencil buffer test function.");
  1900. // reference value
  1901. hr = __SetRenderState(D3DRS_STENCILREF, refValue);
  1902. if (FAILED(hr))
  1903. CM_EXCEPT(RenderingAPIException, "Error setting stencil buffer reference value.");
  1904. // mask
  1905. hr = __SetRenderState(D3DRS_STENCILMASK, mask);
  1906. if (FAILED(hr))
  1907. CM_EXCEPT(RenderingAPIException, "Error setting stencil buffer mask.");
  1908. // fail op
  1909. hr = __SetRenderState(D3DRS_STENCILFAIL, D3D9Mappings::get(stencilFailOp, flip));
  1910. if (FAILED(hr))
  1911. CM_EXCEPT(RenderingAPIException, "Error setting stencil fail operation.");
  1912. // depth fail op
  1913. hr = __SetRenderState(D3DRS_STENCILZFAIL, D3D9Mappings::get(depthFailOp, flip));
  1914. if (FAILED(hr))
  1915. CM_EXCEPT(RenderingAPIException, "Error setting stencil depth fail operation.");
  1916. // pass op
  1917. hr = __SetRenderState(D3DRS_STENCILPASS, D3D9Mappings::get(passOp, flip));
  1918. if (FAILED(hr))
  1919. CM_EXCEPT(RenderingAPIException, "Error setting stencil pass operation.");
  1920. }
  1921. //---------------------------------------------------------------------
  1922. void D3D9RenderSystem::_setTextureUnitFiltering(size_t unit, FilterType ftype,
  1923. FilterOptions filter)
  1924. {
  1925. HRESULT hr;
  1926. D3D9Mappings::eD3DTexType texType = mTexStageDesc[unit].texType;
  1927. hr = __SetSamplerState( static_cast<DWORD>(unit), D3D9Mappings::get(ftype),
  1928. D3D9Mappings::get(ftype, filter, mDeviceManager->getActiveDevice()->getD3D9DeviceCaps(), texType));
  1929. if (FAILED(hr))
  1930. CM_EXCEPT(RenderingAPIException, "Failed to set texture filter ");
  1931. }
  1932. //---------------------------------------------------------------------
  1933. DWORD D3D9RenderSystem::_getCurrentAnisotropy(size_t unit)
  1934. {
  1935. DWORD oldVal;
  1936. getActiveD3D9Device()->GetSamplerState(static_cast<DWORD>(unit), D3DSAMP_MAXANISOTROPY, &oldVal);
  1937. return oldVal;
  1938. }
  1939. //---------------------------------------------------------------------
  1940. void D3D9RenderSystem::_setTextureLayerAnisotropy(size_t unit, unsigned int maxAnisotropy)
  1941. {
  1942. if (static_cast<DWORD>(maxAnisotropy) > mDeviceManager->getActiveDevice()->getD3D9DeviceCaps().MaxAnisotropy)
  1943. maxAnisotropy = mDeviceManager->getActiveDevice()->getD3D9DeviceCaps().MaxAnisotropy;
  1944. if (_getCurrentAnisotropy(unit) != maxAnisotropy)
  1945. __SetSamplerState( static_cast<DWORD>(unit), D3DSAMP_MAXANISOTROPY, maxAnisotropy );
  1946. }
  1947. //---------------------------------------------------------------------
  1948. HRESULT D3D9RenderSystem::__SetRenderState(D3DRENDERSTATETYPE state, DWORD value)
  1949. {
  1950. HRESULT hr;
  1951. DWORD oldVal;
  1952. if ( FAILED( hr = getActiveD3D9Device()->GetRenderState(state, &oldVal) ) )
  1953. return hr;
  1954. if ( oldVal == value )
  1955. return D3D_OK;
  1956. else
  1957. return getActiveD3D9Device()->SetRenderState(state, value);
  1958. }
  1959. //---------------------------------------------------------------------
  1960. HRESULT D3D9RenderSystem::__SetSamplerState(DWORD sampler, D3DSAMPLERSTATETYPE type, DWORD value)
  1961. {
  1962. HRESULT hr;
  1963. DWORD oldVal;
  1964. if ( FAILED( hr = getActiveD3D9Device()->GetSamplerState(sampler, type, &oldVal) ) )
  1965. return hr;
  1966. if ( oldVal == value )
  1967. return D3D_OK;
  1968. else
  1969. return getActiveD3D9Device()->SetSamplerState(sampler, type, value);
  1970. }
  1971. //---------------------------------------------------------------------
  1972. HRESULT D3D9RenderSystem::__SetTextureStageState(DWORD stage, D3DTEXTURESTAGESTATETYPE type, DWORD value)
  1973. {
  1974. HRESULT hr;
  1975. DWORD oldVal;
  1976. // can only set fixed-function texture stage state
  1977. if (stage < 8)
  1978. {
  1979. if ( FAILED( hr = getActiveD3D9Device()->GetTextureStageState(stage, type, &oldVal) ) )
  1980. return hr;
  1981. if ( oldVal == value )
  1982. return D3D_OK;
  1983. else
  1984. return getActiveD3D9Device()->SetTextureStageState(stage, type, value);
  1985. }
  1986. else
  1987. {
  1988. return D3D_OK;
  1989. }
  1990. }
  1991. //---------------------------------------------------------------------
  1992. void D3D9RenderSystem::_setRenderTarget(RenderTarget *target)
  1993. {
  1994. mActiveRenderTarget = target;
  1995. HRESULT hr;
  1996. // If this is called without going through RenderWindow::update, then
  1997. // the device will not have been set. Calling it twice is safe, the
  1998. // implementation ensures nothing happens if the same device is set twice
  1999. if (std::find(mRenderWindows.begin(), mRenderWindows.end(), target) != mRenderWindows.end())
  2000. {
  2001. D3D9RenderWindow *window = static_cast<D3D9RenderWindow*>(target);
  2002. mDeviceManager->setActiveRenderTargetDevice(window->getDevice());
  2003. // also make sure we validate the device; if this never went
  2004. // through update() it won't be set
  2005. window->_validateDevice();
  2006. }
  2007. // Retrieve render surfaces (up to CM_MAX_MULTIPLE_RENDER_TARGETS)
  2008. IDirect3DSurface9* pBack[CM_MAX_MULTIPLE_RENDER_TARGETS];
  2009. memset(pBack, 0, sizeof(pBack));
  2010. target->getCustomAttribute( "DDBACKBUFFER", &pBack );
  2011. if (!pBack[0])
  2012. return;
  2013. IDirect3DSurface9* pDepth = NULL;
  2014. //Check if we saved a depth buffer for this target
  2015. TargetDepthStencilMap::iterator savedTexture = mCheckedOutTextures.find(target);
  2016. if (savedTexture != mCheckedOutTextures.end())
  2017. {
  2018. pDepth = savedTexture->second.surface;
  2019. }
  2020. if (!pDepth)
  2021. target->getCustomAttribute( "D3DZBUFFER", &pDepth );
  2022. if (!pDepth)
  2023. {
  2024. /// No depth buffer provided, use our own
  2025. /// Request a depth stencil that is compatible with the format, multisample type and
  2026. /// dimensions of the render target.
  2027. D3DSURFACE_DESC srfDesc;
  2028. if(FAILED(pBack[0]->GetDesc(&srfDesc)))
  2029. return; // ?
  2030. pDepth = _getDepthStencilFor(srfDesc.Format, srfDesc.MultiSampleType, srfDesc.MultiSampleQuality, srfDesc.Width, srfDesc.Height);
  2031. }
  2032. // Bind render targets
  2033. UINT32 count = mCurrentCapabilities->getNumMultiRenderTargets();
  2034. for(UINT32 x=0; x<count; ++x)
  2035. {
  2036. hr = getActiveD3D9Device()->SetRenderTarget(x, pBack[x]);
  2037. if (FAILED(hr))
  2038. {
  2039. String msg = DXGetErrorDescription(hr);
  2040. CM_EXCEPT(RenderingAPIException, "Failed to setRenderTarget : " + msg);
  2041. }
  2042. }
  2043. hr = getActiveD3D9Device()->SetDepthStencilSurface(pDepth);
  2044. if (FAILED(hr))
  2045. {
  2046. String msg = DXGetErrorDescription(hr);
  2047. CM_EXCEPT(RenderingAPIException, "Failed to setDepthStencil : " + msg);
  2048. }
  2049. }
  2050. //---------------------------------------------------------------------
  2051. void D3D9RenderSystem::_setViewport( Viewport *vp )
  2052. {
  2053. if( vp != mActiveViewport)
  2054. {
  2055. mActiveViewport = vp;
  2056. // ok, it's different, time to set render target and viewport params
  2057. D3DVIEWPORT9 d3dvp;
  2058. HRESULT hr;
  2059. // Set render target
  2060. RenderTarget* target = vp->getTarget();
  2061. _setRenderTarget(target);
  2062. _setCullingMode( mCullingMode );
  2063. // set viewport dimensions
  2064. d3dvp.X = vp->getActualLeft();
  2065. d3dvp.Y = vp->getActualTop();
  2066. d3dvp.Width = vp->getActualWidth();
  2067. d3dvp.Height = vp->getActualHeight();
  2068. if (target->requiresTextureFlipping())
  2069. {
  2070. // Convert "top-left" to "bottom-left"
  2071. d3dvp.Y = target->getHeight() - d3dvp.Height - d3dvp.Y;
  2072. }
  2073. // Z-values from 0.0 to 1.0 (TODO: standardise with OpenGL)
  2074. d3dvp.MinZ = 0.0f;
  2075. d3dvp.MaxZ = 1.0f;
  2076. if( FAILED( hr = getActiveD3D9Device()->SetViewport( &d3dvp ) ) )
  2077. CM_EXCEPT(RenderingAPIException, "Failed to set viewport.");
  2078. // Set sRGB write mode
  2079. __SetRenderState(D3DRS_SRGBWRITEENABLE, target->isHardwareGammaEnabled());
  2080. }
  2081. }
  2082. //---------------------------------------------------------------------
  2083. void D3D9RenderSystem::_beginFrame()
  2084. {
  2085. HRESULT hr;
  2086. if( !mActiveViewport )
  2087. CM_EXCEPT(InternalErrorException, "Cannot begin frame - no viewport selected.");
  2088. if( FAILED( hr = getActiveD3D9Device()->BeginScene() ) )
  2089. {
  2090. String msg = DXGetErrorDescription(hr);
  2091. CM_EXCEPT(RenderingAPIException, "Error beginning frame :" + msg);
  2092. }
  2093. mLastVertexSourceCount = 0;
  2094. // Clear left overs of previous viewport.
  2095. // I.E: Viewport A can use 3 different textures and light states
  2096. // When trying to render viewport B these settings should be cleared, otherwise
  2097. // graphical artifacts might occur.
  2098. mDeviceManager->getActiveDevice()->clearDeviceStreams();
  2099. }
  2100. //---------------------------------------------------------------------
  2101. void D3D9RenderSystem::_endFrame()
  2102. {
  2103. HRESULT hr;
  2104. if( FAILED( hr = getActiveD3D9Device()->EndScene() ) )
  2105. CM_EXCEPT(RenderingAPIException, "Error ending frame");
  2106. mDeviceManager->destroyInactiveRenderDevices();
  2107. }
  2108. //---------------------------------------------------------------------
  2109. struct D3D9RenderContext : public RenderSystem::RenderSystemContext
  2110. {
  2111. RenderTarget* target;
  2112. };
  2113. //---------------------------------------------------------------------
  2114. D3D9RenderSystem::ZBufferIdentifier D3D9RenderSystem::getZBufferIdentifier(RenderTarget* rt)
  2115. {
  2116. // Retrieve render surfaces (up to CM_MAX_MULTIPLE_RENDER_TARGETS)
  2117. IDirect3DSurface9* pBack[CM_MAX_MULTIPLE_RENDER_TARGETS];
  2118. memset(pBack, 0, sizeof(pBack));
  2119. rt->getCustomAttribute( "DDBACKBUFFER", &pBack );
  2120. assert(pBack[0]);
  2121. /// Request a depth stencil that is compatible with the format, multisample type and
  2122. /// dimensions of the render target.
  2123. D3DSURFACE_DESC srfDesc;
  2124. HRESULT hr = pBack[0]->GetDesc(&srfDesc);
  2125. assert(!(FAILED(hr)));
  2126. D3DFORMAT dsfmt = _getDepthStencilFormatFor(srfDesc.Format);
  2127. assert(dsfmt != D3DFMT_UNKNOWN);
  2128. /// Build identifier and return
  2129. ZBufferIdentifier zBufferIdentifier;
  2130. zBufferIdentifier.format = dsfmt;
  2131. zBufferIdentifier.multisampleType = srfDesc.MultiSampleType;
  2132. zBufferIdentifier.device = getActiveD3D9Device();
  2133. return zBufferIdentifier;
  2134. }
  2135. //---------------------------------------------------------------------
  2136. RenderSystem::RenderSystemContext* D3D9RenderSystem::_pauseFrame(void)
  2137. {
  2138. //Stop rendering
  2139. _endFrame();
  2140. D3D9RenderContext* context = new D3D9RenderContext;
  2141. context->target = mActiveRenderTarget;
  2142. //Don't do this to backbuffers. Is there a more elegant way to check?
  2143. if (!dynamic_cast<D3D9RenderWindow*>(mActiveRenderTarget))
  2144. {
  2145. //Get the matching z buffer identifier and queue
  2146. ZBufferIdentifier zBufferIdentifier = getZBufferIdentifier(mActiveRenderTarget);
  2147. ZBufferRefQueue& zBuffers = mZBufferHash[zBufferIdentifier];
  2148. #ifdef CM_DEBUG_MODE
  2149. //Check that queue handling works as expected
  2150. IDirect3DSurface9* pDepth;
  2151. getActiveD3D9Device()->GetDepthStencilSurface(&pDepth);
  2152. // Release immediately -> each get increase the ref count.
  2153. if (pDepth != NULL)
  2154. pDepth->Release();
  2155. assert(zBuffers.front().surface == pDepth);
  2156. #endif
  2157. //Store the depth buffer in the side and remove it from the queue
  2158. mCheckedOutTextures[mActiveRenderTarget] = zBuffers.front();
  2159. zBuffers.pop_front();
  2160. }
  2161. return context;
  2162. }
  2163. //---------------------------------------------------------------------
  2164. void D3D9RenderSystem::_resumeFrame(RenderSystemContext* context)
  2165. {
  2166. //Resume rendering
  2167. _beginFrame();
  2168. D3D9RenderContext* d3dContext = static_cast<D3D9RenderContext*>(context);
  2169. //Don't do this to backbuffers. Is there a more elegant way to check?
  2170. if (!dynamic_cast<D3D9RenderWindow*>(d3dContext->target))
  2171. {
  2172. ///Find the stored depth buffer
  2173. ZBufferIdentifier zBufferIdentifier = getZBufferIdentifier(d3dContext->target);
  2174. ZBufferRefQueue& zBuffers = mZBufferHash[zBufferIdentifier];
  2175. assert(mCheckedOutTextures.find(d3dContext->target) != mCheckedOutTextures.end());
  2176. //Return it to the general queue
  2177. zBuffers.push_front(mCheckedOutTextures[d3dContext->target]);
  2178. mCheckedOutTextures.erase(d3dContext->target);
  2179. }
  2180. delete context;
  2181. }
  2182. //---------------------------------------------------------------------
  2183. void D3D9RenderSystem::setVertexDeclaration(VertexDeclarationPtr decl)
  2184. {
  2185. HRESULT hr;
  2186. std::shared_ptr<D3D9VertexDeclaration> d3ddecl =
  2187. std::static_pointer_cast<D3D9VertexDeclaration>(decl);
  2188. if (FAILED(hr = getActiveD3D9Device()->SetVertexDeclaration(d3ddecl->getD3DVertexDeclaration())))
  2189. {
  2190. CM_EXCEPT(RenderingAPIException, "Unable to set D3D9 vertex declaration");
  2191. }
  2192. }
  2193. //---------------------------------------------------------------------
  2194. void D3D9RenderSystem::setVertexBufferBinding(VertexBufferBinding* binding)
  2195. {
  2196. HRESULT hr;
  2197. // TODO: attempt to detect duplicates
  2198. const VertexBufferBinding::VertexBufferBindingMap& binds = binding->getBindings();
  2199. VertexBufferBinding::VertexBufferBindingMap::const_iterator i, iend;
  2200. size_t source = 0;
  2201. iend = binds.end();
  2202. for (i = binds.begin(); i != iend; ++i, ++source)
  2203. {
  2204. // Unbind gap sources
  2205. for ( ; source < i->first; ++source)
  2206. {
  2207. hr = getActiveD3D9Device()->SetStreamSource(static_cast<UINT>(source), NULL, 0, 0);
  2208. if (FAILED(hr))
  2209. {
  2210. CM_EXCEPT(RenderingAPIException, "Unable to reset unused D3D9 stream source");
  2211. }
  2212. }
  2213. D3D9HardwareVertexBuffer* d3d9buf =
  2214. static_cast<D3D9HardwareVertexBuffer*>(i->second.get());
  2215. hr = getActiveD3D9Device()->SetStreamSource(
  2216. static_cast<UINT>(source),
  2217. d3d9buf->getD3D9VertexBuffer(),
  2218. 0, // no stream offset, this is handled in _render instead
  2219. static_cast<UINT>(d3d9buf->getVertexSize()) // stride
  2220. );
  2221. if (FAILED(hr))
  2222. {
  2223. CM_EXCEPT(RenderingAPIException, "Unable to set D3D9 stream source for buffer binding");
  2224. }
  2225. }
  2226. // Unbind any unused sources
  2227. for (size_t unused = source; unused < mLastVertexSourceCount; ++unused)
  2228. {
  2229. hr = getActiveD3D9Device()->SetStreamSource(static_cast<UINT>(unused), NULL, 0, 0);
  2230. if (FAILED(hr))
  2231. {
  2232. CM_EXCEPT(RenderingAPIException, "Unable to reset unused D3D9 stream source");
  2233. }
  2234. }
  2235. mLastVertexSourceCount = source;
  2236. }
  2237. //---------------------------------------------------------------------
  2238. void D3D9RenderSystem::_render(const RenderOperation& op)
  2239. {
  2240. // Exit immediately if there is nothing to render
  2241. // This caused a problem on FireGL 8800
  2242. if (op.vertexData->vertexCount == 0)
  2243. return;
  2244. // Call super class
  2245. RenderSystem::_render(op);
  2246. // To think about: possibly remove setVertexDeclaration and
  2247. // setVertexBufferBinding from RenderSystem since the sequence is
  2248. // a bit too D3D9-specific?
  2249. setVertexDeclaration(op.vertexData->vertexDeclaration);
  2250. setVertexBufferBinding(op.vertexData->vertexBufferBinding);
  2251. // Determine rendering operation
  2252. D3DPRIMITIVETYPE primType = D3DPT_TRIANGLELIST;
  2253. DWORD primCount = 0;
  2254. switch( op.operationType )
  2255. {
  2256. case RenderOperation::OT_POINT_LIST:
  2257. primType = D3DPT_POINTLIST;
  2258. primCount = static_cast<DWORD>(op.useIndexes ? op.indexData->indexCount : op.vertexData->vertexCount);
  2259. break;
  2260. case RenderOperation::OT_LINE_LIST:
  2261. primType = D3DPT_LINELIST;
  2262. primCount = static_cast<DWORD>(op.useIndexes ? op.indexData->indexCount : op.vertexData->vertexCount) / 2;
  2263. break;
  2264. case RenderOperation::OT_LINE_STRIP:
  2265. primType = D3DPT_LINESTRIP;
  2266. primCount = static_cast<DWORD>(op.useIndexes ? op.indexData->indexCount : op.vertexData->vertexCount) - 1;
  2267. break;
  2268. case RenderOperation::OT_TRIANGLE_LIST:
  2269. primType = D3DPT_TRIANGLELIST;
  2270. primCount = static_cast<DWORD>(op.useIndexes ? op.indexData->indexCount : op.vertexData->vertexCount) / 3;
  2271. break;
  2272. case RenderOperation::OT_TRIANGLE_STRIP:
  2273. primType = D3DPT_TRIANGLESTRIP;
  2274. primCount = static_cast<DWORD>(op.useIndexes ? op.indexData->indexCount : op.vertexData->vertexCount) - 2;
  2275. break;
  2276. case RenderOperation::OT_TRIANGLE_FAN:
  2277. primType = D3DPT_TRIANGLEFAN;
  2278. primCount = static_cast<DWORD>(op.useIndexes ? op.indexData->indexCount : op.vertexData->vertexCount) - 2;
  2279. break;
  2280. }
  2281. if (!primCount)
  2282. return;
  2283. // Issue the op
  2284. HRESULT hr;
  2285. if( op.useIndexes )
  2286. {
  2287. D3D9HardwareIndexBuffer* d3dIdxBuf =
  2288. static_cast<D3D9HardwareIndexBuffer*>(op.indexData->indexBuffer.get());
  2289. hr = getActiveD3D9Device()->SetIndices( d3dIdxBuf->getD3DIndexBuffer() );
  2290. if (FAILED(hr))
  2291. {
  2292. CM_EXCEPT(RenderingAPIException, "Failed to set index buffer");
  2293. }
  2294. do
  2295. {
  2296. // Update derived depth bias
  2297. if (mDerivedDepthBias && mCurrentPassIterationNum > 0)
  2298. {
  2299. _setDepthBias(mDerivedDepthBiasBase +
  2300. mDerivedDepthBiasMultiplier * mCurrentPassIterationNum,
  2301. mDerivedDepthBiasSlopeScale);
  2302. }
  2303. // do indexed draw operation
  2304. hr = getActiveD3D9Device()->DrawIndexedPrimitive(
  2305. primType,
  2306. static_cast<INT>(op.vertexData->vertexStart),
  2307. 0, // Min vertex index - assume we can go right down to 0
  2308. static_cast<UINT>(op.vertexData->vertexCount),
  2309. static_cast<UINT>(op.indexData->indexStart),
  2310. static_cast<UINT>(primCount)
  2311. );
  2312. } while (updatePassIterationRenderState());
  2313. }
  2314. else
  2315. {
  2316. // nfz: gpu_iterate
  2317. do
  2318. {
  2319. // Update derived depth bias
  2320. if (mDerivedDepthBias && mCurrentPassIterationNum > 0)
  2321. {
  2322. _setDepthBias(mDerivedDepthBiasBase +
  2323. mDerivedDepthBiasMultiplier * mCurrentPassIterationNum,
  2324. mDerivedDepthBiasSlopeScale);
  2325. }
  2326. // Unindexed, a little simpler!
  2327. hr = getActiveD3D9Device()->DrawPrimitive(
  2328. primType,
  2329. static_cast<UINT>(op.vertexData->vertexStart),
  2330. static_cast<UINT>(primCount)
  2331. );
  2332. } while (updatePassIterationRenderState());
  2333. }
  2334. if( FAILED( hr ) )
  2335. {
  2336. String msg = DXGetErrorDescription(hr);
  2337. CM_EXCEPT(RenderingAPIException, "Failed to DrawPrimitive : " + msg);
  2338. }
  2339. }
  2340. //---------------------------------------------------------------------
  2341. void D3D9RenderSystem::setNormaliseNormals(bool normalise)
  2342. {
  2343. __SetRenderState(D3DRS_NORMALIZENORMALS,
  2344. normalise ? TRUE : FALSE);
  2345. }
  2346. //---------------------------------------------------------------------
  2347. void D3D9RenderSystem::bindGpuProgram(GpuProgram* prg)
  2348. {
  2349. HRESULT hr;
  2350. switch (prg->getType())
  2351. {
  2352. case GPT_VERTEX_PROGRAM:
  2353. hr = getActiveD3D9Device()->SetVertexShader(
  2354. static_cast<D3D9GpuVertexProgram*>(prg)->getVertexShader());
  2355. if (FAILED(hr))
  2356. {
  2357. CM_EXCEPT(RenderingAPIException, "Error calling SetVertexShader");
  2358. }
  2359. break;
  2360. case GPT_FRAGMENT_PROGRAM:
  2361. hr = getActiveD3D9Device()->SetPixelShader(
  2362. static_cast<D3D9GpuFragmentProgram*>(prg)->getPixelShader());
  2363. if (FAILED(hr))
  2364. {
  2365. CM_EXCEPT(RenderingAPIException, "Error calling SetPixelShader");
  2366. }
  2367. break;
  2368. };
  2369. // Make sure texcoord index is equal to stage value, As SDK Doc suggests:
  2370. // "When rendering using vertex shaders, each stage's texture coordinate index must be set to its default value."
  2371. // This solves such an errors when working with the Debug runtime -
  2372. // "Direct3D9: (ERROR) :Stage 1 - Texture coordinate index in the stage must be equal to the stage index when programmable vertex pipeline is used".
  2373. for (unsigned int nStage=0; nStage < 8; ++nStage)
  2374. __SetTextureStageState(nStage, D3DTSS_TEXCOORDINDEX, nStage);
  2375. RenderSystem::bindGpuProgram(prg);
  2376. }
  2377. //---------------------------------------------------------------------
  2378. void D3D9RenderSystem::unbindGpuProgram(GpuProgramType gptype)
  2379. {
  2380. HRESULT hr;
  2381. switch(gptype)
  2382. {
  2383. case GPT_VERTEX_PROGRAM:
  2384. mActiveVertexGpuProgramParameters = nullptr;
  2385. hr = getActiveD3D9Device()->SetVertexShader(NULL);
  2386. if (FAILED(hr))
  2387. {
  2388. CM_EXCEPT(RenderingAPIException, "Error resetting SetVertexShader to NULL");
  2389. }
  2390. break;
  2391. case GPT_FRAGMENT_PROGRAM:
  2392. mActiveFragmentGpuProgramParameters = nullptr;
  2393. hr = getActiveD3D9Device()->SetPixelShader(NULL);
  2394. if (FAILED(hr))
  2395. {
  2396. CM_EXCEPT(RenderingAPIException, "Error resetting SetPixelShader to NULL");
  2397. }
  2398. break;
  2399. };
  2400. RenderSystem::unbindGpuProgram(gptype);
  2401. }
  2402. //---------------------------------------------------------------------
  2403. void D3D9RenderSystem::bindGpuProgramParameters(GpuProgramType gptype,
  2404. GpuProgramParametersSharedPtr params, UINT16 variability)
  2405. {
  2406. // special case pass iteration
  2407. if (variability == (UINT16)GPV_PASS_ITERATION_NUMBER)
  2408. {
  2409. bindGpuProgramPassIterationParameters(gptype);
  2410. return;
  2411. }
  2412. HRESULT hr;
  2413. GpuLogicalBufferStructPtr floatLogical = params->getFloatLogicalBufferStruct();
  2414. GpuLogicalBufferStructPtr intLogical = params->getIntLogicalBufferStruct();
  2415. GpuLogicalBufferStructPtr samplerLogical = params->getSamplerLogicalBufferStruct();
  2416. // Set texture sampler
  2417. {
  2418. CM_LOCK_MUTEX(samplerLogical->mutex)
  2419. for (GpuLogicalIndexUseMap::const_iterator i = samplerLogical->map.begin();
  2420. i != samplerLogical->map.end(); ++i)
  2421. {
  2422. if (i->second.variability & variability)
  2423. {
  2424. size_t logicalIndex = i->first;
  2425. TexturePtr texture = params->getTexture(i->second.physicalIndex);
  2426. _setTexture(logicalIndex, true, texture);
  2427. }
  2428. }
  2429. }
  2430. switch(gptype)
  2431. {
  2432. case GPT_VERTEX_PROGRAM:
  2433. mActiveVertexGpuProgramParameters = params;
  2434. {
  2435. CM_LOCK_MUTEX(floatLogical->mutex)
  2436. for (GpuLogicalIndexUseMap::const_iterator i = floatLogical->map.begin();
  2437. i != floatLogical->map.end(); ++i)
  2438. {
  2439. if (i->second.variability & variability)
  2440. {
  2441. size_t logicalIndex = i->first;
  2442. const float* pFloat = params->getFloatPointer(i->second.physicalIndex);
  2443. size_t slotCount = i->second.currentSize / 4;
  2444. assert (i->second.currentSize % 4 == 0 && "Should not have any "
  2445. "elements less than 4 wide for D3D9");
  2446. 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
  2447. (UINT)logicalIndex, pFloat, (UINT)slotCount))) // buffer and then only call this method once
  2448. {
  2449. CM_EXCEPT(RenderingAPIException, "Unable to upload vertex shader float parameters");
  2450. }
  2451. }
  2452. }
  2453. }
  2454. // bind ints
  2455. {
  2456. CM_LOCK_MUTEX(intLogical->mutex)
  2457. for (GpuLogicalIndexUseMap::const_iterator i = intLogical->map.begin();
  2458. i != intLogical->map.end(); ++i)
  2459. {
  2460. if (i->second.variability & variability)
  2461. {
  2462. size_t logicalIndex = i->first;
  2463. const int* pInt = params->getIntPointer(i->second.physicalIndex);
  2464. size_t slotCount = i->second.currentSize / 4;
  2465. assert (i->second.currentSize % 4 == 0 && "Should not have any "
  2466. "elements less than 4 wide for D3D9");
  2467. if (FAILED(hr = getActiveD3D9Device()->SetVertexShaderConstantI(
  2468. static_cast<UINT>(logicalIndex), pInt, static_cast<UINT>(slotCount))))
  2469. {
  2470. CM_EXCEPT(RenderingAPIException, "Unable to upload vertex shader int parameters");
  2471. }
  2472. }
  2473. }
  2474. }
  2475. break;
  2476. case GPT_FRAGMENT_PROGRAM:
  2477. mActiveFragmentGpuProgramParameters = params;
  2478. {
  2479. CM_LOCK_MUTEX(floatLogical->mutex)
  2480. for (GpuLogicalIndexUseMap::const_iterator i = floatLogical->map.begin();
  2481. i != floatLogical->map.end(); ++i)
  2482. {
  2483. if (i->second.variability & variability)
  2484. {
  2485. size_t logicalIndex = i->first;
  2486. const float* pFloat = params->getFloatPointer(i->second.physicalIndex);
  2487. size_t slotCount = i->second.currentSize / 4;
  2488. assert (i->second.currentSize % 4 == 0 && "Should not have any "
  2489. "elements less than 4 wide for D3D9");
  2490. if (FAILED(hr = getActiveD3D9Device()->SetPixelShaderConstantF(
  2491. static_cast<UINT>(logicalIndex), pFloat, static_cast<UINT>(slotCount))))
  2492. {
  2493. CM_EXCEPT(RenderingAPIException, "Unable to upload pixel shader float parameters");
  2494. }
  2495. }
  2496. }
  2497. }
  2498. // bind ints
  2499. {
  2500. CM_LOCK_MUTEX(intLogical->mutex)
  2501. for (GpuLogicalIndexUseMap::const_iterator i = intLogical->map.begin();
  2502. i != intLogical->map.end(); ++i)
  2503. {
  2504. if (i->second.variability & variability)
  2505. {
  2506. size_t logicalIndex = i->first;
  2507. const int* pInt = params->getIntPointer(i->second.physicalIndex);
  2508. size_t slotCount = i->second.currentSize / 4;
  2509. assert (i->second.currentSize % 4 == 0 && "Should not have any "
  2510. "elements less than 4 wide for D3D9");
  2511. if (FAILED(hr = getActiveD3D9Device()->SetPixelShaderConstantI(
  2512. static_cast<UINT>(logicalIndex), pInt, static_cast<UINT>(slotCount))))
  2513. {
  2514. CM_EXCEPT(RenderingAPIException, "Unable to upload pixel shader int parameters");
  2515. }
  2516. }
  2517. }
  2518. }
  2519. break;
  2520. };
  2521. }
  2522. //---------------------------------------------------------------------
  2523. void D3D9RenderSystem::bindGpuProgramPassIterationParameters(GpuProgramType gptype)
  2524. {
  2525. HRESULT hr;
  2526. size_t physicalIndex = 0;
  2527. size_t logicalIndex = 0;
  2528. const float* pFloat;
  2529. switch(gptype)
  2530. {
  2531. case GPT_VERTEX_PROGRAM:
  2532. if (mActiveVertexGpuProgramParameters->hasPassIterationNumber())
  2533. {
  2534. physicalIndex = mActiveVertexGpuProgramParameters->getPassIterationNumberIndex();
  2535. logicalIndex = mActiveVertexGpuProgramParameters->getFloatLogicalIndexForPhysicalIndex(physicalIndex);
  2536. pFloat = mActiveVertexGpuProgramParameters->getFloatPointer(physicalIndex);
  2537. if (FAILED(hr = getActiveD3D9Device()->SetVertexShaderConstantF(
  2538. static_cast<UINT>(logicalIndex), pFloat, 1)))
  2539. {
  2540. CM_EXCEPT(RenderingAPIException, "Unable to upload vertex shader multi pass parameters");
  2541. }
  2542. }
  2543. break;
  2544. case GPT_FRAGMENT_PROGRAM:
  2545. if (mActiveFragmentGpuProgramParameters->hasPassIterationNumber())
  2546. {
  2547. physicalIndex = mActiveFragmentGpuProgramParameters->getPassIterationNumberIndex();
  2548. logicalIndex = mActiveFragmentGpuProgramParameters->getFloatLogicalIndexForPhysicalIndex(physicalIndex);
  2549. pFloat = mActiveFragmentGpuProgramParameters->getFloatPointer(physicalIndex);
  2550. if (FAILED(hr = getActiveD3D9Device()->SetPixelShaderConstantF(
  2551. static_cast<UINT>(logicalIndex), pFloat, 1)))
  2552. {
  2553. CM_EXCEPT(RenderingAPIException, "Unable to upload pixel shader multi pass parameters");
  2554. }
  2555. }
  2556. break;
  2557. }
  2558. }
  2559. //---------------------------------------------------------------------
  2560. void D3D9RenderSystem::setClipPlanesImpl(const PlaneList& clipPlanes)
  2561. {
  2562. size_t i;
  2563. size_t numClipPlanes;
  2564. D3DXPLANE dx9ClipPlane;
  2565. DWORD mask = 0;
  2566. HRESULT hr;
  2567. numClipPlanes = clipPlanes.size();
  2568. for (i = 0; i < numClipPlanes; ++i)
  2569. {
  2570. const Plane& plane = clipPlanes[i];
  2571. dx9ClipPlane.a = plane.normal.x;
  2572. dx9ClipPlane.b = plane.normal.y;
  2573. dx9ClipPlane.c = plane.normal.z;
  2574. dx9ClipPlane.d = plane.d;
  2575. if (mVertexProgramBound)
  2576. {
  2577. // programmable clips in clip space (ugh)
  2578. // must transform worldspace planes by view/proj
  2579. D3DXMATRIX xform;
  2580. D3DXMatrixMultiply(&xform, &mDxViewMat, &mDxProjMat);
  2581. D3DXMatrixInverse(&xform, NULL, &xform);
  2582. D3DXMatrixTranspose(&xform, &xform);
  2583. D3DXPlaneTransform(&dx9ClipPlane, &dx9ClipPlane, &xform);
  2584. }
  2585. hr = getActiveD3D9Device()->SetClipPlane(static_cast<DWORD>(i), dx9ClipPlane);
  2586. if (FAILED(hr))
  2587. {
  2588. CM_EXCEPT(RenderingAPIException, "Unable to set clip plane");
  2589. }
  2590. mask |= (1 << i);
  2591. }
  2592. hr = __SetRenderState(D3DRS_CLIPPLANEENABLE, mask);
  2593. if (FAILED(hr))
  2594. {
  2595. CM_EXCEPT(RenderingAPIException, "Unable to set render state for clip planes");
  2596. }
  2597. }
  2598. //---------------------------------------------------------------------
  2599. void D3D9RenderSystem::setScissorTest(bool enabled, size_t left, size_t top, size_t right,
  2600. size_t bottom)
  2601. {
  2602. HRESULT hr;
  2603. if (enabled)
  2604. {
  2605. if (FAILED(hr = __SetRenderState(D3DRS_SCISSORTESTENABLE, TRUE)))
  2606. {
  2607. CM_EXCEPT(RenderingAPIException, "Unable to enable scissor rendering state; " + getErrorDescription(hr));
  2608. }
  2609. RECT rect;
  2610. rect.left = static_cast<LONG>(left);
  2611. rect.top = static_cast<LONG>(top);
  2612. rect.bottom = static_cast<LONG>(bottom);
  2613. rect.right = static_cast<LONG>(right);
  2614. if (FAILED(hr = getActiveD3D9Device()->SetScissorRect(&rect)))
  2615. {
  2616. CM_EXCEPT(RenderingAPIException, "Unable to set scissor rectangle; " + getErrorDescription(hr));
  2617. }
  2618. }
  2619. else
  2620. {
  2621. if (FAILED(hr = __SetRenderState(D3DRS_SCISSORTESTENABLE, FALSE)))
  2622. {
  2623. CM_EXCEPT(RenderingAPIException, "Unable to disable scissor rendering state; " + getErrorDescription(hr));
  2624. }
  2625. }
  2626. }
  2627. //---------------------------------------------------------------------
  2628. void D3D9RenderSystem::clearFrameBuffer(unsigned int buffers,
  2629. const Color& colour, float depth, unsigned short stencil)
  2630. {
  2631. DWORD flags = 0;
  2632. if (buffers & FBT_COLOUR)
  2633. {
  2634. flags |= D3DCLEAR_TARGET;
  2635. }
  2636. if (buffers & FBT_DEPTH)
  2637. {
  2638. flags |= D3DCLEAR_ZBUFFER;
  2639. }
  2640. // Only try to clear the stencil buffer if supported
  2641. if (buffers & FBT_STENCIL && mCurrentCapabilities->hasCapability(RSC_HWSTENCIL))
  2642. {
  2643. flags |= D3DCLEAR_STENCIL;
  2644. }
  2645. HRESULT hr;
  2646. if( FAILED( hr = getActiveD3D9Device()->Clear(
  2647. 0,
  2648. NULL,
  2649. flags,
  2650. colour.getAsARGB(),
  2651. depth,
  2652. stencil ) ) )
  2653. {
  2654. String msg = DXGetErrorDescription(hr);
  2655. CM_EXCEPT(RenderingAPIException, "Error clearing frame buffer : " + msg);
  2656. }
  2657. }
  2658. //---------------------------------------------------------------------
  2659. void D3D9RenderSystem::_makeProjectionMatrix(float left, float right,
  2660. float bottom, float top, float nearPlane, float farPlane, Matrix4& dest,
  2661. bool forGpuProgram)
  2662. {
  2663. // Correct position for off-axis projection matrix
  2664. if (!forGpuProgram)
  2665. {
  2666. float offsetX = left + right;
  2667. float offsetY = top + bottom;
  2668. left -= offsetX;
  2669. right -= offsetX;
  2670. top -= offsetY;
  2671. bottom -= offsetY;
  2672. }
  2673. float width = right - left;
  2674. float height = top - bottom;
  2675. float q, qn;
  2676. if (farPlane == 0)
  2677. {
  2678. q = 1 - Camera::INFINITE_FAR_PLANE_ADJUST;
  2679. qn = nearPlane * (Camera::INFINITE_FAR_PLANE_ADJUST - 1);
  2680. }
  2681. else
  2682. {
  2683. q = farPlane / ( farPlane - nearPlane );
  2684. qn = -q * nearPlane;
  2685. }
  2686. dest = Matrix4::ZERO;
  2687. dest[0][0] = 2 * nearPlane / width;
  2688. dest[0][2] = (right+left) / width;
  2689. dest[1][1] = 2 * nearPlane / height;
  2690. dest[1][2] = (top+bottom) / height;
  2691. if (forGpuProgram)
  2692. {
  2693. dest[2][2] = -q;
  2694. dest[3][2] = -1.0f;
  2695. }
  2696. else
  2697. {
  2698. dest[2][2] = q;
  2699. dest[3][2] = 1.0f;
  2700. }
  2701. dest[2][3] = qn;
  2702. }
  2703. // ------------------------------------------------------------------
  2704. void D3D9RenderSystem::setClipPlane (UINT16 index, float A, float B, float C, float D)
  2705. {
  2706. float plane[4] = { A, B, C, D };
  2707. getActiveD3D9Device()->SetClipPlane (index, plane);
  2708. }
  2709. // ------------------------------------------------------------------
  2710. void D3D9RenderSystem::enableClipPlane (UINT16 index, bool enable)
  2711. {
  2712. DWORD prev;
  2713. getActiveD3D9Device()->GetRenderState(D3DRS_CLIPPLANEENABLE, &prev);
  2714. __SetRenderState(D3DRS_CLIPPLANEENABLE, enable?
  2715. (prev | (1 << index)) : (prev & ~(1 << index)));
  2716. }
  2717. //---------------------------------------------------------------------
  2718. HardwareOcclusionQuery* D3D9RenderSystem::createHardwareOcclusionQuery()
  2719. {
  2720. D3D9HardwareOcclusionQuery* ret = new D3D9HardwareOcclusionQuery();
  2721. mHwOcclusionQueries.push_back(ret);
  2722. return ret;
  2723. }
  2724. //---------------------------------------------------------------------
  2725. float D3D9RenderSystem::getHorizontalTexelOffset()
  2726. {
  2727. // D3D considers the origin to be in the center of a pixel
  2728. return -0.5f;
  2729. }
  2730. //---------------------------------------------------------------------
  2731. float D3D9RenderSystem::getVerticalTexelOffset()
  2732. {
  2733. // D3D considers the origin to be in the center of a pixel
  2734. return -0.5f;
  2735. }
  2736. //---------------------------------------------------------------------
  2737. void D3D9RenderSystem::_applyObliqueDepthProjection(Matrix4& matrix, const Plane& plane,
  2738. bool forGpuProgram)
  2739. {
  2740. // Thanks to Eric Lenyel for posting this calculation at www.terathon.com
  2741. // Calculate the clip-space corner point opposite the clipping plane
  2742. // as (sgn(clipPlane.x), sgn(clipPlane.y), 1, 1) and
  2743. // transform it into camera space by multiplying it
  2744. // by the inverse of the projection matrix
  2745. /* generalised version
  2746. Vector4 q = matrix.inverse() *
  2747. Vector4(Math::Sign(plane.normal.x), Math::Sign(plane.normal.y), 1.0f, 1.0f);
  2748. */
  2749. Vector4 q;
  2750. q.x = Math::Sign(plane.normal.x) / matrix[0][0];
  2751. q.y = Math::Sign(plane.normal.y) / matrix[1][1];
  2752. q.z = 1.0F;
  2753. // flip the next bit from Lengyel since we're right-handed
  2754. if (forGpuProgram)
  2755. {
  2756. q.w = (1.0F - matrix[2][2]) / matrix[2][3];
  2757. }
  2758. else
  2759. {
  2760. q.w = (1.0F + matrix[2][2]) / matrix[2][3];
  2761. }
  2762. // Calculate the scaled plane vector
  2763. Vector4 clipPlane4d(plane.normal.x, plane.normal.y, plane.normal.z, plane.d);
  2764. Vector4 c = clipPlane4d * (1.0F / (clipPlane4d.dotProduct(q)));
  2765. // Replace the third row of the projection matrix
  2766. matrix[2][0] = c.x;
  2767. matrix[2][1] = c.y;
  2768. // flip the next bit from Lengyel since we're right-handed
  2769. if (forGpuProgram)
  2770. {
  2771. matrix[2][2] = c.z;
  2772. }
  2773. else
  2774. {
  2775. matrix[2][2] = -c.z;
  2776. }
  2777. matrix[2][3] = c.w;
  2778. }
  2779. //---------------------------------------------------------------------
  2780. float D3D9RenderSystem::getMinimumDepthInputValue()
  2781. {
  2782. // Range [0.0f, 1.0f]
  2783. return 0.0f;
  2784. }
  2785. //---------------------------------------------------------------------
  2786. float D3D9RenderSystem::getMaximumDepthInputValue()
  2787. {
  2788. // Range [0.0f, 1.0f]
  2789. // D3D inverts even identity view matrices, so maximum INPUT is -1.0
  2790. return -1.0f;
  2791. }
  2792. //---------------------------------------------------------------------
  2793. IDirect3D9* D3D9RenderSystem::getDirect3D9()
  2794. {
  2795. IDirect3D9* pDirect3D9 = msD3D9RenderSystem->mpD3D;
  2796. if (pDirect3D9 == NULL)
  2797. {
  2798. CM_EXCEPT(InvalidParametersException, "Direct3D9 interface is NULL !!!");
  2799. }
  2800. return pDirect3D9;
  2801. }
  2802. //---------------------------------------------------------------------
  2803. UINT D3D9RenderSystem::getResourceCreationDeviceCount()
  2804. {
  2805. D3D9ResourceCreationPolicy creationPolicy = msD3D9RenderSystem->mResourceManager->getCreationPolicy();
  2806. if (creationPolicy == RCP_CREATE_ON_ACTIVE_DEVICE)
  2807. {
  2808. return 1;
  2809. }
  2810. else if (creationPolicy == RCP_CREATE_ON_ALL_DEVICES)
  2811. {
  2812. return msD3D9RenderSystem->mDeviceManager->getDeviceCount();
  2813. }
  2814. CM_EXCEPT(InvalidParametersException, "Invalid resource creation policy !!!" );
  2815. return 0;
  2816. }
  2817. //---------------------------------------------------------------------
  2818. IDirect3DDevice9* D3D9RenderSystem::getResourceCreationDevice(UINT index)
  2819. {
  2820. D3D9ResourceCreationPolicy creationPolicy = msD3D9RenderSystem->mResourceManager->getCreationPolicy();
  2821. IDirect3DDevice9* d3d9Device = NULL;
  2822. if (creationPolicy == RCP_CREATE_ON_ACTIVE_DEVICE)
  2823. {
  2824. d3d9Device = msD3D9RenderSystem->getActiveD3D9Device();
  2825. }
  2826. else if (creationPolicy == RCP_CREATE_ON_ALL_DEVICES)
  2827. {
  2828. d3d9Device = msD3D9RenderSystem->mDeviceManager->getDevice(index)->getD3D9Device();
  2829. }
  2830. else
  2831. {
  2832. CM_EXCEPT(InvalidParametersException, "Invalid resource creation policy !!!" );
  2833. }
  2834. return d3d9Device;
  2835. }
  2836. //---------------------------------------------------------------------
  2837. IDirect3DDevice9* D3D9RenderSystem::getActiveD3D9Device()
  2838. {
  2839. D3D9Device* activeDevice = msD3D9RenderSystem->mDeviceManager->getActiveDevice();
  2840. IDirect3DDevice9* d3d9Device;
  2841. d3d9Device = activeDevice->getD3D9Device();
  2842. if (d3d9Device == NULL)
  2843. {
  2844. CM_EXCEPT(InvalidParametersException, "Current d3d9 device is NULL !!!" );
  2845. }
  2846. return d3d9Device;
  2847. }
  2848. //---------------------------------------------------------------------
  2849. // Formats to try, in decreasing order of preference
  2850. D3DFORMAT ddDepthStencilFormats[]={
  2851. D3DFMT_D24FS8,
  2852. D3DFMT_D24S8,
  2853. D3DFMT_D24X4S4,
  2854. D3DFMT_D24X8,
  2855. D3DFMT_D15S1,
  2856. D3DFMT_D16,
  2857. D3DFMT_D32
  2858. };
  2859. #define NDSFORMATS (sizeof(ddDepthStencilFormats)/sizeof(D3DFORMAT))
  2860. D3DFORMAT D3D9RenderSystem::_getDepthStencilFormatFor(D3DFORMAT fmt)
  2861. {
  2862. /// Check if result is cached
  2863. DepthStencilHash::iterator i = mDepthStencilHash.find((unsigned int)fmt);
  2864. if(i != mDepthStencilHash.end())
  2865. return i->second;
  2866. /// If not, probe with CheckDepthStencilMatch
  2867. D3DFORMAT dsfmt = D3DFMT_UNKNOWN;
  2868. /// Get description of primary render target
  2869. D3D9Device* activeDevice = mDeviceManager->getActiveDevice();
  2870. IDirect3DSurface9* mSurface = activeDevice->getPrimaryWindow()->getRenderSurface();
  2871. D3DSURFACE_DESC srfDesc;
  2872. if(!FAILED(mSurface->GetDesc(&srfDesc)))
  2873. {
  2874. /// Probe all depth stencil formats
  2875. /// Break on first one that matches
  2876. for(size_t x=0; x<NDSFORMATS; ++x)
  2877. {
  2878. // Verify that the depth format exists
  2879. if (mpD3D->CheckDeviceFormat(
  2880. activeDevice->getAdapterNumber(),
  2881. activeDevice->getDeviceType(),
  2882. srfDesc.Format,
  2883. D3DUSAGE_DEPTHSTENCIL,
  2884. D3DRTYPE_SURFACE,
  2885. ddDepthStencilFormats[x]) != D3D_OK)
  2886. {
  2887. continue;
  2888. }
  2889. // Verify that the depth format is compatible
  2890. if(mpD3D->CheckDepthStencilMatch(
  2891. activeDevice->getAdapterNumber(),
  2892. activeDevice->getDeviceType(),
  2893. srfDesc.Format,
  2894. fmt, ddDepthStencilFormats[x]) == D3D_OK)
  2895. {
  2896. dsfmt = ddDepthStencilFormats[x];
  2897. break;
  2898. }
  2899. }
  2900. }
  2901. /// Cache result
  2902. mDepthStencilHash[(unsigned int)fmt] = dsfmt;
  2903. return dsfmt;
  2904. }
  2905. IDirect3DSurface9* D3D9RenderSystem::_getDepthStencilFor(D3DFORMAT fmt,
  2906. D3DMULTISAMPLE_TYPE multisample, DWORD multisample_quality, size_t width, size_t height)
  2907. {
  2908. D3DFORMAT dsfmt = _getDepthStencilFormatFor(fmt);
  2909. if(dsfmt == D3DFMT_UNKNOWN)
  2910. return 0;
  2911. IDirect3DSurface9 *surface = 0;
  2912. /// Check if result is cached
  2913. ZBufferIdentifier zBufferIdentifer;
  2914. zBufferIdentifer.format = dsfmt;
  2915. zBufferIdentifer.multisampleType = multisample;
  2916. zBufferIdentifer.device = getActiveD3D9Device();
  2917. ZBufferRefQueue& zBuffers = mZBufferHash[zBufferIdentifer];
  2918. if(!zBuffers.empty())
  2919. {
  2920. const ZBufferRef& zBuffer = zBuffers.front();
  2921. /// Check if size is larger or equal
  2922. if(zBuffer.width >= width && zBuffer.height >= height)
  2923. {
  2924. surface = zBuffer.surface;
  2925. }
  2926. else
  2927. {
  2928. /// If not, destroy current buffer
  2929. zBuffer.surface->Release();
  2930. zBuffers.pop_front();
  2931. }
  2932. }
  2933. if(!surface)
  2934. {
  2935. /// If not, create the depthstencil surface
  2936. HRESULT hr = getActiveD3D9Device()->CreateDepthStencilSurface(
  2937. static_cast<UINT>(width),
  2938. static_cast<UINT>(height),
  2939. dsfmt,
  2940. multisample,
  2941. multisample_quality,
  2942. TRUE, // discard true or false?
  2943. &surface,
  2944. NULL);
  2945. if(FAILED(hr))
  2946. {
  2947. String msg = DXGetErrorDescription(hr);
  2948. CM_EXCEPT(InvalidParametersException, "Error CreateDepthStencilSurface : " + msg);
  2949. }
  2950. /// And cache it
  2951. ZBufferRef zb;
  2952. zb.surface = surface;
  2953. zb.width = width;
  2954. zb.height = height;
  2955. zBuffers.push_front(zb);
  2956. }
  2957. return surface;
  2958. }
  2959. //---------------------------------------------------------------------
  2960. void D3D9RenderSystem::_cleanupDepthStencils(IDirect3DDevice9* d3d9Device)
  2961. {
  2962. for(ZBufferHash::iterator i = mZBufferHash.begin(); i != mZBufferHash.end();)
  2963. {
  2964. /// Release buffer
  2965. if (i->first.device == d3d9Device)
  2966. {
  2967. while (!i->second.empty())
  2968. {
  2969. IDirect3DSurface9* surface = i->second.front().surface;
  2970. surface->Release();
  2971. i->second.pop_front();
  2972. }
  2973. ZBufferHash::iterator deadi = i++;
  2974. mZBufferHash.erase(deadi);
  2975. }
  2976. else
  2977. {
  2978. ++i;
  2979. }
  2980. }
  2981. }
  2982. //---------------------------------------------------------------------
  2983. void D3D9RenderSystem::registerThread()
  2984. {
  2985. // nothing to do - D3D9 shares rendering context already
  2986. }
  2987. //---------------------------------------------------------------------
  2988. void D3D9RenderSystem::unregisterThread()
  2989. {
  2990. // nothing to do - D3D9 shares rendering context already
  2991. }
  2992. //---------------------------------------------------------------------
  2993. void D3D9RenderSystem::preExtraThreadsStarted()
  2994. {
  2995. // nothing to do - D3D9 shares rendering context already
  2996. }
  2997. //---------------------------------------------------------------------
  2998. void D3D9RenderSystem::postExtraThreadsStarted()
  2999. {
  3000. // nothing to do - D3D9 shares rendering context already
  3001. }
  3002. //---------------------------------------------------------------------
  3003. D3D9ResourceManager* D3D9RenderSystem::getResourceManager()
  3004. {
  3005. return msD3D9RenderSystem->mResourceManager;
  3006. }
  3007. //---------------------------------------------------------------------
  3008. D3D9DeviceManager* D3D9RenderSystem::getDeviceManager()
  3009. {
  3010. return msD3D9RenderSystem->mDeviceManager;
  3011. }
  3012. //---------------------------------------------------------------------
  3013. RenderSystemCapabilities* D3D9RenderSystem::createRenderSystemCapabilities() const
  3014. {
  3015. return mRealCapabilities;
  3016. }
  3017. //---------------------------------------------------------------------
  3018. unsigned int D3D9RenderSystem::getDisplayMonitorCount() const
  3019. {
  3020. return mpD3D->GetAdapterCount();
  3021. }
  3022. //---------------------------------------------------------------------
  3023. void D3D9RenderSystem::notifyOnDeviceLost(D3D9Device* device)
  3024. {
  3025. // you need to stop the physics or game engines after this event
  3026. fireEvent("DeviceLost");
  3027. }
  3028. //---------------------------------------------------------------------
  3029. void D3D9RenderSystem::notifyOnDeviceReset(D3D9Device* device)
  3030. {
  3031. // Reset state attributes.
  3032. mVertexProgramBound = false;
  3033. mFragmentProgramBound = false;
  3034. mLastVertexSourceCount = 0;
  3035. // Restore previous active device.
  3036. // Invalidate active view port.
  3037. mActiveViewport = NULL;
  3038. // Reset the texture stages, they will need to be rebound
  3039. for (size_t i = 0; i < CM_MAX_TEXTURE_LAYERS; ++i)
  3040. _setTexture(i, false, TexturePtr());
  3041. fireEvent("DeviceRestored");
  3042. }
  3043. //---------------------------------------------------------------------
  3044. bool D3D9RenderSystem::ZBufferIdentifierComparator::operator()( const ZBufferIdentifier& z0, const ZBufferIdentifier& z1 ) const
  3045. {
  3046. if (z0.device < z1.device)
  3047. return true;
  3048. if (z0.device == z1.device)
  3049. {
  3050. if (z0.format < z1.format)
  3051. return true;
  3052. if (z0.format == z1.format)
  3053. {
  3054. if (z0.multisampleType < z1.multisampleType)
  3055. return true;
  3056. }
  3057. }
  3058. return false;
  3059. }
  3060. //---------------------------------------------------------------------
  3061. void D3D9RenderSystem::determineFSAASettings(IDirect3DDevice9* d3d9Device,
  3062. size_t fsaa, const String& fsaaHint, D3DFORMAT d3dPixelFormat,
  3063. bool fullScreen, D3DMULTISAMPLE_TYPE *outMultisampleType, DWORD *outMultisampleQuality)
  3064. {
  3065. bool ok = false;
  3066. bool qualityHint = fsaaHint.find("Quality") != String::npos;
  3067. size_t origFSAA = fsaa;
  3068. D3D9DriverList* driverList = getDirect3DDrivers();
  3069. D3D9Driver* deviceDriver = mActiveD3DDriver;
  3070. D3D9Device* device = mDeviceManager->getDeviceFromD3D9Device(d3d9Device);
  3071. for (UINT32 i = 0; i < driverList->count(); ++i)
  3072. {
  3073. D3D9Driver* currDriver = driverList->item(i);
  3074. if (currDriver->getAdapterNumber() == device->getAdapterNumber())
  3075. {
  3076. deviceDriver = currDriver;
  3077. break;
  3078. }
  3079. }
  3080. bool tryCSAA = false;
  3081. // NVIDIA, prefer CSAA if available for 8+
  3082. // it would be tempting to use getCapabilities()->getVendor() == GPU_NVIDIA but
  3083. // if this is the first window, caps will not be initialised yet
  3084. if (deviceDriver->getAdapterIdentifier().VendorId == 0x10DE &&
  3085. fsaa >= 8)
  3086. {
  3087. tryCSAA = true;
  3088. }
  3089. while (!ok)
  3090. {
  3091. // Deal with special cases
  3092. if (tryCSAA)
  3093. {
  3094. // see http://developer.nvidia.com/object/coverage-sampled-aa.html
  3095. switch(fsaa)
  3096. {
  3097. case 8:
  3098. if (qualityHint)
  3099. {
  3100. *outMultisampleType = D3DMULTISAMPLE_8_SAMPLES;
  3101. *outMultisampleQuality = 0;
  3102. }
  3103. else
  3104. {
  3105. *outMultisampleType = D3DMULTISAMPLE_4_SAMPLES;
  3106. *outMultisampleQuality = 2;
  3107. }
  3108. break;
  3109. case 16:
  3110. if (qualityHint)
  3111. {
  3112. *outMultisampleType = D3DMULTISAMPLE_8_SAMPLES;
  3113. *outMultisampleQuality = 2;
  3114. }
  3115. else
  3116. {
  3117. *outMultisampleType = D3DMULTISAMPLE_4_SAMPLES;
  3118. *outMultisampleQuality = 4;
  3119. }
  3120. break;
  3121. }
  3122. }
  3123. else // !CSAA
  3124. {
  3125. *outMultisampleType = (D3DMULTISAMPLE_TYPE)fsaa;
  3126. *outMultisampleQuality = 0;
  3127. }
  3128. HRESULT hr;
  3129. DWORD outQuality;
  3130. hr = mpD3D->CheckDeviceMultiSampleType(
  3131. deviceDriver->getAdapterNumber(),
  3132. D3DDEVTYPE_HAL,
  3133. d3dPixelFormat,
  3134. fullScreen,
  3135. *outMultisampleType,
  3136. &outQuality);
  3137. if (SUCCEEDED(hr) &&
  3138. (!tryCSAA || outQuality > *outMultisampleQuality))
  3139. {
  3140. ok = true;
  3141. }
  3142. else
  3143. {
  3144. // downgrade
  3145. if (tryCSAA && fsaa == 8)
  3146. {
  3147. // for CSAA, we'll try downgrading with quality mode at all samples.
  3148. // then try without quality, then drop CSAA
  3149. if (qualityHint)
  3150. {
  3151. // drop quality first
  3152. qualityHint = false;
  3153. }
  3154. else
  3155. {
  3156. // drop CSAA entirely
  3157. tryCSAA = false;
  3158. }
  3159. // return to original requested samples
  3160. fsaa = origFSAA;
  3161. }
  3162. else
  3163. {
  3164. // drop samples
  3165. --fsaa;
  3166. if (fsaa == 1)
  3167. {
  3168. // ran out of options, no FSAA
  3169. fsaa = 0;
  3170. ok = true;
  3171. }
  3172. }
  3173. }
  3174. } // while !ok
  3175. }
  3176. }