CmD3D9RenderSystem.cpp 95 KB

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