renderer_d3d9.cpp 103 KB

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