CmD3D9RenderSystem.cpp 74 KB

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