renderer_d3d9.cpp 104 KB

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