CmD3D9RenderSystem.cpp 84 KB

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