draw.rs 192 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328
  1. //! Draws on the host GPU (decision 0007, step 3). A list keeps the state
  2. //! the title sets for its draws (pipeline, descriptor heaps, root
  3. //! arguments, vertex and index buffers, targets); each draw then brings the
  4. //! host list up to date: the host pipeline and our root signature, the
  5. //! user data the translated shaders read, the host copies of the buffers
  6. //! and descriptors they read, and the states of the textures involved.
  7. //! State the host keeps across draws (viewports, scissors, blend factor,
  8. //! stencil reference, topology, targets) is set on the host list as the
  9. //! title sets it.
  10. use std::sync::atomic::{AtomicU64, Ordering};
  11. use victory_shader::resource::RootIndexedView;
  12. use victory_shader::{ResourceType, RootType, UsedResource};
  13. use crate::descriptor::View;
  14. use windows::Win32::Foundation::RECT;
  15. use windows::Win32::Graphics::Direct3D::D3D_PRIMITIVE_TOPOLOGY;
  16. use windows::Win32::Graphics::Direct3D12::*;
  17. use windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT;
  18. use windows::core::Interface;
  19. use crate::host::HostList;
  20. use crate::object::This;
  21. use crate::pipeline::host::HostPipeline;
  22. /// A root argument as the title set it.
  23. #[derive(Debug, Clone, Default)]
  24. enum Root {
  25. #[default]
  26. None,
  27. /// A descriptor table's first descriptor (an address in a heap).
  28. Table(u64),
  29. Constants(Vec<u32>),
  30. /// A root view's GPU address.
  31. View(u64),
  32. }
  33. #[repr(C)]
  34. #[derive(Debug, Clone, Copy, Default)]
  35. pub(crate) struct VertexView {
  36. address: u64,
  37. size: u32,
  38. stride: u32,
  39. }
  40. #[repr(C)]
  41. #[derive(Debug, Clone, Copy, Default)]
  42. pub(crate) struct IndexView {
  43. address: u64,
  44. size: u32,
  45. format: u32,
  46. }
  47. /// Host states of a depth target, and of a texture shaders read.
  48. const DEPTH_WRITE: u32 = 0x10;
  49. const DEPTH_READ: u32 = 0x20;
  50. const SHADER_RESOURCE: u32 = 0x40 | 0x80;
  51. thread_local! {
  52. /// While a draw is prepared (`State::bind`, then its targets' states):
  53. /// the depth target the draw only tests (0: none, or one it writes),
  54. /// and whether a view its shaders read is of that same texture.
  55. static TESTED_DEPTH: std::cell::Cell<(usize, bool)> =
  56. const { std::cell::Cell::new((0, false)) };
  57. /// While a stage's tables are walked (`State::tables`): whether that
  58. /// stage's shader can store to buffers (`Translated::stores`).
  59. static STORES: std::cell::Cell<bool> = const { std::cell::Cell::new(true) };
  60. /// While `State::early_textures` runs the texture pass: the
  61. /// milliseconds and the bytes that run may take, in place of the
  62. /// pass's own per frame.
  63. static PASS_BUDGET: std::cell::Cell<Option<(u64, u64)>> = const { std::cell::Cell::new(None) };
  64. }
  65. /// The milliseconds of every frame the pass that uploads textures picked
  66. /// by index takes before a shader that picks by index has asked for it
  67. /// (`VICTORY_EARLY_TEXTURES_MS`, 12; 0: never, as before), and the
  68. /// milliseconds it may take just before a draw of the title's decoration
  69. /// bake (`VICTORY_BAKE_TEXTURES_MS`, 1500; 0: nothing special).
  70. ///
  71. /// The pass ran only from the first world frame on, where it met some
  72. /// 24,000 slots at once and needed 60-80 frames for them. The title bakes
  73. /// its characters' skin and decorations into textures of its own while it
  74. /// loads, 159-1,165 frames before that (runs 156-174), with a pixel shader
  75. /// that picks its sources by index: whatever was not on the card then was
  76. /// baked as nothing, once, for the run. On the console a texture is there
  77. /// when its bytes are.
  78. fn early_budgets() -> (u64, u64) {
  79. static MS: std::sync::OnceLock<(u64, u64)> = std::sync::OnceLock::new();
  80. *MS.get_or_init(|| {
  81. let ms = |name: &str, default: u64| {
  82. std::env::var(name).ok().and_then(|v| v.trim().parse::<u64>().ok()).unwrap_or(default)
  83. };
  84. (ms("VICTORY_EARLY_TEXTURES_MS", 12), ms("VICTORY_BAKE_TEXTURES_MS", 1500))
  85. })
  86. }
  87. /// Whether a draw of the title's bake finds the textures it picks by index
  88. /// as title memory has them at that moment (`VICTORY_BAKE_EXACT=0`: as the
  89. /// pass leaves them, as before). The pass looks at a slot whose memory was
  90. /// written or mapped a frame or two later, by when the rest of it has
  91. /// landed, and at one uploaded whole a few frames later again, for a title
  92. /// that fills memory unnoticed: a bake in between took the bytes from before
  93. /// (another texture's), and what it bakes stays: coloured specks all over
  94. /// the waitress's face for the whole diner scene (run n01), none in other
  95. /// runs. So the pass ahead of a bake takes those slots too, and its uploads
  96. /// wait for title memory that is being remapped (`crate::texture` `BAKING`).
  97. fn bake_exact() -> bool {
  98. static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
  99. *ON.get_or_init(|| std::env::var_os("VICTORY_BAKE_EXACT").is_none_or(|v| v != "0"))
  100. }
  101. /// Whether a texture found changed with nothing to tell of it is looked at
  102. /// again in the next frame (`VICTORY_RECHECK_SOON=0`: after four, as
  103. /// before).
  104. fn recheck_soon() -> bool {
  105. static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
  106. *ON.get_or_init(|| std::env::var_os("VICTORY_RECHECK_SOON").is_none_or(|v| v != "0"))
  107. }
  108. /// Frames ahead the pass before a bake takes slots from that are due only
  109. /// then ([`bake_exact`]): those of notices (1 and 2), and the first looks
  110. /// again ([`RECHECK_FRAMES`]), these at the frame's first bake alone (a
  111. /// look reads 48 KiB, and a frame bakes up to sixteen times).
  112. const BAKE_AHEAD: [u64; 2] = [12, 2];
  113. /// What [`crate::descriptor::host::HostHeap::texture_news`] said when the
  114. /// pass before a bake last served all there was, plus one (0: it did not):
  115. /// until something is new, the next bakes of the frame need no pass.
  116. static BAKE_SERVED: AtomicU64 = AtomicU64::new(0);
  117. /// The pixel shaders of the title's decoration bake (the title:
  118. /// `PS_BakeDecorations_*`), by the first 16 hex digits of their hash as the
  119. /// frame listings print it. They draw into a 256x256 corner of 2048x2048
  120. /// targets and name no texture in a table.
  121. const BAKE_PIXEL_SHADERS: [&str; 4] =
  122. ["c0a7fe77b1862e10", "0d1575a396dfe513", "b7cfd8dda91ebb6b", "280967ad158cee0b"];
  123. /// Since the start: early runs of the texture pass, and those of them
  124. /// made for a bake draw.
  125. pub(crate) static EARLY_TEXTURE_PASSES: [AtomicU64; 2] = [AtomicU64::new(0), AtomicU64::new(0)];
  126. /// Whether a buffer range a shader names through an unordered access view
  127. /// is given to shaders as written (snapshot before the submission, compare
  128. /// and write back after) only if that shader's code can store to buffers.
  129. /// The title binds buffers its shaders only read through such views, and
  130. /// every range declared costs a snapshot and a compare of its bytes: 3.97
  131. /// GB a frame in 31 submissions, 0.49 s of snapshots and 0.28 s of
  132. /// comparing (run 28). On by default; `VICTORY_WRITE_SKIP=0` declares
  133. /// every such range, as before.
  134. fn write_skip() -> bool {
  135. static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
  136. *ON.get_or_init(|| std::env::var_os("VICTORY_WRITE_SKIP").is_none_or(|v| v != "0"))
  137. }
  138. /// A run of indirect records clamped in one pass ([`windows`]): the host
  139. /// copy they came from (its number), their kind and stride, the offset of
  140. /// the first in that copy, how many, and the list's scratch buffer that
  141. /// holds them clamped, record `i` at `i * step`.
  142. #[derive(Clone)]
  143. struct Window {
  144. copy: u64,
  145. kind: u32,
  146. stride: u32,
  147. /// How far apart the records are in the copy, and in the scratch
  148. /// buffer: what the title walks them by ([`windows`]).
  149. step: u32,
  150. base: u64,
  151. records: u32,
  152. scratch: ID3D12Resource,
  153. }
  154. /// The most records clamped in one pass ([`windows`]).
  155. const WINDOW_MOST: u64 = 64;
  156. /// Whether indirect draws that read record after record of one argument
  157. /// buffer are clamped a window at a time (`VICTORY_INDIRECT_WINDOW=1`; off
  158. /// by default).
  159. ///
  160. /// The title issues its mesh draws one record per call, each from the next
  161. /// slot of the same argument buffer: 3,460 a frame in gameplay, and before
  162. /// each our clamp ran as a compute dispatch of its own between two waits,
  163. /// so the card went from drawing to compute and back for every record. In
  164. /// the timing run of the lit scene (run 79) a shadow draw of next to
  165. /// nothing cost 14-16 microseconds, 4,126 records a frame.
  166. ///
  167. /// With the switch, when a draw asks for a record a short step after the
  168. /// one drawn before, the clamp takes that record and the ones that step
  169. /// apart after it (16, then twice as many each time, [`WINDOW_MOST`] at
  170. /// most, never past the buffer) into
  171. /// the list's scratch buffer in one pass, and the draws that follow read
  172. /// their record there with no pass of ours and no barrier (the scratch
  173. /// buffer stays readable as arguments until the next clamp), until one of
  174. /// these: a compute
  175. /// dispatch, a direct draw, an indirect call with a count buffer or more
  176. /// than one record, a draw whose shaders can store to buffers, a record
  177. /// outside the window, another host list.
  178. ///
  179. /// The step is the one the title is seen to take, not the stride its
  180. /// command signature names: it draws one record a call, for which the
  181. /// stride means nothing, and the title names 12 bytes (the three
  182. /// words of a mesh dispatch) for records it keeps 32 bytes apart (2,173 of
  183. /// a frame's 3,349 mesh records in run 87's listed frame; 283 are 16
  184. /// apart, which ends a window). Walked by the named stride the window
  185. /// never opened: run 87, with the switch, still clamped 5,068 records a
  186. /// frame one at a time.
  187. ///
  188. /// What it costs the guard against garbage records: nothing against a
  189. /// hang (every record is bounded as before and charged to the list's
  190. /// budget as before), but the budget is charged when a window is clamped,
  191. /// so also for records of the window's tail that are never drawn. Those
  192. /// hold garbage in this title (slots of all ones: run 93 spent lists'
  193. /// budgets on them and emptied the draws after), so in a window a record
  194. /// that asks for more than can run is left empty and charges nothing
  195. /// (`crate::indirect::bound_ahead`); a tail record that looks real is
  196. /// charged what it asks, a few thousand of 2^27. And arguments the title's CPU side changes are seen as
  197. /// before, at the next submission.
  198. fn windows() -> bool {
  199. static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
  200. *ON.get_or_init(|| std::env::var_os("VICTORY_INDIRECT_WINDOW").is_some_and(|v| v == "1"))
  201. }
  202. /// Whether indirect executions of one record are clamped in batches
  203. /// (`crate::indirect::batch`; `VICTORY_INDIRECT_BATCH=0`: each on its own,
  204. /// or in windows ([`windows`])).
  205. ///
  206. /// A frame of gameplay has 4,809 indirect executions (a capture: 3,523 mesh
  207. /// draws, 948 dispatches, 338 draws), and with the windows still 2,355
  208. /// clamps: each a dispatch between two full waits, with the scratch buffer
  209. /// moved twice. The replayed frame's 84.6 ms are 75.3 ms with the clamps in
  210. /// 133 passes, and 77.7 ms in the 980 of this.
  211. ///
  212. /// A batch is opened by the first execution after a point where arguments
  213. /// may have changed, and all executions up to the next such point read
  214. /// theirs from it, each exactly the record it asks for (windows guess which
  215. /// are next, and clamp what they do not know). Arguments in buffers change
  216. /// by dispatches and by draws whose shaders store to buffers; those end the
  217. /// batch, so the record an execution reads is clamped after all that was
  218. /// recorded before it, and the pass waits for all of it, exactly as the
  219. /// clamp of its own did. Between two executions of a batch is no wait of
  220. /// ours: there is nothing between them to wait for but draws that store to
  221. /// no buffer.
  222. ///
  223. /// `VICTORY_INDIRECT_BATCH=2`: a dispatch does not end the batch before the
  224. /// title waits for it (a barrier, or a pipeline sync) or draws: what a
  225. /// dispatch writes is not there for a later command without a wait, and
  226. /// dispatches the title runs side by side (its tile classes, up to 92 at a
  227. /// time) are not held up by waits of ours. Off: whether the title has ways
  228. /// to wait that do not pass through its lists' methods is not known.
  229. fn batches() -> u8 {
  230. static ON: std::sync::OnceLock<u8> = std::sync::OnceLock::new();
  231. *ON.get_or_init(|| match std::env::var("VICTORY_INDIRECT_BATCH").as_deref() {
  232. Ok("0") => 0,
  233. Ok("2") => 2,
  234. _ => 1,
  235. })
  236. }
  237. /// The records clamped by the pass opened last ([`batches`]).
  238. struct Batch {
  239. table: crate::indirect::batch::Table,
  240. scratch: ID3D12Resource,
  241. /// Dispatches since, which may have written arguments
  242. /// (`VICTORY_INDIRECT_BATCH=2`).
  243. wrote: bool,
  244. }
  245. /// The host copies arguments were read from last: what a batch opens with,
  246. /// as the executions after the first may read theirs from another one.
  247. static ARGUMENT_COPIES: std::sync::Mutex<Vec<std::sync::Weak<crate::shadow::Shadow>>> = std::sync::Mutex::new(Vec::new());
  248. /// [`ARGUMENT_COPIES`] that live, and `first` put in front of them.
  249. fn argument_copies(first: &std::sync::Arc<crate::shadow::Shadow>) -> Vec<(u64, ID3D12Resource)> {
  250. let mut copies = ARGUMENT_COPIES.lock().unwrap_or_else(|e| e.into_inner());
  251. let live: Vec<_> = copies.iter().filter_map(std::sync::Weak::upgrade).filter(|s| s.id() != first.id()).collect();
  252. *copies = std::iter::once(first)
  253. .chain(&live)
  254. .take(crate::indirect::batch::SOURCES)
  255. .map(std::sync::Arc::downgrade)
  256. .collect();
  257. live.iter().map(|s| (s.id(), s.buffer.clone())).collect()
  258. }
  259. /// What one title list has set, and what its host list was last given.
  260. #[derive(Default)]
  261. pub(crate) struct State {
  262. pipeline: usize,
  263. /// View heap, sampler heap.
  264. heaps: [usize; 2],
  265. graphics: Vec<Root>,
  266. compute: Vec<Root>,
  267. vertex: [VertexView; 32],
  268. index: IndexView,
  269. /// Bound render target and depth resources, for their host states.
  270. targets: Vec<usize>,
  271. depth: usize,
  272. /// The host state the bound depth view needs ([`depth_state`]).
  273. depth_state: u32,
  274. /// The title's primitive topology (the host's may differ).
  275. topology: u32,
  276. /// What the title set that goes straight onto the host list, kept for
  277. /// the host list that continues this one after a cut ([`State::replay`]):
  278. /// whether a topology was set, the render target and depth handles, the
  279. /// viewports, the scissors, the blend factor and the stencil reference.
  280. topology_set: bool,
  281. target_handles: Vec<u64>,
  282. depth_handle: u64,
  283. targets_set: bool,
  284. viewports: Vec<D3D12_VIEWPORT>,
  285. scissors: Vec<RECT>,
  286. blend: Option<[f32; 4]>,
  287. stencil: Option<u32>,
  288. depth_bounds: Option<[f32; 2]>,
  289. /// The indirect records clamped last, if later draws may still read
  290. /// them ([`windows`]).
  291. window: Option<Window>,
  292. /// The records clamped in a batch, if later executions may still read
  293. /// them ([`batches`]).
  294. batch: Option<Batch>,
  295. /// The user data bound last, of the last stage that has some (for the
  296. /// report of a removed device, `crate::host::indirects`).
  297. #[cfg(feature = "diagnostics")]
  298. user: Vec<u32>,
  299. /// What the host list has: pipeline, root signature, heaps.
  300. host_pipeline: usize,
  301. /// Graphics, compute.
  302. host_roots: [usize; 2],
  303. host_heaps: [usize; 2],
  304. /// Tables made afresh in this list: (table, slot count, contents) → first
  305. /// dynamic slot.
  306. fresh_tables: std::collections::HashMap<(u64, u32, u64), FreshTable, std::hash::BuildHasherDefault<crate::host::AddressHash>>,
  307. /// The dynamic slots the list holds: title heap, first, count; given
  308. /// back when the list has run, is reset or released.
  309. dynamic: Vec<(usize, u32, u32)>,
  310. /// Root SRVs bound as one-view tables in this list: (title heap, title
  311. /// address; 0 for none) → dynamic slot, and the host copy the slot
  312. /// shows: later draws of the list bring that one up to date, whatever
  313. /// copy the address would find by then (`shadow.rs` `tails`).
  314. root_srv_slots: std::collections::HashMap<(usize, u64), RootSlot>,
  315. /// Root UAVs bound as one-view tables in this list, likewise.
  316. root_uav_slots: std::collections::HashMap<(usize, u64), RootSlot>,
  317. /// The list ran and its dynamic slots were given back.
  318. tables_gone: bool,
  319. /// This recording, for [`crate::descriptor::host::HostHeap::make_listed`]
  320. /// (0: it has none yet).
  321. recording: u64,
  322. }
  323. impl Drop for State {
  324. fn drop(&mut self) {
  325. for &(heap, first, n) in &self.dynamic {
  326. crate::descriptor::release_dynamic(heap, first, n);
  327. }
  328. }
  329. }
  330. impl State {
  331. /// The list's submission has run (submissions are waited for): the
  332. /// dynamic slots its tables were made in are given back, not kept
  333. /// until the title resets the list. A frame of the opening cutscene
  334. /// asks for 12,500 tables; held until the resets they ran the 131,072
  335. /// slots out, and up to 4,900 draws a frame went without their tables.
  336. /// shortcut: a list the title runs a second time without a reset then
  337. /// reads slots others may have taken (logged once).
  338. pub(crate) fn tables_done(&mut self) {
  339. if self.tables_gone && self.dynamic.is_empty() {
  340. return;
  341. }
  342. if self.tables_gone {
  343. static ONCE: std::sync::Once = std::sync::Once::new();
  344. ONCE.call_once(|| tracing::warn!("a list ran again after its descriptor tables were given back"));
  345. }
  346. for (heap, first, n) in self.dynamic.drain(..) {
  347. crate::descriptor::release_dynamic(heap, first, n);
  348. }
  349. self.fresh_tables.clear();
  350. self.recording = 0;
  351. self.root_srv_slots.clear();
  352. self.root_uav_slots.clear();
  353. self.tables_gone = true;
  354. }
  355. }
  356. /// An experiment on the title's scissor rectangles (`VICTORY_SCISSOR_TEST=full`):
  357. /// they are all widened to the whole target. The title's room at
  358. /// the start of the prologue lost its walls in five runs of seven, and in
  359. /// those runs the player's body and the world outside were cut by one
  360. /// rectangle around the window (run 85, frame 2046): one run with this on
  361. /// says whether the walls are drawn and cut away by such a rectangle, or
  362. /// not drawn at all. Off by default: a rectangle the title sets is part of
  363. /// its picture.
  364. fn scissor_test() -> bool {
  365. static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
  366. *ON.get_or_init(|| std::env::var("VICTORY_SCISSOR_TEST").as_deref() == Ok("full"))
  367. }
  368. /// An experiment on mesh draws (`VICTORY_MESH_TEST`): 1 for `skip` (none
  369. /// is issued), 2 for `scissor` (each runs its shaders but rasterises one
  370. /// pixel), 0 otherwise. It tells a card hung by a mesh shader from one hung
  371. /// by what the shader's triangles cover.
  372. fn mesh_test() -> u8 {
  373. static ON: std::sync::OnceLock<u8> = std::sync::OnceLock::new();
  374. *ON.get_or_init(|| match std::env::var("VICTORY_MESH_TEST").as_deref() {
  375. Ok("skip") => 1,
  376. Ok("scissor") => 2,
  377. _ => 0,
  378. })
  379. }
  380. /// `VICTORY_MESH_TEST=keep:<hex digits>[:<hex digits>]`: only the mesh
  381. /// draws whose mesh shader's hash ends in one of the first digits (and
  382. /// whose digit before it is one of the second, if given) are issued: a
  383. /// search for the shaders that stop the card.
  384. fn mesh_kept(pipeline: usize) -> bool {
  385. static KEEP: std::sync::OnceLock<Option<(String, String)>> = std::sync::OnceLock::new();
  386. let Some((last, before)) = KEEP.get_or_init(|| {
  387. let value = std::env::var("VICTORY_MESH_TEST").ok()?;
  388. let mut parts = value.strip_prefix("keep:")?.split(':');
  389. Some((parts.next()?.to_owned(), parts.next().unwrap_or("").to_owned()))
  390. }) else {
  391. return true;
  392. };
  393. let Some(p) = crate::pipeline::host_pipeline(pipeline as This) else {
  394. return true;
  395. };
  396. let Some(at) = p.name.find("mesh ") else {
  397. return true;
  398. };
  399. let hash = p.name[at + 5..].as_bytes();
  400. if hash.len() < 16 {
  401. return true;
  402. }
  403. last.as_bytes().contains(&hash[15]) && (before.is_empty() || before.as_bytes().contains(&hash[14]))
  404. }
  405. /// Draws recorded on the host GPU since the last frame line.
  406. static DRAWN: AtomicU64 = AtomicU64::new(0);
  407. /// Draws run on the host so far.
  408. pub(crate) fn drawn() -> u64 {
  409. DRAWN.load(Ordering::Relaxed)
  410. }
  411. /// The draws traced since the last present (diagnostics builds, with
  412. /// debug logging for this module): logged when the frame comes out black.
  413. #[cfg(feature = "diagnostics")]
  414. static FRAME: std::sync::Mutex<Vec<String>> = std::sync::Mutex::new(Vec::new());
  415. /// The draws traced since the last call.
  416. #[cfg(feature = "diagnostics")]
  417. pub(crate) fn take_frame() -> Vec<String> {
  418. std::mem::take(&mut *FRAME.lock().unwrap_or_else(|e| e.into_inner()))
  419. }
  420. /// Draws, mesh dispatches and dispatches recorded but not run on the host
  421. /// (no host pipeline) since the last call.
  422. pub(crate) fn take_dropped() -> u64 {
  423. DROPPED.swap(0, Ordering::Relaxed)
  424. }
  425. /// A root SRV's dynamic slot in a list, and the host copy it shows.
  426. type RootSlot = (u32, Option<std::sync::Arc<crate::shadow::Shadow>>);
  427. /// Buffer views of the heap whose slot showed another host buffer than
  428. /// the copy the pass brought up to date for them, since the start
  429. /// (diagnostics; for the memory line). It stays 0 while the pass and the
  430. /// slots agree; with `VICTORY_VIEW_EXTENT=0` it counts the views that were
  431. /// read stale.
  432. #[cfg(feature = "diagnostics")]
  433. pub(crate) static HEAP_VIEWS_ELSEWHERE: AtomicU64 = AtomicU64::new(0);
  434. /// Passes over the view heap's buffer views for shaders that pick them by
  435. /// index ([`State::heap_buffers`]), and the microseconds they took.
  436. pub(crate) static HEAP_BUFFER_PASSES: AtomicU64 = AtomicU64::new(0);
  437. pub(crate) static HEAP_BUFFER_MICROS: AtomicU64 = AtomicU64::new(0);
  438. /// Of the passes, nanoseconds since the last frame line: looking at slots,
  439. /// the spans and refreshes of their copies, the texture side.
  440. #[cfg(feature = "diagnostics")]
  441. pub(crate) static HEAP_SPLIT: [AtomicU64; 3] = [const { AtomicU64::new(0) }; 3];
  442. /// Passes after which every buffer slot of the heap was looked at again.
  443. const HEAP_ROUND: u64 = 16;
  444. /// Whether the slots looked at again for no write are a part of them at
  445. /// every pass, each slot at every sixteenth (`VICTORY_HEAP_SPREAD=0`: all of
  446. /// them at every sixteenth pass, as before).
  447. ///
  448. /// All at once was some 115 ms on a thread that records the frame, every
  449. /// sixteenth frame (72,000 slots; run record-1: 11 ms a pass in the lines
  450. /// without such a pass, 22 in those of ten frames with one). A slot is
  451. /// looked at as often as before.
  452. fn heap_spread() -> bool {
  453. static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
  454. *ON.get_or_init(|| std::env::var_os("VICTORY_HEAP_SPREAD").is_none_or(|v| v != "0"))
  455. }
  456. /// The host copy and range the buffer view of each of a heap's slots reads
  457. /// ([`State::heap_buffers`]), by slot.
  458. #[derive(Default)]
  459. struct HeapRanges<T>(Vec<Option<(T, u64, u64)>>);
  460. impl<T> HeapRanges<T> {
  461. fn set(&mut self, slot: u32, range: Option<(T, u64, u64)>) {
  462. let slot = slot as usize;
  463. if range.is_none() && slot >= self.0.len() {
  464. return;
  465. }
  466. if slot >= self.0.len() {
  467. self.0.resize_with(slot + 1, || None);
  468. }
  469. self.0[slot] = range;
  470. }
  471. /// Forgets the slots of one of `parts` parts
  472. /// (`HostHeap::buffer_slots_of`).
  473. fn forget_part(&mut self, part: u32, parts: u32) {
  474. self.0.iter_mut().skip(part as usize).step_by(parts as usize).for_each(|r| *r = None);
  475. }
  476. fn ranges(&self) -> impl Iterator<Item = &(T, u64, u64)> {
  477. self.0.iter().flatten()
  478. }
  479. }
  480. #[cfg(test)]
  481. mod heap_range_tests {
  482. use super::{HEAP_ROUND, HeapRanges};
  483. /// Round by round every slot is looked at again once, whatever was
  484. /// written between, and what a slot holds is what was found last.
  485. #[test]
  486. fn every_slot_is_looked_at_again_in_a_round() {
  487. const SLOTS: u32 = 1000;
  488. let mut ranges = HeapRanges(Vec::new());
  489. ranges.set(7, None);
  490. assert_eq!(ranges.ranges().count(), 0);
  491. for slot in (0..SLOTS).step_by(3) {
  492. ranges.set(slot, Some(((), 0, 1)));
  493. }
  494. let parts = HEAP_ROUND as u32;
  495. for pass in 1..=HEAP_ROUND {
  496. let part = (pass % HEAP_ROUND) as u32;
  497. ranges.forget_part(part, parts);
  498. for slot in (0..SLOTS).step_by(3).filter(|slot| slot % parts == part) {
  499. assert!(ranges.0[slot as usize].is_none(), "slot {slot} not forgotten");
  500. ranges.set(slot, Some(((), pass, pass)));
  501. }
  502. assert_eq!(ranges.ranges().count(), SLOTS.div_ceil(3) as usize);
  503. }
  504. assert!(ranges.ranges().all(|r| r.1 != 0), "a slot not looked at in a round");
  505. ranges.set(3, None);
  506. assert_eq!(ranges.ranges().count(), SLOTS.div_ceil(3) as usize - 1);
  507. }
  508. /// The spans of 4,400 copies from the ranges of 72,000 slots, as a pass
  509. /// makes them, by slot and from the table they were in. Run with
  510. /// `--ignored --nocapture`.
  511. #[test]
  512. #[ignore]
  513. fn spans_of_a_pass() {
  514. use std::collections::HashMap;
  515. use std::sync::Arc;
  516. let copies: Vec<Arc<u64>> = (0..4400).map(Arc::new).collect();
  517. let (mut table, mut slots) = (HashMap::new(), HeapRanges(Vec::new()));
  518. for slot in 0..72_000u32 {
  519. let copy = &copies[slot as usize * 7919 % 4400];
  520. table.insert(slot, (copy.clone(), u64::from(slot), u64::from(slot) + 64));
  521. slots.set(slot, Some((copy.clone(), u64::from(slot), u64::from(slot) + 64)));
  522. }
  523. fn join<S: std::hash::BuildHasher + Default>(ranges: &mut dyn Iterator<Item = &(Arc<u64>, u64, u64)>) -> usize {
  524. let mut spans: HashMap<usize, (Arc<u64>, u64, u64), S> = HashMap::default();
  525. for (copy, from, to) in ranges {
  526. let span = spans.entry(Arc::as_ptr(copy) as usize).or_insert_with(|| (copy.clone(), *from, *to));
  527. span.1 = span.1.min(*from);
  528. span.2 = span.2.max(*to);
  529. }
  530. spans.len()
  531. }
  532. let best = |f: &mut dyn FnMut() -> usize| {
  533. (0..30)
  534. .map(|_| {
  535. let t = std::time::Instant::now();
  536. assert_eq!(f(), 4400);
  537. t.elapsed().as_secs_f64() * 1e3
  538. })
  539. .fold(f64::MAX, f64::min)
  540. };
  541. println!(
  542. "{:.2} ms from the table, {:.2} ms by slot",
  543. best(&mut || join::<std::hash::RandomState>(&mut table.values())),
  544. best(&mut || join::<std::hash::BuildHasherDefault<crate::host::AddressHash>>(&mut slots.ranges())),
  545. );
  546. }
  547. }
  548. /// Textures brought up to date for shaders that pick them by index
  549. /// ([`State::heap_textures`]), the bytes of their memory, and the slots
  550. /// still waiting.
  551. pub(crate) static HEAP_TEXTURES: AtomicU64 = AtomicU64::new(0);
  552. pub(crate) static HEAP_TEXTURE_BYTES: AtomicU64 = AtomicU64::new(0);
  553. pub(crate) static HEAP_TEXTURES_WAITING: AtomicU64 = AtomicU64::new(0);
  554. /// Passes that made no texture because the card had no room
  555. /// (`crate::resource::room`), for the memory line.
  556. pub(crate) static HEAP_TEXTURES_FULL: AtomicU64 = AtomicU64::new(0);
  557. /// Frames after a whole upload of a texture picked by index at which its
  558. /// memory is looked at again, each counted from the look before.
  559. const RECHECK_FRAMES: [u64; 5] = [4, 12, 40, 120, 400];
  560. /// Looks at uploaded textures picked by index that found the memory as it
  561. /// was, and that found it changed (uploaded again), since the start.
  562. pub(crate) static HEAP_TEXTURES_RECHECKED: [AtomicU64; 2] = [AtomicU64::new(0), AtomicU64::new(0)];
  563. /// Uploads of textures already on the card made while it had no room for
  564. /// new ones, since the start.
  565. pub(crate) static HEAP_TEXTURES_REUPLOADED_FULL: AtomicU64 = AtomicU64::new(0);
  566. /// Whether a pass over the textures picked by index on a full card holds
  567. /// back the slots that need a new host copy (`VICTORY_FULL_CARD_PASS=0`:
  568. /// no, as before: they stay due, each pass looks at the same ones again
  569. /// and stops at the 257th). Held back, such a slot is looked at again
  570. /// after about four seconds or as soon as the card has room, and the pass
  571. /// goes on to the slots behind it: the ones whose host copy exists and
  572. /// only wants bringing up to date, and the ones whose memory went (letting
  573. /// their host copies go is what makes room). What is uploaded while the
  574. /// card has room is the same either way.
  575. fn full_card_pass() -> bool {
  576. static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
  577. *ON.get_or_init(|| std::env::var_os("VICTORY_FULL_CARD_PASS").is_none_or(|v| v != "0"))
  578. }
  579. /// Whether a texture that has its host copy is still brought up to date
  580. /// while the card has no room for new ones (`VICTORY_REUPLOAD_WHEN_FULL=0`:
  581. /// no).
  582. fn reupload_when_full() -> bool {
  583. static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
  584. *ON.get_or_init(|| std::env::var_os("VICTORY_REUPLOAD_WHEN_FULL").is_none_or(|v| v != "0"))
  585. }
  586. /// Whether textures picked by index are looked at again after their upload
  587. /// (`VICTORY_HEAP_RECHECK=0`: no).
  588. fn heap_recheck() -> bool {
  589. static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
  590. *ON.get_or_init(|| std::env::var_os("VICTORY_HEAP_RECHECK").is_none_or(|v| v != "0"))
  591. }
  592. /// Times a placed texture's slot was passed over because its memory is not
  593. /// mapped.
  594. pub(crate) static HEAP_TEXTURES_SAME: AtomicU64 = AtomicU64::new(0);
  595. pub(crate) static HEAP_TEXTURES_AWAY: AtomicU64 = AtomicU64::new(0);
  596. /// Slots the pass found up to date already: their texture is uploaded by
  597. /// the draws that read it through a table (it has a staging buffer).
  598. pub(crate) static HEAP_TEXTURES_TABLED: AtomicU64 = AtomicU64::new(0);
  599. /// The queue of textures picked by index at the last pass
  600. /// (`TextureQueue::census`): slots in it, due, waiting for their memory,
  601. /// uploaded in part, and the frames the oldest due one has waited.
  602. pub(crate) static HEAP_TEXTURES_QUEUE: [AtomicU64; 5] = [const { AtomicU64::new(0) }; 5];
  603. /// Since the start: looks at a slot uploaded in part that found no more of
  604. /// its memory mapped; uploads of textures not all mapped; and of those,
  605. /// the ones whose first page was not there (asked by the first page alone,
  606. /// as before, they counted as not there at all).
  607. pub(crate) static HEAP_TEXTURES_PARTLY: [AtomicU64; 3] = [const { AtomicU64::new(0) }; 3];
  608. static DROPPED: AtomicU64 = AtomicU64::new(0);
  609. /// Marks the last traced draw as not run on the host.
  610. #[cfg(feature = "diagnostics")]
  611. fn dropped(pipeline: usize) {
  612. crate::pipeline::note_drop(pipeline as This);
  613. if let Some(last) = FRAME.lock().unwrap_or_else(|e| e.into_inner()).last_mut() {
  614. last.push_str(" DROPPED");
  615. }
  616. }
  617. /// Dispatches run on the host so far.
  618. static DISPATCHED: AtomicU64 = AtomicU64::new(0);
  619. pub(crate) fn dispatched() -> u64 {
  620. DISPATCHED.load(Ordering::Relaxed)
  621. }
  622. /// The host address of a root view: its buffer's host copy, or for a
  623. /// constant buffer not 256-byte aligned there (the console needs 16) a
  624. /// copy in upload memory.
  625. /// shortcut: a root view has no size; constant buffers are taken as 64 KiB
  626. /// (cut at their buffer's end), other views as all that is left of their
  627. /// buffer. (They were taken as 1 MiB: 1,452 of the 2,021 mesh vertex
  628. /// streams of a cutscene frame reach further, and what lay past the first
  629. /// megabyte was never brought up to date - meshes without bodies, exploded
  630. /// triangles. `VICTORY_ROOT_VIEW_MB` sets a limit again.)
  631. fn root_view(list: &HostList, address: u64, srv: bool) -> Option<u64> {
  632. static LIMIT: std::sync::OnceLock<u64> = std::sync::OnceLock::new();
  633. let limit = *LIMIT.get_or_init(|| {
  634. std::env::var("VICTORY_ROOT_VIEW_MB")
  635. .ok()
  636. .and_then(|v| v.parse::<u64>().ok())
  637. .map_or(u64::MAX, |mb| mb << 20)
  638. });
  639. let shadow = crate::shadow::find(address, 1)?;
  640. let len = shadow
  641. .left(address)
  642. .min(if srv { limit } else { 1 << 16 });
  643. let gpu = shadow.gpu(address);
  644. if srv || gpu % 256 == 0 {
  645. shadow.refresh(list, address, len);
  646. #[cfg(feature = "diagnostics")]
  647. crate::book::root(gpu, len);
  648. return Some(gpu);
  649. }
  650. let (gpu, to) = list.scratch(len)?;
  651. list.defer_fill(to, address as *const u8, len as usize);
  652. Some(gpu)
  653. }
  654. macro_rules! once {
  655. ($($arg:tt)*) => {{
  656. static ONCE: std::sync::Once = std::sync::Once::new();
  657. ONCE.call_once(|| tracing::warn!($($arg)*));
  658. }};
  659. }
  660. fn set(roots: &mut Vec<Root>, slot: u32, root: Root) {
  661. let slot = slot as usize;
  662. if roots.len() <= slot {
  663. roots.resize(slot + 1, Root::None);
  664. }
  665. roots[slot] = root;
  666. }
  667. /// The pass over the buffer views of `heap` that shaders pick by index
  668. /// ([`State::heap_buffers`]): their host slots are made, and the host copies
  669. /// they show are to be refreshed.
  670. fn heap_buffer_pass(heap: &crate::descriptor::Heap, host: &crate::descriptor::host::HostHeap, frame: u64) -> Vec<crate::host::aside::Refresh> {
  671. let started = std::time::Instant::now();
  672. // Per host heap: the host copy and range each slot's buffer view
  673. // reads, kept from pass to pass. Only the slots written since the
  674. // last pass are looked at again (83,000 slots a pass otherwise, 0.1 s
  675. // at best); all of them every 16 passes, because a view of a
  676. // released resource goes stale without a write, and a slot written
  677. // before its memory had a host copy is only made then.
  678. type Ranges = HeapRanges<std::sync::Arc<crate::shadow::Shadow>>;
  679. static RANGES: std::sync::Mutex<Option<std::collections::HashMap<usize, (u64, Ranges)>>> =
  680. std::sync::Mutex::new(None);
  681. let mut kept = RANGES.lock().unwrap_or_else(|e| e.into_inner());
  682. let (passes, ranges) = kept
  683. .get_or_insert_with(Default::default)
  684. .entry(std::ptr::from_ref(host) as usize)
  685. .or_insert_with(|| (0, HeapRanges(Vec::new())));
  686. let changed = host.buffer_changes();
  687. let all = *passes == 0 || (*passes % HEAP_ROUND == 0 && !heap_spread());
  688. let slots = if all {
  689. ranges.0.clear();
  690. host.buffer_slots()
  691. } else if heap_spread() {
  692. // The written ones, and this pass's part of the others.
  693. let (part, parts) = ((*passes % HEAP_ROUND) as u32, HEAP_ROUND as u32);
  694. ranges.forget_part(part, parts);
  695. let mut slots = host.buffer_slots_of(part, parts);
  696. slots.extend(changed);
  697. slots
  698. } else {
  699. changed
  700. };
  701. *passes += 1;
  702. // Whether the device was there before the pass: a view that removes
  703. // it is named below.
  704. static GONE: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
  705. let mut alive = !GONE.load(Ordering::Relaxed) && crate::descriptor::host::device_removed().is_none();
  706. let mut unordered = Vec::new();
  707. for (n, &index) in slots.iter().enumerate() {
  708. ranges.set(index, None);
  709. // A draw's table's: the draw brings what it reads up to date.
  710. if host.copied_tabled(index, frame) {
  711. continue;
  712. }
  713. let Some(handle) = heap.handle(index) else {
  714. continue;
  715. };
  716. let Some(view) = host.mirror(index, handle, true) else {
  717. continue;
  718. };
  719. // Every 64 views while the device lives (a cheap query).
  720. if alive
  721. && n % 64 == 63
  722. && let Some(why) = crate::descriptor::host::device_removed()
  723. {
  724. alive = false;
  725. GONE.store(true, Ordering::Relaxed);
  726. let last: Vec<String> = slots[n - 63..=n]
  727. .iter()
  728. .filter_map(|&i| crate::descriptor::view(heap.handle(i)?).map(|v| format!("{i}: {v:?}")))
  729. .map(|s| s.chars().take(200).collect())
  730. .collect();
  731. tracing::error!(why, slot = index, "the host device went while buffer views of the heap were made; one of: {last:#?}");
  732. crate::host::log_removal_context();
  733. }
  734. // The copy the slot shows (`buffer_copy`), not the one the
  735. // view's range alone would find.
  736. let Some((shadow, address, len)) = crate::descriptor::host::buffer_copy(&view) else {
  737. continue;
  738. };
  739. #[cfg(feature = "diagnostics")]
  740. if host.shows(index, &shadow.buffer) == Some(false) {
  741. HEAP_VIEWS_ELSEWHERE.fetch_add(1, Ordering::Relaxed);
  742. }
  743. if crate::picked::on() && view_kind(&view) == Some(ResourceType::Uav) {
  744. unordered.push((shadow.clone(), address, address + len));
  745. }
  746. ranges.set(index, Some((shadow, address, address + len)));
  747. }
  748. if crate::picked::on() {
  749. crate::picked::shown(unordered, all);
  750. }
  751. #[cfg(feature = "diagnostics")]
  752. let looked = std::time::Instant::now();
  753. // Per host copy, the span its picked views cover.
  754. let mut spans: crate::host::ByCopy<(std::sync::Arc<crate::shadow::Shadow>, u64, u64)> = Default::default();
  755. let mut views = 0u32;
  756. for (shadow, from, to) in ranges.ranges() {
  757. views += 1;
  758. let key = std::sync::Arc::as_ptr(shadow) as usize;
  759. let span = spans.entry(key).or_insert_with(|| (shadow.clone(), *from, *to));
  760. span.1 = span.1.min(*from);
  761. span.2 = span.2.max(*to);
  762. }
  763. drop(kept);
  764. let bytes: u64 = spans.values().map(|s| s.2 - s.1).sum();
  765. // Memory that is not write-watched is copied whole by every refresh.
  766. // It was once refreshed only every 120 frames (unmapped pages read
  767. // one by one cost 14 GB a frame in run 11, before they were
  768. // remembered): streamed geometry then drew from stale buffers, and
  769. // the garbage ended runs (the card stopped answering 14-90 frames
  770. // into the opening cutscene; with every frame it ran on). The pass
  771. // costs some 30 ms a frame this way.
  772. static WHOLE: std::sync::Mutex<Option<std::collections::HashMap<usize, u64>>> = std::sync::Mutex::new(None);
  773. let mut whole = WHOLE.lock().unwrap_or_else(|e| e.into_inner());
  774. let whole = whole.get_or_insert_with(Default::default);
  775. let mut found = Vec::with_capacity(spans.len());
  776. for (shadow, from, to) in spans.values() {
  777. if shadow.unwatched() {
  778. // By the copy's number: a copy made where one let go was
  779. // (`shadow::let_go_idle`) has never been refreshed.
  780. let key = shadow.id() as usize;
  781. // `VICTORY_UNWATCHED_FRAMES` sets the interval (1: every frame).
  782. static EVERY: std::sync::OnceLock<u64> = std::sync::OnceLock::new();
  783. let every = *EVERY.get_or_init(|| {
  784. std::env::var("VICTORY_UNWATCHED_FRAMES")
  785. .ok()
  786. .and_then(|v| v.parse().ok())
  787. .unwrap_or(1)
  788. });
  789. match whole.get(&key) {
  790. Some(&last) if frame < last + every => continue,
  791. _ => {
  792. whole.insert(key, frame);
  793. }
  794. }
  795. }
  796. found.push((shadow.clone(), *from, (*to).min(*from + shadow.left(*from))));
  797. }
  798. #[cfg(feature = "diagnostics")]
  799. let refreshed = std::time::Instant::now();
  800. crate::watch::look_at_holes();
  801. #[cfg(feature = "diagnostics")]
  802. for (sum, time) in HEAP_SPLIT.iter().zip([looked - started, refreshed - looked]) {
  803. sum.fetch_add(time.as_nanos() as u64, Ordering::Relaxed);
  804. }
  805. static LOGGED: AtomicU64 = AtomicU64::new(0);
  806. // The first pass and every growth of the set by half.
  807. let seen = LOGGED.load(Ordering::Relaxed);
  808. if u64::from(views) > seen + seen / 2 {
  809. LOGGED.store(u64::from(views), Ordering::Relaxed);
  810. tracing::info!(
  811. slots = slots.len(),
  812. views,
  813. copies = spans.len(),
  814. mb = bytes >> 20,
  815. ms = started.elapsed().as_millis(),
  816. "buffer views of the heap made ready for shaders that pick them by index"
  817. );
  818. }
  819. found
  820. }
  821. impl State {
  822. pub(crate) fn reset(&mut self, pipeline: This) {
  823. *self = State::default();
  824. self.pipeline = pipeline as usize;
  825. }
  826. /// The title's topology; console-only ones become host lists (see
  827. /// [`crate::primitive`]).
  828. pub(crate) fn set_topology(&mut self, list: &HostList, topology: u32) {
  829. self.topology = topology;
  830. self.topology_set = true;
  831. let host = match topology {
  832. RECTANGLES => 4,
  833. TRIANGLE_FAN | LINE_LOOP | QUADS | QUAD_STRIP => {
  834. once!(topology, "console topology drawn as a triangle list");
  835. 4
  836. }
  837. t => t,
  838. };
  839. // SAFETY: an open list.
  840. unsafe {
  841. list.list
  842. .IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY(host as i32))
  843. };
  844. }
  845. pub(crate) fn set_pipeline(&mut self, pipeline: This) {
  846. self.pipeline = pipeline as usize;
  847. }
  848. pub(crate) fn set_heaps(&mut self, heaps: &[This]) {
  849. self.heaps = [0; 2];
  850. for &h in heaps {
  851. if !h.is_null() {
  852. let samplers = crate::descriptor::heap(h).samplers();
  853. self.heaps[usize::from(samplers)] = h as usize;
  854. }
  855. }
  856. }
  857. fn roots(&mut self, compute: bool) -> &mut Vec<Root> {
  858. if compute {
  859. &mut self.compute
  860. } else {
  861. &mut self.graphics
  862. }
  863. }
  864. pub(crate) fn set_table(&mut self, compute: bool, slot: u32, handle: u64) {
  865. set(self.roots(compute), slot, Root::Table(handle));
  866. }
  867. pub(crate) fn set_view(&mut self, compute: bool, slot: u32, address: u64) {
  868. set(self.roots(compute), slot, Root::View(address));
  869. }
  870. pub(crate) fn set_constants(&mut self, compute: bool, slot: u32, values: &[u32], offset: u32) {
  871. let roots = self.roots(compute);
  872. let s = slot as usize;
  873. if !matches!(roots.get(s), Some(Root::Constants(_))) {
  874. set(roots, slot, Root::Constants(Vec::new()));
  875. }
  876. if let Root::Constants(c) = &mut roots[s] {
  877. let end = offset as usize + values.len();
  878. if c.len() < end {
  879. c.resize(end, 0);
  880. }
  881. c[offset as usize..end].copy_from_slice(values);
  882. }
  883. }
  884. pub(crate) fn set_vertex_buffers(&mut self, start: u32, views: &[VertexView]) {
  885. for (i, v) in views.iter().enumerate() {
  886. if let Some(slot) = self.vertex.get_mut(start as usize + i) {
  887. *slot = *v;
  888. }
  889. }
  890. }
  891. pub(crate) fn clear_vertex_buffers(&mut self, start: u32, count: u32) {
  892. for slot in self.vertex.iter_mut().skip(start as usize).take(count as usize) {
  893. *slot = VertexView::default();
  894. }
  895. }
  896. pub(crate) fn set_index_buffer(&mut self, view: Option<&IndexView>) {
  897. self.index = view.copied().unwrap_or_default();
  898. }
  899. /// Render targets and depth, set on the host list at once.
  900. pub(crate) fn set_targets(&mut self, list: &HostList, handles: &[u64], depth: u64) {
  901. let Some(host) = crate::host::host() else {
  902. return;
  903. };
  904. self.target_handles.clear();
  905. self.target_handles.extend_from_slice(handles);
  906. self.depth_handle = depth;
  907. self.targets_set = true;
  908. self.targets.clear();
  909. let mut rtvs = Vec::new();
  910. for &h in handles {
  911. let Some(record) = crate::descriptor::rtv_record(h) else {
  912. once!(
  913. handle = format_args!("{h:#x}"),
  914. "render target without a recorded view"
  915. );
  916. continue;
  917. };
  918. let Some(texture) = crate::resource::host_resource(record.resource) else {
  919. // A typed null view (or a target without a host copy) still
  920. // takes its slot: left out, the next live target would move
  921. // into it and the pixel shader's outputs reach the wrong
  922. // targets.
  923. // shortcut: a view without a description or a format has no
  924. // null view to stand for it and is left out, as before.
  925. let null = record
  926. .desc()
  927. .filter(|d| d.Format.0 != 0 && d.ViewDimension.0 != 0);
  928. if let Some(desc) = null {
  929. rtvs.push(host.rtv(None, Some(&desc)));
  930. }
  931. continue;
  932. };
  933. self.targets.push(record.resource as usize);
  934. #[cfg(feature = "diagnostics")]
  935. crate::capture::note_target(record.resource);
  936. rtvs.push(host.rtv(Some(texture), record.desc().as_ref()));
  937. }
  938. self.depth = 0;
  939. self.depth_state = DEPTH_WRITE;
  940. let dsv = crate::descriptor::dsv_record(depth).and_then(|record| {
  941. let texture = crate::resource::host_resource(record.resource)?;
  942. self.depth = record.resource as usize;
  943. self.depth_state = depth_state(texture, record.depth_desc().as_ref());
  944. if crate::resource::depth_and_unordered(record.resource) {
  945. crate::resource::DEPTH_UNORDERED[1].fetch_add(1, Ordering::Relaxed);
  946. }
  947. #[cfg(feature = "diagnostics")]
  948. crate::capture::note_target(record.resource);
  949. Some(host.dsv(texture, record.depth_desc().as_ref()))
  950. });
  951. // SAFETY: an open list; the views were just made.
  952. unsafe {
  953. list.list.OMSetRenderTargets(
  954. rtvs.len() as u32,
  955. (!rtvs.is_empty()).then_some(rtvs.as_ptr()),
  956. false,
  957. dsv.as_ref().map(std::ptr::from_ref),
  958. )
  959. };
  960. }
  961. /// Viewports, scissors, the blend factor and the stencil reference: set
  962. /// on the host list at once, and kept for [`State::replay`].
  963. pub(crate) fn set_viewports(&mut self, list: &HostList, viewports: &[D3D12_VIEWPORT]) {
  964. #[cfg(feature = "diagnostics")]
  965. if let Some(v) = viewports.first() {
  966. crate::host::spans::viewport(v.Width as u32, v.Height as u32);
  967. }
  968. self.viewports.clear();
  969. self.viewports.extend_from_slice(viewports);
  970. crate::draw::viewports(list, viewports);
  971. }
  972. pub(crate) fn set_scissors(&mut self, list: &HostList, rects: &[RECT]) {
  973. self.scissors.clear();
  974. self.scissors.extend_from_slice(rects);
  975. if scissor_test() {
  976. // The experiment: every rectangle the title sets is widened to
  977. // the largest target there is, so nothing is cut by one. What
  978. // the listing shows (`op_text`) stays the title's own.
  979. let full = RECT {
  980. left: 0,
  981. top: 0,
  982. right: 16384,
  983. bottom: 16384,
  984. };
  985. crate::draw::scissors(list, &vec![full; rects.len()]);
  986. return;
  987. }
  988. crate::draw::scissors(list, rects);
  989. }
  990. pub(crate) fn set_blend_factor(&mut self, list: &HostList, factor: Option<&[f32; 4]>) {
  991. self.blend = factor.copied();
  992. crate::draw::blend_factor(list, factor);
  993. }
  994. pub(crate) fn set_stencil_ref(&mut self, list: &HostList, reference: u32) {
  995. self.stencil = Some(reference);
  996. crate::draw::stencil_ref(list, reference);
  997. }
  998. pub(crate) fn set_depth_bounds(&mut self, list: &HostList, min: f32, max: f32) {
  999. self.depth_bounds = Some([min, max]);
  1000. crate::draw::depth_bounds(list, min, max);
  1001. }
  1002. /// `list` is a new host list that continues the title's list (it was
  1003. /// cut at a wait for a memory value, `crate::list::cut`): a new host
  1004. /// list has nothing set, so what the title set so far is set again.
  1005. /// The pipeline, the root signatures and the heaps are set by the next
  1006. /// draw or dispatch (`bind`, which is told here that the host list has
  1007. /// none); root arguments, vertex and index buffers are set by every
  1008. /// draw anyway. The dynamic descriptor slots and the tables made in
  1009. /// them stay: the parts before the cut have not run yet, and they are
  1010. /// given back when the title's list is reset.
  1011. /// shortcut: the render target views are made again from the handles'
  1012. /// descriptors as they are now, not as they were when the title set
  1013. /// the targets (a descriptor rewritten in between names another view).
  1014. pub(crate) fn replay(&mut self, list: &HostList) {
  1015. self.host_pipeline = 0;
  1016. self.host_roots = [0; 2];
  1017. self.host_heaps = [0; 2];
  1018. if self.topology_set {
  1019. self.set_topology(list, self.topology);
  1020. }
  1021. if self.targets_set {
  1022. let handles = std::mem::take(&mut self.target_handles);
  1023. self.set_targets(list, &handles, self.depth_handle);
  1024. }
  1025. if !self.viewports.is_empty() {
  1026. crate::draw::viewports(list, &self.viewports);
  1027. }
  1028. if !self.scissors.is_empty() {
  1029. let rects = std::mem::take(&mut self.scissors);
  1030. self.set_scissors(list, &rects);
  1031. }
  1032. if let Some(factor) = self.blend {
  1033. crate::draw::blend_factor(list, Some(&factor));
  1034. }
  1035. if let Some(reference) = self.stencil {
  1036. crate::draw::stencil_ref(list, reference);
  1037. }
  1038. if let Some([min, max]) = self.depth_bounds {
  1039. crate::draw::depth_bounds(list, min, max);
  1040. }
  1041. }
  1042. /// The user-data value of a root argument, as translated shaders read
  1043. /// it: a table's byte offset in its heap, a constant's value.
  1044. fn user_value(&self, compute: bool, slot: u8, root: RootType, dword: u32) -> u32 {
  1045. match (self.roots_ref(compute).get(usize::from(slot)), root) {
  1046. (Some(Root::Table(handle)), RootType::Table) => match self.heap_of(*handle) {
  1047. Some(heap) => (handle - heap.start) as u32,
  1048. None => {
  1049. once!(
  1050. handle = format_args!("{handle:#x}"),
  1051. "descriptor table outside the bound heaps"
  1052. );
  1053. 0
  1054. }
  1055. },
  1056. (Some(Root::Constants(c)), RootType::Constants) => {
  1057. c.get(dword as usize).copied().unwrap_or(0)
  1058. }
  1059. // The host's own ([`Self::host_word`]): no root argument.
  1060. (_, RootType::Other(_)) => 0,
  1061. _ => {
  1062. once!(
  1063. slot,
  1064. ?root,
  1065. "a shader reads a root argument the title did not set"
  1066. );
  1067. 0
  1068. }
  1069. }
  1070. }
  1071. /// A user-data dword the host computes for a translated shader
  1072. /// (`victory_shader::emit::USER_MEMORY_BASE`, `USER_VIEW_ADDRESS`).
  1073. fn host_word(
  1074. &self,
  1075. compute: bool,
  1076. kind: u32,
  1077. slot: u8,
  1078. dword: u32,
  1079. memory: Option<&crate::memory::Ready>,
  1080. ) -> u32 {
  1081. use victory_shader::emit::{USER_MEMORY_BASE, USER_ROOT_ADDRESS, USER_VIEW_ADDRESS, USER_VIEW_BIAS};
  1082. if kind == USER_MEMORY_BASE {
  1083. return memory.map_or(0, |m| m.base);
  1084. }
  1085. // All of every group, unless the dispatch says otherwise.
  1086. if kind == victory_shader::emit::USER_DISPATCH_THREADS_X {
  1087. return 0;
  1088. }
  1089. if kind == USER_ROOT_ADDRESS || kind == USER_ROOT_ADDRESS + 1 {
  1090. return match self.roots_ref(compute).get(usize::from(slot)) {
  1091. Some(&Root::View(address)) if kind == USER_ROOT_ADDRESS => address as u32,
  1092. Some(&Root::View(address)) => (address >> 32) as u32,
  1093. _ => 0,
  1094. };
  1095. }
  1096. if kind == USER_VIEW_BIAS {
  1097. // The view begins on 16 bytes of the copy the address finds
  1098. // (`root_uav`, `root_srv_table`).
  1099. // shortcut: found again here, not taken from the list's slot.
  1100. return match self.roots_ref(compute).get(usize::from(slot)) {
  1101. Some(&Root::View(address)) => crate::shadow::find(address, 1).map_or(0, |s| {
  1102. // SAFETY: a live buffer.
  1103. let base = unsafe { s.buffer.GetGPUVirtualAddress() };
  1104. ((s.gpu(address) - base) & 15) as u32
  1105. }),
  1106. _ => 0,
  1107. };
  1108. }
  1109. if kind != USER_VIEW_ADDRESS && kind != USER_VIEW_ADDRESS + 1 {
  1110. once!(kind, "a shader reads a host value this build does not know");
  1111. return 0;
  1112. }
  1113. let address = self.view_address(compute, slot, dword);
  1114. if address == 0 {
  1115. // The first few say what lies there instead.
  1116. static SAID: AtomicU64 = AtomicU64::new(0);
  1117. if SAID.fetch_add(1, Ordering::Relaxed) < 8 {
  1118. let view = match self.roots_ref(compute).get(usize::from(slot)) {
  1119. Some(&Root::Table(table)) => crate::descriptor::view(table + u64::from(dword) * 4),
  1120. _ => None,
  1121. };
  1122. tracing::warn!(slot, dword, ?view, "a shader takes the address of a buffer view that is not there: it reads 0");
  1123. }
  1124. }
  1125. if kind == USER_VIEW_ADDRESS {
  1126. address as u32
  1127. } else {
  1128. (address >> 32) as u32
  1129. }
  1130. }
  1131. /// The title address the view at dword `dword` of the table in root
  1132. /// slot `slot` starts at, 0 without one.
  1133. fn view_address(&self, compute: bool, slot: u8, dword: u32) -> u64 {
  1134. match self.roots_ref(compute).get(usize::from(slot)) {
  1135. Some(&Root::Table(table)) => crate::descriptor::view(table + u64::from(dword) * 4)
  1136. .and_then(|view| crate::descriptor::host::view_address(&view))
  1137. .unwrap_or(0),
  1138. _ => 0,
  1139. }
  1140. }
  1141. /// For a shader that reads title memory by address
  1142. /// ([`crate::memory`]): its directory, fault notes and view slots,
  1143. /// with the pages made ready of the root views the list has set and of
  1144. /// the views whose addresses it takes (`t`: the ray-tracing structures
  1145. /// it walks).
  1146. fn memory_ready(
  1147. &self,
  1148. list: &HostList,
  1149. t: &crate::pipeline::Translated,
  1150. compute: bool,
  1151. use_: crate::memory::Use,
  1152. ) -> Option<crate::memory::Ready> {
  1153. let heap = match self.heaps[0] {
  1154. 0 => None,
  1155. h => crate::descriptor::heap(h as This).host(),
  1156. }?;
  1157. let (mut addresses, mut constants) = (Vec::new(), Vec::new());
  1158. // (What it may write: its root views of unordered access.)
  1159. let written: Vec<u64> = t
  1160. .used
  1161. .iter()
  1162. .filter(|u| u.kind == ResourceType::Uav && u.root == RootType::Descriptor)
  1163. .filter_map(|u| match self.roots_ref(compute).get(usize::from(u.slot)) {
  1164. Some(&Root::View(address)) => Some(address),
  1165. _ => None,
  1166. })
  1167. .collect();
  1168. for root in self.roots_ref(compute) {
  1169. match root {
  1170. // (Of a program that only walks structures, the structures'
  1171. // views below: its root views are constants and tables.)
  1172. Root::View(address) if use_ != crate::memory::Use::Reads => addresses.push(*address),
  1173. Root::Constants(values) => constants.extend_from_slice(values),
  1174. _ => {}
  1175. }
  1176. }
  1177. for u in &t.host.user_data {
  1178. if u.root == RootType::Other(victory_shader::emit::USER_VIEW_ADDRESS) {
  1179. addresses.push(self.view_address(compute, u.slot, u.dword));
  1180. }
  1181. }
  1182. crate::memory::ready(list, heap, &addresses, &written, &constants, use_)
  1183. }
  1184. /// The bound heap holding `handle`.
  1185. fn heap_of(&self, handle: u64) -> Option<&'static crate::descriptor::Heap> {
  1186. self.heaps
  1187. .iter()
  1188. .filter(|&&h| h != 0)
  1189. .map(|&h| crate::descriptor::heap(h as This))
  1190. .find(|h| h.index(handle).is_some())
  1191. }
  1192. /// Brings the host list up to date for a draw; false if the draw cannot
  1193. /// run on the host.
  1194. fn prepare(&mut self, list: &HostList, indexed: bool) -> bool {
  1195. self.prepare_for(list, indexed, false)
  1196. }
  1197. /// As [`State::prepare`], for draws (`mesh` false) or mesh dispatches.
  1198. fn prepare_for(&mut self, list: &HostList, indexed: bool, mesh: bool) -> bool {
  1199. #[cfg(feature = "diagnostics")]
  1200. if crate::pipeline::is_skipped(self.pipeline as This) {
  1201. return false;
  1202. }
  1203. let Some(p) = crate::pipeline::host_pipeline(self.pipeline as This) else {
  1204. return false;
  1205. };
  1206. if p.compute || p.mesh != mesh {
  1207. once!(mesh, "a draw or mesh dispatch with another kind of pipeline");
  1208. return false;
  1209. }
  1210. if p.rects && self.topology != RECTANGLES {
  1211. // Its geometry stage would turn each triangle into a rectangle.
  1212. once!("a rectangle pipeline drawn with another topology");
  1213. }
  1214. if !self.bind(list, p, false) {
  1215. return false;
  1216. }
  1217. let l = &list.list;
  1218. // Vertex buffers the input layout reads.
  1219. let mut views = [D3D12_VERTEX_BUFFER_VIEW::default(); 32];
  1220. let mut count = 0;
  1221. for (slot, (view, &v)) in views.iter_mut().zip(&self.vertex).enumerate() {
  1222. if p.slots & 1 << slot == 0 {
  1223. continue;
  1224. }
  1225. count = slot + 1;
  1226. if v.address == 0 || v.size == 0 {
  1227. continue;
  1228. }
  1229. let Some(shadow) = crate::shadow::find_any(v.address, u64::from(v.size)) else {
  1230. continue;
  1231. };
  1232. shadow.refresh(list, v.address, u64::from(v.size));
  1233. *view = D3D12_VERTEX_BUFFER_VIEW {
  1234. BufferLocation: shadow.gpu(v.address),
  1235. SizeInBytes: v.size.min(u32::try_from(shadow.left(v.address)).unwrap_or(u32::MAX)),
  1236. StrideInBytes: v.stride,
  1237. };
  1238. }
  1239. // SAFETY: an open list; the views name live host buffers.
  1240. unsafe {
  1241. if count > 0 {
  1242. l.IASetVertexBuffers(0, Some(&views[..count]));
  1243. }
  1244. }
  1245. if indexed {
  1246. let v = self.index;
  1247. let Some(shadow) = crate::shadow::find_any(v.address, u64::from(v.size)) else {
  1248. return false;
  1249. };
  1250. shadow.refresh(list, v.address, u64::from(v.size));
  1251. let view = D3D12_INDEX_BUFFER_VIEW {
  1252. BufferLocation: shadow.gpu(v.address),
  1253. SizeInBytes: v.size.min(u32::try_from(shadow.left(v.address)).unwrap_or(u32::MAX)),
  1254. Format: DXGI_FORMAT(v.format as i32),
  1255. };
  1256. // SAFETY: an open list; the view names a live host buffer.
  1257. unsafe { l.IASetIndexBuffer(Some(&view)) };
  1258. }
  1259. const RENDER_TARGET: u32 = 0x4;
  1260. for &t in &self.targets {
  1261. crate::list::ensure_state(list, t as This, RENDER_TARGET);
  1262. }
  1263. if self.depth != 0 {
  1264. // A depth texture shaders also write: what they wrote, first.
  1265. list.twin_use(self.depth as This, false, true);
  1266. // A view that writes neither plane keeps the texture readable:
  1267. // the depth read state, together with the shader read states
  1268. // if this draw's shaders read the same texture (the write state
  1269. // put it out of the state those views need, and a move to it
  1270. // and back for every such draw).
  1271. let state = if self.depth_state == DEPTH_READ {
  1272. let (tested, read) = TESTED_DEPTH.get();
  1273. if read && tested == self.depth {
  1274. DEPTH_READ | SHADER_RESOURCE
  1275. } else {
  1276. DEPTH_READ
  1277. }
  1278. } else {
  1279. DEPTH_WRITE
  1280. };
  1281. crate::list::ensure_state(list, self.depth as This, state);
  1282. }
  1283. true
  1284. }
  1285. /// A descriptor a shader reads through a table: its host slot made if
  1286. /// it changed, constant data copied, textures made readable.
  1287. /// What draws and dispatches share: heaps, our root signature, the
  1288. /// pipeline, and per stage the user data, root views and the
  1289. /// descriptors its tables hold.
  1290. /// False if the draw or dispatch must not run: a root SRV it reads
  1291. /// could not be given a view.
  1292. pub(crate) fn bind(&mut self, list: &HostList, p: &HostPipeline, compute: bool) -> bool {
  1293. let l = &list.list;
  1294. // Textures picked by index, before anything asks for them.
  1295. self.early_textures(list, p, compute);
  1296. if crate::host::walls_trace() {
  1297. self.walls_census(p, compute);
  1298. }
  1299. // A list without a view heap: one of the title's for the views the
  1300. // host itself puts into heap slots.
  1301. if self.heaps[0] == 0
  1302. && p.stages.iter().any(|s| !s.root_uavs.is_empty() || !s.root_srvs.is_empty())
  1303. && let Some(heap) = crate::descriptor::lent_heap()
  1304. {
  1305. once!("a dispatch without a view heap that needs one gets the title's");
  1306. self.heaps[0] = heap;
  1307. }
  1308. // Heaps first: a root signature with directly indexed heaps must be
  1309. // set after them.
  1310. if self.host_heaps != self.heaps {
  1311. let heaps: Vec<Option<ID3D12DescriptorHeap>> = self
  1312. .heaps
  1313. .iter()
  1314. .filter(|&&h| h != 0)
  1315. .filter_map(|&h| crate::descriptor::heap(h as This).host())
  1316. .map(|h| Some(h.heap.clone()))
  1317. .collect();
  1318. heaps.iter().flatten().for_each(|h| list.keep(h));
  1319. // SAFETY: an open list and shader-visible heaps.
  1320. unsafe { l.SetDescriptorHeaps(&heaps) };
  1321. self.host_heaps = self.heaps;
  1322. self.host_roots = [0; 2];
  1323. }
  1324. // The depth target a draw only tests, for the views of it that the
  1325. // draw's shaders read (`readable`).
  1326. let tested = if !compute && self.depth_state == DEPTH_READ {
  1327. self.depth
  1328. } else {
  1329. 0
  1330. };
  1331. TESTED_DEPTH.set((tested, false));
  1332. let root = p.root.as_raw() as usize;
  1333. if self.host_roots[usize::from(compute)] != root {
  1334. // SAFETY: an open list and a live root signature.
  1335. unsafe {
  1336. if compute {
  1337. l.SetComputeRootSignature(&p.root);
  1338. } else {
  1339. l.SetGraphicsRootSignature(&p.root);
  1340. }
  1341. }
  1342. self.host_roots[usize::from(compute)] = root;
  1343. }
  1344. // By host object: a title pipeline released and another made at its
  1345. // address is another host pipeline (the list keeps the old one).
  1346. if self.host_pipeline != p.pso.as_raw() as usize {
  1347. // SAFETY: an open list and a live pipeline.
  1348. unsafe { l.SetPipelineState(&p.pso) };
  1349. self.host_pipeline = p.pso.as_raw() as usize;
  1350. list.used_pipeline(&p.name);
  1351. // The title may release the pipeline before it submits the list.
  1352. list.keep(&p.pso);
  1353. list.keep(&p.root);
  1354. }
  1355. for stage in &p.stages {
  1356. let t = stage.translated();
  1357. STORES.set(t.stores);
  1358. if t.stores && crate::picked::on() && crate::picked::picks(&stage.shader, &t.picks) {
  1359. crate::picked::runs_in(list);
  1360. }
  1361. let made = self.tables(list, &t.used, &t.host.root_indexed_views, compute);
  1362. STORES.set(true);
  1363. if made.iter().any(|m| m.1 == u32::MAX) {
  1364. once!("a draw whose descriptor table found no free slots is dropped");
  1365. return false;
  1366. }
  1367. // What the shader stores through root views and raw addresses is
  1368. // copied back into title memory afterwards.
  1369. let writes = (t.stores || !write_skip())
  1370. && !crate::pipeline::builder_quarantined(self.pipeline as This);
  1371. // Title memory by address: what the shader finds it by.
  1372. let memory = if t.host.root_srvs.contains(&victory_shader::emit::SLOT_MEMORY) {
  1373. // Only through a store by address: what it stores through
  1374. // views is declared with them.
  1375. let use_ = if crate::pipeline::is_builder(self.pipeline as This) || writes && t.stores_by_address {
  1376. crate::memory::Use::Builds { back: writes }
  1377. } else {
  1378. crate::memory::Use::Reads
  1379. };
  1380. let Some(ready) = self.memory_ready(list, &t, compute, use_) else {
  1381. once!("a shader that reads title memory by address without a view heap to hold its views: the draw is dropped");
  1382. return false;
  1383. };
  1384. Some(ready)
  1385. } else {
  1386. None
  1387. };
  1388. if let Some((param, dwords)) = stage.user_data {
  1389. // (A root signature holds 64 dwords.)
  1390. let mut room = [0u32; 64];
  1391. let mut more = Vec::new();
  1392. let values: &mut [u32] = match room.get_mut(..dwords as usize) {
  1393. Some(values) => values,
  1394. None => {
  1395. more.resize(dwords as usize, 0);
  1396. &mut more
  1397. }
  1398. };
  1399. for u in &t.host.user_data {
  1400. if let RootType::Other(kind) = u.root {
  1401. values[u.index as usize] =
  1402. self.host_word(compute, kind, u.slot, u.dword, memory.as_ref());
  1403. continue;
  1404. }
  1405. let fresh = made
  1406. .iter()
  1407. .find(|m| m.0 == u.slot && u.root == RootType::Table);
  1408. values[u.index as usize] = match fresh {
  1409. Some(&(_, offset)) => offset,
  1410. None => self.user_value(compute, u.slot, u.root, u.dword),
  1411. };
  1412. }
  1413. #[cfg(feature = "diagnostics")]
  1414. {
  1415. self.user.clear();
  1416. self.user.extend_from_slice(values);
  1417. }
  1418. // SAFETY: an open list; `values` covers the parameter.
  1419. unsafe {
  1420. if compute {
  1421. l.SetComputeRoot32BitConstants(param, dwords, values.as_ptr().cast(), 0);
  1422. } else {
  1423. l.SetGraphicsRoot32BitConstants(param, dwords, values.as_ptr().cast(), 0);
  1424. }
  1425. }
  1426. }
  1427. for (views, srv) in [(&stage.root_cbvs, false), (&stage.root_srvs, true)] {
  1428. for &(slot, param) in views {
  1429. if srv && slot == victory_shader::emit::SLOT_MEMORY {
  1430. // Ours: the directory of title memory by address.
  1431. if let Some(m) = &memory {
  1432. // SAFETY: an open list; the directory lives as
  1433. // long as the process and the list holds it.
  1434. unsafe {
  1435. if compute {
  1436. l.SetComputeRootShaderResourceView(param, m.directory);
  1437. } else {
  1438. l.SetGraphicsRootShaderResourceView(param, m.directory);
  1439. }
  1440. }
  1441. }
  1442. continue;
  1443. }
  1444. if srv && slot == victory_shader::emit::SLOT_STRIDES {
  1445. // Ours, not the title's: the shader picks buffers
  1446. // from the view heap by an index it computes.
  1447. match self.heap_buffers(list) {
  1448. // SAFETY: an open list; the table lives as long
  1449. // as the heap the list holds.
  1450. Some(gpu) => unsafe {
  1451. if compute {
  1452. l.SetComputeRootShaderResourceView(param, gpu);
  1453. } else {
  1454. l.SetGraphicsRootShaderResourceView(param, gpu);
  1455. }
  1456. },
  1457. None => once!("a shader picks buffers from a view heap that is not set"),
  1458. }
  1459. continue;
  1460. }
  1461. let tabled = srv && crate::pipeline::host::bounded_root_srvs();
  1462. let Some(&Root::View(address)) = self.roots_ref(compute).get(usize::from(slot))
  1463. else {
  1464. once!(slot, "a shader reads a root view the title did not set");
  1465. // A table left unset is undefined: a null view.
  1466. if tabled && !self.root_srv_table(list, None, param, compute, false) {
  1467. return false;
  1468. }
  1469. continue;
  1470. };
  1471. // The shader adds the bytes a raw view begins early by.
  1472. let biased = srv
  1473. && t.host.user_data.iter().any(|u| {
  1474. u.slot == slot
  1475. && u.root == RootType::Other(victory_shader::emit::USER_VIEW_BIAS)
  1476. });
  1477. if tabled {
  1478. if !self.root_srv_table(list, Some(address), param, compute, biased) {
  1479. return false;
  1480. }
  1481. continue;
  1482. }
  1483. let Some(mut gpu) = root_view(list, address, srv) else {
  1484. continue;
  1485. };
  1486. if biased {
  1487. gpu -= u64::from(self.host_word(
  1488. compute,
  1489. victory_shader::emit::USER_VIEW_BIAS,
  1490. slot,
  1491. 0,
  1492. None,
  1493. ));
  1494. }
  1495. // SAFETY: an open list; the address is in live memory.
  1496. unsafe {
  1497. match (compute, srv) {
  1498. (false, false) => l.SetGraphicsRootConstantBufferView(param, gpu),
  1499. (false, true) => l.SetGraphicsRootShaderResourceView(param, gpu),
  1500. (true, false) => l.SetComputeRootConstantBufferView(param, gpu),
  1501. (true, true) => l.SetComputeRootShaderResourceView(param, gpu),
  1502. }
  1503. }
  1504. }
  1505. }
  1506. for &(slot, param) in &stage.root_uavs {
  1507. if slot == victory_shader::emit::SLOT_FAULTS {
  1508. // Ours: where shaders note the pages they found empty.
  1509. if let Some(m) = &memory {
  1510. // SAFETY: an open list; the buffer lives as long as
  1511. // the process and the list holds it.
  1512. unsafe {
  1513. if compute {
  1514. l.SetComputeRootUnorderedAccessView(param, m.faults);
  1515. } else {
  1516. l.SetGraphicsRootUnorderedAccessView(param, m.faults);
  1517. }
  1518. }
  1519. }
  1520. continue;
  1521. }
  1522. let address = match self.roots_ref(compute).get(usize::from(slot)) {
  1523. Some(&Root::View(address)) => Some(address),
  1524. _ => {
  1525. once!(slot, "a shader writes through a root view the title did not set");
  1526. None
  1527. }
  1528. };
  1529. if !self.root_uav(list, address, param, compute, writes) {
  1530. return false;
  1531. }
  1532. }
  1533. }
  1534. // Depth textures it writes through unordered access: their colour
  1535. // twins hold what they lack from here on.
  1536. list.twins_written();
  1537. true
  1538. }
  1539. /// Binds a root UAV: a raw unordered access view of the title buffer's
  1540. /// host copy from `address` on, as a one-view table (a null view
  1541. /// without an address, without a host copy shaders can write, or at an
  1542. /// address not on 16 bytes), or as a root descriptor with
  1543. /// `VICTORY_ROOT_SRV_DIRECT=1` (the dispatch is dropped then if there
  1544. /// is nothing to bind). With `writes`, what the shader stored is copied
  1545. /// back into title memory when the list has run. False if the draw
  1546. /// must be dropped.
  1547. /// shortcut: a root view has no size: the view, the refresh and the
  1548. /// copy back cover all that is left of the title's buffer
  1549. /// (`VICTORY_ROOT_UAV_MB` sets a limit for all three).
  1550. fn root_uav(
  1551. &mut self,
  1552. list: &HostList,
  1553. address: Option<u64>,
  1554. param: u32,
  1555. compute: bool,
  1556. writes: bool,
  1557. ) -> bool {
  1558. const UNORDERED: i32 = D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS.0;
  1559. static LIMIT: std::sync::OnceLock<u64> = std::sync::OnceLock::new();
  1560. let limit = *LIMIT.get_or_init(|| {
  1561. std::env::var("VICTORY_ROOT_UAV_MB")
  1562. .ok()
  1563. .and_then(|v| v.parse::<u64>().ok())
  1564. .map_or(u64::MAX, |mb| mb << 20)
  1565. });
  1566. let find = |a: u64| {
  1567. let s = crate::shadow::find(a, 1)?;
  1568. // SAFETY: a live buffer.
  1569. let flags = unsafe { s.buffer.GetDesc() }.Flags;
  1570. if flags.0 & UNORDERED == 0 {
  1571. once!("a root UAV of a buffer whose host copy shaders cannot write");
  1572. return None;
  1573. }
  1574. Some(s)
  1575. };
  1576. let ready = |a: u64, s: &std::sync::Arc<crate::shadow::Shadow>| {
  1577. let len = s.left(a).min(limit);
  1578. s.refresh(list, a, len);
  1579. if writes {
  1580. #[cfg(feature = "diagnostics")]
  1581. crate::host::wide_write(a, len, self.pipeline);
  1582. s.gpu_writes(list, a, len);
  1583. }
  1584. };
  1585. if !crate::pipeline::host::bounded_root_srvs() {
  1586. let Some((a, s)) = address.and_then(|a| Some((a, find(a)?))) else {
  1587. once!("a root UAV with nothing to bind: the draw is dropped");
  1588. return false;
  1589. };
  1590. ready(a, &s);
  1591. // From the 16 bytes below: the shader adds the rest.
  1592. // SAFETY: a live buffer.
  1593. let base = unsafe { s.buffer.GetGPUVirtualAddress() };
  1594. let gpu = base + ((s.gpu(a) - base) & !15);
  1595. // SAFETY: an open list; the address is in a live buffer.
  1596. unsafe {
  1597. if compute {
  1598. list.list.SetComputeRootUnorderedAccessView(param, gpu);
  1599. } else {
  1600. list.list.SetGraphicsRootUnorderedAccessView(param, gpu);
  1601. }
  1602. }
  1603. return true;
  1604. }
  1605. let heap = match self.heaps[0] {
  1606. 0 => None,
  1607. h => Some(crate::descriptor::heap(h as This)),
  1608. };
  1609. let Some((heap, host)) = heap.and_then(|h| Some((h, h.host()?))) else {
  1610. once!("a root UAV without a bound view heap: the draw is dropped");
  1611. return false;
  1612. };
  1613. let key = (std::ptr::from_ref(heap) as usize, address.unwrap_or(0));
  1614. let (index, shadow) = match self.root_uav_slots.get(&key) {
  1615. Some((index, shadow)) => (*index, address.zip(shadow.clone())),
  1616. None => {
  1617. let shadow = address.and_then(|a| find(a).map(|s| (a, s)));
  1618. let Some(index) = host.dynamic(1) else {
  1619. return false;
  1620. };
  1621. self.dynamic.push((key.0, index, 1));
  1622. if let Some((a, s)) = &shadow {
  1623. // SAFETY: a live buffer.
  1624. let base = unsafe { s.buffer.GetGPUVirtualAddress() };
  1625. let offset = s.gpu(*a) - base;
  1626. // Raw views start on 16 bytes: from the 16 bytes
  1627. // below, and the shader adds the rest to its offsets
  1628. // (`victory_shader::emit::USER_VIEW_BIAS`). (An address
  1629. // not on 16 bytes got a null view at first: the
  1630. // builder's counters are at such addresses.)
  1631. let bias = offset & 15;
  1632. host.raw_uav_at(index, &s.buffer, offset - bias, s.left(*a).min(limit) + bias);
  1633. }
  1634. if shadow.is_none() {
  1635. host.null_raw_uav_at(index);
  1636. }
  1637. self.root_uav_slots
  1638. .insert(key, (index, shadow.as_ref().map(|(_, s)| s.clone())));
  1639. (index, shadow)
  1640. }
  1641. };
  1642. if let Some((a, s)) = &shadow {
  1643. ready(*a, s);
  1644. }
  1645. let handle = host.gpu_handle(index);
  1646. // SAFETY: an open list; the slot is in the bound view heap.
  1647. unsafe {
  1648. if compute {
  1649. list.list.SetComputeRootDescriptorTable(param, handle);
  1650. } else {
  1651. list.list.SetGraphicsRootDescriptorTable(param, handle);
  1652. }
  1653. }
  1654. true
  1655. }
  1656. /// Binds a root SRV as a one-view table
  1657. /// ([`crate::pipeline::host::bounded_root_srvs`]): a raw view of the
  1658. /// title buffer's host copy from `address` to the copy's end, or a null
  1659. /// view (no address, no host copy, or an address not on 16 bytes). One
  1660. /// dynamic slot per address per list, given back with the list's
  1661. /// others. False if no slot could be had or no view heap is bound.
  1662. fn root_srv_table(
  1663. &mut self,
  1664. list: &HostList,
  1665. address: Option<u64>,
  1666. param: u32,
  1667. compute: bool,
  1668. biased: bool,
  1669. ) -> bool {
  1670. let heap = match self.heaps[0] {
  1671. 0 => None,
  1672. h => Some(crate::descriptor::heap(h as This)),
  1673. };
  1674. let Some((heap, host)) = heap.and_then(|h| Some((h, h.host()?))) else {
  1675. once!("a root SRV without a bound view heap: the draw is dropped");
  1676. return false;
  1677. };
  1678. // A view that begins early is another view than one that does not
  1679. // (title addresses stay below bit 63).
  1680. let key = (
  1681. std::ptr::from_ref(heap) as usize,
  1682. address.unwrap_or(0) | u64::from(biased) << 63,
  1683. );
  1684. let (index, shadow) = match self.root_srv_slots.get(&key) {
  1685. Some((index, shadow)) => (*index, address.zip(shadow.clone())),
  1686. None => {
  1687. let shadow = address.and_then(|a| crate::shadow::find(a, 1).map(|s| (a, s)));
  1688. let Some(index) = host.dynamic(1) else {
  1689. return false;
  1690. };
  1691. self.dynamic.push((key.0, index, 1));
  1692. self.root_srv_slots
  1693. .insert(key, (index, shadow.as_ref().map(|(_, s)| s.clone())));
  1694. match &shadow {
  1695. Some((a, s)) => {
  1696. // SAFETY: a live buffer.
  1697. let base = unsafe { s.buffer.GetGPUVirtualAddress() };
  1698. let offset = s.gpu(*a) - base;
  1699. if biased {
  1700. // From the 16 bytes below; the shader adds the
  1701. // rest (`victory_shader::emit::USER_VIEW_BIAS`).
  1702. let bias = offset & 15;
  1703. host.raw_at(index, &s.buffer, offset - bias, s.left(*a) + bias);
  1704. } else if offset.is_multiple_of(16) {
  1705. host.raw_at(index, &s.buffer, offset, s.left(*a));
  1706. } else {
  1707. // Raw views start on 16 bytes; one from the
  1708. // aligned start would shift every read.
  1709. once!(
  1710. address = format_args!("{a:#x}"),
  1711. "a root SRV not on 16 bytes reads zeros"
  1712. );
  1713. host.null_raw_at(index);
  1714. }
  1715. }
  1716. None => host.null_raw_at(index),
  1717. }
  1718. (index, shadow)
  1719. }
  1720. };
  1721. // As for root descriptors (`root_view`): all that is left of the
  1722. // buffer is brought up to date. The first 1 MiB only left what lay
  1723. // past it stale (most mesh vertex streams reach further).
  1724. if let Some((a, s)) = &shadow {
  1725. s.refresh(list, *a, s.left(*a));
  1726. }
  1727. let handle = host.gpu_handle(index);
  1728. // SAFETY: an open list; the slot is in the bound view heap.
  1729. unsafe {
  1730. if compute {
  1731. list.list.SetComputeRootDescriptorTable(param, handle);
  1732. } else {
  1733. list.list.SetGraphicsRootDescriptorTable(param, handle);
  1734. }
  1735. }
  1736. true
  1737. }
  1738. /// For a shader that picks buffers from the view heap by an index it
  1739. /// computes (SM 6.6 dynamic resources): the GPU address of the heap's
  1740. /// table of element strides, with every buffer view of the heap given
  1741. /// its host slot and its memory brought up to date when `list` is
  1742. /// submitted. Tables tell us which views a draw reads; nothing tells
  1743. /// us which of the heap's a computed index names, so all of them are
  1744. /// made ready, once per list.
  1745. /// shortcut: the buffers are read, not written: what such a shader
  1746. /// writes through a picked unordered access view stays in the host
  1747. /// copy. A list refreshes them where it first runs such a shader;
  1748. /// title writes recorded later in the same list are not seen.
  1749. fn heap_buffers(&self, list: &HostList) -> Option<u64> {
  1750. let heap = self
  1751. .heaps
  1752. .iter()
  1753. .filter(|&&h| h != 0)
  1754. .map(|&h| crate::descriptor::heap(h as This))
  1755. .find(|h| !h.samplers())?;
  1756. let host = heap.host()?;
  1757. let gpu = host.strides_gpu()?;
  1758. // One key per list, as textures have: no title resource is there.
  1759. const ONCE: usize = usize::MAX - 0x5e;
  1760. if !list.first_use(ONCE) {
  1761. return Some(gpu);
  1762. }
  1763. // The list may outlive the title's heap object, which owns the table.
  1764. if let Some(buffer) = host.strides_buffer() {
  1765. list.keep(buffer);
  1766. }
  1767. // The pass itself once per frame: per list it ran up to 51 times a
  1768. // frame over 81,000 views and 4,100 host copies, 18 s of every
  1769. // frame (2026-11-24, run 11).
  1770. // shortcut: what the title writes into such buffers between lists
  1771. // of one frame is seen a frame late.
  1772. static FRAME: AtomicU64 = AtomicU64::new(u64::MAX);
  1773. let frame = crate::frame::current();
  1774. if FRAME.swap(frame, Ordering::Relaxed) == frame {
  1775. return Some(gpu);
  1776. }
  1777. let started = std::time::Instant::now();
  1778. let mut stage = crate::timeline::span("the heap pass: begun, or done here");
  1779. if crate::host::aside::on() {
  1780. let at = std::ptr::from_ref(heap) as usize;
  1781. list.refreshes_coming(move || {
  1782. crate::descriptor::with_heap(at, |heap| heap.host().map(|host| heap_buffer_pass(heap, host, frame)))
  1783. .flatten()
  1784. .unwrap_or_default()
  1785. });
  1786. } else {
  1787. for (shadow, from, to) in heap_buffer_pass(heap, host, frame) {
  1788. shadow.refresh(list, from, to - from);
  1789. }
  1790. }
  1791. #[cfg(feature = "diagnostics")]
  1792. let refreshed = std::time::Instant::now();
  1793. stage.next("the heap pass: textures");
  1794. self.heap_textures(list, heap, host);
  1795. stage.end();
  1796. #[cfg(feature = "diagnostics")]
  1797. HEAP_SPLIT[2].fetch_add(refreshed.elapsed().as_nanos() as u64, Ordering::Relaxed);
  1798. HEAP_BUFFER_PASSES.fetch_add(1, Ordering::Relaxed);
  1799. HEAP_BUFFER_MICROS.fetch_add(started.elapsed().as_micros() as u64, Ordering::Relaxed);
  1800. Some(gpu)
  1801. }
  1802. /// Runs the pass that uploads textures picked by index
  1803. /// ([`State::heap_textures`]) where nothing has asked for it yet
  1804. /// ([`early_budgets`]): once a frame for a few milliseconds, at the
  1805. /// frame's first draw with a view heap set, and with a larger budget
  1806. /// of its own before every draw whose pixel shader is one of the
  1807. /// title's bake programs. The uploads are recorded into `list` ahead
  1808. /// of the draw being bound, as the world's pass records them.
  1809. fn early_textures(&self, list: &HostList, p: &HostPipeline, compute: bool) {
  1810. let (early_ms, bake_ms) = early_budgets();
  1811. if compute || (early_ms == 0 && bake_ms == 0) {
  1812. return;
  1813. }
  1814. let bake = bake_ms > 0
  1815. && p.stages.iter().any(|s| BAKE_PIXEL_SHADERS.contains(&s.shader.hash.as_str()));
  1816. static FRAME: AtomicU64 = AtomicU64::new(u64::MAX);
  1817. // The milliseconds this frame's bake draws have taken so far: a
  1818. // frame has several, and together they get `bake_ms`.
  1819. static BAKED_MS: AtomicU64 = AtomicU64::new(0);
  1820. let frame = crate::frame::current();
  1821. let first = FRAME.swap(frame, Ordering::Relaxed) != frame;
  1822. if first {
  1823. BAKED_MS.store(0, Ordering::Relaxed);
  1824. }
  1825. let left = bake_ms.saturating_sub(BAKED_MS.load(Ordering::Relaxed));
  1826. let budget = if bake && left > 0 {
  1827. // What a bake may read must be there now: up to 2 GiB.
  1828. (left, 2 << 30)
  1829. } else if first && early_ms > 0 {
  1830. (early_ms, 64 << 20)
  1831. } else {
  1832. return;
  1833. };
  1834. let Some(heap) = self
  1835. .heaps
  1836. .iter()
  1837. .filter(|&&h| h != 0)
  1838. .map(|&h| crate::descriptor::heap(h as This))
  1839. .find(|h| !h.samplers())
  1840. else {
  1841. return;
  1842. };
  1843. let Some(host) = heap.host() else {
  1844. return;
  1845. };
  1846. let bake = bake && left > 0;
  1847. if bake && !first && bake_exact() {
  1848. let (writes, noted) = host.texture_news();
  1849. if !noted && BAKE_SERVED.load(Ordering::Relaxed) == writes + 1 {
  1850. return;
  1851. }
  1852. }
  1853. let n = EARLY_TEXTURE_PASSES[usize::from(bake)].fetch_add(1, Ordering::Relaxed) + 1;
  1854. if bake && n.is_power_of_two() {
  1855. let [slots, due, ..] = HEAP_TEXTURES_QUEUE.each_ref().map(|c| c.load(Ordering::Relaxed));
  1856. tracing::info!(
  1857. frame,
  1858. bakes = n,
  1859. queued_at_the_last_pass = slots,
  1860. due_at_the_last_pass = due,
  1861. uploaded_so_far = HEAP_TEXTURES.load(Ordering::Relaxed),
  1862. "a draw of the title's decoration bake: textures picked by index are uploaded first (VICTORY_BAKE_TEXTURES_MS=0: not)"
  1863. );
  1864. }
  1865. let began = std::time::Instant::now();
  1866. PASS_BUDGET.set(Some(budget));
  1867. crate::texture::BAKING.set(bake && bake_exact());
  1868. self.heap_textures(list, heap, host);
  1869. crate::texture::BAKING.set(false);
  1870. PASS_BUDGET.set(None);
  1871. if bake {
  1872. BAKED_MS.fetch_add(began.elapsed().as_millis() as u64, Ordering::Relaxed);
  1873. }
  1874. }
  1875. /// The queue's side of the card accounting line
  1876. /// (`crate::resource::card_accounting`, which says what the line
  1877. /// holds): the slots that are due, by what their texture has on the
  1878. /// card. Off unless `VICTORY_CARD_ACCOUNTING=1`; then at the first pass
  1879. /// that finds the card without room, and every five seconds after it.
  1880. /// Nothing is made, uploaded or counted as used here. For 18,000 due
  1881. /// slots: 18,000 looks at a title slot and at the texture it views, a
  1882. /// lock each, some milliseconds of the thread that records the frame.
  1883. fn card_accounting(
  1884. heap: &crate::descriptor::Heap,
  1885. host: &crate::descriptor::host::HostHeap,
  1886. frame: u64,
  1887. room: bool,
  1888. ) {
  1889. static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
  1890. if !*ON.get_or_init(|| std::env::var_os("VICTORY_CARD_ACCOUNTING").is_some_and(|v| v == "1")) {
  1891. return;
  1892. }
  1893. // When the next line is due (0: none yet, the card has had room).
  1894. static NEXT: AtomicU64 = AtomicU64::new(0);
  1895. let now = crate::host::now_ms().max(1);
  1896. let next = NEXT.load(Ordering::Relaxed);
  1897. // (With levels on demand the card may never be without room: the
  1898. // lines then start with the first texture made that way.)
  1899. let by_level = crate::tiles::STATS[4].load(Ordering::Relaxed) > 0;
  1900. let due_now = if next == 0 { !room || by_level } else { now >= next };
  1901. if !due_now || NEXT.compare_exchange(next, now + 5000, Ordering::Relaxed, Ordering::Relaxed).is_err() {
  1902. return;
  1903. }
  1904. // Due slots; of them uploaded before; of them viewing nothing the
  1905. // title fills; and the textures (each once) whose host copy is
  1906. // alive, with their bytes on the card.
  1907. let mut due = [0u64; 5];
  1908. // Textures (each once) that never had a host copy, and ones whose
  1909. // host copy was let go: where their memory is, and its bytes.
  1910. let (mut never, mut gone) = (Vec::new(), Vec::new());
  1911. let mut seen = std::collections::BTreeSet::new();
  1912. for (index, uploaded) in host.texture_slots_all_due(frame) {
  1913. due[0] += 1;
  1914. due[1] += u64::from(uploaded);
  1915. let state = match heap.handle(index).and_then(crate::descriptor::view) {
  1916. Some(View::Placed(false, resource, desc)) if resource[0] != 1 => {
  1917. let address = u64::from(desc[10]) | u64::from(desc[11]) << 32;
  1918. match crate::resource::placed_known(address, &resource) {
  1919. Some(texture) => crate::resource::copy_state(texture),
  1920. // No title texture was made for it: the pass never
  1921. // got as far as making one.
  1922. None => Some((0, crate::resource::placed_bytes(&resource).unwrap_or(0), address)),
  1923. }
  1924. }
  1925. Some(View::Shader(object, _)) if crate::resource::title_fills(object as This) => {
  1926. crate::resource::copy_state(object as This)
  1927. }
  1928. _ => None,
  1929. };
  1930. let Some((state, bytes, memory)) = state else {
  1931. due[2] += 1;
  1932. continue;
  1933. };
  1934. if !seen.insert(memory) {
  1935. continue;
  1936. }
  1937. match state {
  1938. 2 => {
  1939. due[3] += 1;
  1940. due[4] += bytes;
  1941. }
  1942. 1 => gone.push((memory, bytes)),
  1943. _ => never.push((memory, bytes)),
  1944. }
  1945. }
  1946. crate::resource::card_accounting(room, due, never, gone);
  1947. }
  1948. /// The texture side of [`State::heap_buffers`]: textures the title fills
  1949. /// itself (streamed pages, layout-library copies) whose views sit in the
  1950. /// view heap are created (placed textures have no host texture until
  1951. /// something reads them) and uploaded, as a table read would do, for
  1952. /// shaders that pick them by a computed index. Within a budget of bytes
  1953. /// per frame and in all; the rest waits for later lists and frames.
  1954. /// The most recently written slots first (`TextureQueue::due`); slots
  1955. /// draws read through tables are not in the queue.
  1956. /// shortcut: uploaded once, and again only when the title rewrites the
  1957. /// slot. A placed texture not all mapped yet is uploaded with what is
  1958. /// there and looked at again (1, 2, 4, ... frames later, at most about
  1959. /// a second): uploaded again when more of it is mapped. Pages mapped
  1960. /// in place of others, and contents changed with no descriptor write,
  1961. /// are missed (hook the page-mapping events for those).
  1962. /// `VICTORY_HEAP_TEXTURES=0` turns it off.
  1963. fn heap_textures(
  1964. &self,
  1965. list: &HostList,
  1966. heap: &crate::descriptor::Heap,
  1967. host: &crate::descriptor::host::HostHeap,
  1968. ) {
  1969. static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
  1970. if !*ON.get_or_init(|| std::env::var_os("VICTORY_HEAP_TEXTURES").is_none_or(|v| v != "0")) {
  1971. return;
  1972. }
  1973. let memory = crate::host::host().and_then(|h| h.video_memory());
  1974. // `VICTORY_TEXTURE_STAGE_MB` sets it: a backlog of tens of thousands of
  1975. // textures (a scene's first minutes) then drains in fewer frames.
  1976. static PER_FRAME_MB: std::sync::OnceLock<Option<u64>> = std::sync::OnceLock::new();
  1977. let asked = *PER_FRAME_MB.get_or_init(|| {
  1978. std::env::var("VICTORY_TEXTURE_STAGE_MB").ok().and_then(|v| v.trim().parse::<u64>().ok())
  1979. });
  1980. let per_frame = match asked {
  1981. Some(mb) => mb << 20,
  1982. None => staging_budget_per_frame(memory.map(|[budget, ..]| budget)),
  1983. };
  1984. static FRAME: AtomicU64 = AtomicU64::new(u64::MAX);
  1985. static SPENT: AtomicU64 = AtomicU64::new(0);
  1986. let frame = crate::frame::current();
  1987. if FRAME.swap(frame, Ordering::Relaxed) != frame {
  1988. SPENT.store(0, Ordering::Relaxed);
  1989. }
  1990. // No more of them are made while the card has no room
  1991. // (`resource::room`): by what is alive now, not by what was ever
  1992. // staged (4 GB in all, after which later textures stayed empty for
  1993. // the run). The ones nothing names any more are let go, which
  1994. // makes room again: so the slots are still looked at (the pass
  1995. // returned here, and a slot whose texture had been streamed out
  1996. // kept its host copy for as long as the card was full).
  1997. let mut room = crate::resource::room(memory);
  1998. // Bytes uploaded by this pass since the card was last asked
  1999. // whether it has room: asked again every 32 MiB (a pass may upload
  2000. // 192 MB and more, and one asking a pass let the queue run some
  2001. // 400 MB past its line while the world loaded: run 193).
  2002. let mut since_asked = 0u64;
  2003. if !room {
  2004. HEAP_TEXTURES_FULL.fetch_add(1, Ordering::Relaxed);
  2005. once!("textures picked by index: the card has no room for more; they wait");
  2006. }
  2007. let mut refused = 0;
  2008. // Room again: the slots held back while the card was full are due
  2009. // now (`full_card_pass`).
  2010. if room {
  2011. host.texture_slots_room(frame);
  2012. }
  2013. // Slots whose texture's memory the runtime mapped, unmapped or
  2014. // wrote since the last pass are due again.
  2015. host.texture_slots_remapped(frame);
  2016. host.texture_slots_short(frame);
  2017. // The slots of textures whose first level with memory (levels on
  2018. // demand), or whose host copy for one with more levels, changed since
  2019. // the last pass are made again from it; those whose new view's upload
  2020. // has run are made from that.
  2021. host.texture_views_remade();
  2022. host.texture_slots_flip();
  2023. // And with room, the textures whose upload left a held level
  2024. // without the card's memory are uploaded again.
  2025. if room {
  2026. host.texture_slots_waiting(frame);
  2027. }
  2028. let baking = crate::texture::BAKING.get();
  2029. let (mut due, census) = host.texture_slots_due(frame, if baking { 1 << 16 } else { 4096 });
  2030. // (Those that are due later after all that are due.)
  2031. let on_time = due.len();
  2032. if baking {
  2033. let known: std::collections::HashSet<u32> = due.iter().map(|&(index, _)| index).collect();
  2034. static AHEAD: AtomicU64 = AtomicU64::new(u64::MAX);
  2035. let again = AHEAD.swap(frame, Ordering::Relaxed) == frame;
  2036. let (ahead, _) = host.texture_slots_due(frame + BAKE_AHEAD[usize::from(again)], 1 << 16);
  2037. due.extend(ahead.into_iter().filter(|(index, _)| !known.contains(index)));
  2038. }
  2039. HEAP_TEXTURES_WAITING.store(census[0], Ordering::Relaxed);
  2040. for (count, now) in HEAP_TEXTURES_QUEUE.iter().zip(census) {
  2041. count.store(now, Ordering::Relaxed);
  2042. }
  2043. // Where the card's memory is, and what the due slots would need
  2044. // (`VICTORY_CARD_ACCOUNTING=1`; a line when the card first has no
  2045. // room, and every five seconds after it).
  2046. Self::card_accounting(heap, host, frame, room);
  2047. // The frames in about four seconds, between 16 and 256: how long a
  2048. // slot with nothing to upload waits at most for its next look. In
  2049. // frames alone it was 120: four minutes at the opening cutscene's
  2050. // half a frame per second, while the title streams by the clock.
  2051. // (About a second before the runtime told of the memory it maps:
  2052. // the looks are now only for what that does not tell.)
  2053. static PASSED: AtomicU64 = AtomicU64::new(0);
  2054. let now = crate::host::now_ms();
  2055. let took = now.saturating_sub(PASSED.swap(now, Ordering::Relaxed)).max(1);
  2056. let most = (4000 / took).clamp(16, 256);
  2057. // What a table entry of a texture a shader samples says.
  2058. let sampled = UsedResource {
  2059. kind: ResourceType::Srv,
  2060. root: RootType::Table,
  2061. table_offset_dwords: 0,
  2062. lower_bound: 0,
  2063. stride: 0,
  2064. dwords: 8,
  2065. user_data: 0,
  2066. slot: 0,
  2067. };
  2068. // Also within a time per pass: the pass runs on a thread that
  2069. // records the frame, and making and staging 192 MB of textures took
  2070. // 1.6-2.2 s of each of the world's first twenty frames (run 20).
  2071. // The rest waits for the next frames, as it does past the bytes.
  2072. static SPAN_MS: std::sync::OnceLock<u64> = std::sync::OnceLock::new();
  2073. let span = std::time::Duration::from_millis(*SPAN_MS.get_or_init(|| {
  2074. std::env::var("VICTORY_TEXTURE_STAGE_MS").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(250)
  2075. }));
  2076. // A backlog (a scene's first minutes: 22,000 slots due, 2-3 minutes of black
  2077. // surfaces at 192 MB a frame) gets three times the bytes and the time until it
  2078. // drains; `VICTORY_TEXTURE_CATCHUP=0` keeps the plain budget.
  2079. static CATCHUP: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
  2080. let catchup = *CATCHUP.get_or_init(|| std::env::var_os("VICTORY_TEXTURE_CATCHUP").is_none_or(|v| v != "0"));
  2081. let (per_frame, span) = if catchup && on_time >= 1024 { (per_frame * 3, span * 3) } else { (per_frame, span) };
  2082. // A run made early (`State::early_textures`) has a budget of its
  2083. // own: its bytes on top of what the frame has spent so far.
  2084. // (Not `most`: that is the longest wait between looks, used below.)
  2085. let (span, bytes_at_most) = match PASS_BUDGET.get() {
  2086. Some((ms, bytes)) => {
  2087. (std::time::Duration::from_millis(ms), SPENT.load(Ordering::Relaxed).saturating_add(bytes))
  2088. }
  2089. None => (span, per_frame),
  2090. };
  2091. let began = std::time::Instant::now();
  2092. BAKE_SERVED.store(0, Ordering::Relaxed);
  2093. let mut served = true;
  2094. for (index, write) in due {
  2095. if SPENT.load(Ordering::Relaxed) >= bytes_at_most || began.elapsed() > span {
  2096. served = false;
  2097. break;
  2098. }
  2099. // A placed texture whose memory is not mapped (not streamed in
  2100. // yet, or streamed out again: the heap keeps tens of thousands
  2101. // of such views) gets no host texture; looked at again soon (a
  2102. // title writes a texture's view before its pages are mapped,
  2103. // and the pass runs early in a frame). One of which some is
  2104. // mapped (a texture streaming in: its smaller mips lie at the
  2105. // start of its memory and arrive first) is uploaded with what
  2106. // is there, and again when more is. (It was uploaded again
  2107. // every 120 frames, changed or not; and asked by its first
  2108. // page alone, one whose first page is the one missing counted
  2109. // as not there.)
  2110. // A slot uploaded whole is looked at again a few times
  2111. // (`RECHECK_FRAMES`): the title writes a texture's view, and
  2112. // may fill the texture's memory itself only afterwards, with
  2113. // no descriptor write and nothing from the runtime to tell of
  2114. // it. The host copy then kept what the memory held at the
  2115. // first look for the rest of the run. The look reads 48 KiB;
  2116. // only a changed texture is uploaded again.
  2117. // `VICTORY_HEAP_RECHECK=0`: uploaded once, as before.
  2118. // One found changed by such a look is looked at in the next frame
  2119. // again: the textures left that change unnoticed are ones the
  2120. // title paints all the time through another view of their pages
  2121. // (all their blocks are shown at other addresses too), and each
  2122. // was shown four frames late, over and over.
  2123. let mut again_in = RECHECK_FRAMES[0];
  2124. if let Some((at, len, print, looks, uploaded)) = host.texture_slot_checked(index) {
  2125. if crate::texture::fingerprint(at, len) == print {
  2126. HEAP_TEXTURES_RECHECKED[0].fetch_add(1, Ordering::Relaxed);
  2127. match RECHECK_FRAMES.get(usize::from(looks) + 1) {
  2128. Some(wait) => {
  2129. host.texture_slot_recheck(index, write, frame + wait, (at, len), print, looks + 1, uploaded)
  2130. }
  2131. None => host.texture_slot_done(index, write, None),
  2132. }
  2133. continue;
  2134. }
  2135. if recheck_soon() {
  2136. again_in = 1;
  2137. }
  2138. let n = HEAP_TEXTURES_RECHECKED[1].fetch_add(1, Ordering::Relaxed);
  2139. if n < 200 || n.is_multiple_of(1000) {
  2140. // Whether its pages are the title's at other addresses
  2141. // too: what is written there is told of there alone.
  2142. let elsewhere = crate::inplace::shown_elsewhere(at as usize & !0xffff, (at + len) as usize);
  2143. let first = heap.handle(index).and_then(crate::descriptor::view).map_or(0, |view| match view {
  2144. View::Placed(false, _, desc) => crate::resource::first_mip(&desc),
  2145. _ => 0,
  2146. });
  2147. tracing::warn!(
  2148. first_level = first,
  2149. blocks_shown_elsewhere = elsewhere.len(),
  2150. slot = index,
  2151. address = format_args!("{at:#x}"),
  2152. bytes = len,
  2153. frames_after_upload = frame.saturating_sub(uploaded),
  2154. looks,
  2155. changed = n + 1,
  2156. "a texture picked by index changed after its upload with nothing to tell of it: uploaded again"
  2157. );
  2158. }
  2159. }
  2160. let mut partly = None;
  2161. let mut there = None;
  2162. if let Some(View::Placed(false, resource, desc)) = heap.handle(index).and_then(crate::descriptor::view) {
  2163. let address = u64::from(desc[10]) | u64::from(desc[11]) << 32;
  2164. let first = crate::resource::first_mip(&desc);
  2165. let len = crate::resource::placed_bytes_from(&resource, first).unwrap_or(1);
  2166. let mapped = crate::texture::mapped_bytes(address as *const u8, len as usize);
  2167. if mapped == 0 {
  2168. HEAP_TEXTURES_AWAY.fetch_add(1, Ordering::Relaxed);
  2169. // Streamed out: what the slot showed is let go.
  2170. host.texture_slot_gone(index);
  2171. host.texture_slot_later(index, write, frame, most);
  2172. continue;
  2173. }
  2174. host.texture_slot_here(index);
  2175. there = Some(mapped);
  2176. if mapped < len {
  2177. if mapped <= host.texture_slot_mapped(index) {
  2178. HEAP_TEXTURES_PARTLY[0].fetch_add(1, Ordering::Relaxed);
  2179. host.texture_slot_later(index, write, frame, most);
  2180. continue;
  2181. }
  2182. if !crate::texture::committed(address as *const u8, 1) {
  2183. HEAP_TEXTURES_PARTLY[2].fetch_add(1, Ordering::Relaxed);
  2184. }
  2185. partly = Some(mapped);
  2186. }
  2187. }
  2188. // A texture object the host renders to or writes holds the
  2189. // host's own contents: nothing to bring up to date, and this
  2190. // pass is no use of it (its host copy is made when something
  2191. // uses it, and its slots then: `descriptor::make_waiting`).
  2192. if let Some(View::Shader(object, _)) = heap.handle(index).and_then(crate::descriptor::view)
  2193. && crate::resource::buffer_bytes(object as This).is_none()
  2194. && !crate::resource::title_fills(object as This)
  2195. {
  2196. host.texture_slot_done(index, write, None);
  2197. continue;
  2198. }
  2199. // From here on a host texture is made: not without room. The
  2200. // slot stays due.
  2201. // Not so a slot already made from this very view: its host
  2202. // texture exists, and uploading it again takes none of the
  2203. // card's memory. It was refused all the same, so a texture the
  2204. // title filled after its first upload kept its empty host copy
  2205. // from the moment the card reached the line, which is the first
  2206. // world frame in eight launches of nine: the same slots were
  2207. // found changed again at every pass and never uploaded (run
  2208. // 179: 33,000 such findings), and the main character's face
  2209. // had its colour only in the launches that entered the world
  2210. // under the line. `VICTORY_REUPLOAD_WHEN_FULL=0`: refused, as
  2211. // before.
  2212. if !room {
  2213. let has_its_texture = reupload_when_full()
  2214. && heap.handle(index).is_some_and(|handle| host.texture_slot_made_from(index, handle));
  2215. if !has_its_texture {
  2216. refused += 1;
  2217. if full_card_pass() {
  2218. // Held back for the frames of about four seconds
  2219. // (`most`), or until the card has room; the pass
  2220. // goes on, within a count that bounds one pass.
  2221. host.texture_slot_held(index, write, frame + most);
  2222. if refused > 1024 {
  2223. break;
  2224. }
  2225. } else if refused > 256 {
  2226. break;
  2227. }
  2228. continue;
  2229. }
  2230. let n = HEAP_TEXTURES_REUPLOADED_FULL.fetch_add(1, Ordering::Relaxed) + 1;
  2231. if n == 1 || n.is_multiple_of(500) {
  2232. tracing::info!(
  2233. so_far = n,
  2234. slot = index,
  2235. "a texture already on the card is brought up to date although the card has no room for new ones"
  2236. );
  2237. }
  2238. }
  2239. // A slot that shows the texture by an earlier view of it (one
  2240. // from another level) goes on doing so until the upload of what
  2241. // the new one shows has run.
  2242. let shows_other = !baking
  2243. && crate::resource::held_only()
  2244. && heap.handle(index).is_some_and(|handle| host.texture_slot_shows_other(index, handle));
  2245. // A slot that shows nothing of it yet, or something else, shows it
  2246. // when the upload has run too.
  2247. let late = !shows_other
  2248. && !baking
  2249. && crate::descriptor::host::show_after()
  2250. && heap.handle(index).is_some_and(|handle| !host.texture_slot_made_from(index, handle));
  2251. let view = heap.handle(index).and_then(|handle| {
  2252. if shows_other || late { crate::descriptor::view(handle) } else { host.mirror(index, handle, true) }
  2253. });
  2254. let at_once = || {
  2255. if late && let Some(handle) = heap.handle(index) {
  2256. let _ = host.mirror(index, handle, true);
  2257. }
  2258. };
  2259. let placed = view.as_ref().and_then(crate::descriptor::host::placed_texture);
  2260. let resource = match placed.as_ref().or(view.as_ref()) {
  2261. Some(&View::Shader(resource, _)) => resource as This,
  2262. _ => {
  2263. at_once();
  2264. host.texture_slot_done(index, write, None);
  2265. continue;
  2266. }
  2267. };
  2268. let texture = crate::resource::host_resource(resource);
  2269. let title_fills = texture.is_some_and(crate::texture::title_written);
  2270. if !title_fills {
  2271. at_once();
  2272. // a render target, a depth or unordered access texture: the host's own
  2273. host.texture_slot_done(index, write, None);
  2274. continue;
  2275. }
  2276. // A texture that has a staging buffer now is one draws read
  2277. // through a table: they upload it, and check it at every
  2278. // submission that samples it.
  2279. let tabled = crate::texture::is_staged(resource);
  2280. // The host copy holds these very bytes: nothing to upload.
  2281. let first = match (&placed, &view) {
  2282. (Some(_), Some(View::Placed(_, _, desc))) => crate::resource::first_mip(desc),
  2283. _ => 0,
  2284. };
  2285. let same = !tabled && crate::texture::unchanged(resource, first);
  2286. if same {
  2287. HEAP_TEXTURES_SAME.fetch_add(1, Ordering::Relaxed);
  2288. if shows_other && let Some(handle) = heap.handle(index) {
  2289. let _ = host.mirror(index, handle, true);
  2290. }
  2291. // Its bytes are in, or on the way there in a list before.
  2292. if late && texture.is_some_and(crate::pool::fresh) {
  2293. if let Some(handle) = heap.handle(index) {
  2294. host.texture_slot_show_after(list, index, handle);
  2295. }
  2296. } else {
  2297. at_once();
  2298. }
  2299. let again = partly.map(|mapped| (frame + 1, mapped));
  2300. let memory = if again.is_none() && heap_recheck() { crate::texture::title_span(resource, first) } else { None };
  2301. match memory {
  2302. Some((at, len)) => {
  2303. let print = crate::texture::fingerprint(at, len);
  2304. host.texture_slot_recheck(index, write, frame + again_in, (at, len), print, 0, frame);
  2305. }
  2306. None => host.texture_slot_done(index, write, again),
  2307. }
  2308. continue;
  2309. }
  2310. if let Some(view) = &view {
  2311. // (What was found mapped of it a moment ago is not asked
  2312. // again, unless the host copy may need more.)
  2313. crate::texture::PICKING.set(Some(there.filter(|_| partly.is_none()).unwrap_or(u64::MAX)));
  2314. readable(list, sampled.kind, view);
  2315. crate::texture::PICKING.set(None);
  2316. }
  2317. if shows_other && let Some(handle) = heap.handle(index) {
  2318. host.texture_slot_flip(list, index, handle);
  2319. }
  2320. if late && let Some(handle) = heap.handle(index) {
  2321. host.texture_slot_show_after(list, index, handle);
  2322. }
  2323. #[cfg(feature = "diagnostics")]
  2324. if crate::book::on()
  2325. && let Some(texture) = texture.filter(|t| crate::pool::fresh(t))
  2326. {
  2327. use windows::core::Interface;
  2328. let raw = texture.as_raw() as usize;
  2329. let asked = crate::host::submissions();
  2330. list.defer_host(move || {
  2331. let (started, finished) = crate::host::submissions();
  2332. crate::book::note(raw, || {
  2333. format!(
  2334. "; upload for slot {index} recorded at submissions {asked:?}, sent as submission {started} (finished {finished}) at {:.3} s",
  2335. crate::host::now_ms() as f64 / 1e3
  2336. )
  2337. });
  2338. });
  2339. }
  2340. // A texture view the host refuses removes the device: name it.
  2341. static GONE: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
  2342. if !GONE.load(Ordering::Relaxed)
  2343. && let Some(why) = crate::descriptor::host::device_removed()
  2344. {
  2345. GONE.store(true, Ordering::Relaxed);
  2346. let text: String = format!("{view:?}").chars().take(300).collect();
  2347. tracing::error!(why, slot = index, "the host device went while textures picked by index were made ready; last: {text}");
  2348. crate::host::log_removal_context();
  2349. return;
  2350. }
  2351. let (bytes, whole) = crate::texture::staged(resource, there.is_none()).unwrap_or((0, true));
  2352. // Not all of it there: looked at again next frame, and from
  2353. // then on as a slot with nothing new (a placed texture: until
  2354. // more of it is mapped; a texture object at an address the
  2355. // title mapped: again in 120 frames, as before).
  2356. let again = match partly {
  2357. Some(mapped) => Some((frame + 1, mapped)),
  2358. None => (!whole).then_some((frame + 120, 0)),
  2359. };
  2360. if again.is_some() {
  2361. HEAP_TEXTURES_PARTLY[1].fetch_add(1, Ordering::Relaxed);
  2362. }
  2363. if tabled {
  2364. // Nothing was staged here, so nothing is counted or spent,
  2365. // and the staging buffer stays: taking it away made the
  2366. // next draw that reads the texture through a table stage,
  2367. // detile and upload all of it once more.
  2368. HEAP_TEXTURES_TABLED.fetch_add(1, Ordering::Relaxed);
  2369. host.texture_slot_done(index, write, again);
  2370. continue;
  2371. }
  2372. // Uploaded: the list holds the staging buffer until it has run;
  2373. // a table read, or the next look at a texture not all mapped
  2374. // yet, makes it anew. (Kept for those until now: every partly
  2375. // streamed texture of the heap held a staging buffer of its full
  2376. // size for good.)
  2377. let memory = if again.is_none() && heap_recheck() {
  2378. crate::texture::staged_memory(resource)
  2379. } else {
  2380. None
  2381. };
  2382. crate::texture::unstage(resource);
  2383. SPENT.fetch_add(bytes, Ordering::Relaxed);
  2384. since_asked += bytes;
  2385. if room && since_asked >= 32 << 20 {
  2386. since_asked = 0;
  2387. room = crate::resource::room(crate::host::host().and_then(|h| h.video_memory()));
  2388. }
  2389. HEAP_TEXTURE_BYTES.fetch_add(bytes, Ordering::Relaxed);
  2390. HEAP_TEXTURES.fetch_add(1, Ordering::Relaxed);
  2391. match memory {
  2392. // Whole and uploaded: looked at again (see above).
  2393. Some((at, len)) => {
  2394. let print = crate::texture::fingerprint(at, len);
  2395. host.texture_slot_recheck(index, write, frame + again_in, (at, len), print, 0, frame);
  2396. }
  2397. None => host.texture_slot_done(index, write, again),
  2398. }
  2399. }
  2400. if baking && served {
  2401. BAKE_SERVED.store(host.texture_news().0 + 1, Ordering::Relaxed);
  2402. }
  2403. }
  2404. /// For the frame listing, after a dropped dispatch's line: its group
  2405. /// counts and the compute root arguments it was recorded with (root
  2406. /// constants as hex dwords, root views with the title buffer they
  2407. /// point into). A program that does not translate has no bindings to
  2408. /// list; these say which memory it would have read and written (the
  2409. /// ray-tracing structure builder passes its buffers this way).
  2410. #[cfg(feature = "diagnostics")]
  2411. fn list_dropped_roots(&self, groups: [u32; 3]) {
  2412. crate::capture::op(0, || {
  2413. use std::fmt::Write;
  2414. let [x, y, z] = groups;
  2415. let mut text = format!(" its roots ({x}x{y}x{z}):");
  2416. for (slot, root) in self.compute.iter().enumerate() {
  2417. match root {
  2418. Root::None => {}
  2419. Root::Table(a) => {
  2420. let _ = write!(text, " {slot}=table {a:#x}");
  2421. }
  2422. Root::Constants(v) => {
  2423. let _ = write!(text, " {slot}=constants {:x?}", &v[..v.len().min(48)]);
  2424. }
  2425. Root::View(a) => {
  2426. let _ = write!(text, " {slot}=view {a:#x}");
  2427. match crate::shadow::extent(*a) {
  2428. Some((start, len)) => {
  2429. let _ = write!(text, " in buffer {start:#x}+{len:#x}");
  2430. }
  2431. None => text.push_str(" in no buffer"),
  2432. }
  2433. }
  2434. }
  2435. }
  2436. text
  2437. });
  2438. }
  2439. /// Runs a dispatch on the host.
  2440. pub(crate) fn dispatch(&mut self, list: &HostList, x: u32, y: u32, z: u32, flags: u32) {
  2441. // It may write the arguments a window holds clamped.
  2442. self.window = None;
  2443. #[cfg(feature = "diagnostics")]
  2444. if crate::pipeline::is_skipped(self.pipeline as This) {
  2445. DROPPED.fetch_add(1, Ordering::Relaxed);
  2446. crate::pipeline::note_drop(self.pipeline as This);
  2447. return;
  2448. }
  2449. // The ray-tracing structure builder's stages run all or none.
  2450. if crate::pipeline::is_builder(self.pipeline as This) && !crate::pipeline::builder_runs() {
  2451. DROPPED.fetch_add(1, Ordering::Relaxed);
  2452. #[cfg(feature = "diagnostics")]
  2453. {
  2454. crate::pipeline::note_why("a stage of the ray-tracing structure builder, which is off".to_owned());
  2455. self.list_dropped_roots([x, y, z]);
  2456. }
  2457. return;
  2458. }
  2459. let Some(p) = crate::pipeline::host_pipeline(self.pipeline as This) else {
  2460. once!(
  2461. pipeline = format_args!("{:#x}", self.pipeline),
  2462. "a dispatch without a host pipeline dropped"
  2463. );
  2464. DROPPED.fetch_add(1, Ordering::Relaxed);
  2465. #[cfg(feature = "diagnostics")]
  2466. {
  2467. crate::pipeline::note_drop(self.pipeline as This);
  2468. self.list_dropped_roots([x, y, z]);
  2469. }
  2470. return;
  2471. };
  2472. if !p.compute {
  2473. once!("a dispatch with a graphics pipeline");
  2474. return;
  2475. }
  2476. if !self.bind(list, p, true) {
  2477. DROPPED.fetch_add(1, Ordering::Relaxed);
  2478. // A stage of the structure builder that cannot be bound is a
  2479. // dropped stage: the others stop too.
  2480. if crate::pipeline::is_builder(self.pipeline as This) {
  2481. crate::pipeline::builder_rests("one of its dispatches could not be bound");
  2482. }
  2483. return;
  2484. }
  2485. #[cfg(feature = "diagnostics")]
  2486. list.note_op(|| self.op_text(format!("dispatch {x}x{y}x{z}"), true));
  2487. #[cfg(feature = "diagnostics")]
  2488. if crate::pipeline::is_builder(self.pipeline as This) {
  2489. crate::capture::op(list as *const _ as usize, || format!("builder {}", p.name));
  2490. self.list_dropped_roots([x, y, z]);
  2491. }
  2492. // Counted in threads: whole groups of them, and the program is told
  2493. // how many of the last one run, where it asks (its `bind` set that to
  2494. // all of them).
  2495. let size = (flags & THREAD_DIMENSIONS != 0 && thread_dimensions())
  2496. .then(|| p.stages.first().and_then(|s| s.translated().threads))
  2497. .flatten();
  2498. let threads = [x, y, z];
  2499. let [x, y, z] = size.map_or(threads, |size| dispatch_groups(threads, size));
  2500. if size.is_some() {
  2501. if !crate::pipeline::is_builder(self.pipeline as This) {
  2502. once!(pipeline = p.name, "a dispatch counted in threads that is not the structure builder's");
  2503. }
  2504. if let Some((param, word)) = compute_word(p, victory_shader::emit::USER_DISPATCH_THREADS_X) {
  2505. // SAFETY: an open list; the root signature has the word.
  2506. unsafe { list.list.SetComputeRoot32BitConstant(param, threads[0], word) };
  2507. }
  2508. }
  2509. // SAFETY: an open list with everything set.
  2510. unsafe { list.list.Dispatch(x, y, z) };
  2511. self.buffers_written();
  2512. DISPATCHED.fetch_add(1, Ordering::Relaxed);
  2513. }
  2514. /// What a draw or dispatch runs, for the device-removed report
  2515. /// (diagnostics): the pipeline, then per stage the user data it gets
  2516. /// (with the view at that heap index, if one is), the host addresses
  2517. /// of its root views and the views its tables name.
  2518. #[cfg(feature = "diagnostics")]
  2519. fn op_text(&self, kind: String, compute: bool) -> String {
  2520. use std::fmt::Write;
  2521. let Some(p) = crate::pipeline::host_pipeline(self.pipeline as This) else {
  2522. return kind;
  2523. };
  2524. let mut text = format!("{kind} {}", p.name);
  2525. // What it draws into (a dispatch writes through its views below).
  2526. if !compute {
  2527. let described = |t: usize| {
  2528. crate::resource::host_made(t as This).map(|r| {
  2529. // SAFETY: a live resource.
  2530. let d = unsafe { r.GetDesc() };
  2531. format!("{t:#x} {}x{} f{}", d.Width, d.Height, d.Format.0)
  2532. })
  2533. };
  2534. let targets: Vec<String> = self.targets.iter().filter_map(|&t| described(t)).collect();
  2535. let _ = write!(text, " targets {targets:?} depth {:?} state [{}]", described(self.depth), p.state);
  2536. // The title's scissor and viewport at this draw (the first of
  2537. // each): the title draws what it sees through a
  2538. // portal (a window, from inside a room) under the portal's
  2539. // rectangle, and the listing did not say which draws those are.
  2540. if let Some(r) = self.scissors.first() {
  2541. let _ = write!(text, " scissor [{} {} {} {}]", r.left, r.top, r.right, r.bottom);
  2542. }
  2543. if let Some(v) = self.viewports.first() {
  2544. let _ = write!(
  2545. text,
  2546. " viewport [{} {} {} {} depth {}..{}]",
  2547. v.TopLeftX, v.TopLeftY, v.Width, v.Height, v.MinDepth, v.MaxDepth
  2548. );
  2549. }
  2550. }
  2551. let views = (self.heaps[0] != 0)
  2552. .then(|| crate::descriptor::heap(self.heaps[0] as This).host())
  2553. .flatten();
  2554. for stage in &p.stages {
  2555. let t = stage.translated();
  2556. let _ = write!(text, " | {}:", stage.shader.hash);
  2557. for u in &t.host.user_data {
  2558. let v = match u.root {
  2559. RootType::Other(kind) => self.host_word(compute, kind, u.slot, u.dword, None),
  2560. _ => self.user_value(compute, u.slot, u.root, u.dword),
  2561. };
  2562. let _ = write!(text, " u{}={v:#x}", u.index);
  2563. let index = if u.root == RootType::Table { v / 32 } else { v };
  2564. if let Some(slot) = views.and_then(|h| h.describe_slot(index)) {
  2565. let _ = write!(text, " [heap {index}: {slot}]");
  2566. }
  2567. }
  2568. for &(slot, _) in stage.root_cbvs.iter().chain(&stage.root_srvs).chain(&stage.root_uavs) {
  2569. if let Some(Root::View(address)) = self.roots_ref(compute).get(usize::from(slot)) {
  2570. let host = crate::shadow::find(*address, 1)
  2571. .map(|s| (s.gpu(*address), s.left(*address)));
  2572. let _ = write!(text, " root{slot}={address:#x} host {host:#x?}");
  2573. }
  2574. }
  2575. }
  2576. let _ = write!(text, " tables {:?}", self.reads(compute));
  2577. if !compute && !list_slots().is_empty() {
  2578. text.push_str(&self.slots_text());
  2579. }
  2580. text
  2581. }
  2582. /// For the frame listing, after a draw whose shader `VICTORY_LIST_SLOTS`
  2583. /// names: the heap slots it will pick textures from by index, and what
  2584. /// the title and the host hold there (one `~slot` line each), with the
  2585. /// words they were read from (`~raw` lines, to decode offline what is
  2586. /// not decoded here).
  2587. ///
  2588. /// Where the slots are, for the title's character shaders
  2589. /// (`PS_DeferredPedTexturedNC`, from their native code): in the small
  2590. /// buffers and constants of the draw's own table (every word of those
  2591. /// that names a texture view gets a line); in the material record, at
  2592. /// the byte offset the draw's constants (table 1, dword 56) hold at
  2593. /// 0x1c, of the buffer at table 0, dword 160; and in the record at the
  2594. /// byte offset the second root constant holds of the buffer at table 0,
  2595. /// dword 688. A word that is a small number by chance and names a
  2596. /// texture gets a line too.
  2597. #[cfg(feature = "diagnostics")]
  2598. fn slots_text(&self) -> String {
  2599. use std::fmt::Write;
  2600. const MATERIALS: u32 = 160;
  2601. const GLOBAL: u32 = 688;
  2602. const DRAW_CONSTANTS: u32 = 56;
  2603. let wanted = list_slots();
  2604. let Some(p) = crate::pipeline::host_pipeline(self.pipeline as This) else {
  2605. return String::new();
  2606. };
  2607. let Some(stage) = p.stages.iter().find(|s| wanted.iter().any(|w| s.shader.hash.starts_with(w.as_str())))
  2608. else {
  2609. return String::new();
  2610. };
  2611. let Some(heap) = self
  2612. .heaps
  2613. .iter()
  2614. .filter(|&&h| h != 0)
  2615. .map(|&h| crate::descriptor::heap(h as This))
  2616. .find(|h| !h.samplers())
  2617. else {
  2618. return String::new();
  2619. };
  2620. let t = stage.translated();
  2621. let mut text = String::new();
  2622. let entry = |slot: u8, dwords: u32| -> Option<View> {
  2623. let Some(Root::Table(table)) = self.roots_ref(false).get(usize::from(slot)) else {
  2624. return None;
  2625. };
  2626. crate::descriptor::view(table + u64::from(dwords) * 4)
  2627. };
  2628. let mut material = None;
  2629. for u in t.used.iter().filter(|u| u.root == RootType::Table && u.kind != ResourceType::Sampler) {
  2630. let label = format!("s{}+{}", u.slot, u.table_offset_dwords);
  2631. let Some(view) = entry(u.slot, u.table_offset_dwords) else {
  2632. let _ = write!(text, "\n ~table {label} no view");
  2633. continue;
  2634. };
  2635. let range = match &view {
  2636. View::Constant(address, size) => Some((*address, u64::from(*size))),
  2637. other => crate::descriptor::host::buffer_range(other),
  2638. };
  2639. match range {
  2640. // A small buffer or constants: its words.
  2641. Some((address, len)) if len <= 2048 => {
  2642. Self::slot_words(&mut text, heap, &label, address, len as usize);
  2643. if u.slot == 1 && u.table_offset_dwords == DRAW_CONSTANTS && len >= 0x20 {
  2644. let mut word = [0u8; 4];
  2645. if crate::host::read_into((address + 0x1c) as *const u8, &mut word) {
  2646. material = Some(u32::from_le_bytes(word));
  2647. }
  2648. }
  2649. }
  2650. Some(_) => {}
  2651. // A texture read through the table: the title slot it sits in.
  2652. None => {
  2653. let Some(Root::Table(table)) = self.roots_ref(false).get(usize::from(u.slot)) else {
  2654. continue;
  2655. };
  2656. match heap.index(table + u64::from(u.table_offset_dwords) * 4) {
  2657. Some(index) => text.push_str(&Self::slot_line(heap, &format!("table:{label}"), 0, index)),
  2658. None => {
  2659. let _ = write!(text, "\n ~table {label} title=[{}]", view_state(Some(&view)));
  2660. }
  2661. }
  2662. }
  2663. }
  2664. }
  2665. let uses = |slot: u8, dwords: u32| {
  2666. t.used.iter().any(|u| u.root == RootType::Table && u.slot == slot && u.table_offset_dwords == dwords)
  2667. };
  2668. if let Some(at) = material
  2669. && uses(0, MATERIALS)
  2670. && let Some((base, len)) = entry(0, MATERIALS).as_ref().and_then(crate::descriptor::host::buffer_range)
  2671. {
  2672. let at = u64::from(at);
  2673. let _ = write!(text, "\n ~material record at {at:#x} of the buffer at {base:#x} bytes {len}");
  2674. if at + 64 <= len {
  2675. Self::slot_words(&mut text, heap, "M", base + at, 64);
  2676. }
  2677. if at + 1936 + 512 <= len {
  2678. Self::slot_words(&mut text, heap, "M+1936", base + at + 1936, 512);
  2679. }
  2680. }
  2681. if uses(0, GLOBAL)
  2682. && let Some(slot) = t.used.iter().find(|u| u.root == RootType::Constants).map(|u| u.slot)
  2683. && let Some(Root::Constants(words)) = self.roots_ref(false).get(usize::from(slot))
  2684. && let Some(&at) = words.get(1)
  2685. && let Some((base, len)) = entry(0, GLOBAL).as_ref().and_then(crate::descriptor::host::buffer_range)
  2686. {
  2687. let at = u64::from(at);
  2688. let _ = write!(text, "\n ~root constants {words:08x?}: record at {at:#x} of the buffer at {base:#x} bytes {len}");
  2689. if at + 64 <= len {
  2690. Self::slot_words(&mut text, heap, "G", base + at, 64);
  2691. }
  2692. }
  2693. text
  2694. }
  2695. /// Up to 512 bytes of title memory at `address` as hex words (a `~raw`
  2696. /// line), and a `~slot` line for every word of them that names a
  2697. /// texture view in `heap`.
  2698. #[cfg(feature = "diagnostics")]
  2699. fn slot_words(text: &mut String, heap: &crate::descriptor::Heap, label: &str, address: u64, len: usize) {
  2700. use std::fmt::Write;
  2701. let mut bytes = vec![0u8; len.min(512) & !3];
  2702. if bytes.is_empty() || !crate::host::read_into(address as *const u8, &mut bytes) {
  2703. let _ = write!(text, "\n ~raw {label} at {address:#x} bytes {len}: unreadable");
  2704. return;
  2705. }
  2706. let words: Vec<u32> =
  2707. bytes.chunks_exact(4).map(|w| u32::from_le_bytes([w[0], w[1], w[2], w[3]])).collect();
  2708. let _ = write!(text, "\n ~raw {label} at {address:#x} bytes {len}:");
  2709. for w in &words {
  2710. let _ = write!(text, " {w:08x}");
  2711. }
  2712. for (i, &index) in words.iter().enumerate() {
  2713. let names = index != 0
  2714. && heap
  2715. .handle(index)
  2716. .and_then(crate::descriptor::view)
  2717. .as_ref()
  2718. .is_some_and(crate::descriptor::host::is_texture_view);
  2719. if names {
  2720. text.push_str(&Self::slot_line(heap, label, i * 4, index));
  2721. }
  2722. }
  2723. }
  2724. /// One `~slot` line: where the slot number was read (`from`, byte
  2725. /// `at`), what the title's heap holds in slot `index` with the state
  2726. /// of that texture ([`view_state`]), what the host slot was made from,
  2727. /// and what the queue of textures picked by index knows of it.
  2728. #[cfg(feature = "diagnostics")]
  2729. fn slot_line(heap: &crate::descriptor::Heap, from: &str, at: usize, index: u32) -> String {
  2730. let title = heap.handle(index).and_then(crate::descriptor::view);
  2731. let host: String = heap
  2732. .host()
  2733. .and_then(|h| h.describe_slot(index))
  2734. .unwrap_or_else(|| "none".into())
  2735. .chars()
  2736. .take(90)
  2737. .collect();
  2738. let queue = match heap.host() {
  2739. Some(h) => h.texture_slot_state(index, crate::frame::current()),
  2740. None => "no host heap".into(),
  2741. };
  2742. format!(
  2743. "\n ~slot from={from}+{at:#x} slot={index} title=[{}] host=[{host}] queue=[{queue}]",
  2744. view_state(title.as_ref())
  2745. )
  2746. }
  2747. /// A mesh draw under `VICTORY_MESH_TEST=scissor` rasterises one pixel:
  2748. /// the scissors before it (`on`), the title's after it.
  2749. fn mesh_scissor(&self, list: &HostList, on: bool) {
  2750. if mesh_test() != 2 {
  2751. return;
  2752. }
  2753. if on {
  2754. let one = RECT { left: 0, top: 0, right: 1, bottom: 1 };
  2755. crate::draw::scissors(list, &vec![one; self.scissors.len().max(1)]);
  2756. } else if !self.scissors.is_empty() {
  2757. crate::draw::scissors(list, &self.scissors);
  2758. }
  2759. }
  2760. /// Runs a mesh dispatch of `x` groups on the host (the title's mesh
  2761. /// programs are one-dimensional).
  2762. pub(crate) fn dispatch_mesh(&mut self, list: &HostList, x: u32) {
  2763. self.window = None;
  2764. #[cfg(feature = "diagnostics")]
  2765. self.trace("mesh", x, 0);
  2766. let ran = mesh_test() != 1
  2767. && mesh_kept(self.pipeline)
  2768. && self.prepare_for(list, false, true)
  2769. && match list.list.cast::<ID3D12GraphicsCommandList6>() {
  2770. Ok(l6) => {
  2771. #[cfg(feature = "diagnostics")]
  2772. list.note_op(|| self.op_text(format!("mesh {x}"), false));
  2773. self.mesh_scissor(list, true);
  2774. #[cfg(feature = "diagnostics")]
  2775. if let Some(p) = crate::pipeline::host_pipeline(self.pipeline as This) {
  2776. list.ran_indirect(p.pso.as_raw() as usize, &p.name, crate::host::indirects::DIRECT, x, &self.user);
  2777. }
  2778. // (The host takes 65,535 groups in a dimension: more is
  2779. // undefined there.)
  2780. if x > 65_535 {
  2781. once!(x, "a mesh dispatch of more groups than the host takes: cut");
  2782. }
  2783. // SAFETY: an open list with everything set.
  2784. unsafe { l6.DispatchMesh(x.min(65_535), 1, 1) };
  2785. self.drew(crate::pipeline::host_pipeline(self.pipeline as This));
  2786. self.mesh_scissor(list, false);
  2787. DRAWN.fetch_add(1, Ordering::Relaxed);
  2788. true
  2789. }
  2790. Err(_) => false,
  2791. };
  2792. if !ran {
  2793. DROPPED.fetch_add(1, Ordering::Relaxed);
  2794. #[cfg(feature = "diagnostics")]
  2795. dropped(self.pipeline);
  2796. }
  2797. }
  2798. /// The walls trace (`crate::host::walls_trace`): one log line per
  2799. /// frame with the draws of its main pass (four or more colour targets)
  2800. /// by scissor rectangle, and how often each of the title's culling
  2801. /// programs was dispatched. The title clips what it draws
  2802. /// through a window or door to that opening's rectangle while it holds
  2803. /// the camera to be in a room (run 182, frame 1529: 1,386 draws under
  2804. /// `531 0 1789 1337`); in a launch without the room's walls the same
  2805. /// shot has no such rectangle (run 187, frame 1414). The line shows
  2806. /// the frame in which that changes.
  2807. fn walls_census(&self, p: &HostPipeline, compute: bool) {
  2808. const CULL: [(&str, &str); 9] = [
  2809. ("55679a0547649d0b", "tree"),
  2810. ("89d08e561897d4e5", "tree_imposter"),
  2811. ("9209777e8face9dd", "grass"),
  2812. ("17af15c4015cb4b6", "prop"),
  2813. ("fdd56d97a806bcca", "prop_nocull"),
  2814. ("42f717f1b4d18e94", "simple"),
  2815. ("1c4b3c0547e3e6fa", "slod"),
  2816. ("9146291b38ea9ce1", "meshlet_args"),
  2817. ("42683eebec081520", "depth_pyramid_cpu_occlusion"),
  2818. ];
  2819. type Census = (u64, std::collections::BTreeMap<[i32; 4], u32>, [u32; 9]);
  2820. static CENSUS: std::sync::Mutex<Census> =
  2821. std::sync::Mutex::new((u64::MAX, std::collections::BTreeMap::new(), [0; 9]));
  2822. let frame = crate::frame::current();
  2823. let mut census = CENSUS.lock().unwrap_or_else(|e| e.into_inner());
  2824. if census.0 != frame {
  2825. let draws: u32 = census.1.values().sum();
  2826. if draws > 0 {
  2827. let mut rects: Vec<([i32; 4], u32)> = census.1.iter().map(|(r, n)| (*r, *n)).collect();
  2828. rects.sort_unstable_by(|a, b| b.1.cmp(&a.1));
  2829. let scissors: Vec<String> = rects
  2830. .iter()
  2831. .take(5)
  2832. .map(|(r, n)| format!("{} {} {} {} x{n}", r[0], r[1], r[2], r[3]))
  2833. .collect();
  2834. let counts = census.2;
  2835. let culling: Vec<String> = CULL
  2836. .iter()
  2837. .zip(counts)
  2838. .filter(|(_, n)| *n > 0)
  2839. .map(|(c, n)| format!("{}={n}", c.1))
  2840. .collect();
  2841. tracing::info!(
  2842. frame = census.0,
  2843. main_pass_draws = draws,
  2844. rectangles = rects.len(),
  2845. scissors = ?scissors,
  2846. culling = ?culling,
  2847. "walls trace: the frame's main pass by scissor rectangle, and its culling dispatches"
  2848. );
  2849. }
  2850. census.0 = frame;
  2851. census.1.clear();
  2852. census.2 = [0; 9];
  2853. }
  2854. if compute {
  2855. for (i, c) in CULL.iter().enumerate() {
  2856. if p.stages.iter().any(|s| s.shader.hash.as_str() == c.0) {
  2857. census.2[i] += 1;
  2858. }
  2859. }
  2860. } else if self.targets.iter().filter(|&&t| t != 0).count() >= 4 {
  2861. let r = self.scissors.first().map_or([0; 4], |r| [r.left, r.top, r.right, r.bottom]);
  2862. *census.1.entry(r).or_insert(0) += 1;
  2863. }
  2864. }
  2865. fn roots_ref(&self, compute: bool) -> &Vec<Root> {
  2866. if compute {
  2867. &self.compute
  2868. } else {
  2869. &self.graphics
  2870. }
  2871. }
  2872. fn table_entry(&self, list: &HostList, u: &UsedResource, compute: bool) {
  2873. let Some(Root::Table(table)) = self.roots_ref(compute).get(usize::from(u.slot)) else {
  2874. return;
  2875. };
  2876. let handle = table + u64::from(u.table_offset_dwords) * 4;
  2877. let Some(heap) = self.heap_of(handle) else {
  2878. return;
  2879. };
  2880. let (Some(host), Some(index)) = (heap.host(), heap.index(handle)) else {
  2881. return;
  2882. };
  2883. if let Some(view) = host.mirror(index, handle, true) {
  2884. readable(list, u.kind, &view);
  2885. // Up to date by this draw: not the texture pass's to make.
  2886. if crate::descriptor::host::is_texture_view(&view) {
  2887. host.texture_slot_tabled(index, true);
  2888. } else {
  2889. host.slot_tabled(index);
  2890. }
  2891. }
  2892. }
  2893. /// The descriptors a shader reads through tables. Tables holding a
  2894. /// constant buffer are made afresh for the draw in dynamic slots, with
  2895. /// the constant data copied to upload memory when the list is
  2896. /// submitted: the host wants constant buffers 256-byte aligned, the
  2897. /// console only 16. Returns those tables' new byte offsets by root
  2898. /// parameter; the other tables' slots are made from the title's.
  2899. ///
  2900. /// Within a list, the same table holding the same descriptors is made
  2901. /// once: its constant data is copied at submission either way, and the
  2902. /// big tables the world binds would otherwise take hundreds of slots per
  2903. /// draw, wrapping the dynamic slots onto lists not yet submitted.
  2904. pub(crate) fn tables(
  2905. &mut self,
  2906. list: &HostList,
  2907. used: &[UsedResource],
  2908. indexed: &[RootIndexedView],
  2909. compute: bool,
  2910. ) -> Few<(u8, u32), 16> {
  2911. let tables = |u: &&UsedResource| u.root == RootType::Table;
  2912. let mut fresh: Few<u8, 16> = Few::default();
  2913. for u in used.iter().filter(tables).filter(|u| u.kind == ResourceType::Cbv) {
  2914. if !fresh.contains(&u.slot) {
  2915. fresh.push(u.slot);
  2916. }
  2917. }
  2918. // Tables reaching past a host heap smaller than the title's (the
  2919. // host's limit, 1,000,000 views on NVIDIA) are made afresh too: the
  2920. // title's slots there have no host slot of their own.
  2921. for u in used.iter().filter(tables) {
  2922. if fresh.contains(&u.slot) {
  2923. continue;
  2924. }
  2925. let Some(&Root::Table(table)) = self.roots_ref(compute).get(usize::from(u.slot)) else {
  2926. continue;
  2927. };
  2928. let end = table + u64::from(u.table_offset_dwords) * 4;
  2929. let Some(heap) = self.heap_of(table) else {
  2930. continue;
  2931. };
  2932. let (Some(host), Some(index)) = (heap.host(), heap.index(end)) else {
  2933. continue;
  2934. };
  2935. if index >= host.count() {
  2936. fresh.push(u.slot);
  2937. }
  2938. }
  2939. fresh.sort_unstable();
  2940. for u in used.iter().filter(tables) {
  2941. if !fresh.contains(&u.slot) {
  2942. self.table_entry(list, u, compute);
  2943. }
  2944. }
  2945. let mut made = Few::default();
  2946. for &slot in fresh.iter() {
  2947. let Some(&Root::Table(table)) = self.roots_ref(compute).get(usize::from(slot)) else {
  2948. continue;
  2949. };
  2950. // (Their places among `used`.)
  2951. let mut places: Few<u16, 32> = Few::default();
  2952. for (i, _) in used.iter().enumerate().filter(|(_, u)| tables(u) && u.slot == slot) {
  2953. places.push(i as u16);
  2954. }
  2955. let entries = || places.iter().map(|&i| &used[usize::from(i)]);
  2956. let Some(heap) = self.heap_of(table) else {
  2957. continue;
  2958. };
  2959. if heap.samplers() || (table - heap.start) % 32 != 0 {
  2960. continue;
  2961. }
  2962. let Some(host) = heap.host() else {
  2963. continue;
  2964. };
  2965. let mut selected: Vec<u32> = indexed
  2966. .iter()
  2967. .filter(|index| index.table_slot == slot)
  2968. .map(|index| {
  2969. let constant = self.user_value(
  2970. compute,
  2971. index.constant_slot,
  2972. RootType::Constants,
  2973. index.constant_dword,
  2974. );
  2975. // The shader adds i32 byte offsets and shifts by 5.
  2976. index.byte_offset.wrapping_add(constant << index.shift) / 32
  2977. })
  2978. .collect();
  2979. selected.sort_unstable();
  2980. selected.dedup();
  2981. let n = entries()
  2982. .map(|u| u.table_offset_dwords / 8)
  2983. .chain(selected.last().copied())
  2984. .max()
  2985. .unwrap_or(0)
  2986. + 1;
  2987. let last = table.checked_add(u64::from(n - 1) * 32);
  2988. if n > crate::descriptor::host::DYNAMIC
  2989. || last.and_then(|handle| heap.index(handle)).is_none()
  2990. {
  2991. once!(slot, n, "fresh descriptor table exceeds the available span");
  2992. continue;
  2993. }
  2994. // The table and what its entries hold (record words).
  2995. let key = {
  2996. let mut h = RecordHash::default();
  2997. for k in 0..n {
  2998. let at = table + u64::from(k) * 32;
  2999. // SAFETY: a descriptor slot in title memory.
  3000. h.add(unsafe { (at as *const [u32; 3]).read_unaligned() });
  3001. }
  3002. (table, n, h.0)
  3003. };
  3004. // Who reads of it, and as what, as far as [`readable`] goes by it.
  3005. let reader = (used.as_ptr() as usize, used.len(), STORES.get(), TESTED_DEPTH.get().0);
  3006. if let Some(known) = self.fresh_tables.get_mut(&key) {
  3007. let first = known.first;
  3008. // This reader had it brought up to date, and nothing in the
  3009. // list changed since: nothing to do again.
  3010. let once = ready_once() && selected.is_empty() && entries().all(|u| u.kind != ResourceType::Uav);
  3011. if once
  3012. && known.epoch == list.epoch()
  3013. && let Some((_, depth)) = known.ready.iter().find(|(r, _)| *r == reader)
  3014. {
  3015. if *depth {
  3016. TESTED_DEPTH.set((reader.3, true));
  3017. }
  3018. made.push((slot, first * 32));
  3019. continue;
  3020. }
  3021. let depth_before = TESTED_DEPTH.get();
  3022. TESTED_DEPTH.set((depth_before.0, false));
  3023. for u in entries().filter(|u| u.kind != ResourceType::Cbv) {
  3024. let handle = table + u64::from(u.table_offset_dwords) * 4;
  3025. if let Some(view) = crate::descriptor::view(handle) {
  3026. readable(list, u.kind, &view);
  3027. }
  3028. }
  3029. for k in selected {
  3030. if entries().any(|u| u.table_offset_dwords / 8 == k) {
  3031. continue;
  3032. }
  3033. let handle = table + u64::from(k) * 32;
  3034. if let Some(view) = crate::descriptor::view(handle)
  3035. && let Some(kind) = view_kind(&view)
  3036. {
  3037. readable(list, kind, &view);
  3038. }
  3039. }
  3040. let depth = TESTED_DEPTH.get().1;
  3041. TESTED_DEPTH.set((depth_before.0, depth_before.1 || depth));
  3042. if once && let Some(known) = self.fresh_tables.get_mut(&key) {
  3043. // (The epoch as it is now: what this changed itself it
  3044. // need not do again.)
  3045. let epoch = list.epoch();
  3046. if known.epoch != epoch {
  3047. known.epoch = epoch;
  3048. known.ready.clear();
  3049. }
  3050. if known.ready.len() < 16 {
  3051. known.ready.push((reader, depth));
  3052. }
  3053. }
  3054. made.push((slot, first * 32));
  3055. continue;
  3056. }
  3057. let Some(first) = host.dynamic(n) else {
  3058. // No room: the draw must not run with the title's own
  3059. // offsets (slots never made for it); `bind` drops it.
  3060. made.push((slot, u32::MAX));
  3061. continue;
  3062. };
  3063. self.fresh_tables.insert(key, FreshTable { first, epoch: 0, ready: Vec::new() });
  3064. self.dynamic
  3065. .push((std::ptr::from_ref(heap) as usize, first, n));
  3066. // The title's own slots of this table: what the draw reads of
  3067. // them it brings up to date here, in the dynamic slots.
  3068. let title_first = heap.index(table).filter(|first| first + n <= host.count());
  3069. // They are such a table's, whatever they hold. (Of a big one,
  3070. // which may lie over slots shaders pick by index, only the ones
  3071. // the shader names.)
  3072. if let Some(title) = title_first {
  3073. for k in (0..n).filter(|&k| n <= 64 || entries().any(|u| u.table_offset_dwords / 8 == k)) {
  3074. host.slot_tabled(title + k);
  3075. }
  3076. }
  3077. let list_views = crate::descriptor::host::list_views();
  3078. if self.recording == 0 {
  3079. static NEXT: AtomicU64 = AtomicU64::new(1);
  3080. self.recording = NEXT.fetch_add(1, Ordering::Relaxed);
  3081. }
  3082. let recording = self.recording;
  3083. // The whole range: a shader may index past the entries its
  3084. // used-resource list names (descriptor arrays).
  3085. for k in 0..n {
  3086. let index = first + k;
  3087. // A view this list has made before: its descriptor copied,
  3088. // and nothing more if nothing changed in the list since.
  3089. if list_views
  3090. && let Some(words) = crate::descriptor::record_at(table + u64::from(k) * 32)
  3091. && let Some(mut listed) = host.make_listed(recording, words, index)
  3092. {
  3093. let kind = entries()
  3094. .find(|u| u.table_offset_dwords / 8 == k)
  3095. .map(|u| u.kind)
  3096. .or_else(|| selected.binary_search(&k).ok().and(listed.kind));
  3097. let was = (listed.ready, listed.tabled);
  3098. if let Some(kind) = kind {
  3099. let tested = TESTED_DEPTH.get();
  3100. if kind == ResourceType::Srv && listed.ready.0 == list.epoch() && listed.ready.1 == tested.0 {
  3101. if listed.ready.2 {
  3102. TESTED_DEPTH.set((tested.0, true));
  3103. }
  3104. } else if let Some(view) = crate::descriptor::host::listed_view(recording, words) {
  3105. TESTED_DEPTH.set((tested.0, false));
  3106. readable(list, kind, &view);
  3107. let depth = TESTED_DEPTH.get().1;
  3108. TESTED_DEPTH.set((tested.0, tested.1 || depth));
  3109. if kind == ResourceType::Srv {
  3110. listed.ready = (list.epoch(), tested.0, depth);
  3111. }
  3112. }
  3113. }
  3114. if let Some(title) = title_first
  3115. && listed.texture
  3116. && listed.tabled != Some((title + k, kind.is_some()))
  3117. {
  3118. listed.tabled = Some((title + k, kind.is_some()));
  3119. host.texture_slot_tabled(title + k, kind.is_some());
  3120. if kind.is_some() {
  3121. host.mirror_after(list, title + k, table + u64::from(k) * 32);
  3122. }
  3123. }
  3124. if was != (listed.ready, listed.tabled) {
  3125. crate::descriptor::host::note_listed(recording, words, listed);
  3126. }
  3127. continue;
  3128. }
  3129. let used = entries().find(|u| u.table_offset_dwords / 8 == k);
  3130. match crate::descriptor::view(table + u64::from(k) * 32) {
  3131. Some(View::Constant(address, size)) => {
  3132. let Some((buffer, gpu, to)) = list.scratch_held(u64::from(size)) else {
  3133. host.make_null(index);
  3134. continue;
  3135. };
  3136. let slot = (std::ptr::from_ref(heap) as usize, index);
  3137. list.defer_constants(to, address as *const u8, size as usize, slot);
  3138. host.constant_at(index, &buffer, gpu, size);
  3139. }
  3140. Some(view) => {
  3141. host.make_at(index, &view);
  3142. let kind = used.map(|u| u.kind).or_else(|| {
  3143. selected.binary_search(&k).ok().and_then(|_| view_kind(&view))
  3144. });
  3145. if let Some(kind) = kind {
  3146. readable(list, kind, &view);
  3147. }
  3148. // The title's slot is a table's: out of the queue
  3149. // of textures picked by index if the draw read it
  3150. // (its texture is up to date now), and made in
  3151. // place as the texture pass would have made it,
  3152. // for a shader that picks it by index all the same.
  3153. if let Some(title) = title_first
  3154. && crate::descriptor::host::is_texture_view(&view)
  3155. {
  3156. host.texture_slot_tabled(title + k, kind.is_some());
  3157. if kind.is_some() {
  3158. host.mirror_after(list, title + k, table + u64::from(k) * 32);
  3159. }
  3160. }
  3161. }
  3162. None => {
  3163. host.make_null(index);
  3164. if used.is_some() {
  3165. once!(slot, "a table entry without a view");
  3166. }
  3167. }
  3168. }
  3169. }
  3170. made.push((slot, first * 32));
  3171. }
  3172. made
  3173. }
  3174. /// The first draws, at debug level: what they bind and read
  3175. /// (diagnostics builds).
  3176. #[cfg(feature = "diagnostics")]
  3177. fn trace(&self, kind: &str, count: u32, first: u32) {
  3178. static TRACED: AtomicU64 = AtomicU64::new(0);
  3179. if !tracing::enabled!(tracing::Level::DEBUG) {
  3180. return;
  3181. }
  3182. let listed = crate::capture::listed(crate::queue::presented() + 1);
  3183. let logged = listed || TRACED.fetch_add(1, Ordering::Relaxed) < 64;
  3184. let targets: Vec<String> = self
  3185. .targets
  3186. .iter()
  3187. .filter_map(|&t| crate::resource::host_made(t as This))
  3188. .map(|t| {
  3189. // SAFETY: a live resource.
  3190. let d = unsafe { t.GetDesc() };
  3191. format!("{}x{} f{}", d.Width, d.Height, d.Format.0)
  3192. })
  3193. .collect();
  3194. let v = self.vertex[0];
  3195. let line = format!(
  3196. "{kind} {count} from {first} topology {} pipeline {:#x} targets {targets:?} vb {:#x}+{} stride {} reads {:?}",
  3197. self.topology,
  3198. self.pipeline,
  3199. v.address,
  3200. v.size,
  3201. v.stride,
  3202. self.reads(false)
  3203. );
  3204. if logged {
  3205. tracing::debug!("draw {line}");
  3206. }
  3207. let mut frame = FRAME.lock().unwrap_or_else(|e| e.into_inner());
  3208. if frame.len() < 256 {
  3209. frame.push(line);
  3210. }
  3211. }
  3212. /// What a draw's shaders read, one line per used resource (diagnostics
  3213. /// builds).
  3214. #[cfg(feature = "diagnostics")]
  3215. fn reads(&self, compute: bool) -> Vec<String> {
  3216. let Some(p) = crate::pipeline::host_pipeline(self.pipeline as This) else {
  3217. return vec!["no host pipeline".into()];
  3218. };
  3219. let mut out = Vec::new();
  3220. for stage in &p.stages {
  3221. let t = stage.translated();
  3222. for u in &t.used {
  3223. let what = match (u.root, self.roots_ref(compute).get(usize::from(u.slot))) {
  3224. (RootType::Table, Some(Root::Table(table))) => {
  3225. let handle = table + u64::from(u.table_offset_dwords) * 4;
  3226. describe(crate::descriptor::view(handle).as_ref())
  3227. }
  3228. (root, _) => format!("{root:?}"),
  3229. };
  3230. out.push(format!(
  3231. "{} {:?} s{}+{}: {what}",
  3232. stage.shader.hash, u.kind, u.slot, u.table_offset_dwords
  3233. ));
  3234. }
  3235. }
  3236. out
  3237. }
  3238. pub(crate) fn draw(
  3239. &mut self,
  3240. list: &HostList,
  3241. vertices: u32,
  3242. instances: u32,
  3243. first: u32,
  3244. first_instance: u32,
  3245. ) {
  3246. self.window = None;
  3247. #[cfg(feature = "diagnostics")]
  3248. self.trace("draw", vertices, first);
  3249. let ready = self.prepare(list, false);
  3250. // A pipeline with the rectangle geometry stage draws the title's
  3251. // vertices as they are; any other gets its rectangles expanded.
  3252. let rects = self.topology == RECTANGLES && !self.completes_rects();
  3253. let ran = ready && (!rects || self.rectangles(list, vertices, first));
  3254. if ran {
  3255. // Rectangles were expanded into their own vertex buffers.
  3256. let (count, from) = if rects {
  3257. (vertices / 3 * 6, 0)
  3258. } else {
  3259. (vertices, first)
  3260. };
  3261. #[cfg(feature = "diagnostics")]
  3262. list.note_op(|| self.op_text(format!("draw {count}x{instances}"), false));
  3263. // SAFETY: an open list with everything set.
  3264. unsafe {
  3265. list.list
  3266. .DrawInstanced(count, instances, from, first_instance)
  3267. };
  3268. self.drew(crate::pipeline::host_pipeline(self.pipeline as This));
  3269. DRAWN.fetch_add(1, Ordering::Relaxed);
  3270. }
  3271. if !ran {
  3272. DROPPED.fetch_add(1, Ordering::Relaxed);
  3273. #[cfg(feature = "diagnostics")]
  3274. dropped(self.pipeline);
  3275. }
  3276. }
  3277. /// Whether the bound pipeline completes rectangles itself, in the
  3278. /// geometry stage rectangle pipelines get (`HostPipeline::rects`).
  3279. fn completes_rects(&self) -> bool {
  3280. crate::pipeline::host_pipeline(self.pipeline as This).is_some_and(|p| p.rects)
  3281. }
  3282. /// Binds vertex buffers holding the rectangles of vertices `first..first
  3283. /// + count` as triangles, made when the list is submitted.
  3284. fn rectangles(&self, list: &HostList, count: u32, first: u32) -> bool {
  3285. let Some(p) = crate::pipeline::host_pipeline(self.pipeline as This) else {
  3286. return false;
  3287. };
  3288. let rects = u64::from(count / 3);
  3289. for slot in 0..32 {
  3290. let elements: Vec<(u32, u32)> = p
  3291. .inputs
  3292. .iter()
  3293. .filter(|e| e.slot == slot && !e.per_instance)
  3294. .map(|e| (e.offset, e.format))
  3295. .collect();
  3296. if elements.is_empty() {
  3297. continue;
  3298. }
  3299. let v = self.vertex[slot as usize];
  3300. let stride = u64::from(v.stride);
  3301. let from = v.address + u64::from(first) * stride;
  3302. if v.address == 0
  3303. || stride == 0
  3304. || u64::from(first + count) * stride > u64::from(v.size)
  3305. || crate::shadow::find(from, rects * 3 * stride).is_none()
  3306. {
  3307. once!(slot, "rectangle vertices outside their buffer");
  3308. return false;
  3309. }
  3310. let Some((gpu, to)) = list.scratch(rects * 6 * stride) else {
  3311. return false;
  3312. };
  3313. let (from, to, stride) = (from as usize, to as usize, stride as usize);
  3314. let n = rects as usize;
  3315. list.defer_host_read(from, n * 3 * stride, move || {
  3316. // The vertices are read through the kernel, at submission; in
  3317. // place only if that fails, with no change of mapping under
  3318. // the read (see `crate::watch::title_memory_reading`): while
  3319. // the world streams a change is under way most of the time,
  3320. // and this is the thread that submits.
  3321. let mut read = vec![0u8; n * 3 * stride];
  3322. let held = (!crate::host::read_into(from as *const u8, &mut read)).then(crate::watch::title_memory_reading);
  3323. // SAFETY: the vertices lie in a title buffer (checked when
  3324. // recorded) and the scratch memory is the list's.
  3325. let (src, dst) = unsafe {
  3326. (
  3327. if held.is_some() { std::slice::from_raw_parts(from as *const u8, n * 3 * stride) } else { &read[..] },
  3328. std::slice::from_raw_parts_mut(to as *mut u8, n * 6 * stride),
  3329. )
  3330. };
  3331. crate::primitive::expand_rects(src, dst, stride, &elements);
  3332. });
  3333. let view = D3D12_VERTEX_BUFFER_VIEW {
  3334. BufferLocation: gpu,
  3335. SizeInBytes: (rects * 6 * stride as u64) as u32,
  3336. StrideInBytes: v.stride,
  3337. };
  3338. // SAFETY: an open list; the view names live scratch memory.
  3339. unsafe { list.list.IASetVertexBuffers(slot, Some(&[view])) };
  3340. }
  3341. true
  3342. }
  3343. pub(crate) fn draw_indexed(
  3344. &mut self,
  3345. list: &HostList,
  3346. indices: u32,
  3347. instances: u32,
  3348. first: u32,
  3349. base: i32,
  3350. first_instance: u32,
  3351. ) {
  3352. self.window = None;
  3353. #[cfg(feature = "diagnostics")]
  3354. self.trace("indexed", indices, first);
  3355. // Indexed rectangles are drawn by the rectangle geometry stage
  3356. // alone (nothing expands them on the CPU).
  3357. let lost = self.topology == RECTANGLES && !self.completes_rects();
  3358. if lost {
  3359. once!("indexed rectangles not drawn");
  3360. }
  3361. let ran = !lost && self.prepare(list, true);
  3362. if ran {
  3363. #[cfg(feature = "diagnostics")]
  3364. list.note_op(|| self.op_text(format!("indexed {indices}x{instances}"), false));
  3365. // SAFETY: an open list with everything set.
  3366. unsafe {
  3367. list.list
  3368. .DrawIndexedInstanced(indices, instances, first, base, first_instance)
  3369. };
  3370. self.drew(crate::pipeline::host_pipeline(self.pipeline as This));
  3371. DRAWN.fetch_add(1, Ordering::Relaxed);
  3372. }
  3373. if !ran {
  3374. DROPPED.fetch_add(1, Ordering::Relaxed);
  3375. #[cfg(feature = "diagnostics")]
  3376. dropped(self.pipeline);
  3377. }
  3378. }
  3379. }
  3380. impl State {
  3381. /// Shaders that can write buffers were recorded: arguments may be others
  3382. /// from here on.
  3383. fn buffers_written(&mut self) {
  3384. match &mut self.batch {
  3385. Some(batch) if batches() == 2 => batch.wrote = true,
  3386. batch => *batch = None,
  3387. }
  3388. }
  3389. /// A draw with the pipeline `p` was recorded (as [`State::buffers_written`]
  3390. /// if its shaders can store to buffers).
  3391. fn drew(&mut self, p: Option<&HostPipeline>) {
  3392. if p.is_none_or(|p| p.stages.iter().any(|stage| stage.translated().stores)) {
  3393. self.batch = None;
  3394. }
  3395. }
  3396. /// A buffer was copied to: what was clamped of it ahead is clamped anew.
  3397. pub(crate) fn copied(&mut self) {
  3398. self.window = None;
  3399. self.batch = None;
  3400. }
  3401. /// The title waits for earlier work (a barrier or a pipeline sync).
  3402. pub(crate) fn synced(&mut self) {
  3403. if self.batch.as_ref().is_some_and(|b| b.wrote) {
  3404. self.batch = None;
  3405. }
  3406. }
  3407. /// Where the clamped record of `kind` at `arguments` of the copy `args`
  3408. /// is, from the open batch or a new one ([`batches`]). `None` if it
  3409. /// cannot be clamped in one.
  3410. fn batched(
  3411. &mut self,
  3412. list: &HostList,
  3413. args: &std::sync::Arc<crate::shadow::Shadow>,
  3414. arguments: u64,
  3415. kind: u32,
  3416. ) -> Option<(ID3D12Resource, u64)> {
  3417. const BATCH_USE: usize = usize::MAX - 0x78;
  3418. const DISPATCH: u32 = 2;
  3419. // Another host list, or this one after its reset ([`windows`]).
  3420. if list.first_use(BATCH_USE) {
  3421. self.batch = None;
  3422. }
  3423. // A draw after dispatches waits for them.
  3424. if kind != DISPATCH {
  3425. self.synced();
  3426. }
  3427. let (id, offset) = (args.id(), args.offset(arguments));
  3428. if let Some(b) = &mut self.batch
  3429. && let Some(at) = b.table.place(id, offset, kind)
  3430. {
  3431. return Some((b.scratch.clone(), at));
  3432. }
  3433. self.batch = None;
  3434. let (mut table, scratch) = crate::indirect::open_batch(list, (id, &args.buffer), &argument_copies(args))?;
  3435. self.host_pipeline = 0;
  3436. self.host_roots[1] = 0;
  3437. let at = table.place(id, offset, kind)?;
  3438. self.batch = Some(Batch { table, scratch: scratch.clone(), wrote: false });
  3439. Some((scratch, at))
  3440. }
  3441. /// Indirect execution of a one-argument signature of `kind` (PC
  3442. /// numbering: 0 draw, 1 indexed draw, 2 dispatch, 10 mesh dispatch) with
  3443. /// records `stride` bytes apart at title address `arguments`, and the
  3444. /// record count at `count` if the title gives one: the GPU reads them
  3445. /// from the buffer's host copy, where earlier dispatches may have
  3446. /// written them. False if it cannot run on the host.
  3447. pub(crate) fn execute_indirect(
  3448. &mut self,
  3449. list: &HostList,
  3450. (kind, stride, max): (u32, u32, u32),
  3451. arguments: u64,
  3452. count: Option<u64>,
  3453. ) -> bool {
  3454. // Skip before the argument clamp can mutate the indirect buffer.
  3455. #[cfg(feature = "diagnostics")]
  3456. if crate::pipeline::is_skipped(self.pipeline as This) {
  3457. crate::pipeline::note_drop(self.pipeline as This);
  3458. return false;
  3459. }
  3460. if crate::pipeline::is_builder(self.pipeline as This) && !crate::pipeline::builder_runs() {
  3461. return false;
  3462. }
  3463. const DRAW: u32 = 0;
  3464. const INDEXED: u32 = 1;
  3465. const DISPATCH: u32 = 2;
  3466. const MESH: u32 = 10;
  3467. #[cfg(feature = "diagnostics")]
  3468. let why = |what: &str| crate::pipeline::note_why(format!("indirect kind {kind}: {what}"));
  3469. #[cfg(not(feature = "diagnostics"))]
  3470. let why = |_: &str| {};
  3471. let Some(p) = crate::pipeline::host_pipeline(self.pipeline as This) else {
  3472. #[cfg(feature = "diagnostics")]
  3473. crate::pipeline::note_drop(self.pipeline as This);
  3474. return false;
  3475. };
  3476. // Indirect rectangles (the title's tiled lighting, 256
  3477. // indirect draws a frame, makes their corners from the vertex
  3478. // number) are completed by the pipeline's geometry stage: the
  3479. // arguments stay the title's, three vertices a rectangle. They
  3480. // cannot be expanded on the CPU, which does not know their count.
  3481. // shortcut: in a pipeline without that stage, a rectangle with no
  3482. // per-vertex inputs is drawn as its first triangle (three vertices,
  3483. // half of it), and one with vertex buffers is not drawn.
  3484. let made_rects = !p.rects
  3485. && kind == DRAW
  3486. && self.topology == RECTANGLES
  3487. && !p.inputs.iter().any(|e| !e.per_instance);
  3488. if made_rects {
  3489. once!("indirect rectangles without vertex inputs drawn as their first triangle");
  3490. }
  3491. let matches_kind = match kind {
  3492. DRAW | INDEXED => {
  3493. (self.topology != RECTANGLES || made_rects || p.rects) && !p.compute && !p.mesh
  3494. }
  3495. MESH => !p.compute && p.mesh,
  3496. DISPATCH => p.compute,
  3497. _ => false,
  3498. };
  3499. if !matches_kind {
  3500. why(&format!(
  3501. "pipeline mismatch (compute {}, mesh {}, topology {})",
  3502. p.compute, p.mesh, self.topology
  3503. ));
  3504. return false;
  3505. }
  3506. let len = u64::from(stride) * u64::from(max.max(1));
  3507. let Some(args) = crate::shadow::find_any(arguments, len) else {
  3508. why("arguments outside title buffers");
  3509. return false;
  3510. };
  3511. let counter = match count {
  3512. Some(at) => match crate::shadow::find_any(at, 4) {
  3513. Some(s) => Some((s, at)),
  3514. None => {
  3515. why("count outside title buffers");
  3516. return false;
  3517. }
  3518. },
  3519. None => None,
  3520. };
  3521. let Some(signature) = matches!(kind, DRAW | INDEXED | DISPATCH | MESH)
  3522. .then(|| host_signature(kind, stride))
  3523. .flatten()
  3524. else {
  3525. why("no host signature");
  3526. return false;
  3527. };
  3528. if kind == MESH && (mesh_test() == 1 || !mesh_kept(self.pipeline)) {
  3529. why("mesh draws are switched off (VICTORY_MESH_TEST=skip)");
  3530. return false;
  3531. }
  3532. // One record without a count: clamped in a batch (`batches`).
  3533. let batch = if batches() > 0 && max == 1 && count.is_none() {
  3534. args.refresh(list, arguments, len);
  3535. self.batched(list, &args, arguments, kind)
  3536. } else {
  3537. None
  3538. };
  3539. if batch.is_some() {
  3540. self.window = None;
  3541. }
  3542. // A window of records clamped in one pass (`windows`): for single
  3543. // records without a count buffer, drawn by shaders that store to no
  3544. // buffer. Anything else ends the window: it uses the scratch buffer
  3545. // or may write the arguments.
  3546. const WINDOW_USE: usize = usize::MAX - 0x77;
  3547. let offset = args.offset(arguments);
  3548. let windowed = windows()
  3549. && kind != DISPATCH
  3550. && max == 1
  3551. && count.is_none()
  3552. && !p.stages.iter().any(|stage| stage.translated().stores);
  3553. // Another host list (a new one after a cut, or this one after its
  3554. // reset) has another scratch buffer, or this one's with old bytes.
  3555. if !windowed || list.first_use(WINDOW_USE) {
  3556. self.window = None;
  3557. }
  3558. let same = |w: &Window| w.copy == args.id() && w.kind == kind && w.stride == stride;
  3559. let hit = self
  3560. .window
  3561. .as_ref()
  3562. .filter(|w| same(w) && offset >= w.base)
  3563. .filter(|w| (offset - w.base) % u64::from(w.step) == 0 && (offset - w.base) / u64::from(w.step) < u64::from(w.records))
  3564. .map(|w| (w.scratch.clone(), offset - w.base));
  3565. let (bounded, at) = match batch.or(hit) {
  3566. Some(hit) => hit,
  3567. None => {
  3568. // A record a short step after the last window's last one
  3569. // (the same step as that window's, if it had one): the
  3570. // title walks the buffer, so the ones that step apart
  3571. // after it are clamped with it.
  3572. let (step, records) = match &self.window {
  3573. Some(w) if windowed && same(w) => {
  3574. let last = w.base + u64::from(w.records - 1) * u64::from(w.step);
  3575. let step = offset.saturating_sub(last);
  3576. let walks = step >= u64::from(stride)
  3577. && step <= 256
  3578. && step % 4 == 0
  3579. && (w.records == 1 || step == u64::from(w.step));
  3580. if walks {
  3581. let fit = (args.left(arguments) / step).min(WINDOW_MOST) as u32;
  3582. (step as u32, (if w.records == 1 { 16 } else { w.records * 2 }).min(fit).max(1))
  3583. } else {
  3584. (stride, max)
  3585. }
  3586. }
  3587. _ => (stride, max),
  3588. };
  3589. args.refresh(list, arguments, len.max(u64::from(step) * u64::from(records)));
  3590. if let Some((s, at)) = &counter {
  3591. s.refresh(list, *at, 4);
  3592. }
  3593. // Bounded first: the clamp binds a compute pipeline of its
  3594. // own and copies clamped active records into a scratch
  3595. // buffer at offset 0.
  3596. let count_arg = counter.as_ref().map(|(s, at)| (&s.buffer, s.offset(*at)));
  3597. // More than the record asked for: a window clamped ahead,
  3598. // whose unfilled slots must not spend the list's budget.
  3599. let bounded = if windowed && records > 1 {
  3600. crate::indirect::bound_ahead(list, (&args.buffer, offset), (kind, step, records))
  3601. } else {
  3602. crate::indirect::bound(list, (&args.buffer, offset), count_arg, (kind, step, records))
  3603. };
  3604. let Some(bounded) = bounded else {
  3605. self.window = None;
  3606. why("not bounded (no clamp, or arguments not 4-byte aligned)");
  3607. return false;
  3608. };
  3609. self.host_pipeline = 0;
  3610. self.host_roots[1] = 0;
  3611. self.window = windowed.then(|| Window {
  3612. copy: args.id(),
  3613. kind,
  3614. stride,
  3615. step,
  3616. base: offset,
  3617. records,
  3618. scratch: bounded.clone(),
  3619. });
  3620. (bounded, 0)
  3621. }
  3622. };
  3623. let ran = match kind {
  3624. DRAW | INDEXED => self.prepare(list, kind == INDEXED),
  3625. MESH => self.prepare_for(list, false, true),
  3626. DISPATCH => self.bind(list, p, true),
  3627. _ => false,
  3628. };
  3629. if !ran {
  3630. why("prepare failed");
  3631. return false;
  3632. }
  3633. #[cfg(feature = "diagnostics")]
  3634. list.note_op(|| {
  3635. self.op_text(format!("indirect kind {kind} max {max} at {arguments:#x}"), kind == DISPATCH)
  3636. });
  3637. #[cfg(feature = "diagnostics")]
  3638. list.ran_indirect(p.pso.as_raw() as usize, &p.name, kind, max, &self.user);
  3639. if kind == MESH {
  3640. self.mesh_scissor(list, true);
  3641. }
  3642. // SAFETY: an open list with everything set; the scratch buffer and
  3643. // host copies are kept alive by the list, and the signature is cached.
  3644. unsafe {
  3645. list.list.ExecuteIndirect(
  3646. &signature,
  3647. max,
  3648. &bounded,
  3649. at,
  3650. counter.as_ref().map(|(s, _)| &s.buffer),
  3651. counter.as_ref().map_or(0, |(s, at)| s.offset(*at)),
  3652. )
  3653. };
  3654. if kind == MESH {
  3655. self.mesh_scissor(list, false);
  3656. }
  3657. if kind == DISPATCH {
  3658. self.buffers_written();
  3659. } else {
  3660. self.drew(Some(p));
  3661. }
  3662. // The scratch buffer stays readable as arguments: the next draw of
  3663. // the window reads it with no barrier, and the next clamp moves it
  3664. // back (`crate::indirect`).
  3665. if kind == DISPATCH {
  3666. DISPATCHED.fetch_add(1, Ordering::Relaxed);
  3667. } else {
  3668. DRAWN.fetch_add(1, Ordering::Relaxed);
  3669. }
  3670. true
  3671. }
  3672. }
  3673. /// `DispatchX`: the counts are threads (the console's dispatch initiator bit
  3674. /// "use thread dimensions"; DexNom/VIctory bc3cd4b0). Taken for groups, a
  3675. /// rehydration stage of the structure builder ran up to 64 times its threads
  3676. /// and stored over the structures after its own (runs light-1 to light-9).
  3677. const THREAD_DIMENSIONS: u32 = 0x20;
  3678. /// `VICTORY_THREAD_DIMENSIONS=0`: such counts are taken for groups, as before.
  3679. fn thread_dimensions() -> bool {
  3680. static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
  3681. *ON.get_or_init(|| std::env::var_os("VICTORY_THREAD_DIMENSIONS").is_none_or(|v| v != "0"))
  3682. }
  3683. /// The groups of `size` threads that hold `threads`.
  3684. fn dispatch_groups(threads: [u32; 3], size: [u32; 3]) -> [u32; 3] {
  3685. std::array::from_fn(|i| threads[i].div_ceil(size[i]))
  3686. }
  3687. /// Where a compute pipeline's user data has a word the host computes: the
  3688. /// root parameter and the dword in it.
  3689. fn compute_word(p: &HostPipeline, kind: u32) -> Option<(u32, u32)> {
  3690. let stage = p.stages.first().filter(|_| p.compute)?;
  3691. let (param, _) = stage.user_data?;
  3692. let word = stage.translated().host.user_data.iter().find(|u| u.root == RootType::Other(kind))?;
  3693. Some((param, word.index))
  3694. }
  3695. #[cfg(test)]
  3696. mod thread_tests {
  3697. use super::*;
  3698. #[test]
  3699. fn threads_are_counted_in_the_programs_groups() {
  3700. assert_eq!(dispatch_groups([8847, 1, 1], [64, 1, 1]), [139, 1, 1]);
  3701. assert_eq!(dispatch_groups([74, 1, 1], [64, 1, 1]), [2, 1, 1]);
  3702. assert_eq!(dispatch_groups([32, 1, 1], [32, 1, 1]), [1, 1, 1]);
  3703. assert_eq!(dispatch_groups([0, 12, 9], [64, 4, 4]), [0, 3, 3]);
  3704. }
  3705. }
  3706. /// The host command signature for one argument of `kind` with records
  3707. /// `stride` bytes apart (no root arguments, so no root signature), made
  3708. /// once.
  3709. fn host_signature(kind: u32, stride: u32) -> Option<ID3D12CommandSignature> {
  3710. static MADE: std::sync::Mutex<Vec<((u32, u32), ID3D12CommandSignature)>> =
  3711. std::sync::Mutex::new(Vec::new());
  3712. let mut made = MADE.lock().unwrap_or_else(|e| e.into_inner());
  3713. if let Some((_, s)) = made.iter().find(|(k, _)| *k == (kind, stride)) {
  3714. return Some(s.clone());
  3715. }
  3716. let argument = D3D12_INDIRECT_ARGUMENT_DESC {
  3717. Type: D3D12_INDIRECT_ARGUMENT_TYPE(kind as i32),
  3718. ..Default::default()
  3719. };
  3720. let desc = D3D12_COMMAND_SIGNATURE_DESC {
  3721. ByteStride: stride,
  3722. NumArgumentDescs: 1,
  3723. pArgumentDescs: &argument,
  3724. NodeMask: 0,
  3725. };
  3726. let mut signature: Option<ID3D12CommandSignature> = None;
  3727. // SAFETY: a description of one argument; no root arguments.
  3728. let result = unsafe {
  3729. crate::host::host()?.device.CreateCommandSignature(
  3730. &desc,
  3731. None::<&ID3D12RootSignature>,
  3732. &mut signature,
  3733. )
  3734. };
  3735. if let Err(e) = result {
  3736. once!(error = %e, kind, stride, "host command signature refused");
  3737. return None;
  3738. }
  3739. let signature = signature?;
  3740. made.push(((kind, stride), signature.clone()));
  3741. Some(signature)
  3742. }
  3743. /// Gets what a shader reads or writes through a view ready: buffer data
  3744. /// copied, textures moved to the state they need.
  3745. pub(crate) fn view_kind(view: &View) -> Option<ResourceType> {
  3746. match view {
  3747. View::Shader(..) | View::Placed(false, ..) => Some(ResourceType::Srv),
  3748. View::Unordered(..) | View::Placed(true, ..) => Some(ResourceType::Uav),
  3749. _ => None,
  3750. }
  3751. }
  3752. /// The host state a depth view needs of its texture: the read state if the
  3753. /// view writes no plane the format has (the title's read-only flags), else
  3754. /// the write state.
  3755. /// shortcut: whole textures have one state, so a view that writes one of
  3756. /// two planes counts as writing.
  3757. fn depth_state(texture: &ID3D12Resource, desc: Option<&D3D12_DEPTH_STENCIL_VIEW_DESC>) -> u32 {
  3758. // D16_UNORM and D32_FLOAT: depth formats without a stencil plane.
  3759. const ONE_PLANE: [i32; 2] = [55, 40];
  3760. let Some(desc) = desc else {
  3761. return DEPTH_WRITE;
  3762. };
  3763. let format = if desc.Format.0 == 0 {
  3764. // SAFETY: a live texture; a view without a format has its own.
  3765. unsafe { texture.GetDesc() }.Format.0
  3766. } else {
  3767. desc.Format.0
  3768. };
  3769. let mut needed = D3D12_DSV_FLAG_READ_ONLY_DEPTH.0;
  3770. if !ONE_PLANE.contains(&format) {
  3771. needed |= D3D12_DSV_FLAG_READ_ONLY_STENCIL.0;
  3772. }
  3773. if desc.Flags.0 & needed == needed {
  3774. DEPTH_READ
  3775. } else {
  3776. DEPTH_WRITE
  3777. }
  3778. }
  3779. /// A few things, up to `N` of them without memory of the heap: what a draw's
  3780. /// tables are gone through with, some six lists a stage.
  3781. struct Few<T, const N: usize> {
  3782. few: [T; N],
  3783. len: usize,
  3784. /// All of them, if they are more.
  3785. many: Vec<T>,
  3786. }
  3787. impl<T: Copy + Default, const N: usize> Default for Few<T, N> {
  3788. fn default() -> Self {
  3789. Few { few: [T::default(); N], len: 0, many: Vec::new() }
  3790. }
  3791. }
  3792. impl<T: Copy, const N: usize> Few<T, N> {
  3793. fn push(&mut self, what: T) {
  3794. if self.many.is_empty() && self.len < N {
  3795. self.few[self.len] = what;
  3796. self.len += 1;
  3797. } else {
  3798. if self.many.is_empty() {
  3799. self.many.extend_from_slice(&self.few);
  3800. }
  3801. self.many.push(what);
  3802. }
  3803. }
  3804. }
  3805. impl<T, const N: usize> std::ops::Deref for Few<T, N> {
  3806. type Target = [T];
  3807. fn deref(&self) -> &[T] {
  3808. if self.many.is_empty() { &self.few[..self.len] } else { &self.many }
  3809. }
  3810. }
  3811. impl<T, const N: usize> std::ops::DerefMut for Few<T, N> {
  3812. fn deref_mut(&mut self) -> &mut [T] {
  3813. if self.many.is_empty() { &mut self.few[..self.len] } else { &mut self.many }
  3814. }
  3815. }
  3816. /// A table made afresh in dynamic slots, in a list ([`State::tables`]).
  3817. struct FreshTable {
  3818. first: u32,
  3819. /// The list's epoch ([`HostList::epoch`]) at which all its entries that
  3820. /// these readers (a stage's list of what it reads, whether it stores, the
  3821. /// tested depth target) read were brought up to date, and whether that read the
  3822. /// tested depth target.
  3823. epoch: u64,
  3824. ready: Vec<((usize, usize, bool, usize), bool)>,
  3825. }
  3826. /// Whether a table a list reads again, with nothing changed in the list
  3827. /// since, is left as it is (`VICTORY_READY_ONCE=0`: every entry is gone
  3828. /// through again at every draw).
  3829. fn ready_once() -> bool {
  3830. crate::toggled!("VICTORY_READY_ONCE")
  3831. }
  3832. /// A hash of records' words: 64 bits, two multiplications a record. (The
  3833. /// standard library's took 3 % of the recording threads' time.)
  3834. #[derive(Default)]
  3835. struct RecordHash(u64);
  3836. impl RecordHash {
  3837. fn add(&mut self, [a, b, c]: [u32; 3]) {
  3838. let fold = |x: u64, y: u64| {
  3839. let p = u128::from(x) * u128::from(y);
  3840. p as u64 ^ (p >> 64) as u64
  3841. };
  3842. let words = u64::from(a) << 32 | u64::from(b);
  3843. let first = fold(self.0 ^ words ^ 0x2d35_8dcc_aa6c_78a5, 0x8bb8_4b93_962e_acc9 ^ u64::from(c));
  3844. self.0 = fold(first ^ 0x4b33_a62e_d433_d4a3, 0x4d5a_2da5_1de1_aa47 ^ self.0.rotate_left(23)) ^ first;
  3845. }
  3846. }
  3847. fn readable(list: &HostList, kind: ResourceType, view: &View) {
  3848. const UNORDERED_ACCESS: u32 = 0x8;
  3849. let placed = crate::descriptor::host::placed_texture(view);
  3850. let view = placed.as_ref().unwrap_or(view);
  3851. // Buffer views read title memory: their range is copied at submission;
  3852. // what shaders write through unordered access goes back to it after.
  3853. if let Some((shadow, address, len)) = crate::descriptor::host::buffer_copy(view) {
  3854. shadow.refresh(list, address, len);
  3855. if kind == ResourceType::Uav {
  3856. // A shader that cannot store to buffers leaves the range as
  3857. // the title has it: nothing to find afterwards.
  3858. if STORES.get() || !write_skip() {
  3859. #[cfg(feature = "diagnostics")]
  3860. crate::host::wide_write(address, len, 0);
  3861. shadow.gpu_writes(list, address, len);
  3862. } else {
  3863. #[cfg(feature = "diagnostics")]
  3864. {
  3865. crate::copystat::add(crate::copystat::C::GpuWritesLeftOut, 1);
  3866. crate::copystat::add(crate::copystat::C::GpuWritesLeftOutBytes, len);
  3867. }
  3868. }
  3869. }
  3870. }
  3871. match (view, kind) {
  3872. (View::Shader(resource, _), ResourceType::Srv) => {
  3873. // A view the title placed, in another format, in the memory of
  3874. // a texture the host writes: that texture's texels, copied on
  3875. // the host (title memory does not have them).
  3876. let aliased = crate::resource::alias_of(*resource as This)
  3877. .is_some_and(|source| crate::texture::alias(list, *resource as This, source));
  3878. if !aliased
  3879. && let Some(t) = crate::resource::host_copy(*resource as This)
  3880. && t.flags() & 0x7 == 0
  3881. {
  3882. // (A texture the title writes: no target, depth or unordered
  3883. // access, `crate::texture::title_written`.)
  3884. // Of a texture the title placed, the levels the view shows.
  3885. let first = match (&placed, view) {
  3886. (Some(_), View::Shader(_, Some(desc))) => crate::resource::first_mip(desc),
  3887. _ => 0,
  3888. };
  3889. crate::texture::upload_from(list, *resource as This, first);
  3890. }
  3891. // A depth texture shaders also write: what they wrote, first.
  3892. list.twin_use(*resource as This, false, false);
  3893. // The depth target the draw only tests is read in both ways at
  3894. // once: both read states, which its preparation asks for too.
  3895. let (tested, _) = TESTED_DEPTH.get();
  3896. let state = if tested != 0 && tested == *resource {
  3897. TESTED_DEPTH.set((tested, true));
  3898. DEPTH_READ | SHADER_RESOURCE
  3899. } else {
  3900. SHADER_RESOURCE
  3901. };
  3902. crate::list::ensure_state(list, *resource as This, state);
  3903. #[cfg(feature = "diagnostics")]
  3904. if tracing::enabled!(tracing::Level::DEBUG)
  3905. && let Some(t) = crate::resource::host_resource(*resource as This)
  3906. {
  3907. // SAFETY: a live resource.
  3908. let d = unsafe { t.GetDesc() };
  3909. if d.Flags.0 & 7 == 0 {
  3910. tracing::debug!(
  3911. resource = format_args!("{resource:#x}"),
  3912. ?d,
  3913. "a shader reads a texture the title fills"
  3914. );
  3915. }
  3916. }
  3917. }
  3918. (View::Unordered(resource, _, _), ResourceType::Uav) => {
  3919. #[cfg(feature = "diagnostics")]
  3920. crate::capture::note_target(*resource as This);
  3921. // Unordered access to a depth texture is its colour twin's.
  3922. if !list.twin_use(*resource as This, true, true) {
  3923. crate::list::ensure_state(list, *resource as This, UNORDERED_ACCESS);
  3924. }
  3925. }
  3926. _ => {}
  3927. }
  3928. }
  3929. /// The pixel shaders whose draws get their slots listed
  3930. /// ([`State::slots_text`]): `VICTORY_LIST_SLOTS`, hash prefixes separated
  3931. /// by commas. None by default.
  3932. #[cfg(feature = "diagnostics")]
  3933. fn list_slots() -> &'static [String] {
  3934. static LIST: std::sync::OnceLock<Vec<String>> = std::sync::OnceLock::new();
  3935. LIST.get_or_init(|| {
  3936. std::env::var("VICTORY_LIST_SLOTS")
  3937. .unwrap_or_default()
  3938. .split(',')
  3939. .map(|s| s.trim().to_ascii_lowercase())
  3940. .filter(|s| !s.is_empty())
  3941. .collect()
  3942. })
  3943. }
  3944. /// A fingerprint of the 4 KiB of title memory at `at` (FNV-1a, 64 bits; of
  3945. /// 4 KiB of zeros it is always the same value, which `slots.py` knows), or
  3946. /// "unreadable".
  3947. #[cfg(feature = "diagnostics")]
  3948. fn print_4k(at: u64) -> String {
  3949. let mut bytes = [0u8; 4096];
  3950. if at == 0 || !crate::host::read_into(at as *const u8, &mut bytes) {
  3951. return "unreadable".into();
  3952. }
  3953. let mut hash = 0xcbf2_9ce4_8422_2325_u64;
  3954. for b in bytes {
  3955. hash = (hash ^ u64::from(b)).wrapping_mul(0x0000_0100_0000_01b3);
  3956. }
  3957. format!("{hash:016x}")
  3958. }
  3959. /// The `bytes` of title memory at `at`: how many are mapped, and the
  3960. /// fingerprints of the first and the last 4 KiB (a texture's smallest
  3961. /// levels lie first, its largest last).
  3962. #[cfg(feature = "diagnostics")]
  3963. fn memory_state(at: u64, bytes: u64) -> String {
  3964. let mapped = crate::texture::mapped_bytes(at as *const u8, bytes as usize);
  3965. let last = at + bytes.saturating_sub(4096);
  3966. format!("memory={at:#x} mapped={mapped}/{bytes} first4k={} last4k={}", print_4k(at), print_4k(last))
  3967. }
  3968. /// Title texture `this` for the frame listing: its size, whether it has a
  3969. /// host copy (not made here), its staging buffer's state, whether the host
  3970. /// copied into it, and its memory ([`memory_state`]).
  3971. #[cfg(feature = "diagnostics")]
  3972. fn texture_state(this: This) -> String {
  3973. let Some((at, desc)) = crate::resource::texture_memory(this) else {
  3974. return "not a texture".into();
  3975. };
  3976. // SAFETY: 56 bytes in the description's layout.
  3977. let words = unsafe { std::ptr::from_ref(&desc).cast::<[u32; 14]>().read_unaligned() };
  3978. let bytes = crate::resource::placed_bytes(&words).unwrap_or(0);
  3979. let staged = match crate::texture::staged_state(this) {
  3980. Some((uploaded, dirty)) => format!("staged=yes uploaded={uploaded} dirty={dirty}"),
  3981. None => "staged=no".into(),
  3982. };
  3983. format!(
  3984. "{}x{} f{} levels={} host_copy={} {staged} host_written={} title_fills={} {}",
  3985. u64::from(words[4]) | u64::from(words[5]) << 32,
  3986. words[6],
  3987. words[8],
  3988. words[7] >> 16,
  3989. crate::resource::host_made(this).is_some(),
  3990. crate::texture::host_wrote(this as usize),
  3991. crate::resource::title_fills(this),
  3992. memory_state(at as u64, bytes)
  3993. )
  3994. }
  3995. /// A view of the title's heap for the frame listing: a texture with its
  3996. /// state ([`texture_state`]; a placed one that has no resource yet with
  3997. /// its memory alone), anything else in a few words.
  3998. #[cfg(feature = "diagnostics")]
  3999. fn view_state(view: Option<&View>) -> String {
  4000. match view {
  4001. None => "no view".into(),
  4002. Some(View::Placed(false, r, d)) if r[0] != 1 => {
  4003. let address = u64::from(d[10]) | u64::from(d[11]) << 32;
  4004. let state = match crate::resource::texture_at_made(address, r) {
  4005. Some(this) => texture_state(this),
  4006. None => format!(
  4007. "{}x{} f{} levels={} resource=none {}",
  4008. u64::from(r[4]) | u64::from(r[5]) << 32,
  4009. r[6],
  4010. r[8],
  4011. r[7] >> 16,
  4012. memory_state(address, crate::resource::placed_bytes(r).unwrap_or(0))
  4013. ),
  4014. };
  4015. // (Last, so that readers of the older lines still find
  4016. // theirs: the level the view starts at, and how many it shows.)
  4017. format!("placed texture view_format={} {state} view_levels={}+{}", d[0], d[4], d[5] as i32)
  4018. }
  4019. Some(View::Shader(r, d)) if crate::resource::texture_memory(*r as This).is_some() => {
  4020. format!(
  4021. "texture object {r:#x} view_format={} {} view_levels={}",
  4022. d.as_ref().map_or(0, |d| d[0]),
  4023. texture_state(*r as This),
  4024. d.as_ref().map_or("all".to_owned(), |d| format!("{}+{}", d[4], d[5] as i32))
  4025. )
  4026. }
  4027. Some(v) => format!("{v:?}").chars().take(80).collect(),
  4028. }
  4029. }
  4030. /// A view in a few words (diagnostics builds).
  4031. #[cfg(feature = "diagnostics")]
  4032. fn describe(view: Option<&View>) -> String {
  4033. let texture = |r: This| {
  4034. crate::resource::host_made(r).map(|t| {
  4035. // SAFETY: a live resource.
  4036. let d = unsafe { t.GetDesc() };
  4037. format!("{}x{} f{} flags {:#x} of {r:?}", d.Width, d.Height, d.Format.0, d.Flags.0)
  4038. })
  4039. };
  4040. match view {
  4041. None => "no view".into(),
  4042. Some(v @ View::Shader(r, _)) => texture(*r as This)
  4043. .unwrap_or_else(|| format!("buffer {:?}", crate::descriptor::host::buffer_range(v))),
  4044. Some(v @ View::Unordered(r, ..)) => match texture(*r as This) {
  4045. Some(t) => format!("uav texture {t}"),
  4046. None => format!(
  4047. "uav resource {r:#x} buffer {:?}",
  4048. crate::descriptor::host::buffer_range(v)
  4049. ),
  4050. },
  4051. Some(View::Placed(u, r, d)) => format!(
  4052. "placed uav={u} dim {} {}x{} f{} layout {:#x} at {:#x}",
  4053. r[0],
  4054. u64::from(r[4]) | u64::from(r[5]) << 32,
  4055. r[6],
  4056. r[8],
  4057. r[11],
  4058. u64::from(d[10]) | u64::from(d[11]) << 32
  4059. ),
  4060. // The first four values, as a colour rectangle's constants are.
  4061. Some(View::Constant(address, size))
  4062. if *size >= 16 && crate::texture::committed(*address as *const u8, 16) =>
  4063. {
  4064. // SAFETY: 16 committed bytes of title memory.
  4065. let v = unsafe { (*address as *const [f32; 4]).read_unaligned() };
  4066. format!("Constant({address:#x}, {size}) {v:?}")
  4067. }
  4068. Some(v) => format!("{v:?}").chars().take(60).collect(),
  4069. }
  4070. }
  4071. /// The console's own primitive topologies.
  4072. const TRIANGLE_FAN: u32 = 6;
  4073. const RECTANGLES: u32 = 17;
  4074. const LINE_LOOP: u32 = 18;
  4075. const QUADS: u32 = 19;
  4076. const QUAD_STRIP: u32 = 20;
  4077. /// Fixed-function state, straight onto the host list.
  4078. pub(crate) fn viewports(list: &HostList, viewports: &[D3D12_VIEWPORT]) {
  4079. // SAFETY: an open list.
  4080. unsafe { list.list.RSSetViewports(viewports) };
  4081. }
  4082. pub(crate) fn scissors(list: &HostList, rects: &[RECT]) {
  4083. // SAFETY: an open list.
  4084. unsafe { list.list.RSSetScissorRects(rects) };
  4085. }
  4086. pub(crate) fn blend_factor(list: &HostList, factor: Option<&[f32; 4]>) {
  4087. // SAFETY: an open list.
  4088. unsafe { list.list.OMSetBlendFactor(factor) };
  4089. }
  4090. pub(crate) fn stencil_ref(list: &HostList, reference: u32) {
  4091. #[cfg(feature = "diagnostics")]
  4092. crate::capture::op(std::ptr::from_ref(list) as usize, || format!("STENCIL REF {reference:#x}"));
  4093. // SAFETY: an open list.
  4094. unsafe { list.list.OMSetStencilRef(reference) };
  4095. }
  4096. pub(crate) fn depth_bounds(list: &HostList, min: f32, max: f32) {
  4097. #[cfg(feature = "diagnostics")]
  4098. crate::capture::op(std::ptr::from_ref(list) as usize, || {
  4099. format!("DEPTH BOUNDS {min}..{max}")
  4100. });
  4101. if crate::host::host().is_some_and(|h| h.depth_bounds())
  4102. && let Ok(l1) = list.list.cast::<ID3D12GraphicsCommandList1>()
  4103. {
  4104. // SAFETY: an open list on a device that supports depth bounds.
  4105. unsafe { l1.OMSetDepthBounds(min, max) };
  4106. }
  4107. }
  4108. /// Per-frame texture staging byte budget scaled from the adapter's local VRAM
  4109. /// budget (`None` keeps the 192 MiB 12 GiB baseline).
  4110. fn staging_budget_per_frame(vram_budget: Option<u64>) -> u64 {
  4111. const GIB: u64 = 1 << 30;
  4112. const MIB: u64 = 1 << 20;
  4113. match vram_budget {
  4114. Some(budget) if budget <= 6 * GIB => 96 * MIB,
  4115. Some(budget) if budget >= 20 * GIB => 384 * MIB,
  4116. Some(budget) if budget > 12 * GIB => 256 * MIB,
  4117. _ => 192 * MIB,
  4118. }
  4119. }
  4120. #[cfg(test)]
  4121. mod tests {
  4122. use super::staging_budget_per_frame;
  4123. #[test]
  4124. fn staging_budget_scales_with_vram_budget() {
  4125. const GIB: u64 = 1 << 30;
  4126. const MIB: u64 = 1 << 20;
  4127. assert_eq!(staging_budget_per_frame(None), 192 * MIB);
  4128. assert_eq!(staging_budget_per_frame(Some(4 * GIB)), 96 * MIB);
  4129. assert_eq!(staging_budget_per_frame(Some(6 * GIB)), 96 * MIB);
  4130. assert_eq!(staging_budget_per_frame(Some(8 * GIB)), 192 * MIB);
  4131. assert_eq!(staging_budget_per_frame(Some(12 * GIB)), 192 * MIB);
  4132. assert_eq!(staging_budget_per_frame(Some(13 * GIB)), 256 * MIB);
  4133. assert_eq!(staging_budget_per_frame(Some(14 * GIB)), 256 * MIB);
  4134. assert_eq!(staging_budget_per_frame(Some(16 * GIB)), 256 * MIB);
  4135. assert_eq!(staging_budget_per_frame(Some(20 * GIB)), 384 * MIB);
  4136. assert_eq!(staging_budget_per_frame(Some(24 * GIB)), 384 * MIB);
  4137. assert_eq!(staging_budget_per_frame(Some(32 * GIB)), 384 * MIB);
  4138. }
  4139. }
  4140. #[cfg(test)]
  4141. mod record_hash_tests {
  4142. use super::{Few, RecordHash};
  4143. #[test]
  4144. fn a_few_things_are_kept_in_order_however_many() {
  4145. for n in 0..10u32 {
  4146. let mut few: Few<u32, 4> = Few::default();
  4147. (0..n).for_each(|i| few.push(n - i));
  4148. assert_eq!(few.to_vec(), (0..n).map(|i| n - i).collect::<Vec<_>>());
  4149. few.sort_unstable();
  4150. assert_eq!(few.to_vec(), (1..=n).collect::<Vec<_>>());
  4151. }
  4152. }
  4153. #[test]
  4154. fn records_that_differ_hash_apart() {
  4155. let of = |records: &[[u32; 3]]| {
  4156. let mut h = RecordHash::default();
  4157. records.iter().for_each(|r| h.add(*r));
  4158. h.0
  4159. };
  4160. let mut seen = std::collections::HashSet::new();
  4161. // One record, one word or two of it different; runs of zeros; order.
  4162. for a in 0..64u32 {
  4163. for b in 0..64u32 {
  4164. for c in [0, 1, 0x8000_0000, u32::MAX] {
  4165. assert!(seen.insert(of(&[[a, b, c]])));
  4166. assert!(seen.insert(of(&[[1, 2, 3], [a, b, c]])));
  4167. assert!(seen.insert(of(&[[a, b, c], [1, 2, 3], [0, 0, 0]])));
  4168. }
  4169. }
  4170. }
  4171. assert!(seen.insert(of(&[])));
  4172. // (One record of zeros is among the above.)
  4173. let zeros: Vec<u64> = (2..100).map(|n| of(&vec![[0; 3]; n])).collect();
  4174. assert!(zeros.iter().all(|h| seen.insert(*h)));
  4175. }
  4176. }