CmD3D9RenderSystem.cpp 128 KB

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