renderer_d3d9.cpp 119 KB

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