renderer_d3d9.cpp 120 KB

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