renderer_d3d9.cpp 86 KB

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