BsD3D9RenderSystem.cpp 72 KB

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