renderer_d3d9.cpp 84 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955
  1. /*
  2. * Copyright 2011-2013 Branimir Karadzic. All rights reserved.
  3. * License: http://www.opensource.org/licenses/BSD-2-Clause
  4. */
  5. #include "bgfx_p.h"
  6. #if BGFX_CONFIG_RENDERER_DIRECT3D9
  7. # include "renderer_d3d9.h"
  8. namespace bgfx
  9. {
  10. static wchar_t s_viewNameW[BGFX_CONFIG_MAX_VIEWS][256];
  11. static const D3DPRIMITIVETYPE s_primType[] =
  12. {
  13. D3DPT_TRIANGLELIST,
  14. D3DPT_LINELIST,
  15. D3DPT_POINTLIST,
  16. };
  17. static const D3DMULTISAMPLE_TYPE s_checkMsaa[] =
  18. {
  19. D3DMULTISAMPLE_NONE,
  20. D3DMULTISAMPLE_2_SAMPLES,
  21. D3DMULTISAMPLE_4_SAMPLES,
  22. D3DMULTISAMPLE_8_SAMPLES,
  23. D3DMULTISAMPLE_16_SAMPLES,
  24. };
  25. static Msaa s_msaa[] =
  26. {
  27. { D3DMULTISAMPLE_NONE, 0 },
  28. { D3DMULTISAMPLE_2_SAMPLES, 0 },
  29. { D3DMULTISAMPLE_4_SAMPLES, 0 },
  30. { D3DMULTISAMPLE_8_SAMPLES, 0 },
  31. { D3DMULTISAMPLE_16_SAMPLES, 0 },
  32. };
  33. struct Blend
  34. {
  35. D3DBLEND m_src;
  36. D3DBLEND m_dst;
  37. bool m_factor;
  38. };
  39. static const Blend s_blendFactor[] =
  40. {
  41. { (D3DBLEND)0, (D3DBLEND)0, false }, // ignored
  42. { D3DBLEND_ZERO, D3DBLEND_ZERO, false },
  43. { D3DBLEND_ONE, D3DBLEND_ONE, false },
  44. { D3DBLEND_SRCCOLOR, D3DBLEND_SRCCOLOR, false },
  45. { D3DBLEND_INVSRCCOLOR, D3DBLEND_INVSRCCOLOR, false },
  46. { D3DBLEND_SRCALPHA, D3DBLEND_SRCALPHA, false },
  47. { D3DBLEND_INVSRCALPHA, D3DBLEND_INVSRCALPHA, false },
  48. { D3DBLEND_DESTALPHA, D3DBLEND_DESTALPHA, false },
  49. { D3DBLEND_INVDESTALPHA, D3DBLEND_INVDESTALPHA, false },
  50. { D3DBLEND_DESTCOLOR, D3DBLEND_DESTCOLOR, false },
  51. { D3DBLEND_INVDESTCOLOR, D3DBLEND_INVDESTCOLOR, false },
  52. { D3DBLEND_SRCALPHASAT, D3DBLEND_ONE, false },
  53. { D3DBLEND_BLENDFACTOR, D3DBLEND_BLENDFACTOR, true },
  54. { D3DBLEND_INVBLENDFACTOR, D3DBLEND_INVBLENDFACTOR, true },
  55. };
  56. static const D3DBLENDOP s_blendEquation[] =
  57. {
  58. D3DBLENDOP_ADD,
  59. D3DBLENDOP_SUBTRACT,
  60. D3DBLENDOP_REVSUBTRACT,
  61. D3DBLENDOP_MIN,
  62. D3DBLENDOP_MAX,
  63. };
  64. static const D3DCMPFUNC s_depthFunc[] =
  65. {
  66. (D3DCMPFUNC)0, // ignored
  67. D3DCMP_LESS,
  68. D3DCMP_LESSEQUAL,
  69. D3DCMP_EQUAL,
  70. D3DCMP_GREATEREQUAL,
  71. D3DCMP_GREATER,
  72. D3DCMP_NOTEQUAL,
  73. D3DCMP_NEVER,
  74. D3DCMP_ALWAYS,
  75. };
  76. static const D3DCMPFUNC s_stencilFunc[] =
  77. {
  78. (D3DCMPFUNC)0, // ignored
  79. D3DCMP_LESS,
  80. D3DCMP_LESSEQUAL,
  81. D3DCMP_EQUAL,
  82. D3DCMP_GREATEREQUAL,
  83. D3DCMP_GREATER,
  84. D3DCMP_NOTEQUAL,
  85. D3DCMP_NEVER,
  86. D3DCMP_ALWAYS,
  87. };
  88. static const D3DSTENCILOP s_stencilOp[] =
  89. {
  90. D3DSTENCILOP_ZERO,
  91. D3DSTENCILOP_KEEP,
  92. D3DSTENCILOP_REPLACE,
  93. D3DSTENCILOP_INCR,
  94. D3DSTENCILOP_INCRSAT,
  95. D3DSTENCILOP_DECR,
  96. D3DSTENCILOP_DECRSAT,
  97. D3DSTENCILOP_INVERT,
  98. };
  99. static const D3DRENDERSTATETYPE s_stencilFuncRs[] =
  100. {
  101. D3DRS_STENCILFUNC,
  102. D3DRS_CCW_STENCILFUNC,
  103. };
  104. static const D3DRENDERSTATETYPE s_stencilFailRs[] =
  105. {
  106. D3DRS_STENCILFAIL,
  107. D3DRS_CCW_STENCILFAIL,
  108. };
  109. static const D3DRENDERSTATETYPE s_stencilZFailRs[] =
  110. {
  111. D3DRS_STENCILZFAIL,
  112. D3DRS_CCW_STENCILZFAIL,
  113. };
  114. static const D3DRENDERSTATETYPE s_stencilZPassRs[] =
  115. {
  116. D3DRS_STENCILPASS,
  117. D3DRS_CCW_STENCILPASS,
  118. };
  119. static const D3DCULL s_cullMode[] =
  120. {
  121. D3DCULL_NONE,
  122. D3DCULL_CW,
  123. D3DCULL_CCW,
  124. };
  125. static const D3DFORMAT s_checkColorFormats[] =
  126. {
  127. D3DFMT_UNKNOWN,
  128. D3DFMT_A8R8G8B8, D3DFMT_UNKNOWN,
  129. D3DFMT_R32F, D3DFMT_R16F, D3DFMT_G16R16, D3DFMT_A8R8G8B8, D3DFMT_UNKNOWN,
  130. D3DFMT_UNKNOWN, // terminator
  131. };
  132. static D3DFORMAT s_colorFormat[] =
  133. {
  134. D3DFMT_UNKNOWN, // ignored
  135. D3DFMT_A8R8G8B8,
  136. D3DFMT_A2B10G10R10,
  137. D3DFMT_A16B16G16R16,
  138. D3DFMT_A16B16G16R16F,
  139. D3DFMT_R16F,
  140. D3DFMT_R32F,
  141. };
  142. static const D3DFORMAT s_depthFormat[] =
  143. {
  144. D3DFMT_UNKNOWN, // ignored
  145. D3DFMT_D16, // D16
  146. D3DFMT_D24X8, // D24
  147. D3DFMT_D24S8, // D24S8
  148. D3DFMT_D32, // D32
  149. D3DFMT_DF16, // D16F
  150. D3DFMT_DF24, // D24F
  151. D3DFMT_D32F_LOCKABLE, // D32F
  152. #if defined(D3D_DISABLE_9EX)
  153. D3DFMT_UNKNOWN, // D0S8
  154. #else
  155. D3DFMT_S8_LOCKABLE, // D0S8
  156. #endif // defined(D3D_DISABLE_9EX)
  157. };
  158. static const D3DTEXTUREADDRESS s_textureAddress[] =
  159. {
  160. D3DTADDRESS_WRAP,
  161. D3DTADDRESS_MIRROR,
  162. D3DTADDRESS_CLAMP,
  163. };
  164. static const D3DTEXTUREFILTERTYPE s_textureFilter[] =
  165. {
  166. D3DTEXF_LINEAR,
  167. D3DTEXF_POINT,
  168. D3DTEXF_ANISOTROPIC,
  169. };
  170. struct TextureFormatInfo
  171. {
  172. D3DFORMAT m_fmt;
  173. };
  174. static TextureFormatInfo s_textureFormat[TextureFormat::Count] =
  175. {
  176. { D3DFMT_DXT1 }, // BC1
  177. { D3DFMT_DXT3 }, // BC2
  178. { D3DFMT_DXT5 }, // BC3
  179. { D3DFMT_UNKNOWN }, // BC4
  180. { D3DFMT_UNKNOWN }, // BC5
  181. { D3DFMT_UNKNOWN }, // ETC1
  182. { D3DFMT_UNKNOWN }, // ETC2
  183. { D3DFMT_UNKNOWN }, // ETC2A
  184. { D3DFMT_UNKNOWN }, // ETC2A1
  185. { D3DFMT_UNKNOWN }, // PTC12
  186. { D3DFMT_UNKNOWN }, // PTC14
  187. { D3DFMT_UNKNOWN }, // PTC12A
  188. { D3DFMT_UNKNOWN }, // PTC14A
  189. { D3DFMT_UNKNOWN }, // PTC22
  190. { D3DFMT_UNKNOWN }, // PTC24
  191. { D3DFMT_UNKNOWN }, // Unknown
  192. { D3DFMT_L8 }, // L8
  193. { D3DFMT_A8R8G8B8 }, // BGRA8
  194. { D3DFMT_A16B16G16R16 }, // RGBA16
  195. { D3DFMT_A16B16G16R16F }, // RGBA16F
  196. { D3DFMT_R5G6B5 }, // R5G6B5
  197. { D3DFMT_A4R4G4B4 }, // RGBA4
  198. { D3DFMT_A1R5G5B5 }, // RGB5A1
  199. { D3DFMT_A2B10G10R10 }, // RGB10A2
  200. };
  201. static ExtendedFormat s_extendedFormats[ExtendedFormat::Count] =
  202. {
  203. { D3DFMT_ATI1, 0, D3DRTYPE_TEXTURE, false },
  204. { D3DFMT_ATI2, 0, D3DRTYPE_TEXTURE, false },
  205. { D3DFMT_DF16, D3DUSAGE_DEPTHSTENCIL, D3DRTYPE_SURFACE, false },
  206. { D3DFMT_DF24, D3DUSAGE_DEPTHSTENCIL, D3DRTYPE_SURFACE, false },
  207. { D3DFMT_INST, 0, D3DRTYPE_SURFACE, false },
  208. { D3DFMT_INTZ, D3DUSAGE_DEPTHSTENCIL, D3DRTYPE_SURFACE, false },
  209. { D3DFMT_NULL, D3DUSAGE_RENDERTARGET, D3DRTYPE_SURFACE, false },
  210. { D3DFMT_RESZ, D3DUSAGE_RENDERTARGET, D3DRTYPE_SURFACE, false },
  211. { D3DFMT_RAWZ, D3DUSAGE_DEPTHSTENCIL, D3DRTYPE_SURFACE, false },
  212. };
  213. static const GUID IID_IDirect3D9 = { 0x81bdcbca, 0x64d4, 0x426d, { 0xae, 0x8d, 0xad, 0x1, 0x47, 0xf4, 0x27, 0x5c } };
  214. static const GUID IID_IDirect3DDevice9Ex = { 0xb18b10ce, 0x2649, 0x405a, { 0x87, 0xf, 0x95, 0xf7, 0x77, 0xd4, 0x31, 0x3a } };
  215. struct RendererContext
  216. {
  217. RendererContext()
  218. : m_d3d9(NULL)
  219. , m_device(NULL)
  220. , m_backBufferColor(NULL)
  221. , m_backBufferDepthStencil(NULL)
  222. , m_captureTexture(NULL)
  223. , m_captureSurface(NULL)
  224. , m_captureResolve(NULL)
  225. , m_flags(BGFX_RESET_NONE)
  226. , m_initialized(false)
  227. , m_amd(false)
  228. , m_nvidia(false)
  229. , m_instancing(false)
  230. , m_rtMsaa(false)
  231. {
  232. m_rt.idx = invalidHandle;
  233. }
  234. void init()
  235. {
  236. D3DFORMAT adapterFormat = D3DFMT_X8R8G8B8;
  237. // http://msdn.microsoft.com/en-us/library/windows/desktop/bb172588%28v=vs.85%29.aspx
  238. memset(&m_params, 0, sizeof(m_params) );
  239. m_params.BackBufferWidth = BGFX_DEFAULT_WIDTH;
  240. m_params.BackBufferHeight = BGFX_DEFAULT_HEIGHT;
  241. m_params.BackBufferFormat = adapterFormat;
  242. m_params.BackBufferCount = 1;
  243. m_params.MultiSampleType = D3DMULTISAMPLE_NONE;
  244. m_params.MultiSampleQuality = 0;
  245. m_params.EnableAutoDepthStencil = TRUE;
  246. m_params.AutoDepthStencilFormat = D3DFMT_D24S8;
  247. m_params.Flags = D3DPRESENTFLAG_DISCARD_DEPTHSTENCIL;
  248. #if BX_PLATFORM_WINDOWS
  249. m_params.FullScreen_RefreshRateInHz = 0;
  250. m_params.PresentationInterval = D3DPRESENT_INTERVAL_IMMEDIATE;
  251. m_params.SwapEffect = D3DSWAPEFFECT_DISCARD;
  252. m_params.hDeviceWindow = g_bgfxHwnd;
  253. m_params.Windowed = true;
  254. RECT rect;
  255. GetWindowRect(g_bgfxHwnd, &rect);
  256. m_params.BackBufferWidth = rect.right-rect.left;
  257. m_params.BackBufferHeight = rect.bottom-rect.top;
  258. m_d3d9dll = bx::dlopen("d3d9.dll");
  259. BGFX_FATAL(NULL != m_d3d9dll, Fatal::UnableToInitialize, "Failed to load d3d9.dll.");
  260. #if BGFX_CONFIG_DEBUG_PIX
  261. m_D3DPERF_SetMarker = (D3DPERF_SetMarkerFunc)bx::dlsym(m_d3d9dll, "D3DPERF_SetMarker");
  262. m_D3DPERF_BeginEvent = (D3DPERF_BeginEventFunc)bx::dlsym(m_d3d9dll, "D3DPERF_BeginEvent");
  263. m_D3DPERF_EndEvent = (D3DPERF_EndEventFunc)bx::dlsym(m_d3d9dll, "D3DPERF_EndEvent");
  264. BX_CHECK(NULL != m_D3DPERF_SetMarker
  265. && NULL != m_D3DPERF_BeginEvent
  266. && NULL != m_D3DPERF_EndEvent
  267. , "Failed to initialize PIX events."
  268. );
  269. #endif // BGFX_CONFIG_DEBUG_PIX
  270. #if BGFX_CONFIG_RENDERER_DIRECT3D9EX
  271. m_d3d9ex = NULL;
  272. Direct3DCreate9ExFn direct3DCreate9Ex = (Direct3DCreate9ExFn)bx::dlsym(m_d3d9dll, "Direct3DCreate9Ex");
  273. if (NULL != direct3DCreate9Ex)
  274. {
  275. direct3DCreate9Ex(D3D_SDK_VERSION, &m_d3d9ex);
  276. DX_CHECK(m_d3d9ex->QueryInterface(IID_IDirect3D9, (void**)&m_d3d9) );
  277. m_pool = D3DPOOL_DEFAULT;
  278. }
  279. else
  280. #endif // BGFX_CONFIG_RENDERER_DIRECT3D9EX
  281. {
  282. Direct3DCreate9Fn direct3DCreate9 = (Direct3DCreate9Fn)bx::dlsym(m_d3d9dll, "Direct3DCreate9");
  283. BGFX_FATAL(NULL != direct3DCreate9, Fatal::UnableToInitialize, "Function Direct3DCreate9 not found.");
  284. m_d3d9 = direct3DCreate9(D3D_SDK_VERSION);
  285. m_pool = D3DPOOL_MANAGED;
  286. }
  287. BGFX_FATAL(m_d3d9, Fatal::UnableToInitialize, "Unable to create Direct3D.");
  288. m_adapter = D3DADAPTER_DEFAULT;
  289. m_deviceType = D3DDEVTYPE_HAL;
  290. uint32_t adapterCount = m_d3d9->GetAdapterCount();
  291. for (uint32_t ii = 0; ii < adapterCount; ++ii)
  292. {
  293. D3DADAPTER_IDENTIFIER9 identifier;
  294. HRESULT hr = m_d3d9->GetAdapterIdentifier(ii, 0, &identifier);
  295. if (SUCCEEDED(hr) )
  296. {
  297. BX_TRACE("Adapter #%d", ii);
  298. BX_TRACE("\tDriver: %s", identifier.Driver);
  299. BX_TRACE("\tDescription: %s", identifier.Description);
  300. BX_TRACE("\tDeviceName: %s", identifier.DeviceName);
  301. BX_TRACE("\tVendorId: 0x%08x, DeviceId: 0x%08x, SubSysId: 0x%08x, Revision: 0x%08x"
  302. , identifier.VendorId
  303. , identifier.DeviceId
  304. , identifier.SubSysId
  305. , identifier.Revision
  306. );
  307. #if BGFX_CONFIG_DEBUG_PERFHUD
  308. if (0 != strstr(identifier.Description, "PerfHUD") )
  309. {
  310. m_adapter = ii;
  311. m_deviceType = D3DDEVTYPE_REF;
  312. }
  313. #endif // BGFX_CONFIG_DEBUG_PERFHUD
  314. }
  315. }
  316. DX_CHECK(m_d3d9->GetAdapterIdentifier(m_adapter, 0, &m_identifier) );
  317. m_amd = m_identifier.VendorId == 0x1002;
  318. m_nvidia = m_identifier.VendorId == 0x10de;
  319. uint32_t behaviorFlags[] =
  320. {
  321. D3DCREATE_HARDWARE_VERTEXPROCESSING|D3DCREATE_PUREDEVICE|D3DCREATE_FPU_PRESERVE,
  322. D3DCREATE_MIXED_VERTEXPROCESSING|D3DCREATE_FPU_PRESERVE,
  323. D3DCREATE_SOFTWARE_VERTEXPROCESSING|D3DCREATE_FPU_PRESERVE,
  324. };
  325. for (uint32_t ii = 0; ii < BX_COUNTOF(behaviorFlags) && NULL == m_device; ++ii)
  326. {
  327. #if 0 // BGFX_CONFIG_RENDERER_DIRECT3D9EX
  328. DX_CHECK(m_d3d9->CreateDeviceEx(m_adapter
  329. , m_deviceType
  330. , g_bgfxHwnd
  331. , behaviorFlags[ii]
  332. , &m_params
  333. , NULL
  334. , &m_device
  335. ) );
  336. #else
  337. DX_CHECK(m_d3d9->CreateDevice(m_adapter
  338. , m_deviceType
  339. , g_bgfxHwnd
  340. , behaviorFlags[ii]
  341. , &m_params
  342. , &m_device
  343. ) );
  344. #endif // BGFX_CONFIG_RENDERER_DIRECT3D9EX
  345. }
  346. BGFX_FATAL(m_device, Fatal::UnableToInitialize, "Unable to create Direct3D9 device.");
  347. #if BGFX_CONFIG_RENDERER_DIRECT3D9EX
  348. if (NULL != m_d3d9ex)
  349. {
  350. DX_CHECK(m_device->QueryInterface(IID_IDirect3DDevice9Ex, (void**)&m_deviceEx) );
  351. }
  352. #endif // BGFX_CONFIG_RENDERER_DIRECT3D9EX
  353. DX_CHECK(m_device->GetDeviceCaps(&m_caps) );
  354. // For shit GPUs that can create DX9 device but can't do simple stuff. GTFO!
  355. BGFX_FATAL( (D3DPTEXTURECAPS_SQUAREONLY & m_caps.TextureCaps) == 0, Fatal::MinimumRequiredSpecs, "D3DPTEXTURECAPS_SQUAREONLY");
  356. BGFX_FATAL( (D3DPTEXTURECAPS_MIPMAP & m_caps.TextureCaps) == D3DPTEXTURECAPS_MIPMAP, Fatal::MinimumRequiredSpecs, "D3DPTEXTURECAPS_MIPMAP");
  357. BGFX_FATAL( (D3DPTEXTURECAPS_ALPHA & m_caps.TextureCaps) == D3DPTEXTURECAPS_ALPHA, Fatal::MinimumRequiredSpecs, "D3DPTEXTURECAPS_ALPHA");
  358. BGFX_FATAL(m_caps.VertexShaderVersion >= D3DVS_VERSION(2, 0) && m_caps.PixelShaderVersion >= D3DPS_VERSION(2, 1)
  359. , Fatal::MinimumRequiredSpecs
  360. , "Shader Model Version (vs: %x, ps: %x)."
  361. , m_caps.VertexShaderVersion
  362. , m_caps.PixelShaderVersion
  363. );
  364. BX_TRACE("Max vertex shader 3.0 instr. slots: %d", m_caps.MaxVertexShader30InstructionSlots);
  365. BX_TRACE("Max vertex shader constants: %d", m_caps.MaxVertexShaderConst);
  366. BX_TRACE("Max fragment shader 2.0 instr. slots: %d", m_caps.PS20Caps.NumInstructionSlots);
  367. BX_TRACE("Max fragment shader 3.0 instr. slots: %d", m_caps.MaxPixelShader30InstructionSlots);
  368. g_caps.emulated &= ~( 0
  369. | BGFX_CAPS_TEXTURE_FORMAT_BC1
  370. | BGFX_CAPS_TEXTURE_FORMAT_BC2
  371. | BGFX_CAPS_TEXTURE_FORMAT_BC3
  372. );
  373. g_caps.supported |= ( 0
  374. | BGFX_CAPS_TEXTURE_3D
  375. | BGFX_CAPS_VERTEX_ATTRIB_HALF
  376. | BGFX_CAPS_FRAGMENT_DEPTH
  377. );
  378. g_caps.maxTextureSize = bx::uint32_min(m_caps.MaxTextureWidth, m_caps.MaxTextureHeight);
  379. #if BGFX_CONFIG_RENDERER_USE_EXTENSIONS
  380. BX_TRACE("Extended formats:");
  381. for (uint32_t ii = 0; ii < ExtendedFormat::Count; ++ii)
  382. {
  383. ExtendedFormat& fmt = s_extendedFormats[ii];
  384. fmt.m_supported = SUCCEEDED(m_d3d9->CheckDeviceFormat(m_adapter, m_deviceType, adapterFormat, fmt.m_usage, fmt.m_type, fmt.m_fmt) );
  385. const char* fourcc = (const char*)&fmt.m_fmt;
  386. BX_TRACE("\t%2d: %c%c%c%c %s", ii, fourcc[0], fourcc[1], fourcc[2], fourcc[3], fmt.m_supported ? "supported" : "");
  387. BX_UNUSED(fourcc);
  388. }
  389. m_instancing = false
  390. || s_extendedFormats[ExtendedFormat::Inst].m_supported
  391. || (m_caps.VertexShaderVersion >= D3DVS_VERSION(3, 0) )
  392. ;
  393. if (m_amd
  394. && s_extendedFormats[ExtendedFormat::Inst].m_supported)
  395. {
  396. // AMD only
  397. m_device->SetRenderState(D3DRS_POINTSIZE, D3DFMT_INST);
  398. }
  399. s_textureFormat[TextureFormat::BC4].m_fmt = s_extendedFormats[ExtendedFormat::Ati1].m_supported ? D3DFMT_ATI1 : D3DFMT_UNKNOWN;
  400. s_textureFormat[TextureFormat::BC5].m_fmt = s_extendedFormats[ExtendedFormat::Ati2].m_supported ? D3DFMT_ATI2 : D3DFMT_UNKNOWN;
  401. g_caps.emulated &= ~( 0
  402. | (D3DFMT_UNKNOWN != s_textureFormat[TextureFormat::BC4].m_fmt ? BGFX_CAPS_TEXTURE_FORMAT_BC4 : 0)
  403. | (D3DFMT_UNKNOWN != s_textureFormat[TextureFormat::BC5].m_fmt ? BGFX_CAPS_TEXTURE_FORMAT_BC5 : 0)
  404. );
  405. g_caps.supported |= m_instancing ? BGFX_CAPS_INSTANCING : 0;
  406. #endif // BGFX_CONFIG_RENDERER_USE_EXTENSIONS
  407. uint32_t index = 1;
  408. for (const D3DFORMAT* fmt = &s_checkColorFormats[index]; *fmt != D3DFMT_UNKNOWN; ++fmt, ++index)
  409. {
  410. for (; *fmt != D3DFMT_UNKNOWN; ++fmt)
  411. {
  412. if (SUCCEEDED(m_d3d9->CheckDeviceFormat(m_adapter, m_deviceType, adapterFormat, D3DUSAGE_RENDERTARGET, D3DRTYPE_TEXTURE, *fmt) ) )
  413. {
  414. s_colorFormat[index] = *fmt;
  415. break;
  416. }
  417. }
  418. for (; *fmt != D3DFMT_UNKNOWN; ++fmt);
  419. }
  420. m_fmtDepth = D3DFMT_D24S8;
  421. #elif BX_PLATFORM_XBOX360
  422. m_params.PresentationInterval = D3DPRESENT_INTERVAL_ONE;
  423. m_params.DisableAutoBackBuffer = FALSE;
  424. m_params.DisableAutoFrontBuffer = FALSE;
  425. m_params.FrontBufferFormat = D3DFMT_X8R8G8B8;
  426. m_params.FrontBufferColorSpace = D3DCOLORSPACE_RGB;
  427. m_d3d9 = Direct3DCreate9(D3D_SDK_VERSION);
  428. BX_TRACE("Creating D3D9 %p", m_d3d9);
  429. XVIDEO_MODE videoMode;
  430. XGetVideoMode(&videoMode);
  431. if (!videoMode.fIsWideScreen)
  432. {
  433. m_params.Flags |= D3DPRESENTFLAG_NO_LETTERBOX;
  434. }
  435. BX_TRACE("Creating device");
  436. DX_CHECK(m_d3d9->CreateDevice(m_adapter
  437. , m_deviceType
  438. , NULL
  439. , D3DCREATE_HARDWARE_VERTEXPROCESSING|D3DCREATE_BUFFER_2_FRAMES
  440. , &m_params
  441. , &m_device
  442. ) );
  443. BX_TRACE("Device %p", m_device);
  444. m_fmtDepth = D3DFMT_D24FS8;
  445. #endif // BX_PLATFORM_WINDOWS
  446. postReset();
  447. m_initialized = true;
  448. }
  449. void shutdown()
  450. {
  451. preReset();
  452. for (uint32_t ii = 0; ii < BX_COUNTOF(m_indexBuffers); ++ii)
  453. {
  454. m_indexBuffers[ii].destroy();
  455. }
  456. for (uint32_t ii = 0; ii < BX_COUNTOF(m_vertexBuffers); ++ii)
  457. {
  458. m_vertexBuffers[ii].destroy();
  459. }
  460. for (uint32_t ii = 0; ii < BX_COUNTOF(m_vertexShaders); ++ii)
  461. {
  462. m_vertexShaders[ii].destroy();
  463. }
  464. for (uint32_t ii = 0; ii < BX_COUNTOF(m_fragmentShaders); ++ii)
  465. {
  466. m_fragmentShaders[ii].destroy();
  467. }
  468. for (uint32_t ii = 0; ii < BX_COUNTOF(m_textures); ++ii)
  469. {
  470. m_textures[ii].destroy();
  471. }
  472. for (uint32_t ii = 0; ii < BX_COUNTOF(m_vertexDecls); ++ii)
  473. {
  474. m_vertexDecls[ii].destroy();
  475. }
  476. for (uint32_t ii = 0; ii < BX_COUNTOF(m_renderTargets); ++ii)
  477. {
  478. m_renderTargets[ii].destroy();
  479. }
  480. #if BGFX_CONFIG_RENDERER_DIRECT3D9EX
  481. if (NULL != m_d3d9ex)
  482. {
  483. DX_RELEASE(m_deviceEx, 1);
  484. DX_RELEASE(m_device, 0);
  485. DX_RELEASE(m_d3d9, 1);
  486. DX_RELEASE(m_d3d9ex, 0);
  487. }
  488. else
  489. #endif // BGFX_CONFIG_RENDERER_DIRECT3D9EX
  490. {
  491. DX_RELEASE(m_device, 0);
  492. DX_RELEASE(m_d3d9, 0);
  493. }
  494. #if BX_PLATFORM_WINDOWS
  495. bx::dlclose(m_d3d9dll);
  496. #endif // BX_PLATFORM_WINDOWS
  497. m_initialized = false;
  498. }
  499. void updateMsaa()
  500. {
  501. for (uint32_t ii = 1, last = 0; ii < BX_COUNTOF(s_checkMsaa); ++ii)
  502. {
  503. D3DMULTISAMPLE_TYPE msaa = s_checkMsaa[ii];
  504. DWORD quality;
  505. HRESULT hr = m_d3d9->CheckDeviceMultiSampleType(m_adapter
  506. , m_deviceType
  507. , m_params.BackBufferFormat
  508. , m_params.Windowed
  509. , msaa
  510. , &quality
  511. );
  512. if (SUCCEEDED(hr) )
  513. {
  514. s_msaa[ii].m_type = msaa;
  515. s_msaa[ii].m_quality = bx::uint32_imax(0, quality-1);
  516. last = ii;
  517. }
  518. else
  519. {
  520. s_msaa[ii] = s_msaa[last];
  521. }
  522. }
  523. }
  524. void updateResolution(const Resolution& _resolution)
  525. {
  526. if (m_params.BackBufferWidth != _resolution.m_width
  527. || m_params.BackBufferHeight != _resolution.m_height
  528. || m_flags != _resolution.m_flags)
  529. {
  530. m_flags = _resolution.m_flags;
  531. m_textVideoMem.resize(false, _resolution.m_width, _resolution.m_height);
  532. m_textVideoMem.clear();
  533. #if BX_PLATFORM_WINDOWS
  534. D3DDEVICE_CREATION_PARAMETERS dcp;
  535. DX_CHECK(m_device->GetCreationParameters(&dcp) );
  536. D3DDISPLAYMODE dm;
  537. DX_CHECK(m_d3d9->GetAdapterDisplayMode(dcp.AdapterOrdinal, &dm) );
  538. m_params.BackBufferFormat = dm.Format;
  539. #endif // BX_PLATFORM_WINDOWS
  540. m_params.BackBufferWidth = _resolution.m_width;
  541. m_params.BackBufferHeight = _resolution.m_height;
  542. m_params.FullScreen_RefreshRateInHz = BGFX_RESET_FULLSCREEN == (m_flags&BGFX_RESET_FULLSCREEN_MASK) ? 60 : 0;
  543. m_params.PresentationInterval = !!(m_flags&BGFX_RESET_VSYNC) ? D3DPRESENT_INTERVAL_ONE : D3DPRESENT_INTERVAL_IMMEDIATE;
  544. updateMsaa();
  545. Msaa& msaa = s_msaa[(m_flags&BGFX_RESET_MSAA_MASK)>>BGFX_RESET_MSAA_SHIFT];
  546. m_params.MultiSampleType = msaa.m_type;
  547. m_params.MultiSampleQuality = msaa.m_quality;
  548. preReset();
  549. DX_CHECK(m_device->Reset(&m_params) );
  550. postReset();
  551. }
  552. }
  553. void setRenderTarget(RenderTargetHandle _rt, bool _msaa = true)
  554. {
  555. if (!isValid(_rt) )
  556. {
  557. DX_CHECK(m_device->SetRenderTarget(0, m_backBufferColor) );
  558. DX_CHECK(m_device->SetDepthStencilSurface(m_backBufferDepthStencil) );
  559. }
  560. else
  561. {
  562. RenderTarget& renderTarget = m_renderTargets[_rt.idx];
  563. if (NULL != renderTarget.m_rt)
  564. {
  565. DX_CHECK(m_device->SetRenderTarget(0, renderTarget.m_rt) );
  566. }
  567. else
  568. {
  569. DX_CHECK(m_device->SetRenderTarget(0, renderTarget.m_color) );
  570. }
  571. DX_CHECK(m_device->SetDepthStencilSurface(NULL != renderTarget.m_depth ? renderTarget.m_depth : m_backBufferDepthStencil) );
  572. }
  573. if (isValid(m_rt)
  574. && m_rt.idx != _rt.idx
  575. && m_rtMsaa)
  576. {
  577. RenderTarget& renderTarget = m_renderTargets[m_rt.idx];
  578. if (!renderTarget.m_depthOnly
  579. && renderTarget.m_rt != NULL)
  580. {
  581. renderTarget.resolve();
  582. }
  583. }
  584. m_rt = _rt;
  585. m_rtMsaa = _msaa;
  586. }
  587. void setShaderConstantF(uint8_t _flags, uint16_t _regIndex, const float* _val, uint16_t _numRegs)
  588. {
  589. if (_flags&BGFX_UNIFORM_FRAGMENTBIT)
  590. {
  591. DX_CHECK(m_device->SetPixelShaderConstantF(_regIndex, _val, _numRegs) );
  592. }
  593. else
  594. {
  595. DX_CHECK(m_device->SetVertexShaderConstantF(_regIndex, _val, _numRegs) );
  596. }
  597. }
  598. void reset()
  599. {
  600. preReset();
  601. HRESULT hr;
  602. do
  603. {
  604. hr = m_device->Reset(&m_params);
  605. } while (FAILED(hr) );
  606. postReset();
  607. }
  608. bool isLost(HRESULT _hr) const
  609. {
  610. return D3DERR_DEVICELOST == _hr
  611. || D3DERR_DRIVERINTERNALERROR == _hr
  612. #if !defined(D3D_DISABLE_9EX)
  613. || D3DERR_DEVICEHUNG == _hr
  614. || D3DERR_DEVICEREMOVED == _hr
  615. #endif // !defined(D3D_DISABLE_9EX)
  616. ;
  617. }
  618. void flip()
  619. {
  620. if (NULL != m_device)
  621. {
  622. #if BGFX_CONFIG_RENDERER_DIRECT3D9EX
  623. if (NULL != m_deviceEx)
  624. {
  625. DX_CHECK(m_deviceEx->WaitForVBlank(0) );
  626. }
  627. #endif // BGFX_CONFIG_RENDERER_DIRECT3D9EX
  628. HRESULT hr;
  629. hr = m_device->Present(NULL, NULL, NULL, NULL);
  630. #if BX_PLATFORM_WINDOWS
  631. if (isLost(hr) )
  632. {
  633. do
  634. {
  635. do
  636. {
  637. hr = m_device->TestCooperativeLevel();
  638. }
  639. while (D3DERR_DEVICENOTRESET != hr);
  640. reset();
  641. hr = m_device->TestCooperativeLevel();
  642. }
  643. while (FAILED(hr) );
  644. }
  645. else if (FAILED(hr) )
  646. {
  647. BX_TRACE("Present failed with err 0x%08x.", hr);
  648. }
  649. #endif // BX_PLATFORM_
  650. }
  651. }
  652. void preReset()
  653. {
  654. invalidateSamplerState();
  655. for (uint32_t stage = 0; stage < BGFX_STATE_TEX_COUNT; ++stage)
  656. {
  657. DX_CHECK(m_device->SetTexture(stage, NULL) );
  658. }
  659. DX_CHECK(m_device->SetRenderTarget(0, m_backBufferColor) );
  660. DX_CHECK(m_device->SetDepthStencilSurface(m_backBufferDepthStencil) );
  661. DX_CHECK(m_device->SetVertexShader(NULL) );
  662. DX_CHECK(m_device->SetPixelShader(NULL) );
  663. DX_CHECK(m_device->SetStreamSource(0, NULL, 0, 0) );
  664. DX_CHECK(m_device->SetIndices(NULL) );
  665. DX_RELEASE(m_backBufferColor, 0);
  666. DX_RELEASE(m_backBufferDepthStencil, 0);
  667. capturePreReset();
  668. for (uint32_t ii = 0; ii < BX_COUNTOF(m_indexBuffers); ++ii)
  669. {
  670. m_indexBuffers[ii].preReset();
  671. }
  672. for (uint32_t ii = 0; ii < BX_COUNTOF(m_vertexBuffers); ++ii)
  673. {
  674. m_vertexBuffers[ii].preReset();
  675. }
  676. for (uint32_t ii = 0; ii < BX_COUNTOF(m_renderTargets); ++ii)
  677. {
  678. m_renderTargets[ii].preReset();
  679. }
  680. }
  681. void postReset()
  682. {
  683. DX_CHECK(m_device->GetBackBuffer(0, 0, D3DBACKBUFFER_TYPE_MONO, &m_backBufferColor) );
  684. DX_CHECK(m_device->GetDepthStencilSurface(&m_backBufferDepthStencil) );
  685. capturePostReset();
  686. for (uint32_t ii = 0; ii < BX_COUNTOF(m_indexBuffers); ++ii)
  687. {
  688. m_indexBuffers[ii].postReset();
  689. }
  690. for (uint32_t ii = 0; ii < BX_COUNTOF(m_vertexBuffers); ++ii)
  691. {
  692. m_vertexBuffers[ii].postReset();
  693. }
  694. for (uint32_t ii = 0; ii < BX_COUNTOF(m_renderTargets); ++ii)
  695. {
  696. m_renderTargets[ii].postReset();
  697. }
  698. }
  699. void invalidateSamplerState()
  700. {
  701. for (uint32_t stage = 0; stage < BGFX_STATE_TEX_COUNT; ++stage)
  702. {
  703. m_samplerFlags[stage] = UINT32_MAX;
  704. }
  705. }
  706. void setSamplerState(uint8_t _stage, uint32_t _flags)
  707. {
  708. const uint32_t flags = _flags&(~BGFX_TEXTURE_RESERVED_MASK);
  709. if (m_samplerFlags[_stage] != flags)
  710. {
  711. m_samplerFlags[_stage] = flags;
  712. IDirect3DDevice9* device = m_device;
  713. D3DTEXTUREADDRESS tau = s_textureAddress[(_flags&BGFX_TEXTURE_U_MASK)>>BGFX_TEXTURE_U_SHIFT];
  714. D3DTEXTUREADDRESS tav = s_textureAddress[(_flags&BGFX_TEXTURE_V_MASK)>>BGFX_TEXTURE_V_SHIFT];
  715. D3DTEXTUREADDRESS taw = s_textureAddress[(_flags&BGFX_TEXTURE_W_MASK)>>BGFX_TEXTURE_W_SHIFT];
  716. D3DTEXTUREFILTERTYPE minFilter = s_textureFilter[(_flags&BGFX_TEXTURE_MIN_MASK)>>BGFX_TEXTURE_MIN_SHIFT];
  717. D3DTEXTUREFILTERTYPE magFilter = s_textureFilter[(_flags&BGFX_TEXTURE_MAG_MASK)>>BGFX_TEXTURE_MAG_SHIFT];
  718. D3DTEXTUREFILTERTYPE mipFilter = s_textureFilter[(_flags&BGFX_TEXTURE_MIP_MASK)>>BGFX_TEXTURE_MIP_SHIFT];
  719. DX_CHECK(device->SetSamplerState(_stage, D3DSAMP_ADDRESSU, tau) );
  720. DX_CHECK(device->SetSamplerState(_stage, D3DSAMP_ADDRESSV, tav) );
  721. DX_CHECK(device->SetSamplerState(_stage, D3DSAMP_MINFILTER, minFilter) );
  722. DX_CHECK(device->SetSamplerState(_stage, D3DSAMP_MAGFILTER, magFilter) );
  723. DX_CHECK(device->SetSamplerState(_stage, D3DSAMP_MIPFILTER, mipFilter) );
  724. DX_CHECK(device->SetSamplerState(_stage, D3DSAMP_ADDRESSW, taw) );
  725. }
  726. }
  727. void capturePreReset()
  728. {
  729. if (NULL != m_captureSurface)
  730. {
  731. g_callback->captureEnd();
  732. }
  733. DX_RELEASE(m_captureSurface, 1);
  734. DX_RELEASE(m_captureTexture, 0);
  735. DX_RELEASE(m_captureResolve, 0);
  736. }
  737. void capturePostReset()
  738. {
  739. if (m_flags&BGFX_RESET_CAPTURE)
  740. {
  741. uint32_t width = m_params.BackBufferWidth;
  742. uint32_t height = m_params.BackBufferHeight;
  743. D3DFORMAT fmt = m_params.BackBufferFormat;
  744. DX_CHECK(m_device->CreateTexture(width
  745. , height
  746. , 1
  747. , 0
  748. , fmt
  749. , D3DPOOL_SYSTEMMEM
  750. , &m_captureTexture
  751. , NULL
  752. ) );
  753. DX_CHECK(m_captureTexture->GetSurfaceLevel(0
  754. , &m_captureSurface
  755. ) );
  756. if (m_params.MultiSampleType != D3DMULTISAMPLE_NONE)
  757. {
  758. DX_CHECK(m_device->CreateRenderTarget(width
  759. , height
  760. , fmt
  761. , D3DMULTISAMPLE_NONE
  762. , 0
  763. , false
  764. , &m_captureResolve
  765. , NULL
  766. ) );
  767. }
  768. g_callback->captureBegin(width, height, width*4, TextureFormat::BGRA8, false);
  769. }
  770. }
  771. void capture()
  772. {
  773. if (NULL != m_captureSurface)
  774. {
  775. IDirect3DSurface9* resolve = m_backBufferColor;
  776. if (NULL != m_captureResolve)
  777. {
  778. resolve = m_captureResolve;
  779. DX_CHECK(m_device->StretchRect(m_backBufferColor
  780. , 0
  781. , m_captureResolve
  782. , NULL
  783. , D3DTEXF_NONE
  784. ) );
  785. }
  786. HRESULT hr = m_device->GetRenderTargetData(resolve, m_captureSurface);
  787. if (SUCCEEDED(hr) )
  788. {
  789. D3DLOCKED_RECT rect;
  790. DX_CHECK(m_captureSurface->LockRect(&rect
  791. , NULL
  792. , D3DLOCK_NO_DIRTY_UPDATE|D3DLOCK_NOSYSLOCK|D3DLOCK_READONLY
  793. ) );
  794. g_callback->captureFrame(rect.pBits, m_params.BackBufferHeight*rect.Pitch);
  795. DX_CHECK(m_captureSurface->UnlockRect() );
  796. }
  797. }
  798. }
  799. void saveScreenShot(const char* _filePath)
  800. {
  801. #if BX_PLATFORM_WINDOWS
  802. IDirect3DSurface9* surface;
  803. D3DDEVICE_CREATION_PARAMETERS dcp;
  804. DX_CHECK(m_device->GetCreationParameters(&dcp) );
  805. D3DDISPLAYMODE dm;
  806. DX_CHECK(m_d3d9->GetAdapterDisplayMode(dcp.AdapterOrdinal, &dm) );
  807. DX_CHECK(m_device->CreateOffscreenPlainSurface(dm.Width
  808. , dm.Height
  809. , D3DFMT_A8R8G8B8
  810. , D3DPOOL_SCRATCH
  811. , &surface
  812. , NULL
  813. ) );
  814. DX_CHECK(m_device->GetFrontBufferData(0, surface) );
  815. D3DLOCKED_RECT rect;
  816. DX_CHECK(surface->LockRect(&rect
  817. , NULL
  818. , D3DLOCK_NO_DIRTY_UPDATE|D3DLOCK_NOSYSLOCK|D3DLOCK_READONLY
  819. ) );
  820. RECT rc;
  821. GetClientRect(g_bgfxHwnd, &rc);
  822. POINT point;
  823. point.x = rc.left;
  824. point.y = rc.top;
  825. ClientToScreen(g_bgfxHwnd, &point);
  826. uint8_t* data = (uint8_t*)rect.pBits;
  827. uint32_t bytesPerPixel = rect.Pitch/dm.Width;
  828. g_callback->screenShot(_filePath
  829. , m_params.BackBufferWidth
  830. , m_params.BackBufferHeight
  831. , rect.Pitch
  832. , &data[point.y*rect.Pitch+point.x*bytesPerPixel]
  833. , m_params.BackBufferHeight*rect.Pitch
  834. , false
  835. );
  836. DX_CHECK(surface->UnlockRect() );
  837. DX_RELEASE(surface, 0);
  838. #endif // BX_PLATFORM_WINDOWS
  839. }
  840. #if BX_PLATFORM_WINDOWS
  841. D3DCAPS9 m_caps;
  842. # if BGFX_CONFIG_DEBUG_PIX
  843. D3DPERF_SetMarkerFunc m_D3DPERF_SetMarker;
  844. D3DPERF_BeginEventFunc m_D3DPERF_BeginEvent;
  845. D3DPERF_EndEventFunc m_D3DPERF_EndEvent;
  846. # endif // BGFX_CONFIG_DEBUG_PIX
  847. #endif // BX_PLATFORM_WINDOWS
  848. #if BGFX_CONFIG_RENDERER_DIRECT3D9EX
  849. IDirect3D9Ex* m_d3d9ex;
  850. IDirect3DDevice9Ex* m_deviceEx;
  851. #endif // BGFX_CONFIG_RENDERER_DIRECT3D9EX
  852. IDirect3D9* m_d3d9;
  853. IDirect3DDevice9* m_device;
  854. D3DPOOL m_pool;
  855. IDirect3DSurface9* m_backBufferColor;
  856. IDirect3DSurface9* m_backBufferDepthStencil;
  857. IDirect3DTexture9* m_captureTexture;
  858. IDirect3DSurface9* m_captureSurface;
  859. IDirect3DSurface9* m_captureResolve;
  860. IDirect3DVertexDeclaration9* m_instanceDataDecls[BGFX_CONFIG_MAX_INSTANCE_DATA_COUNT];
  861. void* m_d3d9dll;
  862. uint32_t m_adapter;
  863. D3DDEVTYPE m_deviceType;
  864. D3DPRESENT_PARAMETERS m_params;
  865. uint32_t m_flags;
  866. D3DADAPTER_IDENTIFIER9 m_identifier;
  867. bool m_initialized;
  868. bool m_amd;
  869. bool m_nvidia;
  870. bool m_instancing;
  871. D3DFORMAT m_fmtDepth;
  872. IndexBuffer m_indexBuffers[BGFX_CONFIG_MAX_INDEX_BUFFERS];
  873. VertexBuffer m_vertexBuffers[BGFX_CONFIG_MAX_VERTEX_BUFFERS];
  874. Shader m_vertexShaders[BGFX_CONFIG_MAX_VERTEX_SHADERS];
  875. Shader m_fragmentShaders[BGFX_CONFIG_MAX_FRAGMENT_SHADERS];
  876. Program m_program[BGFX_CONFIG_MAX_PROGRAMS];
  877. Texture m_textures[BGFX_CONFIG_MAX_TEXTURES];
  878. VertexDeclaration m_vertexDecls[BGFX_CONFIG_MAX_VERTEX_DECLS];
  879. RenderTarget m_renderTargets[BGFX_CONFIG_MAX_RENDER_TARGETS];
  880. UniformRegistry m_uniformReg;
  881. void* m_uniforms[BGFX_CONFIG_MAX_UNIFORMS];
  882. uint32_t m_samplerFlags[BGFX_STATE_TEX_COUNT];
  883. Texture* m_updateTexture;
  884. uint8_t* m_updateTextureBits;
  885. uint32_t m_updateTexturePitch;
  886. uint8_t m_updateTextureSide;
  887. uint8_t m_updateTextureMip;
  888. TextVideoMem m_textVideoMem;
  889. RenderTargetHandle m_rt;
  890. bool m_rtMsaa;
  891. };
  892. static RendererContext* s_renderCtx;
  893. void IndexBuffer::create(uint32_t _size, void* _data)
  894. {
  895. m_size = _size;
  896. m_dynamic = NULL == _data;
  897. uint32_t usage = D3DUSAGE_WRITEONLY;
  898. D3DPOOL pool = s_renderCtx->m_pool;
  899. if (m_dynamic)
  900. {
  901. usage |= D3DUSAGE_DYNAMIC;
  902. pool = D3DPOOL_DEFAULT;
  903. }
  904. DX_CHECK(s_renderCtx->m_device->CreateIndexBuffer(m_size
  905. , usage
  906. , D3DFMT_INDEX16
  907. , pool
  908. , &m_ptr
  909. , NULL
  910. ) );
  911. if (NULL != _data)
  912. {
  913. update(0, _size, _data);
  914. }
  915. }
  916. void IndexBuffer::preReset()
  917. {
  918. if (m_dynamic)
  919. {
  920. DX_RELEASE(m_ptr, 0);
  921. }
  922. }
  923. void IndexBuffer::postReset()
  924. {
  925. if (m_dynamic)
  926. {
  927. DX_CHECK(s_renderCtx->m_device->CreateIndexBuffer(m_size
  928. , D3DUSAGE_WRITEONLY|D3DUSAGE_DYNAMIC
  929. , D3DFMT_INDEX16
  930. , D3DPOOL_DEFAULT
  931. , &m_ptr
  932. , NULL
  933. ) );
  934. }
  935. }
  936. void VertexBuffer::create(uint32_t _size, void* _data, VertexDeclHandle _declHandle)
  937. {
  938. m_size = _size;
  939. m_decl = _declHandle;
  940. m_dynamic = NULL == _data;
  941. uint32_t usage = D3DUSAGE_WRITEONLY;
  942. D3DPOOL pool = s_renderCtx->m_pool;
  943. if (m_dynamic)
  944. {
  945. usage |= D3DUSAGE_DYNAMIC;
  946. pool = D3DPOOL_DEFAULT;
  947. }
  948. DX_CHECK(s_renderCtx->m_device->CreateVertexBuffer(m_size
  949. , usage
  950. , 0
  951. , pool
  952. , &m_ptr
  953. , NULL
  954. ) );
  955. if (NULL != _data)
  956. {
  957. update(0, _size, _data);
  958. }
  959. }
  960. void VertexBuffer::preReset()
  961. {
  962. if (m_dynamic)
  963. {
  964. DX_RELEASE(m_ptr, 0);
  965. }
  966. }
  967. void VertexBuffer::postReset()
  968. {
  969. if (m_dynamic)
  970. {
  971. DX_CHECK(s_renderCtx->m_device->CreateVertexBuffer(m_size
  972. , D3DUSAGE_WRITEONLY|D3DUSAGE_DYNAMIC
  973. , 0
  974. , D3DPOOL_DEFAULT
  975. , &m_ptr
  976. , NULL
  977. ) );
  978. }
  979. }
  980. static const D3DVERTEXELEMENT9 s_attrib[Attrib::Count+1] =
  981. {
  982. { 0, 0, D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_POSITION, 0 },
  983. { 0, 0, D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_NORMAL, 0 },
  984. { 0, 0, D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TANGENT, 0 },
  985. { 0, 0, D3DDECLTYPE_UBYTE4, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_COLOR, 0 },
  986. { 0, 0, D3DDECLTYPE_UBYTE4, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_COLOR, 1 },
  987. { 0, 0, D3DDECLTYPE_UBYTE4, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_BLENDINDICES, 0 },
  988. { 0, 0, D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_BLENDWEIGHT, 0 },
  989. { 0, 0, D3DDECLTYPE_FLOAT2, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 0 },
  990. { 0, 0, D3DDECLTYPE_FLOAT2, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 1 },
  991. { 0, 0, D3DDECLTYPE_FLOAT2, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 2 },
  992. { 0, 0, D3DDECLTYPE_FLOAT2, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 3 },
  993. { 0, 0, D3DDECLTYPE_FLOAT2, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 4 },
  994. { 0, 0, D3DDECLTYPE_FLOAT2, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 5 },
  995. { 0, 0, D3DDECLTYPE_FLOAT2, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 6 },
  996. { 0, 0, D3DDECLTYPE_FLOAT2, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 7 },
  997. D3DDECL_END()
  998. };
  999. static const D3DDECLTYPE s_attribType[AttribType::Count][4][2] =
  1000. {
  1001. {
  1002. { D3DDECLTYPE_UBYTE4, D3DDECLTYPE_UBYTE4N },
  1003. { D3DDECLTYPE_UBYTE4, D3DDECLTYPE_UBYTE4N },
  1004. { D3DDECLTYPE_UBYTE4, D3DDECLTYPE_UBYTE4N },
  1005. { D3DDECLTYPE_UBYTE4, D3DDECLTYPE_UBYTE4N },
  1006. },
  1007. {
  1008. { D3DDECLTYPE_SHORT2, D3DDECLTYPE_SHORT2N },
  1009. { D3DDECLTYPE_SHORT2, D3DDECLTYPE_SHORT2N },
  1010. { D3DDECLTYPE_SHORT4, D3DDECLTYPE_SHORT4N },
  1011. { D3DDECLTYPE_SHORT4, D3DDECLTYPE_SHORT4N },
  1012. },
  1013. {
  1014. { D3DDECLTYPE_FLOAT16_2, D3DDECLTYPE_FLOAT16_2 },
  1015. { D3DDECLTYPE_FLOAT16_2, D3DDECLTYPE_FLOAT16_2 },
  1016. { D3DDECLTYPE_FLOAT16_4, D3DDECLTYPE_FLOAT16_4 },
  1017. { D3DDECLTYPE_FLOAT16_4, D3DDECLTYPE_FLOAT16_4 },
  1018. },
  1019. {
  1020. { D3DDECLTYPE_FLOAT1, D3DDECLTYPE_FLOAT1 },
  1021. { D3DDECLTYPE_FLOAT2, D3DDECLTYPE_FLOAT2 },
  1022. { D3DDECLTYPE_FLOAT3, D3DDECLTYPE_FLOAT3 },
  1023. { D3DDECLTYPE_FLOAT4, D3DDECLTYPE_FLOAT4 },
  1024. },
  1025. };
  1026. static D3DVERTEXELEMENT9* fillVertexDecl(D3DVERTEXELEMENT9* _out, const VertexDecl& _decl)
  1027. {
  1028. D3DVERTEXELEMENT9* elem = _out;
  1029. for (uint32_t attr = 0; attr < Attrib::Count; ++attr)
  1030. {
  1031. if (0xff != _decl.m_attributes[attr])
  1032. {
  1033. uint8_t num;
  1034. AttribType::Enum type;
  1035. bool normalized;
  1036. bool asInt;
  1037. _decl.decode(Attrib::Enum(attr), num, type, normalized, asInt);
  1038. memcpy(elem, &s_attrib[attr], sizeof(D3DVERTEXELEMENT9) );
  1039. elem->Type = s_attribType[type][num-1][normalized];
  1040. elem->Offset = _decl.m_offset[attr];
  1041. ++elem;
  1042. }
  1043. }
  1044. return elem;
  1045. }
  1046. static IDirect3DVertexDeclaration9* createVertexDecl(const VertexDecl& _decl, uint8_t _numInstanceData)
  1047. {
  1048. D3DVERTEXELEMENT9 vertexElements[Attrib::Count+1+BGFX_CONFIG_MAX_INSTANCE_DATA_COUNT];
  1049. D3DVERTEXELEMENT9* elem = fillVertexDecl(vertexElements, _decl);
  1050. const D3DVERTEXELEMENT9 inst = { 1, 0, D3DDECLTYPE_FLOAT4, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 0 };
  1051. for (uint32_t ii = 0; ii < _numInstanceData; ++ii)
  1052. {
  1053. memcpy(elem, &inst, sizeof(D3DVERTEXELEMENT9) );
  1054. elem->UsageIndex = 8-_numInstanceData+ii;
  1055. elem->Offset = ii*16;
  1056. ++elem;
  1057. }
  1058. memcpy(elem, &s_attrib[Attrib::Count], sizeof(D3DVERTEXELEMENT9) );
  1059. IDirect3DVertexDeclaration9* ptr;
  1060. DX_CHECK(s_renderCtx->m_device->CreateVertexDeclaration(vertexElements, &ptr) );
  1061. return ptr;
  1062. }
  1063. void VertexDeclaration::create(const VertexDecl& _decl)
  1064. {
  1065. memcpy(&m_decl, &_decl, sizeof(VertexDecl) );
  1066. dump(m_decl);
  1067. m_ptr = createVertexDecl(_decl, 0);
  1068. }
  1069. void Shader::create(bool _fragment, const Memory* _mem)
  1070. {
  1071. bx::MemoryReader reader(_mem->data, _mem->size);
  1072. uint32_t magic;
  1073. bx::read(&reader, magic);
  1074. uint32_t iohash;
  1075. bx::read(&reader, iohash);
  1076. uint16_t count;
  1077. bx::read(&reader, count);
  1078. m_numPredefined = 0;
  1079. BX_TRACE("Shader consts %d", count);
  1080. uint8_t fragmentBit = _fragment ? BGFX_UNIFORM_FRAGMENTBIT : 0;
  1081. if (0 < count)
  1082. {
  1083. m_constantBuffer = ConstantBuffer::create(1024);
  1084. for (uint32_t ii = 0; ii < count; ++ii)
  1085. {
  1086. uint8_t nameSize;
  1087. bx::read(&reader, nameSize);
  1088. char name[256];
  1089. bx::read(&reader, &name, nameSize);
  1090. name[nameSize] = '\0';
  1091. uint8_t type;
  1092. bx::read(&reader, type);
  1093. uint8_t num;
  1094. bx::read(&reader, num);
  1095. uint16_t regIndex;
  1096. bx::read(&reader, regIndex);
  1097. uint16_t regCount;
  1098. bx::read(&reader, regCount);
  1099. const char* kind = "invalid";
  1100. const void* data = NULL;
  1101. PredefinedUniform::Enum predefined = nameToPredefinedUniformEnum(name);
  1102. if (PredefinedUniform::Count != predefined)
  1103. {
  1104. kind = "predefined";
  1105. m_predefined[m_numPredefined].m_loc = regIndex;
  1106. m_predefined[m_numPredefined].m_count = regCount;
  1107. m_predefined[m_numPredefined].m_type = predefined|fragmentBit;
  1108. m_numPredefined++;
  1109. }
  1110. else
  1111. {
  1112. const UniformInfo* info = s_renderCtx->m_uniformReg.find(name);
  1113. BX_CHECK(NULL != info, "User defined uniform '%s' is not found, it won't be set.", name);
  1114. if (NULL != info)
  1115. {
  1116. kind = "user";
  1117. data = info->m_data;
  1118. m_constantBuffer->writeUniformRef( (UniformType::Enum)(type|fragmentBit), regIndex, data, regCount);
  1119. }
  1120. }
  1121. BX_TRACE("\t%s: %s, type %2d, num %2d, r.index %3d, r.count %2d"
  1122. , kind
  1123. , name
  1124. , type
  1125. , num
  1126. , regIndex
  1127. , regCount
  1128. );
  1129. BX_UNUSED(kind);
  1130. }
  1131. m_constantBuffer->finish();
  1132. }
  1133. uint16_t shaderSize;
  1134. bx::read(&reader, shaderSize);
  1135. const DWORD* code = (const DWORD*)reader.getDataPtr();
  1136. if (_fragment)
  1137. {
  1138. DX_CHECK(s_renderCtx->m_device->CreatePixelShader(code, (IDirect3DPixelShader9**)&m_ptr) );
  1139. BGFX_FATAL(NULL != m_ptr, bgfx::Fatal::InvalidShader, "Failed to create fragment shader.");
  1140. }
  1141. else
  1142. {
  1143. DX_CHECK(s_renderCtx->m_device->CreateVertexShader(code, (IDirect3DVertexShader9**)&m_ptr) );
  1144. BGFX_FATAL(NULL != m_ptr, bgfx::Fatal::InvalidShader, "Failed to create vertex shader.");
  1145. }
  1146. }
  1147. void Texture::createTexture(uint32_t _width, uint32_t _height, uint8_t _numMips, D3DFORMAT _fmt)
  1148. {
  1149. m_type = Texture2D;
  1150. DX_CHECK(s_renderCtx->m_device->CreateTexture(_width
  1151. , _height
  1152. , _numMips
  1153. , 0
  1154. , _fmt
  1155. , s_renderCtx->m_pool
  1156. , &m_texture2d
  1157. , NULL
  1158. ) );
  1159. BGFX_FATAL(NULL != m_texture2d, Fatal::UnableToCreateTexture, "Failed to create texture (size: %dx%d, mips: %d, fmt: 0x%08x)."
  1160. , _width
  1161. , _height
  1162. , _numMips
  1163. , _fmt
  1164. );
  1165. }
  1166. void Texture::createVolumeTexture(uint32_t _width, uint32_t _height, uint32_t _depth, uint32_t _numMips, D3DFORMAT _fmt)
  1167. {
  1168. m_type = Texture3D;
  1169. DX_CHECK(s_renderCtx->m_device->CreateVolumeTexture(_width
  1170. , _height
  1171. , _depth
  1172. , _numMips
  1173. , 0
  1174. , _fmt
  1175. , s_renderCtx->m_pool
  1176. , &m_texture3d
  1177. , NULL
  1178. ) );
  1179. BGFX_FATAL(NULL != m_texture3d, Fatal::UnableToCreateTexture, "Failed to create volume texture (size: %dx%dx%d, mips: %d, fmt: 0x%08x)."
  1180. , _width
  1181. , _height
  1182. , _depth
  1183. , _numMips
  1184. , _fmt
  1185. );
  1186. }
  1187. void Texture::createCubeTexture(uint32_t _edge, uint32_t _numMips, D3DFORMAT _fmt)
  1188. {
  1189. m_type = TextureCube;
  1190. DX_CHECK(s_renderCtx->m_device->CreateCubeTexture(_edge
  1191. , _numMips
  1192. , 0
  1193. , _fmt
  1194. , s_renderCtx->m_pool
  1195. , &m_textureCube
  1196. , NULL
  1197. ) );
  1198. BGFX_FATAL(NULL != m_textureCube, Fatal::UnableToCreateTexture, "Failed to create cube texture (edge: %d, mips: %d, fmt: 0x%08x)."
  1199. , _edge
  1200. , _numMips
  1201. , _fmt
  1202. );
  1203. }
  1204. uint8_t* Texture::lock(uint8_t _side, uint8_t _lod, uint32_t& _pitch, uint32_t& _slicePitch, const Rect* _rect)
  1205. {
  1206. switch (m_type)
  1207. {
  1208. case Texture2D:
  1209. {
  1210. D3DLOCKED_RECT lockedRect;
  1211. if (NULL != _rect)
  1212. {
  1213. RECT rect;
  1214. rect.left = _rect->m_x;
  1215. rect.top = _rect->m_y;
  1216. rect.right = rect.left + _rect->m_width;
  1217. rect.bottom = rect.top + _rect->m_height;
  1218. DX_CHECK(m_texture2d->LockRect(_lod, &lockedRect, &rect, 0) );
  1219. }
  1220. else
  1221. {
  1222. DX_CHECK(m_texture2d->LockRect(_lod, &lockedRect, NULL, 0) );
  1223. }
  1224. _pitch = lockedRect.Pitch;
  1225. _slicePitch = 0;
  1226. return (uint8_t*)lockedRect.pBits;
  1227. }
  1228. case Texture3D:
  1229. {
  1230. D3DLOCKED_BOX box;
  1231. DX_CHECK(m_texture3d->LockBox(_lod, &box, NULL, 0) );
  1232. _pitch = box.RowPitch;
  1233. _slicePitch = box.SlicePitch;
  1234. return (uint8_t*)box.pBits;
  1235. }
  1236. case TextureCube:
  1237. {
  1238. D3DLOCKED_RECT lockedRect;
  1239. if (NULL != _rect)
  1240. {
  1241. RECT rect;
  1242. rect.left = _rect->m_x;
  1243. rect.top = _rect->m_y;
  1244. rect.right = rect.left + _rect->m_width;
  1245. rect.bottom = rect.top + _rect->m_height;
  1246. DX_CHECK(m_textureCube->LockRect(D3DCUBEMAP_FACES(_side), _lod, &lockedRect, &rect, 0) );
  1247. }
  1248. else
  1249. {
  1250. DX_CHECK(m_textureCube->LockRect(D3DCUBEMAP_FACES(_side), _lod, &lockedRect, NULL, 0) );
  1251. }
  1252. _pitch = lockedRect.Pitch;
  1253. _slicePitch = 0;
  1254. return (uint8_t*)lockedRect.pBits;
  1255. }
  1256. }
  1257. BX_CHECK(false, "You should not be here.");
  1258. _pitch = 0;
  1259. _slicePitch = 0;
  1260. return NULL;
  1261. }
  1262. void Texture::unlock(uint8_t _side, uint8_t _lod)
  1263. {
  1264. switch (m_type)
  1265. {
  1266. case Texture2D:
  1267. {
  1268. DX_CHECK(m_texture2d->UnlockRect(_lod) );
  1269. }
  1270. return;
  1271. case Texture3D:
  1272. {
  1273. DX_CHECK(m_texture3d->UnlockBox(_lod) );
  1274. }
  1275. return;
  1276. case TextureCube:
  1277. {
  1278. DX_CHECK(m_textureCube->UnlockRect(D3DCUBEMAP_FACES(_side), _lod) );
  1279. }
  1280. return;
  1281. }
  1282. BX_CHECK(false, "You should not be here.");
  1283. }
  1284. void Texture::dirty(uint8_t _side, const Rect& _rect, uint16_t _z, uint16_t _depth)
  1285. {
  1286. switch (m_type)
  1287. {
  1288. case Texture2D:
  1289. {
  1290. RECT rect;
  1291. rect.left = _rect.m_x;
  1292. rect.top = _rect.m_y;
  1293. rect.right = rect.left + _rect.m_width;
  1294. rect.bottom = rect.top + _rect.m_height;
  1295. DX_CHECK(m_texture2d->AddDirtyRect(&rect) );
  1296. }
  1297. return;
  1298. case Texture3D:
  1299. {
  1300. D3DBOX box;
  1301. box.Left = _rect.m_x;
  1302. box.Top = _rect.m_y;
  1303. box.Right = box.Left + _rect.m_width;
  1304. box.Bottom = box.Top + _rect.m_height;
  1305. box.Front = _z;
  1306. box.Back = box.Front + _depth;
  1307. DX_CHECK(m_texture3d->AddDirtyBox(&box) );
  1308. }
  1309. return;
  1310. case TextureCube:
  1311. {
  1312. RECT rect;
  1313. rect.left = _rect.m_x;
  1314. rect.top = _rect.m_y;
  1315. rect.right = rect.left + _rect.m_width;
  1316. rect.bottom = rect.top + _rect.m_height;
  1317. DX_CHECK(m_textureCube->AddDirtyRect(D3DCUBEMAP_FACES(_side), &rect) );
  1318. }
  1319. return;
  1320. }
  1321. BX_CHECK(false, "You should not be here.");
  1322. }
  1323. void Texture::create(const Memory* _mem, uint32_t _flags)
  1324. {
  1325. m_flags = _flags;
  1326. ImageContainer imageContainer;
  1327. if (imageParse(imageContainer, _mem->data, _mem->size) )
  1328. {
  1329. m_requestedFormat = (uint8_t)imageContainer.m_format;
  1330. m_textureFormat = (uint8_t)imageContainer.m_format;
  1331. const TextureFormatInfo& tfi = s_textureFormat[m_requestedFormat];
  1332. const bool convert = D3DFMT_UNKNOWN == tfi.m_fmt;
  1333. uint8_t bpp = getBitsPerPixel(TextureFormat::Enum(m_textureFormat) );
  1334. if (convert)
  1335. {
  1336. m_textureFormat = (uint8_t)TextureFormat::BGRA8;
  1337. bpp = 32;
  1338. }
  1339. D3DFORMAT format = s_textureFormat[m_textureFormat].m_fmt;
  1340. if (imageContainer.m_cubeMap)
  1341. {
  1342. createCubeTexture(imageContainer.m_width, imageContainer.m_numMips, format);
  1343. }
  1344. else if (imageContainer.m_depth > 1)
  1345. {
  1346. createVolumeTexture(imageContainer.m_width, imageContainer.m_height, imageContainer.m_depth, imageContainer.m_numMips, format);
  1347. }
  1348. else
  1349. {
  1350. createTexture(imageContainer.m_width, imageContainer.m_height, imageContainer.m_numMips, format);
  1351. }
  1352. // For BC4 and B5 in DX9 LockRect returns wrong number of
  1353. // bytes. If actual mip size is used it causes memory corruption.
  1354. // http://www.aras-p.info/texts/D3D9GPUHacks.html#3dc
  1355. const bool useMipSize = true
  1356. && imageContainer.m_format != TextureFormat::BC4
  1357. && imageContainer.m_format != TextureFormat::BC5
  1358. ;
  1359. const bool compressed = TextureFormat::Unknown > m_requestedFormat;
  1360. const uint32_t min = compressed ? 4 : 1;
  1361. for (uint8_t side = 0, numSides = imageContainer.m_cubeMap ? 6 : 1; side < numSides; ++side)
  1362. {
  1363. uint32_t width = imageContainer.m_width;
  1364. uint32_t height = imageContainer.m_height;
  1365. uint32_t depth = imageContainer.m_depth;
  1366. uint32_t mipWidth = imageContainer.m_width;
  1367. uint32_t mipHeight = imageContainer.m_height;
  1368. for (uint32_t lod = 0, num = imageContainer.m_numMips; lod < num; ++lod)
  1369. {
  1370. width = bx::uint32_max(1, width);
  1371. height = bx::uint32_max(1, height);
  1372. depth = bx::uint32_max(1, depth);
  1373. mipWidth = bx::uint32_max(min, mipWidth);
  1374. mipHeight = bx::uint32_max(min, mipHeight);
  1375. uint32_t mipSize = width*height*depth*bpp/8;
  1376. ImageMip mip;
  1377. if (imageGetRawData(imageContainer, side, lod, _mem->data, _mem->size, mip) )
  1378. {
  1379. uint32_t pitch;
  1380. uint32_t slicePitch;
  1381. uint8_t* bits = lock(side, lod, pitch, slicePitch);
  1382. if (convert)
  1383. {
  1384. if (width != mipWidth
  1385. || height != mipHeight)
  1386. {
  1387. uint32_t srcpitch = mipWidth*bpp/8;
  1388. uint8_t* temp = (uint8_t*)BX_ALLOC(g_allocator, srcpitch*mipHeight);
  1389. imageDecodeToBgra8(temp, mip.m_data, mip.m_width, mip.m_height, srcpitch, mip.m_format);
  1390. uint32_t dstpitch = pitch;
  1391. for (uint32_t yy = 0; yy < height; ++yy)
  1392. {
  1393. uint8_t* src = &temp[yy*srcpitch];
  1394. uint8_t* dst = &bits[yy*dstpitch];
  1395. memcpy(dst, src, dstpitch);
  1396. }
  1397. BX_FREE(g_allocator, temp);
  1398. }
  1399. else
  1400. {
  1401. imageDecodeToBgra8(bits, mip.m_data, mip.m_width, mip.m_height, pitch, mip.m_format);
  1402. }
  1403. }
  1404. else
  1405. {
  1406. uint32_t size = useMipSize ? mip.m_size : mipSize;
  1407. memcpy(bits, mip.m_data, size);
  1408. }
  1409. unlock(side, lod);
  1410. }
  1411. width >>= 1;
  1412. height >>= 1;
  1413. depth >>= 1;
  1414. mipWidth >>= 1;
  1415. mipHeight >>= 1;
  1416. }
  1417. }
  1418. }
  1419. }
  1420. void Texture::updateBegin(uint8_t _side, uint8_t _mip)
  1421. {
  1422. uint32_t slicePitch;
  1423. s_renderCtx->m_updateTextureSide = _side;
  1424. s_renderCtx->m_updateTextureMip = _mip;
  1425. s_renderCtx->m_updateTextureBits = lock(_side, _mip, s_renderCtx->m_updateTexturePitch, slicePitch);
  1426. }
  1427. void Texture::update(uint8_t _side, uint8_t _mip, const Rect& _rect, uint16_t _z, uint16_t _depth, uint16_t _pitch, const Memory* _mem)
  1428. {
  1429. const uint32_t bpp = getBitsPerPixel(TextureFormat::Enum(m_textureFormat) );
  1430. const uint32_t rectpitch = _rect.m_width*bpp/8;
  1431. const uint32_t srcpitch = UINT16_MAX == _pitch ? rectpitch : _pitch;
  1432. const uint32_t dstpitch = s_renderCtx->m_updateTexturePitch;
  1433. uint8_t* bits = s_renderCtx->m_updateTextureBits + _rect.m_y*dstpitch + _rect.m_x*bpp/8;
  1434. const bool convert = m_textureFormat != m_requestedFormat;
  1435. uint8_t* data = _mem->data;
  1436. uint8_t* temp = NULL;
  1437. if (convert)
  1438. {
  1439. uint8_t* temp = (uint8_t*)BX_ALLOC(g_allocator, rectpitch*_rect.m_height);
  1440. imageDecodeToBgra8(temp, data, _rect.m_width, _rect.m_height, srcpitch, m_requestedFormat);
  1441. data = temp;
  1442. }
  1443. {
  1444. uint8_t* src = data;
  1445. uint8_t* dst = bits;
  1446. for (uint32_t yy = 0, height = _rect.m_height; yy < height; ++yy)
  1447. {
  1448. memcpy(dst, src, rectpitch);
  1449. src += srcpitch;
  1450. dst += dstpitch;
  1451. }
  1452. }
  1453. if (NULL != temp)
  1454. {
  1455. BX_FREE(g_allocator, temp);
  1456. }
  1457. if (0 == _mip)
  1458. {
  1459. dirty(_side, _rect, _z, _depth);
  1460. }
  1461. }
  1462. void Texture::updateEnd()
  1463. {
  1464. unlock(s_renderCtx->m_updateTextureSide, s_renderCtx->m_updateTextureMip);
  1465. }
  1466. void Texture::commit(uint8_t _stage, uint32_t _flags)
  1467. {
  1468. s_renderCtx->setSamplerState(_stage, 0 == (BGFX_SAMPLER_DEFAULT_FLAGS & _flags) ? _flags : m_flags);
  1469. DX_CHECK(s_renderCtx->m_device->SetTexture(_stage, m_ptr) );
  1470. }
  1471. void RenderTarget::create(uint16_t _width, uint16_t _height, uint32_t _flags, uint32_t _textureFlags)
  1472. {
  1473. m_width = _width;
  1474. m_height = _height;
  1475. m_flags = _flags;
  1476. m_textureFlags = (_textureFlags&(BGFX_TEXTURE_MIN_MASK|BGFX_TEXTURE_MAG_MASK) )
  1477. | BGFX_TEXTURE_U_CLAMP
  1478. | BGFX_TEXTURE_V_CLAMP
  1479. ;
  1480. createTextures();
  1481. }
  1482. void RenderTarget::createTextures()
  1483. {
  1484. if (0 != m_flags)
  1485. {
  1486. m_msaa = s_msaa[(m_flags&BGFX_RENDER_TARGET_MSAA_MASK)>>BGFX_RENDER_TARGET_MSAA_SHIFT];
  1487. const uint32_t colorFormat = (m_flags&BGFX_RENDER_TARGET_COLOR_MASK)>>BGFX_RENDER_TARGET_COLOR_SHIFT;
  1488. const uint32_t depthFormat = (m_flags&BGFX_RENDER_TARGET_DEPTH_MASK)>>BGFX_RENDER_TARGET_DEPTH_SHIFT;
  1489. m_depthOnly = (0 == colorFormat && 0 < depthFormat);
  1490. // CheckDeviceFormat D3DUSAGE_SRGBWRITE
  1491. if (m_depthOnly)
  1492. {
  1493. DX_CHECK(s_renderCtx->m_device->CreateRenderTarget(1
  1494. , 1
  1495. , D3DFMT_R5G6B5
  1496. , D3DMULTISAMPLE_NONE
  1497. , 0
  1498. , false
  1499. , &m_rt
  1500. , NULL
  1501. ) );
  1502. BGFX_FATAL(m_rt, Fatal::UnableToCreateRenderTarget, "Unable to create 1x1 render target.");
  1503. DX_CHECK(s_renderCtx->m_device->CreateTexture(m_width
  1504. , m_height
  1505. , 1
  1506. , D3DUSAGE_DEPTHSTENCIL
  1507. , s_depthFormat[depthFormat]
  1508. , D3DPOOL_DEFAULT
  1509. , &m_depthTexture
  1510. , NULL
  1511. ) );
  1512. BGFX_FATAL(m_depthTexture, Fatal::UnableToCreateRenderTarget, "Unable to create depth texture.");
  1513. DX_CHECK(m_depthTexture->GetSurfaceLevel(0, &m_depth) );
  1514. }
  1515. else
  1516. {
  1517. if (D3DMULTISAMPLE_NONE != m_msaa.m_type)
  1518. {
  1519. DX_CHECK(s_renderCtx->m_device->CreateRenderTarget(m_width
  1520. , m_height
  1521. , s_colorFormat[colorFormat]
  1522. , m_msaa.m_type
  1523. , m_msaa.m_quality
  1524. , false
  1525. , &m_rt
  1526. , NULL
  1527. ) );
  1528. BGFX_FATAL(m_rt, Fatal::UnableToCreateRenderTarget, "Unable to create MSAA render target.");
  1529. }
  1530. if (0 < colorFormat)
  1531. {
  1532. DX_CHECK(s_renderCtx->m_device->CreateTexture(m_width
  1533. , m_height
  1534. , 1
  1535. , D3DUSAGE_RENDERTARGET
  1536. , s_colorFormat[colorFormat]
  1537. , D3DPOOL_DEFAULT
  1538. , &m_colorTexture
  1539. , NULL
  1540. ) );
  1541. BGFX_FATAL(m_colorTexture, Fatal::UnableToCreateRenderTarget, "Unable to create color render target.");
  1542. DX_CHECK(m_colorTexture->GetSurfaceLevel(0, &m_color) );
  1543. }
  1544. if (0 < depthFormat)
  1545. {
  1546. DX_CHECK(s_renderCtx->m_device->CreateDepthStencilSurface(m_width
  1547. , m_height
  1548. , s_depthFormat[depthFormat]
  1549. , m_msaa.m_type
  1550. , m_msaa.m_quality
  1551. , FALSE
  1552. , &m_depth
  1553. , NULL
  1554. ) );
  1555. BGFX_FATAL(m_depth, Fatal::UnableToCreateRenderTarget, "Unable to create depth stencil surface.");
  1556. }
  1557. }
  1558. }
  1559. }
  1560. void RenderTarget::destroyTextures()
  1561. {
  1562. if (0 != m_flags)
  1563. {
  1564. if (m_depthOnly)
  1565. {
  1566. DX_RELEASE(m_rt, 0);
  1567. DX_RELEASE(m_depth, 1);
  1568. DX_RELEASE(m_depthTexture, 0);
  1569. }
  1570. else
  1571. {
  1572. uint32_t colorFormat = (m_flags&BGFX_RENDER_TARGET_COLOR_MASK)>>BGFX_RENDER_TARGET_COLOR_SHIFT;
  1573. uint32_t depthFormat = (m_flags&BGFX_RENDER_TARGET_DEPTH_MASK)>>BGFX_RENDER_TARGET_DEPTH_SHIFT;
  1574. if (D3DMULTISAMPLE_NONE != m_msaa.m_type)
  1575. {
  1576. DX_RELEASE(m_rt, 0);
  1577. }
  1578. if (0 < colorFormat)
  1579. {
  1580. DX_RELEASE(m_color, 1);
  1581. DX_RELEASE(m_colorTexture, 0);
  1582. }
  1583. if (0 < depthFormat)
  1584. {
  1585. DX_RELEASE(m_depth, 0);
  1586. }
  1587. }
  1588. }
  1589. }
  1590. void RenderTarget::commit(uint8_t _stage, uint32_t _textureFlags)
  1591. {
  1592. s_renderCtx->setSamplerState(_stage, 0 == (BGFX_SAMPLER_DEFAULT_FLAGS & _textureFlags) ? _textureFlags : m_textureFlags);
  1593. DX_CHECK(s_renderCtx->m_device->SetTexture(_stage, m_depthOnly ? m_depthTexture : m_colorTexture) );
  1594. }
  1595. void RenderTarget::resolve()
  1596. {
  1597. #if BX_PLATFORM_WINDOWS
  1598. DX_CHECK(s_renderCtx->m_device->StretchRect(m_rt
  1599. , NULL
  1600. , m_color
  1601. , NULL
  1602. , D3DTEXF_NONE
  1603. ) );
  1604. #endif // BX_PLATFORM_WINDOWS
  1605. }
  1606. void ConstantBuffer::commit()
  1607. {
  1608. reset();
  1609. do
  1610. {
  1611. uint32_t opcode = read();
  1612. if (UniformType::End == opcode)
  1613. {
  1614. break;
  1615. }
  1616. UniformType::Enum type;
  1617. uint16_t loc;
  1618. uint16_t num;
  1619. uint16_t copy;
  1620. decodeOpcode(opcode, type, loc, num, copy);
  1621. const char* data;
  1622. if (copy)
  1623. {
  1624. data = read(g_uniformTypeSize[type]*num);
  1625. }
  1626. else
  1627. {
  1628. memcpy(&data, read(sizeof(void*) ), sizeof(void*) );
  1629. }
  1630. #define CASE_IMPLEMENT_UNIFORM(_uniform, _glsuffix, _dxsuffix, _type) \
  1631. case UniformType::_uniform: \
  1632. { \
  1633. _type* value = (_type*)data; \
  1634. s_renderCtx->m_device->SetVertexShaderConstant##_dxsuffix(loc, value, num); \
  1635. } \
  1636. break; \
  1637. \
  1638. case UniformType::_uniform|BGFX_UNIFORM_FRAGMENTBIT: \
  1639. { \
  1640. _type* value = (_type*)data; \
  1641. s_renderCtx->m_device->SetPixelShaderConstant##_dxsuffix(loc, value, num); \
  1642. } \
  1643. break
  1644. switch ((int32_t)type)
  1645. {
  1646. CASE_IMPLEMENT_UNIFORM(Uniform1i, 1iv, I, int);
  1647. CASE_IMPLEMENT_UNIFORM(Uniform1f, 1fv, F, float);
  1648. CASE_IMPLEMENT_UNIFORM(Uniform1iv, 1iv, I, int);
  1649. CASE_IMPLEMENT_UNIFORM(Uniform1fv, 1fv, F, float);
  1650. CASE_IMPLEMENT_UNIFORM(Uniform2fv, 2fv, F, float);
  1651. CASE_IMPLEMENT_UNIFORM(Uniform3fv, 3fv, F, float);
  1652. CASE_IMPLEMENT_UNIFORM(Uniform4fv, 4fv, F, float);
  1653. CASE_IMPLEMENT_UNIFORM(Uniform3x3fv, Matrix3fv, F, float);
  1654. CASE_IMPLEMENT_UNIFORM(Uniform4x4fv, Matrix4fv, F, float);
  1655. case UniformType::End:
  1656. break;
  1657. default:
  1658. BX_TRACE("%4d: INVALID 0x%08x, t %d, l %d, n %d, c %d", m_pos, opcode, type, loc, num, copy);
  1659. break;
  1660. }
  1661. #undef CASE_IMPLEMENT_UNIFORM
  1662. } while (true);
  1663. }
  1664. void TextVideoMemBlitter::setup()
  1665. {
  1666. uint32_t width = s_renderCtx->m_params.BackBufferWidth;
  1667. uint32_t height = s_renderCtx->m_params.BackBufferHeight;
  1668. RenderTargetHandle rt = BGFX_INVALID_HANDLE;
  1669. s_renderCtx->setRenderTarget(rt, false);
  1670. D3DVIEWPORT9 vp;
  1671. vp.X = 0;
  1672. vp.Y = 0;
  1673. vp.Width = width;
  1674. vp.Height = height;
  1675. vp.MinZ = 0.0f;
  1676. vp.MaxZ = 1.0f;
  1677. IDirect3DDevice9* device = s_renderCtx->m_device;
  1678. DX_CHECK(device->SetViewport(&vp) );
  1679. DX_CHECK(device->SetRenderState(D3DRS_STENCILENABLE, FALSE) );
  1680. DX_CHECK(device->SetRenderState(D3DRS_ZENABLE, FALSE) );
  1681. DX_CHECK(device->SetRenderState(D3DRS_ZFUNC, D3DCMP_ALWAYS) );
  1682. DX_CHECK(device->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE) );
  1683. DX_CHECK(device->SetRenderState(D3DRS_ALPHABLENDENABLE, FALSE) );
  1684. DX_CHECK(device->SetRenderState(D3DRS_ALPHAFUNC, D3DCMP_GREATER) );
  1685. DX_CHECK(device->SetRenderState(D3DRS_COLORWRITEENABLE, D3DCOLORWRITEENABLE_RED|D3DCOLORWRITEENABLE_GREEN|D3DCOLORWRITEENABLE_BLUE) );
  1686. DX_CHECK(device->SetRenderState(D3DRS_FILLMODE, D3DFILL_SOLID) );
  1687. Program& program = s_renderCtx->m_program[m_program.idx];
  1688. device->SetVertexShader( (IDirect3DVertexShader9*)program.m_vsh->m_ptr);
  1689. device->SetPixelShader( (IDirect3DPixelShader9*)program.m_fsh->m_ptr);
  1690. VertexBuffer& vb = s_renderCtx->m_vertexBuffers[m_vb->handle.idx];
  1691. VertexDeclaration& vertexDecl = s_renderCtx->m_vertexDecls[m_vb->decl.idx];
  1692. DX_CHECK(device->SetStreamSource(0, vb.m_ptr, 0, vertexDecl.m_decl.m_stride) );
  1693. DX_CHECK(device->SetVertexDeclaration(vertexDecl.m_ptr) );
  1694. IndexBuffer& ib = s_renderCtx->m_indexBuffers[m_ib->handle.idx];
  1695. DX_CHECK(device->SetIndices(ib.m_ptr) );
  1696. float proj[16];
  1697. mtxOrtho(proj, 0.0f, (float)width, (float)height, 0.0f, 0.0f, 1000.0f);
  1698. PredefinedUniform& predefined = program.m_predefined[0];
  1699. uint8_t flags = predefined.m_type;
  1700. s_renderCtx->setShaderConstantF(flags, predefined.m_loc, proj, 4);
  1701. s_renderCtx->m_textures[m_texture.idx].commit(0);
  1702. }
  1703. void TextVideoMemBlitter::render(uint32_t _numIndices)
  1704. {
  1705. uint32_t numVertices = _numIndices*4/6;
  1706. s_renderCtx->m_indexBuffers[m_ib->handle.idx].update(0, _numIndices*2, m_ib->data, true);
  1707. s_renderCtx->m_vertexBuffers[m_vb->handle.idx].update(0, numVertices*m_decl.m_stride, m_vb->data, true);
  1708. DX_CHECK(s_renderCtx->m_device->DrawIndexedPrimitive(D3DPT_TRIANGLELIST
  1709. , 0
  1710. , 0
  1711. , numVertices
  1712. , 0
  1713. , _numIndices/3
  1714. ) );
  1715. }
  1716. void Context::rendererFlip()
  1717. {
  1718. if (NULL != s_renderCtx)
  1719. {
  1720. s_renderCtx->flip();
  1721. }
  1722. }
  1723. void Context::rendererInit()
  1724. {
  1725. s_renderCtx = BX_NEW(g_allocator, RendererContext);
  1726. s_renderCtx->init();
  1727. }
  1728. void Context::rendererShutdown()
  1729. {
  1730. s_renderCtx->shutdown();
  1731. BX_DELETE(g_allocator, s_renderCtx);
  1732. }
  1733. void Context::rendererCreateIndexBuffer(IndexBufferHandle _handle, Memory* _mem)
  1734. {
  1735. s_renderCtx->m_indexBuffers[_handle.idx].create(_mem->size, _mem->data);
  1736. }
  1737. void Context::rendererDestroyIndexBuffer(IndexBufferHandle _handle)
  1738. {
  1739. s_renderCtx->m_indexBuffers[_handle.idx].destroy();
  1740. }
  1741. void Context::rendererCreateVertexDecl(VertexDeclHandle _handle, const VertexDecl& _decl)
  1742. {
  1743. s_renderCtx->m_vertexDecls[_handle.idx].create(_decl);
  1744. }
  1745. void Context::rendererDestroyVertexDecl(VertexDeclHandle _handle)
  1746. {
  1747. s_renderCtx->m_vertexDecls[_handle.idx].destroy();
  1748. }
  1749. void Context::rendererCreateVertexBuffer(VertexBufferHandle _handle, Memory* _mem, VertexDeclHandle _declHandle)
  1750. {
  1751. s_renderCtx->m_vertexBuffers[_handle.idx].create(_mem->size, _mem->data, _declHandle);
  1752. }
  1753. void Context::rendererDestroyVertexBuffer(VertexBufferHandle _handle)
  1754. {
  1755. s_renderCtx->m_vertexBuffers[_handle.idx].destroy();
  1756. }
  1757. void Context::rendererCreateDynamicIndexBuffer(IndexBufferHandle _handle, uint32_t _size)
  1758. {
  1759. s_renderCtx->m_indexBuffers[_handle.idx].create(_size, NULL);
  1760. }
  1761. void Context::rendererUpdateDynamicIndexBuffer(IndexBufferHandle _handle, uint32_t _offset, uint32_t _size, Memory* _mem)
  1762. {
  1763. s_renderCtx->m_indexBuffers[_handle.idx].update(_offset, bx::uint32_min(_size, _mem->size), _mem->data);
  1764. }
  1765. void Context::rendererDestroyDynamicIndexBuffer(IndexBufferHandle _handle)
  1766. {
  1767. s_renderCtx->m_indexBuffers[_handle.idx].destroy();
  1768. }
  1769. void Context::rendererCreateDynamicVertexBuffer(VertexBufferHandle _handle, uint32_t _size)
  1770. {
  1771. VertexDeclHandle decl = BGFX_INVALID_HANDLE;
  1772. s_renderCtx->m_vertexBuffers[_handle.idx].create(_size, NULL, decl);
  1773. }
  1774. void Context::rendererUpdateDynamicVertexBuffer(VertexBufferHandle _handle, uint32_t _offset, uint32_t _size, Memory* _mem)
  1775. {
  1776. s_renderCtx->m_vertexBuffers[_handle.idx].update(_offset, bx::uint32_min(_size, _mem->size), _mem->data);
  1777. }
  1778. void Context::rendererDestroyDynamicVertexBuffer(VertexBufferHandle _handle)
  1779. {
  1780. s_renderCtx->m_vertexBuffers[_handle.idx].destroy();
  1781. }
  1782. void Context::rendererCreateVertexShader(VertexShaderHandle _handle, Memory* _mem)
  1783. {
  1784. s_renderCtx->m_vertexShaders[_handle.idx].create(false, _mem);
  1785. }
  1786. void Context::rendererDestroyVertexShader(VertexShaderHandle _handle)
  1787. {
  1788. s_renderCtx->m_vertexShaders[_handle.idx].destroy();
  1789. }
  1790. void Context::rendererCreateFragmentShader(FragmentShaderHandle _handle, Memory* _mem)
  1791. {
  1792. s_renderCtx->m_fragmentShaders[_handle.idx].create(true, _mem);
  1793. }
  1794. void Context::rendererDestroyFragmentShader(FragmentShaderHandle _handle)
  1795. {
  1796. s_renderCtx->m_fragmentShaders[_handle.idx].destroy();
  1797. }
  1798. void Context::rendererCreateProgram(ProgramHandle _handle, VertexShaderHandle _vsh, FragmentShaderHandle _fsh)
  1799. {
  1800. s_renderCtx->m_program[_handle.idx].create(s_renderCtx->m_vertexShaders[_vsh.idx], s_renderCtx->m_fragmentShaders[_fsh.idx]);
  1801. }
  1802. void Context::rendererDestroyProgram(FragmentShaderHandle _handle)
  1803. {
  1804. s_renderCtx->m_program[_handle.idx].destroy();
  1805. }
  1806. void Context::rendererCreateTexture(TextureHandle _handle, Memory* _mem, uint32_t _flags)
  1807. {
  1808. s_renderCtx->m_textures[_handle.idx].create(_mem, _flags);
  1809. }
  1810. void Context::rendererUpdateTextureBegin(TextureHandle _handle, uint8_t _side, uint8_t _mip)
  1811. {
  1812. s_renderCtx->m_updateTexture = &s_renderCtx->m_textures[_handle.idx];
  1813. s_renderCtx->m_updateTexture->updateBegin(_side, _mip);
  1814. }
  1815. void Context::rendererUpdateTexture(TextureHandle /*_handle*/, uint8_t _side, uint8_t _mip, const Rect& _rect, uint16_t _z, uint16_t _depth, uint16_t _pitch, const Memory* _mem)
  1816. {
  1817. s_renderCtx->m_updateTexture->update(_side, _mip, _rect, _z, _depth, _pitch, _mem);
  1818. }
  1819. void Context::rendererUpdateTextureEnd()
  1820. {
  1821. s_renderCtx->m_updateTexture->updateEnd();
  1822. s_renderCtx->m_updateTexture = NULL;
  1823. }
  1824. void Context::rendererDestroyTexture(TextureHandle _handle)
  1825. {
  1826. s_renderCtx->m_textures[_handle.idx].destroy();
  1827. }
  1828. void Context::rendererCreateRenderTarget(RenderTargetHandle _handle, uint16_t _width, uint16_t _height, uint32_t _flags, uint32_t _textureFlags)
  1829. {
  1830. s_renderCtx->m_renderTargets[_handle.idx].create(_width, _height, _flags, _textureFlags);
  1831. }
  1832. void Context::rendererDestroyRenderTarget(RenderTargetHandle _handle)
  1833. {
  1834. s_renderCtx->m_renderTargets[_handle.idx].destroy();
  1835. }
  1836. void Context::rendererCreateUniform(UniformHandle _handle, UniformType::Enum _type, uint16_t _num, const char* _name)
  1837. {
  1838. uint32_t size = BX_ALIGN_16(g_uniformTypeSize[_type]*_num);
  1839. void* data = BX_ALLOC(g_allocator, size);
  1840. memset(data, 0, size);
  1841. s_renderCtx->m_uniforms[_handle.idx] = data;
  1842. s_renderCtx->m_uniformReg.add(_name, s_renderCtx->m_uniforms[_handle.idx]);
  1843. }
  1844. void Context::rendererDestroyUniform(UniformHandle _handle)
  1845. {
  1846. BX_FREE(g_allocator, s_renderCtx->m_uniforms[_handle.idx]);
  1847. }
  1848. void Context::rendererSaveScreenShot(const char* _filePath)
  1849. {
  1850. s_renderCtx->saveScreenShot(_filePath);
  1851. }
  1852. void Context::rendererUpdateViewName(uint8_t _id, const char* _name)
  1853. {
  1854. mbstowcs(&s_viewNameW[_id][0], _name, BX_COUNTOF(s_viewNameW[0]) );
  1855. }
  1856. void Context::rendererUpdateUniform(uint16_t _loc, const void* _data, uint32_t _size)
  1857. {
  1858. memcpy(s_renderCtx->m_uniforms[_loc], _data, _size);
  1859. }
  1860. void Context::rendererSetMarker(const char* _marker, uint32_t _size)
  1861. {
  1862. #if BGFX_CONFIG_DEBUG_PIX
  1863. uint32_t size = _size*sizeof(wchar_t);
  1864. wchar_t* name = (wchar_t*)alloca(size);
  1865. mbstowcs(name, _marker, size-2);
  1866. PIX_SETMARKER(D3DCOLOR_RGBA(0xff, 0xff, 0xff, 0xff), name);
  1867. #endif // BGFX_CONFIG_DEBUG_PIX
  1868. BX_UNUSED(_marker, _size);
  1869. }
  1870. void Context::rendererSubmit()
  1871. {
  1872. IDirect3DDevice9* device = s_renderCtx->m_device;
  1873. PIX_BEGINEVENT(D3DCOLOR_RGBA(0xff, 0x00, 0x00, 0xff), L"rendererSubmit");
  1874. s_renderCtx->updateResolution(m_render->m_resolution);
  1875. int64_t elapsed = -bx::getHPCounter();
  1876. int64_t captureElapsed = 0;
  1877. device->BeginScene();
  1878. if (0 < m_render->m_iboffset)
  1879. {
  1880. TransientIndexBuffer* ib = m_render->m_transientIb;
  1881. s_renderCtx->m_indexBuffers[ib->handle.idx].update(0, m_render->m_iboffset, ib->data, true);
  1882. }
  1883. if (0 < m_render->m_vboffset)
  1884. {
  1885. TransientVertexBuffer* vb = m_render->m_transientVb;
  1886. s_renderCtx->m_vertexBuffers[vb->handle.idx].update(0, m_render->m_vboffset, vb->data, true);
  1887. }
  1888. m_render->sort();
  1889. RenderState currentState;
  1890. currentState.reset();
  1891. currentState.m_flags = BGFX_STATE_NONE;
  1892. currentState.m_stencil = packStencil(BGFX_STENCIL_NONE, BGFX_STENCIL_NONE);
  1893. Matrix4 viewProj[BGFX_CONFIG_MAX_VIEWS];
  1894. for (uint32_t ii = 0; ii < BGFX_CONFIG_MAX_VIEWS; ++ii)
  1895. {
  1896. mtxMul(viewProj[ii].val, m_render->m_view[ii].val, m_render->m_proj[ii].val);
  1897. }
  1898. DX_CHECK(device->SetRenderState(D3DRS_FILLMODE, m_render->m_debug&BGFX_DEBUG_WIREFRAME ? D3DFILL_WIREFRAME : D3DFILL_SOLID) );
  1899. uint16_t programIdx = invalidHandle;
  1900. SortKey key;
  1901. uint8_t view = 0xff;
  1902. RenderTargetHandle rt = BGFX_INVALID_HANDLE;
  1903. float alphaRef = 0.0f;
  1904. uint32_t blendFactor = 0;
  1905. D3DPRIMITIVETYPE primType = D3DPT_TRIANGLELIST;
  1906. uint32_t primNumVerts = 3;
  1907. bool viewHasScissor = false;
  1908. Rect viewScissorRect;
  1909. viewScissorRect.clear();
  1910. uint32_t statsNumPrimsSubmitted = 0;
  1911. uint32_t statsNumIndices = 0;
  1912. uint32_t statsNumInstances = 0;
  1913. uint32_t statsNumPrimsRendered = 0;
  1914. s_renderCtx->invalidateSamplerState();
  1915. if (0 == (m_render->m_debug&BGFX_DEBUG_IFH) )
  1916. {
  1917. for (uint32_t item = 0, numItems = m_render->m_num; item < numItems; ++item)
  1918. {
  1919. key.decode(m_render->m_sortKeys[item]);
  1920. const RenderState& state = m_render->m_renderState[m_render->m_sortValues[item] ];
  1921. const uint64_t newFlags = state.m_flags;
  1922. uint64_t changedFlags = currentState.m_flags ^ state.m_flags;
  1923. currentState.m_flags = newFlags;
  1924. const uint64_t newStencil = state.m_stencil;
  1925. uint64_t changedStencil = currentState.m_stencil ^ state.m_stencil;
  1926. currentState.m_stencil = newStencil;
  1927. if (key.m_view != view)
  1928. {
  1929. currentState.clear();
  1930. currentState.m_scissor = !state.m_scissor;
  1931. changedFlags = BGFX_STATE_MASK;
  1932. changedStencil = packStencil(BGFX_STENCIL_MASK, BGFX_STENCIL_MASK);
  1933. currentState.m_flags = newFlags;
  1934. currentState.m_stencil = newStencil;
  1935. PIX_ENDEVENT();
  1936. PIX_BEGINEVENT(D3DCOLOR_RGBA(0xff, 0x00, 0x00, 0xff), s_viewNameW[key.m_view]);
  1937. view = key.m_view;
  1938. programIdx = invalidHandle;
  1939. if (m_render->m_rt[view].idx != rt.idx)
  1940. {
  1941. rt = m_render->m_rt[view];
  1942. s_renderCtx->setRenderTarget(rt);
  1943. }
  1944. const Rect& rect = m_render->m_rect[view];
  1945. const Rect& scissorRect = m_render->m_scissor[view];
  1946. viewHasScissor = !scissorRect.isZero();
  1947. viewScissorRect = viewHasScissor ? scissorRect : rect;
  1948. D3DVIEWPORT9 vp;
  1949. vp.X = rect.m_x;
  1950. vp.Y = rect.m_y;
  1951. vp.Width = rect.m_width;
  1952. vp.Height = rect.m_height;
  1953. vp.MinZ = 0.0f;
  1954. vp.MaxZ = 1.0f;
  1955. DX_CHECK(device->SetViewport(&vp) );
  1956. Clear& clear = m_render->m_clear[view];
  1957. if (BGFX_CLEAR_NONE != clear.m_flags)
  1958. {
  1959. D3DCOLOR color = 0;
  1960. DWORD flags = 0;
  1961. if (BGFX_CLEAR_COLOR_BIT & clear.m_flags)
  1962. {
  1963. flags |= D3DCLEAR_TARGET;
  1964. uint32_t rgba = clear.m_rgba;
  1965. color = D3DCOLOR_RGBA(rgba>>24, (rgba>>16)&0xff, (rgba>>8)&0xff, rgba&0xff);
  1966. DX_CHECK(device->SetRenderState(D3DRS_COLORWRITEENABLE, D3DCOLORWRITEENABLE_RED|D3DCOLORWRITEENABLE_GREEN|D3DCOLORWRITEENABLE_BLUE|D3DCOLORWRITEENABLE_ALPHA) );
  1967. }
  1968. if (BGFX_CLEAR_DEPTH_BIT & clear.m_flags)
  1969. {
  1970. flags |= D3DCLEAR_ZBUFFER;
  1971. DX_CHECK(device->SetRenderState(D3DRS_ZWRITEENABLE, TRUE) );
  1972. }
  1973. if (BGFX_CLEAR_STENCIL_BIT & clear.m_flags)
  1974. {
  1975. flags |= D3DCLEAR_STENCIL;
  1976. }
  1977. if (0 != flags)
  1978. {
  1979. RECT rc;
  1980. rc.left = rect.m_x;
  1981. rc.top = rect.m_y;
  1982. rc.right = rect.m_x + rect.m_width;
  1983. rc.bottom = rect.m_y + rect.m_height;
  1984. DX_CHECK(device->SetRenderState(D3DRS_SCISSORTESTENABLE, TRUE) );
  1985. DX_CHECK(device->SetScissorRect(&rc) );
  1986. DX_CHECK(device->Clear(0, NULL, flags, color, clear.m_depth, clear.m_stencil) );
  1987. DX_CHECK(device->SetRenderState(D3DRS_SCISSORTESTENABLE, FALSE) );
  1988. }
  1989. }
  1990. DX_CHECK(device->SetRenderState(D3DRS_STENCILENABLE, FALSE) );
  1991. DX_CHECK(device->SetRenderState(D3DRS_ZENABLE, TRUE) );
  1992. DX_CHECK(device->SetRenderState(D3DRS_ZFUNC, D3DCMP_LESS) );
  1993. DX_CHECK(device->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE) );
  1994. DX_CHECK(device->SetRenderState(D3DRS_ALPHABLENDENABLE, FALSE) );
  1995. DX_CHECK(device->SetRenderState(D3DRS_ALPHAFUNC, D3DCMP_GREATER) );
  1996. }
  1997. uint16_t scissor = state.m_scissor;
  1998. if (currentState.m_scissor != scissor)
  1999. {
  2000. currentState.m_scissor = scissor;
  2001. if (UINT16_MAX == scissor)
  2002. {
  2003. DX_CHECK(device->SetRenderState(D3DRS_SCISSORTESTENABLE, viewHasScissor) );
  2004. if (viewHasScissor)
  2005. {
  2006. RECT rc;
  2007. rc.left = viewScissorRect.m_x;
  2008. rc.top = viewScissorRect.m_y;
  2009. rc.right = viewScissorRect.m_x + viewScissorRect.m_width;
  2010. rc.bottom = viewScissorRect.m_y + viewScissorRect.m_height;
  2011. DX_CHECK(device->SetScissorRect(&rc) );
  2012. }
  2013. }
  2014. else
  2015. {
  2016. Rect scissorRect;
  2017. scissorRect.intersect(viewScissorRect, m_render->m_rectCache.m_cache[scissor]);
  2018. DX_CHECK(device->SetRenderState(D3DRS_SCISSORTESTENABLE, true) );
  2019. RECT rc;
  2020. rc.left = scissorRect.m_x;
  2021. rc.top = scissorRect.m_y;
  2022. rc.right = scissorRect.m_x + scissorRect.m_width;
  2023. rc.bottom = scissorRect.m_y + scissorRect.m_height;
  2024. DX_CHECK(device->SetScissorRect(&rc) );
  2025. }
  2026. }
  2027. if (0 != changedStencil)
  2028. {
  2029. bool enable = 0 != newStencil;
  2030. DX_CHECK(device->SetRenderState(D3DRS_STENCILENABLE, enable) );
  2031. if (0 != newStencil)
  2032. {
  2033. uint32_t fstencil = unpackStencil(0, newStencil);
  2034. uint32_t bstencil = unpackStencil(1, newStencil);
  2035. uint32_t frontAndBack = bstencil != BGFX_STENCIL_NONE && bstencil != fstencil;
  2036. DX_CHECK(device->SetRenderState(D3DRS_TWOSIDEDSTENCILMODE, 0 != frontAndBack) );
  2037. uint32_t fchanged = unpackStencil(0, changedStencil);
  2038. if ( (BGFX_STENCIL_FUNC_REF_MASK|BGFX_STENCIL_FUNC_RMASK_MASK) & fchanged)
  2039. {
  2040. uint32_t ref = (fstencil&BGFX_STENCIL_FUNC_REF_MASK)>>BGFX_STENCIL_FUNC_REF_SHIFT;
  2041. DX_CHECK(device->SetRenderState(D3DRS_STENCILREF, ref) );
  2042. uint32_t rmask = (fstencil&BGFX_STENCIL_FUNC_RMASK_MASK)>>BGFX_STENCIL_FUNC_RMASK_SHIFT;
  2043. DX_CHECK(device->SetRenderState(D3DRS_STENCILMASK, rmask) );
  2044. }
  2045. // uint32_t bchanged = unpackStencil(1, changedStencil);
  2046. // if (BGFX_STENCIL_FUNC_RMASK_MASK & bchanged)
  2047. // {
  2048. // uint32_t wmask = (bstencil&BGFX_STENCIL_FUNC_RMASK_MASK)>>BGFX_STENCIL_FUNC_RMASK_SHIFT;
  2049. // DX_CHECK(device->SetRenderState(D3DRS_STENCILWRITEMASK, wmask) );
  2050. // }
  2051. for (uint32_t ii = 0, num = frontAndBack+1; ii < num; ++ii)
  2052. {
  2053. uint32_t stencil = unpackStencil(ii, newStencil);
  2054. uint32_t changed = unpackStencil(ii, changedStencil);
  2055. if ( (BGFX_STENCIL_TEST_MASK|BGFX_STENCIL_FUNC_REF_MASK|BGFX_STENCIL_FUNC_RMASK_MASK) & changed)
  2056. {
  2057. uint32_t func = (stencil&BGFX_STENCIL_TEST_MASK)>>BGFX_STENCIL_TEST_SHIFT;
  2058. DX_CHECK(device->SetRenderState(s_stencilFuncRs[ii], s_stencilFunc[func]) );
  2059. }
  2060. if ( (BGFX_STENCIL_OP_FAIL_S_MASK|BGFX_STENCIL_OP_FAIL_Z_MASK|BGFX_STENCIL_OP_PASS_Z_MASK) & changed)
  2061. {
  2062. uint32_t sfail = (stencil&BGFX_STENCIL_OP_FAIL_S_MASK)>>BGFX_STENCIL_OP_FAIL_S_SHIFT;
  2063. DX_CHECK(device->SetRenderState(s_stencilFailRs[ii], s_stencilOp[sfail]) );
  2064. uint32_t zfail = (stencil&BGFX_STENCIL_OP_FAIL_Z_MASK)>>BGFX_STENCIL_OP_FAIL_Z_SHIFT;
  2065. DX_CHECK(device->SetRenderState(s_stencilZFailRs[ii], s_stencilOp[zfail]) );
  2066. uint32_t zpass = (stencil&BGFX_STENCIL_OP_PASS_Z_MASK)>>BGFX_STENCIL_OP_PASS_Z_SHIFT;
  2067. DX_CHECK(device->SetRenderState(s_stencilZPassRs[ii], s_stencilOp[zpass]) );
  2068. }
  2069. }
  2070. }
  2071. }
  2072. if ( (0
  2073. | BGFX_STATE_CULL_MASK
  2074. | BGFX_STATE_DEPTH_WRITE
  2075. | BGFX_STATE_DEPTH_TEST_MASK
  2076. | BGFX_STATE_ALPHA_MASK
  2077. | BGFX_STATE_RGB_WRITE
  2078. | BGFX_STATE_BLEND_MASK
  2079. | BGFX_STATE_BLEND_EQUATION_MASK
  2080. | BGFX_STATE_ALPHA_REF_MASK
  2081. | BGFX_STATE_PT_MASK
  2082. | BGFX_STATE_POINT_SIZE_MASK
  2083. | BGFX_STATE_MSAA
  2084. ) & changedFlags)
  2085. {
  2086. if (BGFX_STATE_CULL_MASK & changedFlags)
  2087. {
  2088. uint32_t cull = (newFlags&BGFX_STATE_CULL_MASK)>>BGFX_STATE_CULL_SHIFT;
  2089. DX_CHECK(device->SetRenderState(D3DRS_CULLMODE, s_cullMode[cull]) );
  2090. }
  2091. if (BGFX_STATE_DEPTH_WRITE & changedFlags)
  2092. {
  2093. DX_CHECK(device->SetRenderState(D3DRS_ZWRITEENABLE, !!(BGFX_STATE_DEPTH_WRITE & newFlags) ) );
  2094. }
  2095. if (BGFX_STATE_DEPTH_TEST_MASK & changedFlags)
  2096. {
  2097. uint32_t func = (newFlags&BGFX_STATE_DEPTH_TEST_MASK)>>BGFX_STATE_DEPTH_TEST_SHIFT;
  2098. DX_CHECK(device->SetRenderState(D3DRS_ZENABLE, 0 != func) );
  2099. if (0 != func)
  2100. {
  2101. DX_CHECK(device->SetRenderState(D3DRS_ZFUNC, s_depthFunc[func]) );
  2102. }
  2103. }
  2104. if (BGFX_STATE_ALPHA_REF_MASK & changedFlags)
  2105. {
  2106. uint32_t ref = (newFlags&BGFX_STATE_ALPHA_REF_MASK)>>BGFX_STATE_ALPHA_REF_SHIFT;
  2107. alphaRef = ref/255.0f;
  2108. }
  2109. if ( (BGFX_STATE_PT_POINTS|BGFX_STATE_POINT_SIZE_MASK) & changedFlags)
  2110. {
  2111. DX_CHECK(device->SetRenderState(D3DRS_POINTSIZE, castfu( (float)( (newFlags&BGFX_STATE_POINT_SIZE_MASK)>>BGFX_STATE_POINT_SIZE_SHIFT) ) ) );
  2112. }
  2113. if (BGFX_STATE_MSAA & changedFlags)
  2114. {
  2115. DX_CHECK(device->SetRenderState(D3DRS_MULTISAMPLEANTIALIAS, (newFlags&BGFX_STATE_MSAA) == BGFX_STATE_MSAA) );
  2116. }
  2117. if ( (BGFX_STATE_ALPHA_WRITE|BGFX_STATE_RGB_WRITE) & changedFlags)
  2118. {
  2119. uint32_t writeEnable = (newFlags&BGFX_STATE_ALPHA_WRITE) ? D3DCOLORWRITEENABLE_ALPHA : 0;
  2120. writeEnable |= (newFlags&BGFX_STATE_RGB_WRITE) ? D3DCOLORWRITEENABLE_RED|D3DCOLORWRITEENABLE_GREEN|D3DCOLORWRITEENABLE_BLUE : 0;
  2121. DX_CHECK(device->SetRenderState(D3DRS_COLORWRITEENABLE, writeEnable) );
  2122. }
  2123. if ( (BGFX_STATE_BLEND_MASK|BGFX_STATE_BLEND_EQUATION_MASK) & changedFlags)
  2124. {
  2125. bool alphaBlendEnabled = !!(BGFX_STATE_BLEND_MASK & newFlags);
  2126. DX_CHECK(device->SetRenderState(D3DRS_ALPHABLENDENABLE, alphaBlendEnabled) );
  2127. // DX_CHECK(device->SetRenderState(D3DRS_SEPARATEALPHABLENDENABLE, alphaBlendEnabled) );
  2128. if (alphaBlendEnabled)
  2129. {
  2130. uint32_t blend = (newFlags&BGFX_STATE_BLEND_MASK)>>BGFX_STATE_BLEND_SHIFT;
  2131. uint32_t equation = (newFlags&BGFX_STATE_BLEND_EQUATION_MASK)>>BGFX_STATE_BLEND_EQUATION_SHIFT;
  2132. uint32_t src = blend&0xf;
  2133. uint32_t dst = (blend>>4)&0xf;
  2134. DX_CHECK(device->SetRenderState(D3DRS_SRCBLEND, s_blendFactor[src].m_src) );
  2135. DX_CHECK(device->SetRenderState(D3DRS_DESTBLEND, s_blendFactor[dst].m_dst) );
  2136. DX_CHECK(device->SetRenderState(D3DRS_BLENDOP, s_blendEquation[equation]) );
  2137. // DX_CHECK(device->SetRenderState(D3DRS_SRCBLENDALPHA, D3DBLEND_SRCALPHA) );
  2138. // DX_CHECK(device->SetRenderState(D3DRS_DESTBLENDALPHA, D3DBLEND_INVSRCALPHA) );
  2139. if ( (s_blendFactor[src].m_factor || s_blendFactor[dst].m_factor)
  2140. && blendFactor != state.m_rgba)
  2141. {
  2142. blendFactor = state.m_rgba;
  2143. D3DCOLOR color = D3DCOLOR_RGBA(blendFactor>>24, (blendFactor>>16)&0xff, (blendFactor>>8)&0xff, blendFactor&0xff);
  2144. DX_CHECK(device->SetRenderState(D3DRS_BLENDFACTOR, color) );
  2145. }
  2146. }
  2147. }
  2148. uint8_t primIndex = uint8_t( (newFlags&BGFX_STATE_PT_MASK)>>BGFX_STATE_PT_SHIFT);
  2149. primType = s_primType[primIndex];
  2150. primNumVerts = 3-primIndex;
  2151. }
  2152. bool programChanged = false;
  2153. bool constantsChanged = state.m_constBegin < state.m_constEnd;
  2154. rendererUpdateUniforms(m_render->m_constantBuffer, state.m_constBegin, state.m_constEnd);
  2155. if (key.m_program != programIdx)
  2156. {
  2157. programIdx = key.m_program;
  2158. if (invalidHandle == programIdx)
  2159. {
  2160. device->SetVertexShader(NULL);
  2161. device->SetPixelShader(NULL);
  2162. }
  2163. else
  2164. {
  2165. Program& program = s_renderCtx->m_program[programIdx];
  2166. device->SetVertexShader( (IDirect3DVertexShader9*)program.m_vsh->m_ptr);
  2167. device->SetPixelShader( (IDirect3DPixelShader9*)program.m_fsh->m_ptr);
  2168. }
  2169. programChanged =
  2170. constantsChanged = true;
  2171. }
  2172. if (invalidHandle != programIdx)
  2173. {
  2174. Program& program = s_renderCtx->m_program[programIdx];
  2175. if (constantsChanged)
  2176. {
  2177. program.commit();
  2178. }
  2179. for (uint32_t ii = 0, num = program.m_numPredefined; ii < num; ++ii)
  2180. {
  2181. PredefinedUniform& predefined = program.m_predefined[ii];
  2182. uint8_t flags = predefined.m_type&BGFX_UNIFORM_FRAGMENTBIT;
  2183. switch (predefined.m_type&(~BGFX_UNIFORM_FRAGMENTBIT) )
  2184. {
  2185. case PredefinedUniform::ViewRect:
  2186. {
  2187. float rect[4];
  2188. rect[0] = m_render->m_rect[view].m_x;
  2189. rect[1] = m_render->m_rect[view].m_y;
  2190. rect[2] = m_render->m_rect[view].m_width;
  2191. rect[3] = m_render->m_rect[view].m_height;
  2192. s_renderCtx->setShaderConstantF(flags, predefined.m_loc, &rect[0], 1);
  2193. }
  2194. break;
  2195. case PredefinedUniform::ViewTexel:
  2196. {
  2197. float rect[4];
  2198. rect[0] = 1.0f/float(m_render->m_rect[view].m_width);
  2199. rect[1] = 1.0f/float(m_render->m_rect[view].m_height);
  2200. s_renderCtx->setShaderConstantF(flags, predefined.m_loc, &rect[0], 1);
  2201. }
  2202. break;
  2203. case PredefinedUniform::View:
  2204. {
  2205. s_renderCtx->setShaderConstantF(flags, predefined.m_loc, m_render->m_view[view].val, bx::uint32_min(4, predefined.m_count) );
  2206. }
  2207. break;
  2208. case PredefinedUniform::ViewProj:
  2209. {
  2210. s_renderCtx->setShaderConstantF(flags, predefined.m_loc, viewProj[view].val, bx::uint32_min(4, predefined.m_count) );
  2211. }
  2212. break;
  2213. case PredefinedUniform::Model:
  2214. {
  2215. const Matrix4& model = m_render->m_matrixCache.m_cache[state.m_matrix];
  2216. s_renderCtx->setShaderConstantF(flags, predefined.m_loc, model.val, bx::uint32_min(state.m_num*4, predefined.m_count) );
  2217. }
  2218. break;
  2219. case PredefinedUniform::ModelView:
  2220. {
  2221. Matrix4 modelView;
  2222. const Matrix4& model = m_render->m_matrixCache.m_cache[state.m_matrix];
  2223. mtxMul(modelView.val, model.val, m_render->m_view[view].val);
  2224. s_renderCtx->setShaderConstantF(flags, predefined.m_loc, modelView.val, bx::uint32_min(4, predefined.m_count) );
  2225. }
  2226. break;
  2227. case PredefinedUniform::ModelViewProj:
  2228. {
  2229. Matrix4 modelViewProj;
  2230. const Matrix4& model = m_render->m_matrixCache.m_cache[state.m_matrix];
  2231. mtxMul(modelViewProj.val, model.val, viewProj[view].val);
  2232. s_renderCtx->setShaderConstantF(flags, predefined.m_loc, modelViewProj.val, bx::uint32_min(4, predefined.m_count) );
  2233. }
  2234. break;
  2235. case PredefinedUniform::ModelViewProjX:
  2236. {
  2237. const Matrix4& model = m_render->m_matrixCache.m_cache[state.m_matrix];
  2238. static const BX_ALIGN_STRUCT_16(float) s_bias[16] =
  2239. {
  2240. 0.5f, 0.0f, 0.0f, 0.0f,
  2241. 0.0f, 0.5f, 0.0f, 0.0f,
  2242. 0.0f, 0.0f, 0.5f, 0.0f,
  2243. 0.5f, 0.5f, 0.5f, 1.0f,
  2244. };
  2245. uint8_t other = m_render->m_other[view];
  2246. Matrix4 viewProjBias;
  2247. mtxMul(viewProjBias.val, viewProj[other].val, s_bias);
  2248. Matrix4 modelViewProj;
  2249. mtxMul(modelViewProj.val, model.val, viewProjBias.val);
  2250. s_renderCtx->setShaderConstantF(flags, predefined.m_loc, modelViewProj.val, bx::uint32_min(4, predefined.m_count) );
  2251. }
  2252. break;
  2253. case PredefinedUniform::ViewProjX:
  2254. {
  2255. static const BX_ALIGN_STRUCT_16(float) s_bias[16] =
  2256. {
  2257. 0.5f, 0.0f, 0.0f, 0.0f,
  2258. 0.0f, 0.5f, 0.0f, 0.0f,
  2259. 0.0f, 0.0f, 0.5f, 0.0f,
  2260. 0.5f, 0.5f, 0.5f, 1.0f,
  2261. };
  2262. uint8_t other = m_render->m_other[view];
  2263. Matrix4 viewProjBias;
  2264. mtxMul(viewProjBias.val, viewProj[other].val, s_bias);
  2265. s_renderCtx->setShaderConstantF(flags, predefined.m_loc, viewProjBias.val, bx::uint32_min(4, predefined.m_count) );
  2266. }
  2267. break;
  2268. case PredefinedUniform::AlphaRef:
  2269. {
  2270. s_renderCtx->setShaderConstantF(flags, predefined.m_loc, &alphaRef, 1);
  2271. }
  2272. break;
  2273. default:
  2274. BX_CHECK(false, "predefined %d not handled", predefined.m_type);
  2275. break;
  2276. }
  2277. }
  2278. }
  2279. // if (BGFX_STATE_TEX_MASK & changedFlags)
  2280. {
  2281. uint64_t flag = BGFX_STATE_TEX0;
  2282. for (uint32_t stage = 0; stage < BGFX_STATE_TEX_COUNT; ++stage)
  2283. {
  2284. const Sampler& sampler = state.m_sampler[stage];
  2285. Sampler& current = currentState.m_sampler[stage];
  2286. if (current.m_idx != sampler.m_idx
  2287. || current.m_flags != sampler.m_flags
  2288. || programChanged)
  2289. {
  2290. if (invalidHandle != sampler.m_idx)
  2291. {
  2292. switch (sampler.m_flags&BGFX_SAMPLER_TYPE_MASK)
  2293. {
  2294. case BGFX_SAMPLER_TEXTURE:
  2295. s_renderCtx->m_textures[sampler.m_idx].commit(stage, sampler.m_flags);
  2296. break;
  2297. case BGFX_SAMPLER_RENDERTARGET_COLOR:
  2298. s_renderCtx->m_renderTargets[sampler.m_idx].commit(stage, sampler.m_flags);
  2299. break;
  2300. case BGFX_SAMPLER_RENDERTARGET_DEPTH:
  2301. // id = s_renderCtx->m_renderTargets[sampler.m_idx].m_depth.m_id;
  2302. break;
  2303. }
  2304. }
  2305. else
  2306. {
  2307. DX_CHECK(device->SetTexture(stage, NULL) );
  2308. }
  2309. }
  2310. current = sampler;
  2311. flag <<= 1;
  2312. }
  2313. }
  2314. if (programChanged
  2315. || currentState.m_vertexBuffer.idx != state.m_vertexBuffer.idx
  2316. || currentState.m_instanceDataBuffer.idx != state.m_instanceDataBuffer.idx
  2317. || currentState.m_instanceDataOffset != state.m_instanceDataOffset
  2318. || currentState.m_instanceDataStride != state.m_instanceDataStride)
  2319. {
  2320. currentState.m_vertexBuffer = state.m_vertexBuffer;
  2321. currentState.m_instanceDataBuffer.idx = state.m_instanceDataBuffer.idx;
  2322. currentState.m_instanceDataOffset = state.m_instanceDataOffset;
  2323. currentState.m_instanceDataStride = state.m_instanceDataStride;
  2324. uint16_t handle = state.m_vertexBuffer.idx;
  2325. if (invalidHandle != handle)
  2326. {
  2327. const VertexBuffer& vb = s_renderCtx->m_vertexBuffers[handle];
  2328. uint16_t decl = !isValid(vb.m_decl) ? state.m_vertexDecl.idx : vb.m_decl.idx;
  2329. const VertexDeclaration& vertexDecl = s_renderCtx->m_vertexDecls[decl];
  2330. DX_CHECK(device->SetStreamSource(0, vb.m_ptr, 0, vertexDecl.m_decl.m_stride) );
  2331. if (isValid(state.m_instanceDataBuffer)
  2332. && s_renderCtx->m_instancing)
  2333. {
  2334. const VertexBuffer& inst = s_renderCtx->m_vertexBuffers[state.m_instanceDataBuffer.idx];
  2335. DX_CHECK(device->SetStreamSourceFreq(0, D3DSTREAMSOURCE_INDEXEDDATA|state.m_numInstances) );
  2336. DX_CHECK(device->SetStreamSourceFreq(1, D3DSTREAMSOURCE_INSTANCEDATA|1) );
  2337. DX_CHECK(device->SetStreamSource(1, inst.m_ptr, state.m_instanceDataOffset, state.m_instanceDataStride) );
  2338. IDirect3DVertexDeclaration9* ptr = createVertexDecl(vertexDecl.m_decl, state.m_instanceDataStride/16);
  2339. DX_CHECK(device->SetVertexDeclaration(ptr) );
  2340. DX_RELEASE(ptr, 0);
  2341. }
  2342. else
  2343. {
  2344. DX_CHECK(device->SetStreamSourceFreq(0, 1) );
  2345. DX_CHECK(device->SetStreamSource(1, NULL, 0, 0) );
  2346. DX_CHECK(device->SetVertexDeclaration(vertexDecl.m_ptr) );
  2347. }
  2348. }
  2349. else
  2350. {
  2351. DX_CHECK(device->SetStreamSource(0, NULL, 0, 0) );
  2352. DX_CHECK(device->SetStreamSource(1, NULL, 0, 0) );
  2353. }
  2354. }
  2355. if (currentState.m_indexBuffer.idx != state.m_indexBuffer.idx)
  2356. {
  2357. currentState.m_indexBuffer = state.m_indexBuffer;
  2358. uint16_t handle = state.m_indexBuffer.idx;
  2359. if (invalidHandle != handle)
  2360. {
  2361. const IndexBuffer& ib = s_renderCtx->m_indexBuffers[handle];
  2362. DX_CHECK(device->SetIndices(ib.m_ptr) );
  2363. }
  2364. else
  2365. {
  2366. DX_CHECK(device->SetIndices(NULL) );
  2367. }
  2368. }
  2369. if (isValid(currentState.m_vertexBuffer) )
  2370. {
  2371. uint32_t numVertices = state.m_numVertices;
  2372. if (UINT32_MAX == numVertices)
  2373. {
  2374. const VertexBuffer& vb = s_renderCtx->m_vertexBuffers[currentState.m_vertexBuffer.idx];
  2375. uint16_t decl = !isValid(vb.m_decl) ? state.m_vertexDecl.idx : vb.m_decl.idx;
  2376. const VertexDeclaration& vertexDecl = s_renderCtx->m_vertexDecls[decl];
  2377. numVertices = vb.m_size/vertexDecl.m_decl.m_stride;
  2378. }
  2379. uint32_t numIndices = 0;
  2380. uint32_t numPrimsSubmitted = 0;
  2381. uint32_t numInstances = 0;
  2382. uint32_t numPrimsRendered = 0;
  2383. if (isValid(state.m_indexBuffer) )
  2384. {
  2385. if (UINT32_MAX == state.m_numIndices)
  2386. {
  2387. numIndices = s_renderCtx->m_indexBuffers[state.m_indexBuffer.idx].m_size/2;
  2388. numPrimsSubmitted = numIndices/primNumVerts;
  2389. numInstances = state.m_numInstances;
  2390. numPrimsRendered = numPrimsSubmitted*state.m_numInstances;
  2391. DX_CHECK(device->DrawIndexedPrimitive(primType
  2392. , state.m_startVertex
  2393. , 0
  2394. , numVertices
  2395. , 0
  2396. , numPrimsSubmitted
  2397. ) );
  2398. }
  2399. else if (primNumVerts <= state.m_numIndices)
  2400. {
  2401. numIndices = state.m_numIndices;
  2402. numPrimsSubmitted = numIndices/primNumVerts;
  2403. numInstances = state.m_numInstances;
  2404. numPrimsRendered = numPrimsSubmitted*state.m_numInstances;
  2405. DX_CHECK(device->DrawIndexedPrimitive(primType
  2406. , state.m_startVertex
  2407. , 0
  2408. , numVertices
  2409. , state.m_startIndex
  2410. , numPrimsSubmitted
  2411. ) );
  2412. }
  2413. }
  2414. else
  2415. {
  2416. numPrimsSubmitted = numVertices/primNumVerts;
  2417. numInstances = state.m_numInstances;
  2418. numPrimsRendered = numPrimsSubmitted*state.m_numInstances;
  2419. DX_CHECK(device->DrawPrimitive(primType
  2420. , state.m_startVertex
  2421. , numPrimsSubmitted
  2422. ) );
  2423. }
  2424. statsNumPrimsSubmitted += numPrimsSubmitted;
  2425. statsNumIndices += numIndices;
  2426. statsNumInstances += numInstances;
  2427. statsNumPrimsRendered += numPrimsRendered;
  2428. }
  2429. }
  2430. PIX_ENDEVENT();
  2431. if (0 < m_render->m_num)
  2432. {
  2433. captureElapsed = -bx::getHPCounter();
  2434. s_renderCtx->capture();
  2435. captureElapsed += bx::getHPCounter();
  2436. }
  2437. }
  2438. int64_t now = bx::getHPCounter();
  2439. elapsed += now;
  2440. static int64_t last = now;
  2441. int64_t frameTime = now - last;
  2442. last = now;
  2443. static int64_t min = frameTime;
  2444. static int64_t max = frameTime;
  2445. min = min > frameTime ? frameTime : min;
  2446. max = max < frameTime ? frameTime : max;
  2447. if (m_render->m_debug & (BGFX_DEBUG_IFH|BGFX_DEBUG_STATS) )
  2448. {
  2449. PIX_BEGINEVENT(D3DCOLOR_RGBA(0x40, 0x40, 0x40, 0xff), L"debugstats");
  2450. TextVideoMem& tvm = s_renderCtx->m_textVideoMem;
  2451. static int64_t next = now;
  2452. if (now >= next)
  2453. {
  2454. next = now + bx::getHPFrequency();
  2455. double freq = double(bx::getHPFrequency() );
  2456. double toMs = 1000.0/freq;
  2457. tvm.clear();
  2458. uint16_t pos = 0;
  2459. tvm.printf(0, pos++, BGFX_CONFIG_DEBUG ? 0x89 : 0x8f, " " BGFX_RENDERER_NAME " / " BX_COMPILER_NAME " / " BX_CPU_NAME " / " BX_ARCH_NAME " / " BX_PLATFORM_NAME " ");
  2460. const D3DADAPTER_IDENTIFIER9& identifier = s_renderCtx->m_identifier;
  2461. tvm.printf(0, pos++, 0x0f, " Device: %s (%s)", identifier.Description, identifier.Driver);
  2462. pos = 10;
  2463. tvm.printf(10, pos++, 0x8e, " Frame: %7.3f, % 7.3f \x1f, % 7.3f \x1e [ms] / % 6.2f FPS%s"
  2464. , double(frameTime)*toMs
  2465. , double(min)*toMs
  2466. , double(max)*toMs
  2467. , freq/frameTime
  2468. , !!(m_resolution.m_flags&BGFX_RESET_VSYNC) ? " (vsync)" : ""
  2469. );
  2470. double elapsedCpuMs = double(elapsed)*toMs;
  2471. tvm.printf(10, pos++, 0x8e, " Draw calls: %4d / CPU %3.4f [ms]"
  2472. , m_render->m_num
  2473. , elapsedCpuMs
  2474. );
  2475. tvm.printf(10, pos++, 0x8e, " Prims: %7d (#inst: %5d), submitted: %7d"
  2476. , statsNumPrimsRendered
  2477. , statsNumInstances
  2478. , statsNumPrimsSubmitted
  2479. );
  2480. double captureMs = double(captureElapsed)*toMs;
  2481. tvm.printf(10, pos++, 0x8e, " Capture: %3.4f [ms]", captureMs);
  2482. tvm.printf(10, pos++, 0x8e, " Indices: %7d", statsNumIndices);
  2483. tvm.printf(10, pos++, 0x8e, " DVB size: %7d", m_render->m_vboffset);
  2484. tvm.printf(10, pos++, 0x8e, " DIB size: %7d", m_render->m_iboffset);
  2485. uint8_t attr[2] = { 0x89, 0x8a };
  2486. uint8_t attrIndex = m_render->m_waitSubmit < m_render->m_waitRender;
  2487. tvm.printf(10, pos++, attr[attrIndex&1], "Submit wait: %3.4f [ms]", m_render->m_waitSubmit*toMs);
  2488. tvm.printf(10, pos++, attr[(attrIndex+1)&1], "Render wait: %3.4f [ms]", m_render->m_waitRender*toMs);
  2489. min = frameTime;
  2490. max = frameTime;
  2491. }
  2492. m_textVideoMemBlitter.blit(tvm);
  2493. PIX_ENDEVENT();
  2494. }
  2495. else if (m_render->m_debug & BGFX_DEBUG_TEXT)
  2496. {
  2497. PIX_BEGINEVENT(D3DCOLOR_RGBA(0x40, 0x40, 0x40, 0xff), L"debugtext");
  2498. m_textVideoMemBlitter.blit(m_render->m_textVideoMem);
  2499. PIX_ENDEVENT();
  2500. }
  2501. device->EndScene();
  2502. }
  2503. }
  2504. #endif // BGFX_CONFIG_RENDERER_DIRECT3D9