OgreD3D9RenderSystem.cpp 134 KB

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