renderer_d3d9.cpp 103 KB

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