renderer_d3d9.cpp 120 KB

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