renderer_d3d9.cpp 124 KB

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