BsD3D9RenderSystem.cpp 69 KB

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