renderer_d3d9.cpp 96 KB

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