renderer_d3d9.cpp 124 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506
  1. /*
  2. * Copyright 2011-2017 Branimir Karadzic. All rights reserved.
  3. * License: https://github.com/bkaradzic/bgfx#license-bsd-2-clause
  4. */
  5. #include "bgfx_p.h"
  6. #if BGFX_CONFIG_RENDERER_DIRECT3D9
  7. # include "renderer_d3d9.h"
  8. # include <bx/pixelformat.h>
  9. namespace bgfx { namespace d3d9
  10. {
  11. static wchar_t s_viewNameW[BGFX_CONFIG_MAX_VIEWS][BGFX_CONFIG_MAX_VIEW_NAME];
  12. static char s_viewName[BGFX_CONFIG_MAX_VIEWS][BGFX_CONFIG_MAX_VIEW_NAME];
  13. struct PrimInfo
  14. {
  15. D3DPRIMITIVETYPE m_type;
  16. uint32_t m_min;
  17. uint32_t m_div;
  18. uint32_t m_sub;
  19. };
  20. static const PrimInfo s_primInfo[] =
  21. {
  22. { D3DPT_TRIANGLELIST, 3, 3, 0 },
  23. { D3DPT_TRIANGLESTRIP, 3, 1, 2 },
  24. { D3DPT_LINELIST, 2, 2, 0 },
  25. { D3DPT_LINESTRIP, 2, 1, 1 },
  26. { D3DPT_POINTLIST, 1, 1, 0 },
  27. { D3DPRIMITIVETYPE(0), 0, 0, 0 },
  28. };
  29. static const char* s_primName[] =
  30. {
  31. "TriList",
  32. "TriStrip",
  33. "Line",
  34. "LineStrip",
  35. "Point",
  36. };
  37. BX_STATIC_ASSERT(BX_COUNTOF(s_primInfo) == BX_COUNTOF(s_primName)+1);
  38. static const D3DMULTISAMPLE_TYPE s_checkMsaa[] =
  39. {
  40. D3DMULTISAMPLE_NONE,
  41. D3DMULTISAMPLE_2_SAMPLES,
  42. D3DMULTISAMPLE_4_SAMPLES,
  43. D3DMULTISAMPLE_8_SAMPLES,
  44. D3DMULTISAMPLE_16_SAMPLES,
  45. };
  46. static Msaa s_msaa[] =
  47. {
  48. { D3DMULTISAMPLE_NONE, 0 },
  49. { D3DMULTISAMPLE_2_SAMPLES, 0 },
  50. { D3DMULTISAMPLE_4_SAMPLES, 0 },
  51. { D3DMULTISAMPLE_8_SAMPLES, 0 },
  52. { D3DMULTISAMPLE_16_SAMPLES, 0 },
  53. };
  54. struct Blend
  55. {
  56. D3DBLEND m_src;
  57. D3DBLEND m_dst;
  58. bool m_factor;
  59. };
  60. static const Blend s_blendFactor[] =
  61. {
  62. { (D3DBLEND)0, (D3DBLEND)0, false }, // ignored
  63. { D3DBLEND_ZERO, D3DBLEND_ZERO, false }, // ZERO
  64. { D3DBLEND_ONE, D3DBLEND_ONE, false }, // ONE
  65. { D3DBLEND_SRCCOLOR, D3DBLEND_SRCCOLOR, false }, // SRC_COLOR
  66. { D3DBLEND_INVSRCCOLOR, D3DBLEND_INVSRCCOLOR, false }, // INV_SRC_COLOR
  67. { D3DBLEND_SRCALPHA, D3DBLEND_SRCALPHA, false }, // SRC_ALPHA
  68. { D3DBLEND_INVSRCALPHA, D3DBLEND_INVSRCALPHA, false }, // INV_SRC_ALPHA
  69. { D3DBLEND_DESTALPHA, D3DBLEND_DESTALPHA, false }, // DST_ALPHA
  70. { D3DBLEND_INVDESTALPHA, D3DBLEND_INVDESTALPHA, false }, // INV_DST_ALPHA
  71. { D3DBLEND_DESTCOLOR, D3DBLEND_DESTCOLOR, false }, // DST_COLOR
  72. { D3DBLEND_INVDESTCOLOR, D3DBLEND_INVDESTCOLOR, false }, // INV_DST_COLOR
  73. { D3DBLEND_SRCALPHASAT, D3DBLEND_ONE, false }, // SRC_ALPHA_SAT
  74. { D3DBLEND_BLENDFACTOR, D3DBLEND_BLENDFACTOR, true }, // FACTOR
  75. { D3DBLEND_INVBLENDFACTOR, D3DBLEND_INVBLENDFACTOR, true }, // INV_FACTOR
  76. };
  77. static const D3DBLENDOP s_blendEquation[] =
  78. {
  79. D3DBLENDOP_ADD,
  80. D3DBLENDOP_SUBTRACT,
  81. D3DBLENDOP_REVSUBTRACT,
  82. D3DBLENDOP_MIN,
  83. D3DBLENDOP_MAX,
  84. };
  85. static const D3DCMPFUNC s_cmpFunc[] =
  86. {
  87. (D3DCMPFUNC)0, // ignored
  88. D3DCMP_LESS,
  89. D3DCMP_LESSEQUAL,
  90. D3DCMP_EQUAL,
  91. D3DCMP_GREATEREQUAL,
  92. D3DCMP_GREATER,
  93. D3DCMP_NOTEQUAL,
  94. D3DCMP_NEVER,
  95. D3DCMP_ALWAYS,
  96. };
  97. static const D3DSTENCILOP s_stencilOp[] =
  98. {
  99. D3DSTENCILOP_ZERO,
  100. D3DSTENCILOP_KEEP,
  101. D3DSTENCILOP_REPLACE,
  102. D3DSTENCILOP_INCR,
  103. D3DSTENCILOP_INCRSAT,
  104. D3DSTENCILOP_DECR,
  105. D3DSTENCILOP_DECRSAT,
  106. D3DSTENCILOP_INVERT,
  107. };
  108. static const D3DRENDERSTATETYPE s_stencilFuncRs[] =
  109. {
  110. D3DRS_STENCILFUNC,
  111. D3DRS_CCW_STENCILFUNC,
  112. };
  113. static const D3DRENDERSTATETYPE s_stencilFailRs[] =
  114. {
  115. D3DRS_STENCILFAIL,
  116. D3DRS_CCW_STENCILFAIL,
  117. };
  118. static const D3DRENDERSTATETYPE s_stencilZFailRs[] =
  119. {
  120. D3DRS_STENCILZFAIL,
  121. D3DRS_CCW_STENCILZFAIL,
  122. };
  123. static const D3DRENDERSTATETYPE s_stencilZPassRs[] =
  124. {
  125. D3DRS_STENCILPASS,
  126. D3DRS_CCW_STENCILPASS,
  127. };
  128. static const D3DCULL s_cullMode[] =
  129. {
  130. D3DCULL_NONE,
  131. D3DCULL_CW,
  132. D3DCULL_CCW,
  133. };
  134. static const D3DTEXTUREADDRESS s_textureAddress[] =
  135. {
  136. D3DTADDRESS_WRAP,
  137. D3DTADDRESS_MIRROR,
  138. D3DTADDRESS_CLAMP,
  139. D3DTADDRESS_BORDER,
  140. };
  141. static const D3DTEXTUREFILTERTYPE s_textureFilter[] =
  142. {
  143. D3DTEXF_LINEAR,
  144. D3DTEXF_POINT,
  145. D3DTEXF_ANISOTROPIC,
  146. };
  147. struct TextureFormatInfo
  148. {
  149. D3DFORMAT m_fmt;
  150. };
  151. static TextureFormatInfo s_textureFormat[] =
  152. {
  153. { D3DFMT_DXT1 }, // BC1
  154. { D3DFMT_DXT3 }, // BC2
  155. { D3DFMT_DXT5 }, // BC3
  156. { D3DFMT_UNKNOWN }, // BC4
  157. { D3DFMT_UNKNOWN }, // BC5
  158. { D3DFMT_UNKNOWN }, // BC6H
  159. { D3DFMT_UNKNOWN }, // BC7
  160. { D3DFMT_UNKNOWN }, // ETC1
  161. { D3DFMT_UNKNOWN }, // ETC2
  162. { D3DFMT_UNKNOWN }, // ETC2A
  163. { D3DFMT_UNKNOWN }, // ETC2A1
  164. { D3DFMT_UNKNOWN }, // PTC12
  165. { D3DFMT_UNKNOWN }, // PTC14
  166. { D3DFMT_UNKNOWN }, // PTC12A
  167. { D3DFMT_UNKNOWN }, // PTC14A
  168. { D3DFMT_UNKNOWN }, // PTC22
  169. { D3DFMT_UNKNOWN }, // PTC24
  170. { D3DFMT_UNKNOWN }, // Unknown
  171. { D3DFMT_A1 }, // R1
  172. { D3DFMT_A8 }, // A8
  173. { D3DFMT_L8 }, // R8
  174. { D3DFMT_UNKNOWN }, // R8I
  175. { D3DFMT_UNKNOWN }, // R8U
  176. { D3DFMT_UNKNOWN }, // R8S
  177. { D3DFMT_L16 }, // R16
  178. { D3DFMT_UNKNOWN }, // R16I
  179. { D3DFMT_UNKNOWN }, // R16U
  180. { D3DFMT_R16F }, // R16F
  181. { D3DFMT_UNKNOWN }, // R16S
  182. { D3DFMT_UNKNOWN }, // R32I
  183. { D3DFMT_UNKNOWN }, // R32U
  184. { D3DFMT_R32F }, // R32F
  185. { D3DFMT_A8L8 }, // RG8
  186. { D3DFMT_UNKNOWN }, // RG8I
  187. { D3DFMT_UNKNOWN }, // RG8U
  188. { D3DFMT_UNKNOWN }, // RG8S
  189. { D3DFMT_G16R16 }, // RG16
  190. { D3DFMT_UNKNOWN }, // RG16I
  191. { D3DFMT_UNKNOWN }, // RG16U
  192. { D3DFMT_G16R16F }, // RG16F
  193. { D3DFMT_UNKNOWN }, // RG16S
  194. { D3DFMT_UNKNOWN }, // RG32I
  195. { D3DFMT_UNKNOWN }, // RG32U
  196. { D3DFMT_G32R32F }, // RG32F
  197. { D3DFMT_UNKNOWN }, // RGB8
  198. { D3DFMT_UNKNOWN }, // RGB8I
  199. { D3DFMT_UNKNOWN }, // RGB8U
  200. { D3DFMT_UNKNOWN }, // RGB8S
  201. { D3DFMT_UNKNOWN }, // RGB9E5F
  202. { D3DFMT_A8R8G8B8 }, // BGRA8
  203. { D3DFMT_UNKNOWN }, // RGBA8
  204. { D3DFMT_UNKNOWN }, // RGBA8I
  205. { D3DFMT_UNKNOWN }, // RGBA8U
  206. { D3DFMT_UNKNOWN }, // RGBA8S
  207. { D3DFMT_A16B16G16R16 }, // RGBA16
  208. { D3DFMT_UNKNOWN }, // RGBA16I
  209. { D3DFMT_UNKNOWN }, // RGBA16U
  210. { D3DFMT_A16B16G16R16F }, // RGBA16F
  211. { D3DFMT_UNKNOWN }, // RGBA16S
  212. { D3DFMT_UNKNOWN }, // RGBA32I
  213. { D3DFMT_UNKNOWN }, // RGBA32U
  214. { D3DFMT_A32B32G32R32F }, // RGBA32F
  215. { D3DFMT_R5G6B5 }, // R5G6B5
  216. { D3DFMT_A4R4G4B4 }, // RGBA4
  217. { D3DFMT_A1R5G5B5 }, // RGB5A1
  218. { D3DFMT_A2B10G10R10 }, // RGB10A2
  219. { D3DFMT_UNKNOWN }, // RG11B10F
  220. { D3DFMT_UNKNOWN }, // UnknownDepth
  221. { D3DFMT_D16 }, // D16
  222. { D3DFMT_D24X8 }, // D24
  223. { D3DFMT_D24S8 }, // D24S8
  224. { D3DFMT_D32 }, // D32
  225. { D3DFMT_DF16 }, // D16F
  226. { D3DFMT_DF24 }, // D24F
  227. { D3DFMT_D32F_LOCKABLE }, // D32F
  228. { D3DFMT_S8_LOCKABLE }, // D0S8
  229. };
  230. BX_STATIC_ASSERT(TextureFormat::Count == BX_COUNTOF(s_textureFormat) );
  231. static ExtendedFormat s_extendedFormats[ExtendedFormat::Count] =
  232. {
  233. { D3DFMT_ATI1, 0, D3DRTYPE_TEXTURE, false },
  234. { D3DFMT_ATI2, 0, D3DRTYPE_TEXTURE, false },
  235. { D3DFMT_DF16, D3DUSAGE_DEPTHSTENCIL, D3DRTYPE_SURFACE, false },
  236. { D3DFMT_DF24, D3DUSAGE_DEPTHSTENCIL, D3DRTYPE_SURFACE, false },
  237. { D3DFMT_INST, 0, D3DRTYPE_SURFACE, false },
  238. { D3DFMT_INTZ, D3DUSAGE_DEPTHSTENCIL, D3DRTYPE_SURFACE, false },
  239. { D3DFMT_NULL, D3DUSAGE_RENDERTARGET, D3DRTYPE_SURFACE, false },
  240. { D3DFMT_RESZ, D3DUSAGE_RENDERTARGET, D3DRTYPE_SURFACE, false },
  241. { D3DFMT_RAWZ, D3DUSAGE_DEPTHSTENCIL, D3DRTYPE_SURFACE, false },
  242. { D3DFMT_ATOC, 0, D3DRTYPE_SURFACE, false },
  243. };
  244. static const GUID IID_IDirect3D9 = { 0x81bdcbca, 0x64d4, 0x426d, { 0xae, 0x8d, 0xad, 0x1, 0x47, 0xf4, 0x27, 0x5c } };
  245. static const GUID IID_IDirect3DDevice9Ex = { 0xb18b10ce, 0x2649, 0x405a, { 0x87, 0xf, 0x95, 0xf7, 0x77, 0xd4, 0x31, 0x3a } };
  246. typedef HRESULT (WINAPI *Direct3DCreate9ExFn)(UINT SDKVersion, IDirect3D9Ex**);
  247. static Direct3DCreate9ExFn Direct3DCreate9Ex;
  248. typedef IDirect3D9* (WINAPI *Direct3DCreate9Fn)(UINT SDKVersion);
  249. static Direct3DCreate9Fn Direct3DCreate9;
  250. static PFN_D3DPERF_SET_MARKER D3DPERF_SetMarker;
  251. static PFN_D3DPERF_BEGIN_EVENT D3DPERF_BeginEvent;
  252. static PFN_D3DPERF_END_EVENT D3DPERF_EndEvent;
  253. static const D3DVERTEXELEMENT9 s_attrib[] =
  254. {
  255. { 0, 0, D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_POSITION, 0 },
  256. { 0, 0, D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_NORMAL, 0 },
  257. { 0, 0, D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TANGENT, 0 },
  258. { 0, 0, D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_BINORMAL, 0 },
  259. { 0, 0, D3DDECLTYPE_UBYTE4, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_COLOR, 0 },
  260. { 0, 0, D3DDECLTYPE_UBYTE4, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_COLOR, 1 },
  261. { 0, 0, D3DDECLTYPE_UBYTE4, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_COLOR, 2 },
  262. { 0, 0, D3DDECLTYPE_UBYTE4, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_COLOR, 3 },
  263. { 0, 0, D3DDECLTYPE_UBYTE4, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_BLENDINDICES, 0 },
  264. { 0, 0, D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_BLENDWEIGHT, 0 },
  265. { 0, 0, D3DDECLTYPE_FLOAT2, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 0 },
  266. { 0, 0, D3DDECLTYPE_FLOAT2, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 1 },
  267. { 0, 0, D3DDECLTYPE_FLOAT2, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 2 },
  268. { 0, 0, D3DDECLTYPE_FLOAT2, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 3 },
  269. { 0, 0, D3DDECLTYPE_FLOAT2, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 4 },
  270. { 0, 0, D3DDECLTYPE_FLOAT2, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 5 },
  271. { 0, 0, D3DDECLTYPE_FLOAT2, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 6 },
  272. { 0, 0, D3DDECLTYPE_FLOAT2, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 7 },
  273. D3DDECL_END()
  274. };
  275. BX_STATIC_ASSERT(Attrib::Count == BX_COUNTOF(s_attrib)-1);
  276. static const uint8_t s_attribType[][4][2] =
  277. {
  278. { // Uint8
  279. { D3DDECLTYPE_UBYTE4, D3DDECLTYPE_UBYTE4N },
  280. { D3DDECLTYPE_UBYTE4, D3DDECLTYPE_UBYTE4N },
  281. { D3DDECLTYPE_UBYTE4, D3DDECLTYPE_UBYTE4N },
  282. { D3DDECLTYPE_UBYTE4, D3DDECLTYPE_UBYTE4N },
  283. },
  284. { // Uint10
  285. { D3DDECLTYPE_UDEC3, D3DDECLTYPE_DEC3N },
  286. { D3DDECLTYPE_UDEC3, D3DDECLTYPE_DEC3N },
  287. { D3DDECLTYPE_UDEC3, D3DDECLTYPE_DEC3N },
  288. { D3DDECLTYPE_UDEC3, D3DDECLTYPE_DEC3N },
  289. },
  290. { // Int16
  291. { D3DDECLTYPE_SHORT2, D3DDECLTYPE_SHORT2N },
  292. { D3DDECLTYPE_SHORT2, D3DDECLTYPE_SHORT2N },
  293. { D3DDECLTYPE_SHORT4, D3DDECLTYPE_SHORT4N },
  294. { D3DDECLTYPE_SHORT4, D3DDECLTYPE_SHORT4N },
  295. },
  296. { // Half
  297. { D3DDECLTYPE_FLOAT16_2, D3DDECLTYPE_FLOAT16_2 },
  298. { D3DDECLTYPE_FLOAT16_2, D3DDECLTYPE_FLOAT16_2 },
  299. { D3DDECLTYPE_FLOAT16_4, D3DDECLTYPE_FLOAT16_4 },
  300. { D3DDECLTYPE_FLOAT16_4, D3DDECLTYPE_FLOAT16_4 },
  301. },
  302. { // Float
  303. { D3DDECLTYPE_FLOAT1, D3DDECLTYPE_FLOAT1 },
  304. { D3DDECLTYPE_FLOAT2, D3DDECLTYPE_FLOAT2 },
  305. { D3DDECLTYPE_FLOAT3, D3DDECLTYPE_FLOAT3 },
  306. { D3DDECLTYPE_FLOAT4, D3DDECLTYPE_FLOAT4 },
  307. },
  308. };
  309. BX_STATIC_ASSERT(AttribType::Count == BX_COUNTOF(s_attribType) );
  310. static D3DVERTEXELEMENT9* fillVertexDecl(uint8_t _stream, D3DVERTEXELEMENT9* _out, const VertexDecl& _decl)
  311. {
  312. D3DVERTEXELEMENT9* elem = _out;
  313. for (uint32_t attr = 0; attr < Attrib::Count; ++attr)
  314. {
  315. if (UINT16_MAX != _decl.m_attributes[attr])
  316. {
  317. uint8_t num;
  318. AttribType::Enum type;
  319. bool normalized;
  320. bool asInt;
  321. _decl.decode(Attrib::Enum(attr), num, type, normalized, asInt);
  322. bx::memCopy(elem, &s_attrib[attr], sizeof(D3DVERTEXELEMENT9) );
  323. elem->Stream = _stream;
  324. elem->Type = s_attribType[type][num-1][normalized];
  325. elem->Offset = _decl.m_offset[attr];
  326. ++elem;
  327. }
  328. }
  329. return elem;
  330. }
  331. inline bool isLost(HRESULT _hr)
  332. {
  333. return false
  334. || _hr == D3DERR_DEVICELOST
  335. || _hr == D3DERR_DRIVERINTERNALERROR
  336. #if !defined(D3D_DISABLE_9EX)
  337. || _hr == D3DERR_DEVICEHUNG
  338. || _hr == D3DERR_DEVICEREMOVED
  339. #endif // !defined(D3D_DISABLE_9EX)
  340. ;
  341. }
  342. struct RendererContextD3D9 : public RendererContextI
  343. {
  344. RendererContextD3D9()
  345. : m_d3d9(NULL)
  346. , m_device(NULL)
  347. , m_flushQuery(NULL)
  348. , m_swapChain(NULL)
  349. , m_captureTexture(NULL)
  350. , m_captureSurface(NULL)
  351. , m_captureResolve(NULL)
  352. , m_maxAnisotropy(1)
  353. , m_initialized(false)
  354. , m_amd(false)
  355. , m_nvidia(false)
  356. , m_atocSupport(false)
  357. , m_instancingSupport(false)
  358. , m_occlusionQuerySupport(false)
  359. , m_timerQuerySupport(false)
  360. , m_rtMsaa(false)
  361. {
  362. }
  363. ~RendererContextD3D9()
  364. {
  365. }
  366. bool init()
  367. {
  368. struct ErrorState
  369. {
  370. enum Enum
  371. {
  372. Default,
  373. LoadedD3D9,
  374. CreatedD3D9,
  375. CreatedDevice,
  376. };
  377. };
  378. ErrorState::Enum errorState = ErrorState::Default;
  379. m_fbh.idx = kInvalidHandle;
  380. bx::memSet(m_uniforms, 0, sizeof(m_uniforms) );
  381. bx::memSet(&m_resolution, 0, sizeof(m_resolution) );
  382. D3DFORMAT adapterFormat = D3DFMT_X8R8G8B8;
  383. // http://msdn.microsoft.com/en-us/library/windows/desktop/bb172588%28v=vs.85%29.aspx
  384. bx::memSet(&m_params, 0, sizeof(m_params) );
  385. m_params.BackBufferWidth = BGFX_DEFAULT_WIDTH;
  386. m_params.BackBufferHeight = BGFX_DEFAULT_HEIGHT;
  387. m_params.BackBufferFormat = adapterFormat;
  388. m_params.BackBufferCount = 1;
  389. m_params.MultiSampleType = D3DMULTISAMPLE_NONE;
  390. m_params.MultiSampleQuality = 0;
  391. m_params.EnableAutoDepthStencil = TRUE;
  392. m_params.AutoDepthStencilFormat = D3DFMT_D24S8;
  393. m_params.Flags = D3DPRESENTFLAG_DISCARD_DEPTHSTENCIL;
  394. m_params.FullScreen_RefreshRateInHz = 0;
  395. m_params.PresentationInterval = D3DPRESENT_INTERVAL_IMMEDIATE;
  396. m_params.SwapEffect = D3DSWAPEFFECT_DISCARD;
  397. m_params.hDeviceWindow = NULL;
  398. m_params.Windowed = true;
  399. RECT rect;
  400. GetWindowRect( (HWND)g_platformData.nwh, &rect);
  401. m_params.BackBufferWidth = rect.right-rect.left;
  402. m_params.BackBufferHeight = rect.bottom-rect.top;
  403. m_d3d9dll = bx::dlopen("d3d9.dll");
  404. if (NULL == m_d3d9dll)
  405. {
  406. BX_TRACE("Init error: Failed to load d3d9.dll.");
  407. goto error;
  408. }
  409. errorState = ErrorState::LoadedD3D9;
  410. m_nvapi.init();
  411. if (BX_ENABLED(BGFX_CONFIG_DEBUG_PIX) )
  412. {
  413. D3DPERF_SetMarker = (PFN_D3DPERF_SET_MARKER )bx::dlsym(m_d3d9dll, "D3DPERF_SetMarker");
  414. D3DPERF_BeginEvent = (PFN_D3DPERF_BEGIN_EVENT)bx::dlsym(m_d3d9dll, "D3DPERF_BeginEvent");
  415. D3DPERF_EndEvent = (PFN_D3DPERF_END_EVENT )bx::dlsym(m_d3d9dll, "D3DPERF_EndEvent");
  416. BX_CHECK(NULL != D3DPERF_SetMarker
  417. && NULL != D3DPERF_BeginEvent
  418. && NULL != D3DPERF_EndEvent
  419. , "Failed to initialize PIX events."
  420. );
  421. }
  422. m_d3d9ex = NULL;
  423. m_deviceEx = NULL;
  424. Direct3DCreate9Ex = (Direct3DCreate9ExFn)bx::dlsym(m_d3d9dll, "Direct3DCreate9Ex");
  425. if (BX_ENABLED(BGFX_CONFIG_RENDERER_DIRECT3D9EX)
  426. && NULL != Direct3DCreate9Ex)
  427. {
  428. Direct3DCreate9Ex(D3D_SDK_VERSION, &m_d3d9ex);
  429. if (NULL != m_d3d9ex)
  430. {
  431. HRESULT hr = m_d3d9ex->QueryInterface(IID_IDirect3D9, (void**)&m_d3d9);
  432. if (FAILED(hr) )
  433. {
  434. BX_TRACE("Failed to query D3D9 interface 0x%08x.", hr);
  435. DX_RELEASE(m_d3d9ex, 0);
  436. }
  437. else
  438. {
  439. m_pool = D3DPOOL_DEFAULT;
  440. }
  441. }
  442. }
  443. if (NULL == m_d3d9)
  444. {
  445. Direct3DCreate9 = (Direct3DCreate9Fn)bx::dlsym(m_d3d9dll, "Direct3DCreate9");
  446. if (NULL == Direct3DCreate9)
  447. {
  448. BX_TRACE("Init error: Function Direct3DCreate9 not found.");
  449. goto error;
  450. }
  451. m_d3d9 = Direct3DCreate9(D3D_SDK_VERSION);
  452. m_pool = D3DPOOL_MANAGED;
  453. }
  454. if (NULL == m_d3d9)
  455. {
  456. BX_TRACE("Init error: Unable to create Direct3D.");
  457. goto error;
  458. }
  459. errorState = ErrorState::CreatedD3D9;
  460. {
  461. m_adapter = D3DADAPTER_DEFAULT;
  462. m_deviceType = BGFX_PCI_ID_SOFTWARE_RASTERIZER == g_caps.vendorId
  463. ? D3DDEVTYPE_REF
  464. : D3DDEVTYPE_HAL
  465. ;
  466. uint8_t numGPUs = uint8_t(bx::uint32_min(BX_COUNTOF(g_caps.gpu), m_d3d9->GetAdapterCount() ) );
  467. for (uint32_t ii = 0; ii < numGPUs; ++ii)
  468. {
  469. D3DADAPTER_IDENTIFIER9 desc;
  470. HRESULT hr = m_d3d9->GetAdapterIdentifier(ii, 0, &desc);
  471. if (SUCCEEDED(hr) )
  472. {
  473. BX_TRACE("Adapter #%d", ii);
  474. BX_TRACE("\tDriver: %s", desc.Driver);
  475. BX_TRACE("\tDescription: %s", desc.Description);
  476. BX_TRACE("\tDeviceName: %s", desc.DeviceName);
  477. BX_TRACE("\tVendorId: 0x%08x, DeviceId: 0x%08x, SubSysId: 0x%08x, Revision: 0x%08x"
  478. , desc.VendorId
  479. , desc.DeviceId
  480. , desc.SubSysId
  481. , desc.Revision
  482. );
  483. g_caps.gpu[ii].vendorId = (uint16_t)desc.VendorId;
  484. g_caps.gpu[ii].deviceId = (uint16_t)desc.DeviceId;
  485. if (D3DADAPTER_DEFAULT == m_adapter)
  486. {
  487. if ( (BGFX_PCI_ID_NONE != g_caps.vendorId || 0 != g_caps.deviceId)
  488. && (BGFX_PCI_ID_NONE == g_caps.vendorId || desc.VendorId == g_caps.vendorId)
  489. && ( 0 == g_caps.deviceId || desc.DeviceId == g_caps.deviceId) )
  490. {
  491. m_adapter = ii;
  492. }
  493. if (BX_ENABLED(BGFX_CONFIG_DEBUG_PERFHUD)
  494. && 0 != bx::strFind(desc.Description, "PerfHUD") )
  495. {
  496. m_adapter = ii;
  497. m_deviceType = D3DDEVTYPE_REF;
  498. }
  499. }
  500. }
  501. }
  502. DX_CHECK(m_d3d9->GetAdapterIdentifier(m_adapter, 0, &m_identifier) );
  503. m_amd = m_identifier.VendorId == BGFX_PCI_ID_AMD;
  504. m_nvidia = m_identifier.VendorId == BGFX_PCI_ID_NVIDIA;
  505. g_caps.vendorId = 0 == m_identifier.VendorId
  506. ? BGFX_PCI_ID_SOFTWARE_RASTERIZER
  507. : (uint16_t)m_identifier.VendorId
  508. ;
  509. g_caps.deviceId = (uint16_t)m_identifier.DeviceId;
  510. uint32_t behaviorFlags[] =
  511. {
  512. D3DCREATE_HARDWARE_VERTEXPROCESSING | D3DCREATE_FPU_PRESERVE | D3DCREATE_PUREDEVICE,
  513. D3DCREATE_MIXED_VERTEXPROCESSING | D3DCREATE_FPU_PRESERVE,
  514. D3DCREATE_SOFTWARE_VERTEXPROCESSING | D3DCREATE_FPU_PRESERVE,
  515. };
  516. for (uint32_t ii = 0; ii < BX_COUNTOF(behaviorFlags) && NULL == m_device; ++ii)
  517. {
  518. if (NULL != m_d3d9ex)
  519. {
  520. DX_CHECK(m_d3d9ex->CreateDeviceEx(m_adapter
  521. , m_deviceType
  522. , (HWND)g_platformData.nwh
  523. , behaviorFlags[ii]
  524. , &m_params
  525. , NULL
  526. , &m_deviceEx
  527. ) );
  528. m_device = m_deviceEx;
  529. }
  530. else
  531. {
  532. DX_CHECK(m_d3d9->CreateDevice(m_adapter
  533. , m_deviceType
  534. , (HWND)g_platformData.nwh
  535. , behaviorFlags[ii]
  536. , &m_params
  537. , &m_device
  538. ) );
  539. }
  540. }
  541. }
  542. if (NULL == m_device)
  543. {
  544. BX_TRACE("Init error: Unable to create Direct3D9 device.");
  545. goto error;
  546. }
  547. errorState = ErrorState::CreatedDevice;
  548. m_numWindows = 1;
  549. if (NULL != m_d3d9ex)
  550. {
  551. DX_CHECK(m_device->QueryInterface(IID_IDirect3DDevice9Ex, (void**)&m_deviceEx) );
  552. }
  553. {
  554. IDirect3DQuery9* timerQueryTest[3] = {};
  555. m_timerQuerySupport = true
  556. && SUCCEEDED(m_device->CreateQuery(D3DQUERYTYPE_TIMESTAMPDISJOINT, &timerQueryTest[0]) )
  557. && SUCCEEDED(m_device->CreateQuery(D3DQUERYTYPE_TIMESTAMP, &timerQueryTest[1]) )
  558. && SUCCEEDED(m_device->CreateQuery(D3DQUERYTYPE_TIMESTAMPFREQ, &timerQueryTest[2]) )
  559. ;
  560. DX_RELEASE(timerQueryTest[0], 0);
  561. DX_RELEASE(timerQueryTest[1], 0);
  562. DX_RELEASE(timerQueryTest[2], 0);
  563. }
  564. {
  565. IDirect3DQuery9* occlusionQueryTest;
  566. m_occlusionQuerySupport = true
  567. && SUCCEEDED(m_device->CreateQuery(D3DQUERYTYPE_OCCLUSION, &occlusionQueryTest) )
  568. ;
  569. DX_RELEASE(occlusionQueryTest, 0);
  570. }
  571. DX_CHECK(m_device->GetDeviceCaps(&m_caps) );
  572. // For shit GPUs that can create DX9 device but can't do simple stuff. GTFO!
  573. BX_WARN( (D3DPTEXTURECAPS_SQUAREONLY & m_caps.TextureCaps) == 0, "D3DPTEXTURECAPS_SQUAREONLY");
  574. BX_WARN( (D3DPTEXTURECAPS_MIPMAP & m_caps.TextureCaps) == D3DPTEXTURECAPS_MIPMAP, "D3DPTEXTURECAPS_MIPMAP");
  575. BX_WARN( (D3DPTEXTURECAPS_ALPHA & m_caps.TextureCaps) == D3DPTEXTURECAPS_ALPHA, "D3DPTEXTURECAPS_ALPHA");
  576. BX_WARN(m_caps.VertexShaderVersion >= D3DVS_VERSION(2, 0) && m_caps.PixelShaderVersion >= D3DPS_VERSION(2, 1)
  577. , "Shader Model Version (vs: %x, ps: %x)."
  578. , m_caps.VertexShaderVersion
  579. , m_caps.PixelShaderVersion
  580. );
  581. if ( (D3DPTEXTURECAPS_SQUAREONLY & m_caps.TextureCaps) != 0
  582. || (D3DPTEXTURECAPS_MIPMAP & m_caps.TextureCaps) != D3DPTEXTURECAPS_MIPMAP
  583. || (D3DPTEXTURECAPS_ALPHA & m_caps.TextureCaps) != D3DPTEXTURECAPS_ALPHA
  584. || !(m_caps.VertexShaderVersion >= D3DVS_VERSION(2, 0) && m_caps.PixelShaderVersion >= D3DPS_VERSION(2, 1) ) )
  585. {
  586. BX_TRACE("Init error: Min spec not satisfied.");
  587. goto error;
  588. }
  589. BX_TRACE("Max vertex shader 3.0 instr. slots: %d", m_caps.MaxVertexShader30InstructionSlots);
  590. BX_TRACE("Max vertex shader constants: %d", m_caps.MaxVertexShaderConst);
  591. BX_TRACE("Max fragment shader 2.0 instr. slots: %d", m_caps.PS20Caps.NumInstructionSlots);
  592. BX_TRACE("Max fragment shader 3.0 instr. slots: %d", m_caps.MaxPixelShader30InstructionSlots);
  593. BX_TRACE("Num simultaneous render targets: %d", m_caps.NumSimultaneousRTs);
  594. BX_TRACE("Max vertex index: %d", m_caps.MaxVertexIndex);
  595. BX_TRACE("Max streams: %d", m_caps.MaxStreams);
  596. g_caps.supported |= ( 0
  597. | BGFX_CAPS_TEXTURE_3D
  598. | BGFX_CAPS_TEXTURE_COMPARE_LEQUAL
  599. | BGFX_CAPS_VERTEX_ATTRIB_HALF
  600. | BGFX_CAPS_VERTEX_ATTRIB_UINT10
  601. | BGFX_CAPS_FRAGMENT_DEPTH
  602. | BGFX_CAPS_SWAP_CHAIN
  603. | ( (UINT16_MAX < m_caps.MaxVertexIndex) ? BGFX_CAPS_INDEX32 : 0)
  604. | ( (m_caps.DevCaps2 & D3DDEVCAPS2_CAN_STRETCHRECT_FROM_TEXTURES) ? BGFX_CAPS_TEXTURE_BLIT : 0)
  605. | BGFX_CAPS_TEXTURE_READ_BACK
  606. | (m_occlusionQuerySupport ? BGFX_CAPS_OCCLUSION_QUERY : 0)
  607. );
  608. m_caps.NumSimultaneousRTs = bx::uint32_min(m_caps.NumSimultaneousRTs, BGFX_CONFIG_MAX_FRAME_BUFFER_ATTACHMENTS);
  609. m_caps.MaxStreams = bx::uint32_min(m_caps.MaxStreams, BGFX_CONFIG_MAX_VERTEX_STREAMS);
  610. m_caps.MaxAnisotropy = bx::uint32_max(m_caps.MaxAnisotropy, 1);
  611. g_caps.limits.maxTextureSize = uint16_t(bx::uint32_min(m_caps.MaxTextureWidth, m_caps.MaxTextureHeight) );
  612. g_caps.limits.maxFBAttachments = uint8_t(m_caps.NumSimultaneousRTs);
  613. g_caps.limits.maxVertexStreams = uint8_t(m_caps.MaxStreams);
  614. if (BX_ENABLED(BGFX_CONFIG_RENDERER_USE_EXTENSIONS) )
  615. {
  616. BX_TRACE("Extended formats:");
  617. for (uint32_t ii = 0; ii < ExtendedFormat::Count; ++ii)
  618. {
  619. ExtendedFormat& fmt = s_extendedFormats[ii];
  620. fmt.m_supported = SUCCEEDED(m_d3d9->CheckDeviceFormat(m_adapter, m_deviceType, adapterFormat, fmt.m_usage, fmt.m_type, fmt.m_fmt) );
  621. const char* fourcc = (const char*)&fmt.m_fmt;
  622. BX_TRACE("\t%2d: %c%c%c%c %s", ii, fourcc[0], fourcc[1], fourcc[2], fourcc[3], fmt.m_supported ? "supported" : "");
  623. BX_UNUSED(fourcc);
  624. }
  625. m_instancingSupport = false
  626. || s_extendedFormats[ExtendedFormat::Inst].m_supported
  627. || (m_caps.VertexShaderVersion >= D3DVS_VERSION(3, 0) )
  628. ;
  629. m_atocSupport = false
  630. || s_extendedFormats[ExtendedFormat::Atoc].m_supported
  631. ;
  632. if (m_amd
  633. && s_extendedFormats[ExtendedFormat::Inst].m_supported)
  634. { // AMD only
  635. m_device->SetRenderState(D3DRS_POINTSIZE, D3DFMT_INST);
  636. }
  637. if (s_extendedFormats[ExtendedFormat::Intz].m_supported)
  638. {
  639. s_textureFormat[TextureFormat::D24].m_fmt = D3DFMT_INTZ;
  640. s_textureFormat[TextureFormat::D32].m_fmt = D3DFMT_INTZ;
  641. }
  642. s_textureFormat[TextureFormat::BC4].m_fmt = s_extendedFormats[ExtendedFormat::Ati1].m_supported ? D3DFMT_ATI1 : D3DFMT_UNKNOWN;
  643. s_textureFormat[TextureFormat::BC5].m_fmt = s_extendedFormats[ExtendedFormat::Ati2].m_supported ? D3DFMT_ATI2 : D3DFMT_UNKNOWN;
  644. g_caps.supported |= m_instancingSupport ? BGFX_CAPS_INSTANCING : 0;
  645. g_caps.supported |= m_atocSupport ? BGFX_CAPS_ALPHA_TO_COVERAGE : 0;
  646. }
  647. for (uint32_t ii = 0; ii < TextureFormat::Count; ++ii)
  648. {
  649. uint16_t support = BGFX_CAPS_FORMAT_TEXTURE_NONE;
  650. support |= SUCCEEDED(m_d3d9->CheckDeviceFormat(m_adapter
  651. , m_deviceType
  652. , adapterFormat
  653. , 0
  654. , D3DRTYPE_TEXTURE
  655. , s_textureFormat[ii].m_fmt
  656. ) ) ? BGFX_CAPS_FORMAT_TEXTURE_2D : BGFX_CAPS_FORMAT_TEXTURE_NONE;
  657. support |= SUCCEEDED(m_d3d9->CheckDeviceFormat(m_adapter
  658. , m_deviceType
  659. , adapterFormat
  660. , D3DUSAGE_QUERY_SRGBREAD
  661. , D3DRTYPE_TEXTURE
  662. , s_textureFormat[ii].m_fmt
  663. ) ) ? BGFX_CAPS_FORMAT_TEXTURE_2D_SRGB : BGFX_CAPS_FORMAT_TEXTURE_NONE;
  664. support |= SUCCEEDED(m_d3d9->CheckDeviceFormat(m_adapter
  665. , m_deviceType
  666. , adapterFormat
  667. , 0
  668. , D3DRTYPE_VOLUMETEXTURE
  669. , s_textureFormat[ii].m_fmt
  670. ) ) ? BGFX_CAPS_FORMAT_TEXTURE_3D : BGFX_CAPS_FORMAT_TEXTURE_NONE;
  671. support |= SUCCEEDED(m_d3d9->CheckDeviceFormat(m_adapter
  672. , m_deviceType
  673. , adapterFormat
  674. , D3DUSAGE_QUERY_SRGBREAD
  675. , D3DRTYPE_VOLUMETEXTURE
  676. , s_textureFormat[ii].m_fmt
  677. ) ) ? BGFX_CAPS_FORMAT_TEXTURE_3D_SRGB : BGFX_CAPS_FORMAT_TEXTURE_NONE;
  678. support |= SUCCEEDED(m_d3d9->CheckDeviceFormat(m_adapter
  679. , m_deviceType
  680. , adapterFormat
  681. , 0
  682. , D3DRTYPE_CUBETEXTURE
  683. , s_textureFormat[ii].m_fmt
  684. ) ) ? BGFX_CAPS_FORMAT_TEXTURE_CUBE : BGFX_CAPS_FORMAT_TEXTURE_NONE;
  685. support |= SUCCEEDED(m_d3d9->CheckDeviceFormat(m_adapter
  686. , m_deviceType
  687. , adapterFormat
  688. , D3DUSAGE_QUERY_SRGBREAD
  689. , D3DRTYPE_CUBETEXTURE
  690. , s_textureFormat[ii].m_fmt
  691. ) ) ? BGFX_CAPS_FORMAT_TEXTURE_CUBE_SRGB : BGFX_CAPS_FORMAT_TEXTURE_NONE;
  692. support |= SUCCEEDED(m_d3d9->CheckDeviceFormat(m_adapter
  693. , m_deviceType
  694. , adapterFormat
  695. , D3DUSAGE_QUERY_VERTEXTEXTURE
  696. , D3DRTYPE_TEXTURE
  697. , s_textureFormat[ii].m_fmt
  698. ) ) ? BGFX_CAPS_FORMAT_TEXTURE_VERTEX : BGFX_CAPS_FORMAT_TEXTURE_NONE;
  699. support |= SUCCEEDED(m_d3d9->CheckDeviceFormat(m_adapter
  700. , m_deviceType
  701. , adapterFormat
  702. , bimg::isDepth(bimg::TextureFormat::Enum(ii) ) ? D3DUSAGE_DEPTHSTENCIL : D3DUSAGE_RENDERTARGET
  703. , D3DRTYPE_TEXTURE
  704. , s_textureFormat[ii].m_fmt
  705. ) ) ? BGFX_CAPS_FORMAT_TEXTURE_FRAMEBUFFER : BGFX_CAPS_FORMAT_TEXTURE_NONE;
  706. support |= SUCCEEDED(m_d3d9->CheckDeviceMultiSampleType(m_adapter
  707. , m_deviceType
  708. , s_textureFormat[ii].m_fmt
  709. , true
  710. , D3DMULTISAMPLE_2_SAMPLES
  711. , NULL
  712. ) ) ? BGFX_CAPS_FORMAT_TEXTURE_FRAMEBUFFER_MSAA : BGFX_CAPS_FORMAT_TEXTURE_NONE;
  713. support |= SUCCEEDED(m_d3d9->CheckDeviceFormat(m_adapter
  714. , m_deviceType
  715. , adapterFormat
  716. , bimg::isDepth(bimg::TextureFormat::Enum(ii) ) ? D3DUSAGE_DEPTHSTENCIL : D3DUSAGE_RENDERTARGET
  717. , D3DRTYPE_TEXTURE
  718. , s_textureFormat[ii].m_fmt
  719. ) ) ? BGFX_CAPS_FORMAT_TEXTURE_MIP_AUTOGEN : BGFX_CAPS_FORMAT_TEXTURE_NONE;
  720. g_caps.formats[ii] = support;
  721. }
  722. m_fmtDepth = D3DFMT_D24S8;
  723. {
  724. IDirect3DSwapChain9* swapChain;
  725. DX_CHECK(m_device->GetSwapChain(0, &swapChain) );
  726. // GPA increases swapchain ref count.
  727. //
  728. // This causes assert in debug. When debugger is present refcount
  729. // checks are off.
  730. setGraphicsDebuggerPresent(1 != getRefCount(swapChain) );
  731. DX_RELEASE(swapChain, 0);
  732. }
  733. // Init reserved part of view name.
  734. for (uint32_t ii = 0; ii < BGFX_CONFIG_MAX_VIEWS; ++ii)
  735. {
  736. bx::snprintf(s_viewName[ii], BGFX_CONFIG_MAX_VIEW_NAME_RESERVED + 1, "%3d ", ii);
  737. mbstowcs(s_viewNameW[ii], s_viewName[ii], BGFX_CONFIG_MAX_VIEW_NAME_RESERVED);
  738. }
  739. if (NULL != m_deviceEx)
  740. {
  741. int32_t gpuPriority;
  742. DX_CHECK(m_deviceEx->GetGPUThreadPriority(&gpuPriority) );
  743. BX_TRACE("GPU thread priority: %d", gpuPriority);
  744. uint32_t maxLatency;
  745. DX_CHECK(m_deviceEx->GetMaximumFrameLatency(&maxLatency) );
  746. BX_TRACE("GPU max frame latency: %d", maxLatency);
  747. }
  748. postReset();
  749. m_initialized = true;
  750. g_internalData.context = m_device;
  751. return true;
  752. error:
  753. switch (errorState)
  754. {
  755. case ErrorState::CreatedDevice:
  756. if (NULL != m_d3d9ex)
  757. {
  758. DX_RELEASE(m_deviceEx, 1);
  759. DX_RELEASE(m_device, 0);
  760. }
  761. else
  762. {
  763. DX_RELEASE(m_device, 0);
  764. }
  765. case ErrorState::CreatedD3D9:
  766. if (NULL != m_d3d9ex)
  767. {
  768. DX_RELEASE(m_d3d9, 1);
  769. DX_RELEASE(m_d3d9ex, 0);
  770. }
  771. else
  772. {
  773. DX_RELEASE(m_d3d9, 0);
  774. }
  775. case ErrorState::LoadedD3D9:
  776. m_nvapi.shutdown();
  777. bx::dlclose(m_d3d9dll);
  778. case ErrorState::Default:
  779. break;
  780. }
  781. return false;
  782. }
  783. void shutdown()
  784. {
  785. preReset();
  786. for (uint32_t ii = 0; ii < BX_COUNTOF(m_indexBuffers); ++ii)
  787. {
  788. m_indexBuffers[ii].destroy();
  789. }
  790. for (uint32_t ii = 0; ii < BX_COUNTOF(m_vertexBuffers); ++ii)
  791. {
  792. m_vertexBuffers[ii].destroy();
  793. }
  794. for (uint32_t ii = 0; ii < BX_COUNTOF(m_shaders); ++ii)
  795. {
  796. m_shaders[ii].destroy();
  797. }
  798. for (uint32_t ii = 0; ii < BX_COUNTOF(m_textures); ++ii)
  799. {
  800. m_textures[ii].destroy();
  801. }
  802. if (NULL != m_d3d9ex)
  803. {
  804. DX_RELEASE(m_deviceEx, 1);
  805. DX_RELEASE(m_device, 0);
  806. DX_RELEASE(m_d3d9, 1);
  807. DX_RELEASE(m_d3d9ex, 0);
  808. }
  809. else
  810. {
  811. DX_RELEASE(m_device, 0);
  812. DX_RELEASE(m_d3d9, 0);
  813. }
  814. m_nvapi.shutdown();
  815. bx::dlclose(m_d3d9dll);
  816. m_initialized = false;
  817. }
  818. RendererType::Enum getRendererType() const override
  819. {
  820. return RendererType::Direct3D9;
  821. }
  822. const char* getRendererName() const override
  823. {
  824. if (NULL != m_d3d9ex)
  825. {
  826. return BGFX_RENDERER_DIRECT3D9_NAME " Ex";
  827. }
  828. return BGFX_RENDERER_DIRECT3D9_NAME;
  829. }
  830. void createIndexBuffer(IndexBufferHandle _handle, Memory* _mem, uint16_t _flags) override
  831. {
  832. m_indexBuffers[_handle.idx].create(_mem->size, _mem->data, _flags);
  833. }
  834. void destroyIndexBuffer(IndexBufferHandle _handle) override
  835. {
  836. m_indexBuffers[_handle.idx].destroy();
  837. }
  838. void createVertexDecl(VertexDeclHandle _handle, const VertexDecl& _decl) override
  839. {
  840. VertexDecl& decl = m_vertexDecls[_handle.idx];
  841. bx::memCopy(&decl, &_decl, sizeof(VertexDecl) );
  842. dump(decl);
  843. }
  844. void destroyVertexDecl(VertexDeclHandle /*_handle*/) override
  845. {
  846. }
  847. void createVertexBuffer(VertexBufferHandle _handle, Memory* _mem, VertexDeclHandle _declHandle, uint16_t /*_flags*/) override
  848. {
  849. m_vertexBuffers[_handle.idx].create(_mem->size, _mem->data, _declHandle);
  850. }
  851. void destroyVertexBuffer(VertexBufferHandle _handle) override
  852. {
  853. m_vertexBuffers[_handle.idx].destroy();
  854. }
  855. void createDynamicIndexBuffer(IndexBufferHandle _handle, uint32_t _size, uint16_t _flags) override
  856. {
  857. m_indexBuffers[_handle.idx].create(_size, NULL, _flags);
  858. }
  859. void updateDynamicIndexBuffer(IndexBufferHandle _handle, uint32_t _offset, uint32_t _size, Memory* _mem) override
  860. {
  861. m_indexBuffers[_handle.idx].update(_offset, bx::uint32_min(_size, _mem->size), _mem->data);
  862. }
  863. void destroyDynamicIndexBuffer(IndexBufferHandle _handle) override
  864. {
  865. m_indexBuffers[_handle.idx].destroy();
  866. }
  867. void createDynamicVertexBuffer(VertexBufferHandle _handle, uint32_t _size, uint16_t /*_flags*/) override
  868. {
  869. VertexDeclHandle decl = BGFX_INVALID_HANDLE;
  870. m_vertexBuffers[_handle.idx].create(_size, NULL, decl);
  871. }
  872. void updateDynamicVertexBuffer(VertexBufferHandle _handle, uint32_t _offset, uint32_t _size, Memory* _mem) override
  873. {
  874. m_vertexBuffers[_handle.idx].update(_offset, bx::uint32_min(_size, _mem->size), _mem->data);
  875. }
  876. void destroyDynamicVertexBuffer(VertexBufferHandle _handle) override
  877. {
  878. m_vertexBuffers[_handle.idx].destroy();
  879. }
  880. void createShader(ShaderHandle _handle, Memory* _mem) override
  881. {
  882. m_shaders[_handle.idx].create(_mem);
  883. }
  884. void destroyShader(ShaderHandle _handle) override
  885. {
  886. m_shaders[_handle.idx].destroy();
  887. }
  888. void createProgram(ProgramHandle _handle, ShaderHandle _vsh, ShaderHandle _fsh) override
  889. {
  890. m_program[_handle.idx].create(m_shaders[_vsh.idx], m_shaders[_fsh.idx]);
  891. }
  892. void destroyProgram(ProgramHandle _handle) override
  893. {
  894. m_program[_handle.idx].destroy();
  895. }
  896. void createTexture(TextureHandle _handle, Memory* _mem, uint32_t _flags, uint8_t _skip) override
  897. {
  898. m_textures[_handle.idx].create(_mem, _flags, _skip);
  899. }
  900. void updateTextureBegin(TextureHandle _handle, uint8_t _side, uint8_t _mip) override
  901. {
  902. m_updateTexture = &m_textures[_handle.idx];
  903. m_updateTexture->updateBegin(_side, _mip);
  904. }
  905. 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) override
  906. {
  907. m_updateTexture->update(_side, _mip, _rect, _z, _depth, _pitch, _mem);
  908. }
  909. void updateTextureEnd() override
  910. {
  911. m_updateTexture->updateEnd();
  912. m_updateTexture = NULL;
  913. }
  914. void readTexture(TextureHandle _handle, void* _data, uint8_t _mip) override
  915. {
  916. TextureD3D9& texture = m_textures[_handle.idx];
  917. D3DLOCKED_RECT lockedRect;
  918. DX_CHECK(texture.m_texture2d->LockRect(_mip
  919. , &lockedRect
  920. , NULL
  921. , D3DLOCK_NO_DIRTY_UPDATE|D3DLOCK_NOSYSLOCK|D3DLOCK_READONLY
  922. ) );
  923. uint32_t srcWidth = bx::uint32_max(1, texture.m_width >>_mip);
  924. uint32_t srcHeight = bx::uint32_max(1, texture.m_height>>_mip);
  925. uint32_t srcPitch = lockedRect.Pitch;
  926. uint8_t* src = (uint8_t*)lockedRect.pBits;
  927. const uint8_t bpp = bimg::getBitsPerPixel(bimg::TextureFormat::Enum(texture.m_textureFormat) );
  928. uint8_t* dst = (uint8_t*)_data;
  929. uint32_t dstPitch = srcWidth*bpp/8;
  930. uint32_t pitch = bx::uint32_min(srcPitch, dstPitch);
  931. for (uint32_t yy = 0, height = srcHeight; yy < height; ++yy)
  932. {
  933. bx::memCopy(dst, src, pitch);
  934. src += srcPitch;
  935. dst += dstPitch;
  936. }
  937. DX_CHECK(texture.m_texture2d->UnlockRect(_mip) );
  938. }
  939. void resizeTexture(TextureHandle _handle, uint16_t _width, uint16_t _height, uint8_t _numMips) override
  940. {
  941. TextureD3D9& texture = m_textures[_handle.idx];
  942. uint32_t size = sizeof(uint32_t) + sizeof(TextureCreate);
  943. const Memory* mem = alloc(size);
  944. bx::StaticMemoryBlockWriter writer(mem->data, mem->size);
  945. uint32_t magic = BGFX_CHUNK_MAGIC_TEX;
  946. bx::write(&writer, magic);
  947. TextureCreate tc;
  948. tc.m_width = _width;
  949. tc.m_height = _height;
  950. tc.m_depth = 0;
  951. tc.m_numLayers = 1;
  952. tc.m_numMips = _numMips;
  953. tc.m_format = TextureFormat::Enum(texture.m_requestedFormat);
  954. tc.m_cubeMap = false;
  955. tc.m_mem = NULL;
  956. bx::write(&writer, tc);
  957. texture.destroy(true);
  958. texture.create(mem, texture.m_flags, 0);
  959. release(mem);
  960. }
  961. void overrideInternal(TextureHandle _handle, uintptr_t _ptr) override
  962. {
  963. // Resource ref. counts might be messed up outside of bgfx.
  964. // Disabling ref. count check once texture is overridden.
  965. setGraphicsDebuggerPresent(true);
  966. m_textures[_handle.idx].overrideInternal(_ptr);
  967. }
  968. uintptr_t getInternal(TextureHandle _handle) override
  969. {
  970. // Resource ref. counts might be messed up outside of bgfx.
  971. // Disabling ref. count check once texture is overridden.
  972. setGraphicsDebuggerPresent(true);
  973. return uintptr_t(m_textures[_handle.idx].m_ptr);
  974. }
  975. void destroyTexture(TextureHandle _handle) override
  976. {
  977. m_textures[_handle.idx].destroy();
  978. }
  979. void createFrameBuffer(FrameBufferHandle _handle, uint8_t _num, const Attachment* _attachment) override
  980. {
  981. m_frameBuffers[_handle.idx].create(_num, _attachment);
  982. }
  983. void createFrameBuffer(FrameBufferHandle _handle, void* _nwh, uint32_t _width, uint32_t _height, TextureFormat::Enum _depthFormat) override
  984. {
  985. uint16_t denseIdx = m_numWindows++;
  986. m_windows[denseIdx] = _handle;
  987. m_frameBuffers[_handle.idx].create(denseIdx, _nwh, _width, _height, _depthFormat);
  988. }
  989. void destroyFrameBuffer(FrameBufferHandle _handle) override
  990. {
  991. uint16_t denseIdx = m_frameBuffers[_handle.idx].destroy();
  992. if (UINT16_MAX != denseIdx)
  993. {
  994. --m_numWindows;
  995. if (m_numWindows > 1)
  996. {
  997. FrameBufferHandle handle = m_windows[m_numWindows];
  998. m_windows[denseIdx] = handle;
  999. m_frameBuffers[handle.idx].m_denseIdx = denseIdx;
  1000. }
  1001. }
  1002. }
  1003. void createUniform(UniformHandle _handle, UniformType::Enum _type, uint16_t _num, const char* _name) override
  1004. {
  1005. if (NULL != m_uniforms[_handle.idx])
  1006. {
  1007. BX_FREE(g_allocator, m_uniforms[_handle.idx]);
  1008. }
  1009. uint32_t size = BX_ALIGN_16(g_uniformTypeSize[_type]*_num);
  1010. void* data = BX_ALLOC(g_allocator, size);
  1011. bx::memSet(data, 0, size);
  1012. m_uniforms[_handle.idx] = data;
  1013. m_uniformReg.add(_handle, _name, data);
  1014. }
  1015. void destroyUniform(UniformHandle _handle) override
  1016. {
  1017. BX_FREE(g_allocator, m_uniforms[_handle.idx]);
  1018. m_uniforms[_handle.idx] = NULL;
  1019. m_uniformReg.remove(_handle);
  1020. }
  1021. void requestScreenShot(FrameBufferHandle _handle, const char* _filePath) override
  1022. {
  1023. IDirect3DSwapChain9* swapChain = isValid(_handle)
  1024. ? m_frameBuffers[_handle.idx].m_swapChain
  1025. : m_swapChain
  1026. ;
  1027. if (NULL == swapChain)
  1028. {
  1029. BX_TRACE("Unable to capture screenshot %s.", _filePath);
  1030. return;
  1031. }
  1032. D3DPRESENT_PARAMETERS params;
  1033. DX_CHECK(swapChain->GetPresentParameters(&params));
  1034. IDirect3DSurface9* surface;
  1035. D3DDEVICE_CREATION_PARAMETERS dcp;
  1036. DX_CHECK(m_device->GetCreationParameters(&dcp) );
  1037. D3DDISPLAYMODE dm;
  1038. DX_CHECK(m_d3d9->GetAdapterDisplayMode(dcp.AdapterOrdinal, &dm) );
  1039. DX_CHECK(m_device->CreateOffscreenPlainSurface(dm.Width
  1040. , dm.Height
  1041. , D3DFMT_A8R8G8B8
  1042. , D3DPOOL_SCRATCH
  1043. , &surface
  1044. , NULL
  1045. ) );
  1046. HWND nwh = params.hDeviceWindow;
  1047. SetWindowPos(nwh, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE|SWP_NOSIZE);
  1048. DX_CHECK(m_device->GetFrontBufferData(0, surface) );
  1049. SetWindowPos(nwh, HWND_NOTOPMOST, 0, 0, 0, 0, SWP_NOMOVE|SWP_NOSIZE);
  1050. D3DLOCKED_RECT rect;
  1051. DX_CHECK(surface->LockRect(&rect
  1052. , NULL
  1053. , D3DLOCK_NO_DIRTY_UPDATE|D3DLOCK_NOSYSLOCK|D3DLOCK_READONLY
  1054. ) );
  1055. RECT rc;
  1056. GetClientRect(nwh, &rc);
  1057. POINT point;
  1058. point.x = rc.left;
  1059. point.y = rc.top;
  1060. ClientToScreen(nwh, &point);
  1061. uint8_t* data = (uint8_t*)rect.pBits;
  1062. uint32_t bytesPerPixel = rect.Pitch/dm.Width;
  1063. g_callback->screenShot(_filePath
  1064. , params.BackBufferWidth
  1065. , params.BackBufferHeight
  1066. , rect.Pitch
  1067. , &data[point.y*rect.Pitch+point.x*bytesPerPixel]
  1068. , params.BackBufferHeight*rect.Pitch
  1069. , false
  1070. );
  1071. DX_CHECK(surface->UnlockRect() );
  1072. DX_RELEASE(surface, 0);
  1073. }
  1074. void updateViewName(uint8_t _id, const char* _name) override
  1075. {
  1076. if (BX_ENABLED(BGFX_CONFIG_DEBUG_PIX) )
  1077. {
  1078. mbstowcs(&s_viewNameW[_id][BGFX_CONFIG_MAX_VIEW_NAME_RESERVED]
  1079. , _name
  1080. , BX_COUNTOF(s_viewNameW[0])-BGFX_CONFIG_MAX_VIEW_NAME_RESERVED
  1081. );
  1082. }
  1083. bx::strCopy(&s_viewName[_id][BGFX_CONFIG_MAX_VIEW_NAME_RESERVED]
  1084. , BX_COUNTOF(s_viewName[0]) - BGFX_CONFIG_MAX_VIEW_NAME_RESERVED
  1085. , _name
  1086. );
  1087. }
  1088. void updateUniform(uint16_t _loc, const void* _data, uint32_t _size) override
  1089. {
  1090. bx::memCopy(m_uniforms[_loc], _data, _size);
  1091. }
  1092. void setMarker(const char* _marker, uint32_t _size) override
  1093. {
  1094. #if BGFX_CONFIG_DEBUG_PIX
  1095. uint32_t size = _size*sizeof(wchar_t);
  1096. wchar_t* name = (wchar_t*)alloca(size);
  1097. mbstowcs(name, _marker, size-2);
  1098. PIX_SETMARKER(D3DCOLOR_MARKER, name);
  1099. #endif // BGFX_CONFIG_DEBUG_PIX
  1100. BX_UNUSED(_marker, _size);
  1101. }
  1102. void invalidateOcclusionQuery(OcclusionQueryHandle _handle) override
  1103. {
  1104. m_occlusionQuery.invalidate(_handle);
  1105. }
  1106. virtual void setName(Handle _handle, const char* _name) override
  1107. {
  1108. BX_UNUSED(_handle, _name)
  1109. }
  1110. void submitBlit(BlitState& _bs, uint16_t _view);
  1111. void submit(Frame* _render, ClearQuad& _clearQuad, TextVideoMemBlitter& _textVideoMemBlitter) override;
  1112. void blitSetup(TextVideoMemBlitter& _blitter) override
  1113. {
  1114. uint32_t width = m_params.BackBufferWidth;
  1115. uint32_t height = m_params.BackBufferHeight;
  1116. FrameBufferHandle fbh = BGFX_INVALID_HANDLE;
  1117. setFrameBuffer(fbh, false, false);
  1118. D3DVIEWPORT9 vp;
  1119. vp.X = 0;
  1120. vp.Y = 0;
  1121. vp.Width = width;
  1122. vp.Height = height;
  1123. vp.MinZ = 0.0f;
  1124. vp.MaxZ = 1.0f;
  1125. IDirect3DDevice9* device = m_device;
  1126. DX_CHECK(device->SetViewport(&vp) );
  1127. DX_CHECK(device->SetRenderState(D3DRS_STENCILENABLE, FALSE) );
  1128. DX_CHECK(device->SetRenderState(D3DRS_ZENABLE, FALSE) );
  1129. DX_CHECK(device->SetRenderState(D3DRS_ZFUNC, D3DCMP_ALWAYS) );
  1130. DX_CHECK(device->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE) );
  1131. DX_CHECK(device->SetRenderState(D3DRS_ALPHABLENDENABLE, FALSE) );
  1132. DX_CHECK(device->SetRenderState(D3DRS_ALPHAFUNC, D3DCMP_GREATER) );
  1133. DX_CHECK(device->SetRenderState(D3DRS_COLORWRITEENABLE, D3DCOLORWRITEENABLE_RED|D3DCOLORWRITEENABLE_GREEN|D3DCOLORWRITEENABLE_BLUE) );
  1134. DX_CHECK(device->SetRenderState(D3DRS_FILLMODE, D3DFILL_SOLID) );
  1135. ProgramD3D9& program = m_program[_blitter.m_program.idx];
  1136. DX_CHECK(device->SetVertexShader(program.m_vsh->m_vertexShader) );
  1137. DX_CHECK(device->SetPixelShader(program.m_fsh->m_pixelShader) );
  1138. VertexBufferD3D9& vb = m_vertexBuffers[_blitter.m_vb->handle.idx];
  1139. VertexDecl& vertexDecl = m_vertexDecls[_blitter.m_vb->decl.idx];
  1140. DX_CHECK(device->SetStreamSource(0, vb.m_ptr, 0, vertexDecl.m_stride) );
  1141. setInputLayout(vertexDecl, 0);
  1142. IndexBufferD3D9& ib = m_indexBuffers[_blitter.m_ib->handle.idx];
  1143. DX_CHECK(device->SetIndices(ib.m_ptr) );
  1144. float proj[16];
  1145. bx::mtxOrtho(proj, 0.0f, (float)width, (float)height, 0.0f, 0.0f, 1000.0f, 0.0f, false);
  1146. PredefinedUniform& predefined = program.m_predefined[0];
  1147. uint8_t flags = predefined.m_type;
  1148. setShaderUniform(flags, predefined.m_loc, proj, 4);
  1149. m_textures[_blitter.m_texture.idx].commit(0, BGFX_TEXTURE_INTERNAL_DEFAULT_SAMPLER, NULL);
  1150. }
  1151. void blitRender(TextVideoMemBlitter& _blitter, uint32_t _numIndices) override
  1152. {
  1153. const uint32_t numVertices = _numIndices*4/6;
  1154. if (0 < numVertices)
  1155. {
  1156. m_indexBuffers[_blitter.m_ib->handle.idx].update(0, _numIndices * 2, _blitter.m_ib->data, true);
  1157. m_vertexBuffers[_blitter.m_vb->handle.idx].update(0, numVertices*_blitter.m_decl.m_stride, _blitter.m_vb->data, true);
  1158. DX_CHECK(m_device->DrawIndexedPrimitive(D3DPT_TRIANGLELIST
  1159. , 0
  1160. , 0
  1161. , numVertices
  1162. , 0
  1163. , _numIndices / 3
  1164. ) );
  1165. }
  1166. }
  1167. void updateMsaa()
  1168. {
  1169. for (uint32_t ii = 1, last = 0; ii < BX_COUNTOF(s_checkMsaa); ++ii)
  1170. {
  1171. D3DMULTISAMPLE_TYPE msaa = s_checkMsaa[ii];
  1172. DWORD quality;
  1173. HRESULT hr = m_d3d9->CheckDeviceMultiSampleType(m_adapter
  1174. , m_deviceType
  1175. , m_params.BackBufferFormat
  1176. , m_params.Windowed
  1177. , msaa
  1178. , &quality
  1179. );
  1180. if (SUCCEEDED(hr) )
  1181. {
  1182. s_msaa[ii].m_type = msaa;
  1183. s_msaa[ii].m_quality = bx::uint32_imax(0, quality-1);
  1184. last = ii;
  1185. }
  1186. else
  1187. {
  1188. s_msaa[ii] = s_msaa[last];
  1189. }
  1190. }
  1191. }
  1192. void updateResolution(const Resolution& _resolution)
  1193. {
  1194. m_maxAnisotropy = !!(_resolution.m_flags & BGFX_RESET_MAXANISOTROPY)
  1195. ? m_caps.MaxAnisotropy
  1196. : 1
  1197. ;
  1198. const uint32_t maskFlags = ~(0
  1199. | BGFX_RESET_HMD_RECENTER
  1200. | BGFX_RESET_MAXANISOTROPY
  1201. | BGFX_RESET_DEPTH_CLAMP
  1202. | BGFX_RESET_SUSPEND
  1203. );
  1204. if (m_resolution.m_width != _resolution.m_width
  1205. || m_resolution.m_height != _resolution.m_height
  1206. || (m_resolution.m_flags&maskFlags) != (_resolution.m_flags&maskFlags) )
  1207. {
  1208. uint32_t flags = _resolution.m_flags & (~BGFX_RESET_INTERNAL_FORCE);
  1209. m_resolution = _resolution;
  1210. m_resolution.m_flags = flags;
  1211. m_textVideoMem.resize(false, _resolution.m_width, _resolution.m_height);
  1212. m_textVideoMem.clear();
  1213. D3DDEVICE_CREATION_PARAMETERS dcp;
  1214. DX_CHECK(m_device->GetCreationParameters(&dcp) );
  1215. D3DDISPLAYMODE dm;
  1216. DX_CHECK(m_d3d9->GetAdapterDisplayMode(dcp.AdapterOrdinal, &dm) );
  1217. m_params.BackBufferFormat = dm.Format;
  1218. m_params.BackBufferWidth = _resolution.m_width;
  1219. m_params.BackBufferHeight = _resolution.m_height;
  1220. m_params.FullScreen_RefreshRateInHz = BGFX_RESET_FULLSCREEN == (m_resolution.m_flags&BGFX_RESET_FULLSCREEN_MASK) ? 60 : 0;
  1221. m_params.PresentationInterval = !!(m_resolution.m_flags&BGFX_RESET_VSYNC) ? D3DPRESENT_INTERVAL_ONE : D3DPRESENT_INTERVAL_IMMEDIATE;
  1222. updateMsaa();
  1223. Msaa& msaa = s_msaa[(m_resolution.m_flags&BGFX_RESET_MSAA_MASK)>>BGFX_RESET_MSAA_SHIFT];
  1224. m_params.MultiSampleType = msaa.m_type;
  1225. m_params.MultiSampleQuality = msaa.m_quality;
  1226. preReset();
  1227. DX_CHECK(m_device->Reset(&m_params) );
  1228. postReset();
  1229. }
  1230. }
  1231. void setFrameBuffer(FrameBufferHandle _fbh, bool _msaa = true, bool _needPresent = true)
  1232. {
  1233. if (isValid(m_fbh)
  1234. && m_fbh.idx != _fbh.idx)
  1235. {
  1236. FrameBufferD3D9& frameBuffer = m_frameBuffers[m_fbh.idx];
  1237. frameBuffer.resolve();
  1238. }
  1239. if (!isValid(_fbh) )
  1240. {
  1241. m_needPresent |= _needPresent;
  1242. DX_CHECK(m_device->SetRenderTarget(0, m_backBufferColor) );
  1243. for (uint32_t ii = 1, num = g_caps.limits.maxFBAttachments; ii < num; ++ii)
  1244. {
  1245. DX_CHECK(m_device->SetRenderTarget(ii, NULL) );
  1246. }
  1247. DX_CHECK(m_device->SetDepthStencilSurface(m_backBufferDepthStencil) );
  1248. DX_CHECK(m_device->SetRenderState(D3DRS_SRGBWRITEENABLE, 0 != (m_resolution.m_flags & BGFX_RESET_SRGB_BACKBUFFER) ) );
  1249. }
  1250. else
  1251. {
  1252. m_frameBuffers[_fbh.idx].set();
  1253. }
  1254. m_fbh = _fbh;
  1255. m_rtMsaa = _msaa;
  1256. }
  1257. void setShaderUniform(uint8_t _flags, uint32_t _regIndex, const void* _val, uint32_t _numRegs)
  1258. {
  1259. if (_flags&BGFX_UNIFORM_FRAGMENTBIT)
  1260. {
  1261. DX_CHECK(m_device->SetPixelShaderConstantF(_regIndex, (const float*)_val, _numRegs) );
  1262. }
  1263. else
  1264. {
  1265. DX_CHECK(m_device->SetVertexShaderConstantF(_regIndex, (const float*)_val, _numRegs) );
  1266. }
  1267. }
  1268. void setShaderUniform4f(uint8_t _flags, uint32_t _regIndex, const void* _val, uint32_t _numRegs)
  1269. {
  1270. setShaderUniform(_flags, _regIndex, _val, _numRegs);
  1271. }
  1272. void setShaderUniform4x4f(uint8_t _flags, uint32_t _regIndex, const void* _val, uint32_t _numRegs)
  1273. {
  1274. setShaderUniform(_flags, _regIndex, _val, _numRegs);
  1275. }
  1276. void reset()
  1277. {
  1278. preReset();
  1279. HRESULT hr;
  1280. do
  1281. {
  1282. hr = m_device->Reset(&m_params);
  1283. } while (FAILED(hr) );
  1284. postReset();
  1285. }
  1286. void flush()
  1287. {
  1288. m_flushQuery->Issue(D3DISSUE_END);
  1289. m_flushQuery->GetData(NULL, 0, D3DGETDATA_FLUSH);
  1290. }
  1291. bool isDeviceRemoved() override
  1292. {
  1293. return false;
  1294. }
  1295. void flip(HMD& /*_hmd*/) override
  1296. {
  1297. if (NULL != m_swapChain)
  1298. {
  1299. if (NULL != m_deviceEx)
  1300. {
  1301. DX_CHECK(m_deviceEx->WaitForVBlank(0) );
  1302. }
  1303. for (uint32_t ii = 0, num = m_numWindows; ii < num; ++ii)
  1304. {
  1305. HRESULT hr = S_OK;
  1306. if (0 == ii)
  1307. {
  1308. if (m_needPresent)
  1309. {
  1310. hr = m_swapChain->Present(NULL, NULL, (HWND)g_platformData.nwh, NULL, 0);
  1311. m_needPresent = false;
  1312. }
  1313. else
  1314. {
  1315. flush();
  1316. }
  1317. }
  1318. else
  1319. {
  1320. hr = m_frameBuffers[m_windows[ii].idx].present();
  1321. }
  1322. if (isLost(hr) )
  1323. {
  1324. do
  1325. {
  1326. do
  1327. {
  1328. hr = m_device->TestCooperativeLevel();
  1329. }
  1330. while (D3DERR_DEVICENOTRESET != hr);
  1331. reset();
  1332. hr = m_device->TestCooperativeLevel();
  1333. }
  1334. while (FAILED(hr) );
  1335. break;
  1336. }
  1337. else if (FAILED(hr) )
  1338. {
  1339. BX_TRACE("Present failed with err 0x%08x.", hr);
  1340. }
  1341. }
  1342. }
  1343. }
  1344. void preReset()
  1345. {
  1346. m_needPresent = false;
  1347. invalidateSamplerState();
  1348. m_inputLayoutCache.invalidate();
  1349. for (uint32_t stage = 0; stage < BGFX_CONFIG_MAX_TEXTURE_SAMPLERS; ++stage)
  1350. {
  1351. DX_CHECK(m_device->SetTexture(stage, NULL) );
  1352. }
  1353. DX_CHECK(m_device->SetRenderTarget(0, m_backBufferColor) );
  1354. for (uint32_t ii = 1, num = g_caps.limits.maxFBAttachments; ii < num; ++ii)
  1355. {
  1356. DX_CHECK(m_device->SetRenderTarget(ii, NULL) );
  1357. }
  1358. DX_CHECK(m_device->SetDepthStencilSurface(m_backBufferDepthStencil) );
  1359. DX_CHECK(m_device->SetVertexShader(NULL) );
  1360. DX_CHECK(m_device->SetPixelShader(NULL) );
  1361. DX_CHECK(m_device->SetStreamSource(0, NULL, 0, 0) );
  1362. DX_CHECK(m_device->SetIndices(NULL) );
  1363. DX_RELEASE(m_backBufferColor, 0);
  1364. DX_RELEASE(m_backBufferDepthStencil, 0);
  1365. DX_RELEASE(m_swapChain, 0);
  1366. capturePreReset();
  1367. DX_RELEASE(m_flushQuery, 0);
  1368. if (m_timerQuerySupport)
  1369. {
  1370. m_gpuTimer.preReset();
  1371. }
  1372. if (m_occlusionQuerySupport)
  1373. {
  1374. m_occlusionQuery.preReset();
  1375. }
  1376. for (uint32_t ii = 0; ii < BX_COUNTOF(m_indexBuffers); ++ii)
  1377. {
  1378. m_indexBuffers[ii].preReset();
  1379. }
  1380. for (uint32_t ii = 0; ii < BX_COUNTOF(m_vertexBuffers); ++ii)
  1381. {
  1382. m_vertexBuffers[ii].preReset();
  1383. }
  1384. for (uint32_t ii = 0; ii < BX_COUNTOF(m_frameBuffers); ++ii)
  1385. {
  1386. m_frameBuffers[ii].preReset();
  1387. }
  1388. for (uint32_t ii = 0; ii < BX_COUNTOF(m_textures); ++ii)
  1389. {
  1390. m_textures[ii].preReset();
  1391. }
  1392. }
  1393. void postReset()
  1394. {
  1395. DX_CHECK(m_device->GetSwapChain(0, &m_swapChain) );
  1396. DX_CHECK(m_swapChain->GetBackBuffer(0, D3DBACKBUFFER_TYPE_MONO, &m_backBufferColor) );
  1397. DX_CHECK(m_device->GetDepthStencilSurface(&m_backBufferDepthStencil) );
  1398. DX_CHECK(m_device->CreateQuery(D3DQUERYTYPE_EVENT, &m_flushQuery) );
  1399. if (m_timerQuerySupport)
  1400. {
  1401. m_gpuTimer.postReset();
  1402. }
  1403. if (m_occlusionQuerySupport)
  1404. {
  1405. m_occlusionQuery.postReset();
  1406. }
  1407. capturePostReset();
  1408. for (uint32_t ii = 0; ii < BX_COUNTOF(m_indexBuffers); ++ii)
  1409. {
  1410. m_indexBuffers[ii].postReset();
  1411. }
  1412. for (uint32_t ii = 0; ii < BX_COUNTOF(m_vertexBuffers); ++ii)
  1413. {
  1414. m_vertexBuffers[ii].postReset();
  1415. }
  1416. for (uint32_t ii = 0; ii < BX_COUNTOF(m_textures); ++ii)
  1417. {
  1418. m_textures[ii].postReset();
  1419. }
  1420. for (uint32_t ii = 0; ii < BX_COUNTOF(m_frameBuffers); ++ii)
  1421. {
  1422. m_frameBuffers[ii].postReset();
  1423. }
  1424. }
  1425. void invalidateSamplerState()
  1426. {
  1427. for (uint32_t stage = 0; stage < BGFX_CONFIG_MAX_TEXTURE_SAMPLERS; ++stage)
  1428. {
  1429. m_samplerFlags[stage] = UINT32_MAX;
  1430. }
  1431. }
  1432. static void setSamplerState(IDirect3DDevice9* _device, DWORD _stage, D3DSAMPLERSTATETYPE _type, DWORD _value)
  1433. {
  1434. DX_CHECK(_device->SetSamplerState(_stage, _type, _value) );
  1435. if (4 > _stage)
  1436. {
  1437. DX_CHECK(_device->SetSamplerState(D3DVERTEXTEXTURESAMPLER0 + _stage, _type, _value) );
  1438. }
  1439. }
  1440. void setSamplerState(uint8_t _stage, uint32_t _flags, const float _rgba[4])
  1441. {
  1442. const uint32_t flags = _flags&( (~BGFX_TEXTURE_RESERVED_MASK) | BGFX_TEXTURE_SAMPLER_BITS_MASK | BGFX_TEXTURE_SRGB);
  1443. BX_CHECK(_stage < BX_COUNTOF(m_samplerFlags), "");
  1444. if (m_samplerFlags[_stage] != flags)
  1445. {
  1446. m_samplerFlags[_stage] = flags;
  1447. IDirect3DDevice9* device = m_device;
  1448. D3DTEXTUREADDRESS tau = s_textureAddress[(_flags&BGFX_TEXTURE_U_MASK)>>BGFX_TEXTURE_U_SHIFT];
  1449. D3DTEXTUREADDRESS tav = s_textureAddress[(_flags&BGFX_TEXTURE_V_MASK)>>BGFX_TEXTURE_V_SHIFT];
  1450. D3DTEXTUREADDRESS taw = s_textureAddress[(_flags&BGFX_TEXTURE_W_MASK)>>BGFX_TEXTURE_W_SHIFT];
  1451. D3DTEXTUREFILTERTYPE minFilter = s_textureFilter[(_flags&BGFX_TEXTURE_MIN_MASK)>>BGFX_TEXTURE_MIN_SHIFT];
  1452. D3DTEXTUREFILTERTYPE magFilter = s_textureFilter[(_flags&BGFX_TEXTURE_MAG_MASK)>>BGFX_TEXTURE_MAG_SHIFT];
  1453. D3DTEXTUREFILTERTYPE mipFilter = s_textureFilter[(_flags&BGFX_TEXTURE_MIP_MASK)>>BGFX_TEXTURE_MIP_SHIFT];
  1454. setSamplerState(device, _stage, D3DSAMP_ADDRESSU, tau);
  1455. setSamplerState(device, _stage, D3DSAMP_ADDRESSV, tav);
  1456. setSamplerState(device, _stage, D3DSAMP_ADDRESSW, taw);
  1457. setSamplerState(device, _stage, D3DSAMP_MINFILTER, minFilter);
  1458. setSamplerState(device, _stage, D3DSAMP_MAGFILTER, magFilter);
  1459. setSamplerState(device, _stage, D3DSAMP_MIPFILTER, mipFilter);
  1460. setSamplerState(device, _stage, D3DSAMP_MAXANISOTROPY, m_maxAnisotropy);
  1461. setSamplerState(device, _stage, D3DSAMP_SRGBTEXTURE, 0 != (flags & BGFX_TEXTURE_SRGB) );
  1462. if (NULL != _rgba)
  1463. {
  1464. if (needBorderColor(_flags) )
  1465. {
  1466. DWORD bc = D3DCOLOR_COLORVALUE(_rgba[0], _rgba[1], _rgba[2], _rgba[3]);
  1467. setSamplerState(device
  1468. , _stage
  1469. , D3DSAMP_BORDERCOLOR
  1470. , bc
  1471. );
  1472. }
  1473. }
  1474. }
  1475. }
  1476. bool isVisible(Frame* _render, OcclusionQueryHandle _handle, bool _visible)
  1477. {
  1478. m_occlusionQuery.resolve(_render);
  1479. return _visible == (0 != _render->m_occlusion[_handle.idx]);
  1480. }
  1481. void capturePreReset()
  1482. {
  1483. if (NULL != m_captureSurface)
  1484. {
  1485. g_callback->captureEnd();
  1486. }
  1487. DX_RELEASE(m_captureSurface, 1);
  1488. DX_RELEASE(m_captureTexture, 0);
  1489. DX_RELEASE(m_captureResolve, 0);
  1490. }
  1491. void capturePostReset()
  1492. {
  1493. if (m_resolution.m_flags&BGFX_RESET_CAPTURE)
  1494. {
  1495. uint32_t width = m_params.BackBufferWidth;
  1496. uint32_t height = m_params.BackBufferHeight;
  1497. D3DFORMAT fmt = m_params.BackBufferFormat;
  1498. DX_CHECK(m_device->CreateTexture(width
  1499. , height
  1500. , 1
  1501. , 0
  1502. , fmt
  1503. , D3DPOOL_SYSTEMMEM
  1504. , &m_captureTexture
  1505. , NULL
  1506. ) );
  1507. DX_CHECK(m_captureTexture->GetSurfaceLevel(0
  1508. , &m_captureSurface
  1509. ) );
  1510. if (m_params.MultiSampleType != D3DMULTISAMPLE_NONE)
  1511. {
  1512. DX_CHECK(m_device->CreateRenderTarget(width
  1513. , height
  1514. , fmt
  1515. , D3DMULTISAMPLE_NONE
  1516. , 0
  1517. , false
  1518. , &m_captureResolve
  1519. , NULL
  1520. ) );
  1521. }
  1522. g_callback->captureBegin(width, height, width*4, TextureFormat::BGRA8, false);
  1523. }
  1524. }
  1525. void capture()
  1526. {
  1527. if (NULL != m_captureSurface)
  1528. {
  1529. IDirect3DSurface9* resolve = m_backBufferColor;
  1530. if (NULL != m_captureResolve)
  1531. {
  1532. resolve = m_captureResolve;
  1533. DX_CHECK(m_device->StretchRect(m_backBufferColor
  1534. , 0
  1535. , m_captureResolve
  1536. , NULL
  1537. , D3DTEXF_NONE
  1538. ) );
  1539. }
  1540. HRESULT hr = m_device->GetRenderTargetData(resolve, m_captureSurface);
  1541. if (SUCCEEDED(hr) )
  1542. {
  1543. D3DLOCKED_RECT rect;
  1544. DX_CHECK(m_captureSurface->LockRect(&rect
  1545. , NULL
  1546. , D3DLOCK_NO_DIRTY_UPDATE|D3DLOCK_NOSYSLOCK|D3DLOCK_READONLY
  1547. ) );
  1548. g_callback->captureFrame(rect.pBits, m_params.BackBufferHeight*rect.Pitch);
  1549. DX_CHECK(m_captureSurface->UnlockRect() );
  1550. }
  1551. }
  1552. }
  1553. void commit(UniformBuffer& _uniformBuffer)
  1554. {
  1555. _uniformBuffer.reset();
  1556. IDirect3DDevice9* device = m_device;
  1557. for (;;)
  1558. {
  1559. uint32_t opcode = _uniformBuffer.read();
  1560. if (UniformType::End == opcode)
  1561. {
  1562. break;
  1563. }
  1564. UniformType::Enum type;
  1565. uint16_t loc;
  1566. uint16_t num;
  1567. uint16_t copy;
  1568. UniformBuffer::decodeOpcode(opcode, type, loc, num, copy);
  1569. const char* data;
  1570. if (copy)
  1571. {
  1572. data = _uniformBuffer.read(g_uniformTypeSize[type]*num);
  1573. }
  1574. else
  1575. {
  1576. UniformHandle handle;
  1577. bx::memCopy(&handle, _uniformBuffer.read(sizeof(UniformHandle) ), sizeof(UniformHandle) );
  1578. data = (const char*)m_uniforms[handle.idx];
  1579. }
  1580. #define CASE_IMPLEMENT_UNIFORM(_uniform, _dxsuffix, _type) \
  1581. case UniformType::_uniform: \
  1582. { \
  1583. _type* value = (_type*)data; \
  1584. DX_CHECK(device->SetVertexShaderConstant##_dxsuffix(loc, value, num) ); \
  1585. } \
  1586. break; \
  1587. \
  1588. case UniformType::_uniform|BGFX_UNIFORM_FRAGMENTBIT: \
  1589. { \
  1590. _type* value = (_type*)data; \
  1591. DX_CHECK(device->SetPixelShaderConstant##_dxsuffix(loc, value, num) ); \
  1592. } \
  1593. break
  1594. switch ( (int32_t)type)
  1595. {
  1596. case UniformType::Mat3:
  1597. {
  1598. float* value = (float*)data;
  1599. for (uint32_t ii = 0, count = num/3; ii < count; ++ii, loc += 3, value += 9)
  1600. {
  1601. Matrix4 mtx;
  1602. mtx.un.val[ 0] = value[0];
  1603. mtx.un.val[ 1] = value[1];
  1604. mtx.un.val[ 2] = value[2];
  1605. mtx.un.val[ 3] = 0.0f;
  1606. mtx.un.val[ 4] = value[3];
  1607. mtx.un.val[ 5] = value[4];
  1608. mtx.un.val[ 6] = value[5];
  1609. mtx.un.val[ 7] = 0.0f;
  1610. mtx.un.val[ 8] = value[6];
  1611. mtx.un.val[ 9] = value[7];
  1612. mtx.un.val[10] = value[8];
  1613. mtx.un.val[11] = 0.0f;
  1614. DX_CHECK(device->SetVertexShaderConstantF(loc, &mtx.un.val[0], 3) );
  1615. }
  1616. }
  1617. break;
  1618. case UniformType::Mat3|BGFX_UNIFORM_FRAGMENTBIT:
  1619. {
  1620. float* value = (float*)data;
  1621. for (uint32_t ii = 0, count = num/3; ii < count; ++ii, loc += 3, value += 9)
  1622. {
  1623. Matrix4 mtx;
  1624. mtx.un.val[ 0] = value[0];
  1625. mtx.un.val[ 1] = value[1];
  1626. mtx.un.val[ 2] = value[2];
  1627. mtx.un.val[ 3] = 0.0f;
  1628. mtx.un.val[ 4] = value[3];
  1629. mtx.un.val[ 5] = value[4];
  1630. mtx.un.val[ 6] = value[5];
  1631. mtx.un.val[ 7] = 0.0f;
  1632. mtx.un.val[ 8] = value[6];
  1633. mtx.un.val[ 9] = value[7];
  1634. mtx.un.val[10] = value[8];
  1635. mtx.un.val[11] = 0.0f;
  1636. DX_CHECK(device->SetPixelShaderConstantF(loc, &mtx.un.val[0], 3) );
  1637. }
  1638. }
  1639. break;
  1640. CASE_IMPLEMENT_UNIFORM(Int1, I, int);
  1641. CASE_IMPLEMENT_UNIFORM(Vec4, F, float);
  1642. CASE_IMPLEMENT_UNIFORM(Mat4, F, float);
  1643. case UniformType::End:
  1644. break;
  1645. default:
  1646. BX_TRACE("%4d: INVALID 0x%08x, t %d, l %d, n %d, c %d", _uniformBuffer.getPos(), opcode, type, loc, num, copy);
  1647. break;
  1648. }
  1649. #undef CASE_IMPLEMENT_UNIFORM
  1650. }
  1651. }
  1652. void clearQuad(ClearQuad& _clearQuad, const Rect& _rect, const Clear& _clear, const float _palette[][4])
  1653. {
  1654. IDirect3DDevice9* device = m_device;
  1655. uint32_t numMrt = 1;
  1656. FrameBufferHandle fbh = m_fbh;
  1657. if (isValid(fbh) )
  1658. {
  1659. const FrameBufferD3D9& fb = m_frameBuffers[fbh.idx];
  1660. numMrt = bx::uint32_max(1, fb.m_num);
  1661. }
  1662. if (1 == numMrt)
  1663. {
  1664. D3DCOLOR color = 0;
  1665. DWORD flags = 0;
  1666. if (BGFX_CLEAR_COLOR & _clear.m_flags)
  1667. {
  1668. if (BGFX_CLEAR_COLOR_USE_PALETTE & _clear.m_flags)
  1669. {
  1670. uint8_t index = (uint8_t)bx::uint32_min(BGFX_CONFIG_MAX_COLOR_PALETTE-1, _clear.m_index[0]);
  1671. const float* rgba = _palette[index];
  1672. const float rr = rgba[0];
  1673. const float gg = rgba[1];
  1674. const float bb = rgba[2];
  1675. const float aa = rgba[3];
  1676. color = D3DCOLOR_COLORVALUE(rr, gg, bb, aa);
  1677. }
  1678. else
  1679. {
  1680. color = D3DCOLOR_RGBA(_clear.m_index[0], _clear.m_index[1], _clear.m_index[2], _clear.m_index[3]);
  1681. }
  1682. flags |= D3DCLEAR_TARGET;
  1683. DX_CHECK(device->SetRenderState(D3DRS_COLORWRITEENABLE
  1684. , D3DCOLORWRITEENABLE_RED
  1685. | D3DCOLORWRITEENABLE_GREEN
  1686. | D3DCOLORWRITEENABLE_BLUE
  1687. | D3DCOLORWRITEENABLE_ALPHA
  1688. ) );
  1689. }
  1690. if (BGFX_CLEAR_DEPTH & _clear.m_flags)
  1691. {
  1692. flags |= D3DCLEAR_ZBUFFER;
  1693. DX_CHECK(device->SetRenderState(D3DRS_ZWRITEENABLE, TRUE) );
  1694. }
  1695. if (BGFX_CLEAR_STENCIL & _clear.m_flags)
  1696. {
  1697. flags |= D3DCLEAR_STENCIL;
  1698. }
  1699. if (0 != flags)
  1700. {
  1701. RECT rc;
  1702. rc.left = _rect.m_x;
  1703. rc.top = _rect.m_y;
  1704. rc.right = _rect.m_x + _rect.m_width;
  1705. rc.bottom = _rect.m_y + _rect.m_height;
  1706. DX_CHECK(device->SetRenderState(D3DRS_SCISSORTESTENABLE, TRUE) );
  1707. DX_CHECK(device->SetScissorRect(&rc) );
  1708. DX_CHECK(device->Clear(0, NULL, flags, color, _clear.m_depth, _clear.m_stencil) );
  1709. DX_CHECK(device->SetRenderState(D3DRS_SCISSORTESTENABLE, FALSE) );
  1710. }
  1711. }
  1712. else
  1713. {
  1714. DX_CHECK(device->SetRenderState(D3DRS_SCISSORTESTENABLE, FALSE) );
  1715. DX_CHECK(device->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE) );
  1716. DX_CHECK(device->SetRenderState(D3DRS_ALPHABLENDENABLE, FALSE) );
  1717. if (BGFX_CLEAR_COLOR & _clear.m_flags)
  1718. {
  1719. DX_CHECK(device->SetRenderState(D3DRS_COLORWRITEENABLE
  1720. , D3DCOLORWRITEENABLE_RED
  1721. | D3DCOLORWRITEENABLE_GREEN
  1722. | D3DCOLORWRITEENABLE_BLUE
  1723. | D3DCOLORWRITEENABLE_ALPHA
  1724. ) );
  1725. }
  1726. else
  1727. {
  1728. DX_CHECK(device->SetRenderState(D3DRS_COLORWRITEENABLE, 0) );
  1729. }
  1730. if (BGFX_CLEAR_DEPTH & _clear.m_flags)
  1731. {
  1732. DX_CHECK(device->SetRenderState(D3DRS_ZWRITEENABLE, TRUE) );
  1733. DX_CHECK(device->SetRenderState(D3DRS_ZENABLE, TRUE) );
  1734. DX_CHECK(device->SetRenderState(D3DRS_ZFUNC, D3DCMP_ALWAYS) );
  1735. }
  1736. else
  1737. {
  1738. DX_CHECK(device->SetRenderState(D3DRS_ZWRITEENABLE, FALSE) );
  1739. DX_CHECK(device->SetRenderState(D3DRS_ZENABLE, FALSE) );
  1740. }
  1741. if (BGFX_CLEAR_STENCIL & _clear.m_flags)
  1742. {
  1743. DX_CHECK(device->SetRenderState(D3DRS_STENCILENABLE, TRUE) );
  1744. DX_CHECK(device->SetRenderState(D3DRS_TWOSIDEDSTENCILMODE, TRUE) );
  1745. DX_CHECK(device->SetRenderState(D3DRS_STENCILREF, _clear.m_stencil) );
  1746. DX_CHECK(device->SetRenderState(D3DRS_STENCILMASK, 0xff) );
  1747. DX_CHECK(device->SetRenderState(D3DRS_STENCILFUNC, D3DCMP_ALWAYS) );
  1748. DX_CHECK(device->SetRenderState(D3DRS_STENCILFAIL, D3DSTENCILOP_REPLACE) );
  1749. DX_CHECK(device->SetRenderState(D3DRS_STENCILZFAIL, D3DSTENCILOP_REPLACE) );
  1750. DX_CHECK(device->SetRenderState(D3DRS_STENCILPASS, D3DSTENCILOP_REPLACE) );
  1751. }
  1752. else
  1753. {
  1754. DX_CHECK(device->SetRenderState(D3DRS_STENCILENABLE, FALSE) );
  1755. }
  1756. VertexBufferD3D9& vb = m_vertexBuffers[_clearQuad.m_vb->handle.idx];
  1757. VertexDecl& vertexDecl = m_vertexDecls[_clearQuad.m_vb->decl.idx];
  1758. uint32_t stride = _clearQuad.m_decl.m_stride;
  1759. {
  1760. struct Vertex
  1761. {
  1762. float m_x;
  1763. float m_y;
  1764. float m_z;
  1765. };
  1766. Vertex* vertex = (Vertex*)_clearQuad.m_vb->data;
  1767. BX_CHECK(stride == sizeof(Vertex), "Stride/Vertex mismatch (stride %d, sizeof(Vertex) %d)", stride, sizeof(Vertex) );
  1768. const float depth = _clear.m_depth;
  1769. vertex->m_x = -1.0f;
  1770. vertex->m_y = -1.0f;
  1771. vertex->m_z = depth;
  1772. vertex++;
  1773. vertex->m_x = 1.0f;
  1774. vertex->m_y = -1.0f;
  1775. vertex->m_z = depth;
  1776. vertex++;
  1777. vertex->m_x = -1.0f;
  1778. vertex->m_y = 1.0f;
  1779. vertex->m_z = depth;
  1780. vertex++;
  1781. vertex->m_x = 1.0f;
  1782. vertex->m_y = 1.0f;
  1783. vertex->m_z = depth;
  1784. }
  1785. vb.update(0, 4*stride, _clearQuad.m_vb->data);
  1786. ProgramD3D9& program = m_program[_clearQuad.m_program[numMrt-1].idx];
  1787. device->SetVertexShader(program.m_vsh->m_vertexShader);
  1788. device->SetPixelShader(program.m_fsh->m_pixelShader);
  1789. float mrtClear[BGFX_CONFIG_MAX_FRAME_BUFFER_ATTACHMENTS][4];
  1790. if (BGFX_CLEAR_COLOR_USE_PALETTE & _clear.m_flags)
  1791. {
  1792. for (uint32_t ii = 0; ii < numMrt; ++ii)
  1793. {
  1794. uint8_t index = (uint8_t)bx::uint32_min(BGFX_CONFIG_MAX_COLOR_PALETTE - 1, _clear.m_index[ii]);
  1795. bx::memCopy(mrtClear[ii], _palette[index], 16);
  1796. }
  1797. }
  1798. else
  1799. {
  1800. float rgba[4] =
  1801. {
  1802. _clear.m_index[0] * 1.0f / 255.0f,
  1803. _clear.m_index[1] * 1.0f / 255.0f,
  1804. _clear.m_index[2] * 1.0f / 255.0f,
  1805. _clear.m_index[3] * 1.0f / 255.0f,
  1806. };
  1807. for (uint32_t ii = 0; ii < numMrt; ++ii)
  1808. {
  1809. bx::memCopy(mrtClear[ii], rgba, 16);
  1810. }
  1811. }
  1812. DX_CHECK(device->SetPixelShaderConstantF(0, mrtClear[0], numMrt));
  1813. DX_CHECK(device->SetStreamSource(0, vb.m_ptr, 0, stride) );
  1814. DX_CHECK(device->SetStreamSourceFreq(0, 1) );
  1815. DX_CHECK(device->SetStreamSource(1, NULL, 0, 0) );
  1816. setInputLayout(vertexDecl, 0);
  1817. DX_CHECK(device->SetIndices(NULL) );
  1818. DX_CHECK(device->DrawPrimitive(D3DPT_TRIANGLESTRIP
  1819. , 0
  1820. , 2
  1821. ) );
  1822. }
  1823. }
  1824. void setInputLayout(uint8_t _numStreams, const VertexDecl** _vertexDecls, uint16_t _numInstanceData)
  1825. {
  1826. bx::HashMurmur2A murmur;
  1827. murmur.begin();
  1828. murmur.add(_numInstanceData);
  1829. for (uint8_t stream = 0; stream < _numStreams; ++stream)
  1830. {
  1831. murmur.add(_vertexDecls[stream]->m_hash);
  1832. }
  1833. uint64_t layoutHash = murmur.end();
  1834. IDirect3DVertexDeclaration9* layout = m_inputLayoutCache.find(layoutHash);
  1835. if (NULL == layout)
  1836. {
  1837. D3DVERTEXELEMENT9 vertexElements[Attrib::Count+1+BGFX_CONFIG_MAX_INSTANCE_DATA_COUNT];
  1838. D3DVERTEXELEMENT9* elem = vertexElements;
  1839. for (uint8_t stream = 0; stream < _numStreams; ++stream)
  1840. {
  1841. elem = fillVertexDecl(stream, elem, *_vertexDecls[stream]);
  1842. }
  1843. const D3DVERTEXELEMENT9 inst = { _numStreams, 0, D3DDECLTYPE_FLOAT4, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 0 };
  1844. for (uint8_t ii = 0; ii < _numInstanceData; ++ii)
  1845. {
  1846. bx::memCopy(elem, &inst, sizeof(D3DVERTEXELEMENT9) );
  1847. elem->UsageIndex = uint8_t(7-ii); // TEXCOORD7 = i_data0, TEXCOORD6 = i_data1, etc.
  1848. elem->Offset = ii*16;
  1849. ++elem;
  1850. }
  1851. bx::memCopy(elem, &s_attrib[Attrib::Count], sizeof(D3DVERTEXELEMENT9) );
  1852. DX_CHECK(m_device->CreateVertexDeclaration(vertexElements, &layout) );
  1853. m_inputLayoutCache.add(layoutHash, layout);
  1854. }
  1855. DX_CHECK(m_device->SetVertexDeclaration(layout) );
  1856. }
  1857. void setInputLayout(const VertexDecl& _vertexDecl, uint16_t _numInstanceData)
  1858. {
  1859. const VertexDecl* decls[1] = { &_vertexDecl };
  1860. setInputLayout(BX_COUNTOF(decls), decls, _numInstanceData);
  1861. }
  1862. D3DCAPS9 m_caps;
  1863. IDirect3D9Ex* m_d3d9ex;
  1864. IDirect3DDevice9Ex* m_deviceEx;
  1865. IDirect3D9* m_d3d9;
  1866. IDirect3DDevice9* m_device;
  1867. IDirect3DQuery9* m_flushQuery;
  1868. TimerQueryD3D9 m_gpuTimer;
  1869. OcclusionQueryD3D9 m_occlusionQuery;
  1870. D3DPOOL m_pool;
  1871. IDirect3DSwapChain9* m_swapChain;
  1872. bool m_needPresent;
  1873. uint16_t m_numWindows;
  1874. FrameBufferHandle m_windows[BGFX_CONFIG_MAX_FRAME_BUFFERS];
  1875. IDirect3DSurface9* m_backBufferColor;
  1876. IDirect3DSurface9* m_backBufferDepthStencil;
  1877. IDirect3DTexture9* m_captureTexture;
  1878. IDirect3DSurface9* m_captureSurface;
  1879. IDirect3DSurface9* m_captureResolve;
  1880. IDirect3DVertexDeclaration9* m_instanceDataDecls[BGFX_CONFIG_MAX_INSTANCE_DATA_COUNT];
  1881. void* m_d3d9dll;
  1882. NvApi m_nvapi;
  1883. uint32_t m_adapter;
  1884. D3DDEVTYPE m_deviceType;
  1885. D3DPRESENT_PARAMETERS m_params;
  1886. uint32_t m_maxAnisotropy;
  1887. D3DADAPTER_IDENTIFIER9 m_identifier;
  1888. Resolution m_resolution;
  1889. bool m_initialized;
  1890. bool m_amd;
  1891. bool m_nvidia;
  1892. bool m_atocSupport;
  1893. bool m_instancingSupport;
  1894. bool m_occlusionQuerySupport;
  1895. bool m_timerQuerySupport;
  1896. D3DFORMAT m_fmtDepth;
  1897. IndexBufferD3D9 m_indexBuffers[BGFX_CONFIG_MAX_INDEX_BUFFERS];
  1898. VertexBufferD3D9 m_vertexBuffers[BGFX_CONFIG_MAX_VERTEX_BUFFERS];
  1899. ShaderD3D9 m_shaders[BGFX_CONFIG_MAX_SHADERS];
  1900. ProgramD3D9 m_program[BGFX_CONFIG_MAX_PROGRAMS];
  1901. TextureD3D9 m_textures[BGFX_CONFIG_MAX_TEXTURES];
  1902. VertexDecl m_vertexDecls[BGFX_CONFIG_MAX_VERTEX_DECLS];
  1903. FrameBufferD3D9 m_frameBuffers[BGFX_CONFIG_MAX_FRAME_BUFFERS];
  1904. UniformRegistry m_uniformReg;
  1905. void* m_uniforms[BGFX_CONFIG_MAX_UNIFORMS];
  1906. uint32_t m_samplerFlags[BGFX_CONFIG_MAX_TEXTURE_SAMPLERS];
  1907. TextureD3D9* m_updateTexture;
  1908. uint8_t* m_updateTextureBits;
  1909. uint32_t m_updateTexturePitch;
  1910. uint8_t m_updateTextureSide;
  1911. uint8_t m_updateTextureMip;
  1912. StateCacheT<IDirect3DVertexDeclaration9> m_inputLayoutCache;
  1913. TextVideoMem m_textVideoMem;
  1914. FrameBufferHandle m_fbh;
  1915. bool m_rtMsaa;
  1916. };
  1917. static RendererContextD3D9* s_renderD3D9;
  1918. RendererContextI* rendererCreate()
  1919. {
  1920. s_renderD3D9 = BX_NEW(g_allocator, RendererContextD3D9);
  1921. if (!s_renderD3D9->init() )
  1922. {
  1923. BX_DELETE(g_allocator, s_renderD3D9);
  1924. s_renderD3D9 = NULL;
  1925. }
  1926. return s_renderD3D9;
  1927. }
  1928. void rendererDestroy()
  1929. {
  1930. s_renderD3D9->shutdown();
  1931. BX_DELETE(g_allocator, s_renderD3D9);
  1932. s_renderD3D9 = NULL;
  1933. }
  1934. void IndexBufferD3D9::create(uint32_t _size, void* _data, uint16_t _flags)
  1935. {
  1936. m_size = _size;
  1937. m_flags = _flags;
  1938. uint32_t usage = D3DUSAGE_WRITEONLY;
  1939. D3DPOOL pool = s_renderD3D9->m_pool;
  1940. if (NULL == _data)
  1941. {
  1942. usage |= D3DUSAGE_DYNAMIC;
  1943. pool = D3DPOOL_DEFAULT;
  1944. m_dynamic = (uint8_t*)BX_ALLOC(g_allocator, _size);
  1945. }
  1946. const D3DFORMAT format = 0 == (_flags & BGFX_BUFFER_INDEX32)
  1947. ? D3DFMT_INDEX16
  1948. : D3DFMT_INDEX32
  1949. ;
  1950. DX_CHECK(s_renderD3D9->m_device->CreateIndexBuffer(m_size
  1951. , usage
  1952. , format
  1953. , pool
  1954. , &m_ptr
  1955. , NULL
  1956. ) );
  1957. if (NULL != _data)
  1958. {
  1959. update(0, _size, _data);
  1960. }
  1961. }
  1962. void IndexBufferD3D9::preReset()
  1963. {
  1964. if (NULL != m_dynamic)
  1965. {
  1966. DX_RELEASE(m_ptr, 0);
  1967. }
  1968. }
  1969. void IndexBufferD3D9::postReset()
  1970. {
  1971. if (NULL != m_dynamic)
  1972. {
  1973. const D3DFORMAT format = 0 == (m_flags & BGFX_BUFFER_INDEX32)
  1974. ? D3DFMT_INDEX16
  1975. : D3DFMT_INDEX32
  1976. ;
  1977. DX_CHECK(s_renderD3D9->m_device->CreateIndexBuffer(m_size
  1978. , D3DUSAGE_WRITEONLY|D3DUSAGE_DYNAMIC
  1979. , format
  1980. , D3DPOOL_DEFAULT
  1981. , &m_ptr
  1982. , NULL
  1983. ) );
  1984. update(0, m_size, m_dynamic);
  1985. }
  1986. }
  1987. void VertexBufferD3D9::create(uint32_t _size, void* _data, VertexDeclHandle _declHandle)
  1988. {
  1989. m_size = _size;
  1990. m_decl = _declHandle;
  1991. uint32_t usage = D3DUSAGE_WRITEONLY;
  1992. D3DPOOL pool = s_renderD3D9->m_pool;
  1993. if (NULL == _data)
  1994. {
  1995. usage |= D3DUSAGE_DYNAMIC;
  1996. pool = D3DPOOL_DEFAULT;
  1997. m_dynamic = (uint8_t*)BX_ALLOC(g_allocator, _size);
  1998. }
  1999. DX_CHECK(s_renderD3D9->m_device->CreateVertexBuffer(m_size
  2000. , usage
  2001. , 0
  2002. , pool
  2003. , &m_ptr
  2004. , NULL
  2005. ) );
  2006. if (NULL != _data)
  2007. {
  2008. update(0, _size, _data);
  2009. }
  2010. }
  2011. void VertexBufferD3D9::preReset()
  2012. {
  2013. if (NULL != m_dynamic)
  2014. {
  2015. DX_RELEASE(m_ptr, 0);
  2016. }
  2017. }
  2018. void VertexBufferD3D9::postReset()
  2019. {
  2020. if (NULL != m_dynamic)
  2021. {
  2022. DX_CHECK(s_renderD3D9->m_device->CreateVertexBuffer(m_size
  2023. , D3DUSAGE_WRITEONLY|D3DUSAGE_DYNAMIC
  2024. , 0
  2025. , D3DPOOL_DEFAULT
  2026. , &m_ptr
  2027. , NULL
  2028. ) );
  2029. update(0, m_size, m_dynamic);
  2030. }
  2031. }
  2032. void ShaderD3D9::create(const Memory* _mem)
  2033. {
  2034. bx::MemoryReader reader(_mem->data, _mem->size);
  2035. uint32_t magic;
  2036. bx::read(&reader, magic);
  2037. switch (magic)
  2038. {
  2039. case BGFX_CHUNK_MAGIC_FSH:
  2040. case BGFX_CHUNK_MAGIC_VSH:
  2041. break;
  2042. default:
  2043. BGFX_FATAL(false, Fatal::InvalidShader, "Unknown shader format %x.", magic);
  2044. break;
  2045. }
  2046. bool fragment = BGFX_CHUNK_MAGIC_FSH == magic;
  2047. uint32_t iohash;
  2048. bx::read(&reader, iohash);
  2049. uint16_t count;
  2050. bx::read(&reader, count);
  2051. m_numPredefined = 0;
  2052. BX_TRACE("Shader consts %d", count);
  2053. uint8_t fragmentBit = fragment ? BGFX_UNIFORM_FRAGMENTBIT : 0;
  2054. if (0 < count)
  2055. {
  2056. for (uint32_t ii = 0; ii < count; ++ii)
  2057. {
  2058. uint8_t nameSize = 0;
  2059. bx::read(&reader, nameSize);
  2060. char name[256] = {};
  2061. bx::read(&reader, &name, nameSize);
  2062. name[nameSize] = '\0';
  2063. uint8_t type = 0;
  2064. bx::read(&reader, type);
  2065. uint8_t num = 0;
  2066. bx::read(&reader, num);
  2067. uint16_t regIndex = 0;
  2068. bx::read(&reader, regIndex);
  2069. uint16_t regCount = 0;
  2070. bx::read(&reader, regCount);
  2071. const char* kind = "invalid";
  2072. PredefinedUniform::Enum predefined = nameToPredefinedUniformEnum(name);
  2073. if (PredefinedUniform::Count != predefined)
  2074. {
  2075. kind = "predefined";
  2076. m_predefined[m_numPredefined].m_loc = regIndex;
  2077. m_predefined[m_numPredefined].m_count = regCount;
  2078. m_predefined[m_numPredefined].m_type = uint8_t(predefined|fragmentBit);
  2079. m_numPredefined++;
  2080. }
  2081. else if (0 == (BGFX_UNIFORM_SAMPLERBIT & type) )
  2082. {
  2083. const UniformRegInfo* info = s_renderD3D9->m_uniformReg.find(name);
  2084. BX_WARN(NULL != info, "User defined uniform '%s' is not found, it won't be set.", name);
  2085. if (NULL != info)
  2086. {
  2087. if (NULL == m_constantBuffer)
  2088. {
  2089. m_constantBuffer = UniformBuffer::create(1024);
  2090. }
  2091. kind = "user";
  2092. m_constantBuffer->writeUniformHandle( (UniformType::Enum)(type|fragmentBit), regIndex, info->m_handle, regCount);
  2093. }
  2094. }
  2095. else
  2096. {
  2097. kind = "sampler";
  2098. }
  2099. BX_TRACE("\t%s: %s (%s), num %2d, r.index %3d, r.count %2d"
  2100. , kind
  2101. , name
  2102. , getUniformTypeName(UniformType::Enum(type&~BGFX_UNIFORM_MASK) )
  2103. , num
  2104. , regIndex
  2105. , regCount
  2106. );
  2107. BX_UNUSED(kind);
  2108. }
  2109. if (NULL != m_constantBuffer)
  2110. {
  2111. m_constantBuffer->finish();
  2112. }
  2113. }
  2114. uint32_t shaderSize;
  2115. bx::read(&reader, shaderSize);
  2116. const DWORD* code = (const DWORD*)reader.getDataPtr();
  2117. if (fragment)
  2118. {
  2119. m_type = 1;
  2120. DX_CHECK(s_renderD3D9->m_device->CreatePixelShader(code, &m_pixelShader) );
  2121. BGFX_FATAL(NULL != m_pixelShader, bgfx::Fatal::InvalidShader, "Failed to create fragment shader.");
  2122. }
  2123. else
  2124. {
  2125. m_type = 0;
  2126. DX_CHECK(s_renderD3D9->m_device->CreateVertexShader(code, &m_vertexShader) );
  2127. BGFX_FATAL(NULL != m_vertexShader, bgfx::Fatal::InvalidShader, "Failed to create vertex shader.");
  2128. }
  2129. }
  2130. void TextureD3D9::createTexture(uint32_t _width, uint32_t _height, uint8_t _numMips)
  2131. {
  2132. m_type = Texture2D;
  2133. const bimg::TextureFormat::Enum fmt = (bimg::TextureFormat::Enum)m_textureFormat;
  2134. DWORD usage = 0;
  2135. D3DPOOL pool = D3DPOOL_DEFAULT;
  2136. const bool renderTarget = 0 != (m_flags&BGFX_TEXTURE_RT_MASK);
  2137. const bool blit = 0 != (m_flags&BGFX_TEXTURE_BLIT_DST);
  2138. const bool readBack = 0 != (m_flags&BGFX_TEXTURE_READ_BACK);
  2139. if (bimg::isDepth(fmt) )
  2140. {
  2141. usage = D3DUSAGE_DEPTHSTENCIL;
  2142. }
  2143. else if (readBack)
  2144. {
  2145. usage = 0;
  2146. pool = D3DPOOL_SYSTEMMEM;
  2147. }
  2148. else if (renderTarget || blit)
  2149. {
  2150. usage = 0
  2151. | D3DUSAGE_RENDERTARGET
  2152. | (1 < _numMips ? D3DUSAGE_AUTOGENMIPMAP : 0)
  2153. ;
  2154. }
  2155. IDirect3DDevice9* device = s_renderD3D9->m_device;
  2156. if (renderTarget)
  2157. {
  2158. uint32_t msaaQuality = ( (m_flags&BGFX_TEXTURE_RT_MSAA_MASK)>>BGFX_TEXTURE_RT_MSAA_SHIFT);
  2159. msaaQuality = bx::uint32_satsub(msaaQuality, 1);
  2160. bool writeOnly = 0 != (m_flags&BGFX_TEXTURE_RT_WRITE_ONLY);
  2161. if (0 != msaaQuality
  2162. || writeOnly)
  2163. {
  2164. const Msaa& msaa = s_msaa[msaaQuality];
  2165. if (bimg::isDepth(fmt) )
  2166. {
  2167. DX_CHECK(device->CreateDepthStencilSurface(
  2168. m_width
  2169. , m_height
  2170. , s_textureFormat[m_textureFormat].m_fmt
  2171. , msaa.m_type
  2172. , msaa.m_quality
  2173. , FALSE
  2174. , &m_surface
  2175. , NULL
  2176. ) );
  2177. }
  2178. else
  2179. {
  2180. DX_CHECK(device->CreateRenderTarget(
  2181. m_width
  2182. , m_height
  2183. , s_textureFormat[m_textureFormat].m_fmt
  2184. , msaa.m_type
  2185. , msaa.m_quality
  2186. , FALSE
  2187. , &m_surface
  2188. , NULL
  2189. ) );
  2190. }
  2191. if (writeOnly)
  2192. {
  2193. // This is render buffer, there is no sampling, no need
  2194. // to create texture.
  2195. return;
  2196. }
  2197. }
  2198. }
  2199. DX_CHECK(device->CreateTexture(_width
  2200. , _height
  2201. , _numMips
  2202. , usage
  2203. , s_textureFormat[fmt].m_fmt
  2204. , pool
  2205. , &m_texture2d
  2206. , NULL
  2207. ) );
  2208. if (!renderTarget
  2209. && !readBack)
  2210. {
  2211. if (NULL == m_staging)
  2212. {
  2213. DX_CHECK(device->CreateTexture(_width
  2214. , _height
  2215. , _numMips
  2216. , 0
  2217. , s_textureFormat[fmt].m_fmt
  2218. , D3DPOOL_SYSTEMMEM
  2219. , &m_staging2d
  2220. , NULL
  2221. ) );
  2222. }
  2223. else
  2224. {
  2225. DX_CHECK(m_staging2d->AddDirtyRect(NULL));
  2226. DX_CHECK(device->UpdateTexture(m_staging2d, m_texture2d));
  2227. }
  2228. }
  2229. BGFX_FATAL(NULL != m_texture2d, Fatal::UnableToCreateTexture, "Failed to create texture (size: %dx%d, mips: %d, fmt: %d)."
  2230. , _width
  2231. , _height
  2232. , _numMips
  2233. , bimg::getName(fmt)
  2234. );
  2235. }
  2236. void TextureD3D9::createVolumeTexture(uint32_t _width, uint32_t _height, uint32_t _depth, uint8_t _numMips)
  2237. {
  2238. m_type = Texture3D;
  2239. const TextureFormat::Enum fmt = (TextureFormat::Enum)m_textureFormat;
  2240. IDirect3DDevice9* device = s_renderD3D9->m_device;
  2241. DX_CHECK(device->CreateVolumeTexture(_width
  2242. , _height
  2243. , _depth
  2244. , _numMips
  2245. , 0
  2246. , s_textureFormat[fmt].m_fmt
  2247. , D3DPOOL_DEFAULT
  2248. , &m_texture3d
  2249. , NULL
  2250. ) );
  2251. if (NULL == m_staging)
  2252. {
  2253. DX_CHECK(device->CreateVolumeTexture(_width
  2254. , _height
  2255. , _depth
  2256. , _numMips
  2257. , 0
  2258. , s_textureFormat[fmt].m_fmt
  2259. , D3DPOOL_SYSTEMMEM
  2260. , &m_staging3d
  2261. , NULL
  2262. ) );
  2263. }
  2264. else
  2265. {
  2266. DX_CHECK(m_staging3d->AddDirtyBox(NULL) );
  2267. DX_CHECK(device->UpdateTexture(m_staging3d, m_texture3d) );
  2268. }
  2269. BGFX_FATAL(NULL != m_texture3d, Fatal::UnableToCreateTexture, "Failed to create volume texture (size: %dx%dx%d, mips: %d, fmt: %s)."
  2270. , _width
  2271. , _height
  2272. , _depth
  2273. , _numMips
  2274. , getName(fmt)
  2275. );
  2276. }
  2277. void TextureD3D9::createCubeTexture(uint32_t _width, uint8_t _numMips)
  2278. {
  2279. m_type = TextureCube;
  2280. const bimg::TextureFormat::Enum fmt = (bimg::TextureFormat::Enum)m_textureFormat;
  2281. DWORD usage = 0;
  2282. const bool renderTarget = 0 != (m_flags&BGFX_TEXTURE_RT_MASK);
  2283. const bool blit = 0 != (m_flags&BGFX_TEXTURE_BLIT_DST);
  2284. if (bimg::isDepth(fmt) )
  2285. {
  2286. usage = D3DUSAGE_DEPTHSTENCIL;
  2287. }
  2288. else if (renderTarget || blit)
  2289. {
  2290. usage = D3DUSAGE_RENDERTARGET;
  2291. }
  2292. IDirect3DDevice9* device = s_renderD3D9->m_device;
  2293. DX_CHECK(device->CreateCubeTexture(_width
  2294. , _numMips
  2295. , usage
  2296. , s_textureFormat[fmt].m_fmt
  2297. , D3DPOOL_DEFAULT
  2298. , &m_textureCube
  2299. , NULL
  2300. ) );
  2301. if (!renderTarget)
  2302. {
  2303. if (NULL == m_staging)
  2304. {
  2305. DX_CHECK(device->CreateCubeTexture(_width
  2306. , _numMips
  2307. , 0
  2308. , s_textureFormat[fmt].m_fmt
  2309. , D3DPOOL_SYSTEMMEM
  2310. , &m_stagingCube
  2311. , NULL
  2312. ) );
  2313. }
  2314. else
  2315. {
  2316. for (uint8_t ii = 0; ii < 6; ++ii)
  2317. {
  2318. DX_CHECK(m_stagingCube->AddDirtyRect(D3DCUBEMAP_FACES(ii), NULL) );
  2319. }
  2320. DX_CHECK(device->UpdateTexture(m_stagingCube, m_textureCube) );
  2321. }
  2322. }
  2323. BGFX_FATAL(NULL != m_textureCube, Fatal::UnableToCreateTexture, "Failed to create cube texture (edge: %d, mips: %d, fmt: %s)."
  2324. , _width
  2325. , _numMips
  2326. , getName(fmt)
  2327. );
  2328. }
  2329. uint8_t* TextureD3D9::lock(uint8_t _side, uint8_t _lod, uint32_t& _pitch, uint32_t& _slicePitch, const Rect* _rect)
  2330. {
  2331. switch (m_type)
  2332. {
  2333. case Texture2D:
  2334. {
  2335. D3DLOCKED_RECT lockedRect;
  2336. if (NULL != _rect)
  2337. {
  2338. RECT rect;
  2339. rect.left = _rect->m_x;
  2340. rect.top = _rect->m_y;
  2341. rect.right = rect.left + _rect->m_width;
  2342. rect.bottom = rect.top + _rect->m_height;
  2343. DX_CHECK(m_staging2d->LockRect(_lod, &lockedRect, &rect, 0) );
  2344. DX_CHECK(m_staging2d->AddDirtyRect(&rect) );
  2345. }
  2346. else
  2347. {
  2348. DX_CHECK(m_staging2d->LockRect(_lod, &lockedRect, NULL, 0) );
  2349. DX_CHECK(m_staging2d->AddDirtyRect(NULL) );
  2350. }
  2351. _pitch = lockedRect.Pitch;
  2352. _slicePitch = 0;
  2353. return (uint8_t*)lockedRect.pBits;
  2354. }
  2355. case Texture3D:
  2356. {
  2357. D3DLOCKED_BOX box;
  2358. DX_CHECK(m_staging3d->LockBox(_lod, &box, NULL, 0) );
  2359. DX_CHECK(m_staging3d->AddDirtyBox(NULL) );
  2360. _pitch = box.RowPitch;
  2361. _slicePitch = box.SlicePitch;
  2362. return (uint8_t*)box.pBits;
  2363. }
  2364. case TextureCube:
  2365. {
  2366. D3DLOCKED_RECT lockedRect;
  2367. if (NULL != _rect)
  2368. {
  2369. RECT rect;
  2370. rect.left = _rect->m_x;
  2371. rect.top = _rect->m_y;
  2372. rect.right = rect.left + _rect->m_width;
  2373. rect.bottom = rect.top + _rect->m_height;
  2374. DX_CHECK(m_stagingCube->LockRect(D3DCUBEMAP_FACES(_side), _lod, &lockedRect, &rect, 0) );
  2375. DX_CHECK(m_textureCube->AddDirtyRect(D3DCUBEMAP_FACES(_side), &rect) );
  2376. }
  2377. else
  2378. {
  2379. DX_CHECK(m_stagingCube->LockRect(D3DCUBEMAP_FACES(_side), _lod, &lockedRect, NULL, 0) );
  2380. DX_CHECK(m_textureCube->AddDirtyRect(D3DCUBEMAP_FACES(_side), NULL) );
  2381. }
  2382. _pitch = lockedRect.Pitch;
  2383. _slicePitch = 0;
  2384. return (uint8_t*)lockedRect.pBits;
  2385. }
  2386. }
  2387. BX_CHECK(false, "You should not be here.");
  2388. _pitch = 0;
  2389. _slicePitch = 0;
  2390. return NULL;
  2391. }
  2392. void TextureD3D9::unlock(uint8_t _side, uint8_t _lod)
  2393. {
  2394. IDirect3DDevice9* device = s_renderD3D9->m_device;
  2395. switch (m_type)
  2396. {
  2397. case Texture2D:
  2398. {
  2399. DX_CHECK(m_staging2d->UnlockRect(_lod) );
  2400. DX_CHECK(device->UpdateTexture(m_staging2d, m_texture2d) );
  2401. }
  2402. return;
  2403. case Texture3D:
  2404. {
  2405. DX_CHECK(m_staging3d->UnlockBox(_lod) );
  2406. DX_CHECK(device->UpdateTexture(m_staging3d, m_texture3d) );
  2407. }
  2408. return;
  2409. case TextureCube:
  2410. {
  2411. DX_CHECK(m_stagingCube->UnlockRect(D3DCUBEMAP_FACES(_side), _lod) );
  2412. DX_CHECK(device->UpdateTexture(m_stagingCube, m_textureCube) );
  2413. }
  2414. return;
  2415. }
  2416. BX_CHECK(false, "You should not be here.");
  2417. }
  2418. void TextureD3D9::dirty(uint8_t _side, const Rect& _rect, uint16_t _z, uint16_t _depth)
  2419. {
  2420. switch (m_type)
  2421. {
  2422. case Texture2D:
  2423. {
  2424. RECT rect;
  2425. rect.left = _rect.m_x;
  2426. rect.top = _rect.m_y;
  2427. rect.right = rect.left + _rect.m_width;
  2428. rect.bottom = rect.top + _rect.m_height;
  2429. DX_CHECK(m_texture2d->AddDirtyRect(&rect) );
  2430. }
  2431. return;
  2432. case Texture3D:
  2433. {
  2434. D3DBOX box;
  2435. box.Left = _rect.m_x;
  2436. box.Top = _rect.m_y;
  2437. box.Right = box.Left + _rect.m_width;
  2438. box.Bottom = box.Top + _rect.m_height;
  2439. box.Front = _z;
  2440. box.Back = box.Front + _depth;
  2441. DX_CHECK(m_texture3d->AddDirtyBox(&box) );
  2442. }
  2443. return;
  2444. case TextureCube:
  2445. {
  2446. RECT rect;
  2447. rect.left = _rect.m_x;
  2448. rect.top = _rect.m_y;
  2449. rect.right = rect.left + _rect.m_width;
  2450. rect.bottom = rect.top + _rect.m_height;
  2451. DX_CHECK(m_textureCube->AddDirtyRect(D3DCUBEMAP_FACES(_side), &rect) );
  2452. }
  2453. return;
  2454. }
  2455. BX_CHECK(false, "You should not be here.");
  2456. }
  2457. IDirect3DSurface9* TextureD3D9::getSurface(uint8_t _side, uint8_t _mip) const
  2458. {
  2459. IDirect3DSurface9* surface = NULL;
  2460. switch (m_type)
  2461. {
  2462. case Texture2D:
  2463. DX_CHECK(m_texture2d->GetSurfaceLevel(_mip, &surface) );
  2464. break;
  2465. case Texture3D:
  2466. BX_CHECK(false, "");
  2467. break;
  2468. case TextureCube:
  2469. DX_CHECK(m_textureCube->GetCubeMapSurface(D3DCUBEMAP_FACES(_side), _mip, &surface) );
  2470. break;
  2471. }
  2472. return surface;
  2473. }
  2474. void TextureD3D9::create(const Memory* _mem, uint32_t _flags, uint8_t _skip)
  2475. {
  2476. bimg::ImageContainer imageContainer;
  2477. if (bimg::imageParse(imageContainer, _mem->data, _mem->size) )
  2478. {
  2479. uint8_t numMips = imageContainer.m_numMips;
  2480. const uint8_t startLod = uint8_t(bx::uint32_min(_skip, numMips-1) );
  2481. numMips -= startLod;
  2482. const bimg::ImageBlockInfo& blockInfo = bimg::getBlockInfo(bimg::TextureFormat::Enum(imageContainer.m_format) );
  2483. const uint32_t textureWidth = bx::uint32_max(blockInfo.blockWidth, imageContainer.m_width >>startLod);
  2484. const uint32_t textureHeight = bx::uint32_max(blockInfo.blockHeight, imageContainer.m_height>>startLod);
  2485. m_flags = _flags;
  2486. m_width = textureWidth;
  2487. m_height = textureHeight;
  2488. m_depth = imageContainer.m_depth;
  2489. m_numMips = numMips;
  2490. m_requestedFormat = uint8_t(imageContainer.m_format);
  2491. m_textureFormat = uint8_t(getViableTextureFormat(imageContainer) );
  2492. const bool convert = m_textureFormat != m_requestedFormat;
  2493. uint8_t bpp = bimg::getBitsPerPixel(bimg::TextureFormat::Enum(m_textureFormat) );
  2494. if (imageContainer.m_cubeMap)
  2495. {
  2496. createCubeTexture(textureWidth, numMips);
  2497. }
  2498. else if (imageContainer.m_depth > 1)
  2499. {
  2500. createVolumeTexture(textureWidth, textureHeight, imageContainer.m_depth, numMips);
  2501. }
  2502. else
  2503. {
  2504. createTexture(textureWidth, textureHeight, numMips);
  2505. }
  2506. BX_TRACE("Texture %3d: %s (requested: %s), %dx%d%s%s."
  2507. , this - s_renderD3D9->m_textures
  2508. , getName( (TextureFormat::Enum)m_textureFormat)
  2509. , getName( (TextureFormat::Enum)m_requestedFormat)
  2510. , textureWidth
  2511. , textureHeight
  2512. , imageContainer.m_cubeMap ? "x6" : ""
  2513. , 0 != (m_flags&BGFX_TEXTURE_RT_MASK) ? " (render target)" : ""
  2514. );
  2515. if (0 != (_flags&BGFX_TEXTURE_RT_WRITE_ONLY) )
  2516. {
  2517. return;
  2518. }
  2519. // For BC4 and B5 in DX9 LockRect returns wrong number of
  2520. // bytes. If actual mip size is used it causes memory corruption.
  2521. // http://www.aras-p.info/texts/D3D9GPUHacks.html#3dc
  2522. const bool useMipSize = true
  2523. && imageContainer.m_format != bimg::TextureFormat::BC4
  2524. && imageContainer.m_format != bimg::TextureFormat::BC5
  2525. ;
  2526. for (uint8_t side = 0, numSides = imageContainer.m_cubeMap ? 6 : 1; side < numSides; ++side)
  2527. {
  2528. uint32_t width = textureWidth;
  2529. uint32_t height = textureHeight;
  2530. uint32_t depth = imageContainer.m_depth;
  2531. uint32_t mipWidth = imageContainer.m_width;
  2532. uint32_t mipHeight = imageContainer.m_height;
  2533. for (uint8_t lod = 0, num = numMips; lod < num; ++lod)
  2534. {
  2535. width = bx::uint32_max(1, width);
  2536. height = bx::uint32_max(1, height);
  2537. depth = bx::uint32_max(1, depth);
  2538. mipWidth = bx::uint32_max(blockInfo.blockWidth, mipWidth);
  2539. mipHeight = bx::uint32_max(blockInfo.blockHeight, mipHeight);
  2540. uint32_t mipSize = width*height*depth*bpp/8;
  2541. bimg::ImageMip mip;
  2542. if (bimg::imageGetRawData(imageContainer, side, lod+startLod, _mem->data, _mem->size, mip) )
  2543. {
  2544. uint32_t pitch;
  2545. uint32_t slicePitch;
  2546. uint8_t* bits = lock(side, lod, pitch, slicePitch);
  2547. if (convert)
  2548. {
  2549. if (width != mipWidth
  2550. || height != mipHeight)
  2551. {
  2552. uint32_t srcpitch = mipWidth*bpp/8;
  2553. uint8_t* temp = (uint8_t*)BX_ALLOC(g_allocator, srcpitch*mipHeight);
  2554. bimg::imageDecodeToBgra8(temp
  2555. , mip.m_data
  2556. , mip.m_width
  2557. , mip.m_height
  2558. , srcpitch
  2559. , mip.m_format
  2560. );
  2561. bx::memCopy(bits, temp, pitch, height, srcpitch, pitch);
  2562. BX_FREE(g_allocator, temp);
  2563. }
  2564. else
  2565. {
  2566. bimg::imageDecodeToBgra8(bits, mip.m_data, mip.m_width, mip.m_height, pitch, mip.m_format);
  2567. }
  2568. }
  2569. else
  2570. {
  2571. uint32_t size = useMipSize ? mip.m_size : mipSize;
  2572. switch (m_textureFormat)
  2573. {
  2574. case TextureFormat::RGB5A1:
  2575. bimg::imageConvert(bits, 16, bx::packBgr5a1, mip.m_data, bx::unpackRgb5a1, size);
  2576. break;
  2577. case TextureFormat::RGBA4:
  2578. bimg::imageConvert(bits, 16, bx::packBgra4, mip.m_data, bx::unpackRgba4, size);
  2579. break;
  2580. default:
  2581. bx::memCopy(bits, mip.m_data, size);
  2582. break;
  2583. }
  2584. }
  2585. unlock(side, lod);
  2586. }
  2587. width >>= 1;
  2588. height >>= 1;
  2589. depth >>= 1;
  2590. mipWidth >>= 1;
  2591. mipHeight >>= 1;
  2592. }
  2593. }
  2594. }
  2595. }
  2596. void TextureD3D9::updateBegin(uint8_t _side, uint8_t _mip)
  2597. {
  2598. uint32_t slicePitch;
  2599. s_renderD3D9->m_updateTextureSide = _side;
  2600. s_renderD3D9->m_updateTextureMip = _mip;
  2601. s_renderD3D9->m_updateTextureBits = lock(_side, _mip, s_renderD3D9->m_updateTexturePitch, slicePitch);
  2602. }
  2603. void TextureD3D9::update(uint8_t _side, uint8_t _mip, const Rect& _rect, uint16_t _z, uint16_t _depth, uint16_t _pitch, const Memory* _mem)
  2604. {
  2605. const uint32_t bpp = bimg::getBitsPerPixel(bimg::TextureFormat::Enum(m_textureFormat) );
  2606. const uint32_t rectpitch = _rect.m_width*bpp/8;
  2607. const uint32_t srcpitch = UINT16_MAX == _pitch ? rectpitch : _pitch;
  2608. const uint32_t dstpitch = s_renderD3D9->m_updateTexturePitch;
  2609. uint8_t* bits = s_renderD3D9->m_updateTextureBits + _rect.m_y*dstpitch + _rect.m_x*bpp/8;
  2610. const bool convert = m_textureFormat != m_requestedFormat;
  2611. uint8_t* data = _mem->data;
  2612. uint8_t* temp = NULL;
  2613. if (convert)
  2614. {
  2615. temp = (uint8_t*)BX_ALLOC(g_allocator, rectpitch*_rect.m_height);
  2616. bimg::imageDecodeToBgra8(temp, data, _rect.m_width, _rect.m_height, srcpitch, bimg::TextureFormat::Enum(m_requestedFormat) );
  2617. data = temp;
  2618. }
  2619. {
  2620. uint8_t* src = data;
  2621. uint8_t* dst = bits;
  2622. for (uint32_t yy = 0, height = _rect.m_height; yy < height; ++yy)
  2623. {
  2624. switch (m_textureFormat)
  2625. {
  2626. case TextureFormat::RGB5A1:
  2627. bimg::imageConvert(dst, 16, bx::packBgr5a1, src, bx::unpackRgb5a1, rectpitch);
  2628. break;
  2629. case TextureFormat::RGBA4:
  2630. bimg::imageConvert(dst, 16, bx::packBgra4, src, bx::unpackRgba4, rectpitch);
  2631. break;
  2632. default:
  2633. bx::memCopy(dst, src, rectpitch);
  2634. break;
  2635. }
  2636. src += srcpitch;
  2637. dst += dstpitch;
  2638. }
  2639. }
  2640. if (NULL != temp)
  2641. {
  2642. BX_FREE(g_allocator, temp);
  2643. }
  2644. if (0 == _mip)
  2645. {
  2646. dirty(_side, _rect, _z, _depth);
  2647. }
  2648. }
  2649. void TextureD3D9::updateEnd()
  2650. {
  2651. unlock(s_renderD3D9->m_updateTextureSide, s_renderD3D9->m_updateTextureMip);
  2652. }
  2653. void TextureD3D9::commit(uint8_t _stage, uint32_t _flags, const float _palette[][4])
  2654. {
  2655. uint32_t flags = 0 == (BGFX_TEXTURE_INTERNAL_DEFAULT_SAMPLER & _flags)
  2656. ? _flags
  2657. : m_flags
  2658. ;
  2659. uint32_t index = (flags & BGFX_TEXTURE_BORDER_COLOR_MASK) >> BGFX_TEXTURE_BORDER_COLOR_SHIFT;
  2660. s_renderD3D9->setSamplerState(_stage, flags, _palette[index]);
  2661. IDirect3DDevice9* device = s_renderD3D9->m_device;
  2662. DX_CHECK(device->SetTexture(_stage, m_ptr) );
  2663. if (4 > _stage)
  2664. {
  2665. DX_CHECK(device->SetTexture(D3DVERTEXTEXTURESAMPLER0 + _stage, m_ptr) );
  2666. }
  2667. }
  2668. void TextureD3D9::resolve() const
  2669. {
  2670. if (NULL != m_surface
  2671. && NULL != m_ptr)
  2672. {
  2673. IDirect3DSurface9* surface = getSurface();
  2674. DX_CHECK(s_renderD3D9->m_device->StretchRect(m_surface
  2675. , NULL
  2676. , surface
  2677. , NULL
  2678. , D3DTEXF_LINEAR
  2679. ) );
  2680. DX_RELEASE(surface, 1);
  2681. if (1 < m_numMips)
  2682. {
  2683. m_ptr->GenerateMipSubLevels();
  2684. }
  2685. }
  2686. }
  2687. void TextureD3D9::preReset()
  2688. {
  2689. TextureFormat::Enum fmt = (TextureFormat::Enum)m_textureFormat;
  2690. if (TextureFormat::Unknown != fmt)
  2691. {
  2692. DX_RELEASE(m_ptr, 0);
  2693. DX_RELEASE(m_surface, 0);
  2694. }
  2695. }
  2696. void TextureD3D9::postReset()
  2697. {
  2698. TextureFormat::Enum fmt = (TextureFormat::Enum)m_textureFormat;
  2699. if (TextureFormat::Unknown != fmt)
  2700. {
  2701. switch (m_type)
  2702. {
  2703. default:
  2704. case Texture2D:
  2705. createTexture(m_width, m_height, m_numMips);
  2706. break;
  2707. case Texture3D:
  2708. createVolumeTexture(m_width, m_height, m_depth, m_numMips);
  2709. break;
  2710. case TextureCube:
  2711. createCubeTexture(m_width, m_numMips);
  2712. break;
  2713. }
  2714. }
  2715. }
  2716. void FrameBufferD3D9::create(uint8_t _num, const Attachment* _attachment)
  2717. {
  2718. for (uint32_t ii = 0; ii < BX_COUNTOF(m_surface); ++ii)
  2719. {
  2720. m_surface[ii] = NULL;
  2721. }
  2722. m_denseIdx = UINT16_MAX;
  2723. m_dsIdx = UINT8_MAX;
  2724. m_num = 0;
  2725. m_numTh = _num;
  2726. m_needResolve = false;
  2727. bx::memCopy(m_attachment, _attachment, _num*sizeof(Attachment) );
  2728. for (uint32_t ii = 0; ii < _num; ++ii)
  2729. {
  2730. TextureHandle handle = m_attachment[ii].handle;
  2731. if (isValid(handle) )
  2732. {
  2733. const TextureD3D9& texture = s_renderD3D9->m_textures[handle.idx];
  2734. if (NULL != texture.m_surface)
  2735. {
  2736. m_surface[ii] = texture.m_surface;
  2737. m_surface[ii]->AddRef();
  2738. }
  2739. else
  2740. {
  2741. m_surface[ii] = texture.getSurface(uint8_t(m_attachment[ii].layer), uint8_t(m_attachment[ii].mip) );
  2742. }
  2743. if (0 == m_num)
  2744. {
  2745. m_width = texture.m_width;
  2746. m_height = texture.m_height;
  2747. }
  2748. if (bimg::isDepth(bimg::TextureFormat::Enum(texture.m_textureFormat) ) )
  2749. {
  2750. m_dsIdx = uint8_t(ii);
  2751. }
  2752. else
  2753. {
  2754. ++m_num;
  2755. }
  2756. m_needResolve |= true
  2757. && (NULL != texture.m_surface)
  2758. && (NULL != texture.m_texture2d)
  2759. ;
  2760. }
  2761. }
  2762. if (0 == m_num)
  2763. {
  2764. createNullColorRT();
  2765. }
  2766. }
  2767. void FrameBufferD3D9::create(uint16_t _denseIdx, void* _nwh, uint32_t _width, uint32_t _height, TextureFormat::Enum _depthFormat)
  2768. {
  2769. BX_UNUSED(_depthFormat);
  2770. m_hwnd = (HWND)_nwh;
  2771. m_width = bx::uint32_max(_width, 16);
  2772. m_height = bx::uint32_max(_height, 16);
  2773. D3DPRESENT_PARAMETERS params;
  2774. bx::memCopy(&params, &s_renderD3D9->m_params, sizeof(D3DPRESENT_PARAMETERS) );
  2775. params.BackBufferWidth = m_width;
  2776. params.BackBufferHeight = m_height;
  2777. DX_CHECK(s_renderD3D9->m_device->CreateAdditionalSwapChain(&params, &m_swapChain) );
  2778. DX_CHECK(m_swapChain->GetBackBuffer(0, D3DBACKBUFFER_TYPE_MONO, &m_surface[0]) );
  2779. DX_CHECK(s_renderD3D9->m_device->CreateDepthStencilSurface(
  2780. params.BackBufferWidth
  2781. , params.BackBufferHeight
  2782. , params.AutoDepthStencilFormat
  2783. , params.MultiSampleType
  2784. , params.MultiSampleQuality
  2785. , FALSE
  2786. , &m_surface[1]
  2787. , NULL
  2788. ) );
  2789. m_dsIdx = 1;
  2790. m_denseIdx = _denseIdx;
  2791. m_num = 1;
  2792. m_needResolve = false;
  2793. m_needPresent = false;
  2794. }
  2795. uint16_t FrameBufferD3D9::destroy()
  2796. {
  2797. if (NULL != m_hwnd)
  2798. {
  2799. DX_RELEASE(m_surface[0], 0);
  2800. DX_RELEASE(m_surface[1], 0);
  2801. DX_RELEASE(m_swapChain, 0);
  2802. }
  2803. else
  2804. {
  2805. uint32_t num = m_numTh;
  2806. num += uint32_t(0 < m_numTh && 0 == m_num);
  2807. for (uint32_t ii = 0; ii < num; ++ii)
  2808. {
  2809. IDirect3DSurface9* ptr = m_surface[ii];
  2810. if (NULL != ptr)
  2811. {
  2812. ptr->Release();
  2813. m_surface[ii] = NULL;
  2814. }
  2815. }
  2816. }
  2817. m_hwnd = NULL;
  2818. m_num = 0;
  2819. m_numTh = 0;
  2820. m_needPresent = false;
  2821. uint16_t denseIdx = m_denseIdx;
  2822. m_denseIdx = UINT16_MAX;
  2823. return denseIdx;
  2824. }
  2825. HRESULT FrameBufferD3D9::present()
  2826. {
  2827. if (m_needPresent)
  2828. {
  2829. HRESULT hr = m_swapChain->Present(NULL, NULL, m_hwnd, NULL, 0);
  2830. m_needPresent = false;
  2831. return hr;
  2832. }
  2833. return S_OK;
  2834. }
  2835. void FrameBufferD3D9::resolve() const
  2836. {
  2837. if (m_needResolve)
  2838. {
  2839. for (uint32_t ii = 0, num = m_numTh; ii < num; ++ii)
  2840. {
  2841. const TextureD3D9& texture = s_renderD3D9->m_textures[m_attachment[ii].handle.idx];
  2842. texture.resolve();
  2843. }
  2844. }
  2845. }
  2846. void FrameBufferD3D9::preReset()
  2847. {
  2848. if (NULL != m_hwnd)
  2849. {
  2850. DX_RELEASE(m_surface[0], 0);
  2851. DX_RELEASE(m_surface[1], 0);
  2852. DX_RELEASE(m_swapChain, 0);
  2853. }
  2854. else
  2855. {
  2856. uint32_t num = m_numTh;
  2857. num += uint32_t(0 < m_numTh && 0 == m_num);
  2858. for (uint32_t ii = 0; ii < num; ++ii)
  2859. {
  2860. m_surface[ii]->Release();
  2861. m_surface[ii] = NULL;
  2862. }
  2863. }
  2864. }
  2865. void FrameBufferD3D9::postReset()
  2866. {
  2867. if (NULL != m_hwnd)
  2868. {
  2869. D3DPRESENT_PARAMETERS params;
  2870. bx::memCopy(&params, &s_renderD3D9->m_params, sizeof(D3DPRESENT_PARAMETERS) );
  2871. params.BackBufferWidth = m_width;
  2872. params.BackBufferHeight = m_height;
  2873. DX_CHECK(s_renderD3D9->m_device->CreateAdditionalSwapChain(&params, &m_swapChain) );
  2874. DX_CHECK(m_swapChain->GetBackBuffer(0, D3DBACKBUFFER_TYPE_MONO, &m_surface[0]) );
  2875. DX_CHECK(s_renderD3D9->m_device->CreateDepthStencilSurface(params.BackBufferWidth
  2876. , params.BackBufferHeight
  2877. , params.AutoDepthStencilFormat
  2878. , params.MultiSampleType
  2879. , params.MultiSampleQuality
  2880. , FALSE
  2881. , &m_surface[1]
  2882. , NULL
  2883. ) );
  2884. }
  2885. else if (0 < m_numTh)
  2886. {
  2887. for (uint32_t ii = 0, num = m_numTh; ii < num; ++ii)
  2888. {
  2889. TextureHandle th = m_attachment[ii].handle;
  2890. if (isValid(th) )
  2891. {
  2892. TextureD3D9& texture = s_renderD3D9->m_textures[th.idx];
  2893. if (NULL != texture.m_surface)
  2894. {
  2895. m_surface[ii] = texture.m_surface;
  2896. m_surface[ii]->AddRef();
  2897. }
  2898. else
  2899. {
  2900. m_surface[ii] = texture.getSurface(uint8_t(m_attachment[ii].layer), uint8_t(m_attachment[ii].mip) );
  2901. }
  2902. }
  2903. }
  2904. if (0 == m_num)
  2905. {
  2906. createNullColorRT();
  2907. }
  2908. }
  2909. }
  2910. void FrameBufferD3D9::createNullColorRT()
  2911. {
  2912. DX_CHECK(s_renderD3D9->m_device->CreateRenderTarget(
  2913. m_width
  2914. , m_height
  2915. , D3DFMT_NULL
  2916. , D3DMULTISAMPLE_NONE
  2917. , 0
  2918. , false
  2919. , &m_surface[1]
  2920. , NULL
  2921. ) );
  2922. }
  2923. void FrameBufferD3D9::set()
  2924. {
  2925. m_needPresent = UINT16_MAX != m_denseIdx;
  2926. // If frame buffer has only depth attachment D3DFMT_NULL
  2927. // render target is created.
  2928. const uint32_t fbnum = bx::uint32_max(2, m_numTh);
  2929. const uint8_t dsIdx = m_dsIdx;
  2930. IDirect3DDevice9* device = s_renderD3D9->m_device;
  2931. DX_CHECK(device->SetDepthStencilSurface(UINT8_MAX == dsIdx
  2932. ? s_renderD3D9->m_backBufferDepthStencil
  2933. : m_surface[dsIdx]
  2934. ) );
  2935. uint32_t rtIdx = 0;
  2936. for (uint32_t ii = 0; ii < fbnum; ++ii)
  2937. {
  2938. IDirect3DSurface9* surface = m_surface[ii];
  2939. if (ii != dsIdx)
  2940. {
  2941. DX_CHECK(device->SetRenderTarget(rtIdx, surface) );
  2942. ++rtIdx;
  2943. }
  2944. }
  2945. for (uint32_t ii = rtIdx, num = g_caps.limits.maxFBAttachments; ii < num; ++ii)
  2946. {
  2947. DX_CHECK(device->SetRenderTarget(ii, NULL) );
  2948. }
  2949. DX_CHECK(device->SetRenderState(D3DRS_SRGBWRITEENABLE, FALSE) );
  2950. }
  2951. void TimerQueryD3D9::postReset()
  2952. {
  2953. IDirect3DDevice9* device = s_renderD3D9->m_device;
  2954. for (uint32_t ii = 0; ii < BX_COUNTOF(m_query); ++ii)
  2955. {
  2956. Query& frame = m_query[ii];
  2957. DX_CHECK(device->CreateQuery(D3DQUERYTYPE_TIMESTAMPDISJOINT, &frame.m_disjoint) );
  2958. DX_CHECK(device->CreateQuery(D3DQUERYTYPE_TIMESTAMP, &frame.m_begin) );
  2959. DX_CHECK(device->CreateQuery(D3DQUERYTYPE_TIMESTAMP, &frame.m_end) );
  2960. DX_CHECK(device->CreateQuery(D3DQUERYTYPE_TIMESTAMPFREQ, &frame.m_freq) );
  2961. }
  2962. for (uint32_t ii = 0; ii < BX_COUNTOF(m_result); ++ii)
  2963. {
  2964. Result& result = m_result[ii];
  2965. result.reset();
  2966. }
  2967. m_control.reset();
  2968. }
  2969. void TimerQueryD3D9::preReset()
  2970. {
  2971. for (uint32_t ii = 0; ii < BX_COUNTOF(m_query); ++ii)
  2972. {
  2973. Query& frame = m_query[ii];
  2974. DX_RELEASE(frame.m_disjoint, 0);
  2975. DX_RELEASE(frame.m_begin, 0);
  2976. DX_RELEASE(frame.m_end, 0);
  2977. DX_RELEASE(frame.m_freq, 0);
  2978. }
  2979. }
  2980. uint32_t TimerQueryD3D9::begin(uint32_t _resultIdx)
  2981. {
  2982. while (0 == m_control.reserve(1) )
  2983. {
  2984. update();
  2985. }
  2986. Result& result = m_result[_resultIdx];
  2987. ++result.m_pending;
  2988. const uint32_t idx = m_control.m_current;
  2989. Query& query = m_query[idx];
  2990. query.m_resultIdx = _resultIdx;
  2991. query.m_ready = false;
  2992. query.m_disjoint->Issue(D3DISSUE_BEGIN);
  2993. query.m_begin->Issue(D3DISSUE_END);
  2994. m_control.commit(1);
  2995. return idx;
  2996. }
  2997. void TimerQueryD3D9::end(uint32_t _idx)
  2998. {
  2999. Query& query = m_query[_idx];
  3000. query.m_ready = true;
  3001. query.m_disjoint->Issue(D3DISSUE_END);
  3002. query.m_freq->Issue(D3DISSUE_END);
  3003. query.m_end->Issue(D3DISSUE_END);
  3004. while (update() )
  3005. {
  3006. }
  3007. }
  3008. bool TimerQueryD3D9::update()
  3009. {
  3010. if (0 != m_control.available() )
  3011. {
  3012. Query& query = m_query[m_control.m_read];
  3013. if (!query.m_ready)
  3014. {
  3015. return false;
  3016. }
  3017. uint64_t timeEnd;
  3018. const bool flush = BX_COUNTOF(m_query)-1 == m_control.available();
  3019. HRESULT hr = query.m_end->GetData(&timeEnd, sizeof(timeEnd), flush ? D3DGETDATA_FLUSH : 0);
  3020. if (S_OK == hr
  3021. || isLost(hr) )
  3022. {
  3023. m_control.consume(1);
  3024. uint64_t timeBegin;
  3025. DX_CHECK(query.m_begin->GetData(&timeBegin, sizeof(timeBegin), 0) );
  3026. uint64_t freq;
  3027. DX_CHECK(query.m_freq->GetData(&freq, sizeof(freq), 0) );
  3028. Result& result = m_result[query.m_resultIdx];
  3029. --result.m_pending;
  3030. result.m_frequency = freq;
  3031. result.m_begin = timeBegin;
  3032. result.m_end = timeEnd;
  3033. return true;
  3034. }
  3035. }
  3036. return false;
  3037. }
  3038. void OcclusionQueryD3D9::postReset()
  3039. {
  3040. IDirect3DDevice9* device = s_renderD3D9->m_device;
  3041. for (uint32_t ii = 0; ii < BX_COUNTOF(m_query); ++ii)
  3042. {
  3043. Query& query = m_query[ii];
  3044. DX_CHECK(device->CreateQuery(D3DQUERYTYPE_OCCLUSION, &query.m_ptr) );
  3045. }
  3046. }
  3047. void OcclusionQueryD3D9::preReset()
  3048. {
  3049. for (uint32_t ii = 0; ii < BX_COUNTOF(m_query); ++ii)
  3050. {
  3051. Query& query = m_query[ii];
  3052. DX_RELEASE(query.m_ptr, 0);
  3053. }
  3054. }
  3055. void OcclusionQueryD3D9::begin(Frame* _render, OcclusionQueryHandle _handle)
  3056. {
  3057. while (0 == m_control.reserve(1) )
  3058. {
  3059. resolve(_render, true);
  3060. }
  3061. Query& query = m_query[m_control.m_current];
  3062. query.m_ptr->Issue(D3DISSUE_BEGIN);
  3063. query.m_handle = _handle;
  3064. }
  3065. void OcclusionQueryD3D9::end()
  3066. {
  3067. Query& query = m_query[m_control.m_current];
  3068. query.m_ptr->Issue(D3DISSUE_END);
  3069. m_control.commit(1);
  3070. }
  3071. void OcclusionQueryD3D9::resolve(Frame* _render, bool)
  3072. {
  3073. while (0 != m_control.available() )
  3074. {
  3075. Query& query = m_query[m_control.m_read];
  3076. if (isValid(query.m_handle) )
  3077. {
  3078. uint32_t result;
  3079. HRESULT hr = query.m_ptr->GetData(&result, sizeof(result), 0);
  3080. if (S_FALSE == hr)
  3081. {
  3082. break;
  3083. }
  3084. _render->m_occlusion[query.m_handle.idx] = int32_t(result);
  3085. }
  3086. m_control.consume(1);
  3087. }
  3088. }
  3089. void OcclusionQueryD3D9::invalidate(OcclusionQueryHandle _handle)
  3090. {
  3091. const uint32_t size = m_control.m_size;
  3092. for (uint32_t ii = 0, num = m_control.available(); ii < num; ++ii)
  3093. {
  3094. Query& query = m_query[(m_control.m_read + ii) % size];
  3095. if (query.m_handle.idx == _handle.idx)
  3096. {
  3097. query.m_handle.idx = bgfx::kInvalidHandle;
  3098. }
  3099. }
  3100. }
  3101. void RendererContextD3D9::submitBlit(BlitState& _bs, uint16_t _view)
  3102. {
  3103. while (_bs.hasItem(_view) )
  3104. {
  3105. const BlitItem& blit = _bs.advance();
  3106. const TextureD3D9& src = m_textures[blit.m_src.idx];
  3107. const TextureD3D9& dst = m_textures[blit.m_dst.idx];
  3108. uint32_t srcWidth = bx::uint32_min(src.m_width, blit.m_srcX + blit.m_width) - blit.m_srcX;
  3109. uint32_t srcHeight = bx::uint32_min(src.m_height, blit.m_srcY + blit.m_height) - blit.m_srcY;
  3110. uint32_t dstWidth = bx::uint32_min(dst.m_width, blit.m_dstX + blit.m_width) - blit.m_dstX;
  3111. uint32_t dstHeight = bx::uint32_min(dst.m_height, blit.m_dstY + blit.m_height) - blit.m_dstY;
  3112. uint32_t width = bx::uint32_min(srcWidth, dstWidth);
  3113. uint32_t height = bx::uint32_min(srcHeight, dstHeight);
  3114. RECT srcRect = { LONG(blit.m_srcX), LONG(blit.m_srcY), LONG(blit.m_srcX + width), LONG(blit.m_srcY + height) };
  3115. RECT dstRect = { LONG(blit.m_dstX), LONG(blit.m_dstY), LONG(blit.m_dstX + width), LONG(blit.m_dstY + height) };
  3116. IDirect3DSurface9* srcSurface = src.getSurface(uint8_t(blit.m_srcZ), blit.m_srcMip);
  3117. IDirect3DSurface9* dstSurface = dst.getSurface(uint8_t(blit.m_dstZ), blit.m_dstMip);
  3118. // UpdateSurface (pool src: SYSTEMMEM, dst: DEFAULT)
  3119. // s/d T RTT RT
  3120. // T y y y
  3121. // RTT - - -
  3122. // RT - - -
  3123. //
  3124. // StretchRect (pool src and dst must be DEFAULT)
  3125. // s/d T RTT RT
  3126. // T - y y
  3127. // RTT - y y
  3128. // RT - y y
  3129. //
  3130. // GetRenderTargetData (dst must be SYSTEMMEM)
  3131. bool depth = bimg::isDepth(bimg::TextureFormat::Enum(src.m_textureFormat) );
  3132. HRESULT hr = m_device->StretchRect(srcSurface
  3133. , depth ? NULL : &srcRect
  3134. , dstSurface
  3135. , depth ? NULL : &dstRect
  3136. , D3DTEXF_NONE
  3137. );
  3138. if (FAILED(hr) )
  3139. {
  3140. hr = m_device->GetRenderTargetData(srcSurface, dstSurface);
  3141. BX_WARN(SUCCEEDED(hr), "StretchRect and GetRenderTargetData failed %x.", hr);
  3142. }
  3143. srcSurface->Release();
  3144. dstSurface->Release();
  3145. }
  3146. }
  3147. void RendererContextD3D9::submit(Frame* _render, ClearQuad& _clearQuad, TextVideoMemBlitter& _textVideoMemBlitter)
  3148. {
  3149. IDirect3DDevice9* device = m_device;
  3150. PIX_BEGINEVENT(D3DCOLOR_FRAME, L"rendererSubmit");
  3151. updateResolution(_render->m_resolution);
  3152. int64_t timeBegin = bx::getHPCounter();
  3153. int64_t captureElapsed = 0;
  3154. uint32_t frameQueryIdx = UINT32_MAX;
  3155. device->BeginScene();
  3156. if (m_timerQuerySupport)
  3157. {
  3158. frameQueryIdx = m_gpuTimer.begin(BGFX_CONFIG_MAX_VIEWS);
  3159. }
  3160. if (0 < _render->m_iboffset)
  3161. {
  3162. TransientIndexBuffer* ib = _render->m_transientIb;
  3163. m_indexBuffers[ib->handle.idx].update(0, _render->m_iboffset, ib->data, true);
  3164. }
  3165. if (0 < _render->m_vboffset)
  3166. {
  3167. TransientVertexBuffer* vb = _render->m_transientVb;
  3168. m_vertexBuffers[vb->handle.idx].update(0, _render->m_vboffset, vb->data, true);
  3169. }
  3170. _render->sort();
  3171. RenderDraw currentState;
  3172. currentState.clear();
  3173. currentState.m_stateFlags = BGFX_STATE_NONE;
  3174. currentState.m_stencil = packStencil(BGFX_STENCIL_NONE, BGFX_STENCIL_NONE);
  3175. RenderBind currentBind;
  3176. currentBind.clear();
  3177. ViewState viewState(_render, false);
  3178. DX_CHECK(device->SetRenderState(D3DRS_FILLMODE, _render->m_debug&BGFX_DEBUG_WIREFRAME ? D3DFILL_WIREFRAME : D3DFILL_SOLID) );
  3179. uint16_t programIdx = kInvalidHandle;
  3180. SortKey key;
  3181. uint16_t view = UINT16_MAX;
  3182. FrameBufferHandle fbh = { BGFX_CONFIG_MAX_FRAME_BUFFERS };
  3183. uint32_t blendFactor = 0;
  3184. BlitState bs(_render);
  3185. uint8_t primIndex;
  3186. {
  3187. const uint64_t pt = _render->m_debug&BGFX_DEBUG_WIREFRAME ? BGFX_STATE_PT_LINES : 0;
  3188. primIndex = uint8_t(pt>>BGFX_STATE_PT_SHIFT);
  3189. }
  3190. PrimInfo prim = s_primInfo[primIndex];
  3191. bool viewHasScissor = false;
  3192. Rect viewScissorRect;
  3193. viewScissorRect.clear();
  3194. uint32_t statsNumPrimsSubmitted[BX_COUNTOF(s_primInfo)] = {};
  3195. uint32_t statsNumPrimsRendered[BX_COUNTOF(s_primInfo)] = {};
  3196. uint32_t statsNumInstances[BX_COUNTOF(s_primInfo)] = {};
  3197. uint32_t statsNumIndices = 0;
  3198. uint32_t statsKeyType[2] = {};
  3199. invalidateSamplerState();
  3200. Profiler<TimerQueryD3D9> profiler(
  3201. _render
  3202. , m_gpuTimer
  3203. , s_viewName
  3204. , m_timerQuerySupport
  3205. );
  3206. if (m_occlusionQuerySupport)
  3207. {
  3208. m_occlusionQuery.resolve(_render);
  3209. }
  3210. if (0 == (_render->m_debug&BGFX_DEBUG_IFH) )
  3211. {
  3212. for (uint32_t item = 0, numItems = _render->m_numRenderItems; item < numItems; ++item)
  3213. {
  3214. const uint64_t encodedKey = _render->m_sortKeys[item];
  3215. const bool isCompute = key.decode(encodedKey, _render->m_viewRemap);
  3216. statsKeyType[isCompute]++;
  3217. if (isCompute)
  3218. {
  3219. BX_CHECK(false, "Compute is not supported on DirectX 9.");
  3220. continue;
  3221. }
  3222. const uint32_t itemIdx = _render->m_sortValues[item];
  3223. const RenderDraw& draw = _render->m_renderItem[itemIdx].draw;
  3224. const RenderBind& renderBind = _render->m_renderItemBind[itemIdx];
  3225. const bool hasOcclusionQuery = 0 != (draw.m_stateFlags & BGFX_STATE_INTERNAL_OCCLUSION_QUERY);
  3226. if (isValid(draw.m_occlusionQuery)
  3227. && !hasOcclusionQuery
  3228. && !isVisible(_render, draw.m_occlusionQuery, 0 != (draw.m_submitFlags&BGFX_SUBMIT_INTERNAL_OCCLUSION_VISIBLE) ) )
  3229. {
  3230. continue;
  3231. }
  3232. const uint64_t newFlags = draw.m_stateFlags;
  3233. uint64_t changedFlags = currentState.m_stateFlags ^ draw.m_stateFlags;
  3234. currentState.m_stateFlags = newFlags;
  3235. const uint64_t newStencil = draw.m_stencil;
  3236. uint64_t changedStencil = currentState.m_stencil ^ draw.m_stencil;
  3237. currentState.m_stencil = newStencil;
  3238. if (key.m_view != view)
  3239. {
  3240. currentState.clear();
  3241. currentState.m_scissor = !draw.m_scissor;
  3242. changedFlags = BGFX_STATE_MASK;
  3243. changedStencil = packStencil(BGFX_STENCIL_MASK, BGFX_STENCIL_MASK);
  3244. currentState.m_stateFlags = newFlags;
  3245. currentState.m_stencil = newStencil;
  3246. view = key.m_view;
  3247. programIdx = kInvalidHandle;
  3248. if (_render->m_fb[view].idx != fbh.idx)
  3249. {
  3250. fbh = _render->m_fb[view];
  3251. setFrameBuffer(fbh);
  3252. }
  3253. PIX_ENDEVENT();
  3254. if (item > 0)
  3255. {
  3256. profiler.end();
  3257. }
  3258. profiler.begin(view);
  3259. PIX_BEGINEVENT(D3DCOLOR_VIEW, s_viewNameW[view]);
  3260. viewState.m_rect = _render->m_rect[view];
  3261. const Rect& scissorRect = _render->m_scissor[view];
  3262. viewHasScissor = !scissorRect.isZero();
  3263. viewScissorRect = viewHasScissor ? scissorRect : viewState.m_rect;
  3264. D3DVIEWPORT9 vp;
  3265. vp.X = viewState.m_rect.m_x;
  3266. vp.Y = viewState.m_rect.m_y;
  3267. vp.Width = viewState.m_rect.m_width;
  3268. vp.Height = viewState.m_rect.m_height;
  3269. vp.MinZ = 0.0f;
  3270. vp.MaxZ = 1.0f;
  3271. DX_CHECK(device->SetViewport(&vp) );
  3272. Clear& clear = _render->m_clear[view];
  3273. if (BGFX_CLEAR_NONE != (clear.m_flags & BGFX_CLEAR_MASK) )
  3274. {
  3275. clearQuad(_clearQuad, viewState.m_rect, clear, _render->m_colorPalette);
  3276. }
  3277. DX_CHECK(device->SetRenderState(D3DRS_STENCILENABLE, FALSE) );
  3278. DX_CHECK(device->SetRenderState(D3DRS_ZENABLE, TRUE) );
  3279. DX_CHECK(device->SetRenderState(D3DRS_ZFUNC, D3DCMP_LESS) );
  3280. DX_CHECK(device->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE) );
  3281. DX_CHECK(device->SetRenderState(D3DRS_ALPHABLENDENABLE, FALSE) );
  3282. DX_CHECK(device->SetRenderState(D3DRS_ALPHAFUNC, D3DCMP_GREATER) );
  3283. submitBlit(bs, view);
  3284. }
  3285. uint16_t scissor = draw.m_scissor;
  3286. if (currentState.m_scissor != scissor)
  3287. {
  3288. currentState.m_scissor = scissor;
  3289. if (UINT16_MAX == scissor)
  3290. {
  3291. DX_CHECK(device->SetRenderState(D3DRS_SCISSORTESTENABLE, viewHasScissor) );
  3292. if (viewHasScissor)
  3293. {
  3294. RECT rc;
  3295. rc.left = viewScissorRect.m_x;
  3296. rc.top = viewScissorRect.m_y;
  3297. rc.right = viewScissorRect.m_x + viewScissorRect.m_width;
  3298. rc.bottom = viewScissorRect.m_y + viewScissorRect.m_height;
  3299. DX_CHECK(device->SetScissorRect(&rc) );
  3300. }
  3301. }
  3302. else
  3303. {
  3304. Rect scissorRect;
  3305. scissorRect.setIntersect(viewScissorRect, _render->m_rectCache.m_cache[scissor]);
  3306. if (scissorRect.isZeroArea() )
  3307. {
  3308. continue;
  3309. }
  3310. DX_CHECK(device->SetRenderState(D3DRS_SCISSORTESTENABLE, true) );
  3311. RECT rc;
  3312. rc.left = scissorRect.m_x;
  3313. rc.top = scissorRect.m_y;
  3314. rc.right = scissorRect.m_x + scissorRect.m_width;
  3315. rc.bottom = scissorRect.m_y + scissorRect.m_height;
  3316. DX_CHECK(device->SetScissorRect(&rc) );
  3317. }
  3318. }
  3319. if (0 != changedStencil)
  3320. {
  3321. bool enable = 0 != newStencil;
  3322. DX_CHECK(device->SetRenderState(D3DRS_STENCILENABLE, enable) );
  3323. if (0 != newStencil)
  3324. {
  3325. uint32_t fstencil = unpackStencil(0, newStencil);
  3326. uint32_t bstencil = unpackStencil(1, newStencil);
  3327. uint8_t frontAndBack = bstencil != BGFX_STENCIL_NONE && bstencil != fstencil;
  3328. DX_CHECK(device->SetRenderState(D3DRS_TWOSIDEDSTENCILMODE, 0 != frontAndBack) );
  3329. uint32_t fchanged = unpackStencil(0, changedStencil);
  3330. if ( (BGFX_STENCIL_FUNC_REF_MASK|BGFX_STENCIL_FUNC_RMASK_MASK) & fchanged)
  3331. {
  3332. uint32_t ref = (fstencil&BGFX_STENCIL_FUNC_REF_MASK)>>BGFX_STENCIL_FUNC_REF_SHIFT;
  3333. DX_CHECK(device->SetRenderState(D3DRS_STENCILREF, ref) );
  3334. uint32_t rmask = (fstencil&BGFX_STENCIL_FUNC_RMASK_MASK)>>BGFX_STENCIL_FUNC_RMASK_SHIFT;
  3335. DX_CHECK(device->SetRenderState(D3DRS_STENCILMASK, rmask) );
  3336. }
  3337. // uint32_t bchanged = unpackStencil(1, changedStencil);
  3338. // if (BGFX_STENCIL_FUNC_RMASK_MASK & bchanged)
  3339. // {
  3340. // uint32_t wmask = (bstencil&BGFX_STENCIL_FUNC_RMASK_MASK)>>BGFX_STENCIL_FUNC_RMASK_SHIFT;
  3341. // DX_CHECK(device->SetRenderState(D3DRS_STENCILWRITEMASK, wmask) );
  3342. // }
  3343. for (uint8_t ii = 0, num = frontAndBack+1; ii < num; ++ii)
  3344. {
  3345. uint32_t stencil = unpackStencil(ii, newStencil);
  3346. uint32_t changed = unpackStencil(ii, changedStencil);
  3347. if ( (BGFX_STENCIL_TEST_MASK|BGFX_STENCIL_FUNC_REF_MASK|BGFX_STENCIL_FUNC_RMASK_MASK) & changed)
  3348. {
  3349. uint32_t func = (stencil&BGFX_STENCIL_TEST_MASK)>>BGFX_STENCIL_TEST_SHIFT;
  3350. DX_CHECK(device->SetRenderState(s_stencilFuncRs[ii], s_cmpFunc[func]) );
  3351. }
  3352. if ( (BGFX_STENCIL_OP_FAIL_S_MASK|BGFX_STENCIL_OP_FAIL_Z_MASK|BGFX_STENCIL_OP_PASS_Z_MASK) & changed)
  3353. {
  3354. uint32_t sfail = (stencil&BGFX_STENCIL_OP_FAIL_S_MASK)>>BGFX_STENCIL_OP_FAIL_S_SHIFT;
  3355. DX_CHECK(device->SetRenderState(s_stencilFailRs[ii], s_stencilOp[sfail]) );
  3356. uint32_t zfail = (stencil&BGFX_STENCIL_OP_FAIL_Z_MASK)>>BGFX_STENCIL_OP_FAIL_Z_SHIFT;
  3357. DX_CHECK(device->SetRenderState(s_stencilZFailRs[ii], s_stencilOp[zfail]) );
  3358. uint32_t zpass = (stencil&BGFX_STENCIL_OP_PASS_Z_MASK)>>BGFX_STENCIL_OP_PASS_Z_SHIFT;
  3359. DX_CHECK(device->SetRenderState(s_stencilZPassRs[ii], s_stencilOp[zpass]) );
  3360. }
  3361. }
  3362. }
  3363. }
  3364. if ( (0
  3365. | BGFX_STATE_CULL_MASK
  3366. | BGFX_STATE_DEPTH_WRITE
  3367. | BGFX_STATE_DEPTH_TEST_MASK
  3368. | BGFX_STATE_RGB_WRITE
  3369. | BGFX_STATE_ALPHA_WRITE
  3370. | BGFX_STATE_BLEND_MASK
  3371. | BGFX_STATE_BLEND_EQUATION_MASK
  3372. | BGFX_STATE_ALPHA_REF_MASK
  3373. | BGFX_STATE_PT_MASK
  3374. | BGFX_STATE_POINT_SIZE_MASK
  3375. | BGFX_STATE_MSAA
  3376. ) & changedFlags)
  3377. {
  3378. if (BGFX_STATE_CULL_MASK & changedFlags)
  3379. {
  3380. uint32_t cull = (newFlags&BGFX_STATE_CULL_MASK)>>BGFX_STATE_CULL_SHIFT;
  3381. DX_CHECK(device->SetRenderState(D3DRS_CULLMODE, s_cullMode[cull]) );
  3382. }
  3383. if (BGFX_STATE_DEPTH_WRITE & changedFlags)
  3384. {
  3385. DX_CHECK(device->SetRenderState(D3DRS_ZWRITEENABLE, !!(BGFX_STATE_DEPTH_WRITE & newFlags) ) );
  3386. }
  3387. if (BGFX_STATE_DEPTH_TEST_MASK & changedFlags)
  3388. {
  3389. uint32_t func = (newFlags&BGFX_STATE_DEPTH_TEST_MASK)>>BGFX_STATE_DEPTH_TEST_SHIFT;
  3390. DX_CHECK(device->SetRenderState(D3DRS_ZENABLE, 0 != func) );
  3391. if (0 != func)
  3392. {
  3393. DX_CHECK(device->SetRenderState(D3DRS_ZFUNC, s_cmpFunc[func]) );
  3394. }
  3395. }
  3396. if (BGFX_STATE_ALPHA_REF_MASK & changedFlags)
  3397. {
  3398. uint32_t ref = (newFlags&BGFX_STATE_ALPHA_REF_MASK)>>BGFX_STATE_ALPHA_REF_SHIFT;
  3399. viewState.m_alphaRef = ref/255.0f;
  3400. }
  3401. if ( (BGFX_STATE_PT_POINTS|BGFX_STATE_POINT_SIZE_MASK) & changedFlags)
  3402. {
  3403. DX_CHECK(device->SetRenderState(D3DRS_POINTSIZE, castfu( (float)( (newFlags&BGFX_STATE_POINT_SIZE_MASK)>>BGFX_STATE_POINT_SIZE_SHIFT) ) ) );
  3404. }
  3405. if (BGFX_STATE_MSAA & changedFlags)
  3406. {
  3407. DX_CHECK(device->SetRenderState(D3DRS_MULTISAMPLEANTIALIAS, (newFlags&BGFX_STATE_MSAA) == BGFX_STATE_MSAA) );
  3408. }
  3409. if (BGFX_STATE_LINEAA & changedFlags)
  3410. {
  3411. DX_CHECK(m_device->SetRenderState(D3DRS_ANTIALIASEDLINEENABLE, !!(newFlags&BGFX_STATE_LINEAA) ) );
  3412. }
  3413. if ( (BGFX_STATE_ALPHA_WRITE|BGFX_STATE_RGB_WRITE) & changedFlags)
  3414. {
  3415. uint32_t writeEnable = (newFlags&BGFX_STATE_ALPHA_WRITE) ? D3DCOLORWRITEENABLE_ALPHA : 0;
  3416. writeEnable |= (newFlags&BGFX_STATE_RGB_WRITE) ? D3DCOLORWRITEENABLE_RED|D3DCOLORWRITEENABLE_GREEN|D3DCOLORWRITEENABLE_BLUE : 0;
  3417. DX_CHECK(device->SetRenderState(D3DRS_COLORWRITEENABLE, writeEnable) );
  3418. }
  3419. if ( ( (0
  3420. | BGFX_STATE_BLEND_MASK
  3421. | BGFX_STATE_BLEND_EQUATION_MASK
  3422. | BGFX_STATE_BLEND_ALPHA_TO_COVERAGE
  3423. ) & changedFlags)
  3424. || blendFactor != draw.m_rgba)
  3425. {
  3426. bool enabled = !!(BGFX_STATE_BLEND_MASK & newFlags);
  3427. DX_CHECK(device->SetRenderState(D3DRS_ALPHABLENDENABLE, enabled) );
  3428. if (m_atocSupport
  3429. && BGFX_STATE_BLEND_ALPHA_TO_COVERAGE & changedFlags)
  3430. {
  3431. DX_CHECK(m_device->SetRenderState(D3DRS_ADAPTIVETESS_Y
  3432. , !!(newFlags&BGFX_STATE_BLEND_ALPHA_TO_COVERAGE)
  3433. ? D3DFMT_ATOC
  3434. : 0
  3435. ) );
  3436. }
  3437. if (enabled)
  3438. {
  3439. const uint32_t blend = uint32_t( (newFlags&BGFX_STATE_BLEND_MASK)>>BGFX_STATE_BLEND_SHIFT);
  3440. const uint32_t equation = uint32_t( (newFlags&BGFX_STATE_BLEND_EQUATION_MASK)>>BGFX_STATE_BLEND_EQUATION_SHIFT);
  3441. const uint32_t srcRGB = (blend )&0xf;
  3442. const uint32_t dstRGB = (blend>> 4)&0xf;
  3443. const uint32_t srcA = (blend>> 8)&0xf;
  3444. const uint32_t dstA = (blend>>12)&0xf;
  3445. const uint32_t equRGB = (equation )&0x7;
  3446. const uint32_t equA = (equation>>3)&0x7;
  3447. DX_CHECK(device->SetRenderState(D3DRS_SRCBLEND, s_blendFactor[srcRGB].m_src) );
  3448. DX_CHECK(device->SetRenderState(D3DRS_DESTBLEND, s_blendFactor[dstRGB].m_dst) );
  3449. DX_CHECK(device->SetRenderState(D3DRS_BLENDOP, s_blendEquation[equRGB]) );
  3450. const bool separate = srcRGB != srcA || dstRGB != dstA || equRGB != equA;
  3451. DX_CHECK(device->SetRenderState(D3DRS_SEPARATEALPHABLENDENABLE, separate) );
  3452. if (separate)
  3453. {
  3454. DX_CHECK(device->SetRenderState(D3DRS_SRCBLENDALPHA, s_blendFactor[srcA].m_src) );
  3455. DX_CHECK(device->SetRenderState(D3DRS_DESTBLENDALPHA, s_blendFactor[dstA].m_dst) );
  3456. DX_CHECK(device->SetRenderState(D3DRS_BLENDOPALPHA, s_blendEquation[equA]) );
  3457. }
  3458. if ( (s_blendFactor[srcRGB].m_factor || s_blendFactor[dstRGB].m_factor)
  3459. && blendFactor != draw.m_rgba)
  3460. {
  3461. const uint32_t rgba = draw.m_rgba;
  3462. D3DCOLOR color = D3DCOLOR_RGBA(rgba>>24
  3463. , (rgba>>16)&0xff
  3464. , (rgba>> 8)&0xff
  3465. , (rgba )&0xff
  3466. );
  3467. DX_CHECK(device->SetRenderState(D3DRS_BLENDFACTOR, color) );
  3468. }
  3469. }
  3470. blendFactor = draw.m_rgba;
  3471. }
  3472. const uint64_t pt = _render->m_debug&BGFX_DEBUG_WIREFRAME ? BGFX_STATE_PT_LINES : newFlags&BGFX_STATE_PT_MASK;
  3473. primIndex = uint8_t(pt>>BGFX_STATE_PT_SHIFT);
  3474. prim = s_primInfo[primIndex];
  3475. }
  3476. bool programChanged = false;
  3477. bool constantsChanged = draw.m_constBegin < draw.m_constEnd;
  3478. rendererUpdateUniforms(this, _render->m_uniformBuffer, draw.m_constBegin, draw.m_constEnd);
  3479. if (key.m_program != programIdx)
  3480. {
  3481. programIdx = key.m_program;
  3482. if (kInvalidHandle == programIdx)
  3483. {
  3484. device->SetVertexShader(NULL);
  3485. device->SetPixelShader(NULL);
  3486. }
  3487. else
  3488. {
  3489. ProgramD3D9& program = m_program[programIdx];
  3490. device->SetVertexShader(program.m_vsh->m_vertexShader);
  3491. device->SetPixelShader(program.m_fsh->m_pixelShader);
  3492. }
  3493. programChanged =
  3494. constantsChanged = true;
  3495. }
  3496. if (kInvalidHandle != programIdx)
  3497. {
  3498. ProgramD3D9& program = m_program[programIdx];
  3499. if (constantsChanged)
  3500. {
  3501. UniformBuffer* vcb = program.m_vsh->m_constantBuffer;
  3502. if (NULL != vcb)
  3503. {
  3504. commit(*vcb);
  3505. }
  3506. UniformBuffer* fcb = program.m_fsh->m_constantBuffer;
  3507. if (NULL != fcb)
  3508. {
  3509. commit(*fcb);
  3510. }
  3511. }
  3512. viewState.setPredefined<4>(this, view, 0, program, _render, draw);
  3513. }
  3514. {
  3515. for (uint8_t stage = 0; stage < BGFX_CONFIG_MAX_TEXTURE_SAMPLERS; ++stage)
  3516. {
  3517. const Binding& bind = renderBind.m_bind[stage];
  3518. Binding& current = currentBind.m_bind[stage];
  3519. if (current.m_idx != bind.m_idx
  3520. || current.m_un.m_draw.m_textureFlags != bind.m_un.m_draw.m_textureFlags
  3521. || programChanged)
  3522. {
  3523. if (kInvalidHandle != bind.m_idx)
  3524. {
  3525. m_textures[bind.m_idx].commit(stage, bind.m_un.m_draw.m_textureFlags, _render->m_colorPalette);
  3526. }
  3527. else
  3528. {
  3529. DX_CHECK(device->SetTexture(stage, NULL) );
  3530. }
  3531. }
  3532. current = bind;
  3533. }
  3534. }
  3535. bool vertexStreamChanged = hasVertexStreamChanged(currentState, draw);
  3536. if (programChanged
  3537. || vertexStreamChanged)
  3538. {
  3539. currentState.m_streamMask = draw.m_streamMask;
  3540. currentState.m_instanceDataBuffer.idx = draw.m_instanceDataBuffer.idx;
  3541. currentState.m_instanceDataOffset = draw.m_instanceDataOffset;
  3542. currentState.m_instanceDataStride = draw.m_instanceDataStride;
  3543. const VertexDecl* decls[BGFX_CONFIG_MAX_VERTEX_STREAMS];
  3544. const bool instanced = true
  3545. && isValid(draw.m_instanceDataBuffer)
  3546. && m_instancingSupport
  3547. ;
  3548. const uint32_t freq = instanced
  3549. ? D3DSTREAMSOURCE_INDEXEDDATA|draw.m_numInstances
  3550. : 1
  3551. ;
  3552. uint32_t numVertices = draw.m_numVertices;
  3553. uint8_t numStreams = 0;
  3554. for (uint32_t idx = 0, streamMask = draw.m_streamMask, ntz = bx::uint32_cnttz(streamMask)
  3555. ; 0 != streamMask
  3556. ; streamMask >>= 1, idx += 1, ntz = bx::uint32_cnttz(streamMask), ++numStreams
  3557. )
  3558. {
  3559. streamMask >>= ntz;
  3560. idx += ntz;
  3561. currentState.m_stream[idx].m_decl = draw.m_stream[idx].m_decl;
  3562. currentState.m_stream[idx].m_handle = draw.m_stream[idx].m_handle;
  3563. currentState.m_stream[idx].m_startVertex = draw.m_stream[idx].m_startVertex;
  3564. const uint16_t handle = draw.m_stream[idx].m_handle.idx;
  3565. const VertexBufferD3D9& vb = m_vertexBuffers[handle];
  3566. const uint16_t decl = !isValid(vb.m_decl) ? draw.m_stream[idx].m_decl.idx : vb.m_decl.idx;
  3567. const VertexDecl& vertexDecl = m_vertexDecls[decl];
  3568. const uint32_t stride = vertexDecl.m_stride;
  3569. decls[numStreams] = &vertexDecl;
  3570. numVertices = bx::uint32_min(UINT32_MAX == draw.m_numVertices
  3571. ? vb.m_size/stride
  3572. : draw.m_numVertices
  3573. , numVertices
  3574. );
  3575. DX_CHECK(device->SetStreamSourceFreq(0, freq) );
  3576. DX_CHECK(device->SetStreamSource(numStreams, vb.m_ptr, 0, stride) );
  3577. }
  3578. currentState.m_numVertices = numVertices;
  3579. if (0 < numStreams)
  3580. {
  3581. if (instanced)
  3582. {
  3583. const VertexBufferD3D9& inst = m_vertexBuffers[draw.m_instanceDataBuffer.idx];
  3584. DX_CHECK(device->SetStreamSourceFreq(numStreams, UINT(D3DSTREAMSOURCE_INSTANCEDATA|1) ) );
  3585. DX_CHECK(device->SetStreamSource(numStreams, inst.m_ptr, draw.m_instanceDataOffset, draw.m_instanceDataStride) );
  3586. setInputLayout(numStreams, decls, draw.m_instanceDataStride/16);
  3587. }
  3588. else
  3589. {
  3590. DX_CHECK(device->SetStreamSource(numStreams, NULL, 0, 0) );
  3591. setInputLayout(numStreams, decls, 0);
  3592. }
  3593. }
  3594. else
  3595. {
  3596. DX_CHECK(device->SetStreamSource(0, NULL, 0, 0) );
  3597. DX_CHECK(device->SetStreamSource(1, NULL, 0, 0) );
  3598. }
  3599. }
  3600. if (currentState.m_indexBuffer.idx != draw.m_indexBuffer.idx)
  3601. {
  3602. currentState.m_indexBuffer = draw.m_indexBuffer;
  3603. uint16_t handle = draw.m_indexBuffer.idx;
  3604. if (kInvalidHandle != handle)
  3605. {
  3606. const IndexBufferD3D9& ib = m_indexBuffers[handle];
  3607. DX_CHECK(device->SetIndices(ib.m_ptr) );
  3608. }
  3609. else
  3610. {
  3611. DX_CHECK(device->SetIndices(NULL) );
  3612. }
  3613. }
  3614. if (0 != currentState.m_streamMask)
  3615. {
  3616. uint32_t numVertices = draw.m_numVertices;
  3617. uint32_t numIndices = 0;
  3618. uint32_t numPrimsSubmitted = 0;
  3619. uint32_t numInstances = 0;
  3620. uint32_t numPrimsRendered = 0;
  3621. if (hasOcclusionQuery)
  3622. {
  3623. m_occlusionQuery.begin(_render, draw.m_occlusionQuery);
  3624. }
  3625. if (isValid(draw.m_indexBuffer) )
  3626. {
  3627. if (UINT32_MAX == draw.m_numIndices)
  3628. {
  3629. const IndexBufferD3D9& ib = m_indexBuffers[draw.m_indexBuffer.idx];
  3630. const uint32_t indexSize = 0 == (ib.m_flags & BGFX_BUFFER_INDEX32) ? 2 : 4;
  3631. numIndices = ib.m_size/indexSize;
  3632. numPrimsSubmitted = numIndices/prim.m_div - prim.m_sub;
  3633. numInstances = draw.m_numInstances;
  3634. numPrimsRendered = numPrimsSubmitted*draw.m_numInstances;
  3635. DX_CHECK(device->DrawIndexedPrimitive(prim.m_type
  3636. , draw.m_stream[0].m_startVertex
  3637. , 0
  3638. , numVertices
  3639. , 0
  3640. , numPrimsSubmitted
  3641. ) );
  3642. }
  3643. else if (prim.m_min <= draw.m_numIndices)
  3644. {
  3645. numIndices = draw.m_numIndices;
  3646. numPrimsSubmitted = numIndices/prim.m_div - prim.m_sub;
  3647. numInstances = draw.m_numInstances;
  3648. numPrimsRendered = numPrimsSubmitted*draw.m_numInstances;
  3649. DX_CHECK(device->DrawIndexedPrimitive(prim.m_type
  3650. , draw.m_stream[0].m_startVertex
  3651. , 0
  3652. , numVertices
  3653. , draw.m_startIndex
  3654. , numPrimsSubmitted
  3655. ) );
  3656. }
  3657. }
  3658. else
  3659. {
  3660. numPrimsSubmitted = numVertices/prim.m_div - prim.m_sub;
  3661. numInstances = draw.m_numInstances;
  3662. numPrimsRendered = numPrimsSubmitted*draw.m_numInstances;
  3663. DX_CHECK(device->DrawPrimitive(prim.m_type
  3664. , draw.m_stream[0].m_startVertex
  3665. , numPrimsSubmitted
  3666. ) );
  3667. }
  3668. if (hasOcclusionQuery)
  3669. {
  3670. m_occlusionQuery.end();
  3671. }
  3672. statsNumPrimsSubmitted[primIndex] += numPrimsSubmitted;
  3673. statsNumPrimsRendered[primIndex] += numPrimsRendered;
  3674. statsNumInstances[primIndex] += numInstances;
  3675. statsNumIndices += numIndices;
  3676. }
  3677. }
  3678. submitBlit(bs, BGFX_CONFIG_MAX_VIEWS);
  3679. if (0 < _render->m_numRenderItems)
  3680. {
  3681. if (0 != (m_resolution.m_flags & BGFX_RESET_FLUSH_AFTER_RENDER) )
  3682. {
  3683. flush();
  3684. }
  3685. captureElapsed = -bx::getHPCounter();
  3686. capture();
  3687. captureElapsed += bx::getHPCounter();
  3688. profiler.end();
  3689. }
  3690. }
  3691. PIX_ENDEVENT();
  3692. int64_t timeEnd = bx::getHPCounter();
  3693. int64_t frameTime = timeEnd - timeBegin;
  3694. static int64_t min = frameTime;
  3695. static int64_t max = frameTime;
  3696. min = min > frameTime ? frameTime : min;
  3697. max = max < frameTime ? frameTime : max;
  3698. static uint32_t maxGpuLatency = 0;
  3699. static double maxGpuElapsed = 0.0f;
  3700. double elapsedGpuMs = 0.0;
  3701. if (UINT32_MAX != frameQueryIdx)
  3702. {
  3703. m_gpuTimer.end(frameQueryIdx);
  3704. const TimerQueryD3D9::Result& result = m_gpuTimer.m_result[BGFX_CONFIG_MAX_VIEWS];
  3705. double toGpuMs = 1000.0 / double(result.m_frequency);
  3706. elapsedGpuMs = (result.m_end - result.m_begin) * toGpuMs;
  3707. maxGpuElapsed = elapsedGpuMs > maxGpuElapsed ? elapsedGpuMs : maxGpuElapsed;
  3708. maxGpuLatency = bx::uint32_imax(maxGpuLatency, result.m_pending-1);
  3709. }
  3710. const int64_t timerFreq = bx::getHPFrequency();
  3711. Stats& perfStats = _render->m_perfStats;
  3712. perfStats.cpuTimeBegin = timeBegin;
  3713. perfStats.cpuTimeEnd = timeEnd;
  3714. perfStats.cpuTimerFreq = timerFreq;
  3715. const TimerQueryD3D9::Result& result = m_gpuTimer.m_result[BGFX_CONFIG_MAX_VIEWS];
  3716. perfStats.gpuTimeBegin = result.m_begin;
  3717. perfStats.gpuTimeEnd = result.m_end;
  3718. perfStats.gpuTimerFreq = result.m_frequency;
  3719. perfStats.numDraw = statsKeyType[0];
  3720. perfStats.numCompute = statsKeyType[1];
  3721. perfStats.maxGpuLatency = maxGpuLatency;
  3722. m_nvapi.getMemoryInfo(perfStats.gpuMemoryUsed, perfStats.gpuMemoryMax);
  3723. if (_render->m_debug & (BGFX_DEBUG_IFH|BGFX_DEBUG_STATS) )
  3724. {
  3725. PIX_BEGINEVENT(D3DCOLOR_FRAME, L"debugstats");
  3726. m_needPresent = true;
  3727. TextVideoMem& tvm = m_textVideoMem;
  3728. static int64_t next = timeEnd;
  3729. if (timeEnd >= next)
  3730. {
  3731. next = timeEnd + timerFreq;
  3732. double freq = double(timerFreq);
  3733. double toMs = 1000.0/freq;
  3734. tvm.clear();
  3735. uint16_t pos = 0;
  3736. tvm.printf(0, pos++, BGFX_CONFIG_DEBUG ? 0x89 : 0x8f, " %s / " BX_COMPILER_NAME " / " BX_CPU_NAME " / " BX_ARCH_NAME " / " BX_PLATFORM_NAME " "
  3737. , getRendererName()
  3738. );
  3739. const D3DADAPTER_IDENTIFIER9& identifier = m_identifier;
  3740. tvm.printf(0, pos++, 0x8f, " Device: %s (%s)", identifier.Description, identifier.Driver);
  3741. char processMemoryUsed[16];
  3742. bx::prettify(processMemoryUsed, BX_COUNTOF(processMemoryUsed), bx::getProcessMemoryUsed() );
  3743. tvm.printf(0, pos++, 0x8f, " Memory: %s (process) ", processMemoryUsed);
  3744. pos = 10;
  3745. tvm.printf(10, pos++, 0x8e, " Frame: %7.3f, % 7.3f \x1f, % 7.3f \x1e [ms] / % 6.2f FPS "
  3746. , double(frameTime)*toMs
  3747. , double(min)*toMs
  3748. , double(max)*toMs
  3749. , freq/frameTime
  3750. );
  3751. const uint32_t msaa = (m_resolution.m_flags&BGFX_RESET_MSAA_MASK)>>BGFX_RESET_MSAA_SHIFT;
  3752. tvm.printf(10, pos++, 0x8e, " Reset flags: [%c] vsync, [%c] MSAAx%d, [%c] MaxAnisotropy "
  3753. , !!(m_resolution.m_flags&BGFX_RESET_VSYNC) ? '\xfe' : ' '
  3754. , 0 != msaa ? '\xfe' : ' '
  3755. , 1<<msaa
  3756. , !!(m_resolution.m_flags&BGFX_RESET_MAXANISOTROPY) ? '\xfe' : ' '
  3757. );
  3758. double elapsedCpuMs = double(frameTime)*toMs;
  3759. tvm.printf(10, pos++, 0x8e, " Submitted: %5d (draw %5d, compute %4d) / CPU %7.4f [ms] %c GPU %7.4f [ms] (latency %d)"
  3760. , _render->m_numRenderItems
  3761. , statsKeyType[0]
  3762. , statsKeyType[1]
  3763. , elapsedCpuMs
  3764. , elapsedCpuMs > maxGpuElapsed ? '>' : '<'
  3765. , maxGpuElapsed
  3766. , maxGpuLatency
  3767. );
  3768. maxGpuLatency = 0;
  3769. maxGpuElapsed = 0.0;
  3770. for (uint32_t ii = 0; ii < BX_COUNTOF(s_primName); ++ii)
  3771. {
  3772. tvm.printf(10, pos++, 0x8e, " %10s: %7d (#inst: %5d), submitted: %7d"
  3773. , s_primName[ii]
  3774. , statsNumPrimsRendered[ii]
  3775. , statsNumInstances[ii]
  3776. , statsNumPrimsSubmitted[ii]
  3777. );
  3778. }
  3779. tvm.printf(10, pos++, 0x8e, " Indices: %7d ", statsNumIndices);
  3780. tvm.printf(10, pos++, 0x8e, " Uniform size: %7d, Max: %7d ", _render->m_uniformEnd, _render->m_uniformMax);
  3781. tvm.printf(10, pos++, 0x8e, " DVB size: %7d ", _render->m_vboffset);
  3782. tvm.printf(10, pos++, 0x8e, " DIB size: %7d ", _render->m_iboffset);
  3783. pos++;
  3784. tvm.printf(10, pos++, 0x8e, " Occlusion queries: %3d ", m_occlusionQuery.m_control.available() );
  3785. pos++;
  3786. tvm.printf(10, pos++, 0x8e, " State cache: ");
  3787. tvm.printf(10, pos++, 0x8e, " Input ");
  3788. tvm.printf(10, pos++, 0x8e, " %6d "
  3789. , m_inputLayoutCache.getCount()
  3790. );
  3791. pos++;
  3792. double captureMs = double(captureElapsed)*toMs;
  3793. tvm.printf(10, pos++, 0x8e, " Capture: %7.4f [ms]", captureMs);
  3794. uint8_t attr[2] = { 0x89, 0x8a };
  3795. uint8_t attrIndex = _render->m_waitSubmit < _render->m_waitRender;
  3796. tvm.printf(10, pos++, attr[attrIndex&1], " Submit wait: %7.4f [ms]", _render->m_waitSubmit*toMs);
  3797. tvm.printf(10, pos++, attr[(attrIndex+1)&1], " Render wait: %7.4f [ms]", _render->m_waitRender*toMs);
  3798. min = frameTime;
  3799. max = frameTime;
  3800. }
  3801. blit(this, _textVideoMemBlitter, tvm);
  3802. PIX_ENDEVENT();
  3803. }
  3804. else if (_render->m_debug & BGFX_DEBUG_TEXT)
  3805. {
  3806. PIX_BEGINEVENT(D3DCOLOR_FRAME, L"debugtext");
  3807. blit(this, _textVideoMemBlitter, _render->m_textVideoMem);
  3808. PIX_ENDEVENT();
  3809. }
  3810. device->EndScene();
  3811. }
  3812. } /* namespace d3d9 */ } // namespace bgfx
  3813. #else
  3814. namespace bgfx { namespace d3d9
  3815. {
  3816. RendererContextI* rendererCreate()
  3817. {
  3818. return NULL;
  3819. }
  3820. void rendererDestroy()
  3821. {
  3822. }
  3823. } /* namespace d3d9 */ } // namespace bgfx
  3824. #endif // BGFX_CONFIG_RENDERER_DIRECT3D9