CmD3D9RenderSystem.cpp 123 KB

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