renderer_d3d9.cpp 125 KB

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