renderer_d3d9.cpp 124 KB

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