CmD3D9RenderSystem.cpp 84 KB

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